System.Collections.Generic.IEnumerable.Min(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Min(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

534 Examples 7

19 Source : ViewDeclarationOrderAnalyzer.cs
with GNU General Public License v3.0
from Acumatica

private static void replacedyzeDacViewsForNumberOfCaches(PXGraphSemanticModel graphSemanticModel, SymbolreplacedysisContext symbolContext,
															 PXContext pxContext, IGrouping<ITypeSymbol, DataViewInfo> dacViews,
															 ILookup<ITypeSymbol, DataViewInfo> viewsGroupedByDAC)
		{
			var dacViewsDeclaredInGraph = dacViews.Where(view => GraphContainsViewDeclaration(graphSemanticModel, view));
			ITypeSymbol dac = dacViews.Key;
			int dacViewDeclarationOrder = dacViews.Min(view => view.DeclarationOrder);
			var baseDacs = dac.GetBaseTypes()
							  .Where(t => t.IsDAC() && viewsGroupedByDAC.Contains(t))
							  .ToList();

			if (baseDacs.Count != 1)
				return;

			ITypeSymbol baseDac = baseDacs[0];
			int baseDacViewOrder = viewsGroupedByDAC[baseDac].Min(baseDacView => baseDacView.DeclarationOrder);

			DiagnosticDescriptor descriptor = dacViewDeclarationOrder > baseDacViewOrder  
					? Descriptors.PX1004_ViewDeclarationOrder                                //the first declared DAC view goes after the first declared base DAC view and two caches will be created
					: Descriptors.PX1006_ViewDeclarationOrder;                               //the first declared DAC view goes before the first declared base DAC view and one cache will be created

			var baseDacViewsDeclaredInGraph = viewsGroupedByDAC[baseDac].Where(view => GraphContainsViewDeclaration(graphSemanticModel, view));
			var viewsToShowDiagnostic = dacViewsDeclaredInGraph.Concat(baseDacViewsDeclaredInGraph);

			ReportDiagnostic(descriptor, symbolContext, pxContext, viewsToShowDiagnostic, dac, baseDac);
		}

19 Source : ClientFactory.cs
with MIT License
from Adoxio

private static bool CheckIfAnyCookieIsExpired(CookieContainer container, Uri url, TimeSpan? expiryWindow)
		{
			var now = DateTime.UtcNow;
			var expires = container.GetCookies(url).Cast<Cookie>().Min(cookie => cookie.Expires);

			if (expiryWindow == null) return now >= expires;

			var expired = (now + expiryWindow.Value) > expires;

			return expired;
		}

19 Source : TagCloudData.cs
with MIT License
from Adoxio

protected virtual IEnumerable<TagCloudDataItem> replacedignWeights(int numberOfWeights, IEnumerable<TagCloudDataItem> items)
		{
            // The call to Max on the next line will fail if there are no items,
            // so return if the collection is empty
            if (items.Count() == 0) return items;

			// Find the highest count in our collection--items with this count will have
			// the max weight (i.e., the value of the "weights" param)
			var maxFrequency = items.Max(item => item.TaggedItemCount);

			// Find the lowest count in our collection--items with this count will have a
			// weight of 1
			var minFrequency = items.Min(item => item.TaggedItemCount);

			// The size of each frequency threshold
			var delta = (maxFrequency - minFrequency) / (double)numberOfWeights;

			return items.Select(item =>
			{
				for (var weight = 1; weight <= numberOfWeights; weight++)
				{
					// We add 2 to each threshold and adjustedFrequency, to cancel out the
					// possibility of log(0) or log(1), which would have distorting effects

					var threshold = 100 * Math.Log((minFrequency + weight * delta) + 2);

					var adjustedFrequency = 100 * Math.Log(item.TaggedItemCount + 2);

					if (adjustedFrequency <= threshold)
					{
						item.Weight = weight;

						break;
					}
				}

				return item;
			});
		}

19 Source : GroupVoiceCallSample.cs
with MIT License
from adrenak

void Update() {
            foreach (var output in agent.PeerOutputs) {
                if (peerViews.ContainsKey(output.Key)) {
                    /*
                     * This is an inefficient way of showing a part of the 
                     * audio source spectrum. AudioSource.GetSpectrumData returns
                     * frequency values up to 24000 Hz in some cases. Most human
                     * speech is no more than 5000 Hz. Showing the entire spectrum
                     * will therefore lead to a spectrum where much of it doesn't
                     * change. So we take only the spectrum frequencies between
                     * the average human vocal range.
                     * 
                     * Great source of information here: 
                     * http://answers.unity.com/answers/158800/view.html
                     */
                    var size = 512;
                    var minVocalFrequency = 50;
                    var maxVocalFrequency = 8000;
                    var sampleRate = AudioSettings.outputSampleRate;
                    var frequencyResolution = sampleRate / 2 / size;

                    var audioSource = (output.Value as InbuiltAudioOutput).AudioSource;
                    var spectrumData = new float[size];                    
                    audioSource.GetSpectrumData(spectrumData, 0, FFTWindow.BlackmanHarris);

                    var indices = Enumerable.Range(0, size - 1).ToList();
                    var minVocalFrequencyIndex = indices.Min(x => (Mathf.Abs(x * frequencyResolution - minVocalFrequency), x)).x;
                    var maxVocalFrequencyIndex = indices.Min(x => (Mathf.Abs(x * frequencyResolution - maxVocalFrequency), x)).x;
                    var indexRange = maxVocalFrequencyIndex - minVocalFrequency;

                    spectrumData = spectrumData.Select(x => 1000 * x)
                        .ToList()
                        .GetRange(minVocalFrequency, indexRange)
                        .ToArray();
                    peerViews[output.Key].DisplaySpectrum(spectrumData);
                }
            }
        }

19 Source : TxHub.cs
with MIT License
from AElfProject

public async Task UpdateTransactionPoolByBestChainAsync(Hash bestChainHash, long bestChainHeight)
        {
            var minimumHeight = _allTransactions.Count == 0
                ? 0
                : _allTransactions.Min(kv => kv.Value.Transaction.RefBlockNumber);
            var prefixes = await GetPrefixesByHeightAsync(minimumHeight, bestChainHash, bestChainHeight);
            ResetCurrentCollections();
            foreach (var queuedTransaction in _allTransactions.Values)
            {
                prefixes.TryGetValue(queuedTransaction.Transaction.RefBlockNumber, out var prefix);
                queuedTransaction.RefBlockStatus =
                    CheckRefBlockStatus(queuedTransaction.Transaction, prefix, bestChainHeight);
                AddToCollection(queuedTransaction);
            }

            CleanTransactions(_expiredByExpiryBlock, bestChainHeight);

            _bestChainHash = bestChainHash;
            _bestChainHeight = bestChainHeight;
        }

19 Source : BiomeSurfaceGraph.cs
with MIT License
from alelievr

public bool BuildGraph(List< BiomeSurfaceSwitch > surfacesSwitches)
		{
			var bSwitchCellMap = new Dictionary< BiomeSurfaceSwitch, BiomeSurfaceCell >();

			isBuilt = false;

			if (surfacesSwitches.Count == 0)
				return false;

			surfaceType = surfacesSwitches.First().surface.type;

			Action< BiomeSurfaceCell, BiomeSurfaceSwitch > AddLink = (cell, s) => {
				var link = new BiomeSurfaceLink();

				link.toCell = bSwitchCellMap[s];

				if (!cell.links.Any(c => c.toCell == link.toCell))
					cell.links.Add(link);
			};

			//calcul ranges
			float heightRange = surfacesSwitches.Max(s => s.maxHeight) - surfacesSwitches.Min(s => s.minHeight);
			float slopeRange = surfacesSwitches.Max(s => s.maxSlope) - surfacesSwitches.Min(s => s.minSlope);
			float paramRange = surfacesSwitches.Max(s => s.maxParam) - surfacesSwitches.Min(s => s.minParam);

			//Generate surface switches nodes:
			foreach (var bSwitch in surfacesSwitches)
				bSwitchCellMap[bSwitch] = new BiomeSurfaceCell();
			
			cells.Clear();
			lastCell = null;

			foreach (var bSwitch in surfacesSwitches)
			{
				BiomeSurfaceCell cell = bSwitchCellMap[bSwitch];
				cell.surface = bSwitch.surface;
				cell.surfaceSwitch = bSwitch;
				cell.weight = bSwitch.GetWeight(heightRange, slopeRange, paramRange);

				foreach (var biomeSwitch in surfacesSwitches)
					if (biomeSwitch.Overlaps(bSwitch))
						AddLink(cell, biomeSwitch);
					
				cell.links.Sort((l1, l2) => {
					float w1 = l1.toCell.weight;
					float w2 = l2.toCell.weight;

					//reverse sort
					return w2.CompareTo(w1);
				});
				
				cells.Add(cell);
			}

			rootCell = cells.First();

			if (!CheckValid())
				return false;

			isBuilt = true;

			return true;
		}

19 Source : MultiLikeControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task DoMultiLike()
        {
            var range = this.GroupContentsControlViewModel.CurrentlySelectedMessages;
            if (range == null)
            {
                return;
            }

            var itemList = (range as ObservableCollection<object>).Cast<MessageControlViewModelBase>().ToList();

            var oldestId = itemList.Min(m => long.Parse(m.Id));
            var newestId = itemList.Max(m => long.Parse(m.Id));

            var loadingControl = new LoadingControlViewModel();
            this.GroupContentsControlViewModel.SmallDialogManager.OpenPopup(loadingControl, Guid.Empty);

            foreach (var message in this.GroupContentsControlViewModel.MessagesSorted)
            {
                var id = long.Parse(message.Id);
                if (id >= oldestId && id <= newestId && message is MessageControlViewModel mcvm)
                {
                    loadingControl.Message = $"Liking Message {mcvm.Message.Text}";
                    await mcvm.LikeMessageAsync();
                    await Task.Delay(this.LikeDelay);
                }
            }

            this.DisableMultiLike();

            this.GroupContentsControlViewModel.SmallDialogManager.ClosePopup();
        }

19 Source : MultiLikeControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task DoMultiLike()
        {
            var range = this.GroupContentsControlViewModel.CurrentlySelectedMessages;
            if (range == null)
            {
                return;
            }

            var itemList = (range as ObservableCollection<object>).Cast<MessageControlViewModelBase>().ToList();

            var oldestId = itemList.Min(m => long.Parse(m.Id));
            var newestId = itemList.Max(m => long.Parse(m.Id));

            var loadingControl = new LoadingControlViewModel();
            this.GroupContentsControlViewModel.PopupManager.PopupDialog = loadingControl;

            foreach (var message in this.GroupContentsControlViewModel.SortedMessages)
            {
                var id = long.Parse(message.Id);
                if (id >= oldestId && id <= newestId && message is MessageControlViewModel mcvm)
                {
                    loadingControl.Message = $"Liking Message {mcvm.Message.Text}";
                    await mcvm.LikeMessageAsync();
                    await Task.Delay(this.LikeDelay);
                }
            }

            this.DisableMultiLike();

            this.GroupContentsControlViewModel.PopupManager.PopupDialog = null;
        }

19 Source : PlotModel.cs
with MIT License
from AlexGyver

private void EnforceCartesianTransforms()
        {
            // Set the same scaling on all axes
            double sharedScale = this.Axes.Min(a => Math.Abs(a.Scale));
            foreach (var a in this.Axes)
            {
                a.Zoom(sharedScale);
            }

            sharedScale = this.Axes.Max(a => Math.Abs(a.Scale));
            foreach (var a in this.Axes)
            {
                a.Zoom(sharedScale);
            }

            foreach (var a in this.Axes)
            {
                a.UpdateTransform(this.PlotArea);
            }
        }

19 Source : DnsStubResolver.cs
with Apache License 2.0
from alexreinert

public List<T> Resolve<T>(DomainName name, RecordType recordType = RecordType.A, RecordClreplaced recordClreplaced = RecordClreplaced.INet)
			where T : DnsRecordBase
		{
			if (name == null)
				throw new ArgumentNullException(nameof(name), "Name must be provided");

			List<T> records;
			if (_cache.TryGetRecords(name, recordType, recordClreplaced, out records))
			{
				return records;
			}

			DnsMessage msg = _dnsClient.Resolve(name, recordType, recordClreplaced);

			if ((msg == null) || ((msg.ReturnCode != ReturnCode.NoError) && (msg.ReturnCode != ReturnCode.NxDomain)))
			{
				throw new Exception("DNS request failed");
			}

			CNameRecord cName = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).OfType<CNameRecord>().FirstOrDefault();

			if (cName != null)
			{
				records = msg.AnswerRecords.Where(x => x.Name.Equals(cName.CanonicalName)).OfType<T>().ToList();
				if (records.Count > 0)
				{
					_cache.Add(name, recordType, recordClreplaced, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));
					return records;
				}

				records = Resolve<T>(cName.CanonicalName, recordType, recordClreplaced);

				if (records.Count > 0)
					_cache.Add(name, recordType, recordClreplaced, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));

				return records;
			}

			records = msg.AnswerRecords.Where(x => x.Name.Equals(name)).OfType<T>().ToList();

			if (records.Count > 0)
				_cache.Add(name, recordType, recordClreplaced, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));

			return records;
		}

19 Source : DnsStubResolver.cs
with Apache License 2.0
from alexreinert

public async Task<List<T>> ResolveAsync<T>(DomainName name, RecordType recordType = RecordType.A, RecordClreplaced recordClreplaced = RecordClreplaced.INet, CancellationToken token = default(CancellationToken))
			where T : DnsRecordBase
		{
			if (name == null)
				throw new ArgumentNullException(nameof(name), "Name must be provided");

			List<T> records;
			if (_cache.TryGetRecords(name, recordType, recordClreplaced, out records))
			{
				return records;
			}

			DnsMessage msg = await _dnsClient.ResolveAsync(name, recordType, recordClreplaced, null, token);

			if ((msg == null) || ((msg.ReturnCode != ReturnCode.NoError) && (msg.ReturnCode != ReturnCode.NxDomain)))
			{
				throw new Exception("DNS request failed");
			}

			CNameRecord cName = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).OfType<CNameRecord>().FirstOrDefault();

			if (cName != null)
			{
				records = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(cName.CanonicalName)).OfType<T>().ToList();
				if (records.Count > 0)
				{
					_cache.Add(name, recordType, recordClreplaced, records, DnsSecValidationResult.Indeterminate, Math.Min(cName.TimeToLive, records.Min(x => x.TimeToLive)));
					return records;
				}

				records = await ResolveAsync<T>(cName.CanonicalName, recordType, recordClreplaced, token);

				if (records.Count > 0)
					_cache.Add(name, recordType, recordClreplaced, records, DnsSecValidationResult.Indeterminate, Math.Min(cName.TimeToLive, records.Min(x => x.TimeToLive)));

				return records;
			}

			records = msg.AnswerRecords.Where(x => x.Name.Equals(name)).OfType<T>().ToList();

			if (records.Count > 0)
				_cache.Add(name, recordType, recordClreplaced, records, DnsSecValidationResult.Indeterminate, records.Min(x => x.TimeToLive));

			return records;
		}

19 Source : DnsSecRecursiveDnsResolver.cs
with Apache License 2.0
from alexreinert

private async Task<DnsSecResult<T>> ResolveAsyncInternal<T>(DomainName name, RecordType recordType, RecordClreplaced recordClreplaced, State state, CancellationToken token)
			where T : DnsRecordBase
		{
			DnsCacheRecordList<T> cachedResults;
			if (_cache.TryGetRecords(name, recordType, recordClreplaced, out cachedResults))
			{
				return new DnsSecResult<T>(cachedResults, cachedResults.ValidationResult);
			}

			DnsCacheRecordList<CNameRecord> cachedCNames;
			if (_cache.TryGetRecords(name, RecordType.CName, recordClreplaced, out cachedCNames))
			{
				var cNameResult = await ResolveAsyncInternal<T>(cachedCNames.First().CanonicalName, recordType, recordClreplaced, state, token);
				return new DnsSecResult<T>(cNameResult.Records, cachedCNames.ValidationResult == cNameResult.ValidationResult ? cachedCNames.ValidationResult : DnsSecValidationResult.Unsigned);
			}

			DnsMessage msg = await ResolveMessageAsync(name, recordType, recordClreplaced, state, token);

			// check for cname
			List<DnsRecordBase> cNameRecords = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).ToList();
			if (cNameRecords.Count > 0)
			{
				DnsSecValidationResult cNameValidationResult = await _validator.ValidateAsync(name, RecordType.CName, recordClreplaced, msg, cNameRecords, state, token);
				if ((cNameValidationResult == DnsSecValidationResult.Bogus) || (cNameValidationResult == DnsSecValidationResult.Indeterminate))
					throw new DnsSecValidationException("CNAME record could not be validated");

				_cache.Add(name, RecordType.CName, recordClreplaced, cNameRecords, cNameValidationResult, cNameRecords.Min(x => x.TimeToLive));

				DomainName canonicalName = ((CNameRecord) cNameRecords.First()).CanonicalName;

				List<DnsRecordBase> matchingAdditionalRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(canonicalName)).ToList();
				if (matchingAdditionalRecords.Count > 0)
				{
					DnsSecValidationResult matchingValidationResult = await _validator.ValidateAsync(canonicalName, recordType, recordClreplaced, msg, matchingAdditionalRecords, state, token);
					if ((matchingValidationResult == DnsSecValidationResult.Bogus) || (matchingValidationResult == DnsSecValidationResult.Indeterminate))
						throw new DnsSecValidationException("CNAME matching records could not be validated");

					DnsSecValidationResult validationResult = cNameValidationResult == matchingValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned;
					_cache.Add(canonicalName, recordType, recordClreplaced, matchingAdditionalRecords, validationResult, matchingAdditionalRecords.Min(x => x.TimeToLive));

					return new DnsSecResult<T>(matchingAdditionalRecords.OfType<T>().ToList(), validationResult);
				}

				var cNameResults = await ResolveAsyncInternal<T>(canonicalName, recordType, recordClreplaced, state, token);
				return new DnsSecResult<T>(cNameResults.Records, cNameValidationResult == cNameResults.ValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned);
			}

			// check for "normal" answer
			List<DnsRecordBase> answerRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).ToList();
			if (answerRecords.Count > 0)
			{
				DnsSecValidationResult validationResult = await _validator.ValidateAsync(name, recordType, recordClreplaced, msg, answerRecords, state, token);
				if ((validationResult == DnsSecValidationResult.Bogus) || (validationResult == DnsSecValidationResult.Indeterminate))
					throw new DnsSecValidationException("Response records could not be validated");

				_cache.Add(name, recordType, recordClreplaced, answerRecords, validationResult, answerRecords.Min(x => x.TimeToLive));
				return new DnsSecResult<T>(answerRecords.OfType<T>().ToList(), validationResult);
			}

			// check for negative answer
			SoaRecord soaRecord = msg.AuthorityRecords
				.Where(x =>
					(x.RecordType == RecordType.Soa)
					&& (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
				.OfType<SoaRecord>()
				.FirstOrDefault();

			if (soaRecord != null)
			{
				DnsSecValidationResult validationResult = await _validator.ValidateAsync(name, recordType, recordClreplaced, msg, answerRecords, state, token);
				if ((validationResult == DnsSecValidationResult.Bogus) || (validationResult == DnsSecValidationResult.Indeterminate))
					throw new DnsSecValidationException("Negative answer could not be validated");

				_cache.Add(name, recordType, recordClreplaced, new List<DnsRecordBase>(), validationResult, soaRecord.NegativeCachingTTL);
				return new DnsSecResult<T>(new List<T>(), validationResult);
			}

			// authoritive response does not contain answer
			throw new Exception("Could not resolve " + name);
		}

19 Source : RecursiveDnsResolver.cs
with Apache License 2.0
from alexreinert

private async Task<List<T>> ResolveAsyncInternal<T>(DomainName name, RecordType recordType, RecordClreplaced recordClreplaced, State state, CancellationToken token)
			where T : DnsRecordBase
		{
			List<T> cachedResults;
			if (_cache.TryGetRecords(name, recordType, recordClreplaced, out cachedResults))
			{
				return cachedResults;
			}

			List<CNameRecord> cachedCNames;
			if (_cache.TryGetRecords(name, RecordType.CName, recordClreplaced, out cachedCNames))
			{
				return await ResolveAsyncInternal<T>(cachedCNames.First().CanonicalName, recordType, recordClreplaced, state, token);
			}

			DnsMessage msg = await ResolveMessageAsync(name, recordType, recordClreplaced, state, token);

			// check for cname
			List<DnsRecordBase> cNameRecords = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).ToList();
			if (cNameRecords.Count > 0)
			{
				_cache.Add(name, RecordType.CName, recordClreplaced, cNameRecords, DnsSecValidationResult.Indeterminate, cNameRecords.Min(x => x.TimeToLive));

				DomainName canonicalName = ((CNameRecord) cNameRecords.First()).CanonicalName;

				List<DnsRecordBase> matchingAdditionalRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(canonicalName)).ToList();
				if (matchingAdditionalRecords.Count > 0)
				{
					_cache.Add(canonicalName, recordType, recordClreplaced, matchingAdditionalRecords, DnsSecValidationResult.Indeterminate, matchingAdditionalRecords.Min(x => x.TimeToLive));
					return matchingAdditionalRecords.OfType<T>().ToList();
				}

				return await ResolveAsyncInternal<T>(canonicalName, recordType, recordClreplaced, state, token);
			}

			// check for "normal" answer
			List<DnsRecordBase> answerRecords = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).ToList();
			if (answerRecords.Count > 0)
			{
				_cache.Add(name, recordType, recordClreplaced, answerRecords, DnsSecValidationResult.Indeterminate, answerRecords.Min(x => x.TimeToLive));
				return answerRecords.OfType<T>().ToList();
			}

			// check for negative answer
			SoaRecord soaRecord = msg.AuthorityRecords
				.Where(x =>
					(x.RecordType == RecordType.Soa)
					&& (name.Equals(x.Name) || name.IsSubDomainOf(x.Name)))
				.OfType<SoaRecord>()
				.FirstOrDefault();

			if (soaRecord != null)
			{
				_cache.Add(name, recordType, recordClreplaced, new List<DnsRecordBase>(), DnsSecValidationResult.Indeterminate, soaRecord.NegativeCachingTTL);
				return new List<T>();
			}

			// authoritive response does not contain answer
			throw new Exception("Could not resolve " + name);
		}

19 Source : SelfValidatingDnsSecStubResolver.cs
with Apache License 2.0
from alexreinert

public async Task<DnsSecResult<T>> ResolveSecureAsync<T>(DomainName name, RecordType recordType = RecordType.A, RecordClreplaced recordClreplaced = RecordClreplaced.INet, CancellationToken token = default(CancellationToken))
			where T : DnsRecordBase
		{
			if (name == null)
				throw new ArgumentNullException(nameof(name), "Name must be provided");

			DnsCacheRecordList<T> cacheResult;
			if (_cache.TryGetRecords(name, recordType, recordClreplaced, out cacheResult))
			{
				return new DnsSecResult<T>(cacheResult, cacheResult.ValidationResult);
			}

			DnsMessage msg = await _dnsClient.ResolveAsync(name, recordType, recordClreplaced, new DnsQueryOptions()
			{
				IsEDnsEnabled = true,
				IsDnsSecOk = true,
				IsCheckingDisabled = true,
				IsRecursionDesired = true
			}, token);

			if ((msg == null) || ((msg.ReturnCode != ReturnCode.NoError) && (msg.ReturnCode != ReturnCode.NxDomain)))
			{
				throw new Exception("DNS request failed");
			}

			DnsSecValidationResult validationResult;

			CNameRecord cName = msg.AnswerRecords.Where(x => (x.RecordType == RecordType.CName) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).OfType<CNameRecord>().FirstOrDefault();

			if (cName != null)
			{
				DnsSecValidationResult cNameValidationResult = await _validator.ValidateAsync(name, RecordType.CName, recordClreplaced, msg, new List<CNameRecord>() { cName }, null, token);
				if ((cNameValidationResult == DnsSecValidationResult.Bogus) || (cNameValidationResult == DnsSecValidationResult.Indeterminate))
					throw new DnsSecValidationException("CNAME record could not be validated");

				var records = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(cName.CanonicalName)).OfType<T>().ToList();
				if (records.Count > 0)
				{
					DnsSecValidationResult recordsValidationResult = await _validator.ValidateAsync(cName.CanonicalName, recordType, recordClreplaced, msg, records, null, token);
					if ((recordsValidationResult == DnsSecValidationResult.Bogus) || (recordsValidationResult == DnsSecValidationResult.Indeterminate))
						throw new DnsSecValidationException("CNAME matching records could not be validated");

					validationResult = cNameValidationResult == recordsValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned;
					_cache.Add(name, recordType, recordClreplaced, records, validationResult, Math.Min(cName.TimeToLive, records.Min(x => x.TimeToLive)));

					return new DnsSecResult<T>(records, validationResult);
				}

				var cNameResults = await ResolveSecureAsync<T>(cName.CanonicalName, recordType, recordClreplaced, token);
				validationResult = cNameValidationResult == cNameResults.ValidationResult ? cNameValidationResult : DnsSecValidationResult.Unsigned;

				if (cNameResults.Records.Count > 0)
					_cache.Add(name, recordType, recordClreplaced, cNameResults.Records, validationResult, Math.Min(cName.TimeToLive, cNameResults.Records.Min(x => x.TimeToLive)));

				return new DnsSecResult<T>(cNameResults.Records, validationResult);
			}

			List<T> res = msg.AnswerRecords.Where(x => (x.RecordType == recordType) && (x.RecordClreplaced == recordClreplaced) && x.Name.Equals(name)).OfType<T>().ToList();

			validationResult = await _validator.ValidateAsync(name, recordType, recordClreplaced, msg, res, null, token);

			if ((validationResult == DnsSecValidationResult.Bogus) || (validationResult == DnsSecValidationResult.Indeterminate))
				throw new DnsSecValidationException("Response records could not be validated");

			if (res.Count > 0)
				_cache.Add(name, recordType, recordClreplaced, res, validationResult, res.Min(x => x.TimeToLive));

			return new DnsSecResult<T>(res, validationResult);
		}

19 Source : ParquetReaderTest.cs
with MIT License
from aloneguid

[Fact]
      public void Read_multiple_data_pages()
      {
         using (var reader =
            new ParquetReader(OpenTestFile("/special/multi_data_page.parquet"), leaveStreamOpen: false))
         {
            DataColumn[] columns = reader.ReadEntireRowGroup();

            string[] s = (string[]) columns[0].Data;
            double?[] d = (double?[]) columns[1].Data;

            // check for nulls (issue #370)
            for (int i = 0; i < s.Length; i++)
            {
               replacedert.True(s[i] != null, "found null in s at " + i);
               replacedert.True(d[i] != null, "found null in d at " + i);
            }

            // run aggregations checking row alignment (issue #371)
            var seq = s.Zip(d.Cast<double>(), (w, v) => new {w, v})
               .Where(p => p.w == "favorable")
               .ToList();

            // double matching is fuzzy, but matching strings is enough for this test
            // ground truth was computed using Spark
            replacedert.Equal(26706.6185312147, seq.Sum(p => p.v), 5);
            replacedert.Equal(0.808287234987281, seq.Average(p => p.v), 5);
            replacedert.Equal(0.71523915461624, seq.Min(p => p.v), 5);
            replacedert.Equal(0.867111980015206, seq.Max(p => p.v), 5);
         }
      }

19 Source : GridViewBuilder.cs
with GNU General Public License v3.0
from AndreiFedarets

private void RecalculateIndexes()
        {
            int minRow = _processedItems.Min(x => x.Row);
            int minColumn = _processedItems.Min(x => x.Column);
            int rowOffset = Math.Abs(minRow);
            int columnOffset = Math.Abs(minColumn);
            foreach (GridViewItem cell in _processedItems)
            {
                cell.Row += rowOffset;
                cell.Column += columnOffset;
            }
        }

19 Source : EventTreeMerger.cs
with GNU General Public License v3.0
from AndreiFedarets

private IEventTree[] MergeByThreads(IEnumerable<ISingleEventTree> source)
        {
            IGrouping<uint, ISingleEventTree>[] groups = source.GroupBy(x => x.ThreadUid).ToArray();
            IEventTree[] result = new IEventTree[groups.Length];
            for (int i = 0; i < groups.Length; i++)
            {
                ISingleEventTree[] items = groups[i].ToArray();
                uint beginLifetime = items.Min(x => x.BeginLifetime);
                uint endLifetime = items.Max(x => x.EndLifetime);
                uint threadOsId = items[0].ThreadOsId;
                uint threadUid = items[0].ThreadUid;
                List<byte[]> data = items.Select(x => x.GetBinaryData()).ToList();
                uint hits = 1;
                uint time = (uint)data.Sum(x => NativeEventHelper.GetTime(x));
                byte[] mergedData = _agentLibrary.MergeEventTrees(data, NativeEventHelper.CreateEvent(ThreadEventTreeMessage.EventType, 0, threadUid, time, hits));
                ThreadEventTree threadEventTree = new ThreadEventTree(threadUid, threadOsId, beginLifetime, endLifetime, mergedData);
                result[i] = threadEventTree;
            }
            return result;
        }

19 Source : EventTreeMerger.cs
with GNU General Public License v3.0
from AndreiFedarets

private IEventTree[] MergeByRoots(IEnumerable<ISingleEventTree> source)
        {
            IGrouping<ulong, ISingleEventTree>[] groups = source.GroupBy(x => x.EventHash).ToArray();
            IEventTree[] result = new IEventTree[groups.Length];
            for (int i = 0; i < groups.Length; i++)
            {
                ISingleEventTree[] items = groups[i].ToArray();
                uint beginLifetime = items.Min(x => x.BeginLifetime);
                uint endLifetime = items.Max(x => x.EndLifetime);
                List<byte[]> data = items.Select(x => x.GetBinaryData()).ToList();
                byte[] mergedData = _agentLibrary.MergeEventTrees(data);
                MergedEventTree mergedEventTree = new MergedEventTree(beginLifetime, endLifetime, mergedData);
                result[i] = mergedEventTree;
            }
            return result;
        }

19 Source : StatisticsDatabase.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public async Task CreateHistogramAsync(
            string rankingFileName)
        {
            if (!File.Exists(rankingFileName))
            {
                return;
            }

            using (var cn = this.OpenRankingDatabaseConnection(rankingFileName))
            {
                using (var tran = cn.BeginTransaction())
                {
                    using (var cm = cn.CreateCommand())
                    {
                        cm.Transaction = tran;

                        var q = new StringBuilder();
                        q.AppendLine("DELETE FROM histograms;");
                        cm.CommandText = q.ToString();
                        await cm.ExecuteNonQueryAsync();
                    }

                    tran.Commit();
                }

                using (var db = new DataContext(cn))
                using (var tran = cn.BeginTransaction())
                {
                    db.Transaction = tran;
                    var rankings = db.GetTable<RankingModel>().ToArray();

                    var averages =
                        from x in rankings
                        group x by
                        x.CharacterHash
                        into g
                        select new
                        {
                            SpecName = g.First().Spec,
                            DPSAverage = g.Average(z => z.Total),
                            Rank = ((int)(g.Average(z => z.Total)) / 100) * 100,
                        };

                    var histograms =
                        from x in averages
                        group x by new
                        {
                            x.SpecName,
                            x.Rank
                        }
                        into g
                        select new
                        {
                            g.Key.SpecName,
                            g.Key.Rank,
                            RankFrom = g.Key.Rank,
                            Frequency = (double)g.Count(),
                        };

                    var id = 1;
                    var specs =
                        from x in histograms
                        orderby
                        x.SpecName,
                        x.Rank
                        group x by
                        x.SpecName;

                    var enreplacedies = new List<HistogramModel>(histograms.Count());

                    foreach (var spec in specs)
                    {
                        var totalCount = spec.Sum(x => x.Frequency);
                        var count = 0d;
                        var rankMin = spec.Min(x => x.Rank);
                        var rankMax = spec.Max(x => x.Rank);

                        for (int i = rankMin; i <= rankMax; i += 100)
                        {
                            var entry = spec.FirstOrDefault(x => x.Rank == i);
                            var f = entry?.Frequency ?? 0;

                            var hist = new HistogramModel()
                            {
                                ID = id++,
                                SpecName = spec.Key,
                                Rank = i,
                                RankFrom = i,
                                Frequency = f,
                                FrequencyPercent = round(f / totalCount * 100d),
                                RankPercentile = round(count / totalCount * 100d),
                            };

                            enreplacedies.Add(hist);
                            count += f;
                        }
                    }

                    var table = db.GetTable<HistogramModel>();
                    table.InsertAllOnSubmit<HistogramModel>(enreplacedies);
                    db.SubmitChanges();

                    // ランキングテーブルを消去する
                    using (var cm = cn.CreateCommand())
                    {
                        cm.Transaction = tran;

                        var q = new StringBuilder();
                        q.AppendLine("DELETE FROM rankings;");
                        cm.CommandText = q.ToString();
                        await cm.ExecuteNonQueryAsync();
                    }

                    tran.Commit();
                }

                // DBを最適化する
                using (var cm = cn.CreateCommand())
                {
                    var q = new StringBuilder();
                    q.AppendLine("VACUUM;");
                    q.AppendLine("PRAGMA Optimize;");
                    cm.CommandText = q.ToString();
                    await cm.ExecuteNonQueryAsync();
                }
            }

            double round(double value)
            {
                return float.Parse(value.ToString("N3"));
            }
        }

19 Source : HistogramsModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private static HistogramsModel CreateDesigntimeModel()
        {
            var model = new HistogramsModel()
            {
                SpecName = "Black Mage",
                Ranks = new[]
                {
                    new HistogramModel() { SpecName = "Black Mage", Rank = 1800, RankFrom = 1800, RankPercentile =  0.000 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 1900, RankFrom = 1900, RankPercentile =  0.016 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2000, RankFrom = 2000, RankPercentile =  0.016 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2100, RankFrom = 2100, RankPercentile =  0.016 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2200, RankFrom = 2200, RankPercentile =  0.016 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2300, RankFrom = 2300, RankPercentile =  0.016 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2400, RankFrom = 2400, RankPercentile =  0.032 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2500, RankFrom = 2500, RankPercentile =  0.032 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2600, RankFrom = 2600, RankPercentile =  0.032 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2700, RankFrom = 2700, RankPercentile =  0.032 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2800, RankFrom = 2800, RankPercentile =  0.032 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 2900, RankFrom = 2900, RankPercentile =  0.032 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3000, RankFrom = 3000, RankPercentile =  0.047 , FrequencyPercent = 0.047 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3100, RankFrom = 3100, RankPercentile =  0.095 , FrequencyPercent = 0.032 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3200, RankFrom = 3200, RankPercentile =  0.126 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3300, RankFrom = 3300, RankPercentile =  0.126 , FrequencyPercent = 0.032 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3400, RankFrom = 3400, RankPercentile =  0.158 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3500, RankFrom = 3500, RankPercentile =  0.158 , FrequencyPercent = 0.032 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3600, RankFrom = 3600, RankPercentile =  0.190 , FrequencyPercent = 0.047 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3700, RankFrom = 3700, RankPercentile =  0.237 , FrequencyPercent = 0.047 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3800, RankFrom = 3800, RankPercentile =  0.284 , FrequencyPercent = 0.047 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 3900, RankFrom = 3900, RankPercentile =  0.332 , FrequencyPercent = 0.095 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4000, RankFrom = 4000, RankPercentile =  0.427 , FrequencyPercent = 0.111 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4100, RankFrom = 4100, RankPercentile =  0.537 , FrequencyPercent = 0.111 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4200, RankFrom = 4200, RankPercentile =  0.648 , FrequencyPercent = 0.142 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4300, RankFrom = 4300, RankPercentile =  0.790 , FrequencyPercent = 0.253 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4400, RankFrom = 4400, RankPercentile =  1.043 , FrequencyPercent = 0.363 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4500, RankFrom = 4500, RankPercentile =  1.406 , FrequencyPercent = 0.300 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4600, RankFrom = 4600, RankPercentile =  1.706 , FrequencyPercent = 0.427 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4700, RankFrom = 4700, RankPercentile =  2.133 , FrequencyPercent = 0.237 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4800, RankFrom = 4800, RankPercentile =  2.370 , FrequencyPercent = 0.537 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 4900, RankFrom = 4900, RankPercentile =  2.907 , FrequencyPercent = 0.648 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5000, RankFrom = 5000, RankPercentile =  3.555 , FrequencyPercent = 1.059 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5100, RankFrom = 5100, RankPercentile =  4.614 , FrequencyPercent = 1.027 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5200, RankFrom = 5200, RankPercentile =  5.641 , FrequencyPercent = 1.201 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5300, RankFrom = 5300, RankPercentile =  6.842 , FrequencyPercent = 1.738 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5400, RankFrom = 5400, RankPercentile =  8.580 , FrequencyPercent = 1.659 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5500, RankFrom = 5500, RankPercentile = 10.239 , FrequencyPercent = 1.975 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5600, RankFrom = 5600, RankPercentile = 12.214 , FrequencyPercent = 2.212 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5700, RankFrom = 5700, RankPercentile = 14.426 , FrequencyPercent = 2.639 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5800, RankFrom = 5800, RankPercentile = 17.064 , FrequencyPercent = 3.429 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 5900, RankFrom = 5900, RankPercentile = 20.493 , FrequencyPercent = 3.492 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6000, RankFrom = 6000, RankPercentile = 23.985 , FrequencyPercent = 3.760 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6100, RankFrom = 6100, RankPercentile = 27.745 , FrequencyPercent = 4.282 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6200, RankFrom = 6200, RankPercentile = 32.027 , FrequencyPercent = 4.677 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6300, RankFrom = 6300, RankPercentile = 36.704 , FrequencyPercent = 5.498 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6400, RankFrom = 6400, RankPercentile = 42.203 , FrequencyPercent = 5.024 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6500, RankFrom = 6500, RankPercentile = 47.227 , FrequencyPercent = 5.309, IsCurrent = true },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6600, RankFrom = 6600, RankPercentile = 52.536 , FrequencyPercent = 5.894 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6700, RankFrom = 6700, RankPercentile = 58.429 , FrequencyPercent = 5.135 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6800, RankFrom = 6800, RankPercentile = 63.565 , FrequencyPercent = 4.661 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 6900, RankFrom = 6900, RankPercentile = 68.226 , FrequencyPercent = 4.076 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7000, RankFrom = 7000, RankPercentile = 72.302 , FrequencyPercent = 4.234 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7100, RankFrom = 7100, RankPercentile = 76.537 , FrequencyPercent = 3.666 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7200, RankFrom = 7200, RankPercentile = 80.202 , FrequencyPercent = 3.365 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7300, RankFrom = 7300, RankPercentile = 83.568 , FrequencyPercent = 2.781 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7400, RankFrom = 7400, RankPercentile = 86.349 , FrequencyPercent = 2.496 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7500, RankFrom = 7500, RankPercentile = 88.845 , FrequencyPercent = 2.465 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7600, RankFrom = 7600, RankPercentile = 91.310 , FrequencyPercent = 1.375 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7700, RankFrom = 7700, RankPercentile = 92.684 , FrequencyPercent = 1.422 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7800, RankFrom = 7800, RankPercentile = 94.106 , FrequencyPercent = 1.343 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 7900, RankFrom = 7900, RankPercentile = 95.450 , FrequencyPercent = 1.106 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8000, RankFrom = 8000, RankPercentile = 96.556 , FrequencyPercent = 1.027 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8100, RankFrom = 8100, RankPercentile = 97.583 , FrequencyPercent = 0.679 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8200, RankFrom = 8200, RankPercentile = 98.262 , FrequencyPercent = 0.521 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8300, RankFrom = 8300, RankPercentile = 98.783 , FrequencyPercent = 0.458 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8400, RankFrom = 8400, RankPercentile = 99.242 , FrequencyPercent = 0.205 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8500, RankFrom = 8500, RankPercentile = 99.447 , FrequencyPercent = 0.284 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8600, RankFrom = 8600, RankPercentile = 99.731 , FrequencyPercent = 0.126 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8700, RankFrom = 8700, RankPercentile = 99.858 , FrequencyPercent = 0.032 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8800, RankFrom = 8800, RankPercentile = 99.889 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 8900, RankFrom = 8900, RankPercentile = 99.889 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9000, RankFrom = 9000, RankPercentile = 99.905 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9100, RankFrom = 9100, RankPercentile = 99.921 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9200, RankFrom = 9200, RankPercentile = 99.937 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9300, RankFrom = 9300, RankPercentile = 99.953 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9400, RankFrom = 9400, RankPercentile = 99.968 , FrequencyPercent = 0.016 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9500, RankFrom = 9500, RankPercentile = 99.984 , FrequencyPercent = 0.000 },
                    new HistogramModel() { SpecName = "Black Mage", Rank = 9600, RankFrom = 9600, RankPercentile = 99.984 , FrequencyPercent = 0.016 },
                },
            };

            var i = 1;
            foreach (var rank in model.Ranks)
            {
                rank.ID = i++;
            }

            model.MaxRank = model.Ranks.Max(x => x.Rank);
            model.MinRank = model.Ranks.Min(x => x.Rank);
            model.MaxFrequencyPercent = Math.Ceiling(model.Ranks.Max(x => x.FrequencyPercent));

            foreach (var rank in model.Ranks)
            {
                rank.FrequencyRatioToMaximum = rank.FrequencyPercent / model.MaxFrequencyPercent;
            }

            return model;
        }

19 Source : LocalFilesTileSource.cs
with MIT License
from apdevelop

Task ITileSource.InitAsync()
        {
            // Configuration values priority:
            // 1. Default values for local files source type.
            // 2. Actual values (from first found tile properties).
            // 3. Values from configuration file - overrides given above, if provided.

            // Detect zoom levels range - build list of folders
            var zoomLevels = new List<int>();
            var xIndex = this.configuration.Location.IndexOf("{x}", StringComparison.InvariantCultureIgnoreCase);
            var yIndex = this.configuration.Location.IndexOf("{y}", StringComparison.InvariantCultureIgnoreCase);
            var zIndex = this.configuration.Location.IndexOf("{z}", StringComparison.InvariantCultureIgnoreCase);
            if ((zIndex < yIndex) && (zIndex < xIndex))
            {
                var baseFolder = new Uri(this.configuration.Location.Substring(0, zIndex)).LocalPath;
                foreach (var directory in Directory.GetDirectories(baseFolder))
                {
                    if (Int32.TryParse(Path.GetFileName(directory), out int zoomLevel))
                    {
                        zoomLevels.Add(zoomLevel);
                    }
                }
            }

            var replacedle = String.IsNullOrEmpty(this.configuration.replacedle) ?
                this.configuration.Id :
                this.configuration.replacedle;

            var minZoom = this.configuration.MinZoom ?? (zoomLevels.Count > 0 ? zoomLevels.Min(z => z) : 0);
            var maxZoom = this.configuration.MaxZoom ?? (zoomLevels.Count > 0 ? zoomLevels.Max(z => z) : 24);

            // Re-create configuration
            this.configuration = new TileSourceConfiguration
            {
                Id = this.configuration.Id,
                Type = this.configuration.Type,
                Format = this.configuration.Format, // TODO: from file properties (extension)
                replacedle = replacedle,
                Tms = this.configuration.Tms ?? false, // Default is tms=false for file storage
                Srs = Utils.SrsCodes.EPSG3857, // TODO: support for EPSG:4326
                Location = this.configuration.Location,
                ContentType = Utils.EnreplacediesConverter.TileFormatToContentType(this.configuration.Format), // TODO: from file properties
                MinZoom = minZoom,
                MaxZoom = maxZoom,
            };

            return Task.CompletedTask;
        }

19 Source : RasterTileSource.cs
with MIT License
from apdevelop

private void DrawGeoTiffTilesToRasterCanvas(
            Bitmap outputImage,
            M.Bounds tileBounds,
            IList<GeoTiff.TileCoordinates> sourceTileCoordinates,
            int backgroundColor,
            int sourceTileWidth,
            int sourceTileHeight)
        {
            var tileMinX = sourceTileCoordinates.Min(t => t.X);
            var tileMinY = sourceTileCoordinates.Min(t => t.Y);
            var tilesCountX = sourceTileCoordinates.Max(t => t.X) - tileMinX + 1;
            var tilesCountY = sourceTileCoordinates.Max(t => t.Y) - tileMinY + 1;
            var canvasWidth = tilesCountX * sourceTileWidth;
            var canvasHeight = tilesCountY * sourceTileHeight;

            // TODO: ? scale before draw to reduce memory allocation
            // TODO: check max canvas size

            var canvas = U.ImageHelper.CreateEmptyPngImage(canvasWidth, canvasHeight, backgroundColor);

            using (var canvasImageStream = new MemoryStream(canvas))
            {
                using (var canvasImage = new Bitmap(canvasImageStream))
                {
                    using (var graphics = Graphics.FromImage(canvasImage))
                    {
                        // Draw all source tiles without scaling
                        foreach (var sourceTile in sourceTileCoordinates)
                        {
                            var pixelX = sourceTile.X * this.rasterProperties.TileWidth;
                            var pixelY = sourceTile.Y * this.rasterProperties.TileHeight;

                            if ((pixelX >= this.rasterProperties.ImageWidth) || (pixelY >= this.rasterProperties.ImageHeight))
                            {
                                continue;
                            }

                            var imageBuffer = ReadTiffTile(
                                this.configuration.Location,
                                this.rasterProperties.TileWidth,
                                this.rasterProperties.TileHeight,
                                this.rasterProperties.TileSize,
                                pixelX,
                                pixelY);

                            const int PixelDataSize = 4;
                            var stride = this.rasterProperties.TileWidth * PixelDataSize;
                            var handle = GCHandle.Alloc(imageBuffer, GCHandleType.Pinned);

                            Bitmap sourceImage = null;
                            try
                            {
                                var offsetX = (sourceTile.X - tileMinX) * sourceTileWidth;
                                var offsetY = (sourceTile.Y - tileMinY) * sourceTileHeight;

                                sourceImage = new Bitmap(this.rasterProperties.TileWidth, this.rasterProperties.TileHeight, stride, PixelFormat.Format32bppArgb, handle.AddrOfPinnedObject());

                                if ((sourceImage.HorizontalResolution == canvasImage.HorizontalResolution) &&
                                    (sourceImage.VerticalResolution == canvasImage.VerticalResolution))
                                {
                                    graphics.DrawImageUnscaled(sourceImage, offsetX, offsetY);
                                }
                                else
                                {
                                    graphics.DrawImage(sourceImage, new Rectangle(offsetX, offsetY, sourceImage.Width, sourceImage.Height));
                                }

                                // For debug
                                ////using var borderPen = new Pen(Color.Magenta, 5.0f);
                                ////graphics.DrawRectangle(borderPen, new Rectangle(offsetX, offsetY, sourceImage.Width, sourceImage.Height));
                                ////graphics.DrawString($"R = {sourceTile.Y * this.geoTiffInfo.TileHeight}", new Font("Arial", 36.0f), Brushes.Magenta, offsetX, offsetY);
                            }
                            finally
                            {
                                handle.Free();
                                sourceImage.Dispose();
                            }
                        }
                    }

                    // TODO: ! better image transformation / reprojection between coordinate systems
                    var pixelOffsetX = XToGeoTiffPixelX(this.rasterProperties, tileBounds.Left) - sourceTileWidth * tileMinX;
                    var pixelOffsetY = YToGeoTiffPixelY(this.rasterProperties, tileBounds.Top) - sourceTileHeight * tileMinY;
                    var pixelWidth = XToGeoTiffPixelX(this.rasterProperties, tileBounds.Right) - XToGeoTiffPixelX(this.rasterProperties, tileBounds.Left);
                    var pixelHeight = YToGeoTiffPixelY(this.rasterProperties, tileBounds.Bottom) - YToGeoTiffPixelY(this.rasterProperties, tileBounds.Top);

                    var sourceRectangle = new Rectangle(
                        (int)Math.Round(pixelOffsetX),
                        (int)Math.Round(pixelOffsetY),
                        (int)Math.Round(pixelWidth),
                        (int)Math.Round(pixelHeight));

                    // Clip and scale to requested size of output image
                    var destRectangle = new Rectangle(0, 0, outputImage.Width, outputImage.Height);
                    using (var graphics = Graphics.FromImage(outputImage))
                    {
                        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bicubic;
                        graphics.DrawImage(canvasImage, destRectangle, sourceRectangle, GraphicsUnit.Pixel);
                    }
                }
            }
        }

19 Source : WmsHelper.cs
with MIT License
from apdevelop

public static void DrawWebMercatorTilesToRasterCanvas(
            Bitmap outputImage,
            Models.Bounds boundingBox,
            IList<Models.TileDataset> sourceTiles,
            int backgroundColor,
            int tileSize)
        {
            var zoom = sourceTiles[0].Z;
            var tileMinX = sourceTiles.Min(t => t.X);
            var tileMinY = sourceTiles.Min(t => t.Y);
            var tilesCountX = sourceTiles.Max(t => t.X) - tileMinX + 1;
            var tilesCountY = sourceTiles.Max(t => t.Y) - tileMinY + 1;
            var canvasWidth = tilesCountX * tileSize;
            var canvasHeight = tilesCountY * tileSize;

            var canvas = ImageHelper.CreateEmptyPngImage(canvasWidth, canvasHeight, backgroundColor);

            using (var canvasImageStream = new MemoryStream(canvas))
            {
                using (var canvasImage = new Bitmap(canvasImageStream))
                {
                    using (var graphics = Graphics.FromImage(canvasImage))
                    {
                        // Draw all tiles without scaling
                        foreach (var sourceTile in sourceTiles)
                        {
                            var offsetX = (sourceTile.X - tileMinX) * tileSize;
                            var offsetY = (sourceTile.Y - tileMinY) * tileSize;
                            using (var sourceStream = new MemoryStream(sourceTile.ImageData))
                            {
                                using (var sourceImage = Image.FromStream(sourceStream))
                                {
                                    if ((sourceImage.HorizontalResolution == canvasImage.HorizontalResolution) &&
                                        (sourceImage.VerticalResolution == canvasImage.VerticalResolution))
                                    {
                                        graphics.DrawImageUnscaled(sourceImage, offsetX, offsetY);
                                    }
                                    else
                                    {
                                        graphics.DrawImage(sourceImage, new Rectangle(offsetX, offsetY, sourceImage.Width, sourceImage.Height));
                                    }
                                }
                            }
                        }
                    }

                    var geoBBox = EnreplacediesConverter.MapRectangleToGeographicalBounds(boundingBox);
                    var pixelOffsetX = WebMercator.LongitudeToPixelXAtZoom(geoBBox.MinLongitude, zoom) - tileSize * tileMinX;
                    var pixelOffsetY = WebMercator.LareplacedudeToPixelYAtZoom(geoBBox.MaxLareplacedude, zoom) - tileSize * tileMinY;
                    var pixelWidth = WebMercator.LongitudeToPixelXAtZoom(geoBBox.MaxLongitude, zoom) - WebMercator.LongitudeToPixelXAtZoom(geoBBox.MinLongitude, zoom);
                    var pixelHeight = WebMercator.LareplacedudeToPixelYAtZoom(geoBBox.MinLareplacedude, zoom) - WebMercator.LareplacedudeToPixelYAtZoom(geoBBox.MaxLareplacedude, zoom);
                    var sourceRectangle = new Rectangle(
                        (int)Math.Round(pixelOffsetX),
                        (int)Math.Round(pixelOffsetY),
                        (int)Math.Round(pixelWidth),
                        (int)Math.Round(pixelHeight));

                    // Clip and scale to requested size of output image
                    var destRectangle = new Rectangle(0, 0, outputImage.Width, outputImage.Height);
                    using (var graphics = Graphics.FromImage(outputImage))
                    {
                        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bicubic;
                        graphics.DrawImage(canvasImage, destRectangle, sourceRectangle, GraphicsUnit.Pixel);
                    }
                }
            }
        }

19 Source : BindableMKMapView.cs
with Apache License 2.0
from AppRopio

public void ZoomToAll()
        {
            if (Items == null || Items.Count < 1 || Items.All(x => x.Coordinates == null))
                return;

            try
            {
                double minLareplacedude = Items.Min(x => x.Coordinates?.Lareplacedude ?? double.MaxValue);
                double maxLareplacedude = Items.Max(x => x.Coordinates?.Lareplacedude ?? double.MinValue);
                double minLongitude = Items.Min(x => x.Coordinates?.Longitude ?? double.MaxValue);
                double maxLongitude = Items.Max(x => x.Coordinates?.Longitude ?? double.MinValue);

                MKCoordinateRegion region;
                region.Center.Lareplacedude = (minLareplacedude + maxLareplacedude) / 2;
                region.Center.Longitude = (minLongitude + maxLongitude) / 2;

                double lareplacedudeDelta = (maxLareplacedude - minLareplacedude) * MAP_PADDING;
                region.Span.LareplacedudeDelta = (lareplacedudeDelta < MIN_VISIBLE_LAreplacedUDE) ? MIN_VISIBLE_LAreplacedUDE : lareplacedudeDelta;
                region.Span.LongitudeDelta = (maxLongitude - minLongitude) * MAP_PADDING;

                SetRegion(RegionThatFits(region), true);
            }
            catch (Exception ex)
            {
                Mvx.IoCProvider.Resolve<IMvxLog>().Error(ex.ToString());
            }
        }

19 Source : LevenshteinDistance.cs
with MIT License
from arafattehsin

public static string GetClosest(List<string> stringsToCheck, string stringtoMatch)
        {
            Dictionary<string, int> resultset = new Dictionary<string, int>();
            foreach (string s in stringsToCheck)
            {
                resultset.Add(s, LevenshteinDistance.Compute(stringtoMatch,s));
            }
            
            //get the minimum number of modifications needed to arrive at the basestring
            int minimumModifications = resultset.Min(c => c.Value);

            //gives you a list with all strings that need a minimum of modifications to become the
            //same as the stringtoMatch
            var closestlist = resultset.Where(c => c.Value == minimumModifications).FirstOrDefault();

            return closestlist.Key;
        }

19 Source : CombatReplayMap.cs
with MIT License
from baaron4

internal void ComputeBoundingBox(ParsedEvtcLog log)
        {
            if (log.CanCombatReplay && _rectInMap.topX == _rectInMap.bottomX)
            {
                _rectInMap.topX = int.MaxValue;
                _rectInMap.topY = int.MaxValue;
                _rectInMap.bottomX = int.MinValue;
                _rectInMap.bottomY = int.MinValue;
                foreach (Player p in log.PlayerList)
                {
                    IReadOnlyList<Point3D> pos = p.GetCombatReplayPolledPositions(log);
                    if (pos.Count == 0)
                    {
                        continue;
                    }
                    _rectInMap.topX = Math.Min(Math.Floor(pos.Min(x => x.X)) - 250, _rectInMap.topX);
                    _rectInMap.topY = Math.Min(Math.Floor(pos.Min(x => x.Y)) - 250, _rectInMap.topY);
                    _rectInMap.bottomX = Math.Max(Math.Floor(pos.Max(x => x.X)) + 250, _rectInMap.bottomX);
                    _rectInMap.bottomY = Math.Max(Math.Floor(pos.Max(x => x.Y)) + 250, _rectInMap.bottomY);
                }
            }
        }

19 Source : FightLogic.cs
with MIT License
from baaron4

private static void RegroupTargetsByID(int id, AgentData agentData, List<Combareplacedem> combareplacedems, IReadOnlyDictionary<uint, AbstractExtensionHandler> extensions)
        {
            IReadOnlyList<Agenreplacedem> agents = agentData.GetNPCsByID(id);
            if (agents.Count > 1)
            {
                Agenreplacedem firsreplacedem = agents.First();
                var agentValues = new HashSet<ulong>(agents.Select(x => x.Agent));
                var newTargetAgent = new Agenreplacedem(firsreplacedem);
                newTargetAgent.OverrideAwareTimes(agents.Min(x => x.FirstAware), agents.Max(x => x.LastAware));
                agentData.SwapMasters(new HashSet<Agenreplacedem>(agents), newTargetAgent);
                agentData.ReplaceAgentsFromID(newTargetAgent);
                foreach (Combareplacedem c in combareplacedems)
                {
                    if (agentValues.Contains(c.SrcAgent) && c.SrcIsAgent(extensions))
                    {
                        c.OverrideSrcAgent(newTargetAgent.Agent);
                    }
                    if (agentValues.Contains(c.DstAgent) && c.DstIsAgent(extensions))
                    {
                        c.OverrideDstAgent(newTargetAgent.Agent);
                    }
                }
            }
        }

19 Source : EvtcParser.cs
with MIT License
from baaron4

private void CompletePlayers(ParserController operation)
        {
            //Fix Disconnected players
            IReadOnlyList<Agenreplacedem> playerAgentList = _agentData.GetAgentByType(Agenreplacedem.AgentType.Player);
            foreach (Agenreplacedem playerAgent in playerAgentList)
            {
                if (playerAgent.InstID == 0 || playerAgent.FirstAware == 0 || playerAgent.LastAware == long.MaxValue)
                {
                    operation.UpdateProgressWithCancellationCheck("Skipping invalid player " + playerAgent.Name);
                    continue;
                }
                bool skip = false;
                var player = new Player(playerAgent, _fightData.Logic.Mode == FightLogic.ParseMode.Instanced5 || _fightData.Logic.Mode == FightLogic.ParseMode.sPvP);
                foreach (Player p in _playerList)
                {
                    if (p.Account == player.Account)// same player
                    {
                        if (p.Character == player.Character) // same character, can be fused
                        {
                            skip = true;
                            ulong agent = p.Agenreplacedem.Agent;
                            operation.UpdateProgressWithCancellationCheck("Merging player " + p.Character);
                            foreach (Combareplacedem c in _combareplacedems)
                            {
                                if (c.DstMatchesAgent(player.Agenreplacedem, _enabledExtensions))
                                {
                                    c.OverrideDstAgent(agent);
                                }
                                if (c.SrcMatchesAgent(player.Agenreplacedem, _enabledExtensions))
                                {
                                    c.OverrideSrcAgent(agent);
                                }
                            }
                            _agentData.SwapMasters(player.Agenreplacedem, p.Agenreplacedem);
                            p.Agenreplacedem.OverrideAwareTimes(Math.Min(p.Agenreplacedem.FirstAware, player.Agenreplacedem.FirstAware), Math.Max(p.Agenreplacedem.LastAware, player.Agenreplacedem.LastAware));
                            break;
                        }
                    }
                }
                if (!skip)
                {
                    _playerList.Add(player);
                }
            }
            if (_parserSettings.AnonymousPlayer)
            {
                for (int i = 0; i < _playerList.Count; i++)
                {
                    _playerList[i].Anonymize(i + 1);
                }
            }
            _playerList = _playerList.OrderBy(a => a.Group).ToList();
            if (_playerList.Exists(x => x.Group == 0))
            {
                _playerList.ForEach(x => x.MakeSquadless());
            }
            uint minToughness = _playerList.Min(x => x.Toughness);
            if (minToughness > 0)
            {
                operation.UpdateProgressWithCancellationCheck("Adjusting player toughness scores");
                uint maxToughness = _playerList.Max(x => x.Toughness);
                foreach (Player p in _playerList)
                {
                    p.Agenreplacedem.OverrideToughness((ushort)Math.Round(10.0 * (p.Agenreplacedem.Toughness - minToughness) / Math.Max(1.0, maxToughness - minToughness)));
                }
            }
        }

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource MinBy<TSource, TResult>
		(
			this IEnumerable<TSource> source,
			Func<TSource, TResult> selector
		)
		{
			var value = source.Min( selector );
			return source.FirstOrDefault( c => selector( c ).Equals( value ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static IEnumerable<TSource> MinElementsBy<TSource, TResult>
		(
			this IEnumerable<TSource> source,
			Func<TSource, TResult> selector
		)
		{
			var value = source.Min( selector );
			return source.Where( c => selector( c ).Equals( value ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int Nearest
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var min = self.Min( c => Math.Abs( c - target ) );
			return self.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int Nearest<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( self.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearest<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var min = self.Min( c => Math.Abs( selector( c ) - target ) );
			return self.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreThan
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => target < c ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreThan<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreThan<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target < selector( c ) ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrLess
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => c <= target );
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) <= target );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) <= target );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrMore
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => target <= c );
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestOrMore<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreLess
		(
			this IEnumerable<int> self,
			int target
		)
		{
			var list = self.Where( c => c < target ).ToArray();
			var min = list.Min( c => Math.Abs( c - target ) );
			return list.FirstOrDefault( c => Math.Abs( c - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static int NearestMoreLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return selector( list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min ) );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestMoreLess<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => selector( c ) < target ).ToArray();
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : IEnumerableExt.cs
with MIT License
from baba-s

public static TSource FindNearestOrMore<TSource>
		(
			this IEnumerable<TSource> self,
			int target,
			Func<TSource, int> selector
		)
		{
			var list = self.Where( c => target <= selector( c ) );
			var min = list.Min( c => Math.Abs( selector( c ) - target ) );
			return list.FirstOrDefault( c => Math.Abs( selector( c ) - target ) == min );
		}

19 Source : RawProduceComparison.cs
with MIT License
from BEagle1984

private static void WriteSummary(List<Stats> statsList)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Writereplacedle("** RESULTS **");

            var maxLabelLength = statsList.Max(stats => stats.Label.Length);

            var groupedStats = statsList.GroupBy(
                stats => new
                {
                    stats.Count,
                    stats.MessageSize
                });

            foreach (var statsGroup in groupedStats)
            {
                Writereplacedle(
                    $"{statsGroup.Key.Count:#,###} messages of {statsGroup.Key.MessageSize:#,###} bytes");

                var minElapsed = statsGroup.Min(stats => stats.Elapsed);

                foreach (var stats in statsGroup)
                {
                    Console.ForegroundColor =
                        stats.Elapsed == minElapsed ? ConsoleColor.Green : ConsoleColor.White;

                    var performance = (stats.Count / stats.Elapsed.TotalSeconds)
                        .ToString("#,##0.00", CultureInfo.CurrentCulture)
                        .PadLeft(12);
                    var elapsed = stats.Elapsed.TotalSeconds.ToString("0.000", CultureInfo.CurrentCulture)
                        .PadLeft(7);

                    Console.Write(stats.Label.PadRight(maxLabelLength));
                    Console.Write(" : ");
                    Console.Write($"{performance} msg/s");
                    Console.Write($" | {elapsed}s");

                    if (stats.Elapsed > minElapsed)
                    {
                        Console.Write(
                            ((stats.Elapsed.TotalMilliseconds - minElapsed.TotalMilliseconds) /
                             minElapsed.TotalMilliseconds).ToString("+0.00%", CultureInfo.CurrentCulture)
                            .PadLeft(10));
                    }

                    Console.WriteLine();
                }
            }
        }

19 Source : ColorHelper.cs
with GNU General Public License v3.0
from berichan

public static int ClosestColor2(IReadOnlyCollection<Color> colors, Color target)
    {
        var colorDiffs = colors.Select(n => ColorDiff(n, target)).Min(n => n);
        return colors.ToList().FindIndex(n => ColorDiff(n, target) == colorDiffs);
    }

19 Source : ColorHelper.cs
with GNU General Public License v3.0
from berichan

public static int ClosestColor1(IReadOnlyCollection<Color> colors, Color target)
    {
        var hue1 = target.GetHue();
        var diffs = colors.Select(n => GetHueDistance(n.GetHue(), hue1));
        var diffMin = diffs.Min(n => n);
        return diffs.ToList().FindIndex(n => n == diffMin);
    }

19 Source : ColorHelper.cs
with GNU General Public License v3.0
from berichan

public static int ClosestColor3(IReadOnlyCollection<Color> colors, Color target)
    {
        float hue1 = target.GetHue();
        var num1 = ColorNum(target);
        var diffs = colors.Select(n => Math.Abs(ColorNum(n) - num1) +
                                       GetHueDistance(n.GetHue(), hue1));
        var diffMin = diffs.Min(x => x);
        return diffs.ToList().FindIndex(n => n == diffMin);
    }

19 Source : BlockConverter.cs
with GNU General Public License v3.0
from BigBang1112

public void Process(CGameCtnChallenge map, int version, ConverterParameters parameters, ConverterTemporary temporary)
        {
            var random = new Random(map.MapUid.GetHashCode());

            var skinLocatorTasks = new Dictionary<Uri, Task<bool>>();
            var skinsWithLocator = new List<CGameCtnBlockSkin>();

            var skins = YamlManager.Parse<Dictionary<string, SkinDefinition>>("Skins.yml");

            var macroblocks = new Dictionary<string, CGameCtnMacroBlockInfo>();
            var log = new HashSet<string>();

            var blocks = map.Blocks.ToList();
            map.Blocks.Clear();

            foreach (var block in blocks)
            {
                if (parameters.Definitions.TryGetValue(block.Name, out Conversion[] variants)) // If the block has a definition in the sheet, return the possible variants
                {
                    if (variants != null)
                    {
                        var variant = block.Variant.GetValueOrDefault(); // Get the variant number

                        if (variants.Length > variant) // If the variant is available in the possible variants
                        {
                            var conversion = variants[variant]; // Reference it with 'conversion'

                            if (conversion != null) // If the variant actually has a conversion
                            {
                                ProcessConversion(block, conversion);
                            }
                            else
                                log.Add($"Missing but defined block variant: {block.Name} variant {block.Variant}");
                        }
                        else
                            log.Add($"Missing block variant: {block.Name} variant {block.Variant}");
                    }
                    else
                        log.Add($"Known block but undefined variants: {block.Name} variant {block.Variant}");
                }
                else
                    log.Add($"Missing block: {block.Name}");
            }

            /*void PlaceMacroblock(CGameCtnBlock referenceBlock, CGameCtnMacroBlockInfo macroblock)
            {
                foreach(var block in macroblock.Blocks)
                {
                    var b = block.Copy();
                    b.Coord += referenceBlock.Coord;

                    map.Blocks.Add(b);
                }
            }*/

            void ProcessConversion(CGameCtnBlock referenceBlock, Conversion conversion)
            {
                List<CGameCtnBlock> placedBlocks = new List<CGameCtnBlock>();

                var radians = ((int)referenceBlock.Direction + conversion.OffsetDir) % 4 * (float)(Math.PI / 2);

                if (conversion.Block != null) // If a Block property is defined
                    placedBlocks.Add(ConvertBlock(referenceBlock, conversion, conversion.Block));

                if (conversion.Blocks != null) // If a Blocks property is defined
                {
                    var center = new Vec3();

                    if (conversion.OffsetCoordByBlockModel)
                    {
                        var allCoords = conversion.Blocks.Select(x => new Int3(x.OffsetCoord[0], x.OffsetCoord[1], x.OffsetCoord[2])).ToArray();
                        var min = new Int3(allCoords.Min(x => x.X), allCoords.Min(x => x.Y), allCoords.Min(x => x.Z));
                        var max = new Int3(allCoords.Max(x => x.X), allCoords.Max(x => x.Y), allCoords.Max(x => x.Z));
                        var size = max - min + (1, 1, 1);

                        center = (min + max) * .5f;

                        if (conversion.Center != null)
                            center = (Vec3)conversion.Center;

                        var newCoords = new List<Vec3>();

                        foreach (var c in conversion.Blocks)
                            newCoords.Add(AdditionalMath.RotateAroundCenter((Int3)c.OffsetCoord, center, radians));

                        if (center != default)
                        {
                            var newMin = new Vec3(newCoords.Min(x => x.X), newCoords.Min(x => x.Y), newCoords.Min(x => x.Z));
							newCoords = newCoords.Select(x => x - newMin).ToList();
						}

                        for (var i = 0; i < conversion.Blocks.Length; i++)
                        {
                            var c = conversion.Blocks[i];

                            placedBlocks.Add(ConvertBlock(referenceBlock, conversion, c, referenceBlock.Coord + (Int3)newCoords[i]));
                        }
                    }
                    else
                    {
                        foreach (var c in conversion.Blocks)
                        {
                            placedBlocks.Add(ConvertBlock(referenceBlock, conversion, c, referenceBlock.Coord + (Int3)c.OffsetCoord));
                        }
                    }
                }

                if (conversion.Item != null)
                    PlaceItem(conversion.Item);

                if (conversion.Items != null)
                    foreach (var item in conversion.Items)
                        PlaceItem(item);

                if (conversion.Light != null)
                    PlaceLight(conversion.Light);

                if (conversion.Lights != null)
                    foreach (var light in conversion.Lights)
                        PlaceLight(light);

                if (referenceBlock.Skin != null)
                {
                    if (conversion.HasItemSkinPack)
                    {
                        if (parameters.ItemSkinPacks.TryGetValue(referenceBlock.Name, out ItemSkinPack[] set))
                        {
                            if (set.Length > referenceBlock.Variant)
                            {
                                var variant = set[referenceBlock.Variant.Value];

                                if (variant != null)
                                {
                                    var skinFile = referenceBlock.Skin.PackDesc.FilePath;
                                    if (skinFile.StartsWith("Skins\\"))
                                        skinFile = skinFile.Substring("Skins\\".Length);
                                    else if (referenceBlock.Skin.PackDesc.Version > 1)
                                        throw new Exception("Skin with unknown folder.");

                                    if (variant.Skins.TryGetValue(skinFile, out string itemName))
                                    {
                                        // Previous skins should be removed
                                        foreach (var b in placedBlocks)
                                        {
                                            if (b.Skin == null) // If the official sign set doesn't include the skin variant, create a new skin
                                            {
                                                var skin = new CGameCtnBlockSkin { Text = "!4" };
                                                skin.CreateChunk<CGameCtnBlockSkin.Chunk03059002>();
                                                skin.CreateChunk<CGameCtnBlockSkin.Chunk03059003>();

                                                b.Skin = skin;
                                                b.Author = "Nadeo";
                                            }

                                            // Set the skin texture of the sign to black for cleanness
                                            b.Skin.PackDesc = new FileRef(3, FileRef.DefaultChecksum, "Skins\\Any\\Advertisement2x1\\Off.tga", "");
                                            b.Skin.SecondaryPackDesc = new FileRef();

                                            skinsWithLocator.Remove(b.Skin);
                                            // Remove the skin from locators if there is one for some reason, to avoid null exception
                                        }

                                        foreach (var item in variant.Items)
                                        {
                                            var offsetRot = default(Vec3);
                                            if (item.OffsetRot != null)
                                                offsetRot = (Vec3)item.OffsetRot;

                                            var offsetPos = default(Vec3);
                                            if (item.OffsetPos != null)
                                                offsetPos = (Vec3)item.OffsetPos;

                                            PlaceObject(itemName, offsetPos, default, (16, 0, 16), offsetRot);

                                            var itemFilePath = $"{Converter.LocalDirectory}/UserData/Items/{itemName}";
                                            if (!map.Embeds.ContainsKey(itemFilePath))
                                                map.ImportFileToEmbed(itemFilePath, $"Items/{Path.GetDirectoryName(itemName)}");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                void PlaceItem(ConversionItem conversionItem)
                {
                    if (conversionItem == null) return;

                    PlaceObject(conversionItem.Name,
                        (Vec3)conversionItem.OffsetPos,
                        (Vec3)conversionItem.OffsetPos2,
                        (Vec3)conversionItem.OffsetPivot,
                        (Vec3)conversionItem.OffsetRot);
                }

                void PlaceLight(ConversionLight conversionLight)
                {
                    if (conversionLight == null) return;

                    var color = conversionLight.Color;
                    if (parameters.ChristmasMode)
                        color = LightManager.ChirstmasLights[random.Next(LightManager.ChirstmasLights.Length)].ToString("X3");

                    PlaceObject($"NationsConverter\\Lights\\Light_{color}.Item.Gbx", default, default, (Vec3)conversionLight.Offset, default);
                }

                void PlaceObject(string convName, Vec3 convOffsetPos, Vec3 convOffsetPos2, Vec3 convOffsetPivot, Vec3 convOffsetRot)
                {
                    var offsetPos = convOffsetPos;

                    var center = new Vec3(0, 0, 0);
                    offsetPos = AdditionalMath.RotateAroundCenter(offsetPos, center, radians);

                    if (version >= GameVersion.TM2)
                    {
                        offsetPos += parameters.Stadium2RelativeOffset + convOffsetPos2;
                    }

                    var name = "";
                    var collection = 26;
                    var author = "Nadeo";
                    if (convName == null) throw new Exception();
                    var meta = convName.Split(' ');
                    if (meta.Length == 0) throw new Exception();
                    name = meta[0];
                    if (meta.Length > 1)
                    {
                        int.TryParse(meta[1], out collection);
                        if(meta.Length == 3) author = meta[2];
                    }
                    if (name.StartsWith("NationsConverter"))
                        author = "Nations Converter Team";

                    var offsetPivot = convOffsetPivot;

                    if(conversion.OffsetPivotByBlockModel)
                    {
                        IEnumerable<Int3> allCoords = null;
                        if(referenceBlock.IsGround && BlockInfoManager.BlockModels[referenceBlock.Name].Ground != null)
                            allCoords = BlockInfoManager.BlockModels[referenceBlock.Name].Ground.Select(x => (Int3)x.Coord);
                        else if(BlockInfoManager.BlockModels[referenceBlock.Name].Air != null)
                            allCoords = BlockInfoManager.BlockModels[referenceBlock.Name].Air.Select(x => (Int3)x.Coord);

                        var min = new Int3(allCoords.Min(x => x.X), allCoords.Min(x => x.Y), allCoords.Min(x => x.Z));
                        var max = new Int3(allCoords.Max(x => x.X), allCoords.Max(x => x.Y), allCoords.Max(x => x.Z));
                        var box = max - min;

                        var directions = new Int3[]
                        {
                            (0, 0, 0),
                            (0, 0, box.Z),
                            (box.X, 0, box.Z),
                            (box.X, 0, 0)
                        };

                        offsetPivot += directions[(int)referenceBlock.Direction] * (32, 8, 32);
                    }

                    map.PlaceAncreplaceddObject(
                        new Ident(name, collection, author),
                        referenceBlock.Coord * new Vec3(32, 8, 32) + offsetPos + (16, 0, 16),
                        (-radians, 0, 0) - AdditionalMath.ToRadians(convOffsetRot),
                        -offsetPivot);
                }

                if (conversion.Macroblock != null)
                {
                    if (!macroblocks.TryGetValue(conversion.Macroblock, out CGameCtnMacroBlockInfo macro))
                        macro = macroblocks[conversion.Macroblock] = GameBox.Parse<CGameCtnMacroBlockInfo>($"{Converter.LocalDirectory}/Macroblocks/{conversion.Macroblock}").MainNode;
                    map.PlaceMacroblock(macro, referenceBlock.Coord + (0, conversion.OffsetY, 0), Dir.Add(referenceBlock.Direction, (Direction)conversion.OffsetDir));
                }

                if (conversion.FreeBlock != null)
                    PlaceFreeBlock(conversion.FreeBlock);

                if (conversion.FreeBlocks != null)
                    foreach(var block in conversion.FreeBlocks)
                        PlaceFreeBlock(block);

                void PlaceFreeBlock(ConversionFreeBlock block)
                {
                    var offsetPos = (Vec3)block.OffsetPos;
                    var offsetRot = AdditionalMath.ToRadians((Vec3)block.OffsetRot); // Gets the offset rotation in radians

                    offsetPos += AdditionalMath.RotateAroundCenter((0, 0, 0), (16, 0, 16), offsetRot.X);
                    // Makes the offset rotation affect around center of the single piece of the block

                    offsetPos = AdditionalMath.RotateAroundCenter(offsetPos, (16, 0, 16), radians);
                    // Applies the block rotation from the center of the entire block structure

                    if (version <= GameVersion.TMUF)
                        offsetPos -= parameters.Stadium2RelativeOffset * (1, 0, 1);

                    CGameCtnBlockSkin skin = null;
                    if (block.Skin != null)
                    {
                        skin = new CGameCtnBlockSkin()
                        {
                            PackDesc = new FileRef(3, FileRef.DefaultChecksum, "Skins\\" + block.Skin, "")
                        };

                        skin.CreateChunk<CGameCtnBlockSkin.Chunk03059002>();
                        skin.CreateChunk<CGameCtnBlockSkin.Chunk03059003>();
                    }

                    var freeBlock = map.PlaceFreeBlock(block.Name,
                        (referenceBlock.Coord + (0, 1, 0)) * (32, 8, 32) + offsetPos,
                        (-radians, 0, 0) - offsetRot, skin);
                    if (skin != null)
                        freeBlock.Author = "Nadeo";
                }

                if (referenceBlock.IsGround)
                {
                    if(conversion.Ground != null)
                        ProcessConversion(referenceBlock, conversion.Ground);

                    var blockModelExists = BlockInfoManager.BlockModels.TryGetValue(referenceBlock.Name, out BlockModel blockModel);

                    if (conversion.DirtGround != null && temporary.DirtCoords.Exists(x =>
                    {
                        if(blockModelExists)
                        {
                            if(blockModel.Ground.Length > 1)
                            {
                                foreach(var unit in blockModel.Ground)
                                {
                                    if (x.XZ == referenceBlock.Coord.XZ + ((Int3)unit.Coord).XZ)
                                        return true;
                                }
                            }
                        }
                        return x.XZ == referenceBlock.Coord.XZ;
                    }))
                        ProcessConversion(referenceBlock, conversion.DirtGround);
                    else if (conversion.FabricGround != null && blocks.Exists(x => x.Coord.XZ == referenceBlock.Coord.XZ && x.Name == "StadiumFabricCross1x1"))
                        ProcessConversion(referenceBlock, conversion.FabricGround);
                    else if (conversion.DirtHill != null && temporary.DirtHillCoords.Exists(x => x.XZ == referenceBlock.Coord.XZ))
                        ProcessConversion(referenceBlock, conversion.DirtHill);
                    else if (conversion.GrreplacedGround != null)
                        ProcessConversion(referenceBlock, conversion.GrreplacedGround);
                }
                else if (conversion.Air != null)
                    ProcessConversion(referenceBlock, conversion.Air);
            }

            CGameCtnBlock ConvertBlock(CGameCtnBlock referenceBlock, Conversion conversion, ConversionBlock conversionBlock,
                Int3? newCoord = null)
            {
                var block = new CGameCtnBlock(conversionBlock.Name,
                    referenceBlock.Direction,
                    referenceBlock.Coord,
                    0);

                if (newCoord.HasValue)
                    block.Coord = newCoord.Value;
                else
                {
                    if (conversionBlock.OffsetCoord2 != null && version >= GameVersion.TM2)
                    {
                        if (conversionBlock.OffsetCoord2.Length >= 3)
                            block.Coord += (Int3)conversionBlock.OffsetCoord2;
                    }
                    else if (conversionBlock.OffsetCoord != null)
                        if (conversionBlock.OffsetCoord.Length >= 3)
                            block.Coord += (Int3)conversionBlock.OffsetCoord;
                }

                block.Coord += (0, conversionBlock.OffsetY, 0);

                if (conversion.OffsetDir != 0)
                    block.Direction = (Direction)(((int)block.Direction + conversion.OffsetDir) % 4);
                if (conversionBlock.OffsetDir != 0)
                    block.Direction = (Direction)(((int)block.Direction + conversionBlock.OffsetDir) % 4);

                var direction = (int)block.Direction;
                var radians = direction * (float)(Math.PI / 2);

                if (conversionBlock.Ghost.HasValue)
                    block.IsGhost = conversionBlock.Ghost.Value;

                if (conversionBlock.Variant.HasValue)
                    block.Variant = conversionBlock.Variant.Value;

                if (conversionBlock.Bit17.HasValue)
                    block.Bit17 = conversionBlock.Bit17.Value;

                if (conversionBlock.Bit21.HasValue)
                    block.Bit21 = conversionBlock.Bit21.Value;

                if(conversionBlock.Skinnable)
                {
                    if(referenceBlock.Skin != null)
                    {
                        var packDesc = referenceBlock.Skin.PackDesc;
                        var skinsFolder = "Skins\\";

                        SkinDefinition def = null;
                        if ((packDesc.LocatorUrl != null && !packDesc.LocatorUrl.IsFile)
                            || (packDesc.FilePath.Length >= skinsFolder.Length && skins.TryGetValue(packDesc.FilePath.Substring(skinsFolder.Length), out def)))
                        {
                            var skin = new CGameCtnBlockSkin();
                            skin.Text = "!4";
                            skin.CreateChunk<CGameCtnBlockSkin.Chunk03059002>();
                            skin.CreateChunk<CGameCtnBlockSkin.Chunk03059003>();

                            if (packDesc.LocatorUrl != null)
                            {
                                if (!skinLocatorTasks.ContainsKey(packDesc.LocatorUrl))
                                {
                                    skinLocatorTasks.Add(packDesc.LocatorUrl, Task.Run(() =>
                                    {
                                        var request = WebRequest.Create(packDesc.LocatorUrl);
                                        request.Method = "HEAD";

                                        try
                                        {
                                            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                                            {
                                                return response.StatusCode == HttpStatusCode.OK;
                                            }
                                        }
                                        catch
                                        {
                                            return false;
                                        }
                                    }));
                                }

                                skin.PackDesc.FilePath = $"Skins\\Any\\{Path.GetFileName(packDesc.LocatorUrl.LocalPath)}";
                                skin.PackDesc.LocatorUrl = packDesc.LocatorUrl;

                                skinsWithLocator.Add(skin);
                            }
                            else
                            {
                                if (def.Primary != null) skin.PackDesc.FilePath = $"Skins\\{def.Primary}";
                                if (def.Secondary != null) skin.SecondaryPackDesc.FilePath = $"Skins\\{def.Secondary}";
                            }

                            block.Skin = skin;
                            block.Author = "Nadeo";
                        }
                    }
                }

                if (referenceBlock.WaypointSpecialProperty != null)
                    block.WaypointSpecialProperty = referenceBlock.WaypointSpecialProperty;

                if (version <= GameVersion.TMUF)
                {
                    if (referenceBlock.Name.Contains("Checkpoint"))
                    {
                        var waypoint = new CGameWaypointSpecialProperty();
                        waypoint.CreateChunk<CGameWaypointSpecialProperty.Chunk2E009000>();
                        block.WaypointSpecialProperty = waypoint;
                    }
                }

                block.IsGround = false;

                if (conversionBlock.Flags.HasValue)
                    block.Flags = conversionBlock.Flags.Value;

                map.Blocks.Add(block);

                return block;
            }

            var sortedLog = log.ToList();
            sortedLog.Sort();

            if (skinsWithLocator.Count > 0)
            {
                var finished = new List<Uri>();

                while (finished.Count < skinLocatorTasks.Count)
                {
                    foreach (var skin in skinsWithLocator)
                    {
                        if (!finished.Contains(skin.PackDesc.LocatorUrl))
                        {
                            if (skinLocatorTasks.TryGetValue(skin.PackDesc.LocatorUrl, out Task<bool> available))
                            {
                                if (available.IsCompleted)
                                {
                                    if (available.Result)
                                    {
                                        Log.Write($"HEAD request succeeded with {skin.PackDesc.LocatorUrl}");
                                    }
                                    else
                                    {
                                        Log.Write($"HEAD requests failed with {skin.PackDesc.LocatorUrl}");

                                        skin.PackDesc.FilePath = "";
                                        skin.PackDesc.LocatorUrl = null;
                                    }

                                    finished.Add(skin.PackDesc.LocatorUrl);
                                }
                            }
                        }

                        System.Threading.Thread.Sleep(1);
                    }
                }
            }
        }

See More Examples