public DijkstraShortestWeightedDirectedPathEnumerator(
     IWeightedDirectedGraph <TVertex, TEdge> graph,
     TVertex origin,
     IAdder <TEdge> adder
     ) : this(graph, origin, adder, Comparer <TEdge> .Default)
 {
 }
Example #2
0
 public ArithmeticCalculator(IAdder <T> adder, ISubtractor <T> subtractor, IMultiplier <T> multiplier, IDivider <T> divider)
 {
     _adder      = adder;
     _subtractor = subtractor;
     _multiplier = multiplier;
     _divider    = divider;
 }
Example #3
0
 //Constructor
 public BooksController(IFetcher myService, ICopyUpdater copyUpdaterService, IAdder adderService, ILogger <BooksController> logger)
 {
     _myService          = myService;
     _copyUpdaterService = copyUpdaterService;
     _adderService       = adderService;
     _logger             = logger;
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IAdder adder, IHostingEnvironment environment)
        {
            // primer middleware de la aplicación:
            app.UseWelcomePage("/test");

            if (environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/friendlyError500.html");
            }

            app.UseStaticFiles(); // Permite retornar archivos estáticos

            app.Run(async(context) =>
            {
                if (context.Request.Path == "/boom")
                {
                    throw new InvalidOperationException("Boom!!");
                }

                await context.Response.WriteAsync("Hello, world!");
            });
        }
Example #5
0
 public PathChromosome(
     List <IWeightedEndpoint <TVertex, TEdge> > genes,
     IAdder <TEdge> adder,
     IComparer <TEdge> comparer
     ) : base(genes, adder, comparer)
 {
 }
        DijkstraShortestPaths <TVertex, TEdge>(
            this IWeightedDirectedGraph <TVertex, TEdge> graph,
            TVertex origin,
            IAdder <TEdge> adder
            )
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            if (origin == null)
            {
                throw new ArgumentNullException(nameof(origin));
            }
            if (adder == null)
            {
                throw new ArgumentNullException(nameof(adder));
            }

            if (!graph.Vertices.Contains(origin))
            {
                throw new ArgumentException();
            }

            return(graph.DijkstraShortestPaths(origin, adder, Comparer <TEdge> .Default));
        }
Example #7
0
        public static readonly IComparer <int[]> COMPARE_INT_ARRAYS = new Int32ArrayComparer(); // ICU4N TODO: API - rename to follow .NET Conventions

        /// <summary>
        /// Compact the set of strings.
        /// </summary>
        /// <param name="source">Set of strings.</param>
        /// <param name="adder">Adds each pair to the output. See the <see cref="IAdder"/> interface.</param>
        /// <param name="shorterPairs">Use abc-d instead of abc-abd.</param>
        /// <param name="moreCompact">Use a more compact form, at the expense of more processing. If false, source must be sorted.</param>
        public static void Compact(ISet <string> source, IAdder adder, bool shorterPairs, bool moreCompact)
        {
            if (!moreCompact)
            {
                string start     = null;
                string end       = null;
                int    lastCp    = 0;
                int    prefixLen = 0;
                foreach (string s in source)
                {
                    if (start != null)
                    { // We have something queued up
                        if (s.RegionMatches(0, start, 0, prefixLen))
                        {
                            int currentCp = s.CodePointAt(prefixLen);
                            if (currentCp == 1 + lastCp && s.Length == prefixLen + Character.CharCount(currentCp))
                            {
                                end    = s;
                                lastCp = currentCp;
                                continue;
                            }
                        }
                        // We failed to find continuation. Add what we have and restart
                        adder.Add(start, end == null ? null
                            : !shorterPairs ? end
                                : end.Substring(prefixLen, end.Length - prefixLen)); // ICU4N: Corrected 2nd parameter
                    }
                    // new possible range
                    start     = s;
                    end       = null;
                    lastCp    = s.CodePointBefore(s.Length);
                    prefixLen = s.Length - Character.CharCount(lastCp);
                }
                adder.Add(start, end == null ? null
                    : !shorterPairs ? end
                        : end.Substring(prefixLen, end.Length - prefixLen)); // ICU4N: Corrected 2nd parameter
            }
            else
            {
                // not a fast algorithm, but ok for now
                // TODO rewire to use the first (slower) algorithm to generate the ranges, then compact them from there.
                // first sort by lengths
                Relation <int, Ranges> lengthToArrays = Relation.Of(new SortedDictionary <int, ISet <Ranges> >(), typeof(SortedDictionary <int, ISet <Ranges> >));
                foreach (string s in source)
                {
                    Ranges item = new Ranges(s);
                    lengthToArrays.Put(item.Length, item);
                }
                // then compact items of each length and emit compacted sets
                foreach (var entry in lengthToArrays.KeyValues)
                {
                    LinkedList <Ranges> compacted = Compact(entry.Key, entry.Value);
                    foreach (Ranges ranges in compacted)
                    {
                        adder.Add(ranges.Start(), ranges.End(shorterPairs));
                    }
                }
            }
        }
Example #8
0
 public Calculator(IQueryParser queryParser, IMultiplier multipler, IAdder adder, ISubtractor subtractor, IDivider divider)
 {
     _queryParser = queryParser;
     _multiplier  = multipler;
     _adder       = adder;
     _subtractor  = subtractor;
     _divider     = divider;
 }
Example #9
0
 public Calculator(IAdder adder, ISubtractor subtractor, IDivider divider, IMultiplier multiplier, IExponenter exponenter)
 {
     this.adder      = adder;
     this.subtractor = subtractor;
     this.divider    = divider;
     this.multiplier = multiplier;
     this.exponenter = exponenter;
 }
Example #10
0
        public void TestStaticInterfaceCast()
        {
            IAdder adder = DuckTyping.StaticCast <IAdder>(typeof(StaticAdder));

            Assert.AreEqual(4, adder.Add(2, 2));
            Assert.AreEqual(4, adder.LastTotal);

            adder.LastTotal = 15;
            Assert.AreEqual(15, adder.LastTotal);
        }
 public DijkstraShortestWeightedDirectedPathAlgorithm(
     IWeightedDirectedGraph <TVertex, TEdge> graph,
     IAdder <TEdge> adder,
     IComparer <TEdge> comparer
     )
 {
     Graph    = graph;
     Adder    = adder;
     Comparer = comparer;
 }
 public WeightedDirectedDirectedPathCollection(
     IWeightedDirectedGraph <TVertex, TEdge> graph,
     TVertex origin,
     IDictionary <TVertex, Tuple <TEdge, TEdge> > edges,
     IAdder <TEdge> adder
     ) : base(graph, origin)
 {
     Graph = graph;
     Edges = edges;
     Adder = adder;
 }
        //sum value in enumeration using adder
        public T Sum <T>(IEnumerable <T> values, IAdder <T> adder)
        {
            T result = adder.Zero;

            foreach (var value in values)
            {
                result = adder.Add(result, value);
            }

            return(result);
        }
Example #14
0
        public void One_Plus_One_Should_Be_Ignored()
        {
            // Arrange
            int    a     = 1;
            int    b     = 1;
            IAdder adder = Container.GetInstance <IAdder>();
            // Act
            int result = adder.Add(a, b);

            // Assert
            Assert.ShouldEqual(3, result);
        }
Example #15
0
        public void One_Plus_One_Should_Equal_Two()
        {
            // Arrange
            int    a     = 1;
            int    b     = 1;
            IAdder adder = Container.GetInstance(typeof(IAdder)) as IAdder;
            // Act
            int result = adder.Add(a, b);

            // Assert
            Assert.ShouldEqual(2, result);
        }
Example #16
0
 public PathGeneticAlgorithm(
     int noOfGenerations,
     int minPopulationSize,
     int maxPopulationSize,
     double mutationProbability,
     IWeightedDirectedGraph <TVertex, TEdge> graph,
     TVertex origin,
     TVertex destination,
     IAdder <TEdge> adder
     ) : this(noOfGenerations, minPopulationSize, maxPopulationSize, mutationProbability, graph, origin, destination, adder, Comparer <TEdge> .Default)
 {
 }
Example #17
0
        public Form(ISettings settings, IRecordsStorage aggregator, IAdder adder, IAmountFactory factory)
        {
            this.settings   = settings;
            this.aggregator = aggregator;
            this.adder      = adder;
            this.factory    = factory;

            amount = factory.Create(selectedType);
            Types  = Enum.GetValues(typeof(Types)).Cast <Types>();
            UpdateCategories(selectedType);

            DateTime     = DateTime.Now;
            Descriptions = settings.Descriptions;
        }
        public DijkstraShortestWeightedDirectedPathEnumerator(
            IWeightedDirectedGraph <TVertex, TEdge> graph,
            TVertex origin,
            IAdder <TEdge> adder,
            IComparer <TEdge> comparer
            )
        {
            Graph    = graph;
            Origin   = origin;
            Adder    = adder;
            Comparer = comparer;
            Heap     = new FibonacciHeap <TEdge, HeapEntry>(comparer);
            Visited  = new Dictionary <TVertex, IMinHeapVertex <TEdge, HeapEntry> >();

            Initialize();
        }
Example #19
0
 public PathGeneticAlgorithm(
     int noOfGenerations,
     int minPopulationSize,
     int maxPopulationSize,
     double mutationProbability,
     IWeightedDirectedGraph <TVertex, TEdge> graph,
     TVertex origin,
     TVertex destination,
     IAdder <TEdge> adder,
     IComparer <TEdge> comparer
     ) : base(noOfGenerations, minPopulationSize, maxPopulationSize, mutationProbability)
 {
     Graph       = graph;
     Origin      = origin;
     Destination = destination;
     Adder       = adder;
     Comparer    = comparer;
 }
Example #20
0
 public SharedAmount(IAdder adder, ISettings settings) : base(adder)
 {
     this.settings = settings;
 }
        private void AssertCanMockInAndOutParamOnMethod(IAdder adder)
        {
            Expect.Once.On(adder).Message("Add").With(3, 5, Is.Out).Will(
                new SetNamedParameterAction("c", 8)
                );

            int outValue;
            adder.Add(3, 5, out outValue);
            Assert.AreEqual(8, outValue, "Outvalue was not set correctly.");
        }
Example #22
0
 public PathChromosome(
     List <IWeightedEndpoint <TVertex, TEdge> > genes,
     IAdder <TEdge> adder
     ) : this(genes, adder, Comparer <TEdge> .Default)
 {
 }
 public SimpleInterfaceCalculator(IAdder adder)
 {
     _adder = adder;
 }
        private void AssertCanMockInAndOutParamWithReturnValueOnMethod(IAdder adder)
        {
            Expect.Once.On(adder).Message("Add").With(4, 7).Will(Return.Value(11));

            int c = adder.Add(4, 7);
            Assert.AreEqual(11, c, "Result was not set correctly.");
        }
Example #25
0
 public MyAdderInterface(IAdder adder)
 {
     _adder = adder;
 }
 public DijkstraShortestWeightedDirectedPathAlgorithm(
     IWeightedDirectedGraph <TVertex, TEdge> graph,
     IAdder <TEdge> adder
     ) : this(graph, adder, Comparer <TEdge> .Default)
 {
 }
 public StringCalculator(INumberParser numberParser, IAdder adder)
 {
     _numberParser = numberParser;
     _adder = adder;
 }
Example #28
0
 public MathMachine(IAdder adder)
 {
     _adder = adder;
 }
        DijkstraShortestPaths <TVertex, TEdge>(
            this IWeightedDirectedGraph <TVertex, TEdge> graph,
            TVertex origin,
            IAdder <TEdge> adder,
            IComparer <TEdge> comparer
            )
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            if (origin == null)
            {
                throw new ArgumentNullException(nameof(origin));
            }
            if (adder == null)
            {
                throw new ArgumentNullException(nameof(adder));
            }
            if (comparer == null)
            {
                throw new ArgumentNullException(nameof(comparer));
            }

            if (!graph.Vertices.Contains(origin))
            {
                throw new ArgumentException();
            }

            // Constructs a dictionary which stores the graphs which contain the shortest path from the origin to
            // each of the vertices that is reachable from the origin by iteratively traversing successor endpoints.
            var graphs = new Dictionary <TVertex, IWeightedDirectedGraph <TVertex, TEdge> >();

            // Constructs a dictionary which stores the additions which represent the added edges which in turn
            // represent the shortest path from the origin to each of the vertices when added.
            var accumulations = new Dictionary <TVertex, TEdge>();

            var settledVertices   = new HashSet <TVertex>();
            var unsettledVertices = new HashSet <TVertex> {
                origin
            };

            while (unsettledVertices.Count > 0)
            {
                // Returns the unsettled vertex that is nearest to the origin by finding the shortest of all the
                // accumulated edges which form a path from the origin to each of the unsettled vertices. Calling
                // the `MinBy` method with only one unsettled vertex in the set of unsettled vertices will return
                // that unsettled vertex, hence it will always return the origin during the first iteration over
                // the unsettled vertices set, because the unsettled vertices set will only contain the origin.
                var nearestVertex = unsettledVertices.MinBy(vertex => accumulations[vertex], comparer);

                // Removes the nearest vertex from the set of unvisited vertices.
                unsettledVertices.Remove(nearestVertex);

                // Iterates over each of the successor endpoints of the nearest vertex.
                foreach (var endpoint in graph.SuccessorEndpoints(nearestVertex))
                {
                    // If the vertex of the endpoint is already settled, then continue to the next iteration.
                    if (settledVertices.Contains(endpoint.Vertex))
                    {
                        continue;
                    }

                    // If the dictionary of additions contains an addition for the nearest vertex, then add this
                    // addition and the endpoint edge together in order to calculate a single path from the origin
                    // to the endpoint vertex of the current iteration; otherwise, an addition for the nearest vertex
                    // does not exist so return the endpoint edge without adding.
                    var currentPath = accumulations.ContainsKey(nearestVertex)
                        ? adder.Add(accumulations[nearestVertex], endpoint.Edge)
                        : endpoint.Edge;

                    // Returns true if the dictionary of additions contains the endpoint vertex and the current path
                    // is less than the existing shortest path from the origin to the endpoint vertex; otherwise,
                    // false. The existing shortest path is taken from the addition of each of the endpoints from
                    // the origin to the endpoint vertex which represent the existing shortest path when added.
                    bool IsCurrentPathLessThanShortestPath()
                    {
                        return(accumulations.ContainsKey(endpoint.Vertex) &&
                               comparer.Compare(currentPath, accumulations[endpoint.Vertex]) < 0);
                    }

                    // If the dictionary of graphs does not contain a graph for the endpoint vertex or the current
                    // path is less than the existing shortest path, then update the graph of the endpoint vertex.
                    if (!graphs.ContainsKey(endpoint.Vertex) || IsCurrentPathLessThanShortestPath())
                    {
                        // If the dictionary of graphs contains a graph for the nearest vertex, then a shortest path
                        // from the origin to the nearest vertex already exists so return a copy of this graph;
                        // otherwise, such a shortest path does not exist so return a new empty graph.
                        var currentGraph = graphs.ContainsKey(nearestVertex)
                            ? graphs[nearestVertex].EndpointPairs.ToGraph()
                            : new WeightedDirectedGraph <TVertex, TEdge>();

                        // Adds an edge from the nearest vertex to the vertex of the endpoint. This means that the
                        // graph will now contain endpoint pairs from the origin to the endpoint vertex.
                        currentGraph.AddEdge(nearestVertex, endpoint.Vertex, endpoint.Edge);

                        // Updates the graph of the endpoint vertex with the current graph because the current graph
                        // contains a shorter path from the origin to the endpoint vertex than the existing graph.
                        graphs[endpoint.Vertex] = currentGraph;

                        // Updates the addition of the endpoint vertex with the current path for the same reason.
                        accumulations[endpoint.Vertex] = currentPath;
                    }

                    // Adds the endpoint vertex to the set of unsettled vertices.
                    unsettledVertices.Add(endpoint.Vertex);
                }

                // Adds the nearest vertex to the set of settled vertices.
                settledVertices.Add(nearestVertex);
            }

            return(graphs);
        }
Example #30
0
 public static int Subtraction(this IAdder adder, int a, int b) //in this case, "this" indicates an extension method
 {
     return(adder.Add(a, -b));
 }
Example #31
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAdder adder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            Console.WriteLine("3");


            // Hello world middleware
            app.Use(async(ctx, next) =>
            {
                if (ctx.Request.Path == "/hello-world")
                {
                    // Procesa la petición y no permite la ejecución de middlewares posteriores
                    await ctx.Response.WriteAsync("Hello, world!");
                }
                else
                {
                    // Pasa el control al siguiente middleware
                    await next();
                }
            });

            app.Use(async(ctx, next) =>
            {
                if (ctx.Request.Path.ToString().StartsWith("/hello"))
                {
                    // Procesa la petición y no permite la ejecución de otros middlewares
                    await ctx.Response.WriteAsync("Hello, user!");
                }
                else
                {
                    // Pasa la petición al siguiente middleware
                    await next();
                }
            });

            app.Run(async(context) =>
            {
                if (context.Request.Path == "/add")
                {
                    int a = 0, b = 0;
                    int.TryParse(context.Request.Query["a"], out a);
                    int.TryParse(context.Request.Query["b"], out b);

                    //var adder = app.ApplicationServices.GetService<IAdder>();
                    await context.Response.WriteAsync(adder.Add(a, b));
                }
                else
                {
                    await context.Response.WriteAsync($"Try again!");
                }
            });

            // Request Info middleware
            app.Run(async ctx =>
            {
                await ctx.Response.WriteAsync($"Path requested: {ctx.Request.Path}");
            });

            //app.Run(async (context) =>
            //{
            //    var msg = $"Current environment: {env.EnvironmentName}";
            //    await context.Response.WriteAsync(msg);
            //});

            //if (env.IsDevelopment())
            //{
            //    app.Run(async (context) =>
            //    {
            //        await context.Response.WriteAsync("Development environment");
            //    });
            //}
            //else
            //{
            //    app.Run(async (context) =>
            //    {
            //        await context.Response.WriteAsync("No development environment");
            //    });
            //}
        }
 public HomeController(IAdder adder)
 {
     AdderFunctionality = adder;
 }
Example #33
0
 public HomeController(IAdder adder, IStringAdditionView stringAdditionView)
 {
     _adder = adder;
     _stringAdditionView = stringAdditionView;
 }
Example #34
0
 /// <summary>
 /// Faster but not as good compaction. Only looks at final codepoint.
 /// </summary>
 /// <param name="source">Set of strings.</param>
 /// <param name="adder">Adds each pair to the output. See the <see cref="IAdder"/> interface.</param>
 /// <param name="shorterPairs">Use abc-d instead of abc-abd.</param>
 public static void Compact(ISet <string> source, IAdder adder, bool shorterPairs)
 {
     Compact(source, adder, shorterPairs, false);
 }
        public static IEnumerable <IWeightedDirectedPath <TVertex, TEdge> > AllSimplePaths <TVertex, TEdge>(
            this IWeightedDirectedGraph <TVertex, TEdge> graph,
            TVertex origin,
            TVertex destination,
            IAdder <TEdge> adder,
            int maxDepth = int.MaxValue
            )
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            if (origin == null)
            {
                throw new ArgumentNullException(nameof(origin));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }
            if (adder == null)
            {
                throw new ArgumentNullException(nameof(adder));
            }

            if (!graph.Vertices.Contains(origin))
            {
                throw new ArgumentException();
            }
            if (!graph.Vertices.Contains(destination))
            {
                throw new ArgumentException();
            }

            var visitedVertices = new Stack <TVertex>();
            var visitedEdges    = new Stack <TEdge>();
            var paths           = new HashSet <IWeightedDirectedPath <TVertex, TEdge> >();

            visitedVertices.Push(origin);

            var stack = new Stack <Tuple <TVertex, Queue <IWeightedEndpoint <TVertex, TEdge> > > >();

            stack.Push(new Tuple <TVertex, Queue <IWeightedEndpoint <TVertex, TEdge> > >(
                           origin,
                           graph.SuccessorEndpoints(origin).ToQueue()
                           ));

            while (stack.Count > 0)
            {
                var(vertex, successorEndpoints) = stack.Peek();

                if (Equals(vertex, destination) || successorEndpoints.Count == 0 || stack.Count > maxDepth)
                {
                    if (Equals(vertex, destination))
                    {
                        var weightedDirectedPath = new WeightedDirectedPath <TVertex, TEdge>(
                            graph,
                            origin,
                            destination,
                            new Stack <TVertex>(visitedVertices),
                            new Stack <TEdge>(visitedEdges),
                            visitedEdges.Aggregate(adder.Add)
                            );

                        paths.Add(weightedDirectedPath);
                    }

                    if (visitedVertices.Count > 0)
                    {
                        visitedVertices.Pop();
                    }
                    if (visitedEdges.Count > 0)
                    {
                        visitedEdges.Pop();
                    }

                    stack.Pop();
                }
                else
                {
                    var successorEndpoint = successorEndpoints.Dequeue();

                    visitedVertices.Push(successorEndpoint.Vertex);
                    visitedEdges.Push(successorEndpoint.Edge);

                    bool Predicate(IWeightedEndpoint <TVertex, TEdge> grandchildEndpoint)
                    {
                        return(!visitedVertices.Contains(grandchildEndpoint.Vertex));
                    }

                    stack.Push(new Tuple <TVertex, Queue <IWeightedEndpoint <TVertex, TEdge> > >(
                                   successorEndpoint.Vertex,
                                   graph.SuccessorEndpoints(successorEndpoint.Vertex).Where(Predicate).ToQueue()
                                   ));
                }
            }

            return(paths);
        }