private void ModifySetForTest(ICollection<int> set)
 {
     set.Remove(1);
     set.Remove(2);
     set.Add(4);
     set.Add(5);
 }
Exemplo n.º 2
0
 private static IEnumerable<PayloadDTO> GetPayloads(IEnumerable<string> types, ICollection<PayloadDTO> list)
 {
     foreach (var item in types)
     {
         switch (item)
         {
             case ("1"):
                 list.Add(new PhotoDTO() { Id = 1 });
                 break;
             case ("2"):
                 list.Add(new TVDTO() { Id = 2 });
                 break;
             case ("3"):
                 list.Add(new IRDTO() { Id = 3 });
                 break;
             case ("4"):
                 list.Add(new FrontalDTO() { Id = 4 });
                 break;
             case ("5"):
                 list.Add(new MultispectralDTO() { Id = 5 });
                 break;
             case ("10"):
                 list.Add(new OtusDTO() { Id = 10 });
                 break;
             default:
                 throw new ArgumentOutOfRangeException("Exception in  GetPayload method");
         }
     }
     return list;
 }
Exemplo n.º 3
0
		public override bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider)
		{
			bool found = false;
			foreach (InternalModule m in InternalModules())
			{
				if (string.IsNullOrEmpty(m.Namespace))
				{
					if (m.Resolve(resultingSet, name, typesToConsider))
						found = true;
					continue;
				}

				if (!HasNamespacePrefix(m, name))
					continue;

				if (m.Namespace.Length == name.Length)
				{
					resultingSet.Add(m.ModuleMembersNamespace);
					found = true;
					continue;
				}

				if (m.Namespace[name.Length] == '.')
				{
					resultingSet.Add(new PartialModuleNamespace(name, m));
					found = true;
					continue;
				}
			}
			return found;
		}
Exemplo n.º 4
0
        public ICollection<EventBean> Lookup(
            EventBean[] eventsPerStream,
            IDictionary<object, CompositeIndexEntry> parent,
            ICollection<EventBean> result,
            CompositeIndexQuery next,
            ExprEvaluatorContext context,
            ICollection<object> optionalKeyCollector,
            CompositeIndexQueryResultPostProcessor postProcessor)
        {
            var comparableStart = EvaluatePerStreamStart(eventsPerStream, context);
            optionalKeyCollector?.Add(comparableStart);

            if (comparableStart == null) {
                return null;
            }

            var comparableEnd = EvaluatePerStreamEnd(eventsPerStream, context);
            optionalKeyCollector?.Add(comparableEnd);

            if (comparableEnd == null) {
                return null;
            }

            var index = (IOrderedDictionary<object, CompositeIndexEntry>) parent;
            var submapOne = index.Head(comparableStart, !includeStart);
            var submapTwo = index.Tail(comparableEnd, !includeEnd);
            return CompositeIndexQueryRange.Handle(eventsPerStream, submapOne, submapTwo, result, next, postProcessor);
        }
Exemplo n.º 5
0
        //Generate new item on the field.
        public static void ProduceItemInField(FrameAnimation enemyAnimation, Enemy enemy, ICollection<IItem> visibleItems)
        {
            Point2D itemPosition = new Point2D(0, 0);

            if (enemy is Zombie)
            {
                if (enemyAnimation.SpriteEffect == SpriteEffects.None)
                {
                    itemPosition = new Point2D(enemyAnimation.Position.X, enemyAnimation.Position.Y + MovingDistanceStomper);
                }
                else
                {
                    itemPosition = new Point2D(enemyAnimation.Position.X + 100, enemyAnimation.Position.Y + MovingDistanceStomper);
                }

                visibleItems.Add(new Stomper("Stomper", itemPosition, OrusTheGame.Instance.Content));

            }
            else if (enemy is Skeleton)
            {

                if (enemyAnimation.SpriteEffect == SpriteEffects.None)
                {
                    itemPosition = new Point2D(enemyAnimation.Position.X, enemyAnimation.Position.Y + MovingDistanceArmour);
                }
                else
                {
                    itemPosition = new Point2D(enemyAnimation.Position.X + 100, enemyAnimation.Position.Y + MovingDistanceArmour);
                }

                visibleItems.Add(new GiantArmour("GiantArmour", itemPosition, OrusTheGame.Instance.Content));
            }
        }
Exemplo n.º 6
0
 private static void Circle(ICollection<ExtendedOpenGlPoint> list, double r, double y, Point center)
 {
     var n = (int)Math.Round(r) * 20;
     var start = new Point();
     for (var i = 0; i < n; i++)
     {
         var angle = 2 * Math.PI * i / n;
         if (i == 0)
         {
             start.X = Math.Round(r * Math.Sin(angle), 5);
             start.Y = Math.Round(r * Math.Cos(angle), 5);
         }
         list.Add(new ExtendedOpenGlPoint(
                 r * Math.Sin(angle) + center.X,
                 y,
                 r * Math.Cos(angle) + center.Y,
                 0,
                 new float[] { 0, 0, 0 }));
     }
     list.Add(new ExtendedOpenGlPoint(
             start.X + center.X,
             y,
             start.Y + center.Y,
             0,
             new float[] { 0, 0, 0 }));
 }
Exemplo n.º 7
0
        protected override void OnInitialize(ICollection<IDisposable> disposables)
        {
            this.body = BodyFactory.CreateCircle(this.Engine.World, 0.5f, 1f);
            this.body.IsSensor = true;
            this.body.UserData = this;

            disposables.Add(this.body);

            disposables.Add(this.Engine.Updates
                                .ObserveOn(this.Engine.PostPhysicsScheduler)
                                .Where(x => this.owner != null)
                                .Subscribe(this.LinkPhysics));

            disposables.Add(this.Engine.Updates
                                .ObserveOn(this.Engine.UpdateScheduler)
                                .Where(x => this.owner != null)
                                .Subscribe(this.Update));

            //disposables.Add(
            //    this.FireRequests.Take(1)
            //        .Concat(
            //            Observable.Interval(TimeSpan.FromMilliseconds(250)).Take(1).Where(x => false).Select(x => Unit.Default))
            //        .Repeat()
            //        .Subscribe(this.Fire));
        }
Exemplo n.º 8
0
        private void BuildCssDocumentImpl(Element element, ICollection<string> path)
        {
            if (!element.IsRoot)
            {
                path.Add(element.Selector.ToCss());
                path.Add(element.Name);

                //Only add an element to the document when we have reached the end of the path
                if(element.Properties.Count !=0 )
                {
                 var cssProperties = new List<CssProperty>();

                    foreach (var property in element.Properties)
                        cssProperties.Add(new CssProperty(property.Key, property.Evaluate().ToCss()));

                    //Get path content i.e. "p > a:Hover"
                    var pathContent = string.Join(string.Empty, path.Where(p => !string.IsNullOrEmpty(p)).ToArray());
                    pathContent = pathContent.StartsWith(" ") ? pathContent.Substring(1) : pathContent;
                    _cssDocument.Elements.Add(new CssElement(pathContent, cssProperties));
                }
            }
            if (element.Inserts.Count != 0){
                foreach (var insert in element.Inserts)
                    _cssDocument.Elements.Add(new CssElement { InsertContent = insert.ToString()});
            }
            //Keep going
            foreach (var nextElement in element.Elements)
            {
                BuildCssDocumentImpl(nextElement, new List<string>(path));
            }
        }
        private static void AddDocumentToResults(object document, ICollection<MetadataSection> results)
        {
            ServiceDescription serviceDescription = document as ServiceDescription;
            XmlSchema xmlSchema = document as XmlSchema;
            XmlElement xmlElement = document as XmlElement;

            if (serviceDescription != null)
            {
                results.Add(MetadataSection.CreateFromServiceDescription(serviceDescription));
            }
            else if (xmlSchema != null)
            {
                results.Add(MetadataSection.CreateFromSchema(xmlSchema));
            }
            else if (xmlElement != null && (xmlElement.NamespaceURI == "http://schemas.xmlsoap.org/ws/2004/09/policy" || xmlElement.NamespaceURI == "http://www.w3.org/ns/ws-policy") && xmlElement.LocalName == "Policy")
            {
                results.Add(MetadataSection.CreateFromPolicy(xmlElement, null));
            }
            else
            {
                MetadataSection mexDoc = new MetadataSection();
                mexDoc.Metadata = document;
                results.Add(mexDoc);
            }
        }
        public void CreateItems(PostfixTemplateAcceptanceContext context, ICollection<ILookupItem> consumer)
        {
            if (!context.CanBeStatement || context.ExpressionType.IsUnknown) return;
              if (!context.Expression.IsPure()) return; // todo: better fix?

              string lengthProperty = null;
              if (context.ExpressionType is IArrayType) lengthProperty = "Length";
              else
              {
            var predefined = context.Expression.GetPredefinedType();
            var rule = context.Expression.GetTypeConversionRule();
            if (rule.IsImplicitlyConvertibleTo(context.ExpressionType, predefined.GenericICollection))
              lengthProperty = "Count";
              }

              if (lengthProperty == null) return;

              var forTemplate = string.Format("for (var $NAME$ = 0; $NAME$ < $EXPR$.{0}; $NAME$++) ", lengthProperty);
              var forrTemplate = string.Format("for (var $NAME$ = $EXPR$.{0}; $NAME$ >= 0; $NAME$--) ", lengthProperty);
              consumer.Add(new NameSuggestionPostfixLookupItem(
                     context, "for", forTemplate, context.Expression,
                     PluralityKinds.Plural, ScopeKind.LocalSelfScoped));
              consumer.Add(new NameSuggestionPostfixLookupItem(
                     context, "forr", forrTemplate, context.Expression,
                     PluralityKinds.Plural, ScopeKind.LocalSelfScoped));
        }
Exemplo n.º 11
0
        public PurchaseService(int dollarCoins, int quarterCoins, int dimeCoins, int nickleCoins, int pennyCoins)
        {
            _changeCoins = new List<Coin>();

            for (int i = 0; i < dollarCoins; i++)
            {
                _changeCoins.Add(new Coin() {ShortName = "o", Title = "Dollar", Value = 1});
            }
            for (int i = 0; i < quarterCoins; i++)
            {
                _changeCoins.Add(new Coin() { ShortName = "q", Title = "Quarter", Value = .25m});
            }
            for (int i = 0; i < dimeCoins; i++)
            {
                _changeCoins.Add(new Coin() { ShortName = "d", Title = "Dime", Value = .1m });
            }
            for (int i = 0; i < nickleCoins; i++)
            {
                _changeCoins.Add(new Coin() { ShortName = "n", Title = "Nickle", Value = .05m });
            }
            for (int i = 0; i < pennyCoins; i++)
            {
                _changeCoins.Add(new Coin() { ShortName = "p", Title = "Penny", Value = .01m });
            }
        }
Exemplo n.º 12
0
        private void BuildElement(ElementBlock elementBlock, ICollection<string> path)
        {
            if (!elementBlock.IsRoot())
            {
                path.Add(elementBlock.Selector.ToCss());
                path.Add(elementBlock.Name);

                //Only add an element to the document when we have reached the end of the path
                if (elementBlock.Properties.Count != 0)
                {
                    var cssProperties = new List<CssProperty>();

                    foreach (var property in elementBlock.Properties)
                        cssProperties.Add(new CssProperty(property.Key, property.Evaluate().ToCss()));

                    //Get path content i.e. "p > a:Hover"
                    var pathContent = path.Where(p => !string.IsNullOrEmpty(p)).JoinStrings(string.Empty);
                    pathContent = pathContent.StartsWith(" ") ? pathContent.Substring(1) : pathContent;
                    document.Elements.Add(new CssElement(pathContent, cssProperties));
                }
            }
            if (elementBlock.Inserts.Count == 0) return;
            foreach (var insert in elementBlock.Inserts)
                document.Elements.Add(new CssElement { InsertContent = insert.ToString() });
        }
Exemplo n.º 13
0
 public override void CollectValidationErrors(ICollection<string> errors)
 {
     if (String.IsNullOrEmpty(TableName))
         errors.Add(ErrorMessages.TableNameCannotBeNullOrEmpty);
     if (String.IsNullOrEmpty(DestinationSchemaName))
         errors.Add(ErrorMessages.DestinationSchemaCannotBeNull);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Flattens the specified curve. See <see cref="ICurve{TParam, TPoint}.Flatten"/>.
        /// </summary>
        /// <remarks>
        /// This method cannot be used for curves that contain gaps!
        /// </remarks>
        internal static void Flatten(ICurve<float, Vector3F> curve, ICollection<Vector3F> points, int maxNumberOfIterations, float tolerance)
        {
            if (tolerance <= 0)
            throw new ArgumentOutOfRangeException("tolerance", "The tolerance must be greater than zero.");

              float totalLength = curve.GetLength(0, 1, maxNumberOfIterations, tolerance);

              // No line segments if the curve has zero length.
              if (totalLength == 0)
            return;

              // A single line segment if the curve's length is less than the tolerance.
              if (totalLength < tolerance)
              {
            points.Add(curve.GetPoint(0));
            points.Add(curve.GetPoint(1));
            return;
              }

              var list = ResourcePools<Vector3F>.Lists.Obtain();

              Flatten(curve, list, 0, 1, curve.GetPoint(0), curve.GetPoint(1), 0, totalLength, 1, maxNumberOfIterations, tolerance);

              foreach (var point in list)
            points.Add(point);

              ResourcePools<Vector3F>.Lists.Recycle(list);
        }
Exemplo n.º 15
0
 private static void AddUvs(int tileRow, float tileSizeY, float tileSizeX, ICollection<Vector2> uvs, int tileColumn)
 {
     uvs.Add(new Vector2(tileColumn * tileSizeX, tileRow * tileSizeY));
     uvs.Add(new Vector2((tileColumn + 1) * tileSizeX, tileRow * tileSizeY));
     uvs.Add(new Vector2((tileColumn + 1) * tileSizeX, (tileRow + 1) * tileSizeY));
     uvs.Add(new Vector2(tileColumn * tileSizeX, (tileRow + 1) * tileSizeY));
 }
Exemplo n.º 16
0
		void RegisterCommands(ICollection<CommandBinding> commandBindings)
		{
			commandBindings.Add(new CommandBinding(ApplicationCommands.Find, ExecuteFind));
			commandBindings.Add(new CommandBinding(SearchCommands.FindNext, ExecuteFindNext));
			commandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious));
			commandBindings.Add(new CommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel));
		}
Exemplo n.º 17
0
 public static void DeserializeNullableCollection(BufferedTextReader sr, int nextToken, ICollection<TreePath?> res)
 {
     if (nextToken == 'n')
     {
         if (sr.Read() == 'u' && sr.Read() == 'l' && sr.Read() == 'l')
             res.Add(null);
         else throw new SerializationException("Invalid value found at position " + JsonSerialization.PositionInStream(sr) + " for string value. Expecting '\"' or null");
     }
     else res.Add(Deserialize(sr, nextToken));
     while ((nextToken = JsonSerialization.GetNextToken(sr)) == ',')
     {
         nextToken = JsonSerialization.GetNextToken(sr);
         if (nextToken == 'n')
         {
             if (sr.Read() == 'u' && sr.Read() == 'l' && sr.Read() == 'l')
                 res.Add(null);
             else throw new SerializationException("Invalid value found at position " + JsonSerialization.PositionInStream(sr) + " for string value. Expecting '\"' or null");
         }
         else res.Add(Deserialize(sr, nextToken));
     }
     if (nextToken != ']')
     {
         if (nextToken == -1) throw new SerializationException("Unexpected end of json in collection.");
         else throw new SerializationException("Expecting ']' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
     }
 }
Exemplo n.º 18
0
        private void RecursiveFindAndAddNodes(ICollection<Node> foundNodes, ArrayList nodesToSearch)
        {
            foreach (Node node in nodesToSearch)
            {
                if (!IsNodeSuitableForIndexing(node))
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(node.Id))
                {
                    foundNodes.Add(node);
                }

                if( node.EnumData != null && node.EnumData.Count > 0 )
                {
                    foreach(string enumVal in node.EnumData)
                    {
                        Node en = LibrarySearchMgr.StaticCreateNodeForEnumValue(node, enumVal);
                        foundNodes.Add(en);
                    }
                }

                if (node.HasChildren)
                {
                    RecursiveFindAndAddNodes(foundNodes, node.Children);
                }
            }
        }
Exemplo n.º 19
0
        private TenantRepository()
        {
            _tenants = new Collection<Tenant>();

            #region Initialize _tenants

            _tenants.Add(new Tenant
            {
                Host = "apple",
                Name = "Apple",
                Id = TenantIds.AppleId
            });
            _tenants.Add(new Tenant
            {
                Host = "microsoft",
                Name = "Microsoft",
                Id = TenantIds.MicrosoftId
            });
            _tenants.Add(new Tenant
            {
                Host = "bestbuy",
                Name = "BestBuy",
                Id = TenantIds.BestBuyId
            });

            #endregion

            _currentTenant = null;
        }
        public void CreateItems(PostfixTemplateAcceptanceContext context, ICollection<ILookupItem> consumer)
        {
            if (context.ExpressionType.IsUnknown)
              {
            if (!context.LooseChecks) return;
              }
              else
              {
            var canBeNull = context.ExpressionType.IsNullable() ||
              (context.ExpressionType.Classify == TypeClassification.REFERENCE_TYPE);

            if (!canBeNull) return;
              }

              var state = CSharpControlFlowNullReferenceState.UNKNOWN;

              if (!context.LooseChecks)
              {
            var declaredElement = context.ExpressionReferencedElement;
            var declaration = context.ContainingFunction;
            if (declaration != null && declaredElement != null && declaration.IsPhysical())
            {
              var graph = CSharpControlFlowBuilder.Build(declaration);
              if (graph != null)
              {
            var result = graph.Inspect(ValueAnalysisMode.OPTIMISTIC);
            if (!result.HasComplexityOverflow)
            {
              var referenceExpression = context.ReferenceExpression;

              foreach (var element in graph.AllElements)
              if (element.SourceElement == referenceExpression)
              {
                state = result.GetVariableStateAt(element, declaredElement); break;
              }
            }
              }
            }
              }

              switch (state)
              {
            case CSharpControlFlowNullReferenceState.MAY_BE_NULL:
            case CSharpControlFlowNullReferenceState.UNKNOWN:
            {
              if (context.CanBeStatement)
              {
            consumer.Add(new PostfixLookupItem(context, "notnull", "if ($EXPR$ != null) "));
            consumer.Add(new PostfixLookupItem(context, "null", "if ($EXPR$ == null) "));
              }
              else
              {
            consumer.Add(new PostfixLookupItem(context, "notnull", "$EXPR$ != null"));
            consumer.Add(new PostfixLookupItem(context, "null", "$EXPR$ == null"));
              }

              break;
            }
              }
        }
Exemplo n.º 21
0
        public void LoadSchemaObjects(ICollection<SchemaObject> objectList, DbConnectionInfo connectionInfo)
        {
            var extractor = new SchemaExtractor();
            objectList.Clear();
            var tables = extractor.GetTables(connectionInfo);
            var columns = extractor.GetTableColumns(connectionInfo);
            AddColumns(tables, columns);
            var primaryKeyColumns = GetPrimaryKeyColumns(connectionInfo);
            AddPrimaryKeys(tables, primaryKeyColumns);
            var views = extractor.GetViews(connectionInfo);
            var viewColumns = extractor.GetViewColumns(connectionInfo);
            AddViewColumns(views, viewColumns);
            var fKeys = GetForeignKeys(connectionInfo);
            AddForeignKeysToTables(tables, fKeys);

            var procedures = extractor.GetStoredProcedures(connectionInfo);
            var parameters = extractor.GetStoredProcedureParameters(connectionInfo);
            AddParametersToStoredProcedures(procedures, parameters);

            foreach (var procedure in procedures.Values)
                objectList.Add(procedure);

            foreach (var view in views.Values)
                objectList.Add(view);

            var sortedTables = from t in tables.Values
                               orderby t.Name
                               select t;
            foreach (var t in sortedTables)
                objectList.Add(t);
        }
Exemplo n.º 22
0
        private void ExtractParams(
            string code,
            StringCollection paramNames,
            ICollection <ObjectViewParameterLoader> paramLoaders)
        {
            int nameStart = 0;
            int nameEnd   = 0;

            for (int startIndex = 0; StrUtils.FindNameInVb(code, startIndex, ref nameStart, ref nameEnd); startIndex = nameEnd)
            {
                string str1 = code.Substring(nameStart, nameEnd - nameStart);
                if (str1.EndsWith("Property", StringComparison.InvariantCultureIgnoreCase))
                {
                    string name = str1.Substring(0, str1.Length - 8);
                    string str2 = name + "Property";
                    if (!paramNames.Contains(str2) && ObjectViewParameterLoader.CanCreate(this.FObjectView, name))
                    {
                        paramNames.Add(str2);
                        paramLoaders?.Add(ObjectViewParameterLoader.Create(this.FObjectView, name));
                    }
                }
            }
            paramNames.Add("ThisObject");
            paramLoaders?.Add((ObjectViewParameterLoader) new ObjectViewThisObjectLoader());
        }
Exemplo n.º 23
0
        private static void Empty(DirectoryInfo directory, ICollection<string> filesInUse)
        {
            if (!directory.Exists) return;

            try
            {
                filesInUse.Add(AggregatedFolder + PictureSlidesLabImagesList);
                filesInUse.Add(LoadingImgPath);
                filesInUse.Add(ChoosePicturesImgPath);
                filesInUse.Add(NoPicturePlaceholderImgPath);
                foreach (var file in directory.GetFiles())
                {
                    if (!filesInUse.Contains(file.FullName))
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch
                        {
                            // may be still in use, which is fine
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignore ex, if cannot delete trash
            }
        }
        private void AddPageTypePropertyDefinitions(IEnumerable<PropertyInfo> properties, ICollection<AuthorizedPropertyDefinition> definitions,
            TabDefinitionCollection tabDefinitions, string hierarchy, AuthorizeAttribute propertyGroupAuthorizeAttribute)
        {
            var pageTypeProperties = properties.Where(AttributedTypesUtility.PropertyHasAttribute<PageTypePropertyAttribute>).ToList();

            foreach (PropertyInfo property in pageTypeProperties)
            {
                AuthorizeAttribute attribute = AttributedTypesUtility
                                                    .GetAttributesFromProperty<AuthorizeAttribute>(property)
                                                    .FirstOrDefault();

                // if property has an authorize attribute
                if (attribute != null)
                {
                    definitions.Add(AuthorizedPropertyDefinitionFactory.Create(string.Concat(hierarchy, property.Name), attribute.GetAuthorizedPrincipals()));
                    continue;
                }

                // Add any tab authorization rules
                if (AddTabAuthorizationRules(tabDefinitions, property, definitions, hierarchy))
                    continue;

                // if property group authorize attribute has been defined then apply to property
                if (propertyGroupAuthorizeAttribute != null)
                {
                    definitions.Add(AuthorizedPropertyDefinitionFactory.Create(string.Concat(hierarchy, property.Name), propertyGroupAuthorizeAttribute.GetAuthorizedPrincipals()));
                    continue;
                }

                // if the page type class has an authorize attribute
                if (HasClassLevelAttribute)
                    definitions.Add(AuthorizedPropertyDefinitionFactory.Create(string.Concat(hierarchy, property.Name), ClassAttribute.GetAuthorizedPrincipals()));
            }
        }
Exemplo n.º 25
0
 private static void CreateObjects(ICollection<ExampleObject> list, int n = 50)
 {
     for (int i = 0; i < n; i++)
     {
         list.Add(
             new ExampleObject
             {
                 Boolean = true,
                 DateTime = DateTime.Now,
                 Color = Colors.Blue,
                 Number = Math.PI,
                 Fruit = Fruit.Apple,
                 Integer = 7,
                 Selector = null,
                 String = "Hello"
             });
         list.Add(
             new ExampleObject
             {
                 Boolean = false,
                 DateTime = DateTime.Now.AddDays(-1),
                 Color = Colors.Gold,
                 Number = Math.E,
                 Fruit = Fruit.Pear,
                 Integer = -1,
                 Selector = null,
                 String = "World"
             });
     }
 }
Exemplo n.º 26
0
        private void PrintCaseTableContent(IReportInfo report, ICaseInfo @case, ICollection<IRemark> remarks)
        {
            int procedureWidth = 19;
            int nameWidth = this.width - 2 * procedureWidth;

            foreach (ISubjectInfo subject in report.GetSubjects())
            {
                IResultData serialization = report.GetSerializationData(subject, @case);
                IResultData deserialization = report.GetDeserializationData(subject, @case);

                this.output.Write(subject.Name.PadRight(nameWidth));
                this.output.Write(serialization.Describe().PadLeft(procedureWidth));
                this.output.Write(deserialization.Describe().PadLeft(procedureWidth));
                this.output.WriteLine();

                if (serialization.HasRemark())
                {
                    remarks.Add(serialization.GetRemark());
                }

                if (deserialization.HasRemark())
                {
                    remarks.Add(deserialization.GetRemark());
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            _myBall = new Ball();
            _myBall.VelocityFromAngle(180.0f * (float)Math.PI / 180.0f, 800);
            _myBall.Circle.Position.X = 180;
            _myBall.Circle.Position.Y = 100 + 44;

            _levelBricks = new List<AABB>();

            _levelBricks.Add(new AABB(0, 0, 1, Game.Window.ClientBounds.Height));
            _levelBricks.Add(new AABB(0, Game.Window.ClientBounds.Height, Game.Window.ClientBounds.Width, 1));
            _levelBricks.Add(new AABB(Game.Window.ClientBounds.Width, 0, 1, Game.Window.ClientBounds.Height));
            _levelBricks.Add(new AABB(0, 0, Game.Window.ClientBounds.Width, 1));

            //_levelBricks.Add(new AABB(200, 100, 20, 65));
            //_levelBricks.Add(new AABB(200, 220, 20, 20));

            //_levelBricks.Add(new AABB(300, 300, 20, 20));
            //_levelBricks.Add(new AABB(20, 20, 20, 20));

            //Random r = new Random();

            //for (int i = 0; i < 40; ++i)
            //{
            //    _levelBricks.Add(new AABB(r.Next(0, Game.Window.ClientBounds.Width), r.Next(0, Game.Window.ClientBounds.Height), r.Next(20, 30), r.Next(20, 30)));
            //}

            _prevKeyState = Keyboard.GetState();

            base.Initialize();
        }
Exemplo n.º 28
0
 protected override bool HandleCore(TokenParser context, ICollection<Token> tokens, char ch)
 {
     if (ch == '>')
     {
         Token token = context.SwitchState(TokenType.Text, new TextHandler());
         tokens.Add(token);
         if (token.Type == TokenType.OpenTag && (token.Value == "script" || token.Value == "style"))
         {
             tokens.Add(context.SwitchState(TokenType.Text, new CDataHandler(string.Format("</{0}", token.Value))));
         }
         return true;
     }
     if (ch == '/' || Char.IsWhiteSpace(ch))
     {
         var handler = new AttibuteNameHandler();
         Token token = context.SwitchState(TokenType.AttributeName, handler);
         if (token.Type == TokenType.OpenTag && (token.Value == "script" || token.Value == "style"))
         {
             handler.ReplaceNextTagOrTextTokenWithCData = string.Format("</{0}", token.Value);
         }
         tokens.Add(token);
         return true;
     }
     return false;
 }
 protected virtual void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
 {
     if (number < 20)
     {
         parts.Add(GetUnits(number, gender));
     }
     else
     {
         var units = number%10;
         var tens = GetTens(number/10);
         if (units == 0)
         {
             parts.Add(tens);
         }
         else if (units == 1)
         {
             parts.Add(tens);
             parts.Add("et");
             parts.Add(GetUnits(1, gender));
         }
         else
         {
             parts.Add(string.Format("{0}-{1}", tens, GetUnits(units, gender)));
         }
     }
 }
Exemplo n.º 30
0
 public PhoneServiceFake()
 {
     sampleData = new List<Models.PhoneModel>();
     sampleData.Add(new Models.PhoneModel{
         applicantId = 1,
         createDate = DateTime.Now,
         lastModifiedDate = DateTime.Now,
         phoneCd = "AA",
         phoneId = 1,
         phoneNumber = 1234567890
     });
     sampleData.Add(new Models.PhoneModel
     {
         applicantId = 1,
         createDate = DateTime.Now,
         lastModifiedDate = DateTime.Now,
         phoneCd = "AA",
         phoneId = 2,
         phoneNumber = 2224567890
     });
     sampleData.Add(new Models.PhoneModel
     {
         applicantId = 2,
         createDate = DateTime.Now,
         lastModifiedDate = DateTime.Now,
         phoneCd = "AA",
         phoneId = 3,
         phoneNumber = 3334567890
     });
 }
Exemplo n.º 31
0
        public static void ParseDealPage(HtmlDocument htmlDoc, ICollection<SteamSpecialItemViewModel> retList)
        {
            if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
            {
                return;
            }
            if (htmlDoc.DocumentNode != null)
            {
                var searchResults = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='search_results']");

                if (searchResults != null)
                {
                    var even = searchResults.SelectNodes("//a[@class='search_result_row even']");
                    var odd = searchResults.SelectNodes("//a[@class='search_result_row odd']");

                    if (even != null && odd != null)
                    {
                        var max = Math.Max(even.Count, odd.Count);
                        for (var i = 0; i < max; ++i)
                        {
                            if (i < even.Count)
                            {
                                retList.Add(ParseNode(even[i]));
                            }
                            if (i < odd.Count)
                            {
                                retList.Add(ParseNode(odd[i]));
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 32
0
 private static void AddNormals(ICollection<Vector3> normals)
 {
     normals.Add(Vector3.forward);
     normals.Add(Vector3.forward);
     normals.Add(Vector3.forward);
     normals.Add(Vector3.forward);
 }
Exemplo n.º 33
0
        public static void FlattenCubic(Point[] controlPoints, double errorTolerance, ICollection <Point> resultPolyline, bool skipFirstPoint, ICollection <double> resultParameters = null)
        {
            if (resultPolyline == null)
            {
                throw new ArgumentNullException(nameof(resultPolyline));
            }
            if (controlPoints == null)
            {
                throw new ArgumentNullException(nameof(controlPoints));
            }
            if (controlPoints.Length != 4)
            {
                throw new ArgumentOutOfRangeException(nameof(controlPoints));
            }
            EnsureErrorTolerance(ref errorTolerance);
            if (!skipFirstPoint)
            {
                resultPolyline.Add(controlPoints[0]);
                resultParameters?.Add(0.0);
            }

            if (IsCubicChordMonotone(controlPoints, errorTolerance * errorTolerance))
            {
                var flattener = new AdaptiveForwardDifferencingCubicFlattener(controlPoints, errorTolerance,
                                                                              errorTolerance, true);
                var p = new Point();
                var u = 0.0;
                while (flattener.Next(ref p, ref u))
                {
                    resultPolyline.Add(p);
                    resultParameters?.Add(u);
                }
            }
            else
            {
                var x     = controlPoints[3].X - controlPoints[2].X + controlPoints[1].X - controlPoints[0].X;
                var y     = controlPoints[3].Y - controlPoints[2].Y + controlPoints[1].Y - controlPoints[0].Y;
                var num4  = 1.0 / errorTolerance;
                var depth = Log8UnsignedInt32((uint)(MathHelper.Hypotenuse(x, y) * num4 + 0.5));
                if (depth > 0)
                {
                    depth--;
                }
                if (depth > 0)
                {
                    DoCubicMidpointSubdivision(controlPoints, depth, 0.0, 1.0, 0.75 * num4, resultPolyline,
                                               resultParameters);
                }
                else
                {
                    DoCubicForwardDifferencing(controlPoints, 0.0, 1.0, 0.75 * num4, resultPolyline,
                                               resultParameters);
                }
            }

            resultPolyline.Add(controlPoints[3]);
            resultParameters?.Add(1.0);
        }
Exemplo n.º 34
0
        public DataReader GetReader(DbCommand command, ICollection <T> key)
        {
            string fullCommandText = command.CommandText;

            try
            {
                string[] columnNames          = null;
                IEnumerable <object[]> values = null;
                List <Tuple <string[], IEnumerable <object[]> > > resultSets = new List <Tuple <string[], IEnumerable <object[]> > >();

                KeyValuePair <T, Item> item = _items.FirstOrDefault(x => x.Value.IsApplicable(command));
                if (item.Value != null)
                {
                    key?.Add(item.Key);
                    columnNames = item.Value.ColumnNames;
                    values      = item.Value.GetValues();
                    resultSets.Add(Tuple.Create(item.Value.ColumnNames, item.Value.GetValues()));
                }
                else
                {
                    foreach (string commandText in fullCommandText.Split(';'))
                    {
                        command.CommandText = commandText;

                        item = _items.FirstOrDefault(x => x.Value.IsApplicable(command));
                        if (item.Value == null)
                        {
                            return(null);
                        }

                        key?.Add(item.Key);
                        if (columnNames == null)
                        {
                            columnNames = item.Value.ColumnNames;
                            values      = item.Value.GetValues();
                        }
                        else
                        {
                            resultSets.Add(Tuple.Create(item.Value.ColumnNames, item.Value.GetValues()));
                        }
                    }
                }

                return(new DataReader(columnNames, values, resultSets));
            }
            finally
            {
                command.CommandText = fullCommandText;
            }
        }
Exemplo n.º 35
0
        public bool Validate(string inputFile, ICollection <string> errors = null)
        {
            string schemaPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "books.xsd");

            settings.Schemas.Add("http://library.by/catalog", schemaPath);
            bool isValid = true;

            settings.ValidationEventHandler += (sender, args) =>
            {
                isValid = false;
                errors?.Add($"[{args.Exception.LineNumber}:{args.Exception.LinePosition}] {args.Message}");
            };

            settings.ValidationFlags = settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationType  = ValidationType.Schema;

            XmlReader reader = XmlReader.Create(inputFile, settings);

            while (reader.Read())
            {
                ;
            }

            return(isValid);
        }
Exemplo n.º 36
0
 private async Task ReadStreamAsync(
     StreamReader source,
     TextWriter?writer,
     ICollection <string>?output1,
     ICollection <string>?output2,
     Action <string>?onOutput1,
     Action <string>?onOutput2,
     StringBuilder?outputBuilder1,
     StringBuilder?outputBuilder2)
 {
     try
     {
         string?line;
         while ((line = await source.ReadLineAsync()) != null)
         {
             writer?.WriteLine(line);
             lock (this.outputLockObject)
             {
                 output1?.Add(line);
                 output2?.Add(line);
                 onOutput1?.Invoke(line);
                 onOutput2?.Invoke(line);
                 outputBuilder1?.AppendLine(line);
                 outputBuilder2?.AppendLine(line);
             }
         }
     }
     catch { }
 }
Exemplo n.º 37
0
        /// <summary>
        /// Add or update entities from a JArray of changes during a PATCH.
        /// </summary>
        /// <param name="entityCollection">Collection of entities:  New entities will be added to this collection.</param>
        /// <param name="changeArray">JArray of changes.</param>
        protected void AddUpdateFromJArray <T1>(ICollection <T1> entityCollection, JArray changeArray) where T1 : class, IEntity
        {
            if (changeArray == null)
            {
                return;
            }

            foreach (JObject jobject in changeArray)
            {
                T1 entity = jobject.ToObject <T1>();
                if (entity != null)
                {
                    T1 foundEntity = null;
                    if (entity.Id != Guid.Empty)
                    {
                        foundEntity = unitOfWork.GetById <T1>(entity.Id);
                    }
                    if (foundEntity != null)
                    {
                        // The entity already exists.
                        UpdateFromJObject(foundEntity, jobject);
                    }
                    else
                    {
                        // The entity doesn't exist - either the ID was empty, or it's a new ID.
                        unitOfWork.Insert(entity);
                        entityCollection?.Add(entity);
                        BusinessLogicHelper.GetBusinessLogic <T1>(unitOfWork)?.Validate(entity);
                    }
                }
            }
        }
Exemplo n.º 38
0
        public static T GetInactiveOrCreate <T>(ICollection <T> collection, Func <T> instantiate, Transform parent,
                                                bool activeSelf = true, bool modifyTransform = true) where T : Component
        {
            T retval = null;

            try {
                retval = collection.First((arg) =>
                                          arg != null && !(activeSelf ? arg.gameObject.activeSelf : arg.gameObject.activeInHierarchy));
            } catch {
                retval = instantiate();
                collection?.Add(retval);
            }

            retval.transform.SetParent(parent, false);

            if (modifyTransform)
            {
                retval.transform.localScale    = Vector3.one;
                retval.transform.localPosition = Vector3.zero;
                retval.transform.localRotation = Quaternion.identity;
            }

            retval.gameObject.SetActive(true);
            return(retval);
        }
Exemplo n.º 39
0
        /// <summary>
        ///     Tests whether the given object instance is valid.
        /// </summary>
        /// <remarks>
        ///     This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type.  It also
        ///     checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set.  If
        ///     <paramref name="validateAllProperties" />
        ///     is <c>true</c>, this method will also evaluate the <see cref="ValidationAttribute" />s for all the immediate
        ///     properties
        ///     of this object.  This process is not recursive.
        ///     <para>
        ///         If <paramref name="validationResults" /> is null, then execution will abort upon the first validation
        ///         failure.  If <paramref name="validationResults" /> is non-null, then all validation attributes will be
        ///         evaluated.
        ///     </para>
        ///     <para>
        ///         For any given property, if it has a <see cref="RequiredAttribute" /> that fails validation, no other validators
        ///         will be evaluated for that property.
        ///     </para>
        /// </remarks>
        /// <param name="instance">The object instance to test.  It cannot be null.</param>
        /// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param>
        /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
        /// <param name="validateAllProperties">
        ///     If <c>true</c>, also evaluates all properties of the object (this process is not
        ///     recursive over properties of the properties).
        /// </param>
        /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
        /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
        /// <exception cref="ArgumentException">
        ///     When <paramref name="instance" /> doesn't match the
        ///     <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
        /// </exception>
        public static bool TryValidateObject(object instance, ValidationContext validationContext,
                                             ICollection <ValidationResult> validationResults, bool validateAllProperties)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            if (validationContext != null && instance != validationContext.ObjectInstance)
            {
                throw new ArgumentException(
                          SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance));
            }

            var result            = true;
            var breakOnFirstError = (validationResults == null);

            foreach (
                var err in
                GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError))
            {
                result = false;

                validationResults?.Add(err.ValidationResult);
            }

            return(result);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Enumerate the directory
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="files"></param>
        /// <param name="directories"></param>
        /// <param name="searchDepth">The maximum search pepth</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        public static void EnumerateDirectory(string dirName, ICollection <string> files = null, ICollection <string> directories = null, int searchDepth = int.MaxValue)
        {
            var q = new Queue <KeyValuePair <string, int> >();

            q.Enqueue(new KeyValuePair <string, int>(dirName, 0));
            try
            {
                while (q.Count > 0)
                {
                    var t = q.Dequeue();
                    if (t.Value < searchDepth)
                    {
                        IEnumerator <string> i;
                        for (i = Directory.EnumerateDirectories(t.Key).GetEnumerator(); i.MoveNext();)
                        {
                            q.Enqueue(new KeyValuePair <string, int>(i.Current, t.Value + 1));
                            directories?.Add(i.Current);
                        }
                        if (files != null)
                        {
                            for (i = Directory.EnumerateFiles(t.Key).GetEnumerator(); i.MoveNext();)
                            {
                                files.Add(i.Current);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error enumerating files/directories: " + ex);
            }
        }
Exemplo n.º 41
0
        protected void AddParseError(string description)
        {
            var errorData = new ScriptParseError(this, description);

            errors?.Add(errorData);
            Debug.LogError(errorData);
        }
Exemplo n.º 42
0
        /// <summary>
        /// Gets the types defined in an assembly.
        /// </summary>
        /// <param name="assembly">The reflected assembly.</param>
        /// <param name="assemblyFileName">The file name of the assembly.</param>
        /// <param name="warningMessages">Contains warnings if any, that need to be passed back to the caller.</param>
        /// <returns>Gets the types defined in the provided assembly.</returns>
        internal Type[] GetTypes(Assembly assembly, string assemblyFileName, ICollection <string> warningMessages)
        {
            var types = new List <Type>();

            try
            {
                types.AddRange(assembly.DefinedTypes.Select(typeinfo => typeinfo.AsType()));
            }
            catch (ReflectionTypeLoadException ex)
            {
                PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning($"MSTestExecutor.TryGetTests: {Resource.TestAssembly_AssemblyDiscoveryFailure}", assemblyFileName, ex);
                PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning(Resource.ExceptionsThrown);

                if (ex.LoaderExceptions != null)
                {
                    // If not able to load all type, log a warning and continue with loaded types.
                    var message = string.Format(CultureInfo.CurrentCulture, Resource.TypeLoadFailed, assemblyFileName, this.GetLoadExceptionDetails(ex));

                    warningMessages?.Add(message);

                    foreach (var loaderEx in ex.LoaderExceptions)
                    {
                        PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning("{0}", loaderEx);
                    }
                }

                return(ex.Types);
            }

            return(types.ToArray());
        }
Exemplo n.º 43
0
        /// <summary>
        ///     Tests whether the given object instance is valid.
        /// </summary>
        /// <remarks>
        ///     This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type.  It also
        ///     checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set.  If
        ///     <paramref name="validateAllProperties" />
        ///     is <c>true</c>, this method will also evaluate the <see cref="ValidationAttribute" />s for all the immediate
        ///     properties
        ///     of this object.  This process is not recursive.
        ///     <para>
        ///         If <paramref name="validationResults" /> is null, then execution will abort upon the first validation
        ///         failure.  If <paramref name="validationResults" /> is non-null, then all validation attributes will be
        ///         evaluated.
        ///     </para>
        ///     <para>
        ///         For any given property, if it has a <see cref="RequiredAttribute" /> that fails validation, no other validators
        ///         will be evaluated for that property.
        ///     </para>
        /// </remarks>
        /// <param name="instance">The object instance to test.  It cannot be null.</param>
        /// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param>
        /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param>
        /// <param name="validateAllProperties">
        ///     If <c>true</c>, also evaluates all properties of the object (this process is not
        ///     recursive over properties of the properties).
        /// </param>
        /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns>
        /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception>
        /// <exception cref="ArgumentException">
        ///     When <paramref name="instance" /> doesn't match the
        ///     <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
        /// </exception>
        public static bool TryValidateObject(object instance, ValidationContext validationContext,
                                             ICollection <ValidationResult>?validationResults, bool validateAllProperties)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            // TODO-NULLABLE: null validationContext isn't supported (GetObjectValidationErrors will throw), remove that check
            if (validationContext != null && instance != validationContext.ObjectInstance)
            {
                throw new ArgumentException(SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance));
            }

            var result            = true;
            var breakOnFirstError = (validationResults == null);

            foreach (ValidationError err in GetObjectValidationErrors(instance, validationContext !, validateAllProperties, breakOnFirstError))
            {
                result = false;

                validationResults?.Add(err.ValidationResult);
            }

            return(result);
        }
Exemplo n.º 44
0
 public static void EnumFiles(this DirectoryInfo directory, ICollection <FileInfo> filecollect, CancellationToken cancellation)
 {
     directory.EnumFiles(_p =>
     {
         filecollect?.Add(_p);
     }, cancellation);
 }
Exemplo n.º 45
0
        public ICollection<EventBean> Lookup(
            EventBean[] eventPerStream,
            IDictionary<object, CompositeIndexEntry> parent,
            ICollection<EventBean> result,
            CompositeIndexQuery next,
            ExprEvaluatorContext context,
            ICollection<object> optionalKeyCollector,
            CompositeIndexQueryResultPostProcessor postProcessor)
        {
            var index = (IOrderedDictionary<object, CompositeIndexEntry>) parent;
            var comparable = base.EvaluatePerStream(eventPerStream, context);
            optionalKeyCollector?.Add(comparable);

            if (comparable == null) {
                return null;
            }

            return CompositeIndexQueryRange.Handle(
                eventPerStream,
                index.Tail(comparable),
                null,
                result,
                next,
                postProcessor);
        }
Exemplo n.º 46
0
        //Primary
        public Cop(string vehmodel, SpawnPt pos, SpawnPt targetPos, bool isSwat = false, ICollection <Cop> copList = null)
        {
            string copModel = isSwat ? "s_m_y_swat_01" : "s_m_y_cop_01";

            Veh = new Vehicle(vehmodel, pos.Spawn, pos.Heading);
            Ped = new Ped(copModel, Veh.LeftPosition, Veh.Heading);
            Ped.RelationshipGroup = RelationshipGroup.Cop;
            if (isSwat)
            {
                var w = new Weapon(new WeaponAsset("WEAPON_CARBINERIFLE"), Ped.Position, 120);
                if (w.Exists())
                {
                    w.GiveTo(Ped);
                }
                NativeFunction.Natives.SetPedPropIndex(Ped, 0, 0, 0, true);
            }
            Functions.SetPedAsCop(Ped);
            Functions.SetCopAsBusy(Ped, true);
            TargetPosition = targetPos;
            Ped.MakeMissionPed();
            Veh.MakeMissionVehicle();
            Ped.BlockPermanentEvents = true;
            Ped.Tasks.StandStill(-1);
            copList?.Add(this);
        }
Exemplo n.º 47
0
 public static void EnumFiles(this DirectoryInfo directory, ICollection <FileInfo> filecollect)
 {
     directory.EnumFiles(_p =>
     {
         filecollect?.Add(_p);
         return(true);
     });
 }
        /// <summary>
        /// Creates a reactive subscriptions for a <see cref="IHaveWritableRequirementStateOfCompliance"/> object
        /// </summary>
        /// <param name="requirementStateOfComplianceObject">The <see cref="IHaveWritableRequirementStateOfCompliance"/></param>
        /// <param name="thing">The <see cref="Thing"/> that te subscription is set for</param>
        /// <param name="disposables">The <see cref="ICollection{IDisposable}"/> where the subscription must be added to to avoid memory leaks</param>
        public static void SetRequirementStateOfComplianceChangedEventSubscription(this IHaveWritableRequirementStateOfCompliance requirementStateOfComplianceObject, Thing thing, ICollection <IDisposable> disposables)
        {
            var requirementVerifierListener = CDPMessageBus.Current.Listen <RequirementStateOfComplianceChangedEvent>(thing)
                                              .ObserveOn(RxApp.MainThreadScheduler)
                                              .Subscribe(x => SetRequirementStateOfCompliance(requirementStateOfComplianceObject, x));

            disposables?.Add(requirementVerifierListener);

            if (thing is RelationalExpression)
            {
                var resetRequirementVerifierListener = CDPMessageBus.Current.Listen <RequirementStateOfComplianceChangedEvent>(typeof(ParameterOrOverrideBase))
                                                       .ObserveOn(RxApp.MainThreadScheduler)
                                                       .Subscribe(x => { ResetRequirementStateOfComplianceTree(requirementStateOfComplianceObject); });

                disposables?.Add(resetRequirementVerifierListener);
            }
        }
Exemplo n.º 49
0
 private void SetSingleTile(Vector3Int generateTileCellPosition, ICollection <Vector3Int> extendCollectionByNewTile = null)
 {
     extendCollectionByNewTile?.Add(generateTileCellPosition);
     if (this.generatedTilesCellPosition.Contains(generateTileCellPosition))
     {
         return;
     }
     this.currentTilemap.SetTile(generateTileCellPosition, this.tile);
 }
Exemplo n.º 50
0
        public int Query(Envelope extent, Predicate <T> filter, ICollection <T> results)
        {
            if (extent == null)
            {
                throw new ArgumentNullException(nameof(extent));
            }

            return(Query(_root, extent, filter, node => results?.Add(node.Payload)));
        }
Exemplo n.º 51
0
        public T LoadOrUseDefault <T>(ICollection <LogEventInfo> log = null) where T : ConfigurationBase, new()
        {
            string path = GetDefaultPath();

            if (!File.Exists(path))
            {
                log?.Add(new LogEventInfo(LogLevel.Info, logger.Name, null, "Unable to load configuration from \"" + path + "\"", null, new FileNotFoundException("File not found", path)));
                return(new T());
            }

            try
            {
                return(Load <T>());
            }
            catch (Exception exc)
            {
                log?.Add(new LogEventInfo(LogLevel.Info, logger.Name, null, "Unable to load configuration from \"" + path + "\"", null, exc));
                return(new T());
            }
        }
Exemplo n.º 52
0
 //based on https://stackoverflow.com/questions/58744/copy-the-entire-contents-of-a-directory-in-c-sharp
 private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target, ICollection <string> copiedPathsCollection = null)
 {
     foreach (DirectoryInfo dir in source.GetDirectories())
     {
         CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name), copiedPathsCollection);
     }
     foreach (FileInfo file in source.GetFiles())
     {
         file.CopyTo(Path.Combine(target.FullName, file.Name), true);
         copiedPathsCollection?.Add(file.Name);
     }
 }
Exemplo n.º 53
0
        private static bool ReassemblyRule([NotNull] string s, ICollection <IReassembly> lr)
        {
            var m = Regex.Match(s, "^.*?reasmb:( )+(?<value>.*)$");

            if (m.Success)
            {
                lr?.Add(new ConstantReassembly(m.Groups["value"].Value));
                return(true);
            }

            return(false);
        }
Exemplo n.º 54
0
        internal static bool TryValidateObject(object instance, LocalizedValidationContext validationContext, ICollection <ValidationResult> validationResults, bool validateAllProperties)
        {
            var result            = true;
            var breakOnFirstError = validationResults == null;

            foreach (var objectValidationError in GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError))
            {
                result = false;
                validationResults?.Add(objectValidationError.ValidationResult);
            }
            return(result);
        }
Exemplo n.º 55
0
        public ICollection<EventBean> Lookup(
            EventBean theEvent,
            IDictionary<object, CompositeIndexEntry> parent,
            ICollection<EventBean> result,
            CompositeIndexQuery next,
            ExprEvaluatorContext context,
            ICollection<object> optionalKeyCollector,
            CompositeIndexQueryResultPostProcessor postProcessor)
        {
            object comparableStart = base.EvaluateLookupStart(theEvent, context);
            optionalKeyCollector?.Add(comparableStart);

            if (comparableStart == null) {
                return null;
            }

            object comparableEnd = base.EvaluateLookupEnd(theEvent, context);
            optionalKeyCollector?.Add(comparableEnd);

            if (comparableEnd == null) {
                return null;
            }

            IOrderedDictionary<object, CompositeIndexEntry> index =
                (IOrderedDictionary<object, CompositeIndexEntry>) parent;

            
            IDictionary<object, CompositeIndexEntry> submap;
            if (index.KeyComparer.Compare(comparableStart, comparableEnd) <= 0) {
                submap = index.Between(comparableStart, includeStart, comparableEnd, includeEnd);
            }
            else if (_allowReverseRange) {
                submap = index.Between(comparableEnd, includeStart, comparableStart, includeEnd);
            }
            else {
                return null;
            }

            return CompositeIndexQueryRange.Handle(theEvent, submap, null, result, next, postProcessor);
        }
Exemplo n.º 56
0
        public static JArray SheetToJson(Sheet sheet,
                                         SheetParser parser, bool ignoreFirstRow = false, ICollection <Cell> notParsedCells = null)
        {
            Ensure.Argument.NotNull(sheet, nameof(sheet));
            Ensure.Argument.NotNull(parser, nameof(parser));

            var json = new JArray();

            foreach (var row in sheet.Rows)
            {
                if (ignoreFirstRow && row.Index == 0)
                {
                    continue;
                }

                var jsonRow = new JObject();
                foreach (var cell in row.Cells)
                {
                    var value = cell.Value;
                    if (!Index.IsValid(cell.ColumnIndex, parser.ColumnCount))
                    {
                        notParsedCells?.Add(cell);
                        continue;
                    }

                    var columnParser = parser[cell.ColumnIndex];
                    var jsonValue    = columnParser.Parse(value);
                    if (jsonValue != null)
                    {
                        jsonRow[columnParser.Name] = jsonValue;
                    }
                    else
                    {
                        notParsedCells?.Add(cell);
                    }
                }
                json.Add(jsonRow);
            }
            return(json);
        }
Exemplo n.º 57
0
 public bool ExecutePlugin(string usage, ICollection <IPlugin> results)
 {
     if (!plugins.TryGetValue(usage, out ICollection <IPlugin> pluginList))
     {
         return(false);
     }
     foreach (IPlugin plugin in pluginList)
     {
         plugin.Execute();
         results?.Add(plugin);
     }
     return(true);
 }
Exemplo n.º 58
0
        internal static bool TryValidateProperty(object value, LocalizedValidationContext validationContext, ICollection <ValidationResult> validationResults)
        {
            var result                       = true;
            var breakOnFirstError            = validationResults == null;
            var propertyValidationAttributes = _store.GetPropertyValidationAttributes(validationContext.Context);

            foreach (var validationError in GetValidationErrors(value, validationContext, propertyValidationAttributes, breakOnFirstError))
            {
                result = false;
                validationResults?.Add(validationError.ValidationResult);
            }
            return(result);
        }
 /// <summary>
 /// Applies Select and Where in a single step to take advantage of TryParse methods, e.g. taking an array of strings and returning
 /// all those as ints that successfully passed int.TryParse(). Items that were rejected by <paramref name="selector"/> are added
 /// to <paramref name="discarded"/>.
 /// </summary>
 public static IEnumerable <TResult> SelectWhere <TSource, TResult>(this IEnumerable <TSource> items, Parser <TSource, TResult> selector, ICollection <TSource> discarded)
 {
     foreach (TSource item in items)
     {
         if (selector(item, out TResult result))
         {
             yield return(result);
         }
         else
         {
             discarded?.Add(item);
         }
     }
 }
Exemplo n.º 60
0
            /// <summary>
            /// Applied after InitializeToggles runs.
            /// </summary>
            internal static void Postfix(ICollection <KIconToggleMenu.ToggleInfo> ___overlayToggleInfos)
            {
                LocString.CreateLocStringKeys(typeof(PipPlantOverlayStrings.UI));
                var action = (OpenOverlay == null) ? PAction.MaxAction : OpenOverlay.
                             GetKAction();
                var info = CreateOverlayInfo(PipPlantOverlayStrings.UI.OVERLAYS.PIPPLANTING.
                                             BUTTON, PipPlantOverlayStrings.OVERLAY_ICON, PipPlantOverlay.ID, action,
                                             PipPlantOverlayStrings.UI.OVERLAYS.PIPPLANTING.TOOLTIP);

                if (info != null)
                {
                    ___overlayToggleInfos?.Add(info);
                }
            }