System.Collections.Generic.Dictionary.ContainsKey(double)

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

38 Examples 7

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

public void AddSlice(RegionOfInterestSlice slice, double coordinate)
        {
            if (!sliceDictionary.ContainsKey(coordinate))
            {
                // Add the ROIs to arrays but ensure they are sorted by z coord
                int insertIndex = BinaryMath.BinarySearchClosest(coordinate, roiZCoordinates);
                if (insertIndex < 0)
                    insertIndex = ~insertIndex;
                RegionOfInterestSlices.Insert(insertIndex, slice);
                roiZCoordinates.Insert(insertIndex, coordinate);
                sliceDictionary.Add(coordinate, slice);
            }
        }

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

public RegionOfInterestSlice GetSlice(double z)
        {
            if (sliceDictionary.ContainsKey(z))
                return sliceDictionary[z];
            else
                return null;
        }

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

private BinaryMask GetInterpolatedMask(double z)
        {
            if (sliceDictionary.ContainsKey(z))
                return sliceDictionary[z].BinaryMask;

            RegionOfInterestSlice slice1 = GetClosestSlicePrevious(z);
            RegionOfInterestSlice slice2 = GetClosestSliceNext(z);
            double z1 = slice1?.ZCoord ?? 0, z2 = slice2?.ZCoord ?? 0;
            BinaryMask mask1 = slice1?.BinaryMask;
            BinaryMask mask2 = slice2?.BinaryMask;
            if (mask1 == null)
            {
                mask1 = new BinaryMask(XRange, YRange);
                z1 = slice2 != null ? slice2.ZCoord - 2 : z - 2;
            }
            if (mask2 == null)
            {
                mask2 = new BinaryMask(XRange, YRange);
                z2 = slice2 != null ? slice2.ZCoord + 2 : z + 2;
            }
            double frac = (z - z1) / (z2 - z1);
            BinaryMask interped = mask1.InterpolateWith(mask2, frac);

            return interped;
        }

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

public RegionOfInterestSlice GetClosestSlicePrevious(double z)
        {
            if (!ZRange.Contains(z))
                return null;

            if (sliceDictionary.ContainsKey(z))
                return sliceDictionary[z];

            int index = BinaryMath.BinarySearchClosest(z, roiZCoordinates);
            if (!(index - 1 > RegionOfInterestSlices.Count - 1) && !(index - 1 < 0))
                return RegionOfInterestSlices[index - 1];

            if (Math.Abs(RegionOfInterestSlices[0].ZCoord - z) <= 1)
                return RegionOfInterestSlices[0];
            if (Math.Abs(RegionOfInterestSlices[RegionOfInterestSlices.Count - 1].ZCoord - z) <= 1)
                return RegionOfInterestSlices[RegionOfInterestSlices.Count - 1];

            return null;
        }

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

public RegionOfInterestSlice GetClosestSlice(double z)
        {
            if (!ZRange.Contains(z))
                return null;

            if (sliceDictionary.ContainsKey(z))
                return sliceDictionary[z];

            int index = BinaryMath.BinarySearchClosest(z, roiZCoordinates);
            RegionOfInterestSlice slice1 = null;
            RegionOfInterestSlice slice2 = null;

            if (!(index - 1 > RegionOfInterestSlices.Count - 1) && !(index - 1 < 0))
                slice1 = RegionOfInterestSlices[index - 1];
            if (!(index > RegionOfInterestSlices.Count - 1) && !(index < 0))
                slice2 = RegionOfInterestSlices[index];

            if (slice2 == null)
                return slice1;
            if (slice1 == null)
                return slice2;

            if (Math.Abs((slice1.ZCoord - z)) <= Math.Abs((slice2.ZCoord - z)))
                return slice1;
            else
                return slice2;
        }

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

public RegionOfInterestSlice GetClosestSliceNext(double z)
        {
            if (!ZRange.Contains(z))
                return null;

            if (sliceDictionary.ContainsKey(z))
                return sliceDictionary[z];

            int index = BinaryMath.BinarySearchClosest(z, roiZCoordinates);
            if (!(index > RegionOfInterestSlices.Count - 1) && !(index < 0))
                return RegionOfInterestSlices[index];

            return null;
        }

19 Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath

public RegionOfInterestSlice GetClosestSlicePrevious(double z)
        {
            if (!ZRange.Contains(z))
                return null;

            if (sliceDictionary.ContainsKey(z))
                return sliceDictionary[z];

            int index = BinaryMath.BinarySearchClosest(z, roiZCoordinates);
            if (!(index - 1 > RegionOfInterestSlices.Count - 1) && !(index - 1 < 0))
                return RegionOfInterestSlices[index - 1];

            return null;
        }

19 Source : Routers.Orthogonal.cs
with MIT License
from Blazor-Diagrams

private static IEnumerable<Point> ReducePoints(List<Point> points)
        {
            var map = new Dictionary<double, List<double>>();
            foreach (var p in points)
            {
                (var x, var y) = p;
                if (!map.ContainsKey(y)) map.Add(y, new List<double>());
                var arr = map[y];

                if (!arr.Contains(x)) arr.Add(x);
            }

            foreach (var (y, xs) in map)
            {
                foreach (var x in xs)
                {
                    yield return new Point(x, y);
                }
            }
        }

19 Source : Routers.Orthogonal.cs
with MIT License
from Blazor-Diagrams

public void Set(double row, double column, Rectangle rectangle)
        {
            Rows = Math.Max(Rows, row + 1);
            Columns = Math.Max(Columns, column + 1);

            if (!Data.ContainsKey(row))
            {
                Data.Add(row, new Dictionary<double, Rectangle>());
            }

            Data[row].Add(column, rectangle);
        }

19 Source : Routers.Orthogonal.cs
with MIT License
from Blazor-Diagrams

public Rectangle? Get(double row, double column)
        {
            if (!Data.ContainsKey(row))
                return null;

            if (!Data[row].ContainsKey(column))
                return null;

            return Data[row][column];
        }

19 Source : MyStatisticsMath.cs
with GNU General Public License v3.0
from DeepHydro

public static double Majority(params double[] x)
        {
            Dictionary<double, double> d = new Dictionary<double, double>();
            int majority = x.Length / 2;

            //Stores the number of occcurences of each item in the preplaceded array in a dictionary
            foreach (int i in x)
                if (d.ContainsKey(i))
                {
                    d[i]++;
                    //Checks if element just added is the majority element
                    if (d[i] > majority)
                        return i;
                }
                else
                    d.Add(i, 1);

            return x[0];
        }

19 Source : Trainer.cs
with MIT License
from Dentrax

private void RemoveXYFromResults(int X, int Y) {
            double lowDestroy = 0.0d;
            int lowX = -1;
            int lowY = -1;
            for (int i = 0; i < this.m_results.GetLength(0); i++) {
                for (int j = 0; j < this.m_results.GetLength(1); j++) {
                    //Console.WriteLine($"X:{X} Y:{Y} i:{i} j:{j} Distance:{this.m_results[i, j]?.Distance}");
                    if(j == X - 1) {
                        TrainingResult current = this.m_results[i, j];
                        if (current != null) {
                            double val = this.m_results[i, j].Distance;
                            if(lowDestroy == 0) {
                                lowDestroy = val;
                                lowX = current.X;
                                lowY = current.Y;
                            } else if (lowDestroy > val) {
                                lowDestroy = val;
                                lowX = current.X;
                                lowY = current.Y;
                            }
                            this.m_results[i, j] = null;
                        }
                    }
                }
            }

            if (lowX >= lowY) {
                this.m_data.Move(lowX, lowY);
            } else {
                this.m_data.Move(lowY, lowX);
            }

            if (!m_clusters.ContainsKey(lowDestroy)) {
                this.m_clusters.Add(lowDestroy, new List<int>() { lowX, lowY });
            } else {
                this.m_clusters[lowDestroy].AddRange(new int[] { lowX, lowY });
            }

        }

19 Source : Trainer.cs
with MIT License
from Dentrax

private void RemoveXYFromResults(int X, int Y) {
            double lowDestroy = 0.0d;
            int lowX = -1;
            int lowY = -1;
            List<TrainingResult> shouldNullList = new List<TrainingResult>();
            for (int i = 0; i < this.m_results.GetLength(0); i++) {
                for (int j = 0; j < this.m_results.GetLength(1); j++) {
                    //Console.WriteLine($"X:{X} Y:{Y} i:{i} j:{j} Distance:{this.m_results[i, j]?.Distance}");
                    if(j == X - 1) {
                        TrainingResult current = this.m_results[i, j];
                        if (current != null) {
                            double val = this.m_results[i, j].Distance;
                            if(lowDestroy == 0) {
                                lowDestroy = val;
                                lowX = current.X;
                                lowY = current.Y;
                            } else if (lowDestroy > val) {
                                lowDestroy = val;
                                lowX = current.X;
                                lowY = current.Y;
                            }
                            shouldNullList.Add(this.m_results[i, j]);
                            this.m_results[i, j] = null;
                        }
                    }
                }
            }

            if (lowX >= lowY) {
                this.m_data.Move(lowX, lowY);
            } else {
                this.m_data.Move(lowY, lowX);
            }

            if (!m_clusters.ContainsKey(lowDestroy)) {
                this.m_clusters.Add(lowDestroy, new List<int>() { lowX, lowY });
            } else {
                this.m_clusters[lowDestroy].AddRange(new int[] { lowX, lowY });
            }

        }

19 Source : LayersDetector.cs
with MIT License
from gradientspace

public void Compute() 
		{
			LayersCounts = new Dictionary<double, int>();

			Action<IToolpath> processPathF = (path) => {
				if ( path.HasFinitePositions ) {
					foreach (Vector3d v in path.AllPositionsItr())
						acreplacedulate(v);
				}
			};
			Action<IToolpathSet> processPathsF = null;
			processPathsF = (paths) => {
				foreach (IToolpath path in paths) {
					if (path is IToolpathSet)
						processPathsF(path as IToolpathSet);
					else
						processPathF(path);
				}
			};

			processPathsF(Paths);

			List<double> erase = new List<double>();
			foreach ( var v in LayersCounts ) {
                // [RMS] nothing should be at Z=0
                if ( v.Key == 0 ) {
                    erase.Add(v.Key);
                    continue;
                }
				if (v.Value < MinLayerCount)
					erase.Add(v.Key);
			}
			foreach (var e in erase)
				LayersCounts.Remove(e);

			LayerZ = new List<double>(LayersCounts.Keys);
			LayerZ.Sort();

			// estimate layer height
			Dictionary<double, int> LayerHeights = new Dictionary<double, int>();
			for (int i = 0; i < LayerZ.Count - 1; ++i ) {
				double dz = Math.Round(LayerZ[i + 1] - LayerZ[i], 3);
				if (LayerHeights.ContainsKey(dz) == false)
					LayerHeights[dz] = 0;
				LayerHeights[dz] = LayerHeights[dz] + 1;
			}
			double best_height = 0; int max_count = 0;
			foreach ( var pair in LayerHeights ) {
				if ( pair.Value > max_count ) {
					max_count = pair.Value;
					best_height = pair.Key;
				}
			}
			EstimatedLayerHeight = best_height;

		}

19 Source : FontsHandler.cs
with MIT License
from huali20040714

private RFont TryGetFont(string family, double size, RFontStyle style)
        {
            RFont font = null;
            if (_fontsCache.ContainsKey(family))
            {
                var a = _fontsCache[family];
                if (a.ContainsKey(size))
                {
                    var b = a[size];
                    if (b.ContainsKey(style))
                    {
                        font = b[style];
                    }
                }
                else
                {
                    _fontsCache[family][size] = new Dictionary<RFontStyle, RFont>();
                }
            }
            else
            {
                _fontsCache[family] = new Dictionary<double, Dictionary<RFontStyle, RFont>>();
                _fontsCache[family][size] = new Dictionary<RFontStyle, RFont>();
            }
            return font;
        }

19 Source : Boomerangs.cs
with MIT License
from jackzhenguo

public static int NumberOfBoomerangs(int[,] points)
        {
            Dictionary<double, int> dict = new Dictionary<double, int>();
            int len = points.GetUpperBound(0);
            int rtnCnt = 0;
            for (int i = 0; i <= len; i++)
            {
                //3点变2点
                for (int j = 0; j <= len; j++)
                {
                    if (i == j) continue;
                    double d = distance(points[i, 0], points[j, 0], points[i, 1], points[j, 1]);
                    if (dict.ContainsKey(d))
                        dict[d]++;
                    else dict.Add(d, 1);
                }
                foreach (var item in dict)
                {
                    if (item.Value > 1)
                    {
                        //如果找到了value个,因为有顺序,所以排序
                        rtnCnt += item.Value * (item.Value - 1);
                    }
                }
                dict.Clear();
            }
            return rtnCnt;
        }

19 Source : ClassificationForestModel.cs
with Apache License 2.0
from jameschch

public ProbabilityPrediction PredictProbability(double[] observation)
        {
            var probabilities = new Dictionary<double, double>();
            var modelsProbability = Trees.Select(m => m.PredictProbability(observation).Probabilities)
                .ToArray();

            foreach (var model in modelsProbability)
            {
                foreach (var probability in model)
                {
                    if(probabilities.ContainsKey(probability.Key))
                    {
                        probabilities[probability.Key] += probability.Value;
                    }
                    else
                    {
                        probabilities.Add(probability.Key, probability.Value);
                    }
                }
            }

            var keys = probabilities.Keys.ToList();
            foreach (var target in keys)
            {
                probabilities[target] /= Trees.Length;
            }

            var prediction = probabilities.OrderByDescending(p => p.Value)
                .First().Key;

            return new ProbabilityPrediction(prediction, probabilities);
        }

19 Source : TreeLayoutTests.cs
with MIT License
from KeRNeLith

private static void CheckTreeLayout<TVertex, TEdge>(
            [NotNull] SimpleTreeLayoutAlgorithm<TVertex, TEdge, IBidirectionalGraph<TVertex, TEdge>> algorithm,
            [NotNull] IDictionary<TVertex, Size> verticesSizes)
            where TVertex : clreplaced
            where TEdge : IEdge<TVertex>
        {
            var slices = new Dictionary<double, HashSet<double>>();

            TVertex[] vertices = algorithm.VisitedGraph.Vertices.ToArray();
            for (int i = 0; i < vertices.Length - 1; ++i)
            {
                TVertex vertexI = vertices[i];
                Point posI = algorithm.VerticesPositions[vertexI];
                for (int j = i + 1; j < vertices.Length; ++j)
                {
                    TVertex vertexJ = vertices[j];
                    Point posJ = algorithm.VerticesPositions[vertexJ];
                    if (algorithm.Parameters.Direction.IsHorizontal())
                    {
                        CheckSpacingAndAddSlice(posI.Y, verticesSizes[vertexI].Height / 2);
                        CheckSpacingAndAddSlice(posJ.Y, verticesSizes[vertexJ].Height / 2);

                        CheckSpacingAndAddLayerToSlice(posI.Y, posI.X, verticesSizes[vertexI].Width / 2);
                        CheckSpacingAndAddLayerToSlice(posJ.Y, posJ.X, verticesSizes[vertexJ].Width / 2);
                    }
                    else if (algorithm.Parameters.Direction.IsVertical())
                    {
                        CheckSpacingAndAddSlice(posI.X, verticesSizes[vertexI].Width / 2);
                        CheckSpacingAndAddSlice(posJ.X, verticesSizes[vertexJ].Width / 2);

                        CheckSpacingAndAddLayerToSlice(posI.X, posI.Y, verticesSizes[vertexI].Height / 2);
                        CheckSpacingAndAddLayerToSlice(posJ.X, posJ.Y, verticesSizes[vertexJ].Height / 2);
                    }
                    else
                    {
                        throw new NotSupportedException("Not supported layout direction.");
                    }
                }
            }

            #region Local functions

            // ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local
            void CheckSpacingAndAddSlice(double slicePos, double size)
            {
                if (!slices.ContainsKey(slicePos))
                {
                    replacedert.IsTrue(slices.All(pair => Math.Abs(slicePos - pair.Key) + size >= algorithm.Parameters.VertexGap));
                    slices.Add(slicePos, new HashSet<double>());
                }
            }

            void CheckSpacingAndAddLayerToSlice(double slicePos, double layerPos, double size)
            {
                replacedert.IsTrue(slices.TryGetValue(slicePos, out HashSet<double> layerPositions));
                replacedert.IsTrue(layerPositions.All(lPos => Math.Abs(layerPos - lPos) + size >= algorithm.Parameters.LayerGap));
            }
            // ReSharper restore ParameterOnlyUsedForPreconditionCheck.Local

            #endregion
        }

19 Source : UniformOneDimensionalSolver.cs
with GNU General Public License v2.0
from league1991

void RegisterBoundVar(double bound){
            if (!boundsToInt.ContainsKey(bound)){
                int varIndex=varList.Count + boundsToInt.Count;
                boundsToInt[bound] = varIndex;
                solverShell.AddFixedVariable(varIndex, bound);
            }
        }

19 Source : LineRenderer.cs
with MIT License
from LumpBloom7

private void addHitObjectToEntry(double entryTime, SentakkiLanedHitObject hitObject)
        {
            // Create new line entry for this entryTime if none exists
            if (!lineEntries.ContainsKey(entryTime))
            {
                var newEntry = new LineLifetimeEntry(animationDuration, drawableRuleset, entryTime);
                lineEntries[entryTime] = newEntry;
                lifetimeManager.AddEntry(newEntry);

                // We want to listen in on line changes in case we need to swap out colours/drawables
                newEntry.OnLineUpdated += onEntryUpdated;
            }
            lineEntries[entryTime].Add(hitObject);
        }

19 Source : OrderBookStatsComputer.cs
with Apache License 2.0
from Marfusios

private void RemoveBook(Book book)
        {
            var id = book.Price;
            if (_bids.ContainsKey(id))
                _bids.Remove(id);
            if (_asks.ContainsKey(id))
                _asks.Remove(id);
        }

19 Source : ColorManager.cs
with GNU General Public License v3.0
from merschformann

public static Brush GenerateHueBrush(double hue)
        {
            hue = Math.Max(hue, 0);
            hue = Math.Min(hue, 360);
            if (!_recycledBrushes.ContainsKey(hue))
            {
                double r, g, b;
                ConvertHSVtoRGB(hue, 0.8, 0.97, out r, out g, out b);
                byte R = (byte)(r * 256);
                byte G = (byte)(g * 256);
                byte B = (byte)(b * 256);
                _recycledBrushes[hue] = new SolidColorBrush(Color.FromRgb(R, G, B));
            }
            return _recycledBrushes[hue];
        }

19 Source : ChartCached.cs
with MIT License
from monitor1394

public static string NumberToStr(double value, string formatter)
        {
            if (!s_NumberToStr.ContainsKey(value))
            {
                s_NumberToStr[value] = new Dictionary<string, string>();
            }
            if (!s_NumberToStr[value].ContainsKey(formatter))
            {
                if (string.IsNullOrEmpty(formatter))
                {
                    if (value - (int)value == 0)
                        s_NumberToStr[value][formatter] = ((int)value).ToString();
                    else
                        s_NumberToStr[value][formatter] = value.ToString();
                }
                else if (formatter.StartsWith(NUMERIC_FORMATTER_D)
                    || formatter.StartsWith(NUMERIC_FORMATTER_d)
                    || formatter.StartsWith(NUMERIC_FORMATTER_X)
                    || formatter.StartsWith(NUMERIC_FORMATTER_x)
                    )
                {
                    s_NumberToStr[value][formatter] = ((int)value).ToString(formatter, ci);
                }
                else
                {
                    s_NumberToStr[value][formatter] = value.ToString(formatter, ci);
                }
            }
            return s_NumberToStr[value][formatter];
        }

19 Source : TestImageDataLayer.cs
with Apache License 2.0
from MyCaffe

public void TestShuffle()
        {
            LayerParameter p = new LayerParameter(LayerParameter.LayerType.IMAGE_DATA);
            int nBatchSize = 5;
            p.data_param.batch_size = (uint)nBatchSize;
            p.data_param.source = m_strFileName;
            p.image_data_param.shuffle = true;

            Layer<T> layer = Layer<T>.Create(m_cuda, m_log, p, m_parent.CancelEvent);

            try
            {
                layer.Setup(BottomVec, TopVec);

                m_log.CHECK_EQ(Top.num, nBatchSize, "The top num should = the batch size of 5.");
                m_log.CHECK_EQ(Top.channels, 3, "The top channels should = 3.");
                m_log.CHECK_EQ(Top.width, 480, "The top width should = 480");
                m_log.CHECK_EQ(Top.height, 360, "The top height should = 360");
                m_log.CHECK_EQ(TopLabel.num, nBatchSize, "The top num should = the batch size of 5.");
                m_log.CHECK_EQ(TopLabel.channels, 1, "The top channels should = 1.");
                m_log.CHECK_EQ(TopLabel.width, 1, "The top width should = 1");
                m_log.CHECK_EQ(TopLabel.height, 1, "The top height should = 1");

                // Go through the data twice.
                for (int iter = 0; iter < 2; iter++)
                {
                    layer.Forward(BottomVec, TopVec);
                    Dictionary<double, int> rgValueToIndices = new Dictionary<double, int>();
                    int nNumInOrder = 0;
                    double[] rgLabel = convert(TopLabel.mutable_cpu_data);

                    for (int i = 0; i < 5; i++)
                    {
                        double dfLabel = rgLabel[i];
                        //Check that the value has not been seen already (no duplicates);
                        m_log.CHECK(!rgValueToIndices.ContainsKey(dfLabel), "Duplicate found!");
                        rgValueToIndices.Add(dfLabel, i);
                        nNumInOrder += (dfLabel == (double)i) ? 1 : 0;
                    }

                    m_log.CHECK_EQ(5, rgValueToIndices.Count, "The value to indices count is incorrect!");
                    m_log.CHECK_GT(5, nNumInOrder, "The number in order is incorrect.");
                }
            }
            catch (Exception excpt)
            {
                throw excpt;
            }
            finally
            {
                layer.Dispose();
            }
        }

19 Source : Input.cs
with MIT License
from nommiin

public static void Initalize(Game _game) {
            InputDown = new List<Key>();
            InputDownPrevious = new List<Key>();
            _game.Window.KeyUp += OnKeyUp;
            _game.Window.KeyDown += OnKeyDown;
            //code to allow for key remapping, but fill default values
            Enum.GetValues(typeof(Key)).Cast<Key>().ToList().ForEach(_key =>
            {
                if (!InputMapping.ContainsKey((double)_key))InputMapping.Add((double) _key, _key);
            });
        }

19 Source : RankedCooccurrenceKwicBlock.cs
with GNU Affero General Public License v3.0
from notesjor

protected override void CalculateCall(AbstractCorpusAdapter corpus, AbstractLayerAdapter layer, Guid dsel, int[][] doc)
    {
      var queries = new List<string> { LayerQuery };
      queries.AddRange(Cooccurrences.Keys);

      var block = Selection.CreateBlock<TextLiveSearchBlock>();
      block.LayerQueries = new AbstractFilterQuery[]
      {
        new FilterQuerySingleLayerFirstAndAnyOtherMatch
        {
          LayerDisplayname = LayerDisplayname,
          LayerQueries = queries
        }
      };
      block.Calculate();

      var internalLock = new object();

      Parallel.ForEach(block.SearchResults, c =>
      {
        Parallel.ForEach(c.Value, d =>
        {
          foreach (var s in d.Value)
          {
            var sent = block.ResultSelection
                            .GetReadableDoreplacedent(d.Key, LayerDisplayname)
                            .ReduceToSentence(s.Key)
                            .ToArray();

            var value = sent.Where(x => Cooccurrences.ContainsKey(x)).Sum(x => Cooccurrences[x]);
            lock (internalLock)
            {
              if (RankedResults.ContainsKey(value))
                RankedResults[value].Add(new Tuple<Guid, Guid, int, string[]>(c.Key, d.Key, s.Key, sent));
              else
                RankedResults.Add(value, new List<Tuple<Guid, Guid, int, string[]>>
                {
                    new Tuple<Guid, Guid, int, string[]>(c.Key, d.Key, s.Key, sent)
                });
            }
          }
        });
      });
    }

19 Source : ExportForm.cs
with Apache License 2.0
from ProteoWizard

private object[] createDecoyPeaks(string peptideName, string decoyPeptideName, Dictionary<double, FragmentPeakInfo> annotatedList , List<double> mzValues, List<double> intensities, Dictionary<int,double> modDict, int charge)
        {
            var splitDecoy = decoyPeptideName.Select(letter => letter.ToString()).ToList();
            var originalPeaks = new Dictionary<double, double>();
            for (var x = 0; x < mzValues.Count; x++)
                originalPeaks.Add(mzValues[x], intensities[x]);
            var DecoyList = CreateFragmentMreplacedReference(splitDecoy, modDict);
            var newPeaks = new Dictionary<double, double>();
            var peakLocations = new List<double>();
            
            var newAnnotations = new Dictionary<double, string>();

            foreach (var peak in annotatedList)
            {
                var mzValue = peak.Value.fragmentID == "?"
                                  ? peak.Key
                                  : Math.Round((DecoyList[peak.Value.fragmentID] + peak.Value.relativePosition) / peak.Value.fragmentCharge, 4);
                var intensity = originalPeaks[peak.Key];
                if (newPeaks.ContainsKey(mzValue))
                    newPeaks[mzValue] += intensity;
                else
                    newPeaks.Add(mzValue, intensity);
                peakLocations.Add(mzValue);
                if (!newAnnotations.ContainsKey(mzValue))
                {
                    var tempstring = peak.Value.fragmentID;
                    var closestModValue = Math.Round(peak.Value.relativePosition);
                    if (closestModValue < 0)
                        tempstring += closestModValue.ToString();
                    else if (closestModValue > 0)
                        tempstring += "+" + closestModValue.ToString();
                    if (peak.Value.fragmentCharge > 1)
                        tempstring += "^" + peak.Value.fragmentCharge;
                    newAnnotations.Add(mzValue, tempstring);
                }
            }

            for (var x = 1; x < peakLocations.Count - 1; x++)
            {
                if (newPeaks[peakLocations[x]] <= 0)
                    continue;
                var closeBehind = false;
                var closeAhead = false;
                if (newPeaks[peakLocations[x - 1]] > 0 &&
                    Math.Abs(peakLocations[x] - peakLocations[x - 1]) < _libraryExportSettings.fragmentMzTolerance)
                    closeBehind = true;
                if (newPeaks[peakLocations[x + 1]] > 0 &&
                    Math.Abs(peakLocations[x] - peakLocations[x + 1]) < _libraryExportSettings.fragmentMzTolerance)
                    closeAhead = true;
                if (closeBehind)
                {
                    newPeaks[peakLocations[x]] += newPeaks[peakLocations[x - 1]];
                    newPeaks[peakLocations[x - 1]] = 0;
                }
                if (closeAhead)
                {
                    newPeaks[peakLocations[x]] += newPeaks[peakLocations[x + 1]];
                    newPeaks[peakLocations[x + 1]] = 0;
                }
            }


            var newPeakMz = new List<double>();
            var newPeakIntensity = new List<double>();
            var possibleAnnotations = new List<string>();
            foreach (var kvp in newPeaks.OrderBy(x => x.Key))
            {
                if (kvp.Value <= 0)
                    continue;
                newPeakMz.Add(kvp.Key);
                newPeakIntensity.Add(kvp.Value);
                possibleAnnotations.Add(newAnnotations[kvp.Key]);
            }

            return new object[] { newPeakMz, newPeakIntensity, possibleAnnotations };
        }

19 Source : ExportForm.cs
with Apache License 2.0
from ProteoWizard

private Dictionary<double, FragmentPeakInfo> AnnotatePeaks(List<double> originalMZs, Dictionary<string, double> fragmentList, int charge)
        {
            Dictionary<double, FragmentPeakInfo> availableAnnotations = CreatePossibleAnnotations(fragmentList, charge);
            var annotationList = availableAnnotations.Select(item => item.Key).OrderBy(x => x).ToList();
            var possibleExplanations = new Dictionary<double, FragmentPeakInfo>();
            foreach (var peak in originalMZs)
            {
                var peak1 = peak;
                var closestMatch = 0.0;
                var peakExplanationList =
                    annotationList.Where(x => x < peak1 + _libraryExportSettings.fragmentMzTolerance && x > peak1 - _libraryExportSettings.fragmentMzTolerance).ToList();
                if (peakExplanationList.Any())
                {
                    var explanationList = availableAnnotations.Where(x => peakExplanationList.Contains(x.Key)).ToList();
                    if (explanationList.Count < 0)
                        continue;
                    var minComplexity = peakExplanationList.Min(x => availableAnnotations[x].complexity);
                    peakExplanationList =
                        peakExplanationList.Where(x => availableAnnotations[x].complexity == minComplexity).ToList();
                    if (peakExplanationList.Any())
                    {
                        var closestDistance = double.MaxValue;
                        foreach (var match in peakExplanationList)
                        {
                            var distance = Math.Abs(peak - match);
                            if (distance < closestDistance)
                            {
                                closestDistance = distance;
                                closestMatch = match;
                            }
                        }
                    }
                }

                if (peakExplanationList.Any() && availableAnnotations.ContainsKey(closestMatch))
                {
                    possibleExplanations.Add(peak, availableAnnotations[closestMatch]);
                    availableAnnotations.Remove(closestMatch);
                    annotationList.Remove(closestMatch);
                }
                else
                {
                    possibleExplanations.Add(peak,
                                         new FragmentPeakInfo
                                         {
                                             fragmentID = "?",
                                             originalMZvalue = peak,
                                             relativePosition = 0,
                                             complexity = int.MaxValue
                                         }
                    );
                }

            }

            return possibleExplanations;
        }

19 Source : ExportForm.cs
with Apache License 2.0
from ProteoWizard

private Dictionary<double, FragmentPeakInfo> CreatePossibleAnnotations(Dictionary<string, double> fragmentList, int charge)
        {
            var possibleAnnotations = new Dictionary<double, FragmentPeakInfo>();
            var allList = new List<double> { -1, 0, 1, 17, 18, 34, 35, 36 };
            var bList = new List<double> { 28, 45, 46, 56 };
            var singleComplexity = new List<double> { -1, 1, 17, 18, 28 };
            foreach (var fragment in fragmentList)
            {
                for (var currentCharge = 1; currentCharge <= charge; currentCharge++)
                {
                    foreach (var item in allList)
                    {
                        var itemComplexity = singleComplexity.Contains(item) ? 1 : 2;
                        if (item == 0)
                            itemComplexity = 0;
                        itemComplexity += (currentCharge > 1 ? 1 : 0);
                        if (!possibleAnnotations.ContainsKey((fragment.Value - item) / currentCharge))
                            possibleAnnotations.Add((fragment.Value - item) / currentCharge,
                                                    new FragmentPeakInfo
                                                    {
                                                        complexity = itemComplexity,
                                                        fragmentID = fragment.Key,
                                                        originalMZvalue = fragment.Value,
                                                        relativePosition = -item,
                                                        fragmentCharge = currentCharge
                                                    });
                        else if (possibleAnnotations[(fragment.Value - item) / currentCharge].complexity > itemComplexity)
                            possibleAnnotations[(fragment.Value - item) / currentCharge] =
                                new FragmentPeakInfo
                                {
                                    complexity = itemComplexity,
                                    fragmentID = fragment.Key,
                                    originalMZvalue = fragment.Value,
                                    relativePosition = -item,
                                    fragmentCharge = currentCharge
                                };
                    }
                    if (fragment.Key.StartsWith("b"))
                    {
                        foreach (var item in bList)
                        {
                            var itemComplexity = singleComplexity.Contains(item) ? 1 : 2;
                            if (item == 0)
                                itemComplexity = 0;
                            itemComplexity += (currentCharge > 1 ? 1 : 0);
                            if (!possibleAnnotations.ContainsKey((fragment.Value - item) / currentCharge))
                                possibleAnnotations.Add((fragment.Value - item) / currentCharge,
                                                        new FragmentPeakInfo
                                                        {
                                                            complexity = itemComplexity,
                                                            fragmentID = fragment.Key,
                                                            originalMZvalue = fragment.Value,
                                                            relativePosition = -item,
                                                            fragmentCharge = currentCharge
                                                        });
                            else if (possibleAnnotations[(fragment.Value - item) / currentCharge].complexity >
                                     itemComplexity)
                                possibleAnnotations[(fragment.Value - item) / currentCharge] =
                                    new FragmentPeakInfo
                                    {
                                        complexity = itemComplexity,
                                        fragmentID = fragment.Key,
                                        originalMZvalue = fragment.Value,
                                        relativePosition = -item,
                                        fragmentCharge = currentCharge
                                    };
                        }
                    }
                }
            }
            return possibleAnnotations;
        }

19 Source : Program.cs
with Apache License 2.0
from ProteoWizard

private void WriteToIDATemplate(MreplacedSpecMethod method, MethodTransitions transitions)
        {
            object idaServer;
            ((IMreplacedSpecMethod2)method).GetDataDependSvr(out idaServer);
            ClearIncludeList(idaServer);

            double minTOFMreplaced = 0;
            double maxTOFMreplaced = 0;
            ((IDDEMethodObj)idaServer).getUsersSurvTOFMreplacedes(ref minTOFMreplaced, ref maxTOFMreplaced);

            var addedEntries = new List<string>();
            var replacedignedCandidateMreplacedToRT = new Dictionary<double, double>();
            var entryKeyToreplacedignedCandidateMreplaced = new Dictionary<string, double>();
            foreach (var transition in transitions.Transitions)
            {
                double retentionTime = 0;

                // If the ScheduledMethod flag was set replacedume that the Dwell time column in the 
                // transition list file has retention time.
                if (ScheduledMethod)
                    retentionTime = transition.Dwell;

                string entryKey = transition.PrecursorMz + retentionTime.ToString(CultureInfo.InvariantCulture);
                if (addedEntries.Contains(entryKey)
                    || transition.PrecursorMz <= minTOFMreplaced
                    || transition.PrecursorMz >= maxTOFMreplaced)
                    continue;

                var precursorMz = Math.Round(transition.PrecursorMz, 3);
                while (replacedignedCandidateMreplacedToRT.ContainsKey(precursorMz))
                {
                    // replacedyst does not allow duplicate mreplacedes in inclusion list
                    precursorMz += 0.001;
                }
                ((IDDEMethodObj)idaServer).AddIonEntry(1, precursorMz, retentionTime);
                addedEntries.Add(entryKey);
                replacedignedCandidateMreplacedToRT.Add(precursorMz, retentionTime);
                entryKeyToreplacedignedCandidateMreplaced.Add(entryKey, precursorMz);
            }

            if (ScheduledMethod) // calculate experiment index which is used for exporting a quanreplacedaion method
            {
                ((IDDEMethodObj)idaServer).putExceedCountSwitch(2000000);
                ((IDDEMethodObj)idaServer).putIntensityThreshold(0);

                int windowInSec = RTWindowInSeconds.HasValue ? RTWindowInSeconds.Value : 60;
                ((IDDEMethodObj3)idaServer).putIncludeForSecs(windowInSec);
                int maxConcurrentCount = MaxConcurrentCount(replacedignedCandidateMreplacedToRT, windowInSec);
                ((IDDEMethodObj)idaServer).putSpectraSwitch(maxConcurrentCount);
                var period = (Period)method.GetPeriod(0);
                while (period.ExperimCount > 2)
                {
                    period.DeleteExperiment(period.ExperimCount -1);
                }
                var templateExperiment = (Experiment) period.GetExperiment(1);
                for (int newExperimentIdx = 1; newExperimentIdx < maxConcurrentCount; newExperimentIdx++)
                {
                    int pIdx;
                    var experiment = (IClone)period.CreateExperiment(out pIdx);
                    experiment.CopyDataFrom(templateExperiment);
                }

                // sort by mreplaced then by RT
                var mreplacedRtList = replacedignedCandidateMreplacedToRT.OrderBy(c => c.Value).ThenBy(c => c.Key).ToList();

                foreach (var transition in transitions.Transitions)
                {
                    double replacedignedCandidateMreplaced;
                    var entryKey = transition.PrecursorMz + transition.Dwell.ToString(CultureInfo.InvariantCulture);
                    if (!entryKeyToreplacedignedCandidateMreplaced.TryGetValue(entryKey, out replacedignedCandidateMreplaced)) 
                        continue;

                    var scheduledIndex = mreplacedRtList.FindIndex(m => Math.Abs(m.Key - replacedignedCandidateMreplaced) < 0.001);
                    transition.ExperimentIndex = IsPrecursorTypeTransition(transition)
                                                     ? 0
                                                     : (scheduledIndex%maxConcurrentCount) + 1;
                }
            }
        }

19 Source : Program.cs
with Apache License 2.0
from ProteoWizard

private void WriteToTargetedMSMSTemplate(MreplacedSpecMethod method, MethodTransitions transitions)
        {
            var period = (Period)method.GetPeriod(0);


            Experiment tofExperiment = null;
            Experiment prodIonExperiment; 
           
            switch (period.ExperimCount)
            {
                case 2:
                    tofExperiment = (Experiment) period.GetExperiment(0);
                    prodIonExperiment = (Experiment) period.GetExperiment(1);

                    // delete the product ion experiment. We will be adding one for each precursor ion in the transition list.
                    period.DeleteExperiment(1);

                    break;

                case 1:
                    prodIonExperiment = (Experiment)period.GetExperiment(0);

                    // delete the product ion experiment. We will be adding one for each precursor ion in the transition list.
                    period.DeleteExperiment(0);

                    break;

                default:
                    throw new IOException(string.Format("Expected 1 or 2 experiments in the template. Found {0} experiments.", period.ExperimCount));
            }
            

            int j;

            if (Ms1Scan)
            {
                // If the template does not already have a TOF MS scan add one now.
                if(tofExperiment == null)
                {
                    var experiment = (Experiment)period.CreateExperiment(out j);
                    experiment.InitExperiment();
                    experiment.ScanType = TOF_MS_SCAN; 
                }
            }


            if(prodIonExperiment == null)
            {
                throw new IOException("Product Ion scan was not found in the method.");
            }

            // Get the TOF mreplaced range from the template
            var tofPropertiesTemplate = (ITOFProperties)prodIonExperiment;

            short s;

            //Get initial source parameters from the template
            var sourceParamsTblInput = (ParamDataColl)prodIonExperiment.SourceParamsTbl;
            ParameterData param = (ParameterData) sourceParamsTblInput.FindParameter("GS1", out s);
            float sourceGas1 = param == null ? 0 : param.startVal;
            param = (ParameterData)sourceParamsTblInput.FindParameter("GS2", out s);
            float sourceGas2 = param == null ? 0 : param.startVal;
            param = (ParameterData)sourceParamsTblInput.FindParameter("CUR", out s);
            float curtainGas = param == null ? 0 : param.startVal;
            param = (ParameterData)sourceParamsTblInput.FindParameter("TEM", out s);
            float temperature = param == null ? 0 : param.startVal;
            param = (ParameterData)sourceParamsTblInput.FindParameter("IHT", out s);
            float nanoTemperature = param == null ? 0 : param.startVal;


            string ionSprayVoltageParamName = "ISVF"; // ISVF on 5600, IS on QSTAR
            float ionSprayVoltage;

            var paramData = ((ParameterData)sourceParamsTblInput.FindParameter(ionSprayVoltageParamName, out s));
            if (s != -1)
            {
                ionSprayVoltage = paramData.startVal;
            }
            else
            {
                ionSprayVoltageParamName = "IS";
                ionSprayVoltage = ((ParameterData)sourceParamsTblInput.FindParameter(ionSprayVoltageParamName, out s)).startVal;
            }

            // We will use parameters from the first mreplaced range in the template product ion experiment.
            var mreplacedRangeTemplate = (IMreplacedRange)prodIonExperiment.GetMreplacedRange(0);
            var paramTblTemplate = (ParamDataColl)mreplacedRangeTemplate.MreplacedDepParamTbl;


            double minPrecursorMreplaced = double.MaxValue;
            double maxPrecursorMreplaced = 0;

            var precursorsToExperimentIndex = new Dictionary<double, int>();

            foreach (var transition in transitions.Transitions)
            {
                if (precursorsToExperimentIndex.ContainsKey(transition.PrecursorMz))
                {
                    transition.ExperimentIndex = IsPrecursorTypeTransition(transition)
                                                     ? 0
                                                     : precursorsToExperimentIndex[transition.PrecursorMz];
                    continue;
                }

                var experiment = (Experiment) period.CreateExperiment(out j);
                experiment.Q1ResolutionFlag = prodIonExperiment.Q1ResolutionFlag;

                precursorsToExperimentIndex.Add(transition.PrecursorMz, j);
                transition.ExperimentIndex = IsPrecursorTypeTransition(transition) ? 0 : j;
                experiment.InitExperiment();

                // Setting ScanType to 6 for QSTAR causes method export to fail. Setting it to 9 works for both AB 5600 and QSTAR
                experiment.ScanType = PROD_ION_SCAN;

                experiment.FixedMreplaced = transition.PrecursorMz;

                minPrecursorMreplaced = Math.Min(minPrecursorMreplaced, transition.PrecursorMz);
                maxPrecursorMreplaced = Math.Max(maxPrecursorMreplaced, transition.PrecursorMz);

                var tofProperties = (ITOFProperties)experiment;

              
                tofProperties.AcreplacedTime = tofPropertiesTemplate.AcreplacedTime;
                tofProperties.TOFMreplacedMin = tofPropertiesTemplate.TOFMreplacedMin;
                tofProperties.TOFMreplacedMax = tofPropertiesTemplate.TOFMreplacedMax;
                

                // The following should trigger the "Suggest" button functionality
                // of updating the Q2 transmission window.
                tofProperties.UseQ1TranDefault = 1;
                //tofProperties.UseTOFExtrDefault = 1; // Works without this one.


                // High Sensitivity vs. High Resolution
                var tofProperties2 = experiment as ITOFProperties2;
                var templateTofProperties2 = prodIonExperiment as ITOFProperties2;
                if (tofProperties2 != null && templateTofProperties2 != null)
                {
                    tofProperties2.HighSensitivity = templateTofProperties2.HighSensitivity;
                }

                var sourceParamsTblOutput = (ParamDataColl)experiment.SourceParamsTbl;
                if (sourceParamsTblInput.FindParameter("GS1", out s) != null && s != -1)
                    sourceParamsTblOutput.AddSetParameter("GS1", sourceGas1, sourceGas1, 0, out s);
                if (sourceParamsTblInput.FindParameter("GS2", out s) != null && s != -1)
                    sourceParamsTblOutput.AddSetParameter("GS2", sourceGas2, sourceGas2, 0, out s);
                if (sourceParamsTblInput.FindParameter("CUR", out s) != null && s != -1)
                    sourceParamsTblOutput.AddSetParameter("CUR", curtainGas, curtainGas, 0, out s);
                if (sourceParamsTblInput.FindParameter("TEM", out s) != null && s != -1)
                    sourceParamsTblOutput.AddSetParameter("TEM", temperature, temperature, 0, out s);
                if (sourceParamsTblInput.FindParameter("IHT", out s) != null && s != -1)
                    sourceParamsTblOutput.AddSetParameter("IHT", nanoTemperature, nanoTemperature, 0, out s);
                if (sourceParamsTblInput.FindParameter(ionSprayVoltageParamName, out s) != null && s != -1)
                    sourceParamsTblOutput.AddSetParameter(ionSprayVoltageParamName, ionSprayVoltage, ionSprayVoltage, 0, out s);

                // Copy the compound dependent parameters from the template
                for (int i = 0; i < experiment.MreplacedRangesCount; i++)
                {
                    var mreplacedRange = (IMreplacedRange)experiment.GetMreplacedRange(i);
                    var mreplacedDepParams = (ParamDataColl)mreplacedRange.MreplacedDepParamTbl;

                    // Declustering potential
                    float dp = ((ParameterData)paramTblTemplate.FindParameter("DP", out s)).startVal;
                    if(s != -1)
                    {
                        if (transition.DP > 0)
                            dp = Convert.ToSingle(transition.DP);
                        mreplacedDepParams.AddSetParameter("DP", dp, dp, 0, out s); 
                    }
                    

                    // Collision engergy
                    float ce = ((ParameterData)paramTblTemplate.FindParameter("CE", out s)).startVal;
                    if (s != -1)
                    {
                        if (transition.CE > 0)
                            ce = Convert.ToSingle(transition.CE);
                        mreplacedDepParams.AddSetParameter("CE", ce, ce, 0, out s);
                    }

                    // Ion release delay
                    float ird = ((ParameterData)paramTblTemplate.FindParameter("IRD", out s)).startVal;
                    if (s != -1)
                    {
                        mreplacedDepParams.AddSetParameter("IRD", ird, ird, 0, out s);
                    }

                    // Ion release width
                    float irw = ((ParameterData)paramTblTemplate.FindParameter("IRW", out s)).startVal;
                    if (s != -1)
                    {
                        mreplacedDepParams.AddSetParameter("IRW", irw, irw, 0, out s);
                    }

                    // Collision energy spread; Only on the replacedyst TF 1.5.1 and TF1.5.2
                    paramData = ((ParameterData)paramTblTemplate.FindParameter("CES", out s));
                    if (s != -1)
                    {
                        mreplacedDepParams.AddSetParameter("CES", paramData.startVal, paramData.startVal, 0, out s);
                    }

                    // Focusing potential; Only on replacedyst QS 2.0
                    paramData = ((ParameterData)paramTblTemplate.FindParameter("FP", out s));
                    if (s != -1)
                    {
                        mreplacedDepParams.AddSetParameter("FP", paramData.startVal, paramData.startVal, 0, out s);
                    }

                    // Declustering potential 2; Only on replacedyst QS 2.0
                    paramData = ((ParameterData)paramTblTemplate.FindParameter("DP2", out s));
                    if (s != -1)
                    {
                        mreplacedDepParams.AddSetParameter("DP2", paramData.startVal, paramData.startVal, 0, out s);
                    }

                    // Collision gas; Only on replacedyst QS 2.0
                    paramData = ((ParameterData)paramTblTemplate.FindParameter("CAD", out s));
                    if (s != -1)
                    {
                        mreplacedDepParams.AddSetParameter("CAD", paramData.startVal, paramData.startVal, 0, out s);
                    }
                }
            }

            // Expand the mreplaced range for the TOF MS scan if the precursor mreplaced of any of the MS/MS experiments
            // was out of the range
            if(Ms1Scan)
            {
                var ms1TofProperties = (ITOFProperties)(period.GetExperiment(0));
                ms1TofProperties.TOFMreplacedMin = Math.Min(ms1TofProperties.TOFMreplacedMin, minPrecursorMreplaced);
                ms1TofProperties.TOFMreplacedMax = Math.Max(ms1TofProperties.TOFMreplacedMax, maxPrecursorMreplaced);
            }


        }

19 Source : SpectrumFilter.cs
with Apache License 2.0
from ProteoWizard

public bool PreplacedesFilterFAIMS(MsDataSpectrum spectrum)
        {
            return _filterMzValuesFAIMSDict == null || // No FAIMS filtering, everything preplacedes
                   !spectrum.IonMobility.Mobility.HasValue || // This spectrum is not ion mobility data
                   _filterMzValuesFAIMSDict.ContainsKey(spectrum.IonMobility.Mobility.Value);
        }

19 Source : Export.cs
with Apache License 2.0
from ProteoWizard

protected override void WriteTransition(TextWriter writer,
                                                int fileNumber,
                                                PeptideGroupDocNode nodePepGroup,
                                                PeptideDocNode nodePep,
                                                TransitionGroupDocNode nodeTranGroup,
                                                TransitionGroupDocNode nodeTranGroupPrimary,
                                                TransitionDocNode nodeTran,
                                                int step)
        {
            // Compound Name
            var compound = GetCompound(nodePep, nodeTranGroup);
            compound += nodeTranGroup.PrecursorAdduct.AsFormulaOrSigns(); // Something like +++ or -- or [M+Na]
            writer.WriteDsvField(compound, FieldSeparator);
            writer.Write(FieldSeparator);
            // Retention Time
            double? rt = null;
            if (MethodType == ExportMethodType.Standard)
            {
                // TODO: Should have run length here
//                writer.Write(RunLength); // Store for later use
                writer.Write(FieldSeparator);
//                writer.Write((RunLength/2).ToString(CultureInfo));
                writer.Write(FieldSeparator);
            }
            else
            {
                // Scheduling information
                double rtWindow;
                rt = Doreplacedent.Settings.PeptideSettings.Prediction.PredictRetentionTime(Doreplacedent, nodePep, nodeTranGroup,
                    SchedulingReplicateIndex, SchedulingAlgorithm, Doreplacedent.Settings.HasResults, out rtWindow);
                if (rt.HasValue)
                    writer.Write(rt);
                writer.Write(FieldSeparator);
                // Retention Time Window
                if (rt.HasValue)
                    writer.Write(rtWindow);
                writer.Write(FieldSeparator);
            }
            // CAS Number
            writer.Write(GetCAS(nodePep, nodeTranGroup));
            writer.Write(FieldSeparator);
            // Retention Index
            double retentionIndexKey = rt.GetValueOrDefault();
            if (_retentionIndices.ContainsKey(retentionIndexKey))
            {
                writer.Write(_retentionIndices[retentionIndexKey]);
            }
            else
            {
                _retentionIndices[retentionIndexKey] = ++_retentionIndex;
                writer.Write(_retentionIndex);
            }
            writer.Write(FieldSeparator);
            // Scan Type
            writer.Write(@"MRM");
            writer.Write(FieldSeparator);
            // Polarity
            if (nodeTranGroup.TransitionGroup.PrecursorCharge > 0)
                writer.Write(@"Positive");
            else
                writer.Write(@"Negative");
            writer.Write(FieldSeparator);
            // Scan Time (ms)
            writer.Write(@"100");
            writer.Write(FieldSeparator);
            // Separation Method
            writer.Write(@"LCMS");
            writer.Write(FieldSeparator);
            // Source
            writer.Write(FieldSeparator);
            // Regulation
            writer.Write(FieldSeparator);
            // Clreplacedification
            writer.Write(FieldSeparator);
            // Comment
            writer.Write(FieldSeparator);
            // Transitions Count
            writer.Write(nodePepGroup.TransitionCount);
            writer.Write(FieldSeparator);
            // Q1 First Mreplaced
            writer.Write(SequenceMreplacedCalc.PersistentMZ(nodeTranGroup.PrecursorMz).ToString(CultureInfo));
            writer.Write(FieldSeparator);
            // Q1 Last Mreplaced
            writer.Write(FieldSeparator);
            // Q1 Resolution
            // TODO fill in value
            writer.Write(FieldSeparator);
            // Q3 First Mreplaced
            double productMz = GetProductMz(SequenceMreplacedCalc.PersistentMZ(nodeTran.Mz), step);
            writer.Write(productMz.ToString(CultureInfo));
            writer.Write(FieldSeparator);
            // Q3 Last Mreplaced
            writer.Write(FieldSeparator);
            // Q3 Resolution
            // TODO fill in value
            writer.Write(FieldSeparator);
            // Collision Energy
            writer.Write(Math.Round(GetCollisionEnergy(nodePep, nodeTranGroup, nodeTran, step), 1).ToString(CultureInfo));
            writer.Write(FieldSeparator);
            // Dwell Time
            writer.Write(DwellTime.HasValue ? DwellTime.ToString() : string.Empty);
            writer.Write(FieldSeparator);
            // Is Quantifier
            writer.Write(1);
            writer.Write(FieldSeparator);
            // Quantifier Ions
            writer.Write(productMz.ToString(CultureInfo));
            writer.Write(FieldSeparator);
            // Is Qualifier
            writer.Write(0);
            writer.Write(FieldSeparator);
            // Qualifier Count
            writer.Write(FieldSeparator);
            // Qual Mreplaced 1
            writer.Write(FieldSeparator);
            // Qual Ratio 1
            writer.Write(FieldSeparator);
            // Qual Mreplaced 2
            writer.Write(FieldSeparator);
            // Qual Ratio 2
            writer.Write(FieldSeparator);
            // Qual Mreplaced 3
            writer.Write(FieldSeparator);
            // Qual Ratio 3
            writer.Write(FieldSeparator);
            // Qual Mreplaced 4
            writer.Write(FieldSeparator);
            // Qual Ratio 4
            writer.Write(FieldSeparator);
            // Qual Mreplaced 5
            writer.Write(FieldSeparator);
            // Qual Ratio 5
            writer.Write(FieldSeparator);
            // GUID ("Dont fill this Column")

            writer.WriteLine();
        }

19 Source : ReactiveTest.cs
with Apache License 2.0
from shoy160

[TestMethod]
        public void ServiceRandomTest()
        {
            var services = new List<ServiceAddress>
            {
                new ServiceAddress {Weight = 3},
                new ServiceAddress {Weight = 2},
                new ServiceAddress {Weight = 1}
            };
            var dict = new Dictionary<double, int>();
            for (var i = 0; i < 200; i++)
            {
                var service = services.Random();
                if (dict.ContainsKey(service.Weight))
                    dict[service.Weight]++;
                else
                    dict[service.Weight] = 1;
            }

            Console.WriteLine(JsonConvert.SerializeObject(dict));
        }

19 Source : UniqueValueCache.cs
with MIT License
from SteeBono

public bool Contains(double value)
        {
            return this.doubles.ContainsKey(value);
        }

19 Source : FileSystemTileServer.cs
with Microsoft Public License
from stewienj

protected string GetZoomDir(double level)
		{
			if (!zoomDirs.ContainsKey(level))
			{
				if (string.IsNullOrEmpty(cachePath))
					throw new InvalidOperationException("Name is not replacedigned.");

				string zoomDirPath = Path.Combine(cachePath, GetDirPath(level));
				zoomDirs[level] = zoomDirPath;
			}

			return zoomDirs[level];
		}

19 Source : Program.cs
with MIT License
from Tuscann

static void Main()
        {
            string products = Console.ReadLine();
            Dictionary<string, Dictionary<double, double>> result = new Dictionary<string, Dictionary<double, double>>();
            double totalAmount = 0.0;

            while (products != "stocked")
            {
                string[] product = products.Split().ToArray();
                string name = product[0];
                double price = double.Parse(product[1]);
                double quanreplacedy = double.Parse(product[2]);

                if (!result.ContainsKey(name)) // if key not exist create new dictionary
                {
                    result[name] = new Dictionary<double, double>();

                }
                if (!result[name].ContainsKey(price)) // if key exist value of neted dictionary 0
            {
                    result[name][price] = 0;
                }
                result[name][price] += quanreplacedy;  //increase value of nested dictionary quanreplacedy

            products = Console.ReadLine();
            }
            foreach (KeyValuePair<string, Dictionary<double, double>> namePriceQuanreplacedy in result)
            {
                string name = namePriceQuanreplacedy.Key;
                double price = namePriceQuanreplacedy.Value.Keys.Last();
                double quanreplacedy = namePriceQuanreplacedy.Value.Values.Sum();
                totalAmount += quanreplacedy * price;

                Console.WriteLine($"{name}: ${price:f2} * {quanreplacedy} = ${quanreplacedy * price:f2}");
            }
            Console.WriteLine("------------------------------");
            Console.WriteLine($"Grand Total: ${totalAmount:f2}");
        }

19 Source : DefaultWordExtractor.cs
with Apache License 2.0
from UglyToad

public IEnumerable<Word> GetWords(IReadOnlyList<Letter> letters)
        {
            var lettersOrder = letters.OrderByDescending(x => x.Location.Y)
                .ThenBy(x => x.Location.X);

            var lettersSoFar = new List<Letter>(10);

            var gapCountsSoFarByFontSize = new Dictionary<double, Dictionary<double, int>>();

            var y = default(double?);
            var lastX = default(double?);
            var lastLetter = default(Letter);
            foreach (var letter in lettersOrder)
            {
                if (!y.HasValue)
                {
                    y = letter.Location.Y;
                }

                if (!lastX.HasValue)
                {
                    lastX = letter.Location.X;
                }

                if (lastLetter == null)
                {
                    if (string.IsNullOrWhiteSpace(letter.Value))
                    {
                        continue;
                    }

                    lettersSoFar.Add(letter);
                    lastLetter = letter;
                    continue;
                }

                if (letter.Location.Y > y.Value + 0.5)
                {
                    if (lettersSoFar.Count > 0)
                    {
                        yield return GenerateWord(lettersSoFar);
                        lettersSoFar.Clear();
                    }

                    if (!string.IsNullOrWhiteSpace(letter.Value))
                    {
                        lettersSoFar.Add(letter);
                    }

                    y = letter.Location.Y;
                    lastX = letter.Location.X;
                    lastLetter = letter;

                    continue;
                }

                var letterHeight = Math.Max(lastLetter.GlyphRectangle.Height, letter.GlyphRectangle.Height);

                var gap = letter.Location.X - (lastLetter.Location.X + lastLetter.Width);
                var nextToLeft = letter.Location.X < lastX.Value - 1;
                var nextBigSpace = gap > letterHeight * 0.39;
                var nextIsWhiteSpace = string.IsNullOrWhiteSpace(letter.Value);
                var nextFontDiffers = !string.Equals(letter.FontName, lastLetter.FontName, StringComparison.OrdinalIgnoreCase) && gap > letter.Width * 0.1;
                var nextFontSizeDiffers = Math.Abs(letter.FontSize - lastLetter.FontSize) > 0.1;
                var nextTextOrientationDiffers = letter.TextOrientation != lastLetter.TextOrientation;

                var suspectGap = false;

                if (!nextFontSizeDiffers && letter.FontSize > 0 && gap >= 0)
                {
                    var fontSize = Math.Round(letter.FontSize);
                    if (!gapCountsSoFarByFontSize.TryGetValue(fontSize, out var gapCounts))
                    {
                        gapCounts = new Dictionary<double, int>();
                        gapCountsSoFarByFontSize[fontSize] = gapCounts;
                    }

                    var gapRounded = Math.Round(gap, 2);
                    if (!gapCounts.ContainsKey(gapRounded))
                    {
                        gapCounts[gapRounded] = 0;
                    }

                    gapCounts[gapRounded]++;

                    // More than one type of gap.
                    if (gapCounts.Count > 1 && gap > letterHeight * 0.16)
                    {
                        var mostCommonGap = gapCounts.OrderByDescending(x => x.Value).First();

                        if (gap > (mostCommonGap.Key * 5) && mostCommonGap.Value > 1)
                        {
                            suspectGap = true;
                        }
                    }
                }

                if (nextToLeft || nextBigSpace || nextIsWhiteSpace || nextFontDiffers || nextFontSizeDiffers || nextTextOrientationDiffers || suspectGap)
                {
                    if (lettersSoFar.Count > 0)
                    {
                        yield return GenerateWord(lettersSoFar);
                        lettersSoFar.Clear();
                    }
                }

                if (!string.IsNullOrWhiteSpace(letter.Value))
                {
                    lettersSoFar.Add(letter);
                }

                lastLetter = letter;

                lastX = letter.Location.X;
            }

            if (lettersSoFar.Count > 0)
            {
                yield return GenerateWord(lettersSoFar);
            }
        }