private void FlowConsoleWrite(int?packetnum) { if (packetnum % 5000 == 0) { GC.Collect(); GC.Collect(); } var value = dListFlow[packetnum]; var connLookup = dListFlow.ToLookup(e => e.Value); Task.Factory.StartNew(() => FlowStatistics.WriteFlowConsole(connLookup[value].Select(e => e.Key).ToList(), value)); }
public void TestGeoserverHasUniqueDataStoreInfoImplPerProjectFirmaWorkspace() { const string dataStoreInfoImpl = "DataStoreInfoImpl"; List <String> workspaceDirs = GetWorkspaceDirectories(); // Sanity check - all workspaces should be distinct. This shouldn't ever happen, but you never know... bool anyDuplicateWorkpaceNames = workspaceDirs.GroupBy(wd => wd).Any(c => c.Count() > 1); Check.Ensure(!anyDuplicateWorkpaceNames, $"Found duplicate workspaces where we weren't expecting them!"); var workspaceDirNameToDataStoreInfoImplDict = new Dictionary <string, string>(); foreach (string workspaceDir in workspaceDirs) { string pathToCurrentDatastoreXmlFile = GetDatastoreXmlFilePathForWorkspaceDir(workspaceDir); string dataStoreInfoImplValue = GetIdValue(pathToCurrentDatastoreXmlFile, dataStoreInfoImpl); workspaceDirNameToDataStoreInfoImplDict.Add(workspaceDir, dataStoreInfoImplValue); } // Retrieve all duplicate values for the workspaces var lookupForDuplicateValues = workspaceDirNameToDataStoreInfoImplDict.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1); string errorString = string.Empty; foreach (var dupeItem in lookupForDuplicateValues) { var keys = dupeItem.Aggregate("", (s, v) => s + ", " + v); string message = "The following keys have the value " + dupeItem.Key + ":" + keys; errorString += message; } Check.Ensure(errorString == string.Empty, $"Found duplicate values for {dataStoreInfoImpl} in the following Geoserver datastore.xml workspaces: {errorString}. These values must be distinct across Geoserver Workspaces, and should not be copied."); }
static IEnumerable<LA_update1> DefineFlow(IEnumerable<LA_update> totalMessge) { var connLookup = dFlow.ToLookup(e => e.Value); foreach (var i in connLookup) { var nLst = i.Select(e => e.Key); var nFlow = totalMessge.Where(e => nLst.Contains(e.PacketNum)); nFlow = nFlow.OrderBy(e => e.PacketTime); foreach (var m in nFlow) { LA_update1 mFlow = new LA_update1(); mFlow.BeginFrameNum = m.BeginFrameNum; mFlow.DumpFor = m.DumpFor; mFlow.FileNum = m.FileNum; mFlow.imsi = m.imsi; mFlow.ip_version = m.ip_version; mFlow.ip_version_MsgType = m.ip_version_MsgType; mFlow.m3ua_dpc = m.m3ua_dpc; mFlow.m3ua_opc = m.m3ua_opc; mFlow.PacketNum = m.PacketNum; mFlow.PacketTime = m.PacketTime; mFlow.PacketTime_ms_ = m.PacketTime_ms_; mFlow.sccp_dlr = m.sccp_dlr; mFlow.sccp_slr = m.sccp_slr; mFlow.tmsi = m.tmsi; mFlow.opcdpcsccp = i.Key; yield return mFlow; } } }
public static void Init() { _Types = new Dictionary <string, BufferType>(); _ReadFunctions = new Dictionary <string, Func <BufferPlus, Encoding, int, int, dynamic> >(); _WriteFunctions = new Dictionary <string, Func <BufferPlus, dynamic, Encoding, int, int, byte[]> >(); _SizeFunctions = new Dictionary <string, Func <BufferPlus, dynamic, int> >(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (System.Reflection.TypeInfo type in assembly.DefinedTypes) { if (type.BaseType == null || type.BaseType.IsGenericType == false) { continue; } if (type.BaseType.Name == typeof(BufferType <>).Name) { dynamic bType = Activator.CreateInstance(type); } } } _TypesLookups = (Lookup <Type, BufferType>)_Types.ToLookup(pair => pair.Value.DataType, pair => pair.Value); }
private static TokenResponse <T> ExtractTokenAndExtraDataJson <T>(string tokenName, Func <string, ILookup <string, string>, T> tokenFactory, string tokenBase) where T : Token { //Convert to dictionary var results = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(tokenBase); //Find access token string accessToken = null; var extraData = new Dictionary <string, string>(); foreach (var item in results) { if (item.Key.Equals(tokenName)) { accessToken = item.Value as string; continue; } if (item.Value is string) { extraData.Add(item.Key, item.Value as string); } else if (item.Value is int) { var val = item.Value as int?; extraData.Add(item.Key, val.ToString()); } } var data = extraData.ToLookup(kv => kv.Key, kv => kv.Value); var token = tokenFactory(accessToken, data); return(new TokenResponse <T>(token)); }
internal override TileModelMapping GetTileModelMapping(Topology topology) { if (frequencies.Sum() == 0.0) { throw new Exception("No tiles have assigned frequences."); } var patternModel = new PatternModel { Propagator = propagator.Select(x => x.Select(y => y.ToArray()).ToArray()).ToArray(), Frequencies = frequencies.ToArray(), }; var tilesToPatternsByOffset = new Dictionary <int, IReadOnlyDictionary <Tile, ISet <int> > >() { { 0, tilesToPatterns.ToLookup(x => x.Key, x => x.Value).ToDictionary(g => g.Key, g => (ISet <int>) new HashSet <int>(g)) } }; var patternsToTilesByOffset = new Dictionary <int, IReadOnlyDictionary <int, Tile> > { { 0, tilesToPatterns.ToDictionary(x => x.Value, x => x.Key) }, }; return(new TileModelMapping { PatternTopology = topology, PatternModel = patternModel, PatternsToTilesByOffset = patternsToTilesByOffset, TilesToPatternsByOffset = tilesToPatternsByOffset, TileCoordToPatternCoord = null, }); }
public ChangeOwnerWaybillMainIndicators GetMainIndicators(ChangeOwnerWaybill waybill, User user, bool calculateValueAddedTaxes = false) { var indicators = new ChangeOwnerWaybillMainIndicators(); var allowToViewAccPrices = user.HasPermissionToViewStorageAccountingPrices(waybill.Storage); if (!allowToViewAccPrices) { indicators.AccountingPriceSum = null; if (calculateValueAddedTaxes) { var emptyLookup = new Dictionary <decimal, decimal>().ToLookup(x => x.Value, x => x.Value); indicators.VatInfoList = emptyLookup; } } else { if (waybill.IsAccepted) { indicators.AccountingPriceSum = waybill.AccountingPriceSum; if (calculateValueAddedTaxes) { indicators.VatInfoList = waybill.Rows.ToLookup(x => x.ValueAddedTax.Value, x => x.ValueAddedTaxSum); } } else { var articleSubQuery = changeOwnerWaybillRepository.GetArticlesSubquery(waybill.Id); var accountingPrices = articlePriceService.GetAccountingPrice(waybill.Storage.Id, articleSubQuery); var valueAddedTaxList = new Dictionary <ChangeOwnerWaybillRow, decimal>(); indicators.AccountingPriceSum = 0M; foreach (var row in waybill.Rows) { var accountingPrice = accountingPrices[row.Article.Id]; if (accountingPrice.HasValue) { var accountingPricePartialSum = accountingPrice.Value * row.MovingCount; indicators.AccountingPriceSum += accountingPricePartialSum; if (calculateValueAddedTaxes) { valueAddedTaxList.Add(row, VatUtils.CalculateVatSum(accountingPricePartialSum, row.ValueAddedTax.Value)); } } } if (calculateValueAddedTaxes) { indicators.VatInfoList = valueAddedTaxList.ToLookup(x => x.Key.ValueAddedTax.Value, x => x.Value); } } } return(indicators); }
public static bool ContainsDuplicate(char[] arr, int k) { try { bool b; Dictionary <int, char> dic = new Dictionary <int, char>(); //creating a dictionary called dic to store key-value pairs for (int i = 0; i <= arr.Length - 1; i++) { dic.Add(i, arr[i]); // for loop to iterate from 0th to last element of array and add it to dic } //initializing a lookup table to store index values for each character var lookup = dic.ToLookup(c => c.Value, c => c.Key).Where(c => c.Count() > 1); //using a foreach loop to traverse through the values in lookup table and find the difference foreach (var item in lookup) { var keys = item.Aggregate("", (t, u) => t + ", " + u); //Finding the difference by subtracting consecutive occurrences of an element from the first occurrence int diff = keys.ElementAt(5) - keys.ElementAt(2); //validate if the difference is equal to target if (diff >= k) { //return true if the condition is met b = true; return(b); } } return(false); } catch (Exception) { throw; } }
public static bool ContainsDuplicate(char[] arr, int k) { try { bool a; Dictionary <int, char> dict = new Dictionary <int, char>(); for (int i = 0; i <= arr.Length - 1; i++) { dict.Add(i, arr[i]); } //Creating a look up table which will note down the index values for the character var lookup = dict.ToLookup(z => z.Value, z => z.Key).Where(z => z.Count() > 1); //iterating through the look up values to find the difference between the index values foreach (var item in lookup) { var keys = item.Aggregate("", (t, u) => t + ", " + u); //Substracting the 2nd occurence of the character with the first to get the absolute difference int diff = keys.ElementAt(5) - keys.ElementAt(2); //Check if the difference is equal to the target value if (diff >= k) { //return true if difference is equal, else return false a = true; return(a); } } return(false); } catch (Exception) { throw; } }
public static ILookup <string, double> GraphStatistic(Dictionary <Tuple <string, Slide>, TimeSpan> tUserSlide) { var graphStatistic = tUserSlide.ToLookup(key => key.Key.Item2.Topic, value => value.Value.TotalHours); var result = graphStatistic.ToLookup(key => key.Key, value => value.Sum()); return(result); }
public static Dictionary <string, List <string> > ReverseNotebook(Dictionary <string, string> phonesToNames) { var mylookup = (Lookup <string, string>)phonesToNames.ToLookup(ph => ph.Value ?? "", ph => ph.Key ?? ""); var mydict = mylookup.ToDictionary(x => x.Key, x => x.ToList()); return(mydict); }
public void ScanForDuplicates(Dictionary<string, string> hashDictionary) { if (hashDictionary == null) { throw new ArgumentNullException("Require not a null dictionary", "hashDictionary"); } //Do a look Up in the current dictionary to see if there are rows that have the same hash var lookup = hashDictionary.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1); if (lookup.Count() == 0) { Console.WriteLine("No duplicated files have been found. ^_^"); } else { foreach (var t in lookup) { //Will Aggregate the keys of the lookup into a string var keys = t.Aggregate("", (s, v) => s + "\n" + v); var messsage = "\n\nThe files with the hash {" + t.Key + "} are \n" + keys; Console.WriteLine(messsage); } } }
public OriginPropertyDictionary(Type rowType) { this.rowType = rowType; rowJoinByAlias = new Dictionary <string, ISqlJoin>(StringComparer.OrdinalIgnoreCase); propertyByName = new Dictionary <string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); foreach (var pi in rowType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { propertyByName[pi.Name] = pi; } origins = new Dictionary <string, OriginAttribute>(StringComparer.OrdinalIgnoreCase); joinPropertyByAlias = new Dictionary <string, Tuple <string, ForeignKeyAttribute[], ISqlJoin> >(); foreach (var property in propertyByName.Values) { var originAttr = property.GetCustomAttribute <OriginAttribute>(); if (originAttr != null) { origins[property.Name] = originAttr; } var lj = property.GetCustomAttribute <LeftJoinAttribute>(); var fk = property.GetCustomAttributes <ForeignKeyAttribute>().ToArray(); if (lj != null && fk != null) { joinPropertyByAlias[lj.Alias] = new Tuple <string, ForeignKeyAttribute[], ISqlJoin>(property.Name, fk, lj); } } foreach (var attr in rowType.GetCustomAttributes <LeftJoinAttribute>()) { rowJoinByAlias[attr.Alias] = attr; } foreach (var attr in rowType.GetCustomAttributes <InnerJoinAttribute>()) { rowJoinByAlias[attr.Alias] = attr; } foreach (var attr in rowType.GetCustomAttributes <OuterApplyAttribute>()) { rowJoinByAlias[attr.Alias] = attr; } originByAlias = origins.ToLookup(x => x.Value.Join); prefixByAlias = originByAlias.ToDictionary(x => x.Key, x => { if (joinPropertyByAlias.TryGetValue(x.Key, out Tuple <string, ForeignKeyAttribute[], ISqlJoin> joinProperty)) { if (joinProperty.Item3.PropertyPrefix != null) { return(joinProperty.Item3.PropertyPrefix); } if (joinProperty.Item1.EndsWith("ID") || joinProperty.Item1.EndsWith("Id")) { return(joinProperty.Item1[0..^ 2]); }
/// <summary> /// Get the current access token - and optinally refreshes it if it is expired /// </summary> /// <param name="refreshToken">The refresh token to use (null == default)</param> /// <param name="forceUpdate">Enfore an update of the access token?</param> /// <param name="safetyMargin">A custom safety margin to check if the access token is expired</param> /// <returns></returns> public async Task <string> GetCurrentToken(string refreshToken = null, bool forceUpdate = false, TimeSpan?safetyMargin = null) { bool refreshRequired = forceUpdate || (ExpiresAt != null && DateTime.Now >= (ExpiresAt - (safetyMargin ?? ExpirationSafetyMargin))) || String.IsNullOrEmpty(AccessToken); if (refreshRequired) { string refreshTokenValue; if (!string.IsNullOrEmpty(refreshToken)) { refreshTokenValue = refreshToken; } else if (!string.IsNullOrEmpty(RefreshToken)) { refreshTokenValue = RefreshToken; } else { throw new Exception("Token never fetched and refresh token not provided."); } var parameters = new Dictionary <string, string>() { { RefreshTokenKey, refreshTokenValue }, }; GrantType = GrantTypeRefreshTokenKey; await QueryAccessToken(parameters.ToLookup(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase)); } return(AccessToken); }
protected async Task<T> WaitForValueOnGroupAsync<T>(DatabaseTopology topology, Func<ServerStore, T> func, T expected, int timeout = 15000) { var nodes = topology.AllNodes; var servers = new List<ServerStore>(); var tasks = new Dictionary<string, Task<T>>(); foreach (var node in nodes) { var server = Servers.Single(s => s.ServerStore.NodeTag == node); servers.Add(server.ServerStore); } foreach (var server in servers) { var task = WaitForValueAsync(() => func(server), expected, timeout); tasks.Add(server.NodeTag, task); } var res = await Task.WhenAll(tasks.Values); var hasExpectedVals = res.Where(t => t?.Equals(expected) ?? false); if (hasExpectedVals.Count() == servers.Count) return expected; var lookup = tasks.ToLookup(key => key.Value.Result, val => val.Key); var otherValues = ""; foreach (var val in lookup) { otherValues += $"\n the value {val.Key} appears on "; foreach (string str in val) { otherValues += str + ", "; } } throw new Exception($"Not all node in the group have the expected value of {expected}. {otherValues}"); }
private ILookup <string, HttpActionDescriptor> GenerateActionMappings( KeyValuePair <string, HttpControllerDescriptor> controller, IEdmEntitySet entitySet) { Dictionary <string, HttpActionDescriptor> actionMaps = new Dictionary <string, HttpActionDescriptor>(); foreach (var relation in entitySet.NavigationPropertyBindings) { //Configure Navigation links string methodName = null; Type relatedPropertyType = null; if (relation.NavigationProperty.TargetMultiplicity() == EdmMultiplicity.Many) { methodName = "GetRelatedEntities"; relatedPropertyType = controller.Value.ControllerType.GetGenericArguments()[0].GetProperty(relation.NavigationProperty.Name).PropertyType.GetGenericArguments()[0]; } else { methodName = "GetRelatedEntity"; relatedPropertyType = controller.Value.ControllerType.GetGenericArguments()[0].GetProperty(relation.NavigationProperty.Name).PropertyType; } var genericRelatedEntityGetter = controller.Value.ControllerType.GetMethod(methodName); var genericMethod = genericRelatedEntityGetter.MakeGenericMethod(relatedPropertyType); //Relate an action link for Get{PropertyName} actionMaps.Add(relation.NavigationProperty.Name, new ReflectedHttpActionDescriptor(controller.Value, genericMethod)); } return(actionMaps.ToLookup( a => a.Key, a => a.Value)); }
public static void Cozy() { Console.WriteLine("\n-----------------------------------------------"); Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); Console.WriteLine("-----------------------------------------------"); #region Dictionary<TKey, TValue> //Dictionary<TKey, TValue> k-v var dictionary = new Dictionary <string, string>(); dictionary.Add("1", "A"); dictionary.Add("2", "B"); dictionary.Add("3", "C"); dictionary.Add("4", "D"); dictionary.Add("5", "A"); dictionary.Add("6", "A"); dictionary.Add("7", "A"); dictionary.Add("8", "A"); dictionary.Remove("5"); foreach (var key in dictionary.Keys) { Console.WriteLine(key); } foreach (var value in dictionary.Values) { Console.WriteLine(value); } Console.WriteLine("key为\"1\"的value是{0}", dictionary["1"]); #endregion #region LookUp<TKey,TValue> //LookUp<TKey,TValue> k-*v //LookUp<TKey,TValue>只能通过ToLookup()方法去创建, //实现了IEnumerable<T>接口的类型都拥有此方法 //拿到Value为A的字典集合 var lookupDictionary = dictionary.ToLookup(x => x.Value)["A"]; //lookupDictionary foreach (KeyValuePair <string, string> item in lookupDictionary) { Console.WriteLine(item); } //dictionary foreach (KeyValuePair <string, string> item in dictionary) { Console.WriteLine(item); } #endregion }
private bool IsTheSameYCoordination(Dictionary <int, int> rememberCoordinationDictionary) { var lookupTheSameCoordinationDictionary = rememberCoordinationDictionary .ToLookup(x => x.Value, x => x.Key) .Where(x => x.Count() > 1); return(lookupTheSameCoordinationDictionary != null); }
public static void Cozy() { Console.WriteLine("\n-----------------------------------------------"); Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); Console.WriteLine("-----------------------------------------------"); #region Dictionary<TKey, TValue> //Dictionary<TKey, TValue> k-v var dictionary = new Dictionary<string, string>(); dictionary.Add("1", "A"); dictionary.Add("2", "B"); dictionary.Add("3", "C"); dictionary.Add("4", "D"); dictionary.Add("5", "A"); dictionary.Add("6", "A"); dictionary.Add("7", "A"); dictionary.Add("8", "A"); dictionary.Remove("5"); foreach (var key in dictionary.Keys) { Console.WriteLine(key); } foreach (var value in dictionary.Values) { Console.WriteLine(value); } Console.WriteLine("key为\"1\"的value是{0}", dictionary["1"]); #endregion #region LookUp<TKey,TValue> //LookUp<TKey,TValue> k-*v //LookUp<TKey,TValue>只能通过ToLookup()方法去创建, //实现了IEnumerable<T>接口的类型都拥有此方法 //拿到Value为A的字典集合 var lookupDictionary = dictionary.ToLookup(x => x.Value)["A"]; //lookupDictionary foreach (KeyValuePair<string, string> item in lookupDictionary) { Console.WriteLine(item); } //dictionary foreach (KeyValuePair<string, string> item in dictionary) { Console.WriteLine(item); } #endregion }
public StringRemappingContractResolver(IEnumerable <KeyValuePair <object, object> > map) { if (map == null) { throw new ArgumentNullException("map"); } this.map = map.ToDictionary(p => p.Key ?? NullValue, p => p.Value); this.reverseMap = map.ToLookup(p => p.Value ?? NullValue, p => p.Key); }
static void Main(string[] args) { Dictionary <string, int> data = new Dictionary <string, int>(); data.Add("Office", 100); data.Add("Walls", 101); data.Add("Stair", 30); ILookup <string, int> look = data.ToLookup(); }
static PermissionUtil() { PermRepository.Add(new SYS_Permission { PermId = Guid.NewGuid().ToString(), Controller = "1", Createtime = DateTime.Now, PermCode = 123, PermName = "2", SystemId = 1 }); InitPermission(); PermissionCode = PermissionUrls.ToLookup(pair => pair.Value); }
public IReadOnlyDictionary <ModuleTreat, IReadOnlySet <ModuleDef> > Resolve() { foreach (var source in _sources) { Resolve(source, null); } AdjustEmbeddedReferences(); return(_states.ToLookup(kv => kv.Value.Treat, kv => kv.Key).Where(l => l.Any()) .ToDictionary(l => l.Key, l => l.AsReadOnlySet())); }
private void Rvrs_Click(object sender, RoutedEventArgs e) { Anatomy = Anatomy .ToLookup(kp => kp.Value) .ToDictionary(g => g.Key, g => g.First().Key); string tmp = TopLab.Content.ToString(); TopLab.Content = BotLab.Content; BotLab.Content = tmp; }
public string getName(ChemicalDbContext _context) { Dictionary <int, string> map = new Dictionary <int, string>(); foreach (Node n in this.ParentChain.NodeList) { if (n.Divergent) { map.Add(n.Position, _context.GetPrefixByLength(n.Branches[0].NodeList.Count()).Name); } } var identicalPairs = map.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1); foreach (var item in identicalPairs) { string countPrefix = ""; var keys = item.Aggregate("", (s, v) => s + ", " + v); switch (item.Count()) { case 2: countPrefix = "Di"; break; case 3: countPrefix = "Tri"; break; case 4: countPrefix = "Tetra"; break; } this.Name += keys + "-" + countPrefix + item.Key + "yl"; this.Name.Substring(1); } foreach (var item in identicalPairs) { item.ToList().ForEach(q => { map.Remove(q); }); } foreach (var item in map) { Name += item.Key + "-" + item.Value + "yl" + "-"; } if (this.Name != null && Equals(this.Name[this.Name.Length - 1], "-")) { this.Name = this.Name.Substring(0, this.Name.Length - 2); } this.Name += _context.GetPrefixByLength(this.ParentChain.NodeList.Count).Name + "ane"; if (Equals(this.Name.Substring(0, 1), ",")) { this.Name = this.Name.Substring(1); } return(this.Name); }
public void AddCard(Guid cardId, int laneId) { AssertLane(laneId); RaiseEvent(new CardAdded() { CardId = cardId, LaneId = laneId, Position = _cardMap.ToLookup(x => x.Value)[laneId].Count() }); }
static void Main(string[] args) { var is_test = false; var filename = is_test ? "sample.txt" : "input.txt"; var lines = File.ReadAllLines(filename); var transforms = new Dictionary <string, string>(); foreach (var line in lines.Skip(2)) { var split = line.Split(" -> "); transforms.Add(split[0], split[1]); } var theLine = lines[0]; var pairs = new Dictionary <string, long>(); for (int i = 0; i < theLine.Count() - 1; i++) { var pair = theLine.Substring(i, 2); Add(pairs, pair, 1); } for (int s = 0; s < 40; s++) { var pairs_new = new Dictionary <string, long>(); foreach (var kv in pairs) { if (transforms.ContainsKey(kv.Key)) { Add(pairs_new, kv.Key[0] + transforms[kv.Key], kv.Value); Add(pairs_new, transforms[kv.Key] + kv.Key[1], kv.Value); } else { Add(pairs_new, kv.Key, kv.Value); } } Console.Write("Step " + (s + 1) + ": " + (pairs_new.Sum(x => x.Value) + 1)); Console.WriteLine(); pairs = pairs_new; } var letters = pairs.ToLookup(x => x.Key[0], x => x.Value).ToDictionary(x => x.Key, x => x.Sum()); foreach (var kv in letters) { Console.WriteLine(kv.Key + ": " + kv.Value); } }
private void write() { Dictionary <String, String> filteredEmails = instanceFilterEmailsData.getFilterEmailsData(); using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputPath)) { if (InputData.KeepAtLeastDomain) { var lookup = filteredEmails.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() >= InputData.NoOfDomainsToKeep); UInt64 counter = 0; foreach (var item in lookup) { String textToWrite = item.Aggregate("", (s, v) => s + Environment.NewLine + v); file.WriteLine(textToWrite); ++counter; noOfEmailsActuallyDumped += Convert.ToUInt64(textToWrite.Count(x => x == '@')); if (null != UpdateStatusProgressBar) { UpdateStatusProgressBar("Dumping in chunks [" + counter + "], please wait ...", Convert.ToUInt16(counter % 100), false, true, false); } } } else { UInt64 counter = 0; UInt64 totalEmails = Convert.ToUInt64(filteredEmails.Count); noOfEmailsActuallyDumped = totalEmails; foreach (KeyValuePair <String, String> email in filteredEmails) { file.WriteLine(email.Key); ++counter; if (null != UpdateStatusProgressBar && (counter % 1000 == 0)) { UpdateStatusProgressBar("Dumping in chunks [" + counter + "], please wait ...", Convert.ToUInt16((counter * 100) / totalEmails), false, true, false); } } } } }
public FhirModel(Dictionary<Type, string> csTypeToFhirTypeNameMapping, IEnumerable<SearchParamDefinition> searchParameters, List<Type> enums) { LoadSearchParameters(searchParameters); _csTypeToFhirTypeName = csTypeToFhirTypeNameMapping; _fhirTypeNameToCsType = _csTypeToFhirTypeName.ToLookup(pair => pair.Value, pair => pair.Key).ToDictionary(group => group.Key, group => group.FirstOrDefault()); _enumMappings = new List<EnumMapping>(); foreach (var enumType in enums) { if (EnumMapping.IsMappableEnum(enumType)) { _enumMappings.Add(EnumMapping.Create(enumType)); } } }
public FhirModel(Dictionary <Type, string> csTypeToFhirTypeNameMapping, IEnumerable <SearchParamDefinition> searchParameters, List <Type> enums) { LoadSearchParameters(searchParameters); _csTypeToFhirTypeName = csTypeToFhirTypeNameMapping; _fhirTypeNameToCsType = _csTypeToFhirTypeName.ToLookup(pair => pair.Value, pair => pair.Key).ToDictionary(group => group.Key, group => group.FirstOrDefault()); _enumMappings = new List <EnumMapping>(); foreach (var enumType in enums) { if (EnumMapping.IsMappableEnum(enumType)) { _enumMappings.Add(EnumMapping.Create(enumType)); } } }
ILookup <string, long?> GetQueueLengths() { var result = new Dictionary <string, long>(); var dirs = Directory.EnumerateDirectories(rootFolder); foreach (var dir in dirs) { var queueName = Path.GetFileName(dir); if (queueName != null) { var queueLength = Directory.EnumerateFiles(dir).LongCount(); result[queueName] = queueLength; } } return(result.ToLookup(x => x.Key, x => (long?)x.Value)); }
public override string GetVideoUrl(VideoInfo video) { var doc = GetWebData <HtmlDocument>(video.VideoUrl); var link = doc.DocumentNode.Descendants("a").FirstOrDefault(a => a.GetAttributeValue("data-extension", "").Contains("\"url\":\"http")); if (link != null) { var json = JObject.Parse(link.GetAttributeValue("data-extension", "")); var playlistUrl = json["mediaObj"].Value <string>("url"); var f = GetWebData(playlistUrl); var startIdx = f.IndexOf('{'); var endIdx = f.LastIndexOf('}'); var length = endIdx - startIdx + 1; var json2 = JObject.Parse(f.Substring(startIdx, length)); var videoUrl = Regex.Match(f, "\"videoURL\":\"(?<url>.*?(f4m|smil|m3u8))\"").Groups["url"].Value; var url = json2["mediaResource"]["alt"].Value <string>("videoURL"); var playbackOptionsByUrl = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); if (url.Contains("master.m3u8")) { var uri = new Uri(new Uri(playlistUrl), url); var m3u8Data = GetWebData(uri.ToString()); foreach (Match match in Regex.Matches(m3u8Data, m3u8Regex)) { playbackOptionsByUrl[match.Groups["url"].Value] = string.Format("HLS - {0} - {1} kbps", match.Groups["resolution"].Value, int.Parse(match.Groups["bitrate"].Value) / 1000); } } video.PlaybackOptions = new Dictionary <string, string>(); foreach (var lookup in playbackOptionsByUrl.ToLookup(kvp => kvp.Value)) { var i = 0; foreach (var optionByUrl in lookup) { video.PlaybackOptions.Add(string.Format("{0} - {1}", optionByUrl.Value, i++), optionByUrl.Key); } } return(video.PlaybackOptions.Select(p => p.Value).LastOrDefault()); } return(null); }
/// <summary> /// Indicator whether a <paramref name="soilProfile"/> has valid state points. /// </summary> /// <param name="soilProfile">The <see cref="IMacroStabilityInwardsSoilProfileUnderSurfaceLine"/> to get the state points from.</param> /// <returns><c>true</c> when every layer in <paramref name="soilProfile"/> has max. 1 state point; <c>false</c> otherwise.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="soilProfile"/> is <c>null</c>.</exception> public static bool HasValidStatePoints(IMacroStabilityInwardsSoilProfileUnderSurfaceLine soilProfile) { if (soilProfile == null) { throw new ArgumentNullException(nameof(soilProfile)); } MacroStabilityInwardsSoilLayer2D[] layers = MacroStabilityInwardsSoilProfile2DLayersHelper.GetLayersRecursively(soilProfile.Layers).ToArray(); Dictionary <IMacroStabilityInwardsPreconsolidationStress, MacroStabilityInwardsSoilLayer2D> stressesWithLayers = soilProfile.PreconsolidationStresses.ToDictionary(pcs => pcs, pcs => GetLayerForPreconsolidationStress(layers, pcs)); IEnumerable <IGrouping <MacroStabilityInwardsSoilLayer2D, IMacroStabilityInwardsPreconsolidationStress> > duplicateLayers = stressesWithLayers.ToLookup(pair => pair.Value, pair => pair.Key).Where(x => x.Count() > 1); return(!duplicateLayers.Any() && stressesWithLayers.All(pair => pair.Value != null) && !stressesWithLayers.Any(stressWithLayer => stressWithLayer.Value.Data.UsePop && HasValidPop(stressWithLayer.Value.Data.Pop))); }
/* The major element in a sequence with the length of L is the element which appears in a sequence more than L/2 times. The challenge is to find that element in a sequence. */ //Did not consider the L/2 times yet. Logic is passing is correct at the moment //But not considering all the constraints of the problem. Will do on later commit. public static string FindTheMajorElement(string input) { var inputDictionary = new Dictionary<string, int>(); var splitValues = input.Split(','); foreach (var value in splitValues) { if (!inputDictionary.ContainsKey(value)) inputDictionary.Add(value, 1); else inputDictionary[value]++; } var max = inputDictionary.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; var lookup = inputDictionary.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1); var isMaxWithinDuplicateValue = false; foreach (var item in lookup) { isMaxWithinDuplicateValue = item.Aggregate("", (s, v) => s + " " + v).Split(' ').Contains(max); } return isMaxWithinDuplicateValue ? "None" : max; }
static void Main() { int n = int.Parse(Console.ReadLine()); string[] text = Console.ReadLine().Split(' ').ToArray(); Dictionary<string, string> allInput = new Dictionary<string, string>(); //create Dictionary for (int i = 0; i < text.Length; i++) //fill it with combinations { for (int j = 0; j < text.Length; j++) { if (!allInput.ContainsKey(string.Concat(text[i], "|", text[j]))) { if (i != j) { allInput.Add(string.Concat(text[i], "|", text[j]), string.Concat(text[i], text[j])); } } if (!allInput.ContainsKey(string.Concat(text[j], "|", text[i]))) { if (i != j) { allInput.Add(string.Concat(text[j], "|", text[i]), string.Concat(text[j], text[i])); } } } } var lookup = allInput.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1); //look for duplicate values foreach (var item in lookup) { var keys = item.Aggregate("", (s, v) => s + " " + v); //print the keys var message = keys; var keysReverse = item.Aggregate("", (s, v) => v + " " + s); ; Console.WriteLine(message); Console.WriteLine(" " + keysReverse); } }
public async Task<UserInfo> GetUserInfo(string refreshToken) { this.RefreshToken = refreshToken; GrantType = GrantTypeRefreshTokenKey; Dictionary<string, string> dicoParameter = new Dictionary<string, string>(); dicoParameter.Add(RefreshTokenKey, refreshToken); return await this.GetUserInfo(dicoParameter.ToLookup(y => y.Key, y => y.Value)); }
/// <summary> /// Get the current access token - and optionally refreshes it if it is expired /// </summary> /// <param name="refreshToken">The refresh token to use (null == default)</param> /// <param name="forceUpdate">Enforce an update of the access token?</param> /// <param name="safetyMargin">A custom safety margin to check if the access token is expired</param> /// <returns>The current access token</returns> public async Task<string> GetCurrentToken(string refreshToken = null, bool forceUpdate = false, TimeSpan? safetyMargin = null) { bool refreshRequired = forceUpdate || (ExpiresAt != null && DateTime.Now >= (ExpiresAt - (safetyMargin ?? ExpirationSafetyMargin))) || string.IsNullOrEmpty(AccessToken); if (refreshRequired) { string refreshTokenValue; if (!string.IsNullOrEmpty(refreshToken)) refreshTokenValue = refreshToken; else if (!string.IsNullOrEmpty(RefreshToken)) refreshTokenValue = RefreshToken; else throw new Exception("Token never fetched and refresh token not provided."); var parameters = new Dictionary<string, string>() { { _refreshTokenKey, refreshTokenValue }, }; GrantType = _grantTypeRefreshTokenKey; await QueryAccessToken(parameters.ToLookup(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase)); } return AccessToken; }
private static RequestGenerationByFuelTypeParams ConstructRequest(DateTimeOffset? newestAemoInterval, Dictionary<string, DateTimeOffset?> newestApviSolarIntervalByRegion, int resolution) { // The APVI web API expects its parameter region ids to be postfixed with 1 but does not return them postfixed with 1. var request5Min = new RequestGenerationByFuelTypeParams { NewestAemoInterval = newestAemoInterval, NewestSolarIntervals = newestApviSolarIntervalByRegion .ToLookup(r => r.Value) .Where(g => g.Key.HasValue) .Select(g => new IntervalRegions { NewestInterval = g.Key.Value, RegionIds = g.Select(r => r + "1").ToArray() }) .ToArray(), Resolution = resolution }; return request5Min; }
public override void Process(ServiceProcess process, object arguments) { _duplicateData = new List<DuplicateBinariesData>(); fileNames = new Dictionary<string, string>(); DuplicateBinariesParameters parameters = (DuplicateBinariesParameters)arguments; //_duplicateBinariesData = new DuplicateBinariesData(); //_duplicateBinariesData.PublicationId = parameters.PublicationId; process.SetCompletePercentage(10); process.SetStatus("working"); using (var coreService = Client.GetCoreService()) { try { process.SetCompletePercentage(15); process.SetStatus("Creating publication filter"); // Create a filter to only fetch multimedia components from the publication RepositoryItemsFilterData filter = new RepositoryItemsFilterData(); filter.ItemTypes = new[] { ItemType.Component }; filter.ComponentTypes = new[] { ComponentType.Multimedia }; XElement mmComponentsListXml = coreService.GetListXml(parameters.PublicationId, filter); XNamespace tcm = "http://www.tridion.com/ContentManager/5.0"; double progressIncrement = mmComponentsListXml.Value.Length == 0 ? 0 : 80 / mmComponentsListXml.Value.Length; //nasty progress calculation int i = 1; // keep a list of all the file names from the items in the publication // the if a file already exists in the filenames, it is considered a 'duplicate file name' foreach(XElement itemElem in mmComponentsListXml.Descendants(tcm + "Item")) { string itemId = itemElem.Attribute("ID").Value; string binaryFileName = GetFileNameFromComponent(coreService, itemId); fileNames.Add(itemId, binaryFileName); int progressPercentage = (int)(20 + i * progressIncrement); // some more nasty progress calculation process.SetCompletePercentage(progressPercentage); i++; } var duplicateValues = fileNames.ToLookup(a => a.Value). Where(b => b.Count() > 1); // todo - refactor this below item to select the id's and values from the file // name list foreach (var group in duplicateValues) { foreach (KeyValuePair<string, string> kvp in group) { _duplicateData.Add(new DuplicateBinariesData { ItemTcmId = kvp.Key, ItemFileName = kvp.Value, }); } } process.Complete("Done"); } catch (Exception ex) { // TODO: Update the GUI that there has been error - solution below is temporary process.Failed = true; process.Complete(string.Format("Failure finding duplicate items reason: {0}", ex.Message)); return; } } }
public async Task<UserInfo> GetUserInfo(string userName, string password) { GrantType = GrantTypeAuthorizationKey; Dictionary<string, string> dicoParameter = new Dictionary<string, string>(); dicoParameter.Add(UsernameKey, userName); dicoParameter.Add(PasswordKey, password); return await this.GetUserInfo(dicoParameter.ToLookup(y => y.Key, y => y.Value)); }