public static Animator CreateAnimator
            (this ImmutableList<IAnimationSection> animationSections,
            ImmutableList<IRenderer> children)
        {
            return new Animator(animationSections, children);

        }
 private void ApplyOverrides(ImmutableList<FileModel> models, IHostService host)
 {
     foreach (var uid in host.GetAllUids())
     {
         var ms = host.LookupByUid(uid);
         var od = ms.SingleOrDefault(m => m.Type == DocumentType.Override);
         if (od != null)
         {
             var ovm = ((List<ItemViewModel>)od.Content).Single(vm => vm.Uid == uid);
             foreach (
                 var pair in
                     from model in ms
                     where model.Type == DocumentType.Article
                     from item in ((PageViewModel)model.Content).Items
                     where item.Uid == uid
                     select new { model, item })
             {
                 var vm = pair.item;
                 // todo : fix file path
                 Merger.Merge(ref vm, ovm);
                 ((HashSet<string>)pair.model.Properties.LinkToUids).UnionWith((HashSet<string>)od.Properties.LinkToUids);
                 ((HashSet<string>)pair.model.Properties.LinkToFiles).UnionWith((HashSet<string>)od.Properties.LinkToFiles);
             }
         }
     }
 }
        public void EnumeratorLengthTest1()
        {
            var list1 = new ImmutableList<int>(new int[] { 0, 1, 2 });
            var list2 = new ImmutableList<int>(new int[] { 3, 4, 5 });

            var list = list1.Concat(list2);

            Assert.True(list.Length == 6);

            list = list.Tail();
            Assert.True(list.Length == 5);

            list = list.Tail();
            list = list.Tail();
            list = list.Tail();
            list = list.Tail();

            Assert.True(list.Length == 1);
            Assert.True(list.IsAlmostEmpty);

            list = list.Tail();
            Assert.True(list.IsEmpty);

			Assert.Throws<ParserException>(() => list.Tail());
        }
 public NavigationItem(string displayName, int imageIndex, [CanBeNull] Location location, int navigationPoint, ImmutableList<NavigationItem> children=null) {
     Extent          = location?.Extent;
     NavigationPoint = navigationPoint;
     DisplayName     = displayName;
     ImageIndex      = imageIndex;
     Children        = children?? ImmutableList<NavigationItem>.Empty;
 }
Example #5
0
 public CompanyState(Company company, int money, int loans, ImmutableList<Train> trains)
 {
     Company = company;
     Money = money;
     Loans = loans;
     Trains = trains;
 }
Example #6
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad (e);

            String version = GL.GetString(StringName.Version);
            Console.WriteLine("GL version: " + version);

            context = GLGraphics.NewContext(Context, true);

            program = context.NewProgramFromFiles("Render.vert", "Render.frag");

            texture0 = context.NewTexture(TextureMinFilter.Nearest, TextureMagFilter.Nearest, TextureWrapMode.Clamp, TextureWrapMode.Clamp);
            texture0.UploadImage(sourceImage);
            sourceImage.Dispose();

            texture1 = context.NewTexture(TextureMinFilter.Nearest, TextureMagFilter.Nearest, TextureWrapMode.Clamp, TextureWrapMode.Clamp);
            texture1.UploadImage(new byte[4 * 4 * 4], 4, 4, PixelInternalFormat.Four, PixelFormat.Rgba, PixelType.UnsignedByte);

            CreateAndFillBuffers();
            paramSpec = ImmutableList<Tuple<String, Object>>.List(new Tuple<String, Object>[] {
                Tuple.Create<String, Object>("a_position", positions),
                Tuple.Create<String, Object>("a_texPos", textureCoords),
                Tuple.Create<String, Object>("u_texture0", texture0),
                Tuple.Create<String, Object>("u_texture1", texture1)});
        }
        public VisualStudioDocumentTrackingService(IServiceProvider serviceProvider)
        {
            _visibleFrames = ImmutableList<FrameListener>.Empty;

            _monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));
            _monitorSelection.AdviseSelectionEvents(this, out _cookie);
        }
Example #8
0
 public static Order MakeMouseClick(ImmutableList<UInt16> selected, Vector point) {
     return new Order() {
         OrderType = 1,
         SelectedUnits = selected,
         PreparedOrderPoint = point
     };
 }
Example #9
0
 public FakeHeaders(IEnumerable<ChainedHeader> blockHeaders)
 {
     this.blockHeaders = ImmutableList.CreateRange(blockHeaders).ToBuilder();
     this.bits = DataCalculator.ToCompact(UnitTestParams.Target0);
     this.nonce = (UInt32)Interlocked.Increment(ref staticNonce);
     this.totalWork = blockHeaders.LastOrDefault()?.TotalWork ?? 0;
 }
Example #10
0
 public RoleName Role(string name)
 {
     if (_roles.Exists(r => r.Name == name)) throw new ArgumentException("non-unique role name " + name);
     var roleName = new RoleName(name);
     _roles = _roles.Add(roleName);
     return roleName;
 }
        private LinearInterpolationSurface(double[] values, IPlotFunction[] functions, LinearInterpolationSurfaceProjection projection)
        {
            int n = values.Length;

            if (functions.Length != n)
            {
                throw new ArgumentException();
            }

            List<Tuple<double, IPlotFunction>> pairs = new List<Tuple<double, IPlotFunction>>();
            for (int i = 0; i < n; i++)
            {
                pairs.Add(Tuple.Create<double, IPlotFunction>(values[i], functions[i]));
            }
            pairs.Sort((p1, p2) => p1.Item1.CompareTo(p2.Item1));

            for (int i = 0; i < n; i++)
            {
                values[i] = pairs[i].Item1;
                functions[i] = pairs[i].Item2;
            }

            Count = n;
            Values = new ImmutableList<double>(values);
            Functions = new ImmutableList<IPlotFunction>(functions);
            Projection = projection;
        }
Example #12
0
 private PrivateAuctionRound(ImmutableList<Player> players, ImmutableList<PrivateCompany> privates, Auction<PrivateCompany> auction, Player activePlayer, Player lastToAct, int seedMoney)
     : base(players, activePlayer, lastToAct)
 {            
     Privates = privates;
     CurrentAuction = auction;
     SeedMoney = seedMoney;
 }
        // --- Initialization ---
        /// <summary>
        /// Initializes a new compilation document from a list of text lines.
        /// This method does not scan the inserted text lines to produce tokens.
        /// You must explicitely call UpdateTokensLines() to start an initial scan of the document.
        /// </summary>
        public CompilationDocument(TextSourceInfo textSourceInfo, IEnumerable<ITextLine> initialTextLines, TypeCobolOptions compilerOptions, IProcessedTokensDocumentProvider processedTokensDocumentProvider)
        {
            TextSourceInfo = textSourceInfo;
            CompilerOptions = compilerOptions;
            this.processedTokensDocumentProvider = processedTokensDocumentProvider;

            // Initialize the compilation document lines
            compilationDocumentLines = ImmutableList<CodeElementsLine>.Empty.ToBuilder();

            // ... with the initial list of text lines received as a parameter
            if (initialTextLines != null)
            {
                // Insert Cobol text lines in the internal tree structure
                compilationDocumentLines.AddRange(initialTextLines.Select(textLine => CreateNewDocumentLine(textLine, textSourceInfo.ColumnsLayout)));
            }

            // Initialize document views versions
            currentTextLinesVersion = new DocumentVersion<ICobolTextLine>(this);
            currentTokensLinesVersion = new DocumentVersion<ITokensLine>(this);

            // Initialize performance stats
            PerfStatsForText = new PerfStatsForCompilationStep(CompilationStep.Text);
            PerfStatsForScanner = new PerfStatsForCompilationStep(CompilationStep.Scanner);
            PerfStatsForPreprocessor = new PerfStatsForCompilationStep(CompilationStep.Preprocessor);
        }
Example #14
0
        public MainForm()
        {
            InitializeComponent();

            cmv = new CMV();
            rawframes = new List<CMVFrame>();
            cmvframes = new ImmutableList<CMVFrame>(rawframes, "empty");
            copybuffer = new List<CMVFrame>();

            foregroundColourPicker.Colors = CMVColours.ForegroundColors;
            backgroundColourPicker.Colors = CMVColours.BackgroundColors;

            updateDelayTimer = new Timer();
                updateDelayTimer.Interval = 24;
                updateDelayTimer.Tick += handleUpdateDelayTimer;

            aboutBox = new AboutBox();
            aboutBox.HelpButtonClicked += new EventHandler(action_HelpTopics);

            newFileDialog = new ChooseDimensionsBox();

            loadTileset();

            RefreshControls();
        }
Example #15
0
        public BenchmarkDiff(BenchmarkRun left, BenchmarkRun right, ImmutableList<SourceLogEntry> log)
        {
            Left = left;
            Right = right;
            var leftResults = left.AllResults.ToList();
            var rightResults = right.AllResults.ToList();
            LeftOnly = leftResults.ExceptBy(rightResults, result => result.FullMethod);
            RightOnly = rightResults.ExceptBy(leftResults, result => result.FullMethod);

            var pairs = (from l in leftResults
                         join r in rightResults on l.FullMethod equals r.FullMethod
                         select new BenchmarkPair(l, r)).ToList();

            LeftBetter = pairs.Where(pair => pair.Percent < ImprovementThreshold).ToList();
            RightBetter = pairs.Where(pair => pair.Percent > RegressionThreshold).ToList();

            bool leftEarlier = BenchmarkRepository.BuildForLabel(left.Label) < BenchmarkRepository.BuildForLabel(right.Label);

            var earlier = leftEarlier ? left : right;
            var later = leftEarlier ? right : left;

            var earlierHash = BenchmarkRepository.HashForLabel(earlier.Label);
            var laterHash = BenchmarkRepository.HashForLabel(later.Label);
            
            LogEntries = log.EntriesBetween(earlierHash, laterHash).ToList();
        }
        private static bool RecoursiveCheckGraph(Task root, ImmutableList<Guid> previousTasks)
        {
            Contract.Requires(root != null);
            Contract.Requires(root.Inputs != null);
            Contract.Requires(previousTasks != null);

            if (previousTasks.Contains(root.Id))
            {
                Logger.Write(
                    LogCategories.Error(string.Format(
                    "{0} is cycled.", root),
                    LogCategories.TaskServices));
                return false;
            }

            foreach (var task in root.Inputs)
            {
                if (previousTasks.Contains(task.Id))
                {
                    Logger.Write(
                        LogCategories.Error(string.Format(
                        "{0} is cycled.", task),
                        LogCategories.TaskServices));
                    return false;
                }

                if (!RecoursiveCheckGraph(task, previousTasks.Add(root.Id)))
                    return false;
            }
            return true;
        }
 public override ImmutableList<char> FreeVariableNames(ImmutableList<Symbol> boundVariables)
 {
     if (boundVariables.Contains(_variable))
         return ImmutableList<char>.Empty;
     else
         return new char[] { _variable.Default }.ToImmutableList();
 }
 internal PathSpec(PathFlags flags, string directorySeparator, IEnumerable<string> elements)
 {
     ValidateFlags(flags);
     Flags = flags;
     DirectorySeparator = directorySeparator;
     Components = elements.SelectMany(SplitComponent).ToImmutableList();
 }
Example #19
0
 public FakeHeaders()
 {
     this.blockHeaders = ImmutableList.CreateBuilder<ChainedHeader>();
     this.bits = DataCalculator.TargetToBits(UnitTestRules.Target0);
     this.nonce = (UInt32)Interlocked.Increment(ref staticNonce);
     this.totalWork = 0;
 }
        public static void Main()
        {
            var list = new List<ClassWithStringProperty>() { "test1", "test2", "test3", "test4"};
            var imlist = new ImmutableList<ClassWithStringProperty>(list);
            Console.WriteLine("Lists created:");
            Console.WriteLine(list.Stringify(e =>e.Prop));
            Console.WriteLine(imlist.Stringify(e => e.Prop));

            Console.WriteLine("Mutable list modified[immutable not modified]:");
            list.Add("test5");
            Console.WriteLine(list.Stringify(e => e.Prop));
            Console.WriteLine(imlist.Stringify(e => e.Prop));

            Console.WriteLine("Element in immutable changed[not really...]:");
            var elem = imlist[2];
            elem.Prop = "1234";
            Console.WriteLine(imlist.Stringify(e => e.Prop));

            Console.WriteLine("Element in mutable changed[& not in immutable]:");
            elem = list[2];
            elem.Prop = "12387";
            Console.WriteLine(list.Stringify(e => e.Prop));
            Console.WriteLine(imlist.Stringify(e => e.Prop));

            Console.ReadLine();
        }
 public PathSyntaxReference(SyntaxNode node)
 {
     this.tree = node.SyntaxTree;
     this.kind = node.CSharpKind();
     this.textSpan = node.Span;
     this.pathFromRoot = ComputePathFromRoot(node);
 }
Example #22
0
        /// <summary>
        /// 1. Expand the TOC reference
        /// 2. Resolve homepage
        /// </summary>
        /// <param name="models"></param>
        /// <param name="host"></param>
        /// <returns></returns>
        public override IEnumerable<FileModel> Prebuild(ImmutableList<FileModel> models, IHostService host)
        {
            var tocModelCache = new Dictionary<string, TocItemInfo>();
            foreach (var model in models)
            {
                if (!tocModelCache.ContainsKey(model.OriginalFileAndType.FullPath))
                {
                    tocModelCache[model.OriginalFileAndType.FullPath] = new TocItemInfo(model.OriginalFileAndType, (TocItemViewModel)model.Content);
                }
            }
            var tocResolver = new TocResolver(host, tocModelCache);
            foreach (var key in tocModelCache.Keys.ToList())
            {
                tocModelCache[key] = tocResolver.Resolve(key);
            }

            foreach (var model in models)
            {
                var wrapper = tocModelCache[model.OriginalFileAndType.FullPath];

                // If the TOC file is referenced by other TOC, remove it from the collection
                if (!wrapper.IsReferenceToc)
                {
                    model.Content = wrapper.Content;
                    yield return model;
                }
            }
        }
Example #23
0
 public void JoinSeedNodeSpecs()
 {
     _seedNodes = ImmutableList.Create(GetAddress(_config.Seed1), GetAddress(_config.Seed2),
         GetAddress(_config.Seed3));
     AClusterWithSeedNodesMustBeAbleToStartTheSeedNodesConcurrently();
     AClusterWithSeedNodesMustBeAbleToJoinTheSeedNodes();
 }
Example #24
0
 internal ProjectDependencyGraph(
     ImmutableList<ProjectId> projectIds,
     ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> referencesMap)
 {
     this.projectIds = projectIds;
     this.referencesMap = referencesMap;
 }
Example #25
0
 public void JoinSeedNodeSpecs()
 {
     _seedNodes = ImmutableList.Create(GetAddress(_config.Seed1), GetAddress(_config.Seed2),
         GetAddress(_config.Seed3));
     A_cluster_with_seed_nodes_must_be_able_to_start_the_seed_nodes_concurrently();
     A_cluster_with_seed_nodes_must_be_able_to_join_the_seed_nodes();
 }
Example #26
0
        private Solution(
            BranchId branchId,
            int workspaceVersion,
            SolutionServices solutionServices,
            SolutionId id,
            string filePath,
            ImmutableList<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
            ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap,
            ProjectDependencyGraph dependencyGraph,
            VersionStamp version,
            Lazy<VersionStamp> lazyLatestProjectVersion)
        {
            this.branchId = branchId;
            this.workspaceVersion = workspaceVersion;
            this.id = id;
            this.filePath = filePath;
            this.solutionServices = solutionServices;
            this.projectIds = projectIds;
            this.projectIdToProjectStateMap = idToProjectStateMap;
            this.projectIdToTrackerMap = projectIdToTrackerMap;
            this.dependencyGraph = dependencyGraph;
            this.projectIdToProjectMap = ImmutableHashMap<ProjectId, Project>.Empty;
            this.version = version;
            this.lazyLatestProjectVersion = lazyLatestProjectVersion;

            CheckInvariants();
        }
Example #27
0
 public FakeHeaders(IEnumerable<ChainedHeader> blockHeaders)
 {
     this.blockHeaders = ImmutableList.CreateRange(blockHeaders).ToBuilder();
     this.bits = DataCalculator.TargetToBits(UnitTestRules.Target0);
     this.nonce = (UInt32)Interlocked.Increment(ref staticNonce);
     this.totalWork = this.blockHeaders.Sum(x => x.BlockHeader.CalculateWork());
 }
Example #28
0
 public SyntaxTree(ChunkNode root, List<Token> tokens, List<StatementNode> statementNodeList, ImmutableList<ParseError> errorList)
 {
     this.Root = root;
     this.Tokens = tokens;
     this.ErrorList = errorList;
     this.StatementNodeList = statementNodeList;
 }
 public FSharpCompilationException(IEnumerable<FSharpDiagnosticMessage> diagnostics)
   : base(GetErrorMessage(diagnostics))
 {
   _failures = diagnostics.Where(d => d.Severity == DiagnosticMessageSeverity.Error)
                          .GroupBy(d => d.SourceFilePath, StringComparer.OrdinalIgnoreCase)
                          .Select(g => new FSharpCompilationFailure(g.Key, g))
                          .ToImmutableList();
 }
Example #30
0
        public void SetInstructions(ImmutableList<string> instructions)
        {
            _instructions.Clear();
            _instructions.AddRange(instructions);

            _playhead.Value = 0;
            Save();
        }
 public FFmpegFilterChainItem(ImmutableList <FFmpegPad> inputStreams, FFmpegFilter filter)
     : this(inputStreams, filter, ImmutableList.Create <FFmpegPad>())
 {
 }
 public FFmpegFilterChainItem(FFmpegFilter filter, ImmutableList <FFmpegPad> outputStreams)
     : this(ImmutableList.Create <FFmpegPad>(), filter, outputStreams)
 {
 }
 public FFmpegFilterChainItem(FFmpegFilter filter)
     : this(ImmutableList.Create <FFmpegPad>(), filter, ImmutableList.Create <FFmpegPad>())
 {
 }
Example #34
0
        public static IMyObjectPrx Run(TestHelper helper)
        {
            bool ice2 = helper.Protocol == Protocol.Ice2;
            var  prx  = IMyObjectPrx.Parse(helper.GetTestProxy("test"), helper.Communicator !);

            System.IO.TextWriter output = helper.Output;

            output.Write("testing retry... ");
            output.Flush();
            TestHelper.Assert(prx.AddWithRetry(33, 12) == 45);
            output.WriteLine("ok");

            output.Write("testing remote exception... ");
            output.Flush();
            try
            {
                prx.BadAdd(33, 12);
                TestHelper.Assert(false);
            }
            catch (InvalidInputException)
            {
                // expected
            }
            output.WriteLine("ok");

            output.Write("testing ONE... ");
            output.Flush();
            try
            {
                prx.NotExistAdd(33, 12);
                TestHelper.Assert(false);
            }
            catch (ObjectNotExistException)
            {
                // expected
            }
            output.WriteLine("ok");

            output.Write("testing exceptions raised by the interceptor... ");
            output.Flush();
            var exceptions = new List <(string operation, string kind)>
            {
                ("raiseBeforeDispatch", "invalidInput"),
                ("raiseBeforeDispatch", "notExist"),
                ("raiseAfterDispatch", "invalidInput"),
                ("raiseAfterDispatch", "notExist")
            };

            foreach ((string operation, string kind) in exceptions)
            {
                var ctx = new Dictionary <string, string>
                {
                    { operation, kind }
                };

                try
                {
                    prx.IcePing(ctx);
                    TestHelper.Assert(false);
                }
                catch (InvalidInputException) when(kind == "invalidInput")
                {
                }
                catch (ObjectNotExistException) when(kind == "notExist")
                {
                }
            }
            output.WriteLine("ok");

            output.Write("testing invocation interceptors... ");
            output.Flush();
            {
                var tasks             = new List <Task>();
                var invocationContext = new AsyncLocal <int>();
                using var communicator = new Communicator(prx.Communicator.GetProperties());

                communicator.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                    (target, request, next, cancel) =>
                {
                    request.WritableContext["interceptor-1"] = "interceptor-1";
                    if (ice2)
                    {
                        request.BinaryContextOverride.Add(110, ostr => ostr.WriteInt(110));
                    }
                    return(next(target, request, cancel));
                },
                    async(target, request, next, cancel) =>
                {
                    TestHelper.Assert(request.Context["interceptor-1"] == "interceptor-1");
                    request.WritableContext["interceptor-2"] = "interceptor-2";
                    if (ice2)
                    {
                        request.BinaryContextOverride.Add(120, ostr => ostr.WriteInt(120));
                    }
                    IncomingResponseFrame response = await next(target, request, cancel);
                    TestHelper.Assert(invocationContext.Value == int.Parse(request.Context["local-user"]));
                    if (ice2)
                    {
                        TestHelper.Assert(response.BinaryContext.ContainsKey(110));
                        TestHelper.Assert(response.BinaryContext[110].Read(istr => istr.ReadInt()) == 110);
                        TestHelper.Assert(response.BinaryContext.ContainsKey(120));
                        TestHelper.Assert(response.BinaryContext[120].Read(istr => istr.ReadInt()) == 120);
                    }
                    return(response);
                });

                communicator.ActivateAsync().GetAwaiter().GetResult();

                for (int i = 0; i < 10; ++i)
                {
                    invocationContext.Value = i;
                    var  prx1 = IMyObjectPrx.Parse(prx.ToString() !, communicator);
                    Task t    = prx1.Op1Async(new Dictionary <string, string> {
                        { "local-user", $"{i}" }
                    });
                    tasks.Add(t);
                }
                Task.WaitAll(tasks.ToArray());
            }

            {
                IncomingResponseFrame?response = null;
                int invocations = 0;
                // An interceptor can stop the chain and directly return a response without calling next,
                // the first invocation calls next and subsequent invocations reuse the first response.
                using var communicator = new Communicator(prx.Communicator.GetProperties());

                communicator.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                    (target, request, next, cancel) =>
                {
                    request.WritableContext["interceptor-1"] = "interceptor-1";
                    return(next(target, request, cancel));
                },
                    async(target, request, next, cancel) =>
                {
                    if (response == null)
                    {
                        response = await next(target, request, cancel);
                    }
                    return(response);
                },
                    (target, request, next, cancel) =>
                {
                    invocations++;
                    TestHelper.Assert(response == null);
                    return(next(target, request, cancel));
                });

                TestHelper.Assert(communicator.DefaultInvocationInterceptors.Count == 3);
                communicator.ActivateAsync().GetAwaiter().GetResult();
                TestHelper.Assert(communicator.DefaultInvocationInterceptors.Count == 4);

                var prx1 = IMyObjectPrx.Parse(prx.ToString() !, communicator);

                // Truly reference equal
                TestHelper.Assert(prx1.InvocationInterceptors == communicator.DefaultInvocationInterceptors);

                prx1.Op1(new Dictionary <string, string> {
                    { "local-user", "10" }
                });
                prx1.Op1(new Dictionary <string, string> {
                    { "local-user", "11" }
                });
                prx1.Op1(new Dictionary <string, string> {
                    { "local-user", "12" }
                });
                TestHelper.Assert(invocations == 1);
            }

            {
                // throwing from an interceptor stops the interceptor chain
                using var communicator = new Communicator(prx.Communicator.GetProperties());
                communicator.DefaultInvocationInterceptors = ImmutableList.Create <InvocationInterceptor>(
                    (target, request, next, cancel) =>
                {
                    request.WritableContext["interceptor-1"] = "interceptor-1";
                    return(next(target, request, cancel));
                },
                    (target, request, next, cancel) =>
                {
                    TestHelper.Assert(request.Context["interceptor-1"] == "interceptor-1");
                    throw new InvalidOperationException("stop interceptor chain");
                },
                    (target, request, next, cancel) =>
                {
                    TestHelper.Assert(false);
                    return(next(target, request, cancel));
                });
                communicator.ActivateAsync().GetAwaiter().GetResult();

                var prx1 = IMyObjectPrx.Parse(prx.ToString() !, communicator);
                try
                {
                    prx1.Op1();
                    TestHelper.Assert(false);
                }
                catch (InvalidOperationException)
                {
                }
            }
            output.WriteLine("ok");

            output.Write("testing binary context... ");
            output.Flush();

            if (ice2)
            {
                for (int size = 128; size < 4096; size *= 2)
                {
                    var token = new Token(1, "mytoken", Enumerable.Range(0, size).Select(i => (byte)2).ToArray());

                    {
                        using var request = OutgoingRequestFrame.WithArgs(prx,
                                                                          "opWithBinaryContext",
                                                                          idempotent: false,
                                                                          compress: false,
                                                                          format: default,
                                                                          context: null,
                                                                          token,
                                                                          Token.IceWriter);
                        request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                        request.BinaryContextOverride.Add(3, ostr => ostr.WriteShort((short)size));
                        request.BinaryContextOverride.Add(
                            2,
                            ostr => ostr.WriteSequence(
                                Enumerable.Range(0, 10).Select(i => $"string-{i}").ToArray(),
                                (ostr, s) => ostr.WriteString(s)));

                        using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
                    }

                    {
                        // repeat with compressed frame
                        using OutgoingRequestFrame request = OutgoingRequestFrame.WithArgs(prx,
                                                                                           "opWithBinaryContext",
                                                                                           idempotent: false,
                                                                                           compress: false,
                                                                                           format: default,
                                                                                           context: null,
                                                                                           token,
                                                                                           Token.IceWriter);
                        request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                        request.BinaryContextOverride.Add(3, ostr => ostr.WriteShort((short)size));
                        request.BinaryContextOverride.Add(
                            2,
                            ostr => ostr.WriteSequence(
                                Enumerable.Range(0, 10).Select(i => $"string-{i}").ToArray(),
                                (ostr, s) => ostr.WriteString(s)));

                        TestHelper.Assert(request.CompressPayload() == CompressionResult.Success);
                        using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
                    }

                    {
                        // repeat compressed the frame before writing the context
                        using OutgoingRequestFrame request = OutgoingRequestFrame.WithArgs(prx,
                                                                                           "opWithBinaryContext",
                                                                                           idempotent: false,
                                                                                           compress: false,
                                                                                           format: default,
                                                                                           context: null,
                                                                                           token,
                                                                                           Token.IceWriter);

                        TestHelper.Assert(request.CompressPayload() == CompressionResult.Success);

                        request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                        request.BinaryContextOverride.Add(3, ostr => ostr.WriteShort((short)size));
                        request.BinaryContextOverride.Add(
                            2,
                            ostr => ostr.WriteSequence(
                                Enumerable.Range(0, 10).Select(i => $"string-{i}").ToArray(),
                                (ostr, s) => ostr.WriteString(s)));

                        using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
                    }
                }
            }
            else
            {
                var token = new Token(1, "mytoken", Enumerable.Range(0, 256).Select(i => (byte)2).ToArray());
                using var request = OutgoingRequestFrame.WithArgs(prx,
                                                                  "opWithBinaryContext",
                                                                  idempotent: false,
                                                                  compress: false,
                                                                  format: default,
                                                                  context: null,
                                                                  token,
                                                                  Token.IceWriter);
                try
                {
                    request.BinaryContextOverride.Add(1, ostr => ostr.WriteStruct(token));
                    TestHelper.Assert(false);
                }
                catch (NotSupportedException)
                {
                }
                using IncomingResponseFrame response = prx.InvokeAsync(request).Result;
            }
            output.WriteLine("ok");

            output.Write("testing per proxy invocation interceptors... ");
            output.Flush();
            {
                var communicator = helper.Communicator !;

                SortedDictionary <string, string>?context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(!context.ContainsKey("context3"));
                prx = prx.Clone(invocationInterceptors: ImmutableList.Create <InvocationInterceptor>(
                                    (target, request, next, cancel) =>
                {
                    request.WritableContext["context2"] = "proxy";
                    request.WritableContext["context3"] = "proxy";
                    return(next(target, request, cancel));
                }).AddRange(communicator.DefaultInvocationInterceptors));
                context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(context["context3"] == "proxy");

                // Calling next twice doesn't change the result
                prx = prx.Clone(invocationInterceptors: ImmutableList.Create <InvocationInterceptor>(
                                    (target, request, next, cancel) =>
                {
                    request.WritableContext["context2"] = "proxy";
                    request.WritableContext["context3"] = "proxy";
                    _ = next(target, request, cancel);
                    return(next(target, request, cancel));
                }).AddRange(communicator.DefaultInvocationInterceptors));
                context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(context["context3"] == "proxy");

                // Cloning the proxy preserve its interceptors
                prx     = prx.Clone(invocationTimeout: TimeSpan.FromSeconds(10));
                context = prx.Op2();
                TestHelper.Assert(context["context1"] == "plug-in");
                TestHelper.Assert(context["context2"] == "plug-in");
                TestHelper.Assert(context["context3"] == "proxy");

                // The server increments the result with each call when using the invocation interceptor we
                // return a cached response, and we will see the same result with each call.
                IncomingResponseFrame?response = null;
                prx = prx.Clone(invocationInterceptors: ImmutableList.Create <InvocationInterceptor>(
                                    async(target, request, next, cancel) =>
                {
                    response ??= await next(target, request, cancel);
                    return(response);
                }).AddRange(communicator.DefaultInvocationInterceptors));
                TestHelper.Assert(prx.Op3() == 0);
                TestHelper.Assert(prx.Op3() == 0);

                // After clearing the invocation interceptors we should see the result increase with each call
                prx = prx.Clone(invocationInterceptors: communicator.DefaultInvocationInterceptors);
                TestHelper.Assert(prx.Op3() == 1);
                TestHelper.Assert(prx.Op3() == 2);
            }
            output.WriteLine("ok");
            return(prx);
        }
Example #35
0
        public void RemoveRangeEnumerableTest()
        {
            var list = ImmutableList.Create(1, 2, 3);

            AssertExtensions.Throws <ArgumentNullException>("items", () => list.RemoveRange(null));

            ImmutableList <int> removed2 = list.RemoveRange(new[] { 2 });

            Assert.Equal(2, removed2.Count);
            Assert.Equal(new[] { 1, 3 }, removed2);

            ImmutableList <int> removed13 = list.RemoveRange(new[] { 1, 3, 5 });

            Assert.Equal(1, removed13.Count);
            Assert.Equal(new[] { 2 }, removed13);
            Assert.Equal(new[] { 2 }, ((IImmutableList <int>)list).RemoveRange(new[] { 1, 3, 5 }));

            Assert.Same(list, list.RemoveRange(new[] { 5 }));
            Assert.Same(ImmutableList.Create <int>(), ImmutableList.Create <int>().RemoveRange(new[] { 1 }));

            var listWithDuplicates = ImmutableList.Create(1, 2, 2, 3);

            Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 }));
            Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 }));

            AssertExtensions.Throws <ArgumentNullException>("items", () => ((IImmutableList <int>)ImmutableList.Create(1, 2, 3)).RemoveRange(null));
            Assert.Equal(new[] { 1, 3 }, ((IImmutableList <int>)ImmutableList.Create(1, 2, 3)).RemoveRange(new[] { 2 }));
        }
Example #36
0
            static void LogWorkspaceDiagnostics(ILogger logger, bool logWorkspaceWarnings, ImmutableList <WorkspaceDiagnostic> diagnostics)
            {
                if (!logWorkspaceWarnings)
                {
                    if (diagnostics.Count > 0)
                    {
                        logger.LogWarning(Resources.Warnings_were_encountered_while_loading_the_workspace_Set_the_verbosity_option_to_the_diagnostic_level_to_log_warnings);
                    }

                    return;
                }

                foreach (var diagnostic in diagnostics)
                {
                    if (diagnostic.Kind == WorkspaceDiagnosticKind.Failure)
                    {
                        logger.LogError(diagnostic.Message);
                    }
                    else
                    {
                        logger.LogWarning(diagnostic.Message);
                    }
                }
            }
Example #37
0
            public bool Equals(Temp other)
            {
                if (other == null)
                {
                    throw new Exception("Equals failed.");
                }
                if (ReferenceEquals(this, other))
                {
                    throw new Exception("Equals failed.");
                }
                if (IntIntArray.Rank != other.IntIntArray.Rank)
                {
                    throw new Exception("Equals failed.");
                }

                for (var i = 0; i < IntIntArray.Rank; ++i)
                {
                    for (var j = 0; j < IntIntArray.GetLength(i); ++j)
                    {
                        if (IntIntArray[j, i] != other.IntIntArray[j, i])
                        {
                            throw new Exception("Equals failed.");
                        }
                    }
                }

                if (Exception.GetType() != other.Exception.GetType())
                {
                    throw new Exception("Equals failed.");
                }
                if (Exception.Message != other.Exception.Message)
                {
                    throw new Exception("Equals failed.");
                }
                if (Exception.InnerException != null &&
                    Exception.InnerException.GetType() != other.Exception.InnerException.GetType())
                {
                    throw new Exception("Equals failed.");
                }

                for (var i = 0; i < SubArray.Length; i++)
                {
                    if (SubArray[i].GetType() != other.SubArray[i].GetType())
                    {
                        throw new Exception("Equals failed.");
                    }

                    if (SubArray[i] is Array arr)
                    {
                        var oArr = (Array)other.SubArray[i];
                        for (var j = 0; j < arr.Length; ++j)
                        {
                            if (!arr.GetValue(j).Equals(oArr.GetValue(j)))
                            {
                                throw new Exception("Equals failed.");
                            }
                        }
                    }
                    else if (!SubArray[i].Equals(other.SubArray[i]))
                    {
                        throw new Exception("Equals failed.");
                    }
                }

                foreach (var key in Dictionary.Keys)
                {
                    if (!Dictionary[key].Equals(other.Dictionary[key]))
                    {
                        throw new Exception("Equals failed.");
                    }
                }

                foreach (var key in ImmutableDictionary.Keys)
                {
                    if (!ImmutableDictionary[key].Equals(other.ImmutableDictionary[key]))
                    {
                        throw new Exception("Equals failed.");
                    }
                }

                if (other.Delegate(2, 2) != 4)
                {
                    throw new Exception("Equals failed.");
                }

                if (!IntArray.SequenceEqual(other.IntArray))
                {
                    throw new Exception("Equals failed.");
                }
                if (!Equals(Poco, other.Poco))
                {
                    throw new Exception("Equals failed.");
                }
                if (String != other.String)
                {
                    throw new Exception("Equals failed.");
                }
                if (!TestEnum.SequenceEqual(other.TestEnum))
                {
                    throw new Exception("Equals failed.");
                }
                if (!ImmutableList.SequenceEqual(other.ImmutableList))
                {
                    throw new Exception("Equals failed.");
                }

                return(true);
            }
        private readonly ImmutableSet <Index> indices;  // not a property, derived and cached from input data

        //-------------------------------------------------------------------------
        /// <summary>
        /// Creates a swap from one or more swap legs.
        /// <para>
        /// While most swaps have two legs, other combinations are possible.
        ///
        /// </para>
        /// </summary>
        /// <param name="legs">  the array of legs </param>
        /// <returns> the swap </returns>
        public static ResolvedSwap of(params ResolvedSwapLeg[] legs)
        {
            ArgChecker.notEmpty(legs, "legs");
            return(new ResolvedSwap(ImmutableList.copyOf(legs)));
        }
Example #39
0
 public SslServerCredentials(ImmutableList <KeyCertificatePair> keyCertPairs)
 {
     this.keyCertPairs = keyCertPairs;
 }
 /// <summary>
 /// Sets the {@code legs} property in the builder
 /// from an array of objects. </summary>
 /// <param name="legs">  the new value, not empty </param>
 /// <returns> this, for chaining, not null </returns>
 public Builder legs(params ResolvedSwapLeg[] legs)
 {
     return(this.legs(ImmutableList.copyOf(legs)));
 }
Example #41
0
        public void ArrayAsRootObject()
        {
            const string ExpectedJson         = @"[1,true,{""City"":""MyCity""},null,""foo""]";
            const string ReversedExpectedJson = @"[""foo"",null,{""City"":""MyCity""},true,1]";

            string[] expectedObjects = { @"""foo""", @"null", @"{""City"":""MyCity""}", @"true", @"1" };

            var address = new Address();

            address.Initialize();

            var    array = new object[] { 1, true, address, null, "foo" };
            string json  = Serializer.Serialize(array);

            Assert.Equal(ExpectedJson, json);

            var dictionary = new Dictionary <string, string> {
                { "City", "MyCity" }
            };
            var arrayWithDictionary = new object[] { 1, true, dictionary, null, "foo" };

            json = Serializer.Serialize(arrayWithDictionary);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(array);
            Assert.Equal(ExpectedJson, json);

            List <object> list = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(list);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(list);
            Assert.Equal(ExpectedJson, json);

            IEnumerable ienumerable = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(ienumerable);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(ienumerable);
            Assert.Equal(ExpectedJson, json);

            IList ilist = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(ilist);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(ilist);
            Assert.Equal(ExpectedJson, json);

            ICollection icollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(icollection);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(icollection);
            Assert.Equal(ExpectedJson, json);

            IEnumerable <object> genericIEnumerable = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(genericIEnumerable);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(genericIEnumerable);
            Assert.Equal(ExpectedJson, json);

            IList <object> genericIList = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(genericIList);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(genericIList);
            Assert.Equal(ExpectedJson, json);

            ICollection <object> genericICollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(genericICollection);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(genericICollection);
            Assert.Equal(ExpectedJson, json);

            IReadOnlyCollection <object> genericIReadOnlyCollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(genericIReadOnlyCollection);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(genericIReadOnlyCollection);
            Assert.Equal(ExpectedJson, json);

            IReadOnlyList <object> genericIReadonlyList = new List <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(genericIReadonlyList);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(genericIReadonlyList);
            Assert.Equal(ExpectedJson, json);

            ISet <object> iset = new HashSet <object> {
                1, true, address, null, "foo"
            };

            json = Serializer.Serialize(iset);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(iset);
            Assert.Equal(ExpectedJson, json);

            Stack <object> stack = new Stack <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(stack);
            Assert.Equal(ReversedExpectedJson, json);

            json = Serializer.Serialize <object>(stack);
            Assert.Equal(ReversedExpectedJson, json);

            Queue <object> queue = new Queue <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(queue);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(queue);
            Assert.Equal(ExpectedJson, json);

            HashSet <object> hashset = new HashSet <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(hashset);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(hashset);
            Assert.Equal(ExpectedJson, json);

            LinkedList <object> linkedlist = new LinkedList <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(linkedlist);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(linkedlist);
            Assert.Equal(ExpectedJson, json);

            ImmutableArray <object> immutablearray = ImmutableArray.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(immutablearray);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(immutablearray);
            Assert.Equal(ExpectedJson, json);

            IImmutableList <object> iimmutablelist = ImmutableList.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(iimmutablelist);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(iimmutablelist);
            Assert.Equal(ExpectedJson, json);

            IImmutableStack <object> iimmutablestack = ImmutableStack.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(iimmutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            json = Serializer.Serialize <object>(iimmutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            IImmutableQueue <object> iimmutablequeue = ImmutableQueue.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(iimmutablequeue);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(iimmutablequeue);
            Assert.Equal(ExpectedJson, json);

            IImmutableSet <object> iimmutableset = ImmutableHashSet.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(iimmutableset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            json = Serializer.Serialize <object>(iimmutableset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            ImmutableHashSet <object> immutablehashset = ImmutableHashSet.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(immutablehashset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            json = Serializer.Serialize <object>(immutablehashset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            ImmutableList <object> immutablelist = ImmutableList.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(immutablelist);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(immutablelist);
            Assert.Equal(ExpectedJson, json);

            ImmutableStack <object> immutablestack = ImmutableStack.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(immutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            json = Serializer.Serialize <object>(immutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            ImmutableQueue <object> immutablequeue = ImmutableQueue.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = Serializer.Serialize(immutablequeue);
            Assert.Equal(ExpectedJson, json);

            json = Serializer.Serialize <object>(immutablequeue);
            Assert.Equal(ExpectedJson, json);
        }
Example #42
0
        public void ToImmutableListOfSameType()
        {
            var list = ImmutableList.Create("a");

            Assert.Same(list, list.ToImmutableList());
        }
        public FFmpegFilterChainItem(ImmutableList <FFmpegPad> inputStreams, FFmpegFilter filter, ImmutableList <FFmpegPad> outputStreams)
        {
            ErrorUtils.ThrowIfArgNull(inputStreams, nameof(inputStreams));
            ErrorUtils.ThrowIfArgNull(filter, nameof(filter));
            ErrorUtils.ThrowIfArgNull(outputStreams, nameof(outputStreams));

            this.InputStreams  = inputStreams;
            this.Filter        = filter;
            this.OutputStreams = outputStreams;
        }
 public void Dispose()
 {
     _entries = ImmutableList <UIBuildSummary> .Empty;
 }
Example #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZenAdapterExpr{TTo, TFrom}"/> class.
 /// </summary>
 /// <param name="expr">The expression.</param>
 /// <param name="converters">Converter between types.</param>
 private ZenAdapterExpr(Zen <TFrom> expr, ImmutableList <Func <object, object> > converters)
 {
     this.Expr       = expr;
     this.Converters = converters;
 }
Example #46
0
 public MarkdownRewriterContext(ICompositionContainer container, ImmutableList <MarkdownTagValidationRule> validators)
 {
     Container  = container;
     Validators = validators;
 }
Example #47
0
 public ViewLibraryPepInfoList(IEnumerable <ViewLibraryPepInfo> items)
 {
     _allEntries = ImmutableList.ValueOf(items.OrderBy(item => item, Comparer <ViewLibraryPepInfo> .Create(ComparePepInfos)));
 }
Example #48
0
        public virtual void test_pv01_calibrated()
        {
            FixedCouponBondTradeCalculationFunction <FixedCouponBondTrade> function = FixedCouponBondTradeCalculationFunction.TRADE;
            ScenarioMarketData                    md                      = marketData();
            LegalEntityDiscountingProvider        provider                = LOOKUP.marketDataView(md.scenario(0)).discountingProvider();
            DiscountingFixedCouponBondTradePricer pricer                  = DiscountingFixedCouponBondTradePricer.DEFAULT;
            PointSensitivities                    pvPointSens             = pricer.presentValueSensitivity(RTRADE, provider);
            CurrencyParameterSensitivities        pvParamSens             = provider.parameterSensitivity(pvPointSens);
            MultiCurrencyAmount                   expectedPv01Cal         = pvParamSens.total().multipliedBy(1e-4);
            CurrencyParameterSensitivities        expectedPv01CalBucketed = pvParamSens.multipliedBy(1e-4);

            ISet <Measure> measures = ImmutableSet.of(Measures.PV01_CALIBRATED_SUM, Measures.PV01_CALIBRATED_BUCKETED);

            assertThat(function.calculate(TRADE, measures, PARAMS, md, REF_DATA)).containsEntry(Measures.PV01_CALIBRATED_SUM, Result.success(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedPv01Cal)))).containsEntry(Measures.PV01_CALIBRATED_BUCKETED, Result.success(ScenarioArray.of(ImmutableList.of(expectedPv01CalBucketed))));
        }
Example #49
0
        public void IsSynchronized()
        {
            ICollection collection = ImmutableList.Create <int>();

            Assert.True(collection.IsSynchronized);
        }
Example #50
0
        public virtual void test_simpleMeasures()
        {
            FixedCouponBondTradeCalculationFunction <FixedCouponBondTrade> function = FixedCouponBondTradeCalculationFunction.TRADE;
            ScenarioMarketData                    md       = marketData();
            LegalEntityDiscountingProvider        provider = LOOKUP.marketDataView(md.scenario(0)).discountingProvider();
            DiscountingFixedCouponBondTradePricer pricer   = DiscountingFixedCouponBondTradePricer.DEFAULT;
            CurrencyAmount      expectedPv = pricer.presentValue(RTRADE, provider);
            MultiCurrencyAmount expectedCurrencyExposure = pricer.currencyExposure(RTRADE, provider);
            CurrencyAmount      expectedCurrentCash      = pricer.currentCash(RTRADE, VAL_DATE);

            ISet <Measure> measures = ImmutableSet.of(Measures.PRESENT_VALUE, Measures.CURRENCY_EXPOSURE, Measures.CURRENT_CASH, Measures.RESOLVED_TARGET);

            assertThat(function.calculate(TRADE, measures, PARAMS, md, REF_DATA)).containsEntry(Measures.PRESENT_VALUE, Result.success(CurrencyScenarioArray.of(ImmutableList.of(expectedPv)))).containsEntry(Measures.CURRENCY_EXPOSURE, Result.success(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedCurrencyExposure)))).containsEntry(Measures.CURRENT_CASH, Result.success(CurrencyScenarioArray.of(ImmutableList.of(expectedCurrentCash)))).containsEntry(Measures.RESOLVED_TARGET, Result.success(RTRADE));
        }
Example #51
0
 public void GetHashCodeVariesByInstance()
 {
     Assert.NotEqual(ImmutableList.Create <int>().GetHashCode(), ImmutableList.Create(5).GetHashCode());
 }
Example #52
0
 ///-------------------------------------------------------------------------------------------------
 /// <summary>
 ///  Constructor.
 /// </summary>
 /// <param name="services">
 ///  The services.
 /// </param>
 ///-------------------------------------------------------------------------------------------------
 public Subject(IServicesContainer services)
 {
     this._observers         = new ImmutableList <IObserver <T> >();
     _synchronizationContext = services.Resolve <ISynchronizationContext>();
 }
Example #53
0
        public static LibKeyMap <TItem> Create(IEnumerable <TItem> items, Func <TItem, LibraryKey> getKeyFunc)
        {
            var itemsList = ImmutableList.ValueOf(items);

            return(new LibKeyMap <TItem>(itemsList, itemsList.Select(getKeyFunc)));
        }
Example #54
0
 public Todo Copy(ImmutableList <object> queue)
 {
     return(new Todo(Target, queue));
 }
Example #55
0
 public LibKeyMap(ImmutableList <TItem> items, IEnumerable <LibraryKey> keys)
 {
     _allItems = items;
     _index    = new LibKeyIndex(keys);
 }
 public AddressBook(ImmutableList <Contact> contacts) => Contacts = contacts;
Example #57
0
 public rd1(
     ImmutableList <Ird1CrossJoinElement> value)
 {
     this.Value = value;
 }
 // trusted constructor
 internal ResolvedSwap(ImmutableList <ResolvedSwapLeg> legs, ImmutableSet <Currency> currencies, ImmutableSet <Index> indices)
 {
     this.legs       = legs;
     this.currencies = currencies;
     this.indices    = indices;
 }
Example #59
0
        public void Add(T value)
        {
            var current = this.Current;
            var newSet  = current.Add(value);

            if (newSet != current)
            {
                this.Subject.OnNext(new SortedSetChangedNotification <T>(newSet, NotifyCollectionChangedAction.Add, ImmutableList <T> .Empty, ImmutableList.Create(value), newSet.IndexOf(value)));
            }
        }
Example #60
0
 public Todo(IActorRef target, ImmutableList <object> queue)
 {
     Target = target;
     Queue  = queue;
 }