/// <summary> /// Apply business logic here /// </summary> /// <param name="productsToImport"></param> /// <returns></returns> public Dictionary<string, List<string>> ValidateBusinessLogic(IEnumerable<ProductImportDataTransferObject> productsToImport) { var errors = new Dictionary<string, List<string>>(); var productRules = MrCMSApplication.GetAll<IProductImportValidationRule>(); var productVariantRules = MrCMSApplication.GetAll<IProductVariantImportValidationRule>(); foreach (var product in productsToImport) { var productErrors = productRules.SelectMany(rule => rule.GetErrors(product)).ToList(); if (productErrors.Any()) errors.Add(product.UrlSegment, productErrors); foreach (var variant in product.ProductVariants) { var productVariantErrors = productVariantRules.SelectMany(rule => rule.GetErrors(variant)).ToList(); if (productVariantErrors.Any()) { if (errors.All(x => x.Key != product.UrlSegment)) errors.Add(product.UrlSegment, productVariantErrors); else errors[product.UrlSegment].AddRange(productVariantErrors); } } } return errors; }
public static List<IRequiredService> DetermineMissingServices(this IEnumerable<XmlModuleConfig> modules, List<string> bootStrappedServices) { var providedServices = new List<IProvidedService>(); var requiredServices = new Dictionary<IRequiredService, XmlModuleConfig>(); foreach (var module in modules) { foreach (IRequiredService requiredService in module.RequiredServices) { if (requiredServices.All(r => r.Key.ServiceName != requiredService.ServiceName)) { requiredServices.Add(requiredService, module); } } foreach (IProvidedService providedService in module.ProvidedServices) { if (providedServices.All(r => r.ServiceName != providedService.ServiceName)) { providedServices.Add(providedService); } } } var query = requiredServices.Where( requiredService => providedServices.All(s => s.ServiceName != requiredService.Key.ServiceName) && bootStrappedServices.All(s => s != requiredService.Key.ServiceName)); return query.Select(s => s.Key).ToList(); }
public string CalculateMode(List<decimal> numbers) { decimal max = 0; string result = ""; var numDictionary = new Dictionary<decimal, int>(); AddToDictionary(numbers, numDictionary); if(numDictionary.Count == 0) throw new ArgumentException("No numbers given!", "numbers"); if (numDictionary.All(d => d.Value == 1)) return "none"; foreach (KeyValuePair<decimal, int> pair in numDictionary) { if (pair.Value > max) { result = ""; max = pair.Value; result += string.Format("{0},", pair.Key); } else if (pair.Value == max) result += string.Format("{0},", pair.Key); } return result.Trim(','); }
public bool DetermineIfAnagram(string s1, string s2) { if (s1.Length != s2.Length) { return false; } var dict = new Dictionary<char,int>(); foreach (var item in s1) { if (dict.ContainsKey(item)) { dict[item]++; } else { dict.Add(item, 1); } } foreach (var item in s2) { if (!dict.ContainsKey(item)) { return false; } else { dict[item]--; } } return dict.All(x => x.Value == 0); }
public void Test_Gamma_Of_Valid_Values() { Dictionary<double, double> expected = new Dictionary<double, double> { {1,1}, {Math.PI, 2.288037796}, {Math.E, 1.567468255}, {-1.5,2.363271801} }; //foreach (var item in expected) //{ // double actual = GammaRelated.Gamma(item.Key); // Assert.IsTrue(AreApproximatelyEqual(item.Value, actual)); //} Assert.IsTrue( expected.All(x => AreApproximatelyEqual(x.Value, GammaRelated.Gamma(x.Key)) ) ); Assert.IsTrue( AreApproximatelyEqual( GammaRelated.Gamma(Math.PI + 1), Math.PI * GammaRelated.Gamma(Math.PI) ) ); }
public void DictionaryExtensions_All_ReturnsTrueIfDictionaryIsEmpty() { var dictionary = new Dictionary<Int32, String>(); var result = dictionary.All(x => x.Key % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void WebConfigStateAllowsEnumeratingOverConfigItems() { // Arrange var dictionary = new Dictionary<string, string> { { "a", "b" }, { "c", "d" }, { "x12", "y34" } }; var stateStorage = GetWebConfigScopeStorage(dictionary); // Act and Assert Assert.IsTrue(dictionary.All(item => item.Value == stateStorage[item.Key] as string)); }
public bool AddStream(string sStreamName) { var results = new Dictionary<IStreamProvider, bool>(); foreach (var streamProvider in _streamProviders) { results.Add(streamProvider, streamProvider.AddStream(sStreamName)); } return results.All(result => !result.Value); }
public void CountWords_EmptySentences_CountsWordCorrectly() { var wordsCounter = new ClassicCounterLogic(); var properDict = new Dictionary<string, int>(); var result = wordsCounter.CountWordsInSentence(string.Empty); Assert.IsTrue(properDict.All(e => result.Contains(e))); }
internal static int DispatchCommand(Dictionary<CommandMetadata, object> commands, string[] args) { if (args == null || !args.Any()) throw new ShellHelpException(); var commandName = args.First().ToLower(); if (commands.All(meta => meta.Key.Name != commandName)) throw new ShellHelpException(); var command = commands.Single(meta => meta.Key.Name == commandName).Value; var metadata = commands.Single(meta => meta.Key.Name == commandName).Key; return RunCommand(command, metadata, args.Skip(1).ToArray()); }
public SearchEngine(Dictionary<string, List<string>> lookups) { if (lookups == null) throw new ArgumentNullException("lookups"); if (lookups.Count == 0) throw new ArgumentException("The lookups must not be empty.", "lookups"); if (lookups.All(x => x.Value.Count == 0)) throw new ArgumentException("None of the lookups (keys) have results (values). This is invalid as a lookup table."); _lookupTable = lookups; }
public void GetAllKeysAsListTestCase() { var dictionary = new Dictionary<String, String> { { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }, { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() } }; var allKeys = dictionary.GetAllKeysAsList(); Assert.IsTrue( dictionary.All( x => allKeys.Contains( x.Key ) ) ); }
public async Task TestPostRequestWithCustomeHeadersAndBody() { using (var server = new HttpHost(TestPort)) { const string path = "/test/path?query=value"; var headers = new Dictionary<string, string> { { "custom-header-1", "custom-value-1" }, { "content-custom", "content-value" } }; const string contentType = "suave/test"; const string content = "string content"; var responseContent = new byte[] { 1, 2, 3 }; await server.OpenAsync(async request => { Assert.Equal(path, request.RequestUri.PathAndQuery); Assert.Equal(HttpMethod.Post, request.Method); Assert.True(headers.All(pair => request.Headers.First(s => s.Key == pair.Key).Value.First() == pair.Value)); Assert.Equal(contentType, request.Content.Headers.ContentType.ToString()); Assert.Equal(content, await request.Content.ReadAsStringAsync()); var response = new HttpResponseMessage { StatusCode = HttpStatusCode.Accepted, Content = new ByteArrayContent(responseContent) }; response.Headers.Add("server-custom", "server-value"); return response; }); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, LocalHost + path); headers.Aggregate(request.Headers, (a, b) => { a.Add(b.Key, b.Value); return a; }); request.Content = new StringContent(content); request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); var response = await client.SendAsync(request); Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); Assert.Equal(responseContent, await response.Content.ReadAsByteArrayAsync()); Assert.Equal("server-value", response.Headers.First(s => s.Key == "server-custom").Value.First()); } } }
/// <summary> /// Adds authorization token to POST body /// </summary> /// <param name="body">Dictionary containing the body parameters</param> /// <param name="token">The token to add to the post body</param> /// <returns></returns> public virtual Dictionary<string, object> Authorize(Dictionary<string, object> body, string token) { if (body == null) throw new ArgumentNullException("body"); var d = new Dictionary<string, object>(body); if (d.All(b => !String.Equals(b.Key, this.FieldName, StringComparison.CurrentCultureIgnoreCase))) d.Add(this.FieldName, token); return d; }
public void DictionaryExtensions_All_ReturnsTrueIfAllItemsMatchPredicate() { var dictionary = new Dictionary<Int32, String>() { { 2, "A" }, { 4, "B" }, { 6, "C" }, }; var result = dictionary.All(x => x.Key % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void DictionaryExtensions_All_ReturnsFalseIfOneItemDoesNotMatchPredicate() { var dictionary = new Dictionary<Int32, String>() { { 1, "A" }, { 2, "B" }, { 4, "C" }, { 6, "D" }, }; var result = dictionary.All(x => x.Key % 2 == 0); TheResultingValue(result).ShouldBe(false); }
public ActionResult CompleteReservation(Dictionary<string, string> roomsToBook) { if (roomsToBook.All(r => r.Value == "0" || string.IsNullOrEmpty(r.Value))) { this.TempData["Notification"] = "No room selected.Choose new dates"; return this.RedirectToAction("Index", "Home"); } var dates = this.Session["SearchDates"] as SearchInputModel; var newRoomsToBook = new Dictionary<string, int>(); var roomToBookTypes = new List<string>(); foreach (var roomType in roomsToBook) { if (roomType.Value != "0" && !string.IsNullOrEmpty(roomType.Value)) { newRoomsToBook.Add(roomType.Key, int.Parse(roomType.Value)); roomToBookTypes.Add(roomType.Key); } } var reservation = new ReservationViewModel { CreatorId = this.User.Identity.GetUserId(), StartDate = dates.Start, EndDate = dates.End, Rooms = new List<BookedRoomView>() }; var availableRoomsTypes = this.rooms .AvailableForPeriod(dates.Start, dates.End).ToList() .Where(r => roomToBookTypes.Contains(r.RoomType.Type)) .GroupBy(r => r.RoomType.Type); foreach (var roomType in availableRoomsTypes) { roomType .Take(newRoomsToBook[roomType.Key]) .ForEach(x => reservation.Rooms.Add(new BookedRoomView { Guests = new List<PersonInputModel>(), Room = x, Status = ReservationStatus.Pending })); } this.Session["reservation"] = reservation; return new HttpStatusCodeResult(HttpStatusCode.OK); }
public GraphPetriNet(string id, Dictionary<int, string> placeNames, Dictionary<int, string> transitionNames, Dictionary<int, List<InArc>> inArcs, Dictionary<int, List<OutArc>> outArcs ) { Contract.Requires(!string.IsNullOrEmpty(id)); Contract.Requires(placeNames != null); Contract.Requires(placeNames.Count > 0); Contract.Requires(placeNames.All(pn => !string.IsNullOrEmpty(pn.Value))); Contract.Requires(transitionNames != null); Contract.Requires(transitionNames.Count > 0); Contract.Requires(transitionNames.All(tn => !string.IsNullOrEmpty(tn.Value))); Contract.Requires(inArcs != null); Contract.Requires(inArcs.Count > 0); Contract.Requires(outArcs != null); // disabled because the petri net may be built in stages using other APIs // Contract.Requires(outArcs.Count > 0); Contract.Ensures(Places.Count == placeNames.Count); Contract.Ensures(Places == placeNames); Id = id; Places = placeNames; Transitions = transitionNames; InArcs = inArcs; // each arc into a transition can be seen as an arc out of a place // (which may be convenient for conflict resolution) if (InArcs != null) { foreach (var transitionInArcs in InArcs) { foreach (var inArc in transitionInArcs.Value) { if (!PlaceOutArcs.ContainsKey(inArc.Source)) { PlaceOutArcs[inArc.Source] = new List<OutArc>(); } PlaceOutArcs[inArc.Source].Add(new OutArc(transitionInArcs.Key)); } } } OutArcs = outArcs; PlaceCapacities = new Dictionary<int, int>(); }
protected virtual IEnumerable<IDictionary<string, object>> ReadFileContents() { while (Reader.Read()) { var rowData = new Dictionary<string, object>(); for (var fieldIndex = 0; fieldIndex < Reader.FieldCount; fieldIndex++) { var name = FieldNames[fieldIndex]; var value = Reader.GetValue(fieldIndex); rowData[name] = value; } if (rowData.All(pair => string.IsNullOrEmpty(string.Format("{0}", pair.Value)))) continue; yield return rowData; } }
public void CountWords_IncorrectSentencePassed_CountsWordCorrectly() { var wordsCounter = new ClassicCounterLogic(); var properDict = new Dictionary<string, int> { { "this", 2 }, { "is", 2 }, { "a", 1 }, { "sentence", 1 }, { "so", 1 } }; var result = wordsCounter.CountWordsInSentence("This a different sentence, so is this."); Assert.IsFalse(properDict.All(e => result.Contains(e))); }
/// <summary> /// Execution of the Action. /// </summary> /// <returns>True: Execution of the Action was successful</returns> public bool Execute(ActionCallingContext ctx) { using (UndoStep undo = new UndoManager().CreateUndoStep()) { SelectionSet sel = new SelectionSet(); //Make sure that terminals are ordered by designation var terminals = sel.Selection.OfType<Terminal>().OrderBy(t => t.Properties.FUNC_PINORTERMINALNUMBER.ToInt()); if (terminals.Count() < 2) throw new Exception("Must select at least 2 Terminals"); //Create a list of terminals for each level. Those lists get added to a dictionnary //with the level as the key. Dictionary<int, List<Terminal>> levels = new Dictionary<int, List<Terminal>>(); //Fill the dictionnary foreach (Terminal t in terminals) { int level = t.Properties.FUNC_TERMINALLEVEL; if (!levels.ContainsKey(level)) levels.Add(level, new List<Terminal>()); levels[level].Add(t); } var keys = levels.Keys.OrderBy(k => k); //Make sure that all levels have the same number of terminals int qty = levels.First().Value.Count; if (!levels.All(l => l.Value.Count == qty)) throw new Exception("There must be the same number of Terminals on each level"); //Assign sort code by taking a terminal from each level in sequence int sortCode = 1; for (int i = 0; i < qty; i++) { foreach (int j in keys) { levels[j][i].Properties.FUNC_TERMINALSORTCODE = sortCode++; } } } return true; }
public List<BulkShippingUpdateDataTransferObject> ValidateAndBulkShippingUpdateOrders(Stream rawFile, ref Dictionary<string, List<string>> parseErrors) { var bulkShippingUpdateDataTransferObjects = new List<BulkShippingUpdateDataTransferObject>(); if (rawFile != null) { using (var file = new CsvReader(new StreamReader(rawFile), new CsvConfiguration{HasHeaderRecord = true})) { while (file.Read()) { var orderId = file.GetField<int?>(0); //skip blank rows if (!orderId.HasValue) continue; //check for duplicates if (bulkShippingUpdateDataTransferObjects.SingleOrDefault(x=>x.OrderId == orderId) != null) continue; if (orderId.HasValue && parseErrors.All(x => x.Key != orderId.ToString())) parseErrors.Add(orderId.ToString(), new List<string>()); else parseErrors.Add("no-supplied-id", new List<string>()); var pv = new BulkShippingUpdateDataTransferObject(); if (file.GetField<string>(0).HasValue()) pv.OrderId = file.GetField<int>(0); else parseErrors["no-supplied-id"].Add("Order Id is required."); if (file.GetField<string>(1).HasValue()) pv.ShippingMethod = file.GetField<string>(1); if (file.GetField<string>(2).HasValue()) pv.TrackingNumber = file.GetField<string>(2).Trim(); bulkShippingUpdateDataTransferObjects.Add(pv); } } } parseErrors = parseErrors.Where(x => x.Value.Any()).ToDictionary(pair => pair.Key, pair => pair.Value); return bulkShippingUpdateDataTransferObjects; }
public void CreateParts_should_add_metadata_from_part_convention_to_part_definition() { var partDefinitions = GetPartDefinitionsFromNonEmptyRegistry(); var expectedMetadata = new Dictionary<string, object> { { CompositionConstants.PartCreationPolicyMetadataName, CreationPolicy.Shared }, { "Foo", "Bar" } }; var inspectedPartDefinition = partDefinitions.First(); expectedMetadata.All(x => inspectedPartDefinition.Metadata.ContainsKey(x.Key)).ShouldBeTrue(); }
// http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html public string MinWindow(string src, string target) { if (src.Length < target.Length) return ""; Dictionary<char, int> mapping = new Dictionary<char, int>(); foreach (char c in target) mapping[c] = mapping.ContainsKey(c) ? mapping[c] + 1 : 1; int left = 0, right = 0; int answerLeft = 0, answerLength = int.MaxValue; while (right < src.Length) { if (mapping.ContainsKey(src[right])) { mapping[src[right]]--; if (mapping.All(s => s.Value <= 0)) { while (left <= right) { if (mapping.ContainsKey(src[left])) { mapping[src[left]]++; if (mapping[src[left]] == 1) // left <-> right can be a candidate answer { if (right - left + 1 < answerLength) { answerLeft = left; answerLength = right - left + 1; } left++; // make it invalid again break; } } left++; } } } right++; } if (answerLength == int.MaxValue) return ""; return src.Substring(answerLeft, answerLength); }
public void Test_Log_Of_Factorial() { Dictionary<int, long> factorials = new Dictionary<int, long>(); for (int i = 0; i < 20; i++) { factorials.Add(i, Get.Factorial(i)); } Assert.IsTrue( factorials.All(x => AreApproximatelyEqual( Math.Log(x.Value), GammaRelated.LogOfFactorial(x.Key)) ) ); }
protected virtual IEnumerable<IDictionary<string, object>> ReadData() { for (var rowIndex = RowStart; rowIndex <= EndAddress.Row; rowIndex++) { var rowData = new Dictionary<string, object>(); for (var colIndex = 1; colIndex <= EndAddress.Column; colIndex++) { var currentCell = Worksheet.Cells[rowIndex, colIndex]; var currentValue = currentCell.Value; var currentKey = FieldNames[(colIndex - 1)]; rowData[currentKey] = currentValue; } if (rowData.All(pair => string.IsNullOrEmpty(string.Format("{0}", pair.Value)))) continue; yield return rowData; } }
public List<BulkStockUpdateDataTransferObject> ValidateAndBulkStockUpdateProductVariants(Stream rawFile, ref Dictionary<string, List<string>> parseErrors) { var items = new List<BulkStockUpdateDataTransferObject>(); if (rawFile != null) { using (var file = new CsvReader(new StreamReader(rawFile))) { while (file.Read()) { string sku = file.GetField<string>(1), name = file.GetField<string>(0); string handle = sku.HasValue() ? sku : SeoHelper.TidyUrl(name); if (parseErrors.All(x => x.Key != handle)) parseErrors.Add(handle, new List<string>()); var pv = new BulkStockUpdateDataTransferObject { Name = file.GetField<string>(0), SKU = file.GetField<string>(1) }; if (file.GetField<string>(1).HasValue()) pv.SKU = file.GetField<string>(1); else parseErrors[handle].Add("SKU is required."); if (!GeneralHelper.IsValidInput<int>(file.GetField<string>(2))) parseErrors[handle].Add("Stock value is not a valid number."); else pv.StockRemaining = file.GetField<string>(2).HasValue() ? Int32.Parse(file.GetField<string>(2)) : 0; items.Add(pv); } } } parseErrors = parseErrors.Where(x => x.Value.Any()).ToDictionary(pair => pair.Key, pair => pair.Value); return items; }
public static bool accidentsEqual(BindingList<tblPatientAccident> left, BindingList<tblPatientAccident> right) { if (left.Count != right.Count) return false; foreach (tblPatientAccident A in left) { if ((A == null) || (A.ClaimNo == null)) return false; } foreach (tblPatientAccident B in right) { if ((B == null) || (B.ClaimNo == null)) return false; } var dict = new Dictionary<string, int>(); foreach (tblPatientAccident member in left) { if (dict.ContainsKey(member.ClaimNo) == false) dict[member.ClaimNo] = 1; else dict[member.ClaimNo]++; } foreach (tblPatientAccident member in right) { switch (dict.ContainsKey(member.ClaimNo)) { case false: return false; default: dict[member.ClaimNo]--; break; } } return dict.All(kvp => kvp.Value == 0); }
public Dictionary<int, string> FindMarkdownTags(string text) { var tagPositions = new Dictionary<int, string>(); foreach (var tag in tagForSymbol.Keys.OrderByDescending(x => x.Length)) { var count = 0; while (text.IndexOf(tag, count, StringComparison.Ordinal) != -1) { var tagIndex = text.IndexOf(tag, count, StringComparison.Ordinal); if (!IsEscaped(tagIndex, text) && (tagForSymbol[tag].IsFormattableInNumbers || !IsInNumbers(tagIndex, text)) && tagPositions.All(item => !IsInAnotherTag(item, tagIndex) && !IsInAnotherTag(item, tagIndex + tag.Length - 1))) { tagPositions.Add(tagIndex, tag); } count = tagIndex + tag.Length; } } return tagPositions; }
public IDictionary<int, RoundResult> GetResults() { var results = new Dictionary<int, RoundResult>(); foreach (var selection in Selections) { RoundResult result; var comparisions = from s in Selections where s.Key != selection.Key select selection.Value.Compare(s.Value); if (comparisions.All(x => x == RoundResult.Draw)) { result = RoundResult.Draw; } else if (comparisions.All(x => x == RoundResult.Win)) { result = RoundResult.Win; } else if (comparisions.Any(x => x == RoundResult.Lose)) { result = RoundResult.Lose; } else { result = RoundResult.Lose; } results[selection.Key] = result; } if (results.All(x => x.Value == RoundResult.Lose)) { results = (from s in Selections select new { Key = s.Key, Value = RoundResult.Draw }) .ToDictionary(x => x.Key, y => y.Value); } return results; }