Example #1
0
        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);
                }
            }
        }
Example #2
0
        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

        }
Example #3
0
        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));
                }
            }
        }
        /*
        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);
        }
    }
        /// <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;
                    
                }

            }


        }
Example #9
0
 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));
 }
Example #10
0
 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));
 }