Example #1
0
        public static bool IsPermutationByCharacterCount(string s, string t)
        {
            if (s.Length != t.Length) return false;

            var counts = new Dictionary<char, int>();

            foreach (var c in s)
            {
                if (!counts.ContainsKey(c)) counts[c] = 0;

                counts[c]++;
            }

            foreach (var c in t)
            {
                if (!counts.ContainsKey(c)) counts[c] = 0;

                if (--counts[c] < 0)
                {
                    return false;
                }
            }

            return true;
        }
Example #2
0
        public int[] Intersect(int[] nums1, int[] nums2)
        {
            //Solution can be:(this one is slower than below)
            //var map1 = nums1.GroupBy(n => n).ToDictionary(g => g.Key, g => g.Count());
            //return nums2.Where(n => map1.ContainsKey(n) && map1[n]-- > 0).ToArray();
            //Or:

            Dictionary<int, int> numbCount=new Dictionary<int, int>();
            foreach (int i in nums1)
            {
                if (!numbCount.ContainsKey(i))
                {
                    numbCount.Add(i,0);
                }
                numbCount[i]++;
            }

            List<int> ls = new List<int>();
            foreach (int j in nums2)
            {
                if (numbCount.ContainsKey(j) && numbCount[j] > 0)
                {
                    ls.Add(j);
                    numbCount[j]--;
                }
            }

            return ls.ToArray();
        }
Example #3
0
        private static void AddPortal(XmlNode portal)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            XmlNodeList childList = portal.ChildNodes;
            for (int i = 0; i < childList.Count; i++)
                data.Add(childList.Item(i).Name, childList.Item(i).InnerText);

            if (!data.ContainsKey("toid")) return;
            try
            {
                Dictionary<byte,PortalInfo> tmpdic;
                System.Globalization.CultureInfo culture;
                culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
                PortalInfo nPortal = new PortalInfo(int.Parse(data["toid"]), float.Parse(data["x"],culture), float.Parse(data["y"],culture), float.Parse(data["z"],culture));
                if (data.ContainsKey("mapid"))
                    nPortal.m_mapID = byte.Parse(data["mapid"]);
                if (!portals.ContainsKey(byte.Parse(data["toid"])))
                {
                    tmpdic = new Dictionary<byte, PortalInfo>();
                    tmpdic.Add(byte.Parse(data["fromid"]), nPortal);
                    portals.Add(byte.Parse(data["toid"]), tmpdic);
                }
                else
                {
                    tmpdic = portals[byte.Parse(data["toid"])];
                    tmpdic.Add(byte.Parse(data["fromid"]), nPortal);
                }

            }
            catch (Exception e) { Logger.ShowError("cannot parse: " + data["toid"],null); Logger.ShowError(e,null); return; }
        }
 protected void BatchAdd(Item item1, Item item2, Item item3, Item item4, Item item5, Section[] sectionList)
 {
     var itemList = new[] {item1, item2, item3, item4, item5};
     var itemDictionary = new Dictionary<ItemCategory, Item>();
     foreach (var item in itemList)
     {
         if (item != null) itemDictionary.Add(item.Category, item);
     }
     var topList = new List<Section>();
     var bottomList = new List<Section>();
     var leftList = new List<Section>();
     var rightList = new List<Section>();
     foreach (var section in sectionList)
     {
         topList.Add(Section.Line(section.GridX, section.GridY + section.Row, section.Column, section.OffsetX,
             section.OffsetY));
         bottomList.Add(Section.Line(section.GridX, section.GridY - 1, section.Column, section.OffsetX,
             section.OffsetY));
         leftList.Add(Section.Tower(section.GridX - 1, section.GridY, section.Row, section.OffsetX,
             section.OffsetY));
         rightList.Add(Section.Line(section.GridX + section.Column, section.GridY, section.Row, section.OffsetX,
             section.OffsetY));
     }
     ObjectData.Add(itemDictionary[ItemCategory.Body].Clone, sectionList);
     if (itemDictionary.ContainsKey(ItemCategory.TopCap))
         ObjectData.Add(itemDictionary[ItemCategory.TopCap].Clone, topList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.BottomCap))
         ObjectData.Add(itemDictionary[ItemCategory.BottomCap].Clone, bottomList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.LeftCap))
         ObjectData.Add(itemDictionary[ItemCategory.LeftCap].Clone, leftList.ToArray());
     if (itemDictionary.ContainsKey(ItemCategory.RightCap))
         ObjectData.Add(itemDictionary[ItemCategory.RightCap].Clone, rightList.ToArray());
 }
Example #5
0
	public override bool CheckAccept()
	{
		Dictionary<int, int> dicHaveItem = new Dictionary<int, int>();
		InvenSlot[] invens = ItemMgr.HadItemManagement.Inven.invenSlots;
		foreach( InvenSlot inven in invens)
		{
			if( inven != null && inven.realItem != null)
			{
				int itemID = inven.realItem.item.ItemID;

				if( dicHaveItem.ContainsKey( itemID))
					dicHaveItem[itemID] += 1;
				else
					dicHaveItem.Add( itemID, 1);
			}
		}

		// 아이템 소유 & 수량 체크
		if( !dicHaveItem.ContainsKey( ItemID))
			return false;

		int count = dicHaveItem[ItemID];
		if( ItemCount > count)
			return false;

		return true;
	}
        protected virtual Dictionary<string, KeyValuePair<string, string>> GetEntityDataFromType(Type type)
        {
            Dictionary<string, KeyValuePair<string, string>> res = new Dictionary<string, KeyValuePair<string, string>>();
            foreach (Attribute attr in type.GetCustomAttributes())
            {
                if (attr is SemanticEntityAttribute)
                {
                    SemanticEntityAttribute semantics = (SemanticEntityAttribute)attr;
                    // we can only support mapping to a single semantic entity, the derived type is set first, so that is what we use
                    if (!res.ContainsKey(semantics.Prefix))
                    {
                        res.Add(semantics.Prefix, new KeyValuePair<string, string>(semantics.Vocab, semantics.EntityName));
                    }
                }
                if (attr is SemanticDefaultsAttribute)
                {
                    SemanticDefaultsAttribute semantics = (SemanticDefaultsAttribute)attr;
                    res.Add(semantics.Prefix, new KeyValuePair<string, string>(semantics.Vocab, String.Empty));
                }
            }

            //Add default mapping if none was specified on entity
            if (!res.ContainsKey(string.Empty))
            {
                res.Add(string.Empty, new KeyValuePair<string, string>(ViewModel.CoreVocabulary, string.Empty));
            }

            return res;
        }
        public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                               OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
                                               ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary<string, object>();

            if (requestParameters.ContainsKey("ResetMenu"))
            {
                PagesMigrator.ResetToDefaults();
                response = "Menu: "+ translator.GetTranslatedString("ChangesSavedSuccessfully");
                return null;
            }
            if (requestParameters.ContainsKey("ResetSettings"))
            {
                SettingsMigrator.ResetToDefaults(webInterface);
                response = "WebUI: "+ translator.GetTranslatedString("ChangesSavedSuccessfully");
                return null;
            }

            vars.Add("FactoryReset", translator.GetTranslatedString("FactoryReset"));
            vars.Add("ResetMenuText", translator.GetTranslatedString("ResetMenuText"));
            vars.Add("ResetSettingsText", translator.GetTranslatedString("ResetSettingsText"));
            vars.Add("ResetMenuInfoText", translator.GetTranslatedString("ResetMenuText"));
            vars.Add("ResetSettingsInfoText", translator.GetTranslatedString("ResetSettingsInfoText"));
            vars.Add("Reset", translator.GetTranslatedString("Reset"));

            return vars;
        }
 public RulerGivenSkillContainerSkill(IRulerGivenSkill InnerSkill, Allegiance al)
 {
     innerSkillType = InnerSkill.GetType();
     Allegiance = al;
     masterList = new Dictionary<Player, IRulerGivenSkill>();
     var trigger = new AutoNotifyPassiveSkillTrigger(
         this,
         DistributeSkills,
         TriggerCondition.OwnerIsSource
     ) { IsAutoNotify = false, AskForConfirmation = false };
     var trigger2 = new AutoNotifyPassiveSkillTrigger(
         this,
         (p, e, a) =>
         {
             if (a.Source.Allegiance == Allegiance && !masterList.ContainsKey(a.Source))
             {
                 DistributeSkills(Owner, null, null);
             }
             if (a.Source.Allegiance != Allegiance && masterList.ContainsKey(a.Source))
             {
                 ISkill skill = masterList[a.Source];
                 masterList.Remove(a.Source);
                 Game.CurrentGame.PlayerLoseAdditionalSkill(a.Source, skill, true);
             }
         },
         TriggerCondition.Global
     ) { IsAutoNotify = false, AskForConfirmation = false };
     Triggers.Add(GameEvent.PlayerGameStartAction, trigger);
     Triggers.Add(GameEvent.PlayerChangedAllegiance, trigger2);
     IsAutoInvoked = null;
     IsRulerOnly = true;
 }
Example #9
0
 public IMMDModelPart Create(int triangleCount, MMDVertexNm[] Vertices, Dictionary<string, object> OpaqueData)
 {
     IndexBuffer indexBuffer = null;
     if (OpaqueData.ContainsKey("IndexBuffer"))
         indexBuffer = OpaqueData["IndexBuffer"] as IndexBuffer;
     Vector2[] extVert = null;
     if (OpaqueData.ContainsKey("VerticesExtention"))
         extVert = OpaqueData["VerticesExtention"] as Vector2[];
     if (indexBuffer == null)
         throw new ArgumentException("MMDModelPartXBoxFactoryのOpaqueDataには\"IndexBuffer\"キーとIndexBufferオブジェクトが必要です。", "OpaqueData");
     if (extVert == null)
         throw new ArgumentException("MMDModelPartXboxFactoryのOpaqueDataには\"VerticesExtention\"キーが必要です。", "OpaqueData");
     if (Vertices is MMDVertexNmTx[])
     {
         if (Vertices is MMDVertexNmTxVc[])
             return new MMDXBoxModelPartPNmTxVc(triangleCount, (MMDVertexNmTxVc[])Vertices, extVert, indexBuffer);
         else
             return new MMDXBoxModelPartPNmTx(triangleCount, (MMDVertexNmTx[])Vertices, extVert, indexBuffer);
     }
     else
     {
         if (Vertices is MMDVertexNmVc[])
             return new MMDXBoxModelPartPNmVc(triangleCount, (MMDVertexNmVc[])Vertices, extVert, indexBuffer);
         else
             return new MMDXBoxModelPartPNm(triangleCount, (MMDVertexNm[])Vertices, extVert, indexBuffer);
     }
 }
Example #10
0
        static void Main()
        {
            var graph = new Dictionary<int, List<int>>();
            int f = int.Parse(Console.ReadLine());
            int k = int.Parse(Console.ReadLine());

            for (int i = 0; i < f; i++)
            {
                int[] edge = new int[2];
                edge =
                    Console.ReadLine()
                        .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(int.Parse)
                        .ToArray();
                if (!graph.ContainsKey(edge[0]))
                {
                    graph[edge[0]] = new List<int>();
                }

                graph[edge[0]].Add(edge[1]);

                if (!graph.ContainsKey(edge[1]))
                {
                    graph[edge[1]] = new List<int>();
                }

                graph[edge[1]].Add(edge[0]);
            }

            var currentNode = k;
            int count = FindLongestDance(graph, k);
            Console.WriteLine(count);
        }
Example #11
0
 public void Parse1CssFileAndValidate() {
     p.Parse(new StringReader(HTML1));
     Dictionary<String, String> props = new Dictionary<String, String>();
     cssFiles.PopulateCss(props, "body");
     Assert.IsTrue(props.ContainsKey("font-size"));
     Assert.IsTrue(props.ContainsKey("color"));
 }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StackTraceElement"/> class using the given property values.
        /// </summary>
        /// <param name="elementAttributes">A <see cref="Dictionary{K, V}"/> containing the names and values for the properties of this <see cref="StackTraceElement"/>.</param>
        public StackTraceElement(Dictionary<string, object> elementAttributes)
        {
            if (elementAttributes != null)
            {
                if (elementAttributes.ContainsKey("className") && elementAttributes["className"] != null)
                {
                    this.className = elementAttributes["className"].ToString();
                }

                if (elementAttributes.ContainsKey("methodName") && elementAttributes["methodName"] != null)
                {
                    this.methodName = elementAttributes["methodName"].ToString();
                }

                if (elementAttributes.ContainsKey("lineNumber"))
                {
                    this.lineNumber = Convert.ToInt32(elementAttributes["lineNumber"], CultureInfo.InvariantCulture);
                }

                if (elementAttributes.ContainsKey("fileName") && elementAttributes["fileName"] != null)
                {
                    this.fileName = elementAttributes["fileName"].ToString();
                }
            }
        }
Example #13
0
        private static bool EvaluateChain(string chain)
        {
            var nodes = new Dictionary<string, string>();

            // Build LinkedList
            foreach (string pair in chain.Split(';'))
            {
                // Node value: node[0]
                // Next node:  node[1]
                var node = pair.Split('-');
                if (nodes.ContainsKey(node[0])) { return false; }   // Duplicate
                if (node[0].Equals(node[1])) { return false; }      // Cycle
                nodes.Add(node[0], node[1]);
            }

            // Evaluate LinkedList
            // 500 pairs, maximum therefore it is more effective to just iterate at max 500 instead of doing cycle detection.
            // The counter will also make sure that we fail, if we have unconnected nodes :)
            // BEGIN-3;3-4;4-2;2-END --> GOOD
            // BEGIN-3;3-4;4-2;2-3   --> BAD
            string transitionTo = "BEGIN";
            for (int i = 0; i < nodes.Count; i++)
            {
                if (!nodes.ContainsKey(transitionTo)) { return false; }
                transitionTo = nodes[transitionTo];
            }

            // At the end, transitionTo should be Pointing to END
            return transitionTo.Equals("END");
        }
Example #14
0
 public void FiltrateFighters()
 {
     var pretendents = new Dictionary<string, int>();
     foreach (var e in Fighters)
         if (!pretendents.ContainsKey(e.Item1))
             pretendents[e.Item1] = 0;
     var temp = pretendents.ToDictionary(x => x.Key, y => y.Value);
     foreach (var e in temp)
     {
         try
         {
             var process = new Process();
             process.StartInfo.FileName = "Checkers.Tournament.exe";
             process.StartInfo.Arguments = e.Key + " " + "testPlayer.dll";
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardInput = true;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.CreateNoWindow = true;
             process.Start();
             var winner = process.StandardOutput.ReadLine()[0];
             if (winner == 'W')
                 pretendents[e.Key]++;
         }
         catch
         {
             pretendents[e.Key] = -10;
         }
     }
     Fighters = Fighters.Where(x => pretendents.ContainsKey(x.Item1) && pretendents.ContainsKey(x.Item2))
                        .ToList();
     //добавить ограничение по победам
     // фильтруем некорректные дллс
 }
Example #15
0
 public override void FillFromDictionary(Dictionary<string, object> dict)
 {
     if(dict.ContainsKey("status")) {
         if(dict["status"] != null) {
             status = DataType.Instance.FillString(dict["status"]);
         }
     }
     if(dict.ContainsKey("date_created")) {
         if(dict["date_created"] != null) {
             date_created = DataType.Instance.FillDateTime(dict["date_created"]);
         }
     }
     if(dict.ContainsKey("active")) {
         if(dict["active"] != null) {
             active = DataType.Instance.FillBool(dict["active"]);
         }
     }
     if(dict.ContainsKey("uuid")) {
         if(dict["uuid"] != null) {
             uuid = DataType.Instance.FillString(dict["uuid"]);
         }
     }
     if(dict.ContainsKey("date_modified")) {
         if(dict["date_modified"] != null) {
             date_modified = DataType.Instance.FillDateTime(dict["date_modified"]);
         }
     }
 }
        public virtual FacebookOAuthResult ParseOAuthCallbackUrl(Uri uri)
        {
            var parameters = new Dictionary<string, object>();

            bool found = false;
            if (!string.IsNullOrEmpty(uri.Fragment))
            {
                // #access_token and expries_in are in fragment
                var fragment = uri.Fragment.Substring(1);
                ParseUrlQueryString("?" + fragment, parameters, true);

                if (parameters.ContainsKey("access_token"))
                    found = true;
            }

            // code, state, error_reason, error and error_description are in query
            // ?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.
            var queryPart = new Dictionary<string, object>();
            ParseUrlQueryString(uri.Query, queryPart, true);

            if (queryPart.ContainsKey("code") || (queryPart.ContainsKey("error") && queryPart.ContainsKey("error_description")))
                found = true;

            foreach (var kvp in queryPart)
                parameters[kvp.Key] = kvp.Value;

            if (found)
                return new FacebookOAuthResult(parameters);

            throw new InvalidOperationException("Could not parse Facebook OAuth url.");
        }
Example #17
0
            public string Correct(string word)
            {
                if (string.IsNullOrEmpty(word))
                    return word;

                word = word.ToLower();

                // known()
                if (_dictionary.ContainsKey(word))
                    return word;

                List<String> list = Edits(word);
                Dictionary<string, int> candidates = new Dictionary<string, int>();

                foreach (string wordVariation in list)
                {
                    if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
                        candidates.Add(wordVariation, _dictionary[wordVariation]);
                }

                if (candidates.Count > 0)
                    return candidates.OrderByDescending(x => x.Value).First().Key;

                // known_edits2()
                foreach (string item in list)
                {
                    foreach (string wordVariation in Edits(item))
                    {
                        if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
                            candidates.Add(wordVariation, _dictionary[wordVariation]);
                    }
                }

                return (candidates.Count > 0) ? candidates.OrderByDescending(x => x.Value).First().Key : word;
            }
 public object StartMethod(object parent = null, Dictionary<string, object> parameters = null)
 {
     if (!parameters.ContainsKey("Tag")) throw new ArgumentNullException("Tag");
     if (!parameters.ContainsKey("ClassName")) throw new ArgumentNullException("ClassName");
     List<string> resultListUrl = new List<string>();
     mshtml.IHTMLDocument2 doc2 = parent as mshtml.IHTMLDocument2;
     Common.WaitForPageReady(doc2);
     string url = doc2.url;
     for (int i = 0; i < 1; i++)
     {
         mshtml.IHTMLDocument2 document2 = parent as mshtml.IHTMLDocument2;
         mshtml.IHTMLDocument3 document3 = parent as mshtml.IHTMLDocument3;
         Common.WaitForPageReady(document2);
         document2.url = string.Format("{0}{1}{2}", url, "&startindex=", i * 20);
         if (document3 != null)
         {
             mshtml.IHTMLElementCollection elements = document3.getElementsByTagName(parameters["Tag"] as string);
             foreach (mshtml.IHTMLElement element in elements)
             {
                 if (element.className == parameters["ClassName"] as string)
                 {
                     mshtml.IHTMLElementCollection elementChildren = element.children as mshtml.IHTMLElementCollection;
                     foreach (mshtml.IHTMLElement firstChild in elementChildren)
                     {
                         resultListUrl.Add(firstChild.getAttribute("href") as string);
                         break;
                     }
                 }
             }
         }
     }
     return resultListUrl;
 }
        private string MinWindow(string s, string t)
        {
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return "";

            int tLen = t.Length, sLen = s.Length, start = -1, end = -1;
            var dicNoCounted = new Dictionary<char, int>();

            for (int index = 0; index < tLen; index++)
                if (!dicNoCounted.ContainsKey(t[index]))
                    dicNoCounted.Add(t[index], 1);
                else
                    dicNoCounted[t[index]]++;

            for (int index = 0; index < sLen && dicNoCounted.Count > 0; index++)
            {
                if (dicNoCounted.ContainsKey(s[index]))
                {
                    if (dicNoCounted[s[index]] > 1)
                        dicNoCounted[s[index]]--;
                    else
                        dicNoCounted.Remove(s[index]);

                    if (start < 0)
                        end = start = index;
                    else
                        end = index;
                }
            }

            if (dicNoCounted.Count > 0 || start < 0 || end < 0) return "";
            return s.Substring(start, end - start + 1);
        }
Example #20
0
        public void CreateModels(IEnumerable<OvhApi> apis)
        {
            Dictionary<string,ModelType> modelsByNamespace = new Dictionary<string, ModelType>();
            foreach (var ovhApi in apis)
            {
                foreach (var model in ovhApi.Models)
                {
                    string fullTypeName = Util.GetType(model.Key);

                    if (modelsByNamespace.ContainsKey(fullTypeName))
                        continue;

                    modelsByNamespace.Add(fullTypeName, new ModelType(model.Value));
                }
            }

            foreach (var st in modelsByNamespace)
            {
                string modelNamespace = Util.GetNamespace(st.Value.Model);

                if (modelsByNamespace.ContainsKey(modelNamespace))
                {
                    modelsByNamespace[modelNamespace].AddChild(st.Value);
                }
            }

            foreach (var type in modelsByNamespace.Where(x => x.Value.Parent == null))
            {
                CodeNamespace ns = new CodeNamespace(Util.GetNamespace(type.Value.Model));
                ns.Types.Add(CreateType(type.Value));
                _code.Namespaces.Add(ns);
            }
        }
Example #21
0
        public Portal(World world, int actorSNO, Vector3D position, Dictionary<int, TagMapEntry> tags)
            : base(world, world.NewActorID, position, tags)
        {
            this.SNOId = actorSNO;
            this.Destination = new ResolvedPortalDestination
            {
                WorldSNO = tags[(int)MarkerTagTypes.DestinationWorld].Int2,
            };

            if (tags.ContainsKey((int)MarkerTagTypes.DestinationLevelArea))
                this.Destination.DestLevelAreaSNO = tags[(int)MarkerTagTypes.DestinationLevelArea].Int2;

            if (tags.ContainsKey((int)MarkerTagTypes.DestinationActorTag))
                this.Destination.StartingPointActorTag = tags[(int)MarkerTagTypes.DestinationActorTag].Int2;
            else
                Logger.Warn("Found portal {0}without target location actor", this.SNOId);

            this.Field8 = this.SNOId;
            this.Field2 = 16;
            this.Field3 = 0;
            this.CollFlags = 0x00000001;

            // FIXME: Hardcoded crap; probably don't need to set most of these. /komiga
            this.Attributes[GameAttribute.MinimapActive] = true;
            this.Attributes[GameAttribute.Hitpoints_Max_Total] = 1f;
            this.Attributes[GameAttribute.Hitpoints_Max] = 0.0009994507f;
            this.Attributes[GameAttribute.Hitpoints_Total_From_Level] = 3.051758E-05f;
            this.Attributes[GameAttribute.Hitpoints_Cur] = 0.0009994507f;
            this.Attributes[GameAttribute.TeamID] = 1;
            this.Attributes[GameAttribute.Level] = 1;
        }
        private IList<Vocabulary> CalcUserVocabulary(IList<string> newWords, IDictionary<int, int> histories)
        {
            var result = new Dictionary<string, Vocabulary>();

            //var histories = dbOperator.GetAll<User_LearnHistory>();
            foreach (var history in histories)
            {
                //读取已经背诵的单元
                var items = dbOperator.GetBookItemsBelowMaxUnitId(history.Key, history.Value);
                foreach (var item in items)
                {
                    if (!result.ContainsKey(item.Word))
                        result.Add(item.Word, new Vocabulary() { Word = item.Word, IsKnown = true });
                }
            }
            foreach (var newword in newWords)
            {
                if (result.ContainsKey(newword))
                {
                    result[newword].IsKnown = false;
                }
                else
                {
                    result.Add(newword, new Vocabulary() { Word = newword, IsKnown = false });
                }
            }
            return new List<Vocabulary>(result.Values);
        }
        public IDictionary<Person, ExchangeCheckSum> PickListToValidateWithPeopleList(PersonCollection personList, XMasPickList pickList)
        {
            IDictionary<Person, ExchangeCheckSum> checkList = new Dictionary<Person, ExchangeCheckSum>();

            foreach (Person person in personList)
            {
                checkList.Add(person, new ExchangeCheckSum());
            }

            foreach (XMasPick pick in pickList)
            {
                if (checkList.ContainsKey(pick.Recipient))
                {
                    checkList[pick.Recipient].updatePresentsIn();
                }
                else
                {
                    throw new Exception(string.Format("The recipient {0} is not found in adult list", pick.Recipient));
                }

                if (checkList.ContainsKey(pick.Subject))
                {
                    checkList[pick.Subject].updatePresentsOut();
                }
                else
                {
                    throw new Exception(string.Format("The subject {0} is not found in adult list", pick.Subject));
                }
            }

            return checkList;
        }
Example #24
0
        public void TestMap()
        {
            foreach (var file in Directory.GetFiles(FilesDirectory))
            {
                DexReader dexreader;
                DexWriter dexwriter;
                TestReadWrite(file, out dexreader, out dexwriter);

                var checklist = new Dictionary<TypeCodes, string>();

                foreach (var tc in dexwriter.Map.Keys.Where(tc => dexreader.Map.ContainsKey(tc)))
                {
                    if (dexreader.Map[tc].Size != dexwriter.Map[tc].Size)
                    {
                        TestContext.WriteLine("{0} Size differs expected={1}, actual={2}", tc, dexreader.Map[tc].Size, dexwriter.Map[tc].Size);
                        if (!checklist.ContainsKey(tc))
                            checklist.Add(tc, tc.ToString());
                    }
                    if (dexreader.Map[tc].Offset != dexwriter.Map[tc].Offset)
                    {
                        TestContext.WriteLine("{0} Offset differs : expected={1}, actual={2}", tc, dexreader.Map[tc].Offset, dexwriter.Map[tc].Offset);
                        if (!checklist.ContainsKey(tc))
                            checklist.Add(tc, tc.ToString());
                    }
                }

                Assert.IsTrue(checklist.Count == 0, string.Concat("Check test report : ", string.Join(", ", checklist.Values)));
            }
        }
Example #25
0
        public static Person Import(String input)
        {
            var parameters = new Dictionary<string, string>();
            var data = input.Split(';');
            foreach (string item in data)
            {
                var specyficData = item.Split(':');
                parameters[specyficData[0]] = specyficData[1];
            }

            var person = new Person();
            person.NameSurname = parameters["NS"];

            IFormatProvider culture = new System.Globalization.CultureInfo("pl-PL", true);
            if (parameters.ContainsKey("BD"))
            {
                person.Birthdate = DateTime.Parse(parameters["BD"], culture);
            }

            if (parameters.ContainsKey("DD"))
            {
                person.Deathdate = DateTime.Parse(parameters["DD"], culture);
            }

            if (parameters.ContainsKey("S"))
            {
                switch (parameters["S"])
                {
                    case "M": person.Sex = PersonSex.Male; break;
                    case "F": person.Sex = PersonSex.Female; break;
                }
            }

            return person;
        }
Example #26
0
        public Diff GetDiff(Dictionary<string, PriceItem> newProds, Dictionary<string, PriceItem> oldProds)
        {
            oldProds = oldProds ?? new Dictionary<string, PriceItem>();

            var diff = new Diff 
            { 
                NewItems = newProds.Where(kvp => !oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                DeletedItems = oldProds.Where(kvp => !newProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                UpdatedItems = newProds.Where(kvp => oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value)
            };

            var toRemove = new List<string>();
            foreach (var item in diff.UpdatedItems.Values)
            {
                var oldItem = oldProds[item.Reference];
                if (item.WholesalePrice == oldItem.WholesalePrice && item.Active == oldItem.Active && !SameBalance(item, oldItem))
                {
                    toRemove.Add(item.Reference);
                }
            }

            foreach (var reference in toRemove)
            {
                diff.UpdatedItems.Remove(reference);
            }

            return diff;
        }
Example #27
0
        public static void CsvLoadTripRoutes(string filename, bool lngFirst)
        {
            // load trip routes
            Dictionary<string, LinkedList<Waypoint>> routes = new Dictionary<string, LinkedList<Waypoint>>();
            using (CsvFileReader reader = new CsvFileReader(filename))
            {
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row, ','))
                {
                    string routeID = row[0];
                    double distance = 0;
                    double lat = Convert.ToDouble(lngFirst ? row[2] : row[1]);
                    double lng = Convert.ToDouble(lngFirst ? row[1] : row[2]);
                    if (routes.ContainsKey(routeID))
                        distance = routes[routeID].First.Value.GetDistance(new Location(lat, lng, "null"));
                    Waypoint waypoint = new Waypoint(lat, lng, TimeSpan.Parse(row[3]), distance, row[4].Replace("\"", ""));

                    // Scenario #1
                    if (!routes.ContainsKey(routeID))
                        routes[routeID] = new LinkedList<Waypoint>();
                    routes[routeID].AddLast(waypoint);

                }
            }
            foreach (LinkedList<Waypoint> w in routes.Values)
            {
                Route r = new Route(w.ToArray());
                string key = Route.GetKey(r.start, r.end);
                MapTools.routes.Add(key, r);
            }
        }
Example #28
0
 public void ConvertFromDic(ref Dictionary<string, string> dic)
 {
     if (dic.ContainsKey("MinBpm"))
         double.TryParse(dic["MinBpm"], out _minBpm);
     if (dic.ContainsKey("MaxBpm"))
         double.TryParse(dic["MaxBpm"], out _maxBpm);
 }
Example #29
0
        public AmzCD(string url, Dictionary<string, string> options)
        {
            var uri = new Utility.Uri(url);

            m_path = uri.HostAndPath;
            if (!m_path.EndsWith("/"))
                m_path += "/";

            string authid = null;
            if (options.ContainsKey(AUTHID_OPTION))
                authid = options[AUTHID_OPTION];

            string labels = DEFAULT_LABELS;
            if (options.ContainsKey(LABELS_OPTION))
                labels = options[LABELS_OPTION];

            string delay = DEFAULT_DELAY;
            if (options.ContainsKey(DELAY_OPTION))
                delay = options[DELAY_OPTION];
            
            if (!string.IsNullOrWhiteSpace(labels))
                m_labels = labels.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            if (string.IsNullOrWhiteSpace(delay))
                m_delayTimeSpan = new TimeSpan(0);
            else
                m_delayTimeSpan = Library.Utility.Timeparser.ParseTimeSpan(delay);

            m_oauth = new OAuthHelper(authid, this.ProtocolKey) { AutoAuthHeader = true };
            m_userid = authid.Split(new string[] {":"}, StringSplitOptions.RemoveEmptyEntries).First();
        }
Example #30
0
 public override void FillFromDictionary(Dictionary<string, object> dict)
 {
     if(dict.ContainsKey("path")) {
         if(dict["path"] != null) {
             path = DataType.Instance.FillString(dict["path"]);
         }
     }
     if(dict.ContainsKey("date_end")) {
         if(dict["date_end"] != null) {
             date_end = DataType.Instance.FillDateTime(dict["date_end"]);
         }
     }
     if(dict.ContainsKey("date_start")) {
         if(dict["date_start"] != null) {
             date_start = DataType.Instance.FillDateTime(dict["date_start"]);
         }
     }
     if(dict.ContainsKey("data")) {
         if(dict["data"] != null) {
             data = DataType.Instance.FillString(dict["data"]);
         }
     }
     if(dict.ContainsKey("type_id")) {
         if(dict["type_id"] != null) {
             type_id = DataType.Instance.FillString(dict["type_id"]);
         }
     }
 }