public collections_example()
        {
            //rule of thumb: generics exist and are a wonderful thing.

            //Lists
            List<string> sList = new List<string>();
            var namesList = new List<string>();//this is implying that var is a List<string>. It shortens variable declarations. This cannot be used as a return type. Variables only.

            sList.Add("James");//this is rather time consuming and not helpful. You are usually adding this from a db or data file.

            //you can add arrays to collections.
            string[] names = new string[]{
                "James",
                "John",
                "Jennifer",
                "Jackie",
                "Jake",
                "Jeremy"
            };
            namesList.AddRange(names);//this adds all the names in an array

            Console.WriteLine("The number of items in namesList is "+namesList.Count); //checks how many values are in the collection.

            bool james = namesList.Contains("James");//would return true.
            bool katie = namesList.Contains("Katie");// returns false

            Console.WriteLine("Does it contain James? {0}\nDoes it contain Katie? {1}\n", james, katie);

            var newList = namesList.FindAll((s) => s[1] == 'a');//lamba expressions, quickest way to write a predicate. More on this in future lessons.
            //copies the name whose second letter contains an a
            Console.WriteLine(newList.ToArray());//prints the name of the array, not the names IN the array.

            foreach (var name in newList)
            {
                Console.WriteLine(name);
            }

            //there's all sorts of stuff you can do to these. Remove, add, skip, sort, foreach, and far more. Use them on an as-needed basis.

            namesList.Clear();//clears everything so it is back at 0. Good for "cleaning the slate". YOU CANNOT GET THEM BACK!

            //Dictionaries
            Dictionary<int, string> dict = new Dictionary<int, string>();//could use var as well.
            dict.Add(0, "Jeremy");//keys must be unique. Int is the key.
            dict.Add(1, "Jake");// this changes the key value.
            dict.Add(2, "Hanna");

            string value = dict[0];//Jeremy
            Console.WriteLine("The value of value is: " + value);

            dict.ContainsValue("0");//returns true
            dict.ContainsValue("9");//returns false

            dict.Remove(1);//usually use a foreach loop to remove all values.

            foreach (var key in dict)
            {
                Console.WriteLine(key.Key + " = " + key.Value);
            }
        }
Example #2
0
        public override HandRanking Catagorize(Hand hand)
        {
            Dictionary<Value, int> seen = new Dictionary<Value, int>();

            foreach (Card c in hand.Cards)
            {
                if (seen.ContainsKey(c.Value))
                {
                    seen[c.Value]++;
                }
                else
                {
                    seen[c.Value] = 1;
                }
            }

            if (seen.Count == 2)
            {
                if(seen.ContainsValue(3) && seen.ContainsValue(2))
                {
                    return HandRanking.FullHouse;
                }
            }

            return Next.Catagorize(hand);
        }
        public bool IsFourOfAKind(IHand hand)
        {
            if (!this.IsValidHand(hand))
            {
                return false;
            }

            Dictionary<CardFace, int> faces = new Dictionary<CardFace, int>();
            for (var i = 0; i < NumberOfCardsInHand; i++)
            {
                if (!faces.ContainsKey(hand.Cards[i].Face))
                {
                    faces.Add(hand.Cards[i].Face, 1);
                }
                else
                {
                    faces[hand.Cards[i].Face] = faces[hand.Cards[i].Face] + 1;
                }
            }

            if (faces.Count == 2 && faces.ContainsValue(4) && faces.ContainsValue(1) && faces.Count == 2)

            {
                return true;
            }
            else
            {
                return false;
            }
        }
Example #4
0
        public void TheIdMapWillContainAMapOfAllChildren()
        {
            TestHierarchy h = new TestHierarchy();
            Dictionary<int, UnityObject> ids = new Dictionary<int, UnityObject>();

            h.root.SetNewId(ids);
            Assert.That(ids.ContainsValue(h.root), Is.True);
            Assert.That(ids.ContainsValue(h.child), Is.True);
            Assert.That(ids.ContainsValue(h.childOfChild), Is.True);
        }
Example #5
0
        public void TheIdMapWillContainTheObjectAndItsOriginalId()
        {
            Dictionary<int, UnityObject> ids = new Dictionary<int, UnityObject>();
            GameObject go = new GameObject();

            go.SetNewId(ids);

            Assert.That(ids.Count, Is.EqualTo(2));
            Assert.That(ids.ContainsValue(go), Is.True);
            Assert.That(ids.ContainsValue(go.transform), Is.True);
        }
Example #6
0
        static void Main(string[] args)
        {
            //Get the string from the application config
            var initialWord = ConfigurationManager.AppSettings["initialString"];

            initialWord = initialWord.ToLower();
            var initialWordFrequence=Class1.getFrequenceVector(initialWord);

            //The words from the file are kept in a dictionary, together with their frequence vector
            var wordsFromFileDict = new Dictionary<string, Dictionary<char, int>>();

            //The result strings are kept in a dictionary
            var resultDict = new Dictionary<string, string>();

            var reader = new StreamReader("wordList.txt");
            var line = "";
            while (line != null)
            {
                line = reader.ReadLine();

                if (line == null)
                    break;
                line = line.ToLower();
                if(!wordsFromFileDict.ContainsKey(line))
                    wordsFromFileDict.Add(line, Class1.getFrequenceVector(line));
            }

            foreach (var x in wordsFromFileDict)
            {

                //Console.WriteLine(x.ToLower());
                foreach (var y in wordsFromFileDict)
                {
                    initialWordFrequence = Class1.getFrequenceVector(initialWord);
                    if (Class1.canBeAnagrams(x.Value, y.Value, initialWordFrequence))

                        if (Class1.areAnagrams(x.Value, y.Value, initialWordFrequence))
                            //Doesn't add duplicates in the result
                            if(!(resultDict.ContainsKey(x.Key) && resultDict.ContainsValue(y.Key))
                                && !(resultDict.ContainsKey(y.Key) && resultDict.ContainsValue(x.Key) ))
                                    resultDict.Add(x.Key, y.Key);
                }
            }

            //Print the results
            foreach (var item in resultDict)
            {
                Console.WriteLine(String.Format("Anagrams of {0} : {1} - {2}", initialWord, item.Key, item.Value));
            }

            Console.ReadLine();
        }
Example #7
0
 public void agregarUsuariosMismoNombreDiccionario()
 {
     Dictionary<int,UsuarioView> usuarios = new Dictionary<int, UsuarioView>();
     UsuarioView a = new UsuarioView(1, "a", "b", "c");
     UsuarioView c = new UsuarioView(2, "a", "b", "c");
     usuarios.Add(int.Parse(a.id), a);
     usuarios.Add(int.Parse(c.id), c);
     bool expected = true;
     bool expected1 = usuarios.ContainsValue(a);
     bool expected2 = usuarios.ContainsValue(c);
     Assert.AreEqual(expected1,expected);
     Assert.AreEqual(expected2, expected);
 }
Example #8
0
        public static async Task<string> GetDataV2(RequestMethod method, string command, Dictionary<string, string> reqParams)
        {
            string json;

            if (reqParams != null && (reqParams.ContainsValue("True") || reqParams.ContainsValue("False")))
            {
                json = JsonConvert.SerializeObject(BoolDictionary(reqParams), Formatting.None);
            }
            else
            {
                json = JsonConvert.SerializeObject(reqParams, Formatting.None);
            }
            return await GetDataV2WithJson(method, command, json);
        }
Example #9
0
        public static void Main(string[] args)
        {
            /* List Operations */

            List<int> list = new List<int>();

            list.Add (10);

            list.AddRange (new List<int> () { 20, 30, 40 });

            list.Remove (10);

            list.Insert (0, 10);

            list.Clear ();

            /* Dictionary Operations */

            Dictionary<int, string> dictionary = new Dictionary<int, string> ();

            dictionary.Add (1, "Sanjana");
            dictionary.Add (2, "Sumana");

            dictionary.ContainsValue ("Sanjana");
            dictionary.Remove (1);

            dictionary.Add (3, "Srinivas");

            dictionary.Clear ();
        }
Example #10
0
        static void Main(string[] args)
        {
            // Task: to convert the Dictionary collection "elements"
            //to List with keeping hierarchy of elements
            Dictionary<string, string> elements = new Dictionary<string, string>()
            {
                {"Tissue", "Organ"},
                {"Cell", "Cells"},
                {"System", "Body"},
                {"Cells", "Tissue"},
                {"Organ", "System"},
            };

            List<string> hierarchy = new List<string>();

            string first = elements.Keys.First(el => !elements.ContainsValue(el));
            hierarchy.Add(first);

            while (elements.ContainsKey(hierarchy.Last()))
                hierarchy.Add(elements[hierarchy.Last()]);

            foreach (var item in hierarchy)
                Console.WriteLine(item);

            Console.ReadKey();
        }
        private bool IsIsomorphic(string s, string t)
        {
            if (string.IsNullOrEmpty(s) && string.IsNullOrEmpty(t)) return true;

            int slength = s.Length;
            int tlength = t.Length;
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t) || slength != tlength) return false;

            Dictionary<char, char> dic = new Dictionary<char, char>();
            for (int index = 0; index < slength; index++)
            {
                if (dic.ContainsKey(s[index]))
                {
                    if (dic[s[index]] != t[index])
                    {
                        return false;
                    }
                }
                else
                {
                    if (dic.ContainsValue(t[index]))
                    {
                        return false;
                    }
                    else
                    {
                        dic.Add(s[index], t[index]);
                    }
                }
            }
            return true;
        }
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ContainsValue(TValue) when the dictionary contains specified value .");

        try
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("txt", "notepad.exe");

            bool actual = dictionary.ContainsValue("notepad.exe");
            bool expected = true;
            if (actual != expected)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method ContainsValue(TValue) Err.");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        private static string UniqueNumber(int[] arr)
        {
            string result = string.Empty;

            if (arr != null && arr.Length > 0 && arr.Length % 2 != 0)
            {
                Dictionary<int, int> count = new Dictionary<int, int>();

                for (int i = 0; i < arr.Length; i++)
                {
                    if (count.ContainsKey(arr[i]))
                    {
                        count[arr[i]]++;
                    }
                    else
                    {
                        count.Add(arr[i], 1);
                    }
                }

                if (count.ContainsValue(1))
                {
                    foreach (var item in count)
                    {
                        if (item.Value == 1)
                        {
                            result = item.Key.ToString();
                            break;
                        }
                    }
                }
            }

            return result;
        }
Example #14
0
        public static void Main(string[] args)
        {
            /* List Operations */

            List<int> list = new List<int>();

            list.Add (1);
            list.Add (2);
            list.Add (3);

            list.Remove (1);

            list.Insert (0, 20);

            Console.WriteLine ("before clearing the list {0}",list.Count);
            list.Clear ();

            Console.WriteLine ("afetr clearing the list {0}",list.Count);

            /* Dictionary Operations */

            Dictionary<int, string> dictionary = new Dictionary<int, string> ();

            dictionary.Add (1, "xxx");
            dictionary.Add (2, "yyy");

            dictionary.ContainsValue ("yyy");
            dictionary.Remove (2);

            dictionary.Add (3, "zzz");
            Console.WriteLine ("before clearing the dictionary {0}",dictionary.Count);
            dictionary.Clear ();
            Console.WriteLine ("after clearing the dictionary {0}",dictionary.Count);
        }
Example #15
0
        /// <summary>
        /// Publish Reusable Workflow
        /// </summary>
        /// <param name="mapping"></param>
        public void PublishReusableWorkflow(NWFMappingEntry mapping)
        {
            SPContentType ct = web.ContentTypes[mapping.BindingName];
            string workflowName = mapping.WorkflowName;
            string pathToNWF = Path.Combine(properties.Definition.RootDirectory, mapping.WorkflowFileName);
            byte[] workflowData = File.ReadAllBytes(pathToNWF);
            string workflowFile = Utility.ConvertByteArrayToString(workflowData);

            while ((int)workflowFile[0] != (int)char.ConvertFromUtf32(60)[0])
                workflowFile = workflowFile.Remove(0, 1);

            ExportedWorkflowWithListMetdata workflowWithListMetdata = ExportedWorkflowWithListMetdata.Deserialize(workflowFile);
            string xmlMessage = workflowWithListMetdata.ExportedWorkflowSeralized;
            SPListCollection lists = web.Lists;
            Dictionary<string, Guid> dictionary = new Dictionary<string, Guid>(lists.Count);
            foreach (SPList spList in lists)
            {
                if (!dictionary.ContainsKey(spList.Title.ToUpper()))
                    dictionary.Add(spList.Title.ToUpper(), spList.ID);
            }
            foreach (var listReference in workflowWithListMetdata.ListReferences)
            {
                string key = listReference.ListName.ToUpper();
                if (dictionary.ContainsKey(key) && !dictionary.ContainsValue(listReference.ListId))
                    xmlMessage = xmlMessage.Replace(Utility.FormatGuid(listReference.ListId), Utility.FormatGuid(dictionary[key]));
            }
            var exportedWorkflow = WorkflowPart.Deserialize<ExportedWorkflow>(xmlMessage);
            foreach (var config in exportedWorkflow.Configurations.ActionConfigs)
                WorkflowRenderer.ProcessActionConfig(config);

            Guid listId = Guid.Empty;
            bool validateWorkflow = true;
            Publish publish = new Publish(web);
            publish.PublishAWorkflow(workflowName, exportedWorkflow.Configurations, listId, web, (ImportContext)null, validateWorkflow, ct.Id, string.Empty);
        }
Example #16
0
        public void DiceRollsShouldBeSeeminglyRandom()
        {
            var countOfPossibleRolls = new Dictionary<Int32, Int32>
                                           {
                                               { 2, 0 },
                                               { 3, 0 },
                                               { 4, 0 },
                                               { 5, 0 },
                                               { 6, 0 },
                                               { 7, 0 },
                                               { 8, 0 },
                                               { 9, 0 },
                                               { 10, 0 },
                                               { 11, 0 },
                                               { 12, 0 }
                                           };

            for (var i = 0; i < 150; i++)
            {
                dice.Roll();
                var totalRoll = dice.Value;
                countOfPossibleRolls[totalRoll]++;
            }

            Assert.That(!countOfPossibleRolls.ContainsValue(0));
        }
        /// <summary>
        /// Filters the promotions.
        /// </summary>
        /// <param name="evaluationContext">The evaluation context.</param>
        /// <param name="records">The records, must be sorted in the order they are applied.</param>
        /// <returns></returns>
		public PromotionRecord[] FilterPromotions(IPromotionEvaluationContext evaluationContext, PromotionRecord[] records)
		{
            var appliedRecords = new List<PromotionRecord>();

            var groups = new Dictionary<string, string>();

            foreach (var record in records)
            {
                if (!groups.ContainsKey(record.PromotionType)) // we already have exclusive withing a current group, so ignore
                {
                    if (record.Reward.Promotion.ExclusionTypeId == (int)ExclusivityType.Group)
                    {
                        groups.Add(record.PromotionType, record.Reward.Promotion.PromotionId);
                    }

                    appliedRecords.Add(record);
                }
                else // remove the rest of promotion records unless it was generated by the applied group promotion
                {
                    if (groups.ContainsValue(record.Reward.Promotion.PromotionId))
                        appliedRecords.Add(record);
                }
            }

            return appliedRecords.ToArray();
		}
Example #18
0
        public bool MakeGETDownloadRequestToAws(bool useSSL, string bucketName, string keyName, string queryString)
        {
            var result = false;
            var mySettings = new Properties.Settings();

            //create an instance of the REST class
            var myDownload = new SprightlySoftAWS.S3.Download();

            // build the URL to call. The bucket name and key name must be empty to return all buckets
            RequestURL = myDownload.BuildS3RequestURL(useSSL, "s3.amazonaws.com", bucketName, keyName, queryString);

            RequestMethod = "GET";

            ExtraRequestHeaders = new Dictionary<String, String> {
                {
                    "x-amz-date", DateTime.UtcNow.ToString("r")
                }};
            //add a date header

            //generate the authorization header value
            var authorizationValue = myDownload.GetS3AuthorizationValue(RequestURL, RequestMethod, ExtraRequestHeaders, "AKIAJCHWEMYQ5UXHOWSQ", "GLQ3fzqhpJmEvRf3J6SWquH1KbQdVEI+3tqqWGiy");
            //add the authorization header
            if (!ExtraRequestHeaders.ContainsValue(authorizationValue))
            {
                ExtraRequestHeaders.Add("Authorization", authorizationValue);
            }

            //call Download file to submit the download request
            result = myDownload.DownloadFile(RequestURL, RequestMethod, ExtraRequestHeaders, DownloadFileName, true);

            return result;
        }
Example #19
0
        public static void Initialize()
        {
            int messagesCount = 0;

            InfoEvents = new Dictionary<string, uint>();

            foreach (var Packet in typeof(RevcHeaders).GetFields())
            {
                var PacketId = (uint)Packet.GetValue(0);
                var PacketName = Packet.Name;

                if (!InfoEvents.ContainsValue(PacketId))
                {
                    InfoEvents.Add(PacketName, PacketId);
                }
            }

            foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
            {
                if (t.GetInterface("IPacketEvent") != null)
                {
                    var message = Activator.CreateInstance(t) as IPacketEvent;

                    if (message != null) Messages.Add(message.EventId, message);

                    messagesCount++;
                }
            }

            Application.Logging.WriteLine(string.Format("RevEmu invoked: {0} Events.", messagesCount));
        }
Example #20
0
        static void Main(string[] args)
        {
            Dictionary<int, Figure> figures = new Dictionary<int, Figure>();

            Circle cir1 = new Circle(3, Color.Orange);
            Rectangle rect1 = new Rectangle(2, 5, Color.Blue);
            Triangle tri1 = new Triangle(3, 7, 8, Color.Green);

            try
            {
                figures.Add(1, cir1);
                figures.Add(2, rect1);
                figures.Add(1, tri1);
            }
            catch (ArgumentException ex)
            {
                figures.Add(3, tri1);
                Console.WriteLine(ex.ToString() + "\n");
            }

            foreach (KeyValuePair<int, Figure> kvp in figures)
            {
                Console.WriteLine(kvp.Value + "\n");
            }

            Rectangle rect2 = rect1; // reference
            rect2.Color = Color.Black;

            Console.WriteLine(rect1);
            Console.WriteLine(figures.ContainsValue(rect2));
        }
        protected void Filterlist_SelectedIndexChanged(object sender, EventArgs e)
        {
            Dictionary<string, bool> paramPreview = new Dictionary<string, bool>();

            for (int i = 0; i < filterlist.Items.Count; i++)
            {
                if (filterlist.Items[i].Selected == true)
                {
                    paramPreview.Add(filterlist.Items[i].Value, true);
                }
            }
            //Keys key = Search.GetID(FederationForms);
            Session["ParamPreview"] = paramPreview;
            if (paramPreview.ContainsValue(true))
            {
                List<Guid> list = Search.GetPropertyIDsSearch(paramPreview, FederationForms);
                lstPropertyView.DataSource = Search.GetPropertyTable(FederationForms, list);
                lstPropertyView.DataBind();

            }
            else
            {
                ListDataBind();

            }
        }
Example #22
0
    public WindowsPaths()
    {
      _paths = new Dictionary<string, string>();
      //_paths.Add("%ProgramFiles", Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));

      foreach (string options in Enum.GetNames(typeof (Environment.SpecialFolder)))
      {
        if (!string.IsNullOrEmpty(Environment.GetFolderPath(
          (Environment.SpecialFolder)Enum.Parse(typeof (Environment.SpecialFolder), options))))
          _paths.Add(string.Format("%{0}%", options),
                     Environment.GetFolderPath(
                       (Environment.SpecialFolder)Enum.Parse(typeof (Environment.SpecialFolder), options)));
      }
      string fontsDir = Environment.GetEnvironmentVariable("windir");

      if (fontsDir == null)
      {
        fontsDir = "C:\\WINDOWS\\Fonts";
      }
      else
      {
        fontsDir = Path.Combine(fontsDir, "Fonts");
      }

      if (!_paths.ContainsValue(fontsDir))
      {
        _paths.Add("%Fonts%", fontsDir);
      }
      _paths.Add("%Temp%", Path.GetTempPath());
    }
Example #23
0
 public Dictionary<string, Dictionary<string, string>> getBill()
 {
     String html = NetUtils.getHtml(HOME_URL);
     html = NetUtils.formateHtml(html);
     if (html == null) {
         return null;
     }
     String pattern = null;
     MatchCollection matches = null;
     Dictionary<string, Dictionary<string, string>> bill;
     bill = new Dictionary<String, Dictionary<String, String>>();
     foreach (String week in allWeek) {
         Dictionary<String, String> playbill = new Dictionary<String, String>();
         pattern = TextUtils.weekToEng(week) + @"array\.push[\s\S]*?,'([\s\S]*?)','([\s\S]*?)'";
         matches = Regex.Matches(html, pattern, RegexOptions.Compiled);
         foreach (Match m in matches) {
             if (playbill.ContainsValue(m.Groups[2].ToString())) {
                 continue;
             }
             playbill.Add(NetUtils.stripHtml(m.Groups[1].ToString()), m.Groups[2].ToString());
         }
         bill.Add(week, playbill);
     }
     return bill;
 }
        public bool IsValid(string s)
        {
            var map = new Dictionary<char, char>
            {
                {'(', ')'},
                {'{', '}'},
                {'[', ']'}
            };

            var bracketStack = new Stack<char>();

            for (var idx = 0; idx < s.Length; ++idx)
            {
                if (map.ContainsKey(s[idx]))
                {
                    bracketStack.Push(map[s[idx]]);
                    continue;
                }
                if (map.ContainsValue(s[idx]))
                {
                    if (bracketStack.Count == 0) return false;
                    var expectedClosingBracket = bracketStack.Pop();
                    if (s[idx] == expectedClosingBracket) continue;
                    return false;
                }
            }

            return (bracketStack.Count == 0);
        }
Example #25
0
 public void AddItemPriceTest_addItem_itemAddedToDictionary() {
     PricingModel pricingModel = new PricingModel(new string[0]);
     Dictionary<Item, double> existingDictionary = new Dictionary<Item, double>();            
     pricingModel.AddItemPrice(existingDictionary, "Apple,2.50");
     Assert.AreEqual(1, existingDictionary.Count);
     Assert.IsTrue(existingDictionary.ContainsKey(new Item("Apple")));
     Assert.IsTrue(existingDictionary.ContainsValue(2.50));
 }
Example #26
0
        public void RemoveAll_MultipleCollection()
        {
            var collection = new Dictionary<int, int> { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 2 }, { 5, 3 } };
            collection.RemoveAll (kvp => kvp.Value == 2);

            Assert.AreEqual (3, collection.Count);
            Assert.IsFalse (collection.ContainsValue (2), "Collection still contains removed items");
        }
        static void Main(string[] args)
        {
            Dictionary<string, string> languagesDictionary = new Dictionary<string, string>();
            languagesDictionary.Add("C#", "The best programming language in the world.");

            Console.WriteLine("This is a dictionary of computer programming languages.  To search for a language by it's name press N or to search by description enter D");
            Console.WriteLine("Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit.");

            char userInput = Convert.ToChar(Console.ReadLine().ToLower());

            do
            {
                switch (userInput)
                {

                    case 'n':
                        Console.WriteLine("Please enter the name of the language you are searching for.");
                        string searchName = Console.ReadLine();
                        if (languagesDictionary.ContainsKey(searchName) == true)
                        {
                            Console.WriteLine(searchName + " is in the dictionary.");
                        }
                        else
                        {
                            Console.WriteLine(searchName + " could not be found.");
                        }
                        break;

                    case 'd':
                        Console.WriteLine("Please enter a description of the language you are searching for.");
                        string searchDescription = Console.ReadLine();
                        if (languagesDictionary.ContainsValue(searchDescription) == true)
                        {
                            Console.WriteLine(searchDescription + " is in the dictionary.");
                        }
                        else
                        {
                            Console.WriteLine(searchDescription + " could not be found.");
                        }
                        break;

                    case 'c':
                        int dictionarySize = languagesDictionary.Count();
                        Console.WriteLine("There are " + dictionarySize + " languages in the dictionary");
                        break;

                    default:
                        break;

                }
                Console.WriteLine("To search for a language by it's name press N or to search by description enter D.  Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit.");
                userInput = Convert.ToChar(Console.ReadLine().ToLower());

            } while (userInput != 'x');

                Console.WriteLine("Your session has now ended.");
        }
Example #28
0
 // This subs in the name used in the SELECT if it's a fuzzy matched column.
 // TODO: Seems like this might belong on the TableContext?
 // TODO: Looking it up with every row is pretty danged inefficient.
 // Flipping the key/value here b/c the fuzzy name is unique, not the strict name,
 // now that we're supporting the same column multiple times with different [fuzzy, for now]
 // names.
 // TODO: Allow column name aliases.
 public static string GetFuzzyNameIfExists(string strStrictColName, Dictionary<string, string> dictNameMapping)
 {
     string strReturn = strStrictColName;
     if (dictNameMapping.ContainsValue(strStrictColName))
     {
         strReturn = dictNameMapping.XGetFirstKeyByValue<string>(strStrictColName);
     }
     return strReturn;
 }
Example #29
0
        internal MarketLog parseMarketLog(FileInfo fi, ref Dictionary<int, string> dRegionNames)
        {
            String sFileName = fi.Name.Substring(0, fi.Name.LastIndexOf('.')).ToString();
            string sDateCreated = string.Empty;
            string sItem = string.Empty;
            string sRegion = string.Empty;
            int iLastHyphen = sFileName.LastIndexOf('-');
            int iFirstHyphen = sFileName.IndexOf('-');

            if (iLastHyphen != -1 && iFirstHyphen != -1 && !(iLastHyphen == iFirstHyphen))
            {
                sDateCreated = sFileName.Substring(iLastHyphen + 1, sFileName.Length - iLastHyphen - 1).Trim();
                sItem = sFileName.Substring(iFirstHyphen + 1, iLastHyphen - iFirstHyphen - 1).Trim();
                sRegion = sFileName.Substring(0, iFirstHyphen).Trim();

                // Check for regions with hyphens
                if (!dRegionNames.ContainsValue(sRegion))
                {
                    string[] saFileNameParts = sFileName.Split('-');
                    sRegion = string.Format("{0}-{1}", saFileNameParts);
                    // If error give light error message and return null, but continue parsing.
                    if (!dRegionNames.ContainsValue(sRegion)) //throw new Exception("Error parsing file: " + sFileName);
                    {
                        MarketScanner.Main.LightErrorMessage += string.Format("Error parsing file:{1}{0}", Environment.NewLine, fi.Name);
                        return null;
                    }
                    // Fix the item
                    sItem = sItem.Substring(sItem.IndexOf('-') + 1).Trim();
                }

                MarketLog oMarketLog = new MarketLog();
                oMarketLog.Created = parseTimestamp(sDateCreated);
                oMarketLog.Item = sItem;
                oMarketLog.Region = sRegion;
                oMarketLog.FileName = fi.Name;
                oMarketLog.FilePath = fi.FullName;

                return oMarketLog;
            }
            else
            {
                return null;
            }
        }
        public void AmbiguousCiteTemplateDates2()
        {
            Dictionary<int, int> ambigDates = new Dictionary<int, int>();

            ambigDates = Parsers.AmbigCiteTemplateDates(@"now {{cite web | url=http://site.it | title=a |date=7-6-2005 }}");

            Assert.AreEqual(ambigDates.Count, 1);
            Assert.IsTrue(ambigDates.ContainsKey(52));
            Assert.IsTrue(ambigDates.ContainsValue(8));
        }