Exemplo n.º 1
0
        public Task <SCG.IReadOnlyDictionary <K, Entry <K, V> > > GetManyAsync(IReadOnlySet <K> keys)
        {
            return(ExecCommandAsync(async cmd => {
                // Retrieve all rows
                cmd.CommandText = $"SELECT * FROM {tableName} WHERE id=ANY(@ids)";
                var idParameter = cmd.CreateParameter();
                idParameter.ParameterName = "ids";
                idParameter.Value = keys.ToArray();
                cmd.Parameters.Add(idParameter);

                using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) {
                    var results = new SCG.Dictionary <K, Entry <K, V> >();
                    while (await reader.ReadAsync().ConfigureAwait(false))
                    {
                        var entry = ReadToEntry(reader);
                        results[entry.Key] = entry;
                    }
                    foreach (var key in keys)
                    {
                        if (!results.ContainsKey(key))
                        {
                            results[key] = Entry <K, V> .CreateNonexistant(key);
                        }
                    }
                    return (SCG.IReadOnlyDictionary <K, Entry <K, V> >)results;
                }
            }));
        }
Exemplo n.º 2
0
        private static bool IsInsideToken(SCG.Dictionary <ParseRecord, bool> memoization, CompositeGrammar compositeGrammar, ParseRecord record)
        {
            bool res;

            if (memoization.TryGetValue(record, out res))
            {
                return(res);
            }

            if (record.Sequence.ParsingSequence.SequenceInfo is SequenceInfo.Ast)
            {
                var parser = record.Sequence.ParsingSequence.SequenceInfo.Parser;
                res = compositeGrammar.Tokens.ContainsKey(parser) || compositeGrammar.VoidTokens.ContainsKey(parser);
                memoization[record] = res;
                if (res)
                {
                    return(res);
                }
            }

            foreach (var caller in record.Sequence.Callers)
            {
                res = IsInsideToken(memoization, compositeGrammar, caller);
                if (res)
                {
                    memoization[record] = true;
                    return(true);
                }
            }

            memoization[record] = false;
            return(false);
        }
        private static double GetEntropy(string result)
        {
            SCG.Dictionary <char, int> frequencies = new SCG.Dictionary <char, int>();
            foreach (char c in result)
            {
                if (frequencies.ContainsKey(c))
                {
                    ++frequencies[c];
                }
                else
                {
                    frequencies[c] = 1;
                }
            }

            int    length  = result.Length;
            double entropy = 0;

            foreach (var keyValue in frequencies)
            {
                double freq = (double)keyValue.Value / length;
                entropy += freq * SYS.Math.Log(freq, 2);
            }

            return(-entropy);
        }
        private async Task RunAsync()
        {
            while (true)
            {
                await jobSignal.WaitAsync().ConfigureAwait(false);

                var jobResultBoxByKey = new SCG.Dictionary <K, AsyncBox <Entry <K, V> > >();
                var spinner           = new SpinWait();
                do
                {
                    Tuple <K, AsyncBox <Entry <K, V> > > job;
                    while (!jobQueue.TryDequeue(out job))
                    {
                        spinner.SpinOnce();
                    }
                    jobResultBoxByKey.Add(job.Item1, job.Item2);
                } while (jobSignal.TryTake());

//            Console.WriteLine("Batch Read: " + jobResultBoxByKey.Count);
                var results = await hitler.GetManyAsync(new HashSet <K>(jobResultBoxByKey.Keys)).ConfigureAwait(false);

                foreach (var kvp in results)
                {
                    jobResultBoxByKey[kvp.Key].SetResult(kvp.Value);
                }
            }
        }
Exemplo n.º 5
0
 private static SCG.IDictionary <T, T> CreateDictionary <T>(int size, Func <int, T> keyValueSelector, SCG.IEqualityComparer <T> comparer = null)
 {
     SCG.Dictionary <T, T> temp = Enumerable.Range(0, size + 1).ToDictionary(keyValueSelector, keyValueSelector, comparer);
     J2N.Collections.Generic.Dictionary <T, T> dict = new Dictionary <T, T>(temp, comparer);
     // Remove first item to reduce Count to size and alter the contiguity of the dictionary
     dict.Remove(keyValueSelector(0));
     return(dict);
 }
Exemplo n.º 6
0
        public System.String ToUri()
        {
            var kv = new SCG.Dictionary <string, string>();

            kv["wrap"] = _wrapped_sender.ToUri();
            kv["max"]  = MAX_PAYLOAD_SIZE.ToString();
            return(SenderFactory.EncodeUri("frag", kv));
        }
Exemplo n.º 7
0
    private void ObtainAllLabelNodes()
    {
        labelsMap = new SCG.Dictionary <int, Label[]>();

        for (int i = 0; i < rankingControls.Length; i++)
        {
            ObtainLabelNodesFromControl(i);
        }
    }
Exemplo n.º 8
0
        private SCG.Dictionary <int, bool[]> MakeSubSubSubDictionary(int n)
        {
            var result = new SCG.Dictionary <int, bool[]>();

            for (var i = 0; i < n; i++)
            {
                bool[] data = Util.Generate(i, x => x % 2 == 0);
                result.Add(i, data);
            }
            return(result);
        }
        SCG.Dictionary <int, string> GetTiller()
        {
            var dict = new SCG.Dictionary <int, string>();

            for (int i = 1000; i < 2000; ++i)
            {
                //var h = Hasher.Rehash(EqualityComparer<int>.Default.GetItemHashCode(Hasher.Rehash(i)));
                var h = Hasher.Rehash(i);

                unchecked
                {
                    dict.Add((int)h, "STR:" + (h & 31).ToString());
                }
            }

            return(dict);
        }
        public void TestEqualsTypeMismatch()
        {
            var list = new SCG.List <int> {
                1, 2, 3, 4, 5
            };
            var set = new SCG.HashSet <int> {
                1, 2, 3, 4, 5
            };
            var dictionary = new SCG.Dictionary <int, int> {
                { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 }, { 5, 0 }
            };
            var array = new int[] { 1, 2, 3, 4, 5 };

            Assert.IsFalse(CollectionUtil.Equals(list, set));
            Assert.IsFalse(CollectionUtil.Equals(list, dictionary));
            Assert.IsTrue(CollectionUtil.Equals(list, array)); // Types are compatible - array implements IList<T>

            Assert.IsFalse(CollectionUtil.Equals(set, dictionary));
            Assert.IsFalse(CollectionUtil.Equals(set, array));
        }
Exemplo n.º 11
0
        private bool CheckUnclosedToken(RecoveryParser rp)
        {
            var maxPos             = rp.MaxPos;
            var grammar            = rp.ParseResult.RuleParser.Grammar;
            var records            = rp.Records[maxPos].ToArray();
            var result             = new SCG.Dictionary <ParseRecord, bool>();
            var unclosedTokenFound = false;

            foreach (var record in records)
            {
                if (record.IsComplete)
                {
                    continue;
                }

                if (record.Sequence.StartPos >= maxPos)
                {
                    continue;
                }

                if (record.Sequence.ParsingSequence.IsNullable)
                {
                    continue;
                }

                var res = IsInsideToken(result, grammar, record);

                if (!res)
                {
                    continue;
                }

                unclosedTokenFound = true;
                rp.SubruleParsed(maxPos, maxPos, record);
            }

            return(unclosedTokenFound);
        }
Exemplo n.º 12
0
        public void NestedArraysTest()
        {
            var dict   = new SCG.Dictionary <int, float[][]>();
            var random = new Random(0);

            for (var i = 0; i < 10; i++)
            {
                dict.Add(i, Util.Generate(i, x => Util.Generate(x, y => (float)random.NextDouble())));
            }

            var context = new PofContext();

            context.RegisterPortableObjectType(1, typeof(Wrapper));
            var serializer = new PofSerializer(context);

            using (var ms = new MemoryStream()) {
                using (var writer = new BinaryWriter(ms, Encoding.UTF8, true)) {
                    serializer.Serialize(writer, new Wrapper(dict));
                }
                ms.Position = 0;
                Console.WriteLine(ms.ToArray().ToHex());
                using (var reader = new BinaryReader(ms, Encoding.UTF8, true)) {
                    var wrapperCopy = (Wrapper)serializer.Deserialize(reader);
                    var dictClone   = (SCG.Dictionary <int, float[][]>)wrapperCopy.Value;
                    AssertTrue(new ICL.HashSet <int>(dict.Keys).SetEquals(dictClone.Keys));
                    random = new Random();
                    for (var i = 0; i < 10; i++)
                    {
                        var arr = dict[i];
                        for (var j = 0; j < arr.Length; j++)
                        {
                            AssertTrue(new ICL.HashSet <float>(arr[j]).SetEquals(dictClone[i][j]));
                        }
                    }
                }
            }
        }
        private async Task RunAsync()
        {
            while (true)
            {
                Console.WriteLine("Begin BU");
                var sw = new Stopwatch();
                sw.Start();

                SCG.Dictionary <K, PendingUpdate <K, V> > mergedPendingUpdates = new SCG.Dictionary <K, PendingUpdate <K, V> >();
                var spinner = new SpinWait();
                while (pendingUpdatesSignal.TryTake())
                {
                    PendingUpdate <K, V> pendingUpdate;
                    while (!pendingUpdates.TryDequeue(out pendingUpdate))
                    {
                        spinner.SpinOnce();
                    }
                    PendingUpdate <K, V> existingPendingUpdate;
                    if (mergedPendingUpdates.TryGetValue(pendingUpdate.Base.Key, out existingPendingUpdate))
                    {
                        existingPendingUpdate.Updated = pendingUpdate.Updated;
                    }
                    else
                    {
                        mergedPendingUpdates[pendingUpdate.Base.Key] = pendingUpdate;
                    }
                }

                if (mergedPendingUpdates.Any())
                {
                    await hitler.BatchUpdateAsync(mergedPendingUpdates.Values.ToArray()).ConfigureAwait(false);
                }
                Console.WriteLine("END BU " + sw.ElapsedMilliseconds);
                await Task.Delay(batchUpdateIntervalMillis).ConfigureAwait(false);
            }
        }
Exemplo n.º 14
0
 internal XobotPackageManager(ContextImpl context)
 {
     this.context    = context;
     loaded_packages = new SCG.Dictionary <string, XobotPackageInfo> ();
 }
Exemplo n.º 15
0
        /// <summary>
        /// Returns the maximum stack depth required by these CIL instructions.
        /// </summary>
        /// <returns>The integer value of the stck depth.</returns>
        public int GetMaxStackDepthRequired()
        {
            if (tide == 0) return 0;

            // Store the code blocks we find
            SCG.List<CodeBlock> codeBlocks = new SCG.List<CodeBlock>();
            SCG.Dictionary<CILLabel, CodeBlock> cbTable = new SCG.Dictionary<CILLabel, CodeBlock>();
            SCG.List<CodeBlock> extraStartingBlocks = new SCG.List<CodeBlock>();

            // Start a default code block
            CodeBlock codeBlock = new CodeBlock(this);
            codeBlock.StartIndex = 0;

            //
            // Identify the code blocks
            //
            for (int i = 0; i < tide; i++) {

                /* Handling the tail instruction:
                 * The tail instruction has not been handled even though
                 * it indicates the end of a code block is coming.  The
                 * reason for this is because any valid tail instruction
                 * must be followed by a call* instruction and then a ret
                 * instruction.  Given a ret instruction must be the second
                 * next instruction anyway it has been decided to just let
                 * the end block be caught then.
                 */

                // If we reach a branch instruction or a switch instruction
                // then end the current code block inclusive of the instruction.
                if ((buffer[i] is BranchInstr) || (buffer[i] is SwitchInstr)) {

                    // Close the old block
                    codeBlock.EndIndex = i;
                    if (codeBlock.EndIndex >= codeBlock.StartIndex) // Don't add empty blocks
                        codeBlocks.Add(codeBlock);

                    // Open a new block
                    codeBlock = new CodeBlock(this);
                    codeBlock.StartIndex = i + 1;

                    // If we reach a label then we need to start a new
                    // code block as the label is an entry point.
                } else if (buffer[i] is CILLabel) {

                    // Close the old block
                    codeBlock.EndIndex = i - 1;
                    if (codeBlock.EndIndex >= codeBlock.StartIndex) // Don't add empty blocks
                        codeBlocks.Add(codeBlock);

                    // Open a new block
                    codeBlock = new CodeBlock(this);
                    codeBlock.StartIndex = i;

                    // Set this label as the entry point for the code block
                    codeBlock.EntryLabel = (CILLabel)buffer[i];
                    // AND ... list in the dictionary.
                    cbTable.Add(codeBlock.EntryLabel, codeBlock);

                    // Check for the ret, throw, rethrow, or jmp instruction as they also end a block
                } else if (buffer[i] is Instr) {
                    if (
                        (((Instr)buffer[i]).GetOp() == Op.ret) ||
                        (((Instr)buffer[i]).GetOp() == Op.throwOp) ||
                        (((Instr)buffer[i]).GetOp() == Op.rethrow) ||
                        ((buffer[i] is MethInstr) && (((MethInstr)buffer[i]).GetMethodOp() == MethodOp.jmp))
                       ) {

                        // Close the old block
                        codeBlock.EndIndex = i;
                        if (codeBlock.EndIndex >= codeBlock.StartIndex) // Don't add empty blocks
                            codeBlocks.Add(codeBlock);

                        // Open a new block
                        // In theory this should never happen but just in case
                        // someone feels like adding dead code it is supported.
                        codeBlock = new CodeBlock(this);
                        codeBlock.StartIndex = i + 1;

                    }

                }

            }

            // Close the last block
            codeBlock.EndIndex = tide - 1;
            if (codeBlock.EndIndex >= codeBlock.StartIndex) // Don't add empty blocks
                codeBlocks.Add(codeBlock);
            codeBlock = null;

            // Check how many code blocks there are.  If an blocks return 0.
            if (codeBlocks.Count == 0) return 0;

            //
            // Loop through each code block and calculate the delta distance
            //
            for (int j = 0; j < codeBlocks.Count; j++) {
                CodeBlock block = codeBlocks[j];

                int maxDepth = 0;
                int currentDepth = 0;

                // Loop through each instruction to work out the max depth
                for (int i = block.StartIndex; i <= block.EndIndex; i++) {

                    // Get the depth after the next instruction
                    currentDepth += buffer[i].GetDeltaDistance();

                    // If the new current depth is greater then the maxDepth adjust the maxDepth to reflect
                    if (currentDepth > maxDepth)
                        maxDepth = currentDepth;

                }

                // Set the depth of the block
                block.MaxDepth = maxDepth;
                block.DeltaDistance = currentDepth;

                //
                // Link up the next blocks
                //

                // If the block ends with a branch statement set the jump and fall through.
                if (buffer[block.EndIndex] is BranchInstr) {
                    BranchInstr branchInst = (BranchInstr)buffer[block.EndIndex];

                    // If this is not a "br" or "br.s" then set the fall through code block
                    if ((branchInst.GetBranchOp() != BranchOp.br) &&
                        (branchInst.GetBranchOp() != BranchOp.br_s))
                        // If there is a following code block set it as the fall through
                        if (j < (codeBlocks.Count - 1))
                            block.NextBlocks.Add(codeBlocks[j + 1]);

                    // Set the code block we are jumping to
                    CodeBlock cb = null;
                    cbTable.TryGetValue(branchInst.GetDest(), out cb);
                    if (cb == null)
                        throw new Exception("Missing Branch Label");
                    block.NextBlocks.Add(cb);

                    // If the block ends in a switch instruction work out the possible next blocks
                } else if (buffer[block.EndIndex] is SwitchInstr) {
                    SwitchInstr switchInstr = (SwitchInstr)buffer[block.EndIndex];

                    // If there is a following code block set it as the fall through
                    if (j < (codeBlocks.Count - 1))
                        block.NextBlocks.Add(codeBlocks[j + 1]);

                    // Add each destination block
                    foreach (CILLabel label in switchInstr.GetDests()) {

                        // Check all of the code blocks to find the jump destination
                        CodeBlock cb = null;
                        cbTable.TryGetValue(label, out cb);
                        if (cb == null) throw new Exception("Missing Case Label");
                        block.NextBlocks.Add(cb);

                    }

                    // So long as the block doesn't end with a terminating instruction like ret or throw, just fall through to the next block
                } else if (!IsTerminatingInstruction(buffer[block.EndIndex])) {

                    // If there is a following code block set it as the fall through
                    if (j < (codeBlocks.Count - 1))
                        block.NextBlocks.Add(codeBlocks[j + 1]);
                }

            }

            //
            // Join up any exception blocks
            //

            if (exceptions != null) {
                foreach (TryBlock tryBlock in exceptions) {

                    // Try to find the code block where this try block starts
                    CodeBlock tryCodeBlock;
                    cbTable.TryGetValue(tryBlock.Start, out tryCodeBlock);

                    // Declare that the entry to this code block must be empty
                    tryCodeBlock.RequireEmptyEntry = true;

                    // Work with each of the handlers
                    foreach (HandlerBlock hb in tryBlock.GetHandlers()) {

                        // Find the code block where this handler block starts.
                        CodeBlock handlerCodeBlock;
                        cbTable.TryGetValue(hb.Start, out handlerCodeBlock);

                        // If the code block is a catch or filter block increment the delta
                        // distance by 1. This is to factor in the exception object that will
                        // be secretly placed on the stack by the runtime engine.
                        // However, this also means that the MaxDepth is up by one also!
                        if (hb is Catch || hb is Filter)
                        {
                            handlerCodeBlock.DeltaDistance++;
                            handlerCodeBlock.MaxDepth++;
                        }

                        // If the code block is a filter block increment the delta distance by 1
                        // This is to factor in the exception object that will be placed on the stack.
                        // if (hb is Filter) handlerCodeBlock.DeltaDistance++;

                        // Add this handler to the list of starting places
                        extraStartingBlocks.Add(handlerCodeBlock);

                    }

                }
            }

            //
            // Traverse the code blocks and get the depth
            //

            // Get the max depth at the starting entry point
            int finalMaxDepth = this.TraverseMaxDepth(codeBlocks[0]);

            // Check the additional entry points
            // If the additional points have a greater depth update the max depth
            foreach (CodeBlock cb in extraStartingBlocks) {
                // int tmpMaxDepth = cb.TraverseMaxDepth();
                int tmpMaxDepth = this.TraverseMaxDepth(cb);
                if (tmpMaxDepth > finalMaxDepth) finalMaxDepth = tmpMaxDepth;
            }

            // Return the max depth we have found
            return finalMaxDepth;
        }
Exemplo n.º 16
0
    private bool CheckUnclosedToken(RecoveryParser rp)
    {
      var maxPos  = rp.MaxPos;
      var grammar = rp.ParseResult.RuleParser.Grammar;
      var records = rp.Records[maxPos].ToArray();
      var result  = new SCG.Dictionary<ParseRecord, bool>();
      var unclosedTokenFound = false;

      foreach (var record in records)
      {
        if (record.IsComplete)
          continue;

        if (record.Sequence.StartPos >= maxPos)
          continue;

        if (record.Sequence.ParsingSequence.IsNullable)
          continue;

        var res = IsInsideToken(result, grammar, record);

        if (!res)
          continue;

        unclosedTokenFound = true;
        rp.SubruleParsed(maxPos, maxPos, record);
      }

      return unclosedTokenFound;
    }
Exemplo n.º 17
0
        public static bool UnsequencedEquals <T>(this ICollection <T> first, ICollection <T> second, SCG.IEqualityComparer <T> equalityComparer = null)
        {
            // !@
            Ensures(Result <bool>() == first.UnsequenceEqual(second, equalityComparer));

            // Equal if reference equal - this is true for two nulls as well
            if (ReferenceEquals(first, second))
            {
                return(true);
            }

            if (first == null || second == null)
            {
                return(false);
            }

            if (first.Count != second.Count)
            {
                return(false);
            }

            if (equalityComparer == null)
            {
                equalityComparer = SCG.EqualityComparer <T> .Default;
            }

            /*if (!first.AllowsDuplicates && (second.AllowsDuplicates || second.ContainsSpeed >= first.ContainsSpeed))
             * {
             *  return first.All(second.Contains);
             * }
             * else if (!second.AllowsDuplicates)
             * {
             *  return second.All(first.Contains);
             * }
             * // Now first.AllowsDuplicates && second.AllowsDuplicates
             * else if (first.DuplicatesByCounting && second.DuplicatesByCounting)
             * {
             *  return second.All(item => first.CountDuplicates(item) == second.CountDuplicates(item));
             * }
             * else */
            {
                // To avoid an O(n^2) algorithm, we make an auxiliary dictionary to hold the count of items
                var dictionary = new SCG.Dictionary <T, int>(equalityComparer); // TODO: Use C6 version (HashBag<T>)

                foreach (var item in second)
                {
                    int count;
                    if (dictionary.TryGetValue(item, out count))
                    {
                        // Dictionary already contained item, so we increment count with one
                        dictionary[item] = count + 1;
                    }
                    else
                    {
                        dictionary.Add(item, 1);
                    }
                }

                foreach (var item in first)
                {
                    int count;
                    if (dictionary.TryGetValue(item, out count) && count > 0)
                    {
                        dictionary[item] = count - 1;
                    }
                    else
                    {
                        return(false);
                    }
                }

                return(true);
            }
        }
Exemplo n.º 18
0
		internal XobotPackageManager (ContextImpl context)
		{
			this.context = context;
			loaded_packages = new SCG.Dictionary<string, XobotPackageInfo> ();
		}
        public void TestEqualityDictionary()
        {
            var control = new SCG.Dictionary <string, IDictionary <HashMap <long, double>, string> >
            {
                { "a", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 123, 9.87 }, { 80, 88 }
                                }, "qwerty" }
                  } },
                { "z", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 456, 9.86 }, { 81, 88 }
                                }, "hexagon" }
                  } },
                { "r", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 789, 9.85 }, { 82, 88 }
                                }, "parasite" }
                  } },
                { "t", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 101, 9.84 }, { 83, 88 }
                                }, "octopus" }
                  } },
            };
            var equal = new SCG.Dictionary <string, IDictionary <HashMap <long, double>, string> >
            {
                { "a", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 123, 9.87 }, { 80, 88 }
                                }, "qwerty" }
                  } },
                { "z", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 456, 9.86 }, { 81, 88 }
                                }, "hexagon" }
                  } },
                { "r", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 789, 9.85 }, { 82, 88 }
                                }, "parasite" }
                  } },
                { "t", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 101, 9.84 }, { 83, 88 }
                                }, "octopus" }
                  } },
            };
            var equalDifferentType = new HashMap <string, IDictionary <HashMap <long, double>, string> >
            {
                { "a", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 123, 9.87 }, { 80, 88 }
                                }, "qwerty" }
                  } },
                { "z", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 456, 9.86 }, { 81, 88 }
                                }, "hexagon" }
                  } },
                { "r", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 789, 9.85 }, { 82, 88 }
                                }, "parasite" }
                  } },
                { "t", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 101, 9.84 }, { 83, 88 }
                                }, "octopus" }
                  } },
            };
            var equalDifferentOrder = new SCG.Dictionary <string, IDictionary <HashMap <long, double>, string> >
            {
                { "r", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 789, 9.85 }, { 82, 88 }
                                }, "parasite" }
                  } },
                { "t", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 101, 9.84 }, { 83, 88 }
                                }, "octopus" }
                  } },
                { "a", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 123, 9.87 }, { 80, 88 }
                                }, "qwerty" }
                  } },
                { "z", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 456, 9.86 }, { 81, 88 }
                                }, "hexagon" }
                  } },
            };

            var level1EqualLevel2EqualLevel3Unequal = new SCG.Dictionary <string, IDictionary <HashMap <long, double>, string> >
            {
                { "a", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 123, 9.87 }, { 80, 88.1 }
                                }, "qwerty" }
                  } },
                { "z", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 456, 9.86 }, { 81, 88 }
                                }, "hexagon" }
                  } },
                { "r", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 789, 9.85 }, { 82, 88 }
                                }, "parasite" }
                  } },
                { "t", new SCG.Dictionary <HashMap <long, double>, string> {
                      { new HashMap <long, double> {
                                    { 101, 9.84 }, { 83, 88 }
                                }, "octopus" }
                  } },
            };

            Assert.AreEqual(CollectionUtil.GetHashCode(control), CollectionUtil.GetHashCode(control));
            Assert.IsTrue(CollectionUtil.Equals(control, control));

            Assert.AreEqual(CollectionUtil.GetHashCode(control), CollectionUtil.GetHashCode(equal));
            Assert.IsTrue(CollectionUtil.Equals(control, equal));

            Assert.AreEqual(CollectionUtil.GetHashCode(control), CollectionUtil.GetHashCode(equalDifferentType));
            Assert.IsTrue(CollectionUtil.Equals(control, equalDifferentType));

            Assert.AreEqual(CollectionUtil.GetHashCode(control), CollectionUtil.GetHashCode(equalDifferentOrder));
            Assert.IsTrue(CollectionUtil.Equals(control, equalDifferentOrder));

            Assert.AreNotEqual(CollectionUtil.GetHashCode(control), CollectionUtil.GetHashCode(level1EqualLevel2EqualLevel3Unequal));
            Assert.IsFalse(CollectionUtil.Equals(control, level1EqualLevel2EqualLevel3Unequal));
        }
        public void TestToString()
        {
            var set = new J2N.Collections.Generic.HashSet <IDictionary <string, string> >
            {
                new SCG.Dictionary <string, string> {
                    { "1", "one" }, { "2", "two" }, { "3", "three" }
                },
                new SCG.Dictionary <string, string> {
                    { "4", "four" }, { "5", "five" }, { "6", "six" }
                },
                new SCG.Dictionary <string, string> {
                    { "7", "seven" }, { "8", "eight" }, { "9", "nine" }
                },
            };
            var setExpected = "[{1=one, 2=two, 3=three}, {4=four, 5=five, 6=six}, {7=seven, 8=eight, 9=nine}]";

            Assert.AreEqual(setExpected, CollectionUtil.ToString(set, StringFormatter.InvariantCulture));


            var set2 = new J2N.Collections.Generic.HashSet <ISet <string> >
            {
                new J2N.Collections.Generic.HashSet <string> {
                    "1", "2", "3"
                },
                new J2N.Collections.Generic.HashSet <string> {
                    "4", "5", "6"
                },
                new System.Collections.Generic.HashSet <string> {
                    "7", "8", "9"
                },
            };
            var set2Expected = "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]";

            Assert.AreEqual(set2Expected, CollectionUtil.ToString(set2, StringFormatter.InvariantCulture));


            var map = new SCG.Dictionary <string, IDictionary <int, double> >
            {
                { "first", new SCG.Dictionary <int, double> {
                      { 1, 1.23 }, { 2, 2.23 }, { 3, 3.23 }
                  } },
                { "second", new SCG.Dictionary <int, double> {
                      { 4, 1.24 }, { 5, 2.24 }, { 6, 3.24 }
                  } },
                { "third", new SCG.Dictionary <int, double> {
                      { 7, 1.25 }, { 8, 2.25 }, { 9, 3.25 }
                  } },
            };
            var mapExpectedPortuguese = "{first={1=1,23, 2=2,23, 3=3,23}, second={4=1,24, 5=2,24, 6=3,24}, third={7=1,25, 8=2,25, 9=3,25}}";
            var mapExpectedUSEnglish  = "{first={1=1.23, 2=2.23, 3=3.23}, second={4=1.24, 5=2.24, 6=3.24}, third={7=1.25, 8=2.25, 9=3.25}}";

            Assert.AreEqual(mapExpectedPortuguese, CollectionUtil.ToString(map, new StringFormatter(new CultureInfo("pt"))));
            Assert.AreEqual(mapExpectedUSEnglish, CollectionUtil.ToString(map, new StringFormatter(new CultureInfo("en-US"))));

            var array = new SCG.List <SCG.Dictionary <string, string> >[]
            {
                new SCG.List <SCG.Dictionary <string, string> > {
                    new SCG.Dictionary <string, string> {
                        { "foo", "bar" }, { "foobar", "barfoo" }
                    }
                },
                new SCG.List <SCG.Dictionary <string, string> > {
                    new SCG.Dictionary <string, string> {
                        { "orange", "yellow" }, { "red", "black" }
                    },
                    new SCG.Dictionary <string, string> {
                        { "rain", "snow" }, { "sleet", "sunshine" }
                    }
                },
            };
            var arrayExpected = "[[{foo=bar, foobar=barfoo}], [{orange=yellow, red=black}, {rain=snow, sleet=sunshine}]]";

            Assert.AreEqual(arrayExpected, CollectionUtil.ToString(array, StringFormatter.InvariantCulture));
        }
Exemplo n.º 21
0
 public FragmentingHandler(int max_frags_cached) : base()
 {
     _fragments = new Cache(max_frags_cached);
     _fragments.EvictionEvent += this.HandleEviction;
     _frag_count = new SCG.Dictionary <Pair <uint, int>, Fragments>();
 }
Exemplo n.º 22
0
Test_CollectionFromSystemDictionaryAdapter()
{
    Print( "Adapt a new dictionary" );
    IUniqueKeyedCollectionRCSG< string, int > c =
        new SCG.Dictionary< string, int >()
        .AsHalfdecentCollection();

    Print( "Check that it's empty" );
    Assert( c.Count == 0 );

    Print( ".Add() and check" );
    c.Add( "1", 1 );
    Assert( c.Count == 1 );
    Assert( c.Contains( "1" ) );
    Assert( c.Get( "1" ) == 1 );

    Print( ".Add() and check" );
    c.Add( "2", 2 );
    Assert( c.Count == 2 );
    Assert( c.Contains( "2" ) );
    Assert( c.Get( "2" ) == 2 );

    Print( ".Add() and check" );
    c.Add( "3", 3 );
    Assert( c.Count == 3 );
    Assert( c.Contains( "3" ) );
    Assert( c.Get( "3" ) == 3 );

    Print( ".Replace() and check" );
    c.Replace( "2", 22 );
    Assert( c.Count == 3 );
    Assert( c.Contains( "2" ) );
    Assert( c.Get( "2" ) == 22 );

    Print( ".Remove() and check" );
    c.Remove( "2" );
    Assert( c.Count == 2 );
    Assert( !c.Contains( "2" ) );
    Expect(
        e => RTypeException.Match(
            e,
            (vr,f) => vr.Equals( f.Down().Parameter( "key" ) ),
            rt => rt.Equals( new ExistingKeyIn< string, int >( c ) ) ),
        () => c.Get( "2" ) );
}
Exemplo n.º 23
0
 public FragmentingHandler(int max_frags_cached) : base() {
   _fragments = new Cache(max_frags_cached);
   _fragments.EvictionEvent += this.HandleEviction;
   _frag_count = new SCG.Dictionary<Pair<uint, int>, Fragments>();
 }
Exemplo n.º 24
0
Test_IUniqueKeyedCollectionRSG_AsImplicitUniqueKeyedCollection()
{
    Print( "Make an implicit collection out of an explicit one" );
    IImplicitUniqueKeyedCollectionRSG< string, int > c
        = new SCG.Dictionary< string, int >()
        .AsHalfdecentCollection()
        .AsImplicitUniqueKeyedCollection( i => i.ToString() );

    Print( "Add() an item and check" );
    c.Add( 1 );
    Assert( c.Count == 1 );
    Assert( c.Contains( "1" ) );
    Assert( c.Get( "1" ) == 1 );

    Print( "Add() another item and check" );
    c.Add( 2 );
    Assert( c.Count == 2 );
    Assert( c.Contains( "2" ) );
    Assert( c.Get( "2" ) == 2 );

    Print( "Remove() an item and check" );
    c.Remove( "1" );
    Assert( c.Count == 1 );
    Assert( c.Contains( "2" ) );
    Assert( c.Get( "2" ) == 2 );

    Print( "Add() item with duplicate key throws RTypeException" );
    Expect(
        e => RTypeException.Match<
            NonExistingKeyIn< string, int > >(
            e ),
        () => c.Add( 2 ) );
}
Exemplo n.º 25
0
 public System.String ToUri() {
   var kv = new SCG.Dictionary<string,string>();
   kv["wrap"] = _wrapped_sender.ToUri();
   kv["max"] = MAX_PAYLOAD_SIZE.ToString();
   return SenderFactory.EncodeUri("frag", kv);
 }