public static ParserResult<object> Choose(
            Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer,
            IEnumerable<Type> types,
            IEnumerable<string> arguments,
            StringComparer nameComparer,
            CultureInfo parsingCulture,
            IEnumerable<ErrorType> nonFatalErrors)
        {
            Func<ParserResult<object>> choose = () =>
            {
                var firstArg = arguments.First();

                Func<string, bool> preprocCompare = command =>
                        nameComparer.Equals(command, firstArg) ||
                        nameComparer.Equals(string.Concat("--", command), firstArg);

                var verbs = Verb.SelectFromTypes(types);

                return preprocCompare("help")
                    ? MakeNotParsed(types,
                        MakeHelpVerbRequestedError(verbs,
                            arguments.Skip(1).SingleOrDefault() ?? string.Empty, nameComparer))
                    : preprocCompare("version")
                        ? MakeNotParsed(types, new VersionRequestedError())
                        : MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture, nonFatalErrors);
            };

            return arguments.Any()
                ? choose()
                : MakeNotParsed(types, new NoVerbSelectedError());
        }
        public static ParserResult<object> Choose(
            Func<IEnumerable<string>, IEnumerable<OptionSpecification>, StatePair<IEnumerable<Token>>> tokenizer,
            IEnumerable<Type> types,
            IEnumerable<string> arguments,
            StringComparer nameComparer,
            CultureInfo parsingCulture)
        {
            if (arguments.Empty())
            {
                return MakeNotParsed(types, new NoVerbSelectedError());
            }

            var firstArg = arguments.First();

            Func<string, bool> preprocCompare = command =>
                    nameComparer.Equals(command, firstArg) ||
                    nameComparer.Equals(string.Concat("--", command), firstArg);

            var verbs = Verb.SelectFromTypes(types);

            if (preprocCompare("help"))
            {
                return MakeNotParsed(types,
                    MakeHelpVerbRequestedError(verbs,
                        arguments.Skip(1).SingleOrDefault() ?? string.Empty, nameComparer));
            }

            if (preprocCompare("version"))
            {
                return MakeNotParsed(types, new VersionRequestedError());
            }

            return MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture);
        }
		public ITypeDefinition GetClass(string nameSpace, string name, int typeParameterCount, StringComparer nameComparer)
		{
			foreach (ITypeDefinition type in types) {
				if (nameComparer.Equals(type.Name, name) && nameComparer.Equals(type.Namespace, nameSpace) && type.TypeParameterCount == typeParameterCount)
					return type;
			}
			return null;
		}
        public static bool MatchName(this string value, string shortName, string longName, StringComparer comparer)
        {
            if (value == null) throw new ArgumentNullException("value");

            return value.Length == 1
               ? comparer.Equals(value, shortName)
               : comparer.Equals(value, longName);
        }
Exemple #5
0
        /// <summary>
        /// Gets all the node indices with matching names per the <paramref name="comparer" />.
        /// </summary>
        private IEnumerable<int> FindNodes(string name, StringComparer comparer)
        {
            // find any node that matches case-insensitively
            var startingPosition = BinarySearch(name);

            if (startingPosition != -1)
            {
                // yield if this matches by the actual given comparer
                if (comparer.Equals(name, _nodes[startingPosition].Name))
                {
                    yield return startingPosition;
                }

                int position = startingPosition;
                while (position > 0 && s_nodeSortComparer.Equals(_nodes[position - 1].Name, name))
                {
                    position--;

                    if (comparer.Equals(_nodes[position].Name, name))
                    {
                        yield return position;
                    }
                }

                position = startingPosition;
                while (position + 1 < _nodes.Count && s_nodeSortComparer.Equals(_nodes[position + 1].Name, name))
                {
                    position++;
                    if (comparer.Equals(_nodes[position].Name, name))
                    {
                        yield return position;
                    }
                }
            }
        }
 public static Func<IEnumerable<string>, IEnumerable<Error>> VersionCommand(StringComparer nameComparer)
 {
     return
         arguments =>
             nameComparer.Equals("--version", arguments.First())
                 ? new Error[] { new VersionRequestedError() }
                 : Enumerable.Empty<Error>();
 }
 private static ParserResult<object> MatchVerb(
     Func<IEnumerable<string>, IEnumerable<OptionSpecification>, StatePair<IEnumerable<Token>>> tokenizer,
     IEnumerable<Tuple<Verb, Type>> verbs,
     IEnumerable<string> arguments,
     StringComparer nameComparer,
     CultureInfo parsingCulture)
 {
     return verbs.Any(a => nameComparer.Equals(a.Item1.Name, arguments.First()))
         ? InstanceBuilder.Build(
             Maybe.Just<Func<object>>(() => verbs.Single(v => nameComparer.Equals(v.Item1.Name, arguments.First())).Item2.AutoDefault()),
             tokenizer,
             arguments.Skip(1),
             nameComparer,
             parsingCulture)
         : new NotParsed<object>(
             new NullInstance(),
             verbs.Select(v => v.Item2),
             new[] { new BadVerbSelectedError(arguments.First()) });
 }
Exemple #8
0
            public static int IndexOf(/*this*/ string[]/*!*/ array, string/*!*/ value, StringComparer/*!*/ comparer) {
                ContractUtils.RequiresNotNull(array, "array");
                ContractUtils.RequiresNotNull(value, "value");
                ContractUtils.RequiresNotNull(comparer, "comparer");

                for (int i = 0; i < array.Length; i++) {
                    if (comparer.Equals(array[i], value)) {
                        return i;
                    }
                }

                return -1;
            }
 private static HelpVerbRequestedError MakeHelpVerbRequestedError(
     IEnumerable<Tuple<Verb, Type>> verbs,
     string verb,
     StringComparer nameComparer)
 {
     return verb.Length > 0
         ? verbs.SingleOrDefault(v => nameComparer.Equals(v.Item1.Name, verb))
                 .ToMaybe()
                 .Return(
                     v => new HelpVerbRequestedError(v.Item1.Name, v.Item2, true),
                     new HelpVerbRequestedError(null, null, false))
         : new HelpVerbRequestedError(null, null, false);
 }
Exemple #10
0
        private static void VerifyComparer(StringComparer sc, bool ignoreCase)
        {
            String s1 = "Hello";
            String s1a = "Hello";
            String s1b = "HELLO";
            String s2 = "There";

            Assert.True(sc.Equals(s1, s1a));
            Assert.True(sc.Equals(s1, s1a));

            Assert.Equal(0, sc.Compare(s1, s1a));
            Assert.Equal(0, ((IComparer)sc).Compare(s1, s1a));

            Assert.True(sc.Equals(s1, s1));
            Assert.True(((IEqualityComparer)sc).Equals(s1, s1));
            Assert.Equal(0, sc.Compare(s1, s1));
            Assert.Equal(0, ((IComparer)sc).Compare(s1, s1));

            Assert.False(sc.Equals(s1, s2));
            Assert.False(((IEqualityComparer)sc).Equals(s1, s2));
            Assert.True(sc.Compare(s1, s2) < 0);
            Assert.True(((IComparer)sc).Compare(s1, s2) < 0);

            Assert.Equal(ignoreCase, sc.Equals(s1, s1b));
            Assert.Equal(ignoreCase, ((IEqualityComparer)sc).Equals(s1, s1b));

            int result = sc.Compare(s1, s1b);
            if (ignoreCase)
                Assert.Equal(0, result);
            else
                Assert.NotEqual(0, result);

            result = ((IComparer)sc).Compare(s1, s1b);
            if (ignoreCase)
                Assert.Equal(0, result);
            else
                Assert.NotEqual(0, result);
        }
		static string FindFreeName(string baseName, List<DeclarationStatement> list1, List<DeclarationStatement> list2, StringComparer nameComparer)
		{
			string tmp = baseName + "__";
			for (int i = 2;; i++) {
				string tryName = tmp + i.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
				bool found = false;
				foreach (DeclarationStatement d in list1) {
					if (nameComparer.Equals(d.Declaration.Name, tryName)) {
						found = true;
						break;
					}
				}
				if (found) continue;
				foreach (DeclarationStatement d in list2) {
					if (nameComparer.Equals(d.Declaration.Name, tryName)) {
						found = true;
						break;
					}
				}
				if (!found)
					return tryName;
			}
		}
        public static string GetStringDifferHint(string left, string right, StringComparer comparer)
        {
            if (left == null) return ", left is null";
            if (right == null) return ", right is null";

            for (int i = 1; i <= left.Length && i <= right.Length; ++i)
            {
                //TODO: this doesn't know about surrogate pairs or things like esszett
                if (!comparer.Equals(left.Substring(0, i), right.Substring(0, i)))
                {
                    var result = CheckCharactersAt(left, right, i - 1, comparer);
                    if (result != null) return result;

                    return string.Format(", strings differ at index {0}, '{1}' != '{2}'", i - 1,
                        left[i - 1], right[i - 1]);
                }
            }

            return null; //err: they don't differ!
        }
 private static ParserResult<object> MatchVerb(
     Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer,
     IEnumerable<Tuple<Verb, Type>> verbs,
     IEnumerable<string> arguments,
     StringComparer nameComparer,
     CultureInfo parsingCulture,
     IEnumerable<ErrorType> nonFatalErrors)
 {
     return verbs.Any(a => nameComparer.Equals(a.Item1.Name, arguments.First()))
         ? InstanceBuilder.Build(
             Maybe.Just<Func<object>>(
                 () =>
                     verbs.Single(v => nameComparer.Equals(v.Item1.Name, arguments.First())).Item2.AutoDefault()),
             tokenizer,
             arguments.Skip(1),
             nameComparer,
             false,
             parsingCulture,
             nonFatalErrors)
         : MakeNotParsed(verbs.Select(v => v.Item2), new BadVerbSelectedError(arguments.First()));
 }
        public static ParserResult<object> Choose(
            Func<IEnumerable<string>, IEnumerable<OptionSpecification>, StatePair<IEnumerable<Token>>> tokenizer,
            IEnumerable<Type> types,
            IEnumerable<string> arguments,
            StringComparer nameComparer,
            CultureInfo parsingCulture)
        {
            var verbs = Verb.SelectFromTypes(types);

            return arguments.Empty()
                ? ParserResult.Create<object>(
                    ParserResultType.Verbs, new NullInstance(), new[] { new NoVerbSelectedError() }, Maybe.Just(types))
                : nameComparer.Equals("help", arguments.First())
                   ? ParserResult.Create<object>(
                        ParserResultType.Verbs,
                        new NullInstance(), new[] { CreateHelpVerbRequestedError(
                            verbs,
                            arguments.Skip(1).SingleOrDefault() ?? string.Empty,
                            nameComparer) }, Maybe.Just(types))
                   : MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture);
        }
		public static void RenameLocals(Block block, StringComparer nameComparer)
		{
			FindVariableDeclarationsVisitor fvdv = new FindVariableDeclarationsVisitor();
			block.Accept(fvdv);
			List<DeclarationStatement> list = new List<DeclarationStatement>();
			foreach (DeclarationStatement decl in fvdv.Declarations) {
				DeclarationStatement conflict = null;
				int conflictIndex = -1;
				for (int i = 0; i < list.Count; i++) {
					if (nameComparer.Equals(list[i].Declaration.Name, decl.Declaration.Name)) {
						conflict = list[i];
						conflictIndex = i;
						break;
					}
				}
				if (conflict == null) {
					list.Add(decl);
				} else {
					// Handle conflict: try if "moveup" would be sufficient
					if (IsSameType(decl.Declaration.Type, conflict.Declaration.Type, nameComparer)) {
						// create declaration at beginning of class and
						// replace decl & conflict by assignment
						DeclarationStatement newDecl = new DeclarationStatement(conflict.LexicalInfo);
						newDecl.Declaration = new Declaration(conflict.Declaration.LexicalInfo, conflict.Declaration.Name, conflict.Declaration.Type);
						block.Insert(0, newDecl);
						ReplaceWithInitializer(decl);
						ReplaceWithInitializer(conflict);
						list[conflictIndex] = newDecl;
					} else {
						string newName = FindFreeName(decl.Declaration.Name, list, fvdv.Declarations, nameComparer);
						decl.ParentNode.Accept(new RenameLocalsVisitor(decl.Declaration.Name, newName, nameComparer));
						decl.Declaration.Name = newName;
					}
				}
			}
		}
 public static bool operator ==(FilePath name1, FilePath name2)
 {
     return(PathComparer.Equals(name1.fileName, name2.fileName));
 }
		public IEnumerable<ITypeDefinition> GetTypes(string nameSpace, StringComparer nameComparer)
		{
			return types.Where(t => nameComparer.Equals(t.Namespace, nameSpace));
		}
        /// <summary>
        /// Compares two <see cref="XObject">XObjects</see>for equality.
        /// </summary>
        /// <param name="obj1">The first <see cref="XObject" />.</param>
        /// <param name="obj2">The second <see cref="XObject" />.</param>
        /// <param name="options">The comparison options.</param>
        /// <param name="stringComparer">The string comparer.</param>
        /// <returns>The <see cref="XObject"/> at which the first mismatch
        /// occurred; otherwise <see langword="null"/>.</returns>
        /// <remarks><para>The order of the parameters maters for ceratin options.</para></remarks>
        public static Tuple <XObject, XObject> DeepEquals(
            [CanBeNull] this XObject obj1,
            [CanBeNull] XObject obj2,
            XObjectComparisonOptions options          = XObjectComparisonOptions.Default,
            [CanBeNull] StringComparer stringComparer = null)
        {
            if (stringComparer == null)
            {
                stringComparer = StringComparer.CurrentCulture;
            }

            // Normalize flags
            bool ignoreAttributes = (options & XObjectComparisonOptions.IgnoreAttributes) ==
                                    XObjectComparisonOptions.IgnoreAttributes;
            bool ignoreAdditionalAttributes = ignoreAttributes ||
                                              ((options & XObjectComparisonOptions.IgnoreAdditionalAttributes) ==
                                               XObjectComparisonOptions.IgnoreAdditionalAttributes);
            bool ignoreAttributeOrder = ignoreAdditionalAttributes ||
                                        ((options & XObjectComparisonOptions.IgnoreAttributeOrder) ==
                                         XObjectComparisonOptions.IgnoreAttributeOrder);

            bool ignoreElements = (options & XObjectComparisonOptions.IgnoreElements) ==
                                  XObjectComparisonOptions.IgnoreElements;
            bool ignoreAdditionalElements = ignoreElements ||
                                            ((options & XObjectComparisonOptions.IgnoreAdditionalElements) ==
                                             XObjectComparisonOptions.IgnoreAdditionalElements);
            bool ignoreElementOrder = ignoreAdditionalElements ||
                                      ((options & XObjectComparisonOptions.IgnoreElementOrder) ==
                                       XObjectComparisonOptions.IgnoreElementOrder);

            bool ignoreComments = (options & XObjectComparisonOptions.IgnoreComments) ==
                                  XObjectComparisonOptions.IgnoreComments;
            bool ignoreAdditionalCommentss = ignoreComments ||
                                             ((options & XObjectComparisonOptions.IgnoreAdditionalComments) ==
                                              XObjectComparisonOptions.IgnoreAdditionalComments);
            bool ignoreCommentOrder = ignoreAdditionalCommentss ||
                                      ((options & XObjectComparisonOptions.IgnoreCommentOrder) ==
                                       XObjectComparisonOptions.IgnoreCommentOrder);

            bool ignoreText = (options & XObjectComparisonOptions.IgnoreText) ==
                              XObjectComparisonOptions.IgnoreText;
            bool ignoreAdditionalText = ignoreText || ((options & XObjectComparisonOptions.IgnoreAdditionalText) ==
                                                       XObjectComparisonOptions.IgnoreAdditionalText);
            bool ignoreTextOrder = ignoreAdditionalText ||
                                   ((options & XObjectComparisonOptions.IgnoreTextOrder) ==
                                    XObjectComparisonOptions.IgnoreTextOrder);
            bool ignoreTextOutsideOfChildren = ignoreText || ((options & XObjectComparisonOptions.IgnoreTextOutsideOfChildren) ==
                                                              XObjectComparisonOptions.IgnoreTextOutsideOfChildren);


            bool ignoreProcessingInstructions = (options & XObjectComparisonOptions.IgnoreProcessingInstructions) ==
                                                XObjectComparisonOptions.IgnoreProcessingInstructions;
            bool ignoreAdditionalProcessingInstructionss = ignoreProcessingInstructions ||
                                                           ((options & XObjectComparisonOptions.IgnoreAdditionalProcessingInstructions) ==
                                                            XObjectComparisonOptions.IgnoreAdditionalProcessingInstructions);
            bool ignoreProcessingInstructionOrder = ignoreAdditionalProcessingInstructionss ||
                                                    ((options & XObjectComparisonOptions.IgnoreProcessingInstructionOrder) ==
                                                     XObjectComparisonOptions.IgnoreProcessingInstructionOrder);

            bool ignoreDocumentTypes = (options & XObjectComparisonOptions.IgnoreDocumentTypes) ==
                                       XObjectComparisonOptions.IgnoreDocumentTypes;
            bool ignoreAdditionalDocumentTypess = ignoreDocumentTypes ||
                                                  ((options & XObjectComparisonOptions.IgnoreAdditionalDocumentTypes) ==
                                                   XObjectComparisonOptions.IgnoreAdditionalDocumentTypes);

            bool ignoreAllChildren = ignoreElements &&
                                     ignoreProcessingInstructions &&
                                     ignoreDocumentTypes &&
                                     ignoreComments &&
                                     ignoreText;
            bool allOrderSignificant = !ignoreElementOrder &&
                                       !ignoreProcessingInstructionOrder &&
                                       !ignoreCommentOrder &&
                                       !ignoreTextOrder &&
                                       !ignoreTextOutsideOfChildren;

            Stack <XObject, XObject> stack = new Stack <XObject, XObject>();

            stack.Push(obj1, obj2);

            while (stack.TryPop(out obj1, out obj2))
            {
                // Generic equality checks
                if (ReferenceEquals(obj1, obj2))
                {
                    continue;
                }
                if (ReferenceEquals(obj1, null) ||
                    ReferenceEquals(obj2, null) ||
                    obj1.NodeType != obj2.NodeType)
                {
                    return(new Tuple <XObject, XObject>(obj1, obj2));
                }

                XContainer container1 = null;
                XContainer container2 = null;
                // Perform type specific checks.
                switch (obj1.NodeType)
                {
                case XmlNodeType.Document:
                    // Process as container
                    container1 = (XContainer)obj1;
                    container2 = (XContainer)obj2;
                    break;

                case XmlNodeType.Element:
                    XElement el1 = (XElement)obj1;
                    XElement el2 = (XElement)obj2;

                    if (el1.Name != el2.Name)
                    {
                        return(new Tuple <XObject, XObject>(obj1, obj2));
                    }

                    if (!ignoreAttributes)
                    {
                        // Add attributes to stack for processing
                        if (ignoreAttributeOrder)
                        {
                            // Build dictionary of attributes
                            Dictionary <XName, XAttribute> el2Attributes =
                                el2.Attributes()
                                // ReSharper disable once PossibleNullReferenceException
                                .ToDictionary(a => a.Name);

                            // Ignore attribute order
                            foreach (XAttribute attribute1 in el1.Attributes())
                            {
                                XAttribute attribute2;
                                // ReSharper disable once PossibleNullReferenceException
                                if (!el2Attributes.TryGetValue(attribute1.Name, out attribute2) ||
                                    !stringComparer.Equals(attribute1.Value, attribute2.Value))
                                {
                                    return(new Tuple <XObject, XObject>(attribute1, attribute2));
                                }

                                // ReSharper disable once PossibleNullReferenceException
                                el2Attributes.Remove(attribute2.Name);
                            }

                            // If additional attributes on the second element are not being ignored, check if we
                            // additional attributes.
                            if (!ignoreAdditionalAttributes &&
                                el2Attributes.Count > 0)
                            {
                                return(new Tuple <XObject, XObject>(null, el2Attributes.Values.First()));
                            }
                        }
                        else
                        {
                            // Attribute order matters
                            XAttribute attribute1 = el1.FirstAttribute;
                            XAttribute attribute2 = el2.FirstAttribute;
                            while (attribute1 != null)
                            {
                                // We have less attributes on the second element than the first
                                if (attribute2 == null ||
                                    !stringComparer.Equals(attribute1.Value, attribute2.Value))
                                {
                                    return(new Tuple <XObject, XObject>(attribute1, attribute2));
                                }
                                attribute1 = attribute1.NextAttribute;
                                attribute2 = attribute2.NextAttribute;
                            }
                            if (attribute2 != null)
                            {
                                return(new Tuple <XObject, XObject>(null, attribute2));
                            }
                        }
                    }

                    // Process as container
                    container1 = el1;
                    container2 = el2;
                    break;

                case XmlNodeType.Attribute:
                    XAttribute attr1 = (XAttribute)obj1;
                    XAttribute attr2 = (XAttribute)obj2;
                    if (!ignoreAttributes &&
                        (attr1.Name != attr2.Name ||
                         !stringComparer.Equals(attr1.Value, attr2.Value)))
                    {
                        return(new Tuple <XObject, XObject>(attr1, attr2));
                    }
                    break;

                case XmlNodeType.ProcessingInstruction:
                    XProcessingInstruction pi1 = (XProcessingInstruction)obj1;
                    XProcessingInstruction pi2 = (XProcessingInstruction)obj2;
                    if (!ignoreProcessingInstructions &&
                        (!stringComparer.Equals(pi1.Target, pi2.Target) ||
                         !stringComparer.Equals(pi1.Data, pi2.Data)))
                    {
                        return(new Tuple <XObject, XObject>(pi1, pi2));
                    }
                    break;

                case XmlNodeType.DocumentType:
                    XDocumentType dt1 = (XDocumentType)obj1;
                    XDocumentType dt2 = (XDocumentType)obj2;
                    if (!ignoreDocumentTypes &&
                        (!stringComparer.Equals(dt1.Name, dt2.Name) ||
                         !stringComparer.Equals(dt1.PublicId, dt2.PublicId) ||
                         !stringComparer.Equals(dt1.SystemId, dt2.SystemId) ||
                         !stringComparer.Equals(dt1.InternalSubset, dt2.InternalSubset)))
                    {
                        return(new Tuple <XObject, XObject>(dt1, dt2));
                    }
                    break;

                case XmlNodeType.Text:
                case XmlNodeType.CDATA:
                    XText txt1 = (XText)obj1;
                    XText txt2 = (XText)obj2;
                    if (!ignoreText &&
                        !stringComparer.Equals(txt1.Value, txt2.Value))
                    {
                        return(new Tuple <XObject, XObject>(txt1, txt2));
                    }
                    break;

                case XmlNodeType.Comment:
                    XComment comment1 = (XComment)obj1;
                    XComment comment2 = (XComment)obj2;
                    if (!ignoreComments &&
                        !stringComparer.Equals(comment1.Value, comment2.Value))
                    {
                        return(new Tuple <XObject, XObject>(comment1, comment2));
                    }
                    break;
                }

                // If we're not a container, or we're ignoring container contents, we can move on.
                if (container1 == null || ignoreAllChildren)
                {
                    continue;
                }
                if (allOrderSignificant)
                {
                    // We care about the order of everything
                    XNode n1 = container1.FirstNode;
                    XNode n2 = container2.FirstNode;
                    while (n1 != null)
                    {
                        if (n2 == null || n1.NodeType != n2.NodeType)
                        {
                            return(new Tuple <XObject, XObject>(n1, n2));
                        }
                        stack.Push(n1, n2);
                        n1 = n1.NextNode;
                        n2 = n2.NextNode;
                    }
                    if (n2 != null)
                    {
                        return(new Tuple <XObject, XObject>(null, n2));
                    }
                    continue;
                }

                // We care about the order of somethings, but not others.
                List <XElement> elements1;
                List <XElement> elements2;
                if (!ignoreElements && ignoreElementOrder)
                {
                    elements1 = new List <XElement>();
                    elements2 = new List <XElement>();
                }
                else
                {
                    elements1 = elements2 = null;
                }
                List <XProcessingInstruction> processingInstructions1;
                List <XProcessingInstruction> processingInstructions2;
                if (!ignoreProcessingInstructions && ignoreProcessingInstructionOrder)
                {
                    processingInstructions1 = new List <XProcessingInstruction>();
                    processingInstructions2 = new List <XProcessingInstruction>();
                }
                else
                {
                    processingInstructions1 = processingInstructions2 = null;
                }
                List <XComment> comments1;
                List <XComment> comments2;
                if (!ignoreComments && ignoreCommentOrder)
                {
                    comments1 = new List <XComment>();
                    comments2 = new List <XComment>();
                }
                else
                {
                    comments1 = comments2 = null;
                }
                List <XText> texts1;
                List <XText> texts2;
                if (!ignoreText && ignoreTextOrder)
                {
                    texts1 = new List <XText>();
                    texts2 = new List <XText>();
                }
                else
                {
                    texts1 = texts2 = null;
                }

                XDocumentType documentType1 = null;
                XDocumentType documentType2 = null;
                bool          hasChildren   = false;
                bool          hasText       = false;

                // Build child lists from first node
                List <XObject> l1 = new List <XObject>();
                XNode          n  = container1.FirstNode;
                while (n != null)
                {
                    switch (n.NodeType)
                    {
                    case XmlNodeType.Element:
                        hasChildren = true;
                        if (elements1 != null)
                        {
                            elements1.Add((XElement)n);
                        }
                        else if (!ignoreElements)
                        {
                            l1.Add(n);
                        }
                        break;

                    case XmlNodeType.Text:
                    case XmlNodeType.CDATA:
                        hasText = true;
                        if (texts1 != null)
                        {
                            texts1.Add((XText)n);
                        }
                        else if (!ignoreText)
                        {
                            l1.Add(n);
                        }
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        if (processingInstructions1 != null)
                        {
                            processingInstructions1.Add((XProcessingInstruction)n);
                        }
                        else if (!ignoreProcessingInstructions)
                        {
                            l1.Add(n);
                        }
                        break;

                    case XmlNodeType.Comment:
                        if (comments1 != null)
                        {
                            comments1.Add((XComment)n);
                        }
                        else if (!ignoreComments)
                        {
                            l1.Add(n);
                        }
                        break;

                    case XmlNodeType.DocumentType:
                        if (!ignoreDocumentTypes)
                        {
                            documentType1 = (XDocumentType)n;
                        }
                        break;
                    }
                    n = n.NextNode;
                }

                // Build child lists from second node
                List <XObject> l2 = new List <XObject>();
                n = container2.FirstNode;
                while (n != null)
                {
                    switch (n.NodeType)
                    {
                    case XmlNodeType.Element:
                        hasChildren = true;
                        if (elements2 != null)
                        {
                            elements2.Add((XElement)n);
                        }
                        else if (!ignoreElements)
                        {
                            l2.Add(n);
                        }
                        break;

                    case XmlNodeType.Text:
                    case XmlNodeType.CDATA:
                        hasText = true;
                        if (texts2 != null)
                        {
                            texts2.Add((XText)n);
                        }
                        else if (!ignoreText)
                        {
                            l2.Add(n);
                        }
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        if (processingInstructions2 != null)
                        {
                            processingInstructions2.Add((XProcessingInstruction)n);
                        }
                        else if (!ignoreProcessingInstructions)
                        {
                            l2.Add(n);
                        }
                        break;

                    case XmlNodeType.Comment:
                        if (comments2 != null)
                        {
                            comments2.Add((XComment)n);
                        }
                        else if (!ignoreComments)
                        {
                            l2.Add(n);
                        }
                        break;

                    case XmlNodeType.DocumentType:
                        if (!ignoreDocumentTypes)
                        {
                            documentType2 = (XDocumentType)n;
                        }
                        break;
                    }
                    n = n.NextNode;
                }

                // Add document type comparison if necessary (note we never consider order of the document type as it
                // always appears before the root node.
                if (!ignoreDocumentTypes)
                {
                    if (documentType1 != null)
                    {
                        if (documentType2 == null ||
                            !stringComparer.Equals(documentType1.Name, documentType2.Name) ||
                            !stringComparer.Equals(documentType1.PublicId, documentType2.PublicId) ||
                            !stringComparer.Equals(documentType1.SystemId, documentType2.SystemId) ||
                            !stringComparer.Equals(documentType1.InternalSubset, documentType2.InternalSubset))
                        {
                            return(new Tuple <XObject, XObject>(documentType1, documentType2));
                        }

                        // Don't push onto stack, as we've already done the comparison at this point.
                    }
                    else if (!ignoreAdditionalDocumentTypess && documentType2 != null)
                    {
                        return(new Tuple <XObject, XObject>(null, documentType2));
                    }
                }

                // Add order specific nodes to stack for processing.
                bool stripText = hasChildren && hasText && ignoreTextOutsideOfChildren;
                List <XObject> .Enumerator l1Enumerator = l1.GetEnumerator();
                List <XObject> .Enumerator l2Enumerator = l2.GetEnumerator();
                while (l1Enumerator.MoveNext())
                {
                    if (stripText && l1Enumerator.Current is XText)
                    {
                        continue;
                    }

                    do
                    {
                        if (!l2Enumerator.MoveNext())
                        {
                            return(new Tuple <XObject, XObject>(l1Enumerator.Current, null));
                        }
                    } while (stripText && l2Enumerator.Current is XText);

                    if (l1Enumerator.Current.NodeType != l2Enumerator.Current.NodeType)
                    {
                        return(new Tuple <XObject, XObject>(l1Enumerator.Current, l2Enumerator.Current));
                    }

                    stack.Push(l1Enumerator.Current, l2Enumerator.Current);
                }
                while (l2Enumerator.MoveNext())
                {
                    if (!stripText || !(l2Enumerator.Current is XText))
                    {
                        return(new Tuple <XObject, XObject>(null, l2Enumerator.Current));
                    }
                }

                // Add order independent nodes for processing
                // ReSharper disable PossibleNullReferenceException
                if (elements1 != null)
                {
                    foreach (XElement e1 in elements1)
                    {
                        XElement e2;
                        if (!elements2.TryRemove(e => e.Name == e1.Name, out e2))
                        {
                            return(new Tuple <XObject, XObject>(e1, null));
                        }
                        stack.Push(e1, e2);
                    }
                    if (!ignoreAdditionalElements && texts2.Count > 0)
                    {
                        return(new Tuple <XObject, XObject>(null, elements2.First()));
                    }
                }
                if (texts1 != null)
                {
                    foreach (XText t1 in texts1)
                    {
                        XText t2;
                        if (!texts2.TryRemove(t => stringComparer.Equals(t1.Value, t.Value), out t2))
                        {
                            return(new Tuple <XObject, XObject>(t1, null));
                        }
                        // Don't push onto stack, as we've already done the comparison at this point.
                    }
                    if (!ignoreAdditionalText && texts2.Count > 0)
                    {
                        return(new Tuple <XObject, XObject>(null, texts2.First()));
                    }
                }
                if (comments1 != null)
                {
                    foreach (XComment c1 in comments1)
                    {
                        XComment c2;
                        if (!comments2.TryRemove(c => stringComparer.Equals(c1.Value, c.Value), out c2))
                        {
                            return(new Tuple <XObject, XObject>(c1, null));
                        }
                        // Don't push onto stack, as we've already done the comparison at this point.
                    }
                    if (!ignoreAdditionalCommentss && comments2.Count > 0)
                    {
                        return(new Tuple <XObject, XObject>(null, comments2.First()));
                    }
                }
                if (processingInstructions1 != null)
                {
                    foreach (XProcessingInstruction pi1 in processingInstructions1)
                    {
                        XProcessingInstruction pi2;
                        if (!processingInstructions2.TryRemove(pi => stringComparer.Equals(pi.Target, pi1.Target) && stringComparer.Equals(pi.Data, pi1.Data), out pi2))
                        {
                            return(new Tuple <XObject, XObject>(pi1, null));
                        }
                        // Don't push onto stack, as we've already done the comparison at this point.
                    }
                    if (!ignoreAdditionalProcessingInstructionss && processingInstructions2.Count > 0)
                    {
                        return(new Tuple <XObject, XObject>(null, processingInstructions2.First()));
                    }
                }
                // ReSharper restore PossibleNullReferenceException
            }

            // Successful comparisons result in null.
            return(null);
        }
Exemple #19
0
 /// <summary>
 /// Equals()
 /// </summary>
 /// <param name="other">Other instance</param>
 /// <returns></returns>
 public bool Equals(ModuleName other)
 {
     return((ModuleNameOnly || other.ModuleNameOnly || AssemblyNameComparer.Equals(AssemblyFullName, other.AssemblyFullName)) &&
            ModuleNameComparer.Equals(Name, other.Name) &&
            (flags & Flags.CompareMask) == (other.flags & Flags.CompareMask));
 }
Exemple #20
0
 /// <summary>
 /// Equals()
 /// </summary>
 /// <param name="other">Other instance</param>
 /// <returns></returns>
 public bool Equals(DnModuleId other) =>
 (ModuleNameOnly || other.ModuleNameOnly || AssemblyNameComparer.Equals(AssemblyFullName, other.AssemblyFullName)) &&
 ModuleNameComparer.Equals(ModuleName, other.ModuleName) &&
 (flags & Flags.CompareMask) == (other.flags & Flags.CompareMask);
Exemple #21
0
 public override bool Equals(String x, String y)
 {
     return(_stringComparer.Equals(x, y));
 }
Exemple #22
0
 public bool Equals(FullNameAndTypeParameterCount x, FullNameAndTypeParameterCount y)
 {
     return(x.TypeParameterCount == y.TypeParameterCount &&
            NameComparer.Equals(x.Name, y.Name) &&
            NameComparer.Equals(x.Namespace, y.Namespace));
 }
Exemple #23
0
        public static async Task Main(string[] args)
        {
            var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var appsettings = ReadConfiguration(currentPath);

            _connection = new HubConnectionBuilder()
                          .WithUrl(appsettings.SignalrUrl)
                          .Build();

            _connection.On <string, string, string>("Welcom", (scalingMachineID, message, unit) =>
            {
                if (scalingMachineID == appsettings.MachineID.ToString())
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    var newMessage          = $"#### ### Welcom Big Scaling Machine Data: {scalingMachineID}: {message}: {unit}";
                    Console.WriteLine(newMessage);
                }
            });
            await _connection.StartAsync();

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"#### ### ClientId Welcom Big Scaling Machine: " + _connection.ConnectionId);

            string         name;
            string         message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread         readThread     = new Thread(async() => await Read());

            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort();

            // Allow the user to set the appropriate properties.
            _serialPort.PortName = ReadConfiguration(currentPath).portName;
            //_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
            //_serialPort.Parity = SetPortParity(_serialPort.Parity);
            //_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
            //_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
            //_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

            // Set the read/write timeouts
            _serialPort.ReadTimeout  = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            _continue = true;
            readThread.Start();

            //Console.Write("Name: ");
            //name = Console.ReadLine();

            Console.WriteLine("Type QUIT to exit");
            while (_continue)
            {
                // emit ve client
                message = Console.ReadLine();

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    //_serialPort.WriteLine(
                    //    String.Format("<{0}>: {1}", name, message));
                }
            }

            readThread.Join();
            _serialPort.Close();
        }
            public static bool Parse(ProcessorConfiguration configuration, string item)
            {
                if (Comparer.Equals(item, MakeBackup))
                {
                    configuration.MakeBackup = true;
                    return(true);
                }

                if (Comparer.Equals(item, WriteStatus))
                {
                    configuration.WriteStatusFile = true;
                    return(true);
                }

                if (Comparer.Equals(item, WriteStamp))
                {
                    configuration.WriteStampFile = true;
                    return(true);
                }

                if (Comparer.Equals(item, ProcessDebugSymbols))
                {
                    configuration.ProcessDebugSymbols = true;
                    return(true);
                }

                string key;
                string value;

                if (!ParseKeyValue(item, out key, out value))
                {
                    return(false);
                }

                if (Comparer.Equals(key, InputFile))
                {
                    configuration.InputFile = value;
                    return(true);
                }

                if (Comparer.Equals(key, OutputFile))
                {
                    configuration.OutputFile = value;
                    return(true);
                }

                if (Comparer.Equals(key, StrongNameKey))
                {
                    configuration.StrongNameKey = value;
                    return(true);
                }

                if (Comparer.Equals(key, ProjectType))
                {
                    configuration.ProjectType = value;
                    return(true);
                }

                if (Comparer.Equals(key, ReferencedAssembly))
                {
                    configuration.ReferencedAssemblies.Add(value);
                    return(true);
                }

                return(false);
            }
Exemple #25
0
 /// <summary>
 /// States whether this QueryItem is equal to another queryitem (same name).
 /// </summary>
 /// <param name="other">The other QueryItem.</param>
 /// <returns>Bool indication whether they are equal.</returns>
 public bool Equals(QueryItem other)
 {
     return(other != null && comparer.Equals(MeshName, other.MeshName));
 }
 public bool Equals(AssemblyShortName other) => StringComparer.Equals(Name, other.Name);
Exemple #27
0
        private static int Main(string[] args)
        {
            try
            {
                //parse command line
                var cmdParseResponse = ParseOptions(args);

                if (cmdParseResponse.Result == CompletionResult.Failure)
                {
                    Notify(cmdParseResponse.Messages);
                    return((int)ErrorLevel.OptionsParseFailure);
                }

                if (!Path.IsPathRooted(cmdParseResponse.Options.SolutionPath))
                {
                    cmdParseResponse.Options.SolutionPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), cmdParseResponse.Options.SolutionPath);
                }

                if (!File.Exists(cmdParseResponse.Options.SolutionPath))
                {
                    Notify($"Solution {cmdParseResponse.Options.SolutionPath} does not exist.");
                    return((int)ErrorLevel.SolutionDoesNotExist);
                }

                //build if we need to
                if (cmdParseResponse.Options.Build)
                {
                    var response = BuildSolutions(cmdParseResponse.Options, new ProjectCollection());
                    if (response.Result == CompletionResult.Failure)
                    {
                        response.Messages.Add("BUILD FAILED");
                        Notify(response.Messages);
                        return((int)ErrorLevel.BuildFailure);
                    }
                }

                //load the projects
                var loadProjectsResponse = LoadProjects(cmdParseResponse.Options);
                if (loadProjectsResponse.Result == CompletionResult.Failure)
                {
                    loadProjectsResponse.Messages.Add("Couldn't load the projects");
                    Notify(loadProjectsResponse.Messages);
                    return((int)ErrorLevel.ProjectLoadFailure);
                }

                #region PROCESS THE RULES

                var suppressTypesRegex = ConfigurationManager.AppSettings["RulesSuppressionRegex"];
                Notify("Creating analysis requests");
                var requests =
                    (from p in loadProjectsResponse.Projects
                     from i in p.Items
                     where _comparer.Equals(i.ItemType, "SqlTarget")
                     select new ReportRequest
                {
                    InputPath = FixPath(p.DirectoryPath, Path.GetFileName(i.EvaluatedInclude)),      //this needs the right configuration to be set when parsing the solution
                                                                                                     //InputPath = i.EvaluatedInclude, //would love to go straight off the path, but it does not point to the right location in some cases.
                    Solution = cmdParseResponse.Options.SolutionPath,
                    Suppress = p => Regex.IsMatch(p.Problem.RuleId, suppressTypesRegex, RegexOptions.IgnoreCase),
                    SuppressIssueTypes = p => Regex.IsMatch(p.RuleId, suppressTypesRegex, RegexOptions.IgnoreCase),
                    OutputDirectory = cmdParseResponse.Options.ReportDirectory,
                    ReportOutputType = cmdParseResponse.Options.ReportOutputType
                }).ToList();

                var factory = new ReportFactory();

                factory.Notify += Factory_Notify;

                requests.ForEach(r => factory.Create(r));

                return((int)ErrorLevel.Success);

                #endregion PROCESS THE RULES
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.ToString());
                Console.ResetColor();
                return((int)ErrorLevel.GeneralException);
            }
            finally
            {
                if (Debugger.IsAttached)
                {
                    Console.WriteLine("Done.");
                    Console.ReadKey();
                }
            }
        }
    // Main thread to transmit packets to target (reading .exe files).
    public static void Main(string[] args)
    {
        string exeFilename;

        if (args.Length != 1)
        {
            //Console.WriteLine("Usage: HostSerialLoader.exe <file.exe>");

            exeFilename = "C:/Users/Roman/Documents/School/TERM-8/Soen422/project test files/T01.exe";
        }
        else
        {
            exeFilename = args[0];
        }

//t        Console.WriteLine("file = {0}", exeFilename);

        // Get the executable code in a buffer to build packet(s).
        var buf = GetCode(exeFilename);


        byte[] sendDataPacketFile = new byte[buf.Length];

        for (int n = 0; n < buf.Length; ++n)
        {
            sendDataPacketFile[n] = buf[n];
        }


        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread         readThread     = new Thread(ReadByte);

        // Create a new SerialPort with the same Arduino Nano settings.
        _serialPort           = new SerialPort();
        _serialPort.PortName  = "COM3";
        _serialPort.BaudRate  = 9600;;
        _serialPort.Parity    = Parity.None;
        _serialPort.DataBits  = 8;
        _serialPort.StopBits  = StopBits.One;
        _serialPort.Handshake = Handshake.None;

        // Set the read/write timeouts
        _serialPort.ReadTimeout  = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        _run      = false;

        // Start a second thread to receive bytes from target.
        readThread.Start();

        Console.WriteLine("Host Serial Loader v1.0 (Cm Virtual Machine on Arduino Nano)");
        //Console.WriteLine("Usage: type 'p'(ping), 'd'(download), 'r'(run), and 'q' to quit.");

        string cmd;

        // Send cmd to target using a command prompt (for debugging purpose).

        while (_continue)
        {
            Console.WriteLine("Usage: type 'ping'(ping), 'status', 'd'(download), 'run', 'reset', and 'quit'");
            Console.Write("$ ");
            cmd = Console.ReadLine();

            if (stringComparer.Equals("quit", cmd))
            {
                _continue = false;
            }
            else if (stringComparer.Equals("ping", cmd))     // ping
            {
                Console.WriteLine("sending ping");
                _serialPort.Write(pingPacket, 0, 4);
            }
            else if (stringComparer.Equals("status", cmd))     // getStatus
            {
                _serialPort.Write(getStatusPacket, 0, 4);
            }
            else if (stringComparer.Equals("d", cmd))     // download (sendData - small pgm)
            {
                transmitCode(buf);
            }
            else if (stringComparer.Equals("reset", cmd))    // reset packet
            {
                _serialPort.Write(resetPacket, 0, 4);
            }
            else if (stringComparer.Equals("run", cmd))     // run
            {
                _serialPort.Write(runPacket, 0, 4);
                _run = true;
            }
            else
            {
                _serialPort.Write(pingPacketChecksumInvalid, 0, 4);
            }
        }

        Console.WriteLine("bye!");
        readThread.Join();
        _serialPort.Close();
    }
Exemple #29
0
 /// <summary>
 /// Checks that given <paramref name="input"/> is in a list of
 /// potential <paramref name="matches"/>.
 /// <remarks>Inspired by: <see href="http://stackoverflow.com/a/20644611/23199"/> </remarks>
 /// </summary>
 public static bool EqualsAny(this string input, StringComparer comparer, params string[] matches) =>
 matches.Any(x => comparer.Equals(x, input));
 public IEnumerable <ITypeDefinition> GetClasses(string nameSpace, StringComparer nameComparer)
 {
     return(types.Where(t => nameComparer.Equals(t.Namespace, nameSpace)));
 }
Exemple #31
0
 public static bool IsCSharpProject(string language)
 {
     return(LanguageNameComparer.Equals(language, ProjectLanguages.CSharp));
 }
        /// <summary>
        /// Calculates information about types and namespaces immediately contained within a namespace.
        /// </summary>
        /// <param name="namespaceNameLength">
        /// Length of the fully-qualified name of this namespace.
        /// </param>
        /// <param name="typesByNS">
        /// The sequence of groups of TypeDef row ids for types contained within the namespace, 
        /// recursively including those from nested namespaces. The row ids must be grouped by the 
        /// fully-qualified namespace name in case-sensitive manner. 
        /// Key of each IGrouping is a fully-qualified namespace name, which starts with the name of 
        /// this namespace. There could be multiple groups for each fully-qualified namespace name.
        /// 
        /// The groups must be sorted by the keys in a manner consistent with comparer passed in as
        /// nameComparer. Therefore, all types immediately contained within THIS namespace, if any, 
        /// must be in several IGrouping at the very beginning of the sequence.
        /// </param>
        /// <param name="nameComparer">
        /// Equality comparer to compare namespace names.
        /// </param>
        /// <param name="types">
        /// Output parameter, never null:
        /// A sequence of groups of TypeDef row ids for types immediately contained within this namespace.
        /// </param>
        /// <param name="namespaces">
        /// Output parameter, never null:
        /// A sequence with information about namespaces immediately contained within this namespace.
        /// For each pair:
        ///   Key - contains simple name of a child namespace.
        ///   Value – contains a sequence similar to the one passed to this function, but
        ///           calculated for the child namespace. 
        /// </param>
        /// <remarks></remarks>
        public static void GetInfoForImmediateNamespaceMembers(
            int namespaceNameLength,
            IEnumerable<IGrouping<string, TypeHandle>> typesByNS,
            StringComparer nameComparer,
            out IEnumerable<IGrouping<string, TypeHandle>> types,
            out IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeHandle>>>> namespaces)
        {
            Debug.Assert(typesByNS != null);
            Debug.Assert(namespaceNameLength >= 0);

            // A list of groups of TypeDef row ids for types immediately contained within this namespace.
            var nestedTypes = new List<IGrouping<string, TypeHandle>>();

            // A list accumulating information about namespaces immediately contained within this namespace.
            // For each pair:
            //   Key - contains simple name of a child namespace.
            //   Value – contains a sequence similar to the one passed to this function, but
            //           calculated for the child namespace. 
            var nestedNamespaces = new List<KeyValuePair<string, IEnumerable<IGrouping<string, TypeHandle>>>>();

            var enumerator = typesByNS.GetEnumerator();

            using (enumerator)
            {
                if (enumerator.MoveNext())
                {
                    var pair = enumerator.Current;

                    // Simple name of the last encountered child namespace.
                    string lastChildNamespaceName = string.Empty;

                    // A list accumulating information about types within the last encountered child namespace.
                    // The list is similar to the sequence passed to this function.
                    List<IGrouping<string, TypeHandle>> typesInLastChildNamespace = null;

                    // if there are any types in this namespace,
                    // they will be in the first several groups if if their key length 
                    // is equal to namespaceNameLength.
                    while (pair.Key.Length == namespaceNameLength)
                    {
                        nestedTypes.Add(pair);

                        if (!enumerator.MoveNext())
                        {
                            goto DoneWithSequence;
                        }

                        pair = enumerator.Current;
                    }

                    // Account for the dot following THIS namespace name.
                    if (namespaceNameLength != 0)
                    {
                        namespaceNameLength++;
                    }

                    do
                    {
                        pair = enumerator.Current;

                        string childNamespaceName = ExtractSimpleNameOfChildNamespace(namespaceNameLength, pair.Key);

                        if (nameComparer.Equals(childNamespaceName, lastChildNamespaceName))
                        {
                            // We are still processing the same child namespace
                            typesInLastChildNamespace.Add(pair);
                        }
                        else
                        {
                            // This is a new child namespace

                            // Preserve information about previous child namespace.
                            if (typesInLastChildNamespace != null)
                            {
                                Debug.Assert(typesInLastChildNamespace.Count != 0);
                                nestedNamespaces.Add(
                                    new KeyValuePair<string, IEnumerable<IGrouping<string, TypeHandle>>>(
                                        lastChildNamespaceName, typesInLastChildNamespace));
                            }

                            typesInLastChildNamespace = new List<IGrouping<string, TypeHandle>>();
                            lastChildNamespaceName = childNamespaceName;

                            typesInLastChildNamespace.Add(pair);
                        }
                    }
                    while (enumerator.MoveNext());

                    // Preserve information about last child namespace.
                    if (typesInLastChildNamespace != null)
                    {
                        Debug.Assert(typesInLastChildNamespace.Count != 0);
                        nestedNamespaces.Add(
                            new KeyValuePair<string, IEnumerable<IGrouping<string, TypeHandle>>>(
                                lastChildNamespaceName, typesInLastChildNamespace));
                    }

                DoneWithSequence:
                /*empty statement*/
                    ;
                }
            } // using

            types = nestedTypes;
            namespaces = nestedNamespaces;

            Debug.Assert(types != null);
            Debug.Assert(namespaces != null);
        }
Exemple #33
0
 public bool SubsectionNameEquals(string name)
 => SubsectionNameComparer.Equals(SubsectionName, name);
Exemple #34
0
 public bool Equals(string x, string y)
 {
     return(_baseComparer.Equals(Adjust(x), Adjust(y)));
 }
Exemple #35
0
 public bool VariableNameEquals(string name)
 => VariableNameComparer.Equals(VariableName, name);
Exemple #36
0
        /// <summary>
        /// Determines if the candidate value matches the target value specified using the data compare operator
        /// </summary>
        /// <param name="candidateValue">The candidate value to compare</param>
        /// <param name="targetValue">The target value to compare against</param>
        /// <param name="compareOperator">The data comparer operator</param>
        /// <returns>True, if the candidate value matches the target value using the comparison operator</returns>
        public bool IsMatch
        (
            string candidateValue,
            string targetValue,
            DataCompareOperator compareOperator
        )
        {
            if (String.IsNullOrEmpty(candidateValue) || String.IsNullOrEmpty(targetValue))
            {
                return(false);
            }

            switch (compareOperator)
            {
            case DataCompareOperator.Equals:
                return(_comparer.Equals(candidateValue, targetValue));

            case DataCompareOperator.NotEqual:
                return(false == _comparer.Equals(candidateValue, targetValue));

            case DataCompareOperator.GreaterThan:
            case DataCompareOperator.GreaterThanEqual:
            case DataCompareOperator.LessThan:
            case DataCompareOperator.LessThanEqual:
                if (candidateValue.IsNumeric() && targetValue.IsNumeric())
                {
                    var candidateNumber = Double.Parse(candidateValue);
                    var targetNumber    = Double.Parse(targetValue);

                    switch (compareOperator)
                    {
                    case DataCompareOperator.GreaterThan:
                        return(candidateNumber > targetNumber);

                    case DataCompareOperator.GreaterThanEqual:
                        return(candidateNumber >= targetNumber);

                    case DataCompareOperator.LessThan:
                        return(candidateNumber < targetNumber);

                    case DataCompareOperator.LessThanEqual:
                        return(candidateNumber <= targetNumber);

                    default:
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }

            case DataCompareOperator.Contains:
                return(candidateValue.Contains(targetValue));

            case DataCompareOperator.DoesNotContain:
                return(false == candidateValue.Contains(targetValue));

            case DataCompareOperator.BeginsWith:
                return(candidateValue.StartsWith(targetValue));

            case DataCompareOperator.DoesNotBeginWith:
                return(false == candidateValue.StartsWith(targetValue));

            case DataCompareOperator.EndsWith:
                return(candidateValue.EndsWith(targetValue));

            case DataCompareOperator.DoesNotEndWith:
                return(false == candidateValue.EndsWith(targetValue));

            default:
                return(false);
            }
        }
		public IEnumerable<ITypeDefinition> GetClasses(string nameSpace, StringComparer nameComparer)
		{
			foreach (TypeDefinition cecilType in module.Types) {
				if (nameComparer.Equals(nameSpace, cecilType.Namespace))
					yield return GetClass(cecilType);
			}
		}
Exemple #38
0
 public static bool MatchName(this string value, string shortName, string longName, StringComparer comparer)
 {
     return value.Length == 1
        ? comparer.Equals(value, shortName)
        : comparer.Equals(value, longName);
 }
        /// <summary>
        /// Returns a copy of the <paramref name="value"/> string with snake case format, where punctuation is removed,
        /// and spaces are replaced by single underscores. e.g. "The quick brown fox" is converted into "the_quick_brown_fox".
        /// See <a href="https://en.wikipedia.org/wiki/Snake_case">wikipedia#snake</a>. See also
        /// <a href="https://en.wikipedia.org/wiki/Letter_case#Title_Case">wikipedia#title</a>.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="cultureInfo">The culture information settings.</param>
        /// <returns>
        /// Returns a copy of the <paramref name="value"/> string with with snake case format, where punctuation is removed,
        /// and spaces are replaced by single underscores.
        /// </returns>
        public string Convert(string value, CultureInfo cultureInfo = null)
        {
            // Validate.
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (Comparer.Equals(value, string.Empty))
            {
                return(string.Empty);
            }
            if (cultureInfo == null)
            {
                cultureInfo = CultureInfo.CurrentCulture;
            }

            // Remove all the does not match pattern, punctuation, etc.
            value = value.ToRegexReplaceString(Replace);

            // Validate after mutation.
            if (string.IsNullOrEmpty(value))
            {
                return(value);
            }
            if (value.Length == 1)
            {
                return(value.ToLower(cultureInfo));
            }

            // Process words by splitting on underscores or whitespace.
            var words = value.Split(new[] { '_', ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            // Speed performance consideration if it ends up that there is an underscore every other character.
            var wordBuilder = new StringBuilder(value.Length, value.Length * 2);
            // The isFirstUpperSet variable is a global word short circuit so we can let the second letter being
            // processed know, if the first letter encountered got capitalized. This value is reset per every new
            // word in the phrase. However, the first letter encountered overall should be lowercase, if not
            // proceeded by a number.
            var isFirstUpperSet = false;

            // For each split word.
            foreach (var word in words)
            {
                // Speed performance consideration if it ends up that there is an underscore every other character.
                var subWordBuilder = new StringBuilder(word.Length * 2);
                // For each word character.
                foreach (var wordCharacter in word)
                {
                    // Determine if it is upper case.
                    var isUpper = char.IsUpper(wordCharacter);
                    if (isUpper)
                    {
                        // Check our global lookahead flag.
                        if (isFirstUpperSet)
                        {
                            // Append lowercase letter and move on.
                            subWordBuilder.Append(char.ToLower(wordCharacter, cultureInfo));
                            continue;
                        }

                        // Set our global lookahead flag to true.
                        isFirstUpperSet = true;
                        // If it is not the first character in the word, append a snake bump.
                        if (subWordBuilder.Length > 0)
                        {
                            subWordBuilder.Append("_");
                        }
                        // Append lowercase letter and move on.
                        subWordBuilder.Append(char.ToLower(wordCharacter, cultureInfo));
                        continue;
                    }

                    // Determine if it is lower case.
                    var isLower = char.IsLower(wordCharacter);
                    if (isLower)
                    {
                        // Check our global lookahead flag.
                        if (isFirstUpperSet)
                        {
                            // Set our global lookahead flag to false.
                            isFirstUpperSet = false;
                            // This is an existing lowercase letter or digit, just append it and move on,
                            // and set our global lookahead flag to false.
                            subWordBuilder.Append(wordCharacter);
                            continue;
                        }

                        // If it is the first character for the word, and no existing numbers have been placed,
                        // it should be a lowercase letter.
                        if (subWordBuilder.Length == 0)
                        {
                            // Set our global lookahead flag to true.
                            isFirstUpperSet = true;
                        }

                        // Append lowercase letter and move on.
                        subWordBuilder.Append(wordCharacter);
                        continue;
                    }

                    var isNumber = char.IsNumber(wordCharacter);
                    if (isNumber)
                    {
                        // This is an existing digit, just append it and move on, and set our global lookahead flag to false.
                        if (isFirstUpperSet)
                        {
                            isFirstUpperSet = false;
                        }
                        subWordBuilder.Append(wordCharacter);
                        continue;
                    }

                    // We hit an invalid character that does not fit in this scheme, and if they are the first characters
                    // encountered just skip them, otherwise we will need to set our global lookahead flag to false,
                    // as we will need to capitalize the next lowercase value.
                    if (subWordBuilder.Length > 0 && isFirstUpperSet)
                    {
                        isFirstUpperSet = false;
                    }
                }

                // If no sub-word could be built, move on.
                if (subWordBuilder.Length == 0)
                {
                    continue;
                }
                // A word could be built, append a new Snake bump, and append the sub-word.
                if (wordBuilder.Length > 0)
                {
                    wordBuilder.Append('_');
                }
                wordBuilder.Append(subWordBuilder);
            }

            // Return built word.
            var fullWord = wordBuilder.ToString();

            return(fullWord);
        }
		public string GetNamespace(string nameSpace, StringComparer nameComparer)
		{
			foreach (string ns in namespaces) {
				if (nameComparer.Equals(ns, nameSpace))
					return ns;
			}
			return null;
		}
Exemple #41
0
 bool IEqualityComparer <MetadataMember> .Equals(MetadataMember x, MetadataMember y)
 {
     Debug.Assert(x != null && y != null, "metadata members must not be null");
     return(_stringComparer.Equals(x.Name, y.Name));
 }
Exemple #42
0
 protected override bool CompareKeyToValue(string key, ModuleData value)
 {
     return(_comparer.Equals(key, value.SimpleName));
 }
Exemple #43
0
 public bool IsSameSignature(PartialMethodInfo other, StringComparer nameComparer)
 {
     return(nameComparer.Equals(this.Name, other.Name) &&
            this.TypeParameterCount == other.TypeParameterCount &&
            ParameterListComparer.Instance.Equals(this.Parameters, other.Parameters));
 }
Exemple #44
0
 /// <summary>
 /// Checks that given <paramref name="input"/> matches any of the potential matches.
 /// Inspired by: http://stackoverflow.com/a/20644611/23199
 /// </summary>
 public static bool EqualsAny(this string input, StringComparer comparer, string match1, string match2, string match3) =>
 comparer.Equals(input, match1) || comparer.Equals(input, match2) || comparer.Equals(input, match3);
 public static bool operator ==(GitInstallation install1, GitInstallation install2)
 {
     return(install1.Version == install2.Version &&
            PathComparer.Equals(install1.Path, install2.Path));
 }
 public bool Equals(Entry other)
 {
     return(KeyComparer.Equals(_key, other._key) &&
            ValueComparer.Equals(_value, other._value));
 }
 public bool Equals(LocalRootSegment?x, LocalRootSegment?y) => stringComparer.Equals(x?.Token, y?.Token);
		static bool IsSameType(TypeReference a, TypeReference b, StringComparer nameComparer)
		{
			ArrayTypeReference arr1 = a as ArrayTypeReference;
			ArrayTypeReference arr2 = b as ArrayTypeReference;
			SimpleTypeReference s1 = a as SimpleTypeReference;
			SimpleTypeReference s2 = b as SimpleTypeReference;
			if (arr1 != null && arr2 != null) {
				if (arr1.Rank.Value != arr2.Rank.Value)
					return false;
				return IsSameType(arr1.ElementType, arr2.ElementType, nameComparer);
			} else if (s1 != null && s2 != null) {
				return nameComparer.Equals(s1.Name, s2.Name);
			} else {
				return false;
			}
		}
Exemple #49
0
        /// <summary>
        /// By giving XML namespace finds the XSLT that transforms CurcuitProject of given version to the next version
        /// </summary>
        /// <param name="ns">XML namespace that defines the project version</param>
        /// <returns>
        /// String.Empty -- when ns is for current version and no transformation is required
        /// XSLT string  -- when ns is for known previous version
        /// null         -- when ns is unknown
        /// </returns>
        private static string FindTransformation(string ns)
        {
            StringComparer cmp = StringComparer.OrdinalIgnoreCase;

            if (cmp.Equals(ns, CircuitProject.PersistenceNamespace))
            {
                return(string.Empty);
            }

            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.9/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_9);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.8/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_8);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.7/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_7);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.6/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_6);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.5/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_5);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.4/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_4);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.3/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_3);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.2/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_2);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/2.0.0.1/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_2_0_0_1);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/1.0.0.3/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_1_0_0_3);
            }
            if (cmp.Equals(ns, "http://LogicCircuit.net/1.0.0.2/CircuitProject.xsd"))
            {
                return(Schema.ConvertFrom_1_0_0_2);
            }

            return(null);
        }
			public WholeWordTextFinder(string word, StringComparer nameComparer)
			{
				if (word == null) word = string.Empty;
				
				caseInsensitive = nameComparer.Equals("a", "A");
				if (caseInsensitive)
					this.searchedText = word.ToLowerInvariant();
				else
					this.searchedText = word;
			}
Exemple #51
0
    public static void Main()
    {
        string         name;
        string         message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread         readThread     = new Thread(Read);

        Thread readThreadDestination = new Thread(ReadDestination);


        // Create a new SerialPort object with default settings.
        _sourcePortPair = new SerialPort();

        Console.Write("*********************************************************************************");
        Console.Write("SOURCE PAIR PORT DEFITIONS");
        Console.Write("*********************************************************************************");

        // Allow the user to set the appropriate properties.
        _sourcePortPair.PortName  = SetPortName(_sourcePortPair.PortName);
        _sourcePortPair.BaudRate  = SetPortBaudRate(_sourcePortPair.BaudRate);
        _sourcePortPair.Parity    = SetPortParity(_sourcePortPair.Parity);
        _sourcePortPair.DataBits  = SetPortDataBits(_sourcePortPair.DataBits);
        _sourcePortPair.StopBits  = SetPortStopBits(_sourcePortPair.StopBits);
        _sourcePortPair.Handshake = SetPortHandshake(_sourcePortPair.Handshake);

        // Set the read/write timeouts
        _sourcePortPair.ReadTimeout  = 5000;
        _sourcePortPair.WriteTimeout = 5000;

        _sourcePortPair.Open();


        Console.WriteLine("********************************************************************************");
        Console.WriteLine("DESTINATION PORT DEFITIONS");
        Console.WriteLine("********************************************************************************");

        _destinationPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _destinationPort.PortName = SetPortName(_destinationPort.PortName);
        if (_destinationPort.PortName != "COMX")
        {
            _destinationPort.BaudRate  = SetPortBaudRate(_destinationPort.BaudRate);
            _destinationPort.Parity    = SetPortParity(_destinationPort.Parity);
            _destinationPort.DataBits  = SetPortDataBits(_destinationPort.DataBits);
            _destinationPort.StopBits  = SetPortStopBits(_destinationPort.StopBits);
            _destinationPort.Handshake = SetPortHandshake(_destinationPort.Handshake);
            _destinationPort.Open();
        }


        _continue = true;
        if (_destinationPort.PortName != "COMX")
        {
            readThreadDestination.Start();
        }
        readThread.Start();



        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            Console.WriteLine("Send Message to <{0}>: ", _sourcePortPair.PortName);
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _sourcePortPair.WriteLine(
                    String.Format("{1}", _sourcePortPair.PortName, message));
            }
        }

        readThread.Join();
        _sourcePortPair.Close();
    }
Exemple #52
0
        /// <summary>
        /// Calculates information about types and namespaces immediately contained within a namespace.
        /// </summary>
        /// <param name="namespaceNameLength">
        /// Length of the fully-qualified name of this namespace.
        /// </param>
        /// <param name="typesByNS">
        /// The sequence of groups of TypeDef row ids for types contained within the namespace,
        /// recursively including those from nested namespaces. The row ids must be grouped by the
        /// fully-qualified namespace name in case-sensitive manner.
        /// Key of each IGrouping is a fully-qualified namespace name, which starts with the name of
        /// this namespace. There could be multiple groups for each fully-qualified namespace name.
        ///
        /// The groups must be sorted by the keys in a manner consistent with comparer passed in as
        /// nameComparer. Therefore, all types immediately contained within THIS namespace, if any,
        /// must be in several IGrouping at the very beginning of the sequence.
        /// </param>
        /// <param name="nameComparer">
        /// Equality comparer to compare namespace names.
        /// </param>
        /// <param name="types">
        /// Output parameter, never null:
        /// A sequence of groups of TypeDef row ids for types immediately contained within this namespace.
        /// </param>
        /// <param name="namespaces">
        /// Output parameter, never null:
        /// A sequence with information about namespaces immediately contained within this namespace.
        /// For each pair:
        ///   Key - contains simple name of a child namespace.
        ///   Value – contains a sequence similar to the one passed to this function, but
        ///           calculated for the child namespace.
        /// </param>
        /// <remarks></remarks>
        public static void GetInfoForImmediateNamespaceMembers(
            int namespaceNameLength,
            IEnumerable <IGrouping <string, TypeHandle> > typesByNS,
            StringComparer nameComparer,
            out IEnumerable <IGrouping <string, TypeHandle> > types,
            out IEnumerable <KeyValuePair <string, IEnumerable <IGrouping <string, TypeHandle> > > > namespaces)
        {
            Debug.Assert(typesByNS != null);
            Debug.Assert(namespaceNameLength >= 0);

            // A list of groups of TypeDef row ids for types immediately contained within this namespace.
            var nestedTypes = new List <IGrouping <string, TypeHandle> >();

            // A list accumulating information about namespaces immediately contained within this namespace.
            // For each pair:
            //   Key - contains simple name of a child namespace.
            //   Value – contains a sequence similar to the one passed to this function, but
            //           calculated for the child namespace.
            var nestedNamespaces = new List <KeyValuePair <string, IEnumerable <IGrouping <string, TypeHandle> > > >();

            var enumerator = typesByNS.GetEnumerator();

            using (enumerator)
            {
                if (enumerator.MoveNext())
                {
                    var pair = enumerator.Current;

                    // Simple name of the last encountered child namespace.
                    string lastChildNamespaceName = string.Empty;

                    // A list accumulating information about types within the last encountered child namespace.
                    // The list is similar to the sequence passed to this function.
                    List <IGrouping <string, TypeHandle> > typesInLastChildNamespace = null;

                    // if there are any types in this namespace,
                    // they will be in the first several groups if if their key length
                    // is equal to namespaceNameLength.
                    while (pair.Key.Length == namespaceNameLength)
                    {
                        nestedTypes.Add(pair);

                        if (!enumerator.MoveNext())
                        {
                            goto DoneWithSequence;
                        }

                        pair = enumerator.Current;
                    }

                    // Account for the dot following THIS namespace name.
                    if (namespaceNameLength != 0)
                    {
                        namespaceNameLength++;
                    }

                    do
                    {
                        pair = enumerator.Current;

                        string childNamespaceName = ExtractSimpleNameOfChildNamespace(namespaceNameLength, pair.Key);

                        if (nameComparer.Equals(childNamespaceName, lastChildNamespaceName))
                        {
                            // We are still processing the same child namespace
                            typesInLastChildNamespace.Add(pair);
                        }
                        else
                        {
                            // This is a new child namespace

                            // Preserve information about previous child namespace.
                            if (typesInLastChildNamespace != null)
                            {
                                Debug.Assert(typesInLastChildNamespace.Count != 0);
                                nestedNamespaces.Add(
                                    new KeyValuePair <string, IEnumerable <IGrouping <string, TypeHandle> > >(
                                        lastChildNamespaceName, typesInLastChildNamespace));
                            }

                            typesInLastChildNamespace = new List <IGrouping <string, TypeHandle> >();
                            lastChildNamespaceName    = childNamespaceName;

                            typesInLastChildNamespace.Add(pair);
                        }
                    }while (enumerator.MoveNext());

                    // Preserve information about last child namespace.
                    if (typesInLastChildNamespace != null)
                    {
                        Debug.Assert(typesInLastChildNamespace.Count != 0);
                        nestedNamespaces.Add(
                            new KeyValuePair <string, IEnumerable <IGrouping <string, TypeHandle> > >(
                                lastChildNamespaceName, typesInLastChildNamespace));
                    }

DoneWithSequence:
                    /*empty statement*/
                    ;
                }
            } // using

            types      = nestedTypes;
            namespaces = nestedNamespaces;

            Debug.Assert(types != null);
            Debug.Assert(namespaces != null);
        }
		public ITypeDefinition GetClass(string nameSpace, string name, int typeParameterCount, StringComparer nameComparer)
		{
			if (typeParameterCount > 0)
				name = name + "`" + typeParameterCount.ToString();
			if (nameComparer == StringComparer.Ordinal) {
				TypeDefinition cecilType = module.GetType(nameSpace, name);
				if (cecilType != null)
					return GetClass(cecilType);
				else
					return null;
			}
			foreach (TypeDefinition cecilType in module.Types) {
				if (nameComparer.Equals(name, cecilType.Name)
				    && nameComparer.Equals(nameSpace, cecilType.Namespace)
				    && cecilType.GenericParameters.Count == typeParameterCount)
				{
					return GetClass(cecilType);
				}
			}
			return null;
		}