Example #1
0
        public ToolAction(CodeGenerator codeGenerator, CodeGeneratorEntry entry, Dictionary<string, string> props)
        {
            this.CodeGenerator = codeGenerator;
            _props = props;
            this.Entry = entry;

            this.Comment = _props.GetOrDefault("comment");
            this.FileName = _props.GetOrDefault("file-name");
        }
        public void ShouldBeAbleToGetADefaultValueIfTheKeyDoesntExist()
        {
            DateTime theDate = DateTime.Parse("April 04, 2005");
            DateTime defaultDate = DateTime.Parse("October 31, 2005");

            var bag = new Dictionary<string, object>();
            Assert.That(bag.GetOrDefault("some_date", defaultDate), Is.EqualTo(defaultDate));

            bag.Add("some_date", theDate);
            Assert.That(bag.GetOrDefault("some_date", defaultDate), Is.EqualTo(theDate));
        }
        public void GetOrDefaultPresent()
        {
            Dictionary<string, int> dict = new Dictionary<string, int>() { { "one", 1 } };

            int value = dict.GetOrDefault("one", -999);

            Assert.Equal(1, 1);
        }
        public void GetOrDefaultMissing()
        {
            Dictionary<string, int> dict = new Dictionary<string, int>();
            int @default = 15;

            int value = dict.GetOrDefault("two", @default);

            Assert.Equal(15, @default);
        }
 private static Func<Question, RichQuestion> QuestionCreateor(Dictionary<int, int> votes,
                                                              Dictionary<int, int> answerCounts)
 {
     return q => new RichQuestion(q,
                                  votes.GetOrDefault(q.Id),
                                  null,
                                  null,
                                  answerCounts.GetOrDefault(q.Id));
 }
        public void Value_Not_Exists()
        {
            var key = "key";

            Dictionary<string, object> target = new Dictionary<string, object>();
            var actual = target.GetOrDefault(key);

            Assert.IsNull(actual);
        }
Example #7
0
		PositionedNode MatchNode(PositionedNode oldNode, Dictionary<int, PositionedNode> newNodeMap)
		{
			PositionedNode newNodeFound = newNodeMap.GetOrDefault(oldNode.ObjectNode.HashCode);
			if ((newNodeFound != null) && IsSameAddress(oldNode, newNodeFound))	{
				return newNodeFound;
			} else {
				return null;
			}
		}
        public void Value_Is_Null()
        {
            var key = "key";

            Dictionary<string, object> target = new Dictionary<string, object>();
            target.Add(key, null);
            var actual = target.GetOrDefault(key);

            Assert.IsNull(actual);
        }
        public void Value_Exists()
        {
            var key = "key";
            var expected = "hello world!";

            Dictionary<string, object> target = new Dictionary<string, object>();
            target.Add(key, expected);
            var actual = target.GetOrDefault(key);

            Assert.AreEqual(expected, actual);
        }
Example #10
0
    /* 3 Write a program that finds a set of words (e.g. 1000 words)
     * in a large text (e.g. 100 MB text file). Print how many times
     * each word occurs in the text.
     * Hint: you may find a C# trie in Internet.
     * */
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, int>();
        var knownCount = new Dictionary<string, int>
        {
            {"foo", 10*1000},
            {"bar", 20*1000},
            {"quux",30*1000},
            {"frob",40*1000},
            {"asdf",50*1000}
        };
        var trie = new Trie<int>();

        var sw = new Stopwatch();

        sw.Start();

        // obviously, I couldn't zip the 100 MB file
        // use "bin\debug\generator.cs" to generate it if you want

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                dict[word] = 1 + dict.GetOrDefault(word, 0);

        sw.Stop();
        /*
        foreach (var kvp in knownCount)
            Debug.Assert(dict[kvp.Key] == kvp.Value);
        */

        Console.WriteLine("Using hashtable: " + sw.Elapsed.TotalMilliseconds);

        sw.Reset();
        sw.Start();

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                trie.Add(word, 1 + trie.GetOrDefault(word, 0));

        sw.Stop();

        foreach (var kvp in dict)
            Debug.Assert(trie.Find(kvp.Key) == kvp.Value);

        // the trie would probably do much better compared to a hashtable when used on
        // natural text with large amount of repetition and low average word length
        // it is however extremely space inefficient

        // at any rate, I'd be surprised if this implementation could beat .NET's build-in
        // hashtable

        Console.WriteLine("Using trie: " + sw.Elapsed.TotalMilliseconds);
    }
		public void DeleteMappedResultsForDocumentId(string documentId, string view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
			foreach (var key in storage.MappedResults["ByViewAndDocumentId"].SkipTo(new RavenJObject
			{
				{"view", view},
				{"docId", documentId}
			}).TakeWhile(x => StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("view"), view) &&
							  StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("docId"), documentId)))
			{
				storage.MappedResults.Remove(key);

				var reduceKey = key.Value<string>("reduceKey");
				var bucket = new ReduceKeyAndBucket(key.Value<int>("bucket"), reduceKey);
				removed[bucket] = removed.GetOrDefault(bucket) + 1;
			}
		}
Example #12
0
        public static string Build(IEnumerable<AssemblyDefinition> assemblys, string outDirectory, string bridgeDllPath, string libWhite, string libBlack) {
            TypeDefinitionBuilder builder = new TypeDefinitionBuilder(libWhite, libBlack);
            List<CodeCompileUnit> units = new List<CodeCompileUnit>();

            foreach(var assemblyDefinition in assemblys) {
                CodeCompileUnit unit = new CodeCompileUnit();
                Dictionary<string, CodeNamespace> namespaces = new Dictionary<string, CodeNamespace>();
                foreach(var module in assemblyDefinition.Modules) {
                    foreach(var type in module.Types) {
                        if(builder.IsEnableType(type)) {
                            CodeTypeDeclaration codeTypeDeclaration = builder.Build(type);
                            CodeNamespace codeNamespace = namespaces.GetOrDefault(type.Namespace);
                            if(codeNamespace == null) {
                                codeNamespace = new CodeNamespace(type.Namespace);
                                namespaces.Add(codeNamespace.Name, codeNamespace);
                            }
                            codeNamespace.Types.Add(codeTypeDeclaration);
                        }
                    }
                }

                unit.Namespaces.AddRange(namespaces.Values.ToArray());
                units.Add(unit);
            }

            CompilerParameters cp = new CompilerParameters();
            cp.CoreAssemblyFileName = bridgeDllPath;
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;
            cp.TempFiles.KeepFiles = true;
            cp.OutputAssembly = Path.Combine(outDirectory, kWrapDllName);
            cp.ReferencedAssemblies.Add(bridgeDllPath);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, units.Select(i => i.Compile()).ToArray());
            if(cr.Errors.Count > 0) {
                StringBuilder sb = new StringBuilder();
                foreach(CompilerError ce in cr.Errors) {
                    sb.AppendFormat(" {0}", ce.ToString());
                    sb.AppendLine();
                }
                throw new System.Exception(sb.ToString());
            }

            return cr.PathToAssembly;
        }
Example #13
0
        public Core.Entity Generate(Core.EntitySet set, Resources.ResourceCache cache, string entityName, Dictionary<string, object> parameters)
        {
            var e = set.Create(entityName);

            var sprite = e.AddComponent<Sprite>();
            if (r == null)
                r = new Random((int)(DateTime.Now.Ticks % (long)int.MaxValue));
            var path = "Data/Texture/house" + r.Next(500) % (MaxIndex + 1) + ".png";
            sprite.Load(cache, path);
            sprite.Origin = new SharpDX.Vector2(160f / 2f);

            var rot = parameters.GetOrDefault("Rotation", 0f);
            e.Transform.LocalRotation = rot;

            var area = e.AddComponent<ClickArea>();
            area.BaseWidth = 160;
            area.BaseHeight = 160;
            area.OriginX = sprite.Origin.X;
            area.OriginY = sprite.Origin.Y;

            return e;
        }
Example #14
0
		public void DeleteMappedResultsForDocumentId(string documentId, string view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
			Api.JetSetCurrentIndex(session, MappedResults, "by_view_and_doc_key");
			Api.MakeKey(session, MappedResults, view, Encoding.Unicode, MakeKeyGrbit.NewKey);
			Api.MakeKey(session, MappedResults, documentId, Encoding.Unicode, MakeKeyGrbit.None);
			if (Api.TrySeek(session, MappedResults, SeekGrbit.SeekEQ) == false)
				return;

			Api.MakeKey(session, MappedResults, view, Encoding.Unicode, MakeKeyGrbit.NewKey);
			Api.MakeKey(session, MappedResults, documentId, Encoding.Unicode, MakeKeyGrbit.None);
			Api.JetSetIndexRange(session, MappedResults, SetIndexRangeGrbit.RangeUpperLimit | SetIndexRangeGrbit.RangeInclusive);
			do
			{
				// esent index ranges are approximate, and we need to check them ourselves as well
				var viewFromDb = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["view"]);
				if (StringComparer.OrdinalIgnoreCase.Equals(viewFromDb, view) == false)
					continue;
				var documentIdFromDb = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["document_key"]);
				if (StringComparer.OrdinalIgnoreCase.Equals(documentIdFromDb, documentId) == false)
					continue;
				var reduceKey = Api.RetrieveColumnAsString(session, MappedResults, tableColumnsCache.MappedResultsColumns["reduce_key"],
														   Encoding.Unicode);
				var bucket = Api.RetrieveColumnAsInt32(session, MappedResults, tableColumnsCache.MappedResultsColumns["bucket"]).Value;

				var key = new ReduceKeyAndBucket(bucket, reduceKey);
				removed[key] = removed.GetOrDefault(key) + 1;
				Api.JetDelete(session, MappedResults);
			} while (Api.TryMoveNext(session, MappedResults));
		}
		public void DeleteMappedResultsForDocumentId(string documentId, int view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
            var viewKey = CreateKey(view);
            var viewKeySlice = new Slice(viewKey);
			var viewAndDocumentId = new Slice(AppendToKey(viewKey, documentId));

            var mappedResultsByViewAndDocumentId = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndDocumentId);
            var mappedResultsByView = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByView);
            var mappedResultsByViewAndReduceKey = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndReduceKey);
            var mappedResultsByViewAndReduceKeyAndSourceBucket = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndReduceKeyAndSourceBucket);
            var mappedResultsData = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.Data);

			using (var iterator = mappedResultsByViewAndDocumentId.MultiRead(Snapshot, viewAndDocumentId))
			{
				if (!iterator.Seek(Slice.BeforeAllKeys))
					return;

				do
				{
					// TODO: Check if we can relax the clone.
                    var id = iterator.CurrentKey.Clone();

					ushort version;
					var value = LoadStruct(tableStorage.MappedResults, id, writeBatch.Value, out version);
					var reduceKey = value.ReadString(MappedResultFields.ReduceKey);
					var bucket = value.ReadInt(MappedResultFields.Bucket);

                    var reduceKeyHash = HashKey(reduceKey);                  
                    var viewAndReduceKey = AppendToKey(viewKey, ReduceKeySizeLimited(reduceKey), reduceKeyHash);
                    var viewAndReduceKeyAndSourceBucket = AppendToKey(viewAndReduceKey, bucket);

                    tableStorage.MappedResults.Delete(writeBatch.Value, id);

                    mappedResultsByViewAndDocumentId.MultiDelete(writeBatch.Value, viewAndDocumentId, id);
                    mappedResultsByView.MultiDelete(writeBatch.Value, viewKeySlice, id);
                    mappedResultsByViewAndReduceKey.MultiDelete(writeBatch.Value, (Slice)viewAndReduceKey, id);
                    mappedResultsByViewAndReduceKeyAndSourceBucket.MultiDelete(writeBatch.Value, (Slice)viewAndReduceKeyAndSourceBucket, id);
                    mappedResultsData.Delete(writeBatch.Value, id);

					var reduceKeyAndBucket = new ReduceKeyAndBucket(bucket, reduceKey);
					removed[reduceKeyAndBucket] = removed.GetOrDefault(reduceKeyAndBucket) + 1;
				}
				while (iterator.MoveNext());
			}
		}
Example #16
0
			private void UpdateFacetResults(Dictionary<string, Dictionary<string, FacetValue>> facetsByName)
			{
				foreach (var facet in Facets.Values)
				{
					if (facet.Mode == FacetMode.Ranges)
						continue;

					var values = new List<FacetValue>();
					List<string> allTerms;

					int maxResults = Math.Min(PageSize ?? facet.MaxResults ?? Database.Configuration.MaxPageSize, Database.Configuration.MaxPageSize);
					var groups = facetsByName.GetOrDefault(facet.DisplayName);

					if (groups == null)
						continue;

					switch (facet.TermSortMode)
					{
						case FacetTermSortMode.ValueAsc:
							allTerms = new List<string>(groups.OrderBy(x => x.Key).ThenBy(x => x.Value.Hits).Select(x => x.Key));
							break;
						case FacetTermSortMode.ValueDesc:
							allTerms = new List<string>(groups.OrderByDescending(x => x.Key).ThenBy(x => x.Value.Hits).Select(x => x.Key));
							break;
						case FacetTermSortMode.HitsAsc:
							allTerms = new List<string>(groups.OrderBy(x => x.Value.Hits).ThenBy(x => x.Key).Select(x => x.Key));
							break;
						case FacetTermSortMode.HitsDesc:
							allTerms = new List<string>(groups.OrderByDescending(x => x.Value.Hits).ThenBy(x => x.Key).Select(x => x.Key));
							break;
						default:
							throw new ArgumentException(string.Format("Could not understand '{0}'", facet.TermSortMode));
					}

					foreach (var term in allTerms.Skip(Start).TakeWhile(term => values.Count < maxResults))
					{
						var facetValue = groups.GetOrDefault(term);
						values.Add(facetValue ?? new FacetValue { Range = term });
					}

					var previousHits = allTerms.Take(Start).Sum(allTerm =>
					{
						var facetValue = groups.GetOrDefault(allTerm);
						return facetValue == null ? 0 : facetValue.Hits;
					});

					var key = string.IsNullOrWhiteSpace(facet.DisplayName) ? facet.Name : facet.DisplayName;

					Results.Results[key] = new FacetResult
					{
						Values = values,
						RemainingTermsCount = allTerms.Count - (Start + values.Count),
						RemainingHits = groups.Values.Sum(x => x.Hits) - (previousHits + values.Sum(x => x.Hits)),
					};

					if (facet.IncludeRemainingTerms)
						Results.Results[key].RemainingTerms = allTerms.Skip(Start + values.Count).ToList();
				}
			}
		public void UpdateRemovedMapReduceStats(string view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
			var statsByKey = new Dictionary<string, int>();
			foreach (var reduceKeyAndBucket in removed)
			{
				statsByKey[reduceKeyAndBucket.Key.ReduceKey] = statsByKey.GetOrDefault(reduceKeyAndBucket.Key.ReduceKey) - reduceKeyAndBucket.Value;
			}

			foreach (var reduceKeyStat in statsByKey)
			{
				IncrementReduceKeyCounter(view, reduceKeyStat.Key, reduceKeyStat.Value);
			}
		}
        /// <inheritdoc/>
        public async Task<IReadOnlyList<ISettingValue>> GetAllSettingValuesAsync(SettingScopes scopes)
        {
            var settingDefinitions = new Dictionary<string, SettingDefinition>();
            var settingValues = new Dictionary<string, ISettingValue>();

            //Fill all setting with default values.
            foreach (var setting in _settingDefinitionManager.GetAllSettingDefinitions())
            {
                settingDefinitions[setting.Name] = setting;
                settingValues[setting.Name] = new SettingValueObject(setting.Name, setting.DefaultValue);
            }

            //Overwrite application settings
            if (scopes.HasFlag(SettingScopes.Application))
            {
                foreach (var settingValue in await GetAllSettingValuesForApplicationAsync())
                {
                    var setting = settingDefinitions.GetOrDefault(settingValue.Name);

                    //TODO: Conditions get complicated, try to simplify it
                    if (setting == null || !setting.Scopes.HasFlag(SettingScopes.Application))
                    {
                        continue;
                    }

                    if (!setting.IsInherited &&
                        (setting.Scopes.HasFlag(SettingScopes.User) && AbpSession.UserId.HasValue))
                    {
                        continue;
                    }

                    settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                }
            }

       

            //Overwrite user settings
            if (scopes.HasFlag(SettingScopes.User) && AbpSession.UserId.HasValue)
            {
                foreach (var settingValue in await GetAllSettingValuesForUserAsync(AbpSession.UserId.Value))
                {
                    var setting = settingDefinitions.GetOrDefault(settingValue.Name);
                    if (setting != null && setting.Scopes.HasFlag(SettingScopes.User))
                    {
                        settingValues[settingValue.Name] = new SettingValueObject(settingValue.Name, settingValue.Value);
                    }
                }
            }

            return settingValues.Values.ToImmutableList();
        }
		public void DeleteMappedResultsForView(string view)
		{
			var statsByKey = new Dictionary<string, int>();
			foreach (var key in storage.MappedResults["ByViewAndReduceKey"].SkipTo(new RavenJObject { { "view", view } })
			.TakeWhile(x => StringComparer.OrdinalIgnoreCase.Equals(x.Value<string>("view"), view)))
			{
				storage.MappedResults.Remove(key);

				var reduceKey = key.Value<string>("reduceKey");
				statsByKey[reduceKey] = statsByKey.GetOrDefault(reduceKey) - 1;
			}
			foreach (var reduceKeyStat in statsByKey)
			{
				IncrementReduceKeyCounter(view, reduceKeyStat.Key, reduceKeyStat.Value);
			}
		}
Example #20
0
        public static ControlFlowGraph DoCreateCarcass(IMethodBody cil, out ReadOnlyDictionary<ControlFlowBlock, ReadOnlyCollection<IILOp>> blocks2parts)
        {
            // create the control flow graph
            var cfg = new ControlFlowGraph();

            // partition the code into blocks with continuous control flow
            // todo. support switches and protected regions
            var targets = new HashSet<IILOp>(cil.OfType<Branch>().Select(br => br.Target));
            var l_partitions = new List<ReadOnlyCollection<IILOp>>();
            var l_partition = new List<IILOp>();
            Action qualifyPartition = () => { if (l_partition.IsNotEmpty()) { l_partitions.Add(l_partition.ToReadOnly()); l_partition = new List<IILOp>(); } };
            foreach (var op in cil)
            {
                if (op is Branch || op is Ret) qualifyPartition();
                else 
                {
                    if (targets.Contains(op)) qualifyPartition();
                    l_partition.Add(op);
                    if (op is Throw) qualifyPartition();
                }
            }
            qualifyPartition();
            var partitions = l_partitions.ToReadOnly();

            // create blocks and map those to ops and partitions
            blocks2parts = partitions.ToDictionary(p => new ControlFlowBlock(), p => p).ToReadOnly();
            blocks2parts.ForEach(kvp => cfg.AddVertex(kvp.Key));
            var op2blocks = new Dictionary<IILOp, ControlFlowBlock>();
            blocks2parts.ForEach(kvp => kvp.Value.ForEach(op => op2blocks.Add(op, kvp.Key)));
            cil.ForEach(op => { if (!op2blocks.ContainsKey(op)) op2blocks.Add(op, null); });

            // prepare to link the blocks
            Action<IILOp, IILOp, CilPredicateType?> link = (op1, op2, cil_pred) =>
            {
                var source = op1 == null ? cfg.Start : op2blocks[op1];
                var target = op2 == null ? cfg.Finish : op2blocks[op2];
                var hir_pred = cil_pred == null ? (HirPredicateType?)null :
                    (HirPredicateType)Enum.Parse(typeof(HirPredicateType), cil_pred.Value.ToString());
                cfg.AddEdge(new ControlFlowEdge(source, target, hir_pred));
            };

            // link the blocks (down from 300+ LOC to this simple loop =))
            if (cil.IsEmpty()) link(null, null, null);
            foreach (var op in cil)
            {
                // todo. support switches here
                if (op is Switch) throw AssertionHelper.Fail();

                // todo. support general case of control flow
                // n0te. throw needs something on stack, so br > throw is impossible
                Func<IILOp, bool> isJmp = op1 => op1 is Ret || op1 is Branch;
                if (isJmp(op) && isJmp(op.Prev)) continue;

                if (isJmp(op))
                {
                    Func<IILOp, CilPredicateType?> pred = op1 => op1 is Ret ? null : op1 is Branch ? ((Branch)op1).PredicateType : ((Func<CilPredicateType?>)(() => { throw AssertionHelper.Fail(); }))();
                    Func<IILOp, bool> uncond = op1 => isJmp(op1) && pred(op1) == null;
                    Func<IILOp, bool> cond = op1 => isJmp(op1) && pred(op1) != null;
                    Func<IILOp, IILOp> target = null; target = op1 => 
                        op1 is Ret ? null : op1 is Branch ? target(((Branch)op1).Target) : op1;

                    (target(op) is Branch).AssertFalse();
                    if (target(op) is Ret) link(op.Prev, null, pred(op));
                    else link(op.Prev, target(op), pred(op));

                    isJmp(op.Next).AssertImplies(uncond(op.Next));
                    if (cond(op)) link(op.Prev, target(op.Next), pred(op).Negate());
                }
                else if (op is Throw)
                {
                    // do nothing - throw doesn't create links
                }
                else
                {
                    if (op.Prev == null) link(null, op, null);
                    if (isJmp(op.Next)) continue;

                    var blk = op2blocks.GetOrDefault(op);
                    var blk_next = op2blocks.GetOrDefault(op.Next);
                    if (blk != blk_next) link(op, op.Next, null);
                }
            }

            // yield control to the next step of the pipeline
            return cfg;
        }
Example #21
0
 private static Dictionary<char, int> getCharactersCount(string s)
 {
     Dictionary<char, int> res = new Dictionary<char, int>();
     foreach (char c in s) {
         res[c] = res.GetOrDefault(c, 0) + 1;
     }
     return res;
 }
Example #22
0
        private void ProcessTCPPacket(TcpPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, PacketStream pStream, bool pInbound)
        {
            if (pTCPPacket.SequenceNumber > pSequence)
            {
                byte[] data;
                while ((data = pBuffer.GetOrDefault(pSequence, null)) != null)
                {
                    pBuffer.Remove(pSequence);
                    pStream.Append(data);
                    pSequence += (uint)data.Length;
                }
                if (pTCPPacket.SequenceNumber > pSequence)
                {
                    pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.PayloadData;
                }
            }
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                if (difference > 0)
                {
                    byte[] data = pTCPPacket.PayloadData;
                    if (data.Length > difference)
                    {
                        pStream.Append(data, difference, data.Length - difference);
                        pSequence += (uint)(data.Length - difference);
                    }
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.PayloadData;
                pStream.Append(data);
                pSequence += (uint)data.Length;
            }

            CheckForPackets(pStream, pInbound);

        }
Example #23
0
        private void ProcessTCPPacket(TcpPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, MapleStream pStream, DateTime pArrivalDate)
        {
            if (pTCPPacket.SequenceNumber > pSequence)
            {
                byte[] data;
                while ((data = pBuffer.GetOrDefault(pSequence, null)) != null)
                {
                    pBuffer.Remove(pSequence);
                    pStream.Append(data);
                    pSequence += (uint)data.Length;
                }
                if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.PayloadData;
            }
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                if (difference > 0)
                {
                    byte[] data = pTCPPacket.PayloadData;
                    if (data.Length > difference)
                    {
                        pStream.Append(data, difference, data.Length - difference);
                        pSequence += (uint)(data.Length - difference);
                    }
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.PayloadData;
                pStream.Append(data);
                pSequence += (uint)data.Length;
            }

            MaplePacket packet;
            bool refreshOpcodes = false;
            try
            {
                while ((packet = pStream.Read(pArrivalDate, mBuild, mLocale)) != null)
                {
                    mPackets.Add(packet);
                    Definition definition = Config.Instance.GetDefinition(mBuild, mLocale, packet.Outbound, packet.Opcode);
                    if (!mOpcodes.Exists(kv => kv.First == packet.Outbound && kv.Second == packet.Opcode))
                    {
                        mOpcodes.Add(new Pair<bool, ushort>(packet.Outbound, packet.Opcode));
                        refreshOpcodes = true;
                    }
                    if (definition != null && !mViewIgnoredMenu.Checked && definition.Ignore) continue;
                    mPacketList.Items.Add(packet);
                    if (mPacketList.SelectedItems.Count == 0) packet.EnsureVisible();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                mTerminated = true;
                Text += " (Terminated)";
                //MainForm.CloseSession(this);
                return;
            }

            if (DockPanel.ActiveDocument == this && refreshOpcodes) MainForm.SearchForm.RefreshOpcodes(true);
        }
		public void DeleteMappedResultsForDocumentId(string documentId, int view, Dictionary<ReduceKeyAndBucket, int> removed)
		{
			var viewAndDocumentId = CreateKey(view, documentId);

			var mappedResultsByViewAndDocumentId = tableStorage.MappedResults.GetIndex(Tables.MappedResults.Indices.ByViewAndDocumentId);
			using (var iterator = mappedResultsByViewAndDocumentId.MultiRead(Snapshot, viewAndDocumentId))
			{
				if (!iterator.Seek(Slice.BeforeAllKeys))
					return;

				do
				{
					var id = iterator.CurrentKey.Clone();

					ushort version;
					var value = LoadJson(tableStorage.MappedResults, id, writeBatch.Value, out version);
					var reduceKey = value.Value<string>("reduceKey");
					var bucket = value.Value<int>("bucket");

					DeleteMappedResult(id, view, documentId, reduceKey, bucket.ToString(CultureInfo.InvariantCulture));

					var reduceKeyAndBucket = new ReduceKeyAndBucket(bucket, reduceKey);
					removed[reduceKeyAndBucket] = removed.GetOrDefault(reduceKeyAndBucket) + 1;
				}
				while (iterator.MoveNext());
			}
		}
Example #25
0
        /// <summary>
        /// 建立 SubCategoryUser 個體。
        /// </summary>
        /// <param name="catSub">CatSub 個體</param>
        /// <param name="userMap">User 快查表。</param>
        /// <returns>子站維護人員資訊</returns>
        private CategoryContactModel CreateCategoryContact(CatSub catSub, Dictionary<string, PriUser> userMap)
        {
            var categoryContact = new CategoryContactModel
            {
                Id = catSub.Id,
            };

            categoryContact.Pm = userMap.GetOrDefault(catSub.User.UsrName);

            categoryContact.Manager = userMap.GetOrDefault(catSub.MdyPm);

            categoryContact.Purchaser = userMap.GetOrDefault(catSub.MdyPurher);

            categoryContact.Staff = userMap.GetOrDefault(catSub.MdyStaff);

            return categoryContact;
        }
        public void GetOrDefault()
        {
            Dictionary<int, string> dict = new Dictionary<int, string>();
            dict.Add(1, "one");

            Assert.AreEqual("one", dict.GetOrDefault(1));
            Assert.IsNull(dict.GetOrDefault(4));

            dict.Add(2, "two");
            dict.Add(3, "three");
            dict.Add(4, "four");
            Assert.AreEqual("three", dict.GetOrDefault((k, v) => !v.Contains('o')));
        }
Example #27
0
        private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, FiestaStream pStream)
        {
            if (pTCPPacket.SequenceNumber > pSequence)
            {
                byte[] data;
                while ((data = pBuffer.GetOrDefault(pSequence, null)) != null)
                {
                    pBuffer.Remove(pSequence);
                    pStream.Append(data);
                    pSequence += (uint)data.Length;
                }
                if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.TCPData;
            }
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                if (difference > 0)
                {
                    byte[] data = pTCPPacket.TCPData;
                    if (data.Length > difference)
                    {
                        pStream.Append(data, difference, data.Length - difference);
                        pSequence += (uint)(data.Length - difference);
                    }
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.TCPData;
                pStream.Append(data);
                pSequence += (uint)data.Length;
            }

            FiestaPacket packet;
            try
            {
                while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null)
                {
                    mPackets.Add(packet);
                    Definition definition = Config.Instance.Definitions.Find(d => d.Build == 1 && d.Outbound == packet.Outbound && d.Opcode == packet.Opcode);
                    if (!mOpcodes.Exists(kv => kv.Item1 == packet.Outbound && kv.Item2 == packet.Opcode))
                    {
                        mOpcodes.Add(new Tuple<bool, ushort>(packet.Outbound, packet.Opcode));

                    }
                    if (definition != null && definition.Ignore) continue;
                    if (!FilterOut(packet))
                    {
                        mPacketList.Items.Add(packet);
                    }
                    if (mPacketList.SelectedItems.Count == 0) packet.EnsureVisible();
                }
            }
            catch (Exception exc)
            {
                OutputForm output = new OutputForm("Packet Error");
                output.Append(exc.ToString());
                output.Show(DockPanel, new Rectangle(MainForm.Location, new Size(400, 400)));
                mTerminated = true;
                Text += " (Terminated)";
            }
        }