예제 #1
0
파일: Antipatterns.cs 프로젝트: sestoft/C5
 private static void DontModifyInner()
 {
     Console.WriteLine("\nMake a snapshot and add it to outer");
     ICollection<ISequenced<int>> outer = new HashSet<ISequenced<int>>();
     for (int i = 0; i < 100; i++)
     {
         ISequenced<int> inner = new TreeSet<int>();
         inner.Add(i); inner.Add(i + 1);
         outer.Add(inner);
     }
     IPersistentSorted<int>
       inner1 = new TreeSet<int>(),
       inner2 = new TreeSet<int>(),
       inner3 = new TreeSet<int>();
     inner1.AddAll(new[] { 2, 3, 5, 7, 11 });
     inner2.AddAll(inner1); inner2.Add(13);
     inner3.AddAll(inner1);
     // Take a snapshot and add it to outer:
     outer.Add(inner1.Snapshot());
     Console.WriteLine("inner1 in outer: {0}", outer.Contains(inner1));
     Console.WriteLine("inner2 in outer: {0}", outer.Contains(inner2));
     Console.WriteLine("inner3 in outer: {0}", outer.Contains(inner3));
     inner1.Add(13);
     Console.WriteLine("inner1 equals inner2: {0}",
                       outer.EqualityComparer.Equals(inner1, inner2));
     Console.WriteLine("inner1 equals inner3: {0}",
                       outer.EqualityComparer.Equals(inner1, inner3));
     Console.WriteLine("inner1 in outer: {0}", outer.Contains(inner1));
     Console.WriteLine("inner2 in outer: {0}", outer.Contains(inner2));
     Console.WriteLine("inner3 in outer: {0}", outer.Contains(inner3));
     Console.WriteLine("outer.Count: {0}", outer.Count);
 }
예제 #2
0
        // Anti-pattern: modifying an inner collection while it is a
        // member of an outer one may cause it to be lost from the outer
        // collection.

        private static void ModifyInner()
        {
            Console.WriteLine("\nAnti-pattern: Add to outer, modify, lose");
            ICollection<ISequenced<int>> outer = new HashSet<ISequenced<int>>();
            for (int i = 0; i < 100; i++)
            {
                ISequenced<int> inner = new TreeSet<int>();
                inner.Add(i); inner.Add(i + 1);
                outer.Add(inner);
            }
            ISequenced<int>
              inner1 = new TreeSet<int>(),
              inner2 = new TreeSet<int>(),
              inner3 = new TreeSet<int>();
            inner1.AddAll(new[] { 2, 3, 5, 7, 11 });
            inner2.AddAll(inner1); inner2.Add(13);
            inner3.AddAll(inner1);
            outer.Add(inner1);
            Console.WriteLine("inner1 in outer: {0}", outer.Contains(inner1));
            Console.WriteLine("inner2 in outer: {0}", outer.Contains(inner2));
            Console.WriteLine("inner3 in outer: {0}", outer.Contains(inner3));
            inner1.Add(13);
            Console.WriteLine("inner1 equals inner2: {0}",
                              outer.EqualityComparer.Equals(inner1, inner2));
            Console.WriteLine("inner1 equals inner3: {0}",
                              outer.EqualityComparer.Equals(inner1, inner3));
            Console.WriteLine("inner1 in outer: {0}", outer.Contains(inner1));
            Console.WriteLine("inner2 in outer: {0}", outer.Contains(inner2));
            Console.WriteLine("inner3 in outer: {0}", outer.Contains(inner3));
            Console.WriteLine("outer.Count: {0}", outer.Count);
        }
예제 #3
0
        public void testCollection() 
        {
		    List<String> data = new TreeSet<String>();
		    data.Add("foo");
		    data.Add("bar");
		    data.Add("baz");
		    Assert.AreEqual(TEST_DATA, IteratorUtils.iterableToList(data));
	    }
예제 #4
0
        public IGeometry Union()
        {
            PointLocator locater = new PointLocator();

            // use a set to eliminate duplicates, as required for union
#if Goletas
            HashSet<ICoordinate> exteriorCoords = new HashSet<ICoordinate>();
#else
            TreeSet exteriorCoords = new TreeSet();
#endif

            foreach (IPoint point in PointExtracter.GetPoints(_pointGeom))
            {
                ICoordinate coord = point.Coordinate;
                Locations loc = locater.Locate(coord, _otherGeom);

                if (loc == Locations.Exterior)
                {
                    exteriorCoords.Add(coord);
                }
            }

            // if no points are in exterior, return the other geom
            if (exteriorCoords.Count == 0)
            {
                return _otherGeom;
            }

            // make a puntal geometry of appropriate size
            IGeometry ptComp = null;
            ICoordinateSequence coords = _geomFact.CoordinateSequenceFactory.Create(exteriorCoords.ToArray());
            ptComp = coords.Count == 1 ? (IGeometry)_geomFact.CreatePoint(coords.GetCoordinate(0)) : _geomFact.CreateMultiPoint(coords);

            // add point component to the other geometry
            return GeometryCombiner.Combine(ptComp, _otherGeom);
        }
예제 #5
0
 public static void IntSetSet()
 {
     ICollection<ISequenced<int>> outer = new HashSet<ISequenced<int>>();
     int[] ss = { 2, 3, 5, 7 };
     TreeSet<int> inner = new TreeSet<int>();
     outer.Add(inner.Snapshot());
     foreach (int i in ss)
     {
         inner.Add(i);
         outer.Add(inner.Snapshot());
     }
     foreach (ISequenced<int> s in outer)
     {
         int sum = 0;
         s.Apply(delegate(int x) { sum += x; });
         Console.WriteLine("Set has {0} elements and sum {1}", s.Count, sum);
     }
 }
예제 #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Option"/> class.
        /// </summary>
        /// <param name="attribute">The attribute describing this option.</param>
        /// <param name="memberInfo">The <see cref="MemberInfo"/> object pointing to the member to which the attribute was applied.</param>
        /// <param name="cmdLineObject">The command line manager object.</param>
        /// <param name="optionGroups">A complete list of all available option groups.</param>
        /// <param name="numberFormatInfo">The number format info to use for parsing numerical arguments.</param>
        public Option(CommandLineOptionAttribute attribute, MemberInfo memberInfo, object cmdLineObject, 
            ICollection<OptionGroup> optionGroups, NumberFormatInfo numberFormatInfo)
        {            
            mObject = cmdLineObject;
            mMember = memberInfo;
            mUsage = attribute.BoolFunction;
            mDescription = attribute.Description;
            mNumberFormatInfo = numberFormatInfo ?? CultureInfo.CurrentCulture.NumberFormat;
            mDefaultValue = attribute.DefaultAssignmentValue;
            mMinValue = attribute.MinValue;
            mMaxValue = attribute.MaxValue;

            // Check the validity of the member for which this attribute was defined
            switch (memberInfo.MemberType)
            {
                case MemberTypes.Field:
                    FieldInfo fieldInfo = (FieldInfo)memberInfo;
                    if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral)
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal field for this attribute; field must be writeable");

                    mOptionType = fieldInfo.FieldType;
                    break;
                case MemberTypes.Method:
                    MethodInfo method = (MethodInfo)memberInfo;
                    ParameterInfo[] parameters = method.GetParameters();

                    if (parameters.Length != 1)
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal method for this attribute; the method must accept exactly one parameter");

                    if (parameters[0].IsOut)
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal method for this attribute; the parameter of the method must not be an out parameter");

                    if (IsArray(parameters[0].ParameterType) || IsCollectionType(parameters[0].ParameterType))
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal method for this attribute; the parameter of the method must be a non-array and non-collection type");

                    mOptionType = parameters[0].ParameterType;
                    break;
                case MemberTypes.Property:
                    PropertyInfo propInfo = (PropertyInfo)memberInfo;

                    if (!propInfo.CanWrite && !IsCollectionType(propInfo.PropertyType))
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal property for this attribute; property for non-collection type must be writable");

                    if (!propInfo.CanRead && IsCollectionType(propInfo.PropertyType))
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal property for this attribute; property for collection type must be readable");

                    if (!(propInfo.CanRead && propInfo.CanWrite) && IsArray(propInfo.PropertyType))
                        throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                            "Illegal property for this attribute; property representing array type must be both readable and writeable");

                    mOptionType = propInfo.PropertyType;
                    break;
                default:
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                        "Illegal member for this attribute; member must be a property, method (accepting one parameter) or a field");
            }

            mMinOccurs = attribute.MinOccurs;

            // MaxOccurs does not have a default value (since this is different for various types), so we set it here.
            if (!attribute.IsMaxOccursSet)
            {
                // Use default setting for MaxOccurs
                if (IsArray(mOptionType) || IsCollectionType(mOptionType))
                    mMaxOccurs = 0; // Unlimited 
                else
                    mMaxOccurs = 1;
            }
            else
            {
                mMaxOccurs = attribute.MaxOccurs;
            }

            if (mMinOccurs > mMaxOccurs && mMaxOccurs > 0)
                throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo, 
                    String.Format(CultureInfo.CurrentUICulture, "MinOccurs ({0}) must not be larger than MaxOccurs ({1})", mMinOccurs, mMaxOccurs));

            if (mMaxOccurs != 1 && !(IsArray(mOptionType) || IsCollectionType(mOptionType)) && mMember.MemberType != MemberTypes.Method)
                throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                    "Invalid cardinality for member; MaxOccurs must be equal to one (1) for any non-array or non-collection type");

            CommandLineManagerAttribute objectAttr = (CommandLineManagerAttribute)Attribute.GetCustomAttribute(mObject.GetType(), typeof(CommandLineManagerAttribute));
            if (objectAttr == null)
                throw new AttributeException(String.Format(CultureInfo.CurrentUICulture, 
                    "Class {0} contains a CommandLineOptionAttribute, but does not have the attribute CommandLineObjectAttribute", mObject.GetType().FullName));


            // Assign the name of this option from the member itself if no name is explicitly provided 
            if (attribute.Name == null)
            {
                mName = memberInfo.Name;
            }
            else
            {
                mName = attribute.Name;
            }

            // Find the group (if any) that this option belongs to in the list of available option groups
            if (attribute.GroupId != null)
            {
                if (!optionGroups.Find(new Fun<OptionGroup, bool>(
                    delegate(OptionGroup searchGroup)
                    {
                        return attribute.GroupId.Equals(searchGroup.Id);
                    }), out mGroup)) 
                {
                    throw new LogicException(String.Format(CultureInfo.CurrentUICulture, "Undefined group {0} referenced from  member {1} in {2}", attribute.GroupId, memberInfo.Name, cmdLineObject.GetType().FullName));
                }
                mGroup.Options.Add(mName, this);
            }

            // Recursively find out if this option requires explicit assignment
            if (attribute.DoesRequireExplicitAssignment.HasValue)
            {
                mRequireExplicitAssignment = attribute.DoesRequireExplicitAssignment.Value;
            }
            else if (mGroup != null)
            {
                mRequireExplicitAssignment = mGroup.RequireExplicitAssignment;
            }
            else
            {
                mRequireExplicitAssignment = objectAttr.RequireExplicitAssignment;
            }

            // Make sure the type of the field, property or method is supported
            if (!IsTypeSupported(mOptionType))
                throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                    "Unsupported type for command line option.");


            // Make sure MinValue and MaxValue is not specified for any non-numerical type.
            if (mMinValue != null || mMaxValue != null)
            {
                if (!IsNumericalType)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                        "MinValue and MaxValue must not be specified for a non-numerical type");
                }
                else if (!mMinValue.GetType().IsAssignableFrom(GetBaseType(mOptionType)))
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                        "Illegal value for MinValue or MaxValue, not the same type as option");
                }
            }

            // Some special checks for numerical types
            if (IsNumericalType)
            {
                // Assign the default MinValue if it was not set and this is a numerical type
                if (IsNumericalType && mMinValue == null)
                {
                    mMinValue = GetBaseType(mOptionType).GetField("MinValue", BindingFlags.Static | BindingFlags.Public).GetValue(null);
                }

                // Assign the defaul MaxValue if it was not set and this is a numerical type
                if (IsNumericalType && mMaxValue == null)
                {
                    mMaxValue = GetBaseType(mOptionType).GetField("MaxValue", BindingFlags.Static | BindingFlags.Public).GetValue(null);
                }

                // Check that MinValue <= MaxValue
                if (IsNumericalType && ((IComparable)MinValue).CompareTo(MaxValue) > 0)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                        "MinValue must not be greater than MaxValue");
                }
            }

            // Check that the DefaultValue is not set if the option does not require explicit assignment. 
            // If it were allowed, it would be ambiguos for an option separated from a value by a white space character
            // since we wouldn't know whether that would set the default value or assign it to the following value.
            if (mDefaultValue != null && !mRequireExplicitAssignment)
            {
                throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                    "DefaultValue must not be specified when RequireExplicitAssignment is set to false");
            }

            // Check that the type of any set default value matches that of this option, or is string, and
            // convert it to the type of this option.
            if (mDefaultValue != null)
            {
                if (mDefaultValue.GetType() == typeof(string))
                {
                    try
                    {
                        mDefaultValue = GetCheckedValueForSetOperation(mDefaultValue);
                    }
                    catch (OverflowException)
                    {
                        throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                            "DefaultValue was less than MinValue or greater than MaxValue for this option");
                    }
                    catch (FormatException)
                    {
                        throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                            "DefaultValue was not specified in the correct format for the type of this option");
                    }
                }
                else if (GetBaseType(mOptionType) != mDefaultValue.GetType())
                {
                    try
                    {
                        mDefaultValue = Convert.ChangeType(mDefaultValue, GetBaseType(mOptionType), mNumberFormatInfo);
                    }
                    catch (InvalidCastException)
                    {
                        throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                            "The type of the DefaultValue specified is not compatible with the type of the member to which this attribute applies");
                    }
                }
            }            

            // If this is an enum, check that it doesn't have members only distinguishable by case, and
            // add the members to the mEnumerationValues set for speedy access when checking values assigned 
            // to this member.
            Type type = GetBaseType(mOptionType);
            if (type.IsEnum)
            {
                mEnumerationValues = new TreeSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (FieldInfo field in type.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        if (mEnumerationValues.Contains(field.Name))
                        {
                            throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                "This enumeration is not allowed as a command line option since it contains fields that differ only by case");
                        }
                        mEnumerationValues.Add(field.Name);
                    }
                }                
            }
        }
예제 #7
0
            private void UpdateNextGroup(int topN, ShardIter <T> shard)
            {
                while (shard.iter.MoveNext())
                {
                    ISearchGroup <T> group       = shard.Next();
                    MergedGroup <T>  mergedGroup = groupsSeen.ContainsKey(group.GroupValue) ? groupsSeen[group.GroupValue] : null;
                    bool             isNew       = mergedGroup == null;
                    //System.out.println("    next group=" + (group.groupValue == null ? "null" : ((BytesRef) group.groupValue).utf8ToString()) + " sort=" + Arrays.toString(group.sortValues));

                    if (isNew)
                    {
                        // Start a new group:
                        //System.out.println("      new");
                        mergedGroup = new MergedGroup <T>(group.GroupValue);
                        mergedGroup.minShardIndex = shard.shardIndex;
                        Debug.Assert(group.SortValues != null);
                        mergedGroup.topValues        = group.SortValues;
                        groupsSeen[group.GroupValue] = mergedGroup;
                        mergedGroup.inQueue          = true;
                        queue.Add(mergedGroup);
                    }
                    else if (mergedGroup.processed)
                    {
                        // This shard produced a group that we already
                        // processed; move on to next group...
                        continue;
                    }
                    else
                    {
                        //System.out.println("      old");
                        bool competes = false;
                        for (int compIDX = 0; compIDX < groupComp.comparators.Length; compIDX++)
                        {
                            int cmp = groupComp.reversed[compIDX] * groupComp.comparators[compIDX].CompareValues(group.SortValues[compIDX],
                                                                                                                 mergedGroup.topValues[compIDX]);
                            if (cmp < 0)
                            {
                                // Definitely competes
                                competes = true;
                                break;
                            }
                            else if (cmp > 0)
                            {
                                // Definitely does not compete
                                break;
                            }
                            else if (compIDX == groupComp.comparators.Length - 1)
                            {
                                if (shard.shardIndex < mergedGroup.minShardIndex)
                                {
                                    competes = true;
                                }
                            }
                        }

                        //System.out.println("      competes=" + competes);

                        if (competes)
                        {
                            // Group's sort changed -- remove & re-insert
                            if (mergedGroup.inQueue)
                            {
                                queue.Remove(mergedGroup);
                            }
                            mergedGroup.topValues     = group.SortValues;
                            mergedGroup.minShardIndex = shard.shardIndex;
                            queue.Add(mergedGroup);
                            mergedGroup.inQueue = true;
                        }
                    }

                    mergedGroup.shards.Add(shard);
                    break;
                }

                // Prune un-competitive groups:
                while (queue.Count > topN)
                {
                    MergedGroup <T> group = queue.Last();
                    queue.Remove(group);
                    //System.out.println("PRUNE: " + group);
                    group.inQueue = false;
                }
            }
예제 #8
0
 private void CmdAdd_Click(object sender, EventArgs e)
 {
     mExcludedDates.Add(ExcludeDay.Value.Date);
     DaysExcluded.DataSource = mExcludedDates.ToList();
     FireCalendarChanged(sender, e);
 }
예제 #9
0
        public virtual bool GradientCheck(int numOfChecks, int numOfRandomChecks, double[] x)
        {
            double epsilon          = 1e-5;
            double diffThreshold    = 0.01;
            double diffPctThreshold = 0.1;
            double twoEpsilon       = epsilon * 2;
            int    xLen             = x.Length;

            // log.info("\n\n\ncalling derivativeAt");
            DerivativeAt(x);
            double[] savedDeriv = new double[xLen];
            System.Array.Copy(derivative, 0, savedDeriv, 0, derivative.Length);
            int interval = Math.Max(1, x.Length / numOfChecks);
            ICollection <int> indicesToCheck = new TreeSet <int>();

            for (int paramIndex = 0; paramIndex < xLen; paramIndex += interval)
            {
                indicesToCheck.Add(paramIndex);
            }
            for (int i = xLen - 1; i >= 0 && i > xLen - numOfChecks; i--)
            {
                indicesToCheck.Add(i);
            }
            for (int i_1 = 1; i_1 < xLen && i_1 < numOfChecks; i_1++)
            {
                indicesToCheck.Add(i_1);
            }
            for (int i_2 = 0; i_2 < numOfRandomChecks; i_2++)
            {
                indicesToCheck.Add(generator.NextInt(xLen));
            }
            bool        returnVal  = true;
            IList <int> badIndices = new List <int>();

            foreach (int paramIndex_1 in indicesToCheck)
            {
                double oldX = x[paramIndex_1];
                x[paramIndex_1] = oldX + epsilon;
                // log.info("\n\n\ncalling valueAt1");
                double plusVal = ValueAt(x);
                x[paramIndex_1] = oldX - epsilon;
                // log.info("\n\n\ncalling valueAt2");
                double minusVal  = ValueAt(x);
                double appDeriv  = (plusVal - minusVal) / twoEpsilon;
                double calcDeriv = savedDeriv[paramIndex_1];
                double diff      = Math.Abs(appDeriv - calcDeriv);
                double pct       = diff / Math.Min(Math.Abs(appDeriv), Math.Abs(calcDeriv));
                if (diff > diffThreshold && pct > diffPctThreshold)
                {
                    System.Console.Error.Printf("Grad fail at %2d, appGrad=%9.7f, calcGrad=%9.7f, diff=%9.7f, pct=%9.7f\n", paramIndex_1, appDeriv, calcDeriv, diff, pct);
                    badIndices.Add(paramIndex_1);
                    returnVal = false;
                }
                else
                {
                    System.Console.Error.Printf("Grad good at %2d, appGrad=%9.7f, calcGrad=%9.7f, diff=%9.7f, pct=%9.7f\n", paramIndex_1, appDeriv, calcDeriv, diff, pct);
                }
                x[paramIndex_1] = oldX;
            }
            if (returnVal)
            {
                System.Console.Error.Printf("ALL gradients passed. Yay!\n");
            }
            else
            {
                log.Info("Bad indices: ");
                for (int i_3 = 0; i_3 < badIndices.Count && i_3 < 10; ++i_3)
                {
                    log.Info(" " + badIndices[i_3]);
                }
                if (badIndices.Count >= 10)
                {
                    log.Info(" (...)");
                }
                log.Info();
            }
            return(returnVal);
        }
예제 #10
0
        /// <summary>
        /// Add the given Date to the list of excluded days. Only the month, day and
        /// year of the returned dates are significant.
        /// </summary>
        public virtual void AddExcludedDate(DateTime excludedDateUtc)
        {
            DateTime date = excludedDateUtc.Date;

            dates.Add(date);
        }
        private static void CollapsePrepAndPoss(List<TypedDependency> list)
        {

            // Man oh man, how gnarly is the logic of this method....
            var newTypedDeps = new List<TypedDependency>();

            // Construct a map from tree nodes to the set of typed
            // dependencies in which the node appears as governor.
            // cdm: could use CollectionValuedMap here!
            var map = new Dictionary<IndexedWord, Util.SortedSet<TypedDependency>>();
            var vmod = new List<IndexedWord>();

            foreach (TypedDependency typedDep in list)
            {
                if (!map.ContainsKey(typedDep.Gov))
                {
                    map.Add(typedDep.Gov, new TreeSet<TypedDependency>());
                }
                map[typedDep.Gov].Add(typedDep);

                if (typedDep.Reln == EnglishGrammaticalRelations.VerbalModifier)
                {
                    // look for aux deps which indicate this was a to-be verb
                    bool foundAux = false;
                    foreach (TypedDependency auxDep in list)
                    {
                        if (auxDep.Reln != EnglishGrammaticalRelations.AuxModifier)
                        {
                            continue;
                        }
                        if (!auxDep.Gov.Equals(typedDep.Dep) ||
                            !auxDep.Dep.Value().Equals("to", StringComparison.InvariantCultureIgnoreCase))
                        {
                            continue;
                        }
                        foundAux = true;
                        break;
                    }
                    if (!foundAux)
                    {
                        vmod.Add(typedDep.Dep);
                    }
                }
            }

            // Do preposition conjunction interaction for
            // governor p NP and p NP case ... a lot of special code cdm jan 2006

            foreach (TypedDependency td1 in list)
            {
                if (td1.Reln != EnglishGrammaticalRelations.PrepositionalModifier)
                {
                    continue;
                }
                if (td1.Reln == GrammaticalRelation.Kill)
                {
                    continue;
                }

                IndexedWord td1Dep = td1.Dep;
                Util.SortedSet<TypedDependency> possibles = map[td1Dep];
                if (possibles == null)
                {
                    continue;
                }

                // look for the "second half"

                // unique: the head prep and whether it should be pobj
                Tuple<TypedDependency, bool> prepDep = null;
                TypedDependency ccDep = null; // treat as unique
                // list of dep and prepOtherDep and pobj (or  pcomp)
                var conjs = new List<Tuple<TypedDependency, TypedDependency, bool>>();
                Set<TypedDependency> otherDtrs = new TreeSet<TypedDependency>();

                // first look for a conj(prep, prep) (there might be several conj relations!!!)
                bool samePrepositionInEachConjunct = true;
                int conjIndex = -1;
                foreach (TypedDependency td2 in possibles)
                {
                    if (td2.Reln == EnglishGrammaticalRelations.Conjunct)
                    {
                        IndexedWord td2Dep = td2.Dep;
                        string td2DepPOS = td2Dep.Tag();
                        if (td2DepPOS == PartsOfSpeech.PrepositionOrSubordinateConjunction 
                            || td2DepPOS == PartsOfSpeech.To)
                        {
                            samePrepositionInEachConjunct = samePrepositionInEachConjunct &&
                                                            td2Dep.Value().Equals(td1Dep.Value());
                            Set<TypedDependency> possibles2 = map[td2Dep];
                            bool pobj = true; // default of collapsing preposition is prep_
                            TypedDependency prepOtherDep = null;
                            if (possibles2 != null)
                            {
                                foreach (TypedDependency td3 in possibles2)
                                {
                                    IndexedWord td3Dep = td3.Dep;
                                    string td3DepPOS = td3Dep.Tag();
                                    // CDM Mar 2006: I put in disjunction here when I added in
                                    // PREPOSITIONAL_OBJECT. If it catches all cases, we should
                                    // be able to delete the DEPENDENT disjunct
                                    // maybe better to delete the DEPENDENT disjunct - it creates
                                    // problem with multiple prep (mcdm)
                                    if ((td3.Reln == EnglishGrammaticalRelations.PrepositionalObject ||
                                         td3.Reln == EnglishGrammaticalRelations.PrepositionalComplement) &&
                                        (!(td3DepPOS == PartsOfSpeech.PrepositionOrSubordinateConjunction || td3DepPOS == PartsOfSpeech.To)) && prepOtherDep == null)
                                    {
                                        prepOtherDep = td3;
                                        if (td3.Reln == EnglishGrammaticalRelations.PrepositionalComplement)
                                        {
                                            pobj = false;
                                        }
                                    }
                                    else
                                    {
                                        otherDtrs.Add(td3);
                                    }
                                }
                            }
                            if (conjIndex < td2Dep.Index())
                            {
                                conjIndex = td2Dep.Index();
                            }
                            conjs.Add(new Tuple<TypedDependency, TypedDependency, Boolean>(td2, prepOtherDep, pobj));
                        }
                    }
                } // end td2:possibles

                if (!conjs.Any())
                {
                    continue;
                }

                // if we have a conj under a preposition dependency, we look for the other
                // parts

                string td1DepPOS = td1Dep.Tag();
                foreach (TypedDependency td2 in possibles)
                {
                    // we look for the cc linked to this conjDep
                    // the cc dep must have an index smaller than the dep of conjDep
                    if (td2.Reln == EnglishGrammaticalRelations.Coordination && td2.Dep.Index() < conjIndex)
                    {
                        ccDep = td2;
                    }
                    else
                    {
                        IndexedWord td2Dep = td2.Dep;
                        string td2DepPOS = td2Dep.Tag();
                        if ((td2.Reln == GrammaticalRelation.Dependent ||
                             td2.Reln == EnglishGrammaticalRelations.PrepositionalObject ||
                             td2.Reln == EnglishGrammaticalRelations.PrepositionalComplement) &&
                            (PartsOfSpeech.PrepositionOrSubordinateConjunction == td1DepPOS || PartsOfSpeech.To == td1DepPOS
                            || PartsOfSpeech.VerbGerundOrPresentParticiple == td1DepPOS) 
                            && prepDep == null 
                            && (!(PartsOfSpeech.Adverb == td2DepPOS || PartsOfSpeech.PrepositionOrSubordinateConjunction == td2DepPOS || PartsOfSpeech.To == td2DepPOS)))
                        {
                            // same index trick, in case we have multiple deps
                            // I deleted this to see if it helped [cdm Jan 2010] &&
                            // td2.dep().index() < index)
                            prepDep = new Tuple<TypedDependency, Boolean>(td2,
                                td2.Reln != EnglishGrammaticalRelations.PrepositionalComplement);
                        }
                        else if (!inConjDeps(td2, conjs))
                        {
                            // don't want to add the conjDep
                            // again!
                            otherDtrs.Add(td2);
                        }
                    }
                }

                if (prepDep == null || ccDep == null)
                {
                    continue; // we can't deal with it in the hairy prep/conj interaction
                    // case!
                }
                
                // check if we have the same prepositions in the conjunction
                if (samePrepositionInEachConjunct)
                {
                    // conjDep != null && prepOtherDep !=
                    // null &&
                    // OK, we have a conjunction over parallel PPs: Fred flew to Greece and
                    // to Serbia.
                    GrammaticalRelation reln = DeterminePrepRelation(map, vmod, td1, td1, prepDep.Item2);

                    var tdNew = new TypedDependency(reln, td1.Gov, prepDep.Item1.Dep);
                    newTypedDeps.Add(tdNew);
                    td1.Reln = GrammaticalRelation.Kill; // remember these are "used up"
                    prepDep.Item1.Reln = GrammaticalRelation.Kill;
                    ccDep.Reln = GrammaticalRelation.Kill;

                    foreach (Tuple<TypedDependency, TypedDependency, Boolean> trip in conjs)
                    {
                        TypedDependency conjDep = trip.Item1;
                        TypedDependency prepOtherDep = trip.Item2;
                        if (prepOtherDep == null)
                        {
                            // CDM July 2010: I think this should only ever happen if there is a
                            // misparse, but it has happened in such circumstances. You have
                            // something like (PP in or in (NP Serbia)), with the two
                            // prepositions the same. We just clean up the mess.
                            ccDep.Reln = GrammaticalRelation.Kill;
                        }
                        else
                        {
                            var tdNew2 = new TypedDependency(ConjValue(ccDep.Dep.Value()),
                                prepDep.Item1.Dep, prepOtherDep.Dep);
                            newTypedDeps.Add(tdNew2);
                            prepOtherDep.Reln = GrammaticalRelation.Kill;
                        }
                        conjDep.Reln = GrammaticalRelation.Kill;
                    }

                    // promote dtrs that would be orphaned
                    foreach (TypedDependency otd in otherDtrs)
                    {
                        otd.Gov = td1.Gov;
                    }

                    // Now we need to see if there are any TDs that will be "orphaned"
                    // by this collapse. Example: if we have:
                    // dep(drew, on)
                    // dep(on, book)
                    // dep(on, right)
                    // the first two will be collapsed to on(drew, book), but then
                    // the third one will be orphaned, since its governor no
                    // longer appears. So, change its governor to 'drew'.
                    // CDM Feb 2010: This used to not move COORDINATION OR CONJUNCT, but now
                    // it does, since they're not automatically deleted
                    // Some things in possibles may have already been changed, so check gov
                    foreach (TypedDependency td2 in possibles)
                    {
                        if (td2.Reln != GrammaticalRelation.Kill && td2.Gov.Equals(td1.Dep))
                        {
                            // && td2.reln()
                            // != COORDINATION
                            // && td2.reln()
                            // != CONJUNCT
                            td2.Gov = td1.Gov;
                        }
                    }
                    continue; // This one has been dealt with successfully
                } // end same prepositions

                // case of "Lufthansa flies to and from Serbia". Make it look like next
                // case :-)
                // that is, the prepOtherDep should be the same as prepDep !
                var newConjList = new List<Tuple<TypedDependency, TypedDependency, bool>>();
                foreach (Tuple<TypedDependency, TypedDependency, Boolean> trip in conjs)
                {
                    if (trip.Item1 != null && trip.Item2 == null)
                    {
                        /*trip.Item2 = new TypedDependency(prepDep.Item1.reln(), trip.Item1.dep(), prepDep.Item1.dep());
          trip.Item3 = prepDep.Item2;*/
                        newConjList.Add(new Tuple<TypedDependency, TypedDependency, bool>(trip.Item1,
                            new TypedDependency(prepDep.Item1.Reln, trip.Item1.Dep, prepDep.Item1.Dep),
                            prepDep.Item2));
                    }
                    else
                    {
                        newConjList.Add(trip);
                    }
                }
                conjs = newConjList;

                // we have two different prepositions in the conjunction
                // in this case we need to add a node
                // "Bill jumped over the fence and through the hoop"
                // prep_over(jumped, fence)
                // conj_and(jumped, jumped)
                // prep_through(jumped, hoop)

                GrammaticalRelation _reln = DeterminePrepRelation(map, vmod, td1, td1, prepDep.Item2);
                var _tdNew = new TypedDependency(_reln, td1.Gov, prepDep.Item1.Dep);
                newTypedDeps.Add(_tdNew);

                td1.Reln = GrammaticalRelation.Kill; // remember these are "used up"
                prepDep.Item1.Reln = GrammaticalRelation.Kill;
                ccDep.Reln = GrammaticalRelation.Kill;
                // so far we added the first prep grammatical relation

                int copyNumber = 1;
                foreach (Tuple<TypedDependency, TypedDependency, bool> trip in conjs)
                {
                    TypedDependency conjDep = trip.Item1;
                    TypedDependency prepOtherDep = trip.Item2;
                    bool pobj = trip.Item3;
                    // OK, we have a conjunction over different PPs
                    // we create a new node;
                    // in order to make a distinction between the original node and its copy
                    // we add a "copy" entry in the CoreLabel
                    // existence of copy key is checked at printing (ToString method of
                    // TypedDependency)
                    IndexedWord label = td1.Gov.MakeCopy(copyNumber);
                    copyNumber++;

                    // now we add the conjunction relation between td1.gov and the copy
                    // the copy has the same label as td1.gov() but is another TreeGraphNode
                    var tdNew2 = new TypedDependency(ConjValue(ccDep.Dep.Value()), td1.Gov, label);
                    newTypedDeps.Add(tdNew2);

                    // now we still need to add the second prep grammatical relation
                    // between the copy and the dependent of the prepOtherDep node
                    GrammaticalRelation reln2 = DeterminePrepRelation(map, vmod, conjDep, td1, pobj);
                    var tdNew3 = new TypedDependency(reln2, label, prepOtherDep.Dep);
                    newTypedDeps.Add(tdNew3);

                    conjDep.Reln = GrammaticalRelation.Kill;
                    prepOtherDep.Reln = GrammaticalRelation.Kill;

                    // promote dtrs that would be orphaned
                    foreach (TypedDependency otd in otherDtrs)
                    {
                        // special treatment for prepositions: the original relation is
                        // likely to be a "dep" and we want this to be a "prep"
                        if (otd.Dep.Tag() == PartsOfSpeech.PrepositionOrSubordinateConjunction)
                        {
                            otd.Reln = EnglishGrammaticalRelations.PrepositionalModifier;
                        }
                        otd.Gov = td1.Gov;
                    }
                }

                // Now we need to see if there are any TDs that will be "orphaned" off
                // the first preposition
                // by this collapse. Example: if we have:
                // dep(drew, on)
                // dep(on, book)
                // dep(on, right)
                // the first two will be collapsed to on(drew, book), but then
                // the third one will be orphaned, since its governor no
                // longer appears. So, change its governor to 'drew'.
                // CDM Feb 2010: This used to not move COORDINATION OR CONJUNCT, but now
                // it does, since they're not automatically deleted
                foreach (TypedDependency td2 in possibles)
                {
                    if (td2.Reln != GrammaticalRelation.Kill)
                    {
                        // && td2.reln() != COORDINATION &&
                        // td2.reln() != CONJUNCT) {
                        td2.Gov = td1.Gov;
                    }
                }
                // end for different prepositions
            } // for TypedDependency td1 : list

            // below here is the single preposition/possessor basic case!!
            foreach (TypedDependency td1 in list)
            {
                if (td1.Reln == GrammaticalRelation.Kill)
                {
                    continue;
                }

                IndexedWord td1Dep = td1.Dep;
                string td1DepPOS = td1Dep.Tag();
                // find all other typedDeps having our dep as gov
                Set<TypedDependency> possibles = map[td1Dep];

                if (possibles != null &&
                    (td1.Reln == EnglishGrammaticalRelations.PrepositionalModifier ||
                     td1.Reln == EnglishGrammaticalRelations.PossessionModifier ||
                     td1.Reln == EnglishGrammaticalRelations.Conjunct))
                {

                    // look for the "second half"
                    bool pobj = true; // default for prep relation is prep_
                    foreach (TypedDependency td2 in possibles)
                    {
                        if (td2.Reln != EnglishGrammaticalRelations.Coordination &&
                            td2.Reln != EnglishGrammaticalRelations.Conjunct)
                        {

                            IndexedWord td2Dep = td2.Dep;
                            string td2DepPOS = td2Dep.Tag();
                            if ((td1.Reln == EnglishGrammaticalRelations.PossessionModifier ||
                                 td1.Reln == EnglishGrammaticalRelations.Conjunct))
                            {
                                if (td2.Reln == EnglishGrammaticalRelations.PossessiveModifier)
                                {
                                    if (! map.ContainsKey(td2Dep))
                                    {
                                        // if 's has no kids of its own (it shouldn't!)
                                        td2.Reln = GrammaticalRelation.Kill;
                                    }
                                }
                            }
                            else if ((td2.Reln == EnglishGrammaticalRelations.PrepositionalObject ||
                                      td2.Reln == EnglishGrammaticalRelations.PrepositionalComplement) &&
                                     (PartsOfSpeech.PrepositionOrSubordinateConjunction == td1DepPOS 
                                || PartsOfSpeech.To == td1DepPOS || PartsOfSpeech.VerbGerundOrPresentParticiple == td1DepPOS) &&
                                     (!(PartsOfSpeech.Adverb == td2DepPOS 
                                || PartsOfSpeech.PrepositionOrSubordinateConjunction == td2DepPOS || PartsOfSpeech.To == td2DepPOS)) &&
                                     !IsConjWithNoPrep(td2.Gov, possibles))
                            {
                                // we don't collapse preposition conjoined with a non-preposition
                                // to avoid disconnected constituents
                                // OK, we have a pair td1, td2 to collapse to td3

                                // check whether we are in a pcomp case:
                                if (td2.Reln == EnglishGrammaticalRelations.PrepositionalComplement)
                                {
                                    pobj = false;
                                }

                                GrammaticalRelation reln = DeterminePrepRelation(map, vmod, td1, td1, pobj);
                                var td3 = new TypedDependency(reln, td1.Gov, td2.Dep);
                                // add it to map to deal with recursive cases like "achieved this (PP (PP in part) with talent)"
                                map[td3.Gov].Add(td3);

                                newTypedDeps.Add(td3);
                                td1.Reln = GrammaticalRelation.Kill; // remember these are "used up"
                                td2.Reln = GrammaticalRelation.Kill; // remember these are "used up"
                            }
                        }
                    } // for TypedDependency td2
                }

                // Now we need to see if there are any TDs that will be "orphaned"
                // by this collapse. Example: if we have:
                // dep(drew, on)
                // dep(on, book)
                // dep(on, right)
                // the first two will be collapsed to on(drew, book), but then
                // the third one will be orphaned, since its governor no
                // longer appears. So, change its governor to 'drew'.
                // CDM Feb 2010: This used to not move COORDINATION OR CONJUNCT, but now
                // it does, since they're not automatically deleted
                if (possibles != null && td1.Reln == GrammaticalRelation.Kill)
                {
                    foreach (TypedDependency td2 in possibles)
                    {
                        if (td2.Reln != GrammaticalRelation.Kill)
                        {
                            // && td2.reln() != COORDINATION &&
                            // td2.reln() != CONJUNCT) {
                            td2.Gov = td1.Gov;
                        }
                    }
                }

            } // for TypedDependency td1

            // now remove typed dependencies with reln "kill" and add new ones.
            /*for (Iterator<TypedDependency> iter = list.iterator(); iter.hasNext();) {
      TypedDependency td = iter.next();
      if (td.reln() == KILL) {
        iter.remove();
      }
    }*/
            list.RemoveAll(td => td.Reln == GrammaticalRelation.Kill);
            list.AddRange(newTypedDeps);
        } // end collapsePrepAndPoss()
        /// <summary>
        /// Initializes a new instance of the <see cref="Option"/> class.
        /// </summary>
        /// <param name="attribute">The attribute describing this option.</param>
        /// <param name="memberInfo">The <see cref="MemberInfo"/> object pointing to the member to which the attribute was applied.</param>
        /// <param name="cmdLineObject">The command line manager object.</param>
        /// <param name="optionGroups">A complete list of all available option groups.</param>
        /// <param name="numberFormatInfo">The number format info to use for parsing numerical arguments.</param>
        public Option(CommandLineOptionAttribute attribute, MemberInfo memberInfo, object cmdLineObject,
                      ICollection <OptionGroup> optionGroups, NumberFormatInfo numberFormatInfo)
        {
            mObject           = cmdLineObject;
            mMember           = memberInfo;
            mUsage            = attribute.BoolFunction;
            mDescription      = attribute.Description;
            mNumberFormatInfo = numberFormatInfo ?? CultureInfo.CurrentCulture.NumberFormat;
            mDefaultValue     = attribute.DefaultAssignmentValue;
            mMinValue         = attribute.MinValue;
            mMaxValue         = attribute.MaxValue;

            // Check the validity of the member for which this attribute was defined
            switch (memberInfo.MemberType)
            {
            case MemberTypes.Field:
                FieldInfo fieldInfo = (FieldInfo)memberInfo;
                if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal field for this attribute; field must be writeable");
                }

                mOptionType = fieldInfo.FieldType;
                break;

            case MemberTypes.Method:
                MethodInfo      method     = (MethodInfo)memberInfo;
                ParameterInfo[] parameters = method.GetParameters();

                if (parameters.Length != 1)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal method for this attribute; the method must accept exactly one parameter");
                }

                if (parameters[0].IsOut)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal method for this attribute; the parameter of the method must not be an out parameter");
                }

                if (IsArray(parameters[0].ParameterType) || IsCollectionType(parameters[0].ParameterType))
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal method for this attribute; the parameter of the method must be a non-array and non-collection type");
                }

                mOptionType = parameters[0].ParameterType;
                break;

            case MemberTypes.Property:
                PropertyInfo propInfo = (PropertyInfo)memberInfo;

                if (!propInfo.CanWrite && !IsCollectionType(propInfo.PropertyType))
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal property for this attribute; property for non-collection type must be writable");
                }

                if (!propInfo.CanRead && IsCollectionType(propInfo.PropertyType))
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal property for this attribute; property for collection type must be readable");
                }

                if (!(propInfo.CanRead && propInfo.CanWrite) && IsArray(propInfo.PropertyType))
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                                 "Illegal property for this attribute; property representing array type must be both readable and writeable");
                }

                mOptionType = propInfo.PropertyType;
                break;

            default:
                throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                             "Illegal member for this attribute; member must be a property, method (accepting one parameter) or a field");
            }

            mMinOccurs = attribute.MinOccurs;

            // MaxOccurs does not have a default value (since this is different for various types), so we set it here.
            if (!attribute.IsMaxOccursSet)
            {
                // Use default setting for MaxOccurs
                if (IsArray(mOptionType) || IsCollectionType(mOptionType))
                {
                    mMaxOccurs = 0; // Unlimited
                }
                else
                {
                    mMaxOccurs = 1;
                }
            }
            else
            {
                mMaxOccurs = attribute.MaxOccurs;
            }

            if (mMinOccurs > mMaxOccurs && mMaxOccurs > 0)
            {
                throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                             String.Format(CultureInfo.CurrentUICulture, "MinOccurs ({0}) must not be larger than MaxOccurs ({1})", mMinOccurs, mMaxOccurs));
            }

            if (mMaxOccurs != 1 && !(IsArray(mOptionType) || IsCollectionType(mOptionType)) && mMember.MemberType != MemberTypes.Method)
            {
                throw new AttributeException(typeof(CommandLineOptionAttribute), memberInfo,
                                             "Invalid cardinality for member; MaxOccurs must be equal to one (1) for any non-array or non-collection type");
            }

            CommandLineManagerAttribute objectAttr = (CommandLineManagerAttribute)Attribute.GetCustomAttribute(mObject.GetType(), typeof(CommandLineManagerAttribute));

            if (objectAttr == null)
            {
                throw new AttributeException(String.Format(CultureInfo.CurrentUICulture,
                                                           "Class {0} contains a CommandLineOptionAttribute, but does not have the attribute CommandLineObjectAttribute", mObject.GetType().FullName));
            }


            // Assign the name of this option from the member itself if no name is explicitly provided
            if (attribute.Name == null)
            {
                mName = memberInfo.Name;
            }
            else
            {
                mName = attribute.Name;
            }

            // Find the group (if any) that this option belongs to in the list of available option groups
            if (attribute.GroupId != null)
            {
                if (!optionGroups.Find(new Func <OptionGroup, bool>(
                                           delegate(OptionGroup searchGroup)
                {
                    return(attribute.GroupId.Equals(searchGroup.Id));
                }), out mGroup))
                {
                    throw new LogicException(String.Format(CultureInfo.CurrentUICulture, "Undefined group {0} referenced from  member {1} in {2}", attribute.GroupId, memberInfo.Name, cmdLineObject.GetType().FullName));
                }
                mGroup.Options.Add(mName, this);
            }

            // Recursively find out if this option requires explicit assignment
            if (attribute.DoesRequireExplicitAssignment.HasValue)
            {
                mRequireExplicitAssignment = attribute.DoesRequireExplicitAssignment.Value;
            }
            else if (mGroup != null)
            {
                mRequireExplicitAssignment = mGroup.RequireExplicitAssignment;
            }
            else
            {
                mRequireExplicitAssignment = objectAttr.RequireExplicitAssignment;
            }

            // Make sure the type of the field, property or method is supported
            if (!IsTypeSupported(mOptionType))
            {
                throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                             "Unsupported type for command line option.");
            }


            // Make sure MinValue and MaxValue is not specified for any non-numerical type.
            if (mMinValue != null || mMaxValue != null)
            {
                if (!IsNumericalType)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                 "MinValue and MaxValue must not be specified for a non-numerical type");
                }
                else if (!mMinValue.GetType().IsAssignableFrom(GetBaseType(mOptionType)))
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                 "Illegal value for MinValue or MaxValue, not the same type as option");
                }
            }

            // Some special checks for numerical types
            if (IsNumericalType)
            {
                // Assign the default MinValue if it was not set and this is a numerical type
                if (IsNumericalType && mMinValue == null)
                {
                    mMinValue = GetBaseType(mOptionType).GetField("MinValue", BindingFlags.Static | BindingFlags.Public).GetValue(null);
                }

                // Assign the defaul MaxValue if it was not set and this is a numerical type
                if (IsNumericalType && mMaxValue == null)
                {
                    mMaxValue = GetBaseType(mOptionType).GetField("MaxValue", BindingFlags.Static | BindingFlags.Public).GetValue(null);
                }

                // Check that MinValue <= MaxValue
                if (IsNumericalType && ((IComparable)MinValue).CompareTo(MaxValue) > 0)
                {
                    throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                 "MinValue must not be greater than MaxValue");
                }
            }

            // Check that the DefaultValue is not set if the option does not require explicit assignment.
            // If it were allowed, it would be ambiguos for an option separated from a value by a white space character
            // since we wouldn't know whether that would set the default value or assign it to the following value.
            if (mDefaultValue != null && !mRequireExplicitAssignment)
            {
                throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                             "DefaultValue must not be specified when RequireExplicitAssignment is set to false");
            }

            // Check that the type of any set default value matches that of this option, or is string, and
            // convert it to the type of this option.
            if (mDefaultValue != null)
            {
                if (mDefaultValue.GetType() == typeof(string))
                {
                    try
                    {
                        mDefaultValue = GetCheckedValueForSetOperation(mDefaultValue);
                    }
                    catch (OverflowException)
                    {
                        throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                     "DefaultValue was less than MinValue or greater than MaxValue for this option");
                    }
                    catch (FormatException)
                    {
                        throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                     "DefaultValue was not specified in the correct format for the type of this option");
                    }
                }
                else if (GetBaseType(mOptionType) != mDefaultValue.GetType())
                {
                    try
                    {
                        mDefaultValue = Convert.ChangeType(mDefaultValue, GetBaseType(mOptionType), mNumberFormatInfo);
                    }
                    catch (InvalidCastException)
                    {
                        throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                     "The type of the DefaultValue specified is not compatible with the type of the member to which this attribute applies");
                    }
                }
            }

            // If this is an enum, check that it doesn't have members only distinguishable by case, and
            // add the members to the mEnumerationValues set for speedy access when checking values assigned
            // to this member.
            Type type = GetBaseType(mOptionType);

            if (type.IsEnum)
            {
                mEnumerationValues = new TreeSet <string>(StringComparer.OrdinalIgnoreCase);
                foreach (FieldInfo field in type.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        if (mEnumerationValues.Contains(field.Name))
                        {
                            throw new AttributeException(typeof(CommandLineOptionAttribute), mMember,
                                                         "This enumeration is not allowed as a command line option since it contains fields that differ only by case");
                        }
                        mEnumerationValues.Add(field.Name);
                    }
                }
            }
        }
예제 #13
0
        /**
         * Copies a sheet from a read-only version to the writable version.
         * Performs shallow copies
         */
        public void copySheet()
        {
            shallowCopyCells();

            // Copy the column info records
            CSharpJExcel.Jxl.Read.Biff.ColumnInfoRecord[] readCirs = fromSheet.getColumnInfos();

            for (int i = 0; i < readCirs.Length; i++)
            {
                CSharpJExcel.Jxl.Read.Biff.ColumnInfoRecord rcir = readCirs[i];
                for (int j = rcir.getStartColumn(); j <= rcir.getEndColumn(); j++)
                {
                    ColumnInfoRecord cir = new ColumnInfoRecord(rcir, j,
                                                                formatRecords);
                    cir.setHidden(rcir.getHidden());
                    columnFormats.Add(cir);
                }
            }

            // Copy the hyperlinks
            Hyperlink[] hls = fromSheet.getHyperlinks();
            for (int i = 0; i < hls.Length; i++)
            {
                WritableHyperlink hr = new WritableHyperlink
                                           (hls[i], toSheet);
                hyperlinks.Add(hr);
            }

            // Copy the merged cells
            Range[] merged = fromSheet.getMergedCells();

            for (int i = 0; i < merged.Length; i++)
            {
                mergedCells.add(new SheetRangeImpl((SheetRangeImpl)merged[i], toSheet));
            }

            // Copy the row properties
            try
            {
                CSharpJExcel.Jxl.Read.Biff.RowRecord[] rowprops = fromSheet.getRowProperties();

                for (int i = 0; i < rowprops.Length; i++)
                {
                    RowRecord rr     = toSheet.getRowRecord(rowprops[i].getRowNumber());
                    XFRecord  format = rowprops[i].hasDefaultFormat() ?
                                       formatRecords.getXFRecord(rowprops[i].getXFIndex()) : null;
                    rr.setRowDetails(rowprops[i].getRowHeight(),
                                     rowprops[i].matchesDefaultFontHeight(),
                                     rowprops[i].isCollapsed(),
                                     rowprops[i].getOutlineLevel(),
                                     rowprops[i].getGroupStart(),
                                     format);
                    numRows = System.Math.Max(numRows, rowprops[i].getRowNumber() + 1);
                }
            }
            catch (RowsExceededException e)
            {
                // Handle the rows exceeded exception - this cannot occur since
                // the sheet we are copying from will have a valid number of rows
                Assert.verify(false);
            }

            // Copy the headers and footers
            //    sheetWriter.setHeader(new HeaderRecord(si.getHeader()));
            //    sheetWriter.setFooter(new FooterRecord(si.getFooter()));

            // Copy the page breaks
            int[] rowbreaks = fromSheet.getRowPageBreaks();

            if (rowbreaks != null)
            {
                for (int i = 0; i < rowbreaks.Length; i++)
                {
                    rowBreaks.Add(rowbreaks[i]);
                }
            }

            int[] columnbreaks = fromSheet.getColumnPageBreaks();

            if (columnbreaks != null)
            {
                for (int i = 0; i < columnbreaks.Length; i++)
                {
                    columnBreaks.Add(columnbreaks[i]);
                }
            }

            // Copy the charts
            sheetWriter.setCharts(fromSheet.getCharts());

            // Copy the drawings
            DrawingGroupObject[] dr = fromSheet.getDrawings();
            for (int i = 0; i < dr.Length; i++)
            {
                if (dr[i] is CSharpJExcel.Jxl.Biff.Drawing.Drawing)
                {
                    WritableImage wi = new WritableImage
                                           (dr[i], toSheet.getWorkbook().getDrawingGroup());
                    drawings.Add(wi);
                    images.Add(wi);
                }
                else if (dr[i] is CSharpJExcel.Jxl.Biff.Drawing.Comment)
                {
                    CSharpJExcel.Jxl.Biff.Drawing.Comment c =
                        new CSharpJExcel.Jxl.Biff.Drawing.Comment(dr[i],
                                                                  toSheet.getWorkbook().getDrawingGroup(),
                                                                  workbookSettings);
                    drawings.Add(c);

                    // Set up the reference on the cell value
                    CellValue cv = (CellValue)toSheet.getWritableCell(c.getColumn(),
                                                                      c.getRow());
                    Assert.verify(cv.getCellFeatures() != null);
                    cv.getWritableCellFeatures().setCommentDrawing(c);
                }
                else if (dr[i] is CSharpJExcel.Jxl.Biff.Drawing.Button)
                {
                    CSharpJExcel.Jxl.Biff.Drawing.Button b =
                        new CSharpJExcel.Jxl.Biff.Drawing.Button
                            (dr[i],
                            toSheet.getWorkbook().getDrawingGroup(),
                            workbookSettings);
                    drawings.Add(b);
                }
                else if (dr[i] is CSharpJExcel.Jxl.Biff.Drawing.ComboBox)
                {
                    CSharpJExcel.Jxl.Biff.Drawing.ComboBox cb =
                        new CSharpJExcel.Jxl.Biff.Drawing.ComboBox
                            (dr[i],
                            toSheet.getWorkbook().getDrawingGroup(),
                            workbookSettings);
                    drawings.Add(cb);
                }
                else if (dr[i] is CSharpJExcel.Jxl.Biff.Drawing.CheckBox)
                {
                    CSharpJExcel.Jxl.Biff.Drawing.CheckBox cb =
                        new CSharpJExcel.Jxl.Biff.Drawing.CheckBox
                            (dr[i],
                            toSheet.getWorkbook().getDrawingGroup(),
                            workbookSettings);
                    drawings.Add(cb);
                }
            }

            // Copy the data validations
            DataValidation rdv = fromSheet.getDataValidation();

            if (rdv != null)
            {
                dataValidation = new DataValidation(rdv,
                                                    toSheet.getWorkbook(),
                                                    toSheet.getWorkbook(),
                                                    workbookSettings);
                uint objid = dataValidation.getComboBoxObjectId();
                if (objid != 0)
                {
                    comboBox = (ComboBox)drawings[(int)objid];
                }
            }

            // Copy the conditional formats
            ConditionalFormat[] cf = fromSheet.getConditionalFormats();
            if (cf.Length > 0)
            {
                for (int i = 0; i < cf.Length; i++)
                {
                    conditionalFormats.Add(cf[i]);
                }
            }

            // Get the autofilter
            autoFilter = fromSheet.getAutoFilter();

            // Copy the workspace options
            sheetWriter.setWorkspaceOptions(fromSheet.getWorkspaceOptions());

            // Set a flag to indicate if it contains a chart only
            if (fromSheet.getSheetBof().isChart())
            {
                chartOnly = true;
                sheetWriter.setChartOnly();
            }

            // Copy the environment specific print record
            if (fromSheet.getPLS() != null)
            {
                if (fromSheet.getWorkbookBof().isBiff7())
                {
                    //logger.warn("Cannot copy Biff7 print settings record - ignoring");
                }
                else
                {
                    plsRecord = new PLSRecord(fromSheet.getPLS());
                }
            }

            // Copy the button property set
            if (fromSheet.getButtonPropertySet() != null)
            {
                buttonPropertySet = new ButtonPropertySetRecord
                                        (fromSheet.getButtonPropertySet());
            }

            // Copy the outline levels
            maxRowOutlineLevel    = fromSheet.getMaxRowOutlineLevel();
            maxColumnOutlineLevel = fromSheet.getMaxColumnOutlineLevel();
        }
예제 #14
0
 public static bool Add(this TreeSet <TestPriorityQueue.Integer> ss, int value)
 {
     return(ss.Add(new TestPriorityQueue.Integer(value)));
 }
예제 #15
0
파일: c.cs 프로젝트: SomeoneSerge/cf
 public void Add(Segment s)
 {
     PositionOrdered.Add(s);
     WidthOrdered.Add(s);
 }
예제 #16
0
        /**
         * @see <a href="http://en.wikipedia.org/wiki/Sweep_line_algorithm">Sweep line algorithm</a>
         */
        private void SweepCleanColumns(CT_Cols cols, CT_Col[] flattenedColsArray, CT_Col overrideColumn)
        {
            List <CT_Col>        flattenedCols   = new List <CT_Col>(flattenedColsArray);
            TreeSet <CT_Col>     currentElements = new TreeSet <CT_Col>(CTColComparator.BY_MAX);
            IEnumerator <CT_Col> flIter          = flattenedCols.GetEnumerator();
            CT_Col         haveOverrideColumn    = null;
            long           lastMaxIndex          = 0;
            long           currentMax            = 0;
            IList <CT_Col> toRemove = new List <CT_Col>();
            int            pos      = -1;

            //while (flIter.hasNext())
            while ((pos + 1) < flattenedCols.Count)
            {
                //CTCol col = flIter.next();
                pos++;
                CT_Col col = flattenedCols[pos];

                long currentIndex = col.min;
                long colMax       = col.max;
                long nextIndex    = (colMax > currentMax) ? colMax : currentMax;
                //if (flIter.hasNext()) {
                if ((pos + 1) < flattenedCols.Count)
                {
                    //nextIndex = flIter.next().getMin();
                    nextIndex = flattenedCols[pos + 1].min;
                    //flIter.previous();
                }
                IEnumerator <CT_Col> iter = currentElements.GetEnumerator();
                toRemove.Clear();
                while (iter.MoveNext())
                {
                    CT_Col elem = iter.Current;
                    if (currentIndex <= elem.max)
                    {
                        break;                           // all passed elements have been purged
                    }
                    //iter.remove();
                    toRemove.Add(elem);
                }

                foreach (CT_Col rc in toRemove)
                {
                    currentElements.Remove(rc);
                }

                if (!(currentElements.Count == 0) && lastMaxIndex < currentIndex)
                {
                    // we need to process previous elements first
                    CT_Col[] copyCols = new CT_Col[currentElements.Count];
                    currentElements.CopyTo(copyCols);
                    insertCol(cols, lastMaxIndex, currentIndex - 1, copyCols, true, haveOverrideColumn);
                }
                currentElements.Add(col);
                if (colMax > currentMax)
                {
                    currentMax = colMax;
                }
                if (col.Equals(overrideColumn))
                {
                    haveOverrideColumn = overrideColumn;
                }
                while (currentIndex <= nextIndex && !(currentElements.Count == 0))
                {
                    NPOI.Util.Collections.HashSet <CT_Col> currentIndexElements = new NPOI.Util.Collections.HashSet <CT_Col>();
                    long currentElemIndex;

                    {
                        // narrow scope of currentElem
                        CT_Col currentElem = currentElements.First();
                        currentElemIndex = currentElem.max;
                        currentIndexElements.Add(currentElem);

                        while (true)
                        {
                            CT_Col higherElem = currentElements.Higher(currentElem);
                            if (higherElem == null || higherElem.max != currentElemIndex)
                            {
                                break;
                            }
                            currentElem = higherElem;
                            currentIndexElements.Add(currentElem);
                            if (colMax > currentMax)
                            {
                                currentMax = colMax;
                            }
                            if (col.Equals(overrideColumn))
                            {
                                haveOverrideColumn = overrideColumn;
                            }
                        }
                    }

                    //if (currentElemIndex < nextIndex || !flIter.hasNext()) {
                    if (currentElemIndex < nextIndex || !((pos + 1) < flattenedCols.Count))
                    {
                        CT_Col[] copyCols = new CT_Col[currentElements.Count];
                        currentElements.CopyTo(copyCols);
                        insertCol(cols, currentIndex, currentElemIndex, copyCols, true, haveOverrideColumn);
                        //if (flIter.hasNext()) {
                        if ((pos + 1) < flattenedCols.Count)
                        {
                            if (nextIndex > currentElemIndex)
                            {
                                //currentElements.removeAll(currentIndexElements);
                                foreach (CT_Col rc in currentIndexElements)
                                {
                                    currentElements.Remove(rc);
                                }
                                if (currentIndexElements.Contains(overrideColumn))
                                {
                                    haveOverrideColumn = null;
                                }
                            }
                        }
                        else
                        {
                            //currentElements.removeAll(currentIndexElements);
                            foreach (CT_Col rc in currentIndexElements)
                            {
                                currentElements.Remove(rc);
                            }
                            if (currentIndexElements.Contains(overrideColumn))
                            {
                                haveOverrideColumn = null;
                            }
                        }
                        lastMaxIndex = currentIndex = currentElemIndex + 1;
                    }
                    else
                    {
                        lastMaxIndex = currentIndex;
                        currentIndex = nextIndex + 1;
                    }
                }
            }
            SortColumns(cols);
        }
        private IEnumerable<BrowseFacet> BuildDynamicRanges()
        {
            TreeSet<BrowseFacet> facetSet = new TreeSet<BrowseFacet>(new RangeComparator());

            int minCount = ospec.MinHitCount;
            // we would skip first element at index 0 (which means no value)
            for (int i = 1; i < count.Length; ++i)
            {
                if (count[i] >= minCount)
                {
                    object val = dataCache.valArray.GetRawValue(i);
                    facetSet.Add(new BrowseFacet(val, count[i]));
                }
            }

            if (ospec.MaxCount <= 0)
            {
                ospec.MaxCount = 5;
            }
            int maxCount = ospec.MaxCount;

            BrowseFacet[] facets = facetSet.ToArray();

            if (facetSet.Count < maxCount)
            {
                ConvertFacets(facets);
            }
            else
            {
                facets = FoldChoices(facets, maxCount);
            }

            return facets;
        }
예제 #18
0
        private async void LoadData()
        {
            if (projectId != 0)
            {
                if (Utility.IsInternetAvailable(Application.Context))
                {
                    try
                    {
                        reportService = new ReportService(userSession.AccessToken);
                        var unOrderedReportList = await reportService.GetArchivedReportList(projectId);

                        var listBeforFilter = unOrderedReportList.Where(x => x.IsArchived).OrderByDescending(a => a.CreatedDateTime.Date).ThenByDescending(a => a.CreatedDateTime.TimeOfDay);
                        var resultList      = listBeforFilter.ToList();

                        emptyView.Visibility = resultList.Count == 0 ? ViewStates.Visible : ViewStates.Gone;

                        headerandItemsList = new List <Report>();
                        TreeSet sectionHeaders = new TreeSet();

                        var todayheader = false;
                        var yesterday   = false;
                        var lastweek    = false;
                        var other       = false;

                        for (int i = 0; i < resultList.Count; i++)
                        {
                            if (resultList[i].CreatedDateTime.Date >= DateTime.Today)
                            {
                                if (todayheader == false)
                                {
                                    todayheader = true;
                                    Report reportDataDataDto = new Report();
                                    reportDataDataDto.ReportName = Application.Context.Resources.GetString(Resource.String.today);
                                    headerandItemsList.Add(reportDataDataDto);
                                    sectionHeaders.Add(headerandItemsList.Count - 1);
                                }

                                headerandItemsList.Add(resultList[i]);
                            }
                            else if (resultList[i].CreatedDateTime.Date == DateTime.Today.AddDays(-1))
                            {
                                if (!yesterday)
                                {
                                    yesterday = true;
                                    Report reportDataDataDto = new Report();
                                    reportDataDataDto.ReportName = Application.Context.Resources.GetString(Resource.String.yesterday);
                                    headerandItemsList.Add(reportDataDataDto);
                                    sectionHeaders.Add(headerandItemsList.Count - 1);
                                }
                                headerandItemsList.Add(resultList[i]);
                            }


                            else if (resultList[i].CreatedDateTime.Date <DateTime.Today.AddDays(-2) && resultList[i].CreatedDateTime.Date> DateTime.Today.AddDays(-7))
                            {
                                if (!lastweek)
                                {
                                    lastweek = true;
                                    Report reportDataDataDto = new Report();
                                    reportDataDataDto.ReportName = Application.Context.Resources.GetString(Resource.String.last_week);
                                    headerandItemsList.Add(reportDataDataDto);
                                    sectionHeaders.Add(headerandItemsList.Count - 1);
                                }
                                headerandItemsList.Add(resultList[i]);
                            }
                            else
                            {
                                if (!other)
                                {
                                    other = true;
                                    Report reportDataDataDto = new Report();
                                    reportDataDataDto.ReportName = Application.Context.Resources.GetString(Resource.String.other);
                                    headerandItemsList.Add(reportDataDataDto);
                                    sectionHeaders.Add(headerandItemsList.Count - 1);
                                }

                                headerandItemsList.Add(resultList[i]);
                            }
                        }

                        listAdapter      = new ReportListArchiveAdapter(Application.Context, headerandItemsList, sectionHeaders);
                        ListView.Adapter = listAdapter;
                        listAdapter.NotifyDataSetChanged();
                    }

                    catch (Exception)
                    {
                        Log.Debug("Exception", "Archeive List");
                    }
                }
            }
            else
            {
                emptyView.Visibility = ViewStates.Visible;
            }
        }