Example #1
0
        public bool ValidAttributesFor(string table, string featureType, IEnumerable<FeatureActions> actions)
        {
            if (string.IsNullOrEmpty(featureType))
            {
                return false;
            }

            featureType = featureType.ToLower();

            if (featureType == "affected area" && actions == null)
            {
                return true;
            }

            if (string.IsNullOrEmpty(table))
            {
                return false;
            }

            table = table.ToLower();

            if (actions == null)
            {
                return false;
            }

            switch (table)
            {
                case "poly":
                    return
                        actions.All(
                            x =>
                                !string.IsNullOrEmpty(x.Action) &&
                                x.Treatments.All(t => !string.IsNullOrEmpty(t.Treatment)));
                case "point":
                    if (actions.Count() != 1)
                    {
                        return false;
                    }

                    if (new[] {"guzzler", "fish passage structure"}.Contains(featureType))
                    {
                        return actions.All(x => !string.IsNullOrEmpty(x.Action) &&
                                                 !string.IsNullOrEmpty(x.Type));
                    }

                    return actions.All(x => !string.IsNullOrEmpty(x.Description));
                case "line":
                    if (actions.Count() != 1)
                    {
                        return false;
                    }

                    return actions.All(x => !string.IsNullOrEmpty(x.Action) &&
                                                 !string.IsNullOrEmpty(x.Type));

            }

            return false;
        }
        /// <summary>
        /// Exports specified stops to serializable stop information.
        /// </summary>
        /// <param name="stops">The reference to the collection of stops to be exported.</param>
        /// <param name="capacitiesInfo">The reference to capacities info object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderCustomPropertiesInfo">The reference custom order properties info
        /// object.</param>
        /// <param name="addressFields">The reference to address fields object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="solver">The reference to VRPSolver to be used for retrieving
        /// curb approach policies for stops.</param>
        /// <param name="orderPropertiesFilter">Function returning true for custom order
        /// property names which should not be exported.</param>
        /// <returns>A reference to the collection of serializable stop information objects.
        /// </returns>
        public static IEnumerable<StopInfo> ExportStops(
            IEnumerable<Stop> stops,
            CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo,
            AddressField[] addressFields,
            IVrpSolver solver,
            Func<string, bool> orderPropertiesFilter = null)
        {
            Debug.Assert(stops != null);
            Debug.Assert(stops.All(stop => stop != null));
            Debug.Assert(stops.All(stop => stop.Route != null));
            Debug.Assert(capacitiesInfo != null);
            Debug.Assert(orderCustomPropertiesInfo != null);
            Debug.Assert(addressFields != null);

            if (!stops.Any())
            {
                return Enumerable.Empty<StopInfo>();
            }

            var capacityProperties = Order.GetPropertiesInfo(capacitiesInfo);
            var addressProperties = Order.GetPropertiesInfo(addressFields);
            var customProperties = Order.GetPropertiesInfo(orderCustomPropertiesInfo);

            var exportOrderProperties = _CreateExportOrderProperties(
                capacitiesInfo,
                orderCustomPropertiesInfo,
                addressFields,
                orderPropertiesFilter);

            // Make a dictionary for mapping routes to collection of sorted route stops.
            var routesSortedStops = stops
                .Select(stop => stop.Route)
                .Distinct()
                .ToDictionary(route => route, route => CommonHelpers.GetSortedStops(route));

            // Prepare result by exporting each stop individually.
            var settings = CommonHelpers.GetSolverSettings(solver);
            var result = stops
                .Select(stop => _ExportStop(
                    stop,
                    routesSortedStops[stop.Route],
                    exportOrderProperties,
                    addressProperties,
                    capacityProperties,
                    customProperties,
                    settings))
                .ToList();

            return result;
        }
        public static ValidationResult Create(RuleValidator validator, RuleValidatorContext context, IList<Object> parameterValues, object messageKey, IEnumerable<ValidationResult> nestedValidationResults = null)
        {
            string message = string.Empty;
            var messageService = new MessageService();

            if (String.IsNullOrEmpty(validator.Message))
            {
                var messageContext = new MessageContext(context, validator.GetType(), validator.Negate, validator.MessageStoreName, messageKey, validator.MessageFormatter);
                message = messageService.GetDefaultMessageAndFormat(messageContext, parameterValues);
            }
            else
            {
                //Since the message was supplied, don't get the default message from the store, just format it
                message = messageService.FormatMessage(validator.Message, context, parameterValues, validator.MessageFormatter);
            }

            //Override level if all the nested validation errors are Warnings

            if (nestedValidationResults != null && nestedValidationResults.All(vr => vr.Level == ValidationLevelType.Warn))
            {
                return new ValidationResult(context.PropertyInfo, message, ValidationLevelType.Warn, context.PropertyValue, nestedValidationResults);
            }
            else
            {
                return new ValidationResult(context.PropertyInfo, message, context.Level, context.PropertyValue, nestedValidationResults);
            }

            //return new ValidationResult(context.PropertyInfo, message, context.Level, context.PropertyValue, nestedValidationResults);
        }
Example #4
0
        /// <summary>
        /// Create a span_near query.
        /// </summary>
        /// <param name="clauses">The span queries used to find documents.</param>
        public SpanNearQuery(IEnumerable<SpanQueryBase> clauses)
        {
            if (clauses == null || clauses.All(x => x == null))
                throw new ArgumentNullException("clauses", "SpanNearQuery requires at least one span query for clauses.");

            Clauses = clauses;
        }
		public IReadOnlyCollection<string> GetBlockWrapper(IEnumerable<string> code)
		{
			// If the code doesn't have any braces, surround it in a ruleset so that properties are valid.
			if (code.All(t => t.IndexOfAny(new[] { '{', '}' }) == -1))
				return new[] { ".GeneratedClass-" + Guid.NewGuid() + " {", "}" };
			return null;
		}
        /// <summary>
        /// Create a script_field value.
        /// </summary>
        /// <param name="fields">The fields to create, and the scripts to create them with.</param>
        public ScriptFieldRequest(IEnumerable<ScriptField> fields)
        {
            if (fields == null || fields.All(x => x == null))
                throw new ArgumentNullException("fields", "ScriptFields requires at least one field.");

            Fields = fields.Where(x => x != null);
        }
Example #7
0
        static XDocument MergeXml(IEnumerable<XDocument> inputs)
        {
            // What assembly is this?
            var assemblyName = GetAssemblyName(inputs.First());

            if (!inputs.All(input => GetAssemblyName(input) == assemblyName))
            {
                throw new Exception("All input files must be for the same assembly.");
            }

            // Merge all the member documentation into a single list.
            var mergedMembers = from input in inputs
                                from member in input.Element("doc").Element("members").Elements()
                                where !IsNamespace(member)
                                select member;

            // Remove documentation tags that Intellisense does not use, to minimize the size of the shipping XML files.
            RemoveUnwantedElements(mergedMembers);

            // Generate new Intellisense XML.
            return new XDocument(
                new XElement("doc",
                    new XElement("assembly",
                        new XElement("name", assemblyName)
                    ),
                    new XElement("members",
                        mergedMembers
                    )
                )
            );
        }
Example #8
0
        private void ValidateUniqueCurrency(IEnumerable<Currency> otherCurrencies, ref ModelStateDictionary modelStateDictionary)
        {
            if (otherCurrencies.All(oc => oc.CurrencyType != CurrencyType))
                return;

            modelStateDictionary.AddModelError(BaseCache.CurrencyTypeField, String.Format(ValidationResource.Global_OwnUnique_ErrorMessage, FieldResource.Global_Currency_Name));
        }
        public async void SavePackageSources(IEnumerable<IPackageSource> packageSources)
        {
            if (_busy)
                return;

            _busy = true;

            await Task.Run(() =>
            {
                foreach (var packageSource in _packageSources.ToArray())
                {
                    if (packageSources.All(n => n != packageSource))
                    {
                        Remove(packageSource);
                    }
                }

                foreach (var packageSource in packageSources.ToArray())
                {
                    if (!_packageSources.Any(n => n.Name == packageSource.Name && n.Location == packageSource.Location && n.Provider == packageSource.Provider))
                    {
                        Add(packageSource);
                    }
                }
            });

            Reload();

            _busy = false;
        }
Example #10
0
        /// <summary>
        /// Create a suggest request body document.
        /// </summary>
        /// <param name="suggestors">Sets the fields to get suggests from.</param>
        public Suggest(IEnumerable<ISuggester> suggestors)
        {
            if (suggestors == null || suggestors.All(x => x == null))
                throw new ArgumentNullException("suggestors", "Suggest requires at least one field suggest.");

            Suggestors = suggestors.Where(x => x != null);
        }
Example #11
0
 private static IEnumerable<Variant> GenerateVariants(Variant variant, Potter aBook, IEnumerable<Variant> alreadyGenerated)
 {
     return variant.Piles
         .Where(pile => !pile.Contains(aBook))
         .Select(pile => CreateNewVariant(variant, pile, aBook))
         .Where(newVariant => alreadyGenerated.All(v => !v.Equals(newVariant)));
 }
Example #12
0
        /// <summary>
        /// Create the highlighter.
        /// </summary>
        /// <param name="fieldHighlighters">Sets the fields to highlight.</param>
        public Highlighter(IEnumerable<FieldHighlighter> fieldHighlighters)
        {
            if (fieldHighlighters == null || fieldHighlighters.All(x => x == null))
                throw new ArgumentNullException("fieldHighlighters", "Highlighter requires at least one field highlighter.");

            FieldHighlighters = fieldHighlighters.Where(x => x != null);
        }
		public void Prepend( IEnumerable<object> sut, object[] items )
		{
			var prepended = sut.Prepend( items );
			Assert.Equal( sut.Count() + items.Length, prepended.Count() );
			Assert.True( sut.All( x => prepended.Contains( x ) ) );
			Assert.True( items.All( x => prepended.Contains( x ) ) );
		}
Example #14
0
        public Facets(IEnumerable<IFacet> facetGenerators)
        {
            if (facetGenerators == null || facetGenerators.All(x => x == null))
                throw new ArgumentNullException("facetGenerators", "Facets requires at least one facet generator.");

            FacetGenerators = facetGenerators.Where(x => x != null);
        }
Example #15
0
        /// <summary>
        /// Create an aggregations object.
        /// </summary>
        /// <param name="aggregators">Sets the aggregations.</param>
        public Aggregations(IEnumerable<IAggregation> aggregators)
        {
            if (aggregators == null || aggregators.All(x => x == null))
                throw new ArgumentNullException("aggregators", "Aggregations requires at least one aggregator.");

            Aggregators = aggregators.Where(x => x != null);
        }
Example #16
0
 public void Save(IEnumerable<Sim> simList)
 {
     if (simList.Count() == 0)
         return;
     using (MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; password = ; database = test"))
     {
         conn.Open();
         var cmd = conn.CreateCommand();
         cmd.CommandText = "set character set 'utf8'";
         cmd.ExecuteNonQuery();
         var cmdText = @"select * from quest_sim";
         cmd = conn.CreateCommand();
         cmd.CommandText = cmdText;
         var quest_sim = @"INSERT INTO quest_sim SET quest_id=?quest_id,compare_id=?compare_id,value=?value,start=?start";
         //路径
         simList.All(sim =>
         {
             cmd = conn.CreateCommand();
             cmd.CommandText = quest_sim;
             cmd.Parameters.AddWithValue("?quest_id", sim.QuestID);
             cmd.Parameters.AddWithValue("?compare_id", sim.CompareID);
             cmd.Parameters.AddWithValue("?value", sim.Value);
             cmd.Parameters.AddWithValue("?start", sim.StartCity);
             cmd.ExecuteNonQuery();
             return true;
         });
     }
 }
 public void Purge(IEnumerable<int> livingIds)
 {
     foreach (var idToRemove in this.elementMap.Keys.Where(k => livingIds.All(id => id != k)).ToArray())
     {
         this.elementMap.Remove(idToRemove);
     }
 }
Example #18
0
        public override Func<DataASTMutable.WarewolfAtom, bool> CreateFunc(IEnumerable<DataASTMutable.WarewolfAtom> values, IEnumerable<DataASTMutable.WarewolfAtom> warewolfAtoms, IEnumerable<DataASTMutable.WarewolfAtom> to, bool all)
        {
            if (all)
                return a => values.All(x => DataASTMutable.CompareAtoms(a,x)==0);
            return a => values.Any(x =>  DataASTMutable.CompareAtoms(a, x) == 0);

        }
Example #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CharacterTemplate"/> class.
        /// </summary>
        /// <param name="templateTable">The template table.</param>
        /// <param name="inventory">The inventory.</param>
        /// <param name="equipment">The equipment.</param>
        /// <param name="quests">The quests.</param>
        /// <param name="knownSkills">The known skills.</param>
        /// <exception cref="ArgumentNullException"><paramref name="templateTable" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="inventory" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="equipment" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="knownSkills" /> is <c>null</c>.</exception>
        public CharacterTemplate(ICharacterTemplateTable templateTable, IEnumerable<CharacterTemplateInventoryItem> inventory,
                                 IEnumerable<CharacterTemplateEquipmentItem> equipment, IEnumerable<IQuest<User>> quests,
                                 IEnumerable<SkillType> knownSkills)
        {
            _templateTable = templateTable;

            if (templateTable == null)
                throw new ArgumentNullException("templateTable");
            if (inventory == null)
                throw new ArgumentNullException("inventory");
            if (equipment == null)
                throw new ArgumentNullException("equipment");
            if (knownSkills == null)
                throw new ArgumentNullException("knownSkills");

            // Compact all the collections given to us to ensure they are immutable and have minimal overhead
            _inventory = inventory.ToCompact();
            _equipment = equipment.ToCompact();
            _quests = quests.ToCompact();
            _knownSkills = knownSkills.ToCompact();

            // Assert values are valid
            Debug.Assert(_inventory.All(x => x != null));
            Debug.Assert(_equipment.All(x => x != null));
            Debug.Assert(_quests.All(x => x != null));
            Debug.Assert(_knownSkills.All(EnumHelper<SkillType>.IsDefined),
                string.Format("One or more SkillTypes for CharacterTemplate `{0}` are invalid!", this));

            if (log.IsInfoEnabled)
                log.InfoFormat("Loaded CharacterTemplate `{0}`.", this);
        }
Example #20
0
        /// <summary>
        /// Queries the plugwise database for the yield in the given month.
        /// </summary>
        /// <param name="from">start point, inclusive</param>
        /// <param name="to">start point, inclusive</param>
        /// <returns></returns>
        public IList<YieldAggregate> Get5minPlugwiseYield(DateTime from, IEnumerable<int> applianceIds)
        {
            // Querying on a datetime fails somehow
            // As a workaround we list the complete table and use linq to objects for the filter
            // This presents some scalability issues and should be looked in to.
            IList<Minute_Log_5> latest;
            if (!applianceIds.Any())
                latest = LoadAll5minData();
            else
                latest = Load5minApplianceData(applianceIds);

            Console.WriteLine("Loading 5minute plugwise production data since {0}", from);

            var applianceLog = (from logline in latest
                                where logline.LogDate >= @from.AddHours(-1)
                                from log in Get5minParts(logline)
                                where log.Date >= @from && log.Yield > 0.0
                                group log by log.Date into logbydate
                                orderby logbydate.Key
                                where applianceIds.All(
                                  appliance => logbydate.Any(log => log.ApplianceID == appliance))

                                select new YieldAggregate(
                                    date: logbydate.Key,
                                    yield: logbydate.Sum(l => l.Yield),
                                    duration: logbydate.First().Duration)
                                ).ToList();
            return applianceLog;
        }
Example #21
0
 internal RepositoryVersions( IEnumerable<TagCommit> collected, StringBuilder errors, ReleaseTagVersion startingVersionForCSemVer, bool checkCompactExistingVersions )
 {
     Debug.Assert( collected.All( c => c.ThisTag != null ) );
     _versions = collected.OrderBy( t => t.ThisTag ).ToList();
     if( _versions.Count > 0 )
     {
         var first = _versions[0].ThisTag;
         if( checkCompactExistingVersions && startingVersionForCSemVer == null && !first.IsDirectPredecessor( null ) )
         {
             errors.AppendFormat( "First existing version is '{0}' (on '{1}'). One or more previous versions are missing.", first, _versions[0].CommitSha )
                     .AppendLine();
         }
         for( int i = 0; i < _versions.Count - 1; ++i )
         {
             var prev = _versions[i].ThisTag;
             var next = _versions[i + 1].ThisTag;
             if( next.Equals( prev ) )
             {
                 errors.AppendFormat( "Version '{0}' is defined on '{1}' and '{2}'.", prev, _versions[i].CommitSha, _versions[i + 1].CommitSha )
                         .AppendLine();
             }
             else if( checkCompactExistingVersions && !next.IsDirectPredecessor( prev ) )
             {
                 errors.AppendFormat( "Missing one or more version(s) between '{0}' and '{1}'.", prev, next )
                         .AppendLine();
             }
         }
     }
 }
Example #22
0
        private bool AddNewTorgetItems(IEnumerable<HtmlNode> items)
        {
            foreach (var torgetItem in items.Where(IsNewTorgetItem).Select(CreateTorgetItem))
                _items.Add(torgetItem);

            return items.All(IsNewTorgetItem);
        }
Example #23
0
        public IdsQuery(IEnumerable<string> documentIds)
        {
            if (documentIds == null || documentIds.All(x => string.IsNullOrWhiteSpace(x)))
                throw new ArgumentNullException("documentIds", "IdsQuery requires at least one document id.");

            DocumentIds = documentIds;
        }
Example #24
0
        public IndicesBoost(IEnumerable<IndexBoost> boostedIndices)
        {
            if (boostedIndices == null || boostedIndices.All(x => x == null))
                throw new ArgumentNullException("boostedIndices", "IndicesBoost requires at least one IndexBoost.");

            BoostedIndices = boostedIndices.Where(x => x != null);
        }
        /// <summary>
        /// Loads the given target faces
        /// </summary>
        public virtual void SetTargetFaces(IEnumerable<ITargetFace> faces)
        {
            if (!faces.All(x => x is IFaceModelTargetFace))
                throw new ArgumentException("All target faces must implement IFaceModelTargetFace!");

            this.SetTargetFaces(faces.Cast<IFaceModelTargetFace>());
        }
Example #26
0
        /// <summary>
        /// Creates a source filter to include multiple fields.
        /// </summary>
        /// <param name="includeFields"></param>
        public SourceFilter(IEnumerable<string> includeFields)
        {
            if (includeFields == null || includeFields.All(x => string.IsNullOrWhiteSpace(x)))
                throw new ArgumentNullException("includeFields", "SourceFilter requires at least one field to include in this constructor.");

            IncludeFields = includeFields;
        }
Example #27
0
        /// <summary>
        /// Create a rescore request.
        /// </summary>
        /// <param name="rescoreQueries">The queries to run that will rescore the documents.</param>
        public Rescore(IEnumerable<RescoreQuery> rescoreQueries)
        {
            if (rescoreQueries == null || rescoreQueries.All(x => x == null))
                throw new ArgumentNullException("rescoreQueries", "RescoreRequest requires at least one rescore query.");

            RescoreQueries = rescoreQueries.Where(x => x != null);
        }
        public static bool CanZip(IEnumerable<IProtectAttachment> attachments)
        {
            if (!PolicyBridge.IsEnabled("InteractiveProtectAllowUsersToCompressToZip"))
                return false;

            return !attachments.All(x => x.FileType == FileType.ZIP);
        }
        public static bool AreAllKeysUp(this KeyboardState keyboardState, IEnumerable<Keys> keys)
        {
            keyboardState.ThrowIfNull("keyboardState");
            keys.ThrowIfNull("keys");

            return keys.All(keyboardState.IsKeyUp);
        }
Example #30
0
        /// <summary>
        /// Creates a range facet, some combination of key/value field/script values are expected.
        /// </summary>
        /// <param name="facetName"></param>
        /// <param name="rangeBuckets"></param>
        public RangeFacet(string facetName, IEnumerable<RangeBucket> rangeBuckets)
            : this(facetName)
        {
            if (rangeBuckets == null || rangeBuckets.All(x => x == null))
                throw new ArgumentNullException("rangeBuckets", "RangeFacet requires at least one range bucket.");

            RangeBuckets = rangeBuckets.Where(x => x != null);
        }