Don't ignore params and pass them to init as the referenced plug expects (#3409)

defmodule Phoenix.Router do
  defmodule NoRouteError do
    @moduledoc """
    Exception raised when no route is found.
    """
    defexception plug_status: 404, message: "no route found", conn: nil, router: nil

    def exception(opts) do
      conn   = Keyword.fetch!(opts, :conn)
      router = Keyword.fetch!(opts, :router)
      path   = "/" <> Enum.join(conn.path_info, "/")

      %NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
                    conn: conn, router: router}
    end
  end

  @moduledoc """
  Defines a Phoenix router.

  The router provides a set of macros for generating routes
  that dispatch to specific controllers and actions. Those
  macros are named after HTTP verbs. For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        get "/pages/:page", PageController, :show
      end

  The `get/3` macro above accepts a request of format `"/pages/VALUE"` and
  dispatches it to the show action in the `PageController`.

  Routes can also match glob-like patterns, routing any path with a common
  base to the same controller. For example:

      get "/dynamic*anything", DynamicController, :show

  Phoenix's router is extremely efficient, as it relies on Elixir
  pattern matching for matching routes and serving requests.

  ## Helpers

  Phoenix automatically generates a module `Helpers` inside your router
  which contains named helpers to help developers generate and keep
  their routes up to date.

  Helpers are automatically generated based on the controller name.
  For example, the route:

      get "/pages/:page", PageController, :show

  will generate the following named helper:

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
      "/pages/hello"

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
      "/pages/hello?some=query"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
      "http://example.com/pages/hello"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
      "http://example.com/pages/hello?some=query"

  If the route contains glob-like patterns, parameters for those have to be given as
  list:

      MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
      "/dynamic/something"

  The URL generated in the named URL helpers is based on the configuration for
  `:url`, `:http` and `:https`. However, if for some reason you need to manually
  control the URL generation, the url helpers also allow you to pass in a `URI`
  struct:

      uri = %URI{scheme: "https", host: "other.example.com"}
      MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
      "https://other.example.com/pages/hello"

  The named helper can also be customized with the `:as` option. Given
  the route:

      get "/pages/:page", PageController, :show, as: :special_page

  the named helper will be:

      MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
      "/pages/hello"

  ## Scopes and Resources

  It is very common in Phoenix applications to namespace all of your
  routes under the application scope:

      scope "/", MyAppWeb do
        get "/pages/:id", PageController, :show
      end

  The route above will dispatch to `MyAppWeb.PageController`. This syntax
  is not only convenient for developers, since we don't have to repeat
  the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put
  less pressure on the Elixir compiler. If instead we had written:

      get "/pages/:id", MyAppWeb.PageController, :show

  The Elixir compiler would infer that the router depends directly on
  `MyAppWeb.PageController`, which is not true. By using scopes, Phoenix
  can properly hint to the Elixir compiler the controller is not an
  actual dependency of the router. This provides more efficient
  compilation times.

  Scopes allow us to scope on any path or even on the helper name:

      scope "/api/v1", MyAppWeb, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  For example, the route above will match on the path `"/api/v1/pages/:id"`
  and the named route will be `api_v1_page_path`, as expected from the
  values given to `scope/2` option.

  Phoenix also provides a `resources/4` macro that allows developers
  to generate "RESTful" routes to a given resource:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        resources "/pages", PageController, only: [:show]
        resources "/users", UserController, except: [:delete]
      end

  Finally, Phoenix ships with a `mix phx.routes` task that nicely
  formats all routes in a given router. We can use it to verify all
  routes included in the router above:

      $ mix phx.routes
      page_path  GET    /pages/:id       PageController.show/2
      user_path  GET    /users           UserController.index/2
      user_path  GET    /users/:id/edit  UserController.edit/2
      user_path  GET    /users/new       UserController.new/2
      user_path  GET    /users/:id       UserController.show/2
      user_path  POST   /users           UserController.create/2
      user_path  PATCH  /users/:id       UserController.update/2
                 PUT    /users/:id       UserController.update/2

  One can also pass a router explicitly as an argument to the task:

      $ mix phx.routes MyAppWeb.Router

  Check `scope/2` and `resources/4` for more information.

  ## Pipelines and plugs

  Once a request arrives at the Phoenix router, it performs
  a series of transformations through pipelines until the
  request is dispatched to a desired end-point.

  Such transformations are defined via plugs, as defined
  in the [Plug](http://github.com/elixir-lang/plug) specification.
  Once a pipeline is defined, it can be piped through per scope.

  For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        pipeline :browser do
          plug :fetch_session
          plug :accepts, ["html"]
        end

        scope "/" do
          pipe_through :browser

          # browser related routes and resources
        end
      end

  `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
  to help define plugs. In the example above, `fetch_session/2`
  comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.

  Note that router pipelines are only invoked after a route is found.
  No plug is invoked in case no matches were found.
  """

  alias Phoenix.Router.{Resource, Scope, Route, Helpers}

  @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]

  @doc false
  defmacro __using__(_) do
    quote do
      unquote(prelude())
      unquote(defs())
      unquote(match_dispatch())
    end
  end

  defp prelude() do
    quote do
      Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
      @phoenix_forwards %{}

      import Phoenix.Router

      # TODO v2: No longer automatically import dependencies
      import Plug.Conn
      import Phoenix.Controller

      # Set up initial scope
      @phoenix_pipeline nil
      Phoenix.Router.Scope.init(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  # Because those macros are executed multiple times,
  # we end-up generating a huge scope that drastically
  # affects compilation. We work around it by defining
  # those functions only once and calling it over and
  # over again.
  defp defs() do
    quote unquote: false do
      var!(add_resources, Phoenix.Router) = fn resource ->
        path = resource.path
        ctrl = resource.controller
        opts = resource.route

        if resource.singleton do
          Enum.each resource.actions, fn
            :show    -> get    path,            ctrl, :show, opts
            :new     -> get    path <> "/new",  ctrl, :new, opts
            :edit    -> get    path <> "/edit", ctrl, :edit, opts
            :create  -> post   path,            ctrl, :create, opts
            :delete  -> delete path,            ctrl, :delete, opts
            :update  ->
              patch path, ctrl, :update, opts
              put   path, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        else
          param = resource.param

          Enum.each resource.actions, fn
            :index   -> get    path,                             ctrl, :index, opts
            :show    -> get    path <> "/:" <> param,            ctrl, :show, opts
            :new     -> get    path <> "/new",                   ctrl, :new, opts
            :edit    -> get    path <> "/:" <> param <> "/edit", ctrl, :edit, opts
            :create  -> post   path,                             ctrl, :create, opts
            :delete  -> delete path <> "/:" <> param,            ctrl, :delete, opts
            :update  ->
              patch path <> "/:" <> param, ctrl, :update, opts
              put   path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        end
      end
    end
  end

  @doc false
  def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do
    Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
  end
  def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do
    conn
  end
  def __call__({conn, pipeline, {plug, opts}}) do
    case pipeline.(conn) do
      %Plug.Conn{halted: true} = halted_conn ->
        halted_conn
      %Plug.Conn{} = piped_conn ->
        try do
          plug.call(piped_conn, plug.init(opts))
        rescue
          e in Plug.Conn.WrapperError ->
            Plug.Conn.WrapperError.reraise(e)
        catch
          :error, reason ->
            Plug.Conn.WrapperError.reraise(piped_conn, :error, reason, System.stacktrace())
        end
    end
  end

  defp match_dispatch() do
    quote location: :keep do
      @behaviour Plug

      @doc """
      Callback required by Plug that initializes the router
      for serving web requests.
      """
      def init(opts) do
        opts
      end

      @doc """
      Callback invoked by Plug on every request.
      """
      def call(conn, _opts) do
        conn
        |> prepare()
        |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host)
        |> Phoenix.Router.__call__()
      end

      defoverridable [init: 1, call: 2]
    end
  end

  @anno (if :erlang.system_info(:otp_release) >= '19' do
    [generated: true]
  else
    [line: -1]
  end)

  @doc false
  defmacro __before_compile__(env) do
    routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
    routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})

    Helpers.define(env, routes_with_exprs)
    {matches, _} = Enum.map_reduce(routes_with_exprs, %{}, &build_match/2)

    checks =
      for {%{line: line}, %{dispatch: {plug, params}}} <- routes_with_exprs, into: %{} do
        quote line: line do
          {unquote(plug).init(unquote(params)), true}
        end
      end

    # @anno is used here to avoid warnings if forwarding to root path
    match_404 =
      quote @anno do
        def __match_route__(conn, _method, _path_info, _host) do
          raise NoRouteError, conn: conn, router: __MODULE__
        end
      end

    quote do
      @doc false
      def __routes__,  do: unquote(Macro.escape(routes))

      @doc false
      def __checks__, do: unquote({:__block__, [], Map.keys(checks)})

      @doc false
      def __helpers__, do: __MODULE__.Helpers

      defp prepare(conn) do
        update_in conn.private,
          &(&1
            |> Map.put(:phoenix_router, __MODULE__)
            |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
      end

      unquote(matches)
      unquote(match_404)
    end
  end

  defp build_match({route, exprs}, known_pipelines) do
    %{pipe_through: pipe_through} = route

    %{
      prepare: prepare,
      dispatch: dispatch,
      verb_match: verb_match,
      path: path,
      host: host
    } = exprs

    {pipe_name, pipe_definition, known_pipelines} =
      case known_pipelines do
        %{^pipe_through => name} ->
          {name, :ok, known_pipelines}

        %{} ->
          name = :"__pipe_through#{map_size(known_pipelines)}__"
          {name, build_pipes(name, pipe_through), Map.put(known_pipelines, pipe_through, name)}
      end

    quoted =
      quote line: route.line do
        unquote(pipe_definition)

        @doc false
        def __match_route__(var!(conn), unquote(verb_match), unquote(path), unquote(host)) do
          {unquote(prepare), &unquote(Macro.var(pipe_name, __MODULE__))/1, unquote(dispatch)}
        end
      end

    {quoted, known_pipelines}
  end

  defp build_pipes(name, []) do
    quote do
      defp unquote(name)(conn) do
        Plug.Conn.put_private(conn, :phoenix_pipelines, [])
      end
    end
  end

  defp build_pipes(name, pipe_through) do
    plugs = pipe_through |> Enum.reverse |> Enum.map(&{&1, [], true})
    {conn, body} = Plug.Builder.compile(__ENV__, plugs, init_mode: Phoenix.plug_init_mode())

    quote do
      defp unquote(name)(unquote(conn)) do
        unquote(conn) = Plug.Conn.put_private(unquote(conn), :phoenix_pipelines, unquote(pipe_through))
        unquote(body)
      end
    end
  end

  @doc """
  Generates a route match based on an arbitrary HTTP method.

  Useful for defining routes not included in the builtin macros:

  #{Enum.map_join(@http_methods, ", ", &"`#{&1}`")}

  The catch-all verb, `:*`, may also be used to match all HTTP methods.

  ## Examples

      match(:move, "/events/:id", EventController, :move)

      match(:*, "/any", SomeController, :any)

  """
  defmacro match(verb, path, plug, plug_opts, options \\ []) do
    add_route(:match, verb, path, plug, plug_opts, options)
  end

  for verb <- @http_methods do
    @doc """
    Generates a route to handle a #{verb} request to the given path.
    """
    defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
      add_route(:match, unquote(verb), path, plug, plug_opts, options)
    end
  end

  defp add_route(kind, verb, path, plug, plug_opts, options) do
    quote do
      @phoenix_routes Scope.route(
        __ENV__.line,
        __ENV__.module,
        unquote(kind),
        unquote(verb),
        unquote(path),
        unquote(plug),
        unquote(plug_opts),
        unquote(options)
      )
    end
  end

  @doc """
  Defines a plug pipeline.

  Pipelines are defined at the router root and can be used
  from any scope.

  ## Examples

      pipeline :api do
        plug :token_authentication
        plug :dispatch
      end

  A scope may then use this pipeline as:

      scope "/" do
        pipe_through :api
      end

  Every time `pipe_through/1` is called, the new pipelines
  are appended to the ones previously given.
  """
  defmacro pipeline(plug, do: block) do
    block =
      quote do
        plug = unquote(plug)
        @phoenix_pipeline []
        unquote(block)
      end

    compiler =
      quote unquote: false do
        Scope.pipeline(__MODULE__, plug)
        {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline,
          init_mode: Phoenix.plug_init_mode())

        def unquote(plug)(unquote(conn), _) do
          try do
            unquote(body)
          rescue
            e in Plug.Conn.WrapperError ->
              Plug.Conn.WrapperError.reraise(e)
          catch
            :error, reason ->
              Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason, System.stacktrace())
          end
        end
        @phoenix_pipeline nil
      end

    quote do
      try do
        unquote(block)
        unquote(compiler)
      after
        :ok
      end
    end
  end

  @doc """
  Defines a plug inside a pipeline.

  See `pipeline/2` for more information.
  """
  defmacro plug(plug, opts \\ []) do
    quote do
      if pipeline = @phoenix_pipeline do
        @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
      else
        raise "cannot define plug at the router level, plug must be defined inside a pipeline"
      end
    end
  end

  @doc """
  Defines a pipeline to send the connection through.

  See `pipeline/2` for more information.
  """
  defmacro pipe_through(pipes) do
    quote do
      if pipeline = @phoenix_pipeline do
        raise "cannot pipe_through inside a pipeline"
      else
        Scope.pipe_through(__MODULE__, unquote(pipes))
      end
    end
  end

  @doc """
  Defines "RESTful" routes for a resource.

  The given definition:

      resources "/users", UserController

  will include routes to the following actions:

    * `GET /users` => `:index`
    * `GET /users/new` => `:new`
    * `POST /users` => `:create`
    * `GET /users/:id` => `:show`
    * `GET /users/:id/edit` => `:edit`
    * `PATCH /users/:id` => `:update`
    * `PUT /users/:id` => `:update`
    * `DELETE /users/:id` => `:delete`

  ## Options

  This macro accepts a set of options:

    * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
    * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
    * `:param` - the name of the parameter for this resource, defaults to `"id"`
    * `:name` - the prefix for this resource. This is used for the named helper
      and as the prefix for the parameter in nested resources. The default value
      is automatically derived from the controller name, i.e. `UserController` will
      have name `"user"`
    * `:as` - configures the named helper exclusively
    * `:singleton` - defines routes for a singleton resource that is looked up by
      the client without referencing an ID. Read below for more information

  ## Singleton resources

  When a resource needs to be looked up without referencing an ID, because
  it contains only a single entry in the given context, the `:singleton`
  option can be used to generate a set of routes that are specific to
  such single resource:

    * `GET /user` => `:show`
    * `GET /user/new` => `:new`
    * `POST /user` => `:create`
    * `GET /user/edit` => `:edit`
    * `PATCH /user` => `:update`
    * `PUT /user` => `:update`
    * `DELETE /user` => `:delete`

  Usage example:

      resources "/account", AccountController, only: [:show], singleton: true

  ## Nested Resources

  This macro also supports passing a nested block of route definitions.
  This is helpful for nesting children resources within their parents to
  generate nested routes.

  The given definition:

      resources "/users", UserController do
        resources "/posts", PostController
      end

  will include the following routes:

      user_post_path  GET     /users/:user_id/posts           PostController :index
      user_post_path  GET     /users/:user_id/posts/:id/edit  PostController :edit
      user_post_path  GET     /users/:user_id/posts/new       PostController :new
      user_post_path  GET     /users/:user_id/posts/:id       PostController :show
      user_post_path  POST    /users/:user_id/posts           PostController :create
      user_post_path  PATCH   /users/:user_id/posts/:id       PostController :update
                      PUT     /users/:user_id/posts/:id       PostController :update
      user_post_path  DELETE  /users/:user_id/posts/:id       PostController :delete

  """
  defmacro resources(path, controller, opts, do: nested_context) do
    add_resources path, controller, opts, do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, do: nested_context) do
    add_resources path, controller, [], do: nested_context
  end

  defmacro resources(path, controller, opts) do
    add_resources path, controller, opts, do: nil
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller) do
    add_resources path, controller, [], do: nil
  end

  defp add_resources(path, controller, options, do: context) do
    scope =
      if context do
        quote do
          scope resource.member, do: unquote(context)
        end
      end

    quote do
      resource = Resource.build(unquote(path), unquote(controller), unquote(options))
      var!(add_resources, Phoenix.Router).(resource)
      unquote(scope)
    end
  end

  @doc """
  Defines a scope in which routes can be nested.

  ## Examples

      scope path: "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  The generated route above will match on the path `"/api/v1/pages/:id"`
  and will dispatch to `:show` action in `API.V1.PageController`. A named
  helper `api_v1_page_path` will also be generated.

  ## Options

  The supported options are:

    * `:path` - a string containing the path scope
    * `:as` - a string or atom containing the named helper scope
    * `:alias` - an alias (atom) containing the controller scope.
      When set, this value may be overridden per route by passing `alias: false`
      to route definitions, such as `get`, `post`, etc.
    * `:host` - a string containing the host scope, or prefix host scope,
      ie `"foo.bar.com"`, `"foo."`
    * `:private` - a map of private data to merge into the connection when a route matches
    * `:assigns` - a map of data to merge into the connection when a route matches

  """
  defmacro scope(options, do: context) do
    do_scope(options, context)
  end

  @doc """
  Define a scope with the given path.

  This function is a shortcut for:

      scope path: path do
        ...
      end

  ## Examples

      scope "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, options, do: context) do
    options = quote do
      path = unquote(path)
      case unquote(options) do
        alias when is_atom(alias) -> [path: path, alias: alias]
        options when is_list(options) -> Keyword.put(options, :path, path)
      end
    end
    do_scope(options, context)
  end

  @doc """
  Defines a scope with the given path and alias.

  This function is a shortcut for:

      scope path: path, alias: alias do
        ...
      end

  ## Examples

      scope "/api/v1", API.V1, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, alias, options, do: context) do
    options = quote do
      unquote(options)
      |> Keyword.put(:path, unquote(path))
      |> Keyword.put(:alias, unquote(alias))
    end
    do_scope(options, context)
  end

  defp do_scope(options, context) do
    quote do
      Scope.push(__MODULE__, unquote(options))
      try do
        unquote(context)
      after
        Scope.pop(__MODULE__)
      end
    end
  end

  @doc """
  Returns the full alias with the current scope's aliased prefix.

  Useful for applying the same short-hand alias handling to
  other values besides the second argument in route definitions.

  ## Examples

      scope "/", MyPrefix do
        get "/", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)
      end
  """
  def scoped_alias(router_module, alias) do
    Scope.expand_alias(router_module, alias)
  end

  @doc """
  Forwards a request at the given path to a plug.

  All paths that match the forwarded prefix will be sent to
  the forwarded plug. This is useful for sharing a router between
  applications or even breaking a big router into smaller ones.
  The router pipelines will be invoked prior to forwarding the
  connection.

  The forwarded plug will be initialized at compile time.

  Note, however, that we don't advise forwarding to another
  endpoint. The reason is that plugs defined by your app
  and the forwarded endpoint would be invoked twice, which
  may lead to errors.

  ## Examples

      scope "/", MyApp do
        pipe_through [:browser, :admin]

        forward "/admin", SomeLib.AdminDashboard
        forward "/api", ApiRouter
      end

  """
  defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
    router_opts = Keyword.put(router_opts, :as, nil)

    quote unquote: true, bind_quoted: [path: path, plug: plug] do
      plug = Scope.register_forwards(__MODULE__, path, plug)
      unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
    end
  end
end

defmodule Phoenix.Router do
  defmodule NoRouteError do
    @moduledoc """
    Exception raised when no route is found.
    """
    defexception plug_status: 404, message: "no route found", conn: nil, router: nil

    def exception(opts) do
      conn   = Keyword.fetch!(opts, :conn)
      router = Keyword.fetch!(opts, :router)
      path   = "/" <> Enum.join(conn.path_info, "/")

      %NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
                    conn: conn, router: router}
    end
  end

  @moduledoc """
  Defines a Phoenix router.

  The router provides a set of macros for generating routes
  that dispatch to specific controllers and actions. Those
  macros are named after HTTP verbs. For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        get "/pages/:page", PageController, :show
      end

  The `get/3` macro above accepts a request of format `"/pages/VALUE"` and
  dispatches it to the show action in the `PageController`.

  Routes can also match glob-like patterns, routing any path with a common
  base to the same controller. For example:

      get "/dynamic*anything", DynamicController, :show

  Phoenix's router is extremely efficient, as it relies on Elixir
  pattern matching for matching routes and serving requests.

  ## Helpers

  Phoenix automatically generates a module `Helpers` inside your router
  which contains named helpers to help developers generate and keep
  their routes up to date.

  Helpers are automatically generated based on the controller name.
  For example, the route:

      get "/pages/:page", PageController, :show

  will generate the following named helper:

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
      "/pages/hello"

      MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
      "/pages/hello?some=query"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
      "http://example.com/pages/hello"

      MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
      "http://example.com/pages/hello?some=query"

  If the route contains glob-like patterns, parameters for those have to be given as
  list:

      MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
      "/dynamic/something"

  The URL generated in the named URL helpers is based on the configuration for
  `:url`, `:http` and `:https`. However, if for some reason you need to manually
  control the URL generation, the url helpers also allow you to pass in a `URI`
  struct:

      uri = %URI{scheme: "https", host: "other.example.com"}
      MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
      "https://other.example.com/pages/hello"

  The named helper can also be customized with the `:as` option. Given
  the route:

      get "/pages/:page", PageController, :show, as: :special_page

  the named helper will be:

      MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
      "/pages/hello"

  ## Scopes and Resources

  It is very common in Phoenix applications to namespace all of your
  routes under the application scope:

      scope "/", MyAppWeb do
        get "/pages/:id", PageController, :show
      end

  The route above will dispatch to `MyAppWeb.PageController`. This syntax
  is not only convenient for developers, since we don't have to repeat
  the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put
  less pressure on the Elixir compiler. If instead we had written:

      get "/pages/:id", MyAppWeb.PageController, :show

  The Elixir compiler would infer that the router depends directly on
  `MyAppWeb.PageController`, which is not true. By using scopes, Phoenix
  can properly hint to the Elixir compiler the controller is not an
  actual dependency of the router. This provides more efficient
  compilation times.

  Scopes allow us to scope on any path or even on the helper name:

      scope "/api/v1", MyAppWeb, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  For example, the route above will match on the path `"/api/v1/pages/:id"`
  and the named route will be `api_v1_page_path`, as expected from the
  values given to `scope/2` option.

  Phoenix also provides a `resources/4` macro that allows developers
  to generate "RESTful" routes to a given resource:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        resources "/pages", PageController, only: [:show]
        resources "/users", UserController, except: [:delete]
      end

  Finally, Phoenix ships with a `mix phx.routes` task that nicely
  formats all routes in a given router. We can use it to verify all
  routes included in the router above:

      $ mix phx.routes
      page_path  GET    /pages/:id       PageController.show/2
      user_path  GET    /users           UserController.index/2
      user_path  GET    /users/:id/edit  UserController.edit/2
      user_path  GET    /users/new       UserController.new/2
      user_path  GET    /users/:id       UserController.show/2
      user_path  POST   /users           UserController.create/2
      user_path  PATCH  /users/:id       UserController.update/2
                 PUT    /users/:id       UserController.update/2

  One can also pass a router explicitly as an argument to the task:

      $ mix phx.routes MyAppWeb.Router

  Check `scope/2` and `resources/4` for more information.

  ## Pipelines and plugs

  Once a request arrives at the Phoenix router, it performs
  a series of transformations through pipelines until the
  request is dispatched to a desired end-point.

  Such transformations are defined via plugs, as defined
  in the [Plug](http://github.com/elixir-lang/plug) specification.
  Once a pipeline is defined, it can be piped through per scope.

  For example:

      defmodule MyAppWeb.Router do
        use Phoenix.Router

        pipeline :browser do
          plug :fetch_session
          plug :accepts, ["html"]
        end

        scope "/" do
          pipe_through :browser

          # browser related routes and resources
        end
      end

  `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
  to help define plugs. In the example above, `fetch_session/2`
  comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.

  Note that router pipelines are only invoked after a route is found.
  No plug is invoked in case no matches were found.
  """

  alias Phoenix.Router.{Resource, Scope, Route, Helpers}

  @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]

  @doc false
  defmacro __using__(_) do
    quote do
      unquote(prelude())
      unquote(defs())
      unquote(match_dispatch())
    end
  end

  defp prelude() do
    quote do
      Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
      @phoenix_forwards %{}

      import Phoenix.Router

      # TODO v2: No longer automatically import dependencies
      import Plug.Conn
      import Phoenix.Controller

      # Set up initial scope
      @phoenix_pipeline nil
      Phoenix.Router.Scope.init(__MODULE__)
      @before_compile unquote(__MODULE__)
    end
  end

  # Because those macros are executed multiple times,
  # we end-up generating a huge scope that drastically
  # affects compilation. We work around it by defining
  # those functions only once and calling it over and
  # over again.
  defp defs() do
    quote unquote: false do
      var!(add_resources, Phoenix.Router) = fn resource ->
        path = resource.path
        ctrl = resource.controller
        opts = resource.route

        if resource.singleton do
          Enum.each resource.actions, fn
            :show    -> get    path,            ctrl, :show, opts
            :new     -> get    path <> "/new",  ctrl, :new, opts
            :edit    -> get    path <> "/edit", ctrl, :edit, opts
            :create  -> post   path,            ctrl, :create, opts
            :delete  -> delete path,            ctrl, :delete, opts
            :update  ->
              patch path, ctrl, :update, opts
              put   path, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        else
          param = resource.param

          Enum.each resource.actions, fn
            :index   -> get    path,                             ctrl, :index, opts
            :show    -> get    path <> "/:" <> param,            ctrl, :show, opts
            :new     -> get    path <> "/new",                   ctrl, :new, opts
            :edit    -> get    path <> "/:" <> param <> "/edit", ctrl, :edit, opts
            :create  -> post   path,                             ctrl, :create, opts
            :delete  -> delete path <> "/:" <> param,            ctrl, :delete, opts
            :update  ->
              patch path <> "/:" <> param, ctrl, :update, opts
              put   path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
          end
        end
      end
    end
  end

  @doc false
  def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do
    Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
  end
  def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do
    conn
  end
  def __call__({conn, pipeline, {plug, opts}}) do
    case pipeline.(conn) do
      %Plug.Conn{halted: true} = halted_conn ->
        halted_conn
      %Plug.Conn{} = piped_conn ->
        try do
          plug.call(piped_conn, plug.init(opts))
        rescue
          e in Plug.Conn.WrapperError ->
            Plug.Conn.WrapperError.reraise(e)
        catch
          :error, reason ->
            Plug.Conn.WrapperError.reraise(piped_conn, :error, reason, System.stacktrace())
        end
    end
  end

  defp match_dispatch() do
    quote location: :keep do
      @behaviour Plug

      @doc """
      Callback required by Plug that initializes the router
      for serving web requests.
      """
      def init(opts) do
        opts
      end

      @doc """
      Callback invoked by Plug on every request.
      """
      def call(conn, _opts) do
        conn
        |> prepare()
        |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host)
        |> Phoenix.Router.__call__()
      end

      defoverridable [init: 1, call: 2]
    end
  end

  @anno (if :erlang.system_info(:otp_release) >= '19' do
    [generated: true]
  else
    [line: -1]
  end)

  @doc false
  defmacro __before_compile__(env) do
    routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
    routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})

    Helpers.define(env, routes_with_exprs)
    {matches, _} = Enum.map_reduce(routes_with_exprs, %{}, &build_match/2)

    checks =
      for {%{line: line}, %{dispatch: {plug, _}}} <- routes_with_exprs, into: %{} do
        quote line: line do
          {unquote(plug).init([]), true}
        end
      end

    # @anno is used here to avoid warnings if forwarding to root path
    match_404 =
      quote @anno do
        def __match_route__(conn, _method, _path_info, _host) do
          raise NoRouteError, conn: conn, router: __MODULE__
        end
      end

    quote do
      @doc false
      def __routes__,  do: unquote(Macro.escape(routes))

      @doc false
      def __checks__, do: unquote({:__block__, [], Map.keys(checks)})

      @doc false
      def __helpers__, do: __MODULE__.Helpers

      defp prepare(conn) do
        update_in conn.private,
          &(&1
            |> Map.put(:phoenix_router, __MODULE__)
            |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
      end

      unquote(matches)
      unquote(match_404)
    end
  end

  defp build_match({route, exprs}, known_pipelines) do
    %{pipe_through: pipe_through} = route

    %{
      prepare: prepare,
      dispatch: dispatch,
      verb_match: verb_match,
      path: path,
      host: host
    } = exprs

    {pipe_name, pipe_definition, known_pipelines} =
      case known_pipelines do
        %{^pipe_through => name} ->
          {name, :ok, known_pipelines}

        %{} ->
          name = :"__pipe_through#{map_size(known_pipelines)}__"
          {name, build_pipes(name, pipe_through), Map.put(known_pipelines, pipe_through, name)}
      end

    quoted =
      quote line: route.line do
        unquote(pipe_definition)

        @doc false
        def __match_route__(var!(conn), unquote(verb_match), unquote(path), unquote(host)) do
          {unquote(prepare), &unquote(Macro.var(pipe_name, __MODULE__))/1, unquote(dispatch)}
        end
      end

    {quoted, known_pipelines}
  end

  defp build_pipes(name, []) do
    quote do
      defp unquote(name)(conn) do
        Plug.Conn.put_private(conn, :phoenix_pipelines, [])
      end
    end
  end

  defp build_pipes(name, pipe_through) do
    plugs = pipe_through |> Enum.reverse |> Enum.map(&{&1, [], true})
    {conn, body} = Plug.Builder.compile(__ENV__, plugs, init_mode: Phoenix.plug_init_mode())

    quote do
      defp unquote(name)(unquote(conn)) do
        unquote(conn) = Plug.Conn.put_private(unquote(conn), :phoenix_pipelines, unquote(pipe_through))
        unquote(body)
      end
    end
  end

  @doc """
  Generates a route match based on an arbitrary HTTP method.

  Useful for defining routes not included in the builtin macros:

  #{Enum.map_join(@http_methods, ", ", &"`#{&1}`")}

  The catch-all verb, `:*`, may also be used to match all HTTP methods.

  ## Examples

      match(:move, "/events/:id", EventController, :move)

      match(:*, "/any", SomeController, :any)

  """
  defmacro match(verb, path, plug, plug_opts, options \\ []) do
    add_route(:match, verb, path, plug, plug_opts, options)
  end

  for verb <- @http_methods do
    @doc """
    Generates a route to handle a #{verb} request to the given path.
    """
    defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
      add_route(:match, unquote(verb), path, plug, plug_opts, options)
    end
  end

  defp add_route(kind, verb, path, plug, plug_opts, options) do
    quote do
      @phoenix_routes Scope.route(
        __ENV__.line,
        __ENV__.module,
        unquote(kind),
        unquote(verb),
        unquote(path),
        unquote(plug),
        unquote(plug_opts),
        unquote(options)
      )
    end
  end

  @doc """
  Defines a plug pipeline.

  Pipelines are defined at the router root and can be used
  from any scope.

  ## Examples

      pipeline :api do
        plug :token_authentication
        plug :dispatch
      end

  A scope may then use this pipeline as:

      scope "/" do
        pipe_through :api
      end

  Every time `pipe_through/1` is called, the new pipelines
  are appended to the ones previously given.
  """
  defmacro pipeline(plug, do: block) do
    block =
      quote do
        plug = unquote(plug)
        @phoenix_pipeline []
        unquote(block)
      end

    compiler =
      quote unquote: false do
        Scope.pipeline(__MODULE__, plug)
        {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline,
          init_mode: Phoenix.plug_init_mode())

        def unquote(plug)(unquote(conn), _) do
          try do
            unquote(body)
          rescue
            e in Plug.Conn.WrapperError ->
              Plug.Conn.WrapperError.reraise(e)
          catch
            :error, reason ->
              Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason, System.stacktrace())
          end
        end
        @phoenix_pipeline nil
      end

    quote do
      try do
        unquote(block)
        unquote(compiler)
      after
        :ok
      end
    end
  end

  @doc """
  Defines a plug inside a pipeline.

  See `pipeline/2` for more information.
  """
  defmacro plug(plug, opts \\ []) do
    quote do
      if pipeline = @phoenix_pipeline do
        @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
      else
        raise "cannot define plug at the router level, plug must be defined inside a pipeline"
      end
    end
  end

  @doc """
  Defines a pipeline to send the connection through.

  See `pipeline/2` for more information.
  """
  defmacro pipe_through(pipes) do
    quote do
      if pipeline = @phoenix_pipeline do
        raise "cannot pipe_through inside a pipeline"
      else
        Scope.pipe_through(__MODULE__, unquote(pipes))
      end
    end
  end

  @doc """
  Defines "RESTful" routes for a resource.

  The given definition:

      resources "/users", UserController

  will include routes to the following actions:

    * `GET /users` => `:index`
    * `GET /users/new` => `:new`
    * `POST /users` => `:create`
    * `GET /users/:id` => `:show`
    * `GET /users/:id/edit` => `:edit`
    * `PATCH /users/:id` => `:update`
    * `PUT /users/:id` => `:update`
    * `DELETE /users/:id` => `:delete`

  ## Options

  This macro accepts a set of options:

    * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
    * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
    * `:param` - the name of the parameter for this resource, defaults to `"id"`
    * `:name` - the prefix for this resource. This is used for the named helper
      and as the prefix for the parameter in nested resources. The default value
      is automatically derived from the controller name, i.e. `UserController` will
      have name `"user"`
    * `:as` - configures the named helper exclusively
    * `:singleton` - defines routes for a singleton resource that is looked up by
      the client without referencing an ID. Read below for more information

  ## Singleton resources

  When a resource needs to be looked up without referencing an ID, because
  it contains only a single entry in the given context, the `:singleton`
  option can be used to generate a set of routes that are specific to
  such single resource:

    * `GET /user` => `:show`
    * `GET /user/new` => `:new`
    * `POST /user` => `:create`
    * `GET /user/edit` => `:edit`
    * `PATCH /user` => `:update`
    * `PUT /user` => `:update`
    * `DELETE /user` => `:delete`

  Usage example:

      resources "/account", AccountController, only: [:show], singleton: true

  ## Nested Resources

  This macro also supports passing a nested block of route definitions.
  This is helpful for nesting children resources within their parents to
  generate nested routes.

  The given definition:

      resources "/users", UserController do
        resources "/posts", PostController
      end

  will include the following routes:

      user_post_path  GET     /users/:user_id/posts           PostController :index
      user_post_path  GET     /users/:user_id/posts/:id/edit  PostController :edit
      user_post_path  GET     /users/:user_id/posts/new       PostController :new
      user_post_path  GET     /users/:user_id/posts/:id       PostController :show
      user_post_path  POST    /users/:user_id/posts           PostController :create
      user_post_path  PATCH   /users/:user_id/posts/:id       PostController :update
                      PUT     /users/:user_id/posts/:id       PostController :update
      user_post_path  DELETE  /users/:user_id/posts/:id       PostController :delete

  """
  defmacro resources(path, controller, opts, do: nested_context) do
    add_resources path, controller, opts, do: nested_context
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller, do: nested_context) do
    add_resources path, controller, [], do: nested_context
  end

  defmacro resources(path, controller, opts) do
    add_resources path, controller, opts, do: nil
  end

  @doc """
  See `resources/4`.
  """
  defmacro resources(path, controller) do
    add_resources path, controller, [], do: nil
  end

  defp add_resources(path, controller, options, do: context) do
    scope =
      if context do
        quote do
          scope resource.member, do: unquote(context)
        end
      end

    quote do
      resource = Resource.build(unquote(path), unquote(controller), unquote(options))
      var!(add_resources, Phoenix.Router).(resource)
      unquote(scope)
    end
  end

  @doc """
  Defines a scope in which routes can be nested.

  ## Examples

      scope path: "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  The generated route above will match on the path `"/api/v1/pages/:id"`
  and will dispatch to `:show` action in `API.V1.PageController`. A named
  helper `api_v1_page_path` will also be generated.

  ## Options

  The supported options are:

    * `:path` - a string containing the path scope
    * `:as` - a string or atom containing the named helper scope
    * `:alias` - an alias (atom) containing the controller scope.
      When set, this value may be overridden per route by passing `alias: false`
      to route definitions, such as `get`, `post`, etc.
    * `:host` - a string containing the host scope, or prefix host scope,
      ie `"foo.bar.com"`, `"foo."`
    * `:private` - a map of private data to merge into the connection when a route matches
    * `:assigns` - a map of data to merge into the connection when a route matches

  """
  defmacro scope(options, do: context) do
    do_scope(options, context)
  end

  @doc """
  Define a scope with the given path.

  This function is a shortcut for:

      scope path: path do
        ...
      end

  ## Examples

      scope "/api/v1", as: :api_v1, alias: API.V1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, options, do: context) do
    options = quote do
      path = unquote(path)
      case unquote(options) do
        alias when is_atom(alias) -> [path: path, alias: alias]
        options when is_list(options) -> Keyword.put(options, :path, path)
      end
    end
    do_scope(options, context)
  end

  @doc """
  Defines a scope with the given path and alias.

  This function is a shortcut for:

      scope path: path, alias: alias do
        ...
      end

  ## Examples

      scope "/api/v1", API.V1, as: :api_v1 do
        get "/pages/:id", PageController, :show
      end

  """
  defmacro scope(path, alias, options, do: context) do
    options = quote do
      unquote(options)
      |> Keyword.put(:path, unquote(path))
      |> Keyword.put(:alias, unquote(alias))
    end
    do_scope(options, context)
  end

  defp do_scope(options, context) do
    quote do
      Scope.push(__MODULE__, unquote(options))
      try do
        unquote(context)
      after
        Scope.pop(__MODULE__)
      end
    end
  end

  @doc """
  Returns the full alias with the current scope's aliased prefix.

  Useful for applying the same short-hand alias handling to
  other values besides the second argument in route definitions.

  ## Examples

      scope "/", MyPrefix do
        get "/", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)
      end
  """
  def scoped_alias(router_module, alias) do
    Scope.expand_alias(router_module, alias)
  end

  @doc """
  Forwards a request at the given path to a plug.

  All paths that match the forwarded prefix will be sent to
  the forwarded plug. This is useful for sharing a router between
  applications or even breaking a big router into smaller ones.
  The router pipelines will be invoked prior to forwarding the
  connection.

  The forwarded plug will be initialized at compile time.

  Note, however, that we don't advise forwarding to another
  endpoint. The reason is that plugs defined by your app
  and the forwarded endpoint would be invoked twice, which
  may lead to errors.

  ## Examples

      scope "/", MyApp do
        pipe_through [:browser, :admin]

        forward "/admin", SomeLib.AdminDashboard
        forward "/api", ApiRouter
      end

  """
  defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
    router_opts = Keyword.put(router_opts, :as, nil)

    quote unquote: true, bind_quoted: [path: path, plug: plug] do
      plug = Scope.register_forwards(__MODULE__, path, plug)
      unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
    end
  end
end


fix decimals

fix decimals

defmodule Neoscan.Claims.Unclaimed do
  @moduledoc false
  import Ecto.Query, warn: false
  alias Decimal, as: D
  alias Neoscan.Repo
  alias Neoscan.Vouts.Vout
  alias NeoscanMonitor.Api
  alias Neoscan.Blocks.Block

  #total amount of available NEO
  def total_neo, do: 100_000_000
  D.set_context(%D.Context{D.get_context | precision: 10})

  #calculate unclaimed gas bonus
  def calculate_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> add_end_height
    |> route_if_there_is_unclaimed
    |> divide(total_neo())
  end

  defp divide(a, b) do
    a / b
  end

  #calculate unclaimed gas bonus
  def calculate_vouts_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> filter_end_height
    |> route_if_there_is_unclaimed_but_dont_add
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed([]) do
    0
  end
  def route_if_there_is_unclaimed(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.reduce(
      unclaimed,
      0,
      fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end
    )
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed_but_dont_add([]) do
    []
  end
  def route_if_there_is_unclaimed_but_dont_add(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.map(
      unclaimed,
      fn %{:value => value} = vout -> Map.merge(vout, %{
          :unclaimed => compute_vout_bonus(vout, blocks_with_gas),
          :value => round(value),
        }) end
    )
  end

  #compute bonus for a singel vout
  def compute_vout_bonus(
        %{
          :value => value,
          :start_height => start_height,
          :end_height => end_height
        },
        blocks_with_gas
      ) do
    total_gas = Enum.filter(
                  blocks_with_gas,
                  fn %{:index => index} ->
                    index > start_height && index <= end_height end
                )
                |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)

    round(value) * total_gas
  end

  #get all unclaimed transaction vouts
  def get_unclaimed_vouts(address_id) do
    query = from v in Vout,
                 where: v.address_id == ^address_id
                        and v.claimed == false
                        and v.asset == "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
                 select: map(v, [:value, :start_height, :end_height, :n, :txid])

    Repo.all(query)
  end

  def add_end_height(unclaimed_vouts) do
    Enum.map(
      unclaimed_vouts,
      fn %{:end_height => height} = vout ->
        Map.put(vout, :end_height, check_end_height(height)) end
    )
  end

  def filter_end_height(unclaimed_vouts) do
    Enum.filter(
      unclaimed_vouts,
      fn %{:end_height => height} ->
        height != nil end
    )
  end

  #get block range of unclaimed transaction vouts
  def get_unclaimed_block_range(unclaimed_vouts) do
    end_height_list = Enum.map(
      unclaimed_vouts,
      fn %{:end_height => end_height} -> check_end_height(end_height) end
    )

    max = end_height_list
          |> Enum.max

    min = Enum.map(
            unclaimed_vouts,
            fn %{:start_height => start_height} -> start_height end
          )
          |> Enum.min

    {min, max}
  end

  #check end_height and use current height when transaction vout wasn't used
  def check_end_height(nil) do
    {:ok, height} = Api.get_height
    height
  end
  def check_end_height(number) do
    number
  end

  #get total gas distribution amount for all blocks in a given range tuple
  def get_blocks_gas({min, max}) do
    query = from b in Block,
                 where: b.index > ^min and b.index <= ^max,
                 select: map(b, [:index, :total_sys_fee, :gas_generated])

    Repo.all(query)
    |> Enum.map(
         fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->
           sys = sys
                 |> round()

           gen = gen
                 |> round()
           %{:index => index, :gas => sys + gen}
         end
       )
  end

end

defmodule Neoscan.Claims.Unclaimed do
  @moduledoc false
  import Ecto.Query, warn: false
  alias Decimal, as: D
  alias Neoscan.Repo
  alias Neoscan.Vouts.Vout
  alias NeoscanMonitor.Api
  alias Neoscan.Blocks.Block

  #total amount of available NEO
  def total_neo, do: 100_000_000
  D.set_context(%D.Context{D.get_context | precision: 10})

  #calculate unclaimed gas bonus
  def calculate_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> add_end_height
    |> route_if_there_is_unclaimed
    |> divide(total_neo())
  end

  defp divide(a, b) do
    a / b
  end

  #calculate unclaimed gas bonus
  def calculate_vouts_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> filter_end_height
    |> route_if_there_is_unclaimed_but_dont_add
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed([]) do
    0
  end
  def route_if_there_is_unclaimed(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.reduce(
      unclaimed,
      0,
      fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end
    )
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed_but_dont_add([]) do
    []
  end
  def route_if_there_is_unclaimed_but_dont_add(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.map(
      unclaimed,
      fn %{:value => value} = vout -> Map.merge(vout, %{
          :unclaimed => compute_vout_bonus(vout, blocks_with_gas),
          :value => round(value),
        }) end
    )
  end

  #compute bonus for a singel vout
  def compute_vout_bonus(
        %{
          :value => value,
          :start_height => start_height,
          :end_height => end_height
        },
        blocks_with_gas
      ) do
    total_gas = Enum.filter(
                  blocks_with_gas,
                  fn %{:index => index} ->
                    index >= start_height && index <= end_height end
                )
                |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)

    round(value) * total_gas
  end

  #get all unclaimed transaction vouts
  def get_unclaimed_vouts(address_id) do
    query = from v in Vout,
                 where: v.address_id == ^address_id
                        and v.claimed == false
                        and v.asset == "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
                 select: map(v, [:value, :start_height, :end_height, :n, :txid])

    Repo.all(query)
  end

  def add_end_height(unclaimed_vouts) do
    Enum.map(
      unclaimed_vouts,
      fn %{:end_height => height} = vout ->
        Map.put(vout, :end_height, check_end_height(height)) end
    )
  end

  def filter_end_height(unclaimed_vouts) do
    Enum.filter(
      unclaimed_vouts,
      fn %{:end_height => height} ->
        height != nil end
    )
  end

  #get block range of unclaimed transaction vouts
  def get_unclaimed_block_range(unclaimed_vouts) do
    end_height_list = Enum.map(
      unclaimed_vouts,
      fn %{:end_height => end_height} -> check_end_height(end_height) end
    )

    max = end_height_list
          |> Enum.max

    min = Enum.map(
            unclaimed_vouts,
            fn %{:start_height => start_height} -> start_height end
          )
          |> Enum.min

    {min, max}
  end

  #check end_height and use current height when transaction vout wasn't used
  def check_end_height(nil) do
    {:ok, height} = Api.get_height
    height
  end
  def check_end_height(number) do
    number
  end

  #get total gas distribution amount for all blocks in a given range tuple
  def get_blocks_gas({min, max}) do
    query = from b in Block,
                 where: b.index > ^min and b.index <= ^max,
                 select: map(b, [:index, :total_sys_fee, :gas_generated])

    Repo.all(query)
    |> Enum.map(
         fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->
           sys = sys
                 |> round()

           gen = gen
                 |> round()
           %{:index => index, :gas => sys + gen}
         end
       )
  end

end


Added new get active timer action

Added new get active timer action

defmodule PhoenixToggl.TimeEntryActions do
  alias PhoenixToggl.{Repo, TimeEntry}

  @doc """
  Returns the active TimeEntry for a user from the database
  """
  def get_active_for_user(user_id) do
    TimeEntry
    |> TimeEntry.active_for_user(user_id)
    |> Repo.one
  end

  @doc """
  Creates a new TimeEntry
  """
  def start(%{user_id: user_id} = time_entry_params) do
    case get_active_for_user(user_id) do
      nil ->
        perform_start(time_entry_params)
      _time_entry_params ->
        {:error, :active_time_entry_params_exists}
    end
  end

  defp perform_start(time_entry_params) do
    %TimeEntry{}
    |> TimeEntry.start(time_entry_params)
    |> Repo.insert!
  end
end

defmodule PhoenixToggl.TimeEntryActions do
  alias PhoenixToggl.{Repo, TimeEntry}

  def start(%{user_id: user_id} = time_entry_params) do
    TimeEntry
    |> TimeEntry.active_for_user(user_id)
    |> Repo.one
    |> case  do
      nil ->
        perform_start(time_entry_params)
      _time_entry_params ->
        {:error, :active_time_entry_params_exists}
    end
  end

  defp perform_start(time_entry_params) do
    %TimeEntry{}
    |> TimeEntry.start(time_entry_params)
    |> Repo.insert!
  end
end


hotsort /tags

hotsort /tags

defmodule News.TagController do
  use News.Web, :controller

  alias News.Tag
  alias News.Story

  plug :scrub_params, "tag" when action in [:create, :update]
  plug News.Plug.Authenticate, ~w(admin) when action in [:edit, :create, :update, :delete]

  def index(conn, _params) do
    tags = Repo.all from tag in Tag,
      left_join: taggings in assoc(tag, :taggings),
      left_join: story in assoc(taggings, :story),
      group_by: tag.id,
      order_by: fragment("round(cast(log(greatest(abs(?), 1)) * sign(?) + (cast(extract(epoch from ?) as integer) - 1134028003) / 45000.0 as numeric), 7) DESC", sum(story.score), sum(story.score), max(story.inserted_at))
    render(conn, "index.html", tags: tags)
  end

  def show(conn, %{"name" => name}) do
    name = String.downcase(name)
    tag = Repo.one from t in Tag,
      where: fragment("lower(?)", t.name) == ^name,
      preload: [:taggings]
    if tag do
      stories = Repo.all from story in Story,
        left_join: user in assoc(story, :user),
        left_join: comments in assoc(story, :comments),
        left_join: taggings in assoc(story, :taggings),
        left_join: tag in assoc(taggings, :tag),
        left_join: v in News.Vote, on: v.votable_id == story.id and v.votable_type == "story",
        where: taggings.tag_id == ^tag.id and story.score > 0,
        order_by: fragment("LOG(10,ABS(?)+1)*SIGN(?) + cast(extract(epoch from ?) as integer)/300000 DESC", story.score, story.score, story.inserted_at),
        preload: [user: user, tags: tag, comments: comments, votes: v]
      conn
        |> assign(:title, tag.name)
        |> render("show.html", tag: tag, stories: stories)
    else
      error_not_found conn
    end
  end

  def edit(conn, %{"id" => id}) do
    tag = Repo.get!(Tag, id)
    changeset = Tag.changeset(tag)
    render(conn, "edit.html", tag: tag, changeset: changeset)
  end

  def update(conn, %{"id" => id, "tag" => tag_params}) do
    tag = Repo.get!(Tag, id)
    changeset = Tag.changeset(tag, tag_params)

    if changeset.valid? do
      Repo.update!(changeset)

      conn
      |> put_flash(:info, "Tag updated successfully.")
      |> redirect(to: tag_path(conn, :index))
    else
      render(conn, "edit.html", tag: tag, changeset: changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    tag = Repo.get!(Tag, id)
    Repo.delete!(tag)

    conn
    |> put_flash(:info, "Tag deleted successfully.")
    |> redirect(to: tag_path(conn, :index))
  end
end

defmodule News.TagController do
  use News.Web, :controller

  alias News.Tag
  alias News.Story

  plug :scrub_params, "tag" when action in [:create, :update]
  plug News.Plug.Authenticate, ~w(admin) when action in [:edit, :create, :update, :delete]

  def index(conn, _params) do
    tags = Repo.all(Tag)
    render(conn, "index.html", tags: tags)
  end

  def show(conn, %{"name" => name}) do
    name = String.downcase(name)
    tag = Repo.one from t in Tag,
      where: fragment("lower(?)", t.name) == ^name,
      preload: [:taggings]
    if tag do
      stories = Repo.all from story in Story,
        left_join: user in assoc(story, :user),
        left_join: comments in assoc(story, :comments),
        left_join: taggings in assoc(story, :taggings),
        left_join: tag in assoc(taggings, :tag),
        left_join: v in News.Vote, on: v.votable_id == story.id and v.votable_type == "story",
        where: taggings.tag_id == ^tag.id and story.score > 0,
        order_by: fragment("LOG(10,ABS(?)+1)*SIGN(?) + cast(extract(epoch from ?) as integer)/300000 DESC", story.score, story.score, story.inserted_at),
        preload: [user: user, tags: tag, comments: comments, votes: v]
      conn
        |> assign(:title, tag.name)
        |> render("show.html", tag: tag, stories: stories)
    else
      error_not_found conn
    end
  end

  def edit(conn, %{"id" => id}) do
    tag = Repo.get!(Tag, id)
    changeset = Tag.changeset(tag)
    render(conn, "edit.html", tag: tag, changeset: changeset)
  end

  def update(conn, %{"id" => id, "tag" => tag_params}) do
    tag = Repo.get!(Tag, id)
    changeset = Tag.changeset(tag, tag_params)

    if changeset.valid? do
      Repo.update!(changeset)

      conn
      |> put_flash(:info, "Tag updated successfully.")
      |> redirect(to: tag_path(conn, :index))
    else
      render(conn, "edit.html", tag: tag, changeset: changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    tag = Repo.get!(Tag, id)
    Repo.delete!(tag)

    conn
    |> put_flash(:info, "Tag deleted successfully.")
    |> redirect(to: tag_path(conn, :index))
  end
end


Version 0.14.7

Version 0.14.7

docs_task = "tasks/docs.exs"
if File.exists?(docs_task) do
  Code.eval_file "tasks/docs.exs"
end

defmodule ReleaseManager.Mixfile do
  use Mix.Project

  def project do
    [ app: :exrm,
      version: "0.14.7",
      elixir: "~> 1.0.0",
      description: description,
      package: package,
      deps: [{:conform, "~> 0.10.4"}] ]
  end

  def application, do: []

  defp description do
    """
    Exrm, or Elixir Release Manager, provides mix tasks for building,
    upgrading, and controlling release packages for your application.
    """
  end

  defp package do
    [ files: ["lib", "priv", "mix.exs", "README.md", "LICENSE"],
      contributors: ["Paul Schoenfelder"],
      licenses: ["MIT"],
      links: %{ "GitHub": "https://github.com/bitwalker/exrm" } ]
  end

end

docs_task = "tasks/docs.exs"
if File.exists?(docs_task) do
  Code.eval_file "tasks/docs.exs"
end

defmodule ReleaseManager.Mixfile do
  use Mix.Project

  def project do
    [ app: :exrm,
      version: "0.14.6",
      elixir: "~> 1.0.0",
      description: description,
      package: package,
      deps: [{:conform, "~> 0.10.4"}] ]
  end

  def application, do: []

  defp description do
    """
    Exrm, or Elixir Release Manager, provides mix tasks for building,
    upgrading, and controlling release packages for your application.
    """
  end

  defp package do
    [ files: ["lib", "priv", "mix.exs", "README.md", "LICENSE"],
      contributors: ["Paul Schoenfelder"],
      licenses: ["MIT"],
      links: %{ "GitHub": "https://github.com/bitwalker/exrm" } ]
  end

end


Use aliases and explicit parens in mix.exs

defmodule Nerves.Mixfile do
  use Mix.Project

  def project do
    [app: :nerves,
     name: "Nerves",
     source_url: "https://github.com/nerves-project/nerves",
     homepage_url: "http://nerves-project.org/",
     version: "0.3.2",
     elixir: "~> 1.2.4 or ~> 1.3.0-dev",
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     deps: deps(),
     description: description(),
     package: package(),
     aliases: ["docs": ["docs", &copy_images/1]],
     docs: docs()]
  end

  def application do
    []
  end

  defp deps do
    [
      {:exrm, "~> 1.0.4"},
      {:earmark, "~> 0.1", only: :dev},
      {:ex_doc, "~> 0.11", only: :dev},
      {:porcelain, "~> 2.0"}
    ]
  end

  defp docs do
    [main: "getting-started",
     logo: "resources/logo.png",
     extras: [
        "docs/Installation.md",
        "docs/Getting Started.md",
        "docs/Targets.md",
        "docs/Systems.md",
        "docs/User Interfaces.md",
        "docs/Advanced Configuration.md"
    ]]
  end

  # Copy the images referenced by docs, since ex_doc doesn't do this.
  defp copy_images(_) do
    File.cp_r "resources", "doc/resources"
  end

  defp description do
    """
    Nerves - Create firmware for embedded devices like Raspberry Pi, BeagleBone Black, and more
    """
  end

  defp package do
    [maintainers: ["Frank Hunleth", "Garth Hitchens", "Justin Schneck", "Greg Mefford"],
     licenses: ["Apache 2.0"],
     links: %{"Github" => "https://github.com/nerves-project/nerves"}]
  end
end

defmodule Mix.Tasks.CopyImages do
  @shortdoc "Copy the images referenced by docs, since ex_doc doesn't do this."
  use Mix.Task
  def run(_) do
    File.cp_r "resources", "doc/resources"
  end
end

defmodule Nerves.Mixfile do
  use Mix.Project

  def project do
    [app: :nerves,
     name: "Nerves",
     source_url: "https://github.com/nerves-project/nerves",
     homepage_url: "http://nerves-project.org/",
     version: "0.3.2",
     elixir: "~> 1.2.4 or ~> 1.3.0-dev",
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     deps: deps,
     description: description,
     package: package,
     aliases: ["docs": ["docs", "copy_images"]],
     docs: docs]
  end

  def application do
    []
  end

  defp deps do
    [
      {:exrm, "~> 1.0.4"},
      {:earmark, "~> 0.1", only: :dev},
      {:ex_doc, "~> 0.11", only: :dev},
      {:porcelain, "~> 2.0"}
    ]
  end

  defp docs do
    [main: "getting-started",
     logo: "resources/logo.png",
     extras: [
        "docs/Installation.md",
        "docs/Getting Started.md",
        "docs/Targets.md",
        "docs/Systems.md",
        "docs/User Interfaces.md",
        "docs/Advanced Configuration.md"
    ]]
  end

  defp description do
    """
    Nerves - Create firmware for embedded devices like Raspberry Pi, BeagleBone Black, and more
    """
  end

  defp package do
    [maintainers: ["Frank Hunleth", "Garth Hitchens", "Justin Schneck", "Greg Mefford"],
     licenses: ["Apache 2.0"],
     links: %{"Github" => "https://github.com/nerves-project/nerves"}]
  end
end


Fix mix.exs

Fix mix.exs

defmodule Cazoc.Mixfile do
  use Mix.Project

  def project do
    [app: :cazoc,
     version: "0.2.1",
     elixir: "~> 1.3.2",
     elixirc_paths: elixirc_paths(Mix.env),
     compilers: [:phoenix, :gettext] ++ Mix.compilers,
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     aliases: aliases,
     deps: deps]
  end

  # Configuration for the OTP application.
  #
  # Type `mix help compile.app` for more information.
  def application do
    [mod: {Cazoc, []},
     applications: [:comeonin,
                    :connection,
                    :cowboy,
                    :ex_admin,
                    :gettext,
                    :git_cli,
                    :logger,
                    :pandex,
                    :phoenix, :phoenix_ecto, :phoenix_html, :phoenix_slime,
                    :postgrex,
                    :scrivener,
                    :ssl,
                    :tentacat,
                    :timex,
                    :timex_ecto,
                    :tzdata,
                    :secure_random,
                    :ueberauth,
                    :ueberauth_github]]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
  defp elixirc_paths(_),     do: ["lib", "web"]

  defp deps do
    [{:phoenix, "~> 1.2.1"},
     {:phoenix_ecto, "~> 3.0.1"},
     {:postgrex, ">= 0.0.0"},
     {:phoenix_html, "~> 2.6"},
     {:phoenix_slime, "~> 0.7"},
     {:phoenix_live_reload, "~> 1.0", only: :dev},
     {:cowboy, "~> 1.0"},
     {:comeonin, "~> 2.5"},
     {:ecto, "~> 1.1 or ~> 2.0", [optional: false, hex: :ecto, manager: :mix, override: true]},
     {:exrm, "~> 1.0"},
     {:ex_admin, github: "smpallen99/ex_admin"},
     {:gettext, "~> 0.11"},
     {:git_cli, "~> 0.2"},
     {:pandex, "~> 0.1.0"},
     {:tentacat, "~> 0.5"},
     {:timex, "~> 3.0"},
     {:timex_ecto, "~> 3.0"},
     {:secure_random, "~> 0.5"},
     {:ueberauth, "~> 0.3"},
     {:ueberauth_github, "~> 0.2"}
    ]
  end

  defp aliases do
    ["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
     "ecto.reset": ["ecto.drop", "ecto.setup"]]
  end
end

defmodule Cazoc.Mixfile do
  use Mix.Project

  def project do
    [app: :cazoc,
     version: "0.2.1",
     elixir: "~> 1.3.2",
     elixirc_paths: elixirc_paths(Mix.env),
     compilers: [:phoenix, :gettext] ++ Mix.compilers,
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     aliases: aliases,
     deps: deps]
  end

  # Configuration for the OTP application.
  #
  # Type `mix help compile.app` for more information.
  def application do
    [mod: {Cazoc, []},
     applications: [:comeonin,
                    :connection,
                    :cowboy,
                    :ex_admin,
                    :gettext,
                    :git_cli,
                    :logger,
                    :pandex,
                    :phoenix, :phoenix_ecto, :phoenix_html, :phoenix_slime, :phoenix_live_reload,
                    :postgrex,
                    :scrivener,
                    :ssl,
                    :tentacat,
                    :timex,
                    :timex_ecto,
                    :tzdata,
                    :secure_random,
                    :ueberauth,
                    :ueberauth_github]]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
  defp elixirc_paths(_),     do: ["lib", "web"]

  defp deps do
    [{:phoenix, "~> 1.2.1"},
     {:phoenix_ecto, "~> 3.0.1"},
     {:postgrex, ">= 0.0.0"},
     {:phoenix_html, "~> 2.6"},
     {:phoenix_slime, "~> 0.7"},
     {:phoenix_live_reload, "~> 1.0", only: :dev},
     {:cowboy, "~> 1.0"},
     {:comeonin, "~> 2.5"},
     {:ecto, "~> 1.1 or ~> 2.0", [optional: false, hex: :ecto, manager: :mix, override: true]},
     {:exrm, "~> 1.0"},
     {:ex_admin, github: "smpallen99/ex_admin"},
     {:gettext, "~> 0.11"},
     {:git_cli, "~> 0.2"},
     {:pandex, "~> 0.1.0"},
     {:tentacat, "~> 0.5"},
     {:timex, "~> 3.0"},
     {:timex_ecto, "~> 3.0"},
     {:secure_random, "~> 0.5"},
     {:ueberauth, "~> 0.3"},
     {:ueberauth_github, "~> 0.2"}
    ]
  end

  defp aliases do
    ["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
     "ecto.reset": ["ecto.drop", "ecto.setup"]]
  end
end


bump version to 1.0.5

bump version to 1.0.5

- it removes some deprecation warnings

defmodule Breadcrumble.Mixfile do
  use Mix.Project

  def project do
    [
      app: :breadcrumble,
      version: "1.0.5",
      elixir: "~> 1.9",
      description: "Elixir port of Breadcrumble library",
      package: [
        maintainers: ["Takayuki Matsubara"],
        licenses: ["MIT"],
        links: %{"GitHub" => "https://github.com/ma2gedev/breadcrumble_ex"}
      ],
      build_embedded: Mix.env() == :prod,
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Configuration for the OTP application
  #
  # Type `mix help compile.app` for more information
  def application do
    [extra_applications: [:logger, :eex]]
  end

  # Dependencies can be Hex packages:
  #
  #   {:mydep, "~> 0.3.0"}
  #
  # Or git/path repositories:
  #
  #   {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
  #
  # Type `mix help deps` for more examples and options
  defp deps do
    [
      {:plug, ">= 0.12.0 and < 2.0.0"},
      {:power_assert, "~> 0.3.0", only: :test}
    ]
  end
end

defmodule Breadcrumble.Mixfile do
  use Mix.Project

  def project do
    [
      app: :breadcrumble,
      version: "1.0.4",
      elixir: "~> 1.9",
      description: "Elixir port of Breadcrumble library",
      package: [
        maintainers: ["Takayuki Matsubara"],
        licenses: ["MIT"],
        links: %{"GitHub" => "https://github.com/ma2gedev/breadcrumble_ex"}
      ],
      build_embedded: Mix.env() == :prod,
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Configuration for the OTP application
  #
  # Type `mix help compile.app` for more information
  def application do
    [extra_applications: [:logger, :eex]]
  end

  # Dependencies can be Hex packages:
  #
  #   {:mydep, "~> 0.3.0"}
  #
  # Or git/path repositories:
  #
  #   {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
  #
  # Type `mix help deps` for more examples and options
  defp deps do
    [
      {:plug, ">= 0.12.0 and < 2.0.0"},
      {:power_assert, "~> 0.3.0", only: :test}
    ]
  end
end


Increment version [ci skip]

Increment version [ci skip]

defmodule Gateway.Mixfile do
  use Mix.Project

  @version "0.1.20"

  def project do
    [app: :gateway,
     description: "Add description to your package.",
     package: package(),
     version: @version,
     elixir: "~> 1.3",
     elixirc_paths: elixirc_paths(Mix.env),
     compilers: [] ++ Mix.compilers,
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     aliases: aliases(),
     deps: deps(),
     test_coverage: [tool: ExCoveralls],
     preferred_cli_env: [coveralls: :test],
     docs: [source_ref: "v#\{@version\}", main: "readme", extras: ["README.md"]]]
  end

  # Configuration for the OTP application
  #
  # Type "mix help compile.app" for more information
  def application do
    [
      applications: [:logger, :confex, :cowboy, :plug, :postgrex, :ecto, :ecto_enum, :timex, :joken, :nex_json_schema,
                     :poison, :httpoison, :ex_statsd, :libcluster, :eview],
      mod: {Gateway, []}
    ]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "test/support"]
  defp elixirc_paths(_),     do: ["lib"]

  # Dependencies can be Hex packages:
  #
  #   {:mydep, "~> 0.3.0"}
  #
  # Or git/path repositories:
  #
  #   {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
  #
  # To depend on another app inside the umbrella:
  #
  #   {:myapp, in_umbrella: true}
  #
  # Type "mix help deps" for more examples and options
  defp deps do
    [{:distillery, "~> 0.10.1"},
     {:libcluster, github: "gmile/libcluster", branch: "master"},
     {:confex, "~> 1.4.2"},
     {:plug, ">= 0.0.0"},
     {:cowboy, ">= 0.0.0"},
     {:postgrex, ">= 0.0.0", override: true},
     {:ecto, ">= 2.1.0-rc.3", override: true},
     {:ecto_enum, git: "https://github.com/gjaldon/ecto_enum", branch: "ecto-2.0", override: true},
     {:timex, "~> 3.0"},
     {:poison, "~> 2.0"},
     {:joken, "~> 1.3"},
     {:nex_json_schema, "~> 0.5.1"},
     {:httpoison, ">= 0.0.0"},
     {:httpoison, ">= 0.0.0"},
     {:ex_statsd, ">= 0.5.1"},
     {:eview,  ">= 0.0.0"},
     {:faker, "~> 0.7.0", only: [:dev, :test]},
     {:dogma, "> 0.1.0", only: [:dev, :test]},
     {:benchfella, "~> 0.3", only: [:dev, :test]},
     {:ex_doc, ">= 0.0.0", only: [:dev, :test]},
     {:excoveralls, "~> 0.5", only: [:dev, :test]},
     {:credo, ">= 0.4.8", only: [:dev, :test]},
    ]
  end

  # Settings for publishing in Hex package manager:
  defp package do
    [contributors: ["Nebo #15"],
     maintainers: ["Nebo #15"],
     licenses: ["LISENSE.md"],
     links: %{github: "https://github.com/Nebo15/os.gateway"},
     files: ~w(lib LICENSE.md mix.exs README.md)]
  end

  defp aliases do
    ["ecto.setup": ["ecto.create --quiet",
                    "ecto.migrate",
                    "run priv/repos/seeds.exs"],
     "ecto.reset": ["ecto.drop", "ecto.setup"],
     "test":       ["ecto.create --quiet",
                    "ecto.migrate",
                    "test"]]
  end
end

defmodule Gateway.Mixfile do
  use Mix.Project

  @version "0.1.19"

  def project do
    [app: :gateway,
     description: "Add description to your package.",
     package: package(),
     version: @version,
     elixir: "~> 1.3",
     elixirc_paths: elixirc_paths(Mix.env),
     compilers: [] ++ Mix.compilers,
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     aliases: aliases(),
     deps: deps(),
     test_coverage: [tool: ExCoveralls],
     preferred_cli_env: [coveralls: :test],
     docs: [source_ref: "v#\{@version\}", main: "readme", extras: ["README.md"]]]
  end

  # Configuration for the OTP application
  #
  # Type "mix help compile.app" for more information
  def application do
    [
      applications: [:logger, :confex, :cowboy, :plug, :postgrex, :ecto, :ecto_enum, :timex, :joken, :nex_json_schema,
                     :poison, :httpoison, :ex_statsd, :libcluster, :eview],
      mod: {Gateway, []}
    ]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "test/support"]
  defp elixirc_paths(_),     do: ["lib"]

  # Dependencies can be Hex packages:
  #
  #   {:mydep, "~> 0.3.0"}
  #
  # Or git/path repositories:
  #
  #   {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
  #
  # To depend on another app inside the umbrella:
  #
  #   {:myapp, in_umbrella: true}
  #
  # Type "mix help deps" for more examples and options
  defp deps do
    [{:distillery, "~> 0.10.1"},
     {:libcluster, github: "gmile/libcluster", branch: "master"},
     {:confex, "~> 1.4.2"},
     {:plug, ">= 0.0.0"},
     {:cowboy, ">= 0.0.0"},
     {:postgrex, ">= 0.0.0", override: true},
     {:ecto, ">= 2.1.0-rc.3", override: true},
     {:ecto_enum, git: "https://github.com/gjaldon/ecto_enum", branch: "ecto-2.0", override: true},
     {:timex, "~> 3.0"},
     {:poison, "~> 2.0"},
     {:joken, "~> 1.3"},
     {:nex_json_schema, "~> 0.5.1"},
     {:httpoison, ">= 0.0.0"},
     {:httpoison, ">= 0.0.0"},
     {:ex_statsd, ">= 0.5.1"},
     {:eview,  ">= 0.0.0"},
     {:faker, "~> 0.7.0", only: [:dev, :test]},
     {:dogma, "> 0.1.0", only: [:dev, :test]},
     {:benchfella, "~> 0.3", only: [:dev, :test]},
     {:ex_doc, ">= 0.0.0", only: [:dev, :test]},
     {:excoveralls, "~> 0.5", only: [:dev, :test]},
     {:credo, ">= 0.4.8", only: [:dev, :test]},
    ]
  end

  # Settings for publishing in Hex package manager:
  defp package do
    [contributors: ["Nebo #15"],
     maintainers: ["Nebo #15"],
     licenses: ["LISENSE.md"],
     links: %{github: "https://github.com/Nebo15/os.gateway"},
     files: ~w(lib LICENSE.md mix.exs README.md)]
  end

  defp aliases do
    ["ecto.setup": ["ecto.create --quiet",
                    "ecto.migrate",
                    "run priv/repos/seeds.exs"],
     "ecto.reset": ["ecto.drop", "ecto.setup"],
     "test":       ["ecto.create --quiet",
                    "ecto.migrate",
                    "test"]]
  end
end


test unclaimed

test unclaimed

defmodule Neoscan.Claims.Unclaimed do
  @moduledoc false
  import Ecto.Query, warn: false
  alias Decimal, as: D
  alias Neoscan.Repo
  alias Neoscan.Vouts.Vout
  alias NeoscanMonitor.Api
  alias Neoscan.Blocks.Block
  alias Neoscan.Helpers

  #total amount of available NEO
  def total_neo, do: 100_000_000
  D.set_context(%D.Context{D.get_context | precision: 10})

  #calculate unclaimed gas bonus
  def calculate_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> add_end_height
    |> route_if_there_is_unclaimed
    |> Helpers.round_or_not()
  end

  #calculate unclaimed gas bonus
  def calculate_vouts_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> filter_end_height
    |> route_if_there_is_unclaimed_but_dont_add
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed([]) do
    0
  end
  def route_if_there_is_unclaimed(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.reduce(
      unclaimed,
      0,
      fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end
    )
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed_but_dont_add([]) do
    []
  end
  def route_if_there_is_unclaimed_but_dont_add(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.map(
      unclaimed,
      fn %{:value => value} = vout -> Map.merge(vout, %{
          :unclaimed => compute_vout_bonus(vout, blocks_with_gas),
          :value => Helpers.round_or_not(value),
        }) end
    )
  end

  #compute bonus for a singel vout
  def compute_vout_bonus(
        %{
          :value => value,
          :start_height => start_height,
          :end_height => end_height
        },
        blocks_with_gas
      ) do
    total_gas = Enum.filter(
                  blocks_with_gas,
                  fn %{:index => index} ->
                    index >= start_height && index <= end_height end
                )
                |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)

    D.mult(D.new(value), D.new(total_gas))
    |> D.div(D.new(100_000_000))
    |> D.to_float()
  end

  #get all unclaimed transaction vouts
  def get_unclaimed_vouts(address_id) do
    query = from v in Vout,
                 where: v.address_id == ^address_id
                        and v.claimed == false
                        and v.asset == "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
                 select: map(v, [:value, :start_height, :end_height, :n, :txid])

    Repo.all(query)
  end

  def add_end_height(unclaimed_vouts) do
    Enum.map(
      unclaimed_vouts,
      fn %{:end_height => height} = vout ->
        Map.put(vout, :end_height, check_end_height(height)) end
    )
  end

  def filter_end_height(unclaimed_vouts) do
    Enum.filter(
      unclaimed_vouts,
      fn %{:end_height => height} ->
        height != nil end
    )
  end

  #get block range of unclaimed transaction vouts
  def get_unclaimed_block_range(unclaimed_vouts) do
    end_height_list = Enum.map(
      unclaimed_vouts,
      fn %{:end_height => end_height} -> check_end_height(end_height) end
    )

    max = end_height_list
          |> Enum.max

    min = Enum.map(
            unclaimed_vouts,
            fn %{:start_height => start_height} -> start_height end
          )
          |> Enum.min

    {min, max}
  end

  #check end_height and use current height when transaction vout wasn't used
  def check_end_height(nil) do
    {:ok, height} = Api.get_height
    height
  end
  def check_end_height(number) do
    number
  end

  #get total gas distribution amount for all blocks in a given range tuple
  def get_blocks_gas({min, max}) do
    query = from b in Block,
                 where: b.index >= ^min and b.index <= ^max,
                 select: map(b, [:index, :total_sys_fee, :gas_generated])

    Repo.all(query)
    |> Enum.map(
         fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->
           sys = sys
                 |> round()

           gen = gen
                 |> round
           %{:index => index, :gas => sys + gen}
         end
       )
  end

end

defmodule Neoscan.Claims.Unclaimed do
  @moduledoc false
  import Ecto.Query, warn: false
  alias Decimal, as: D
  alias Neoscan.Repo
  alias Neoscan.Vouts.Vout
  alias NeoscanMonitor.Api
  alias Neoscan.Blocks.Block
  alias Neoscan.Helpers

  #total amount of available NEO
  def total_neo, do: 100_000_000
  D.set_context(%D.Context{D.get_context | precision: 10})

  #calculate unclaimed gas bonus
  def calculate_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> add_end_height
    |> route_if_there_is_unclaimed
    |> Helpers.round_or_not()
  end

  #calculate unclaimed gas bonus
  def calculate_vouts_bonus(address_id) do
    get_unclaimed_vouts(address_id)
    |> filter_end_height
    |> route_if_there_is_unclaimed_but_dont_add
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed([]) do
    0
  end
  def route_if_there_is_unclaimed(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.reduce(
      unclaimed,
      0,
      fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end
    )
  end

  #proceed calculus if there are unclaimed results, otherwise return 0
  def route_if_there_is_unclaimed_but_dont_add([]) do
    []
  end
  def route_if_there_is_unclaimed_but_dont_add(unclaimed) do
    blocks_with_gas = get_unclaimed_block_range(unclaimed)
                      |> get_blocks_gas

    Enum.map(
      unclaimed,
      fn %{:value => value} = vout -> Map.merge(vout, %{
          :unclaimed => compute_vout_bonus(vout, blocks_with_gas),
          :value => Helpers.round_or_not(value),
        }) end
    )
  end

  #compute bonus for a singel vout
  def compute_vout_bonus(
        %{
          :value => value,
          :start_height => start_height,
          :end_height => end_height
        },
        blocks_with_gas
      ) do
    total_gas = Enum.filter(
                  blocks_with_gas,
                  fn %{:index => index} ->
                    index >= start_height && index <= end_height end
                )
                |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)

    fact = D.div(D.new(value), D.new(total_neo()))

    D.mult(D.new(total_gas), D.new(fact))
    |> D.div(D.new(100_000_000))
    |> D.to_float()
  end

  #get all unclaimed transaction vouts
  def get_unclaimed_vouts(address_id) do
    query = from v in Vout,
                 where: v.address_id == ^address_id
                        and v.claimed == false
                        and v.asset == "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b",
                 select: map(v, [:value, :start_height, :end_height, :n, :txid])

    Repo.all(query)
  end

  def add_end_height(unclaimed_vouts) do
    Enum.map(
      unclaimed_vouts,
      fn %{:end_height => height} = vout ->
        Map.put(vout, :end_height, check_end_height(height)) end
    )
  end

  def filter_end_height(unclaimed_vouts) do
    Enum.filter(
      unclaimed_vouts,
      fn %{:end_height => height} ->
        height != nil end
    )
  end

  #get block range of unclaimed transaction vouts
  def get_unclaimed_block_range(unclaimed_vouts) do
    end_height_list = Enum.map(
      unclaimed_vouts,
      fn %{:end_height => end_height} -> check_end_height(end_height) end
    )

    max = end_height_list
          |> Enum.max

    min = Enum.map(
            unclaimed_vouts,
            fn %{:start_height => start_height} -> start_height end
          )
          |> Enum.min

    {min, max}
  end

  #check end_height and use current height when transaction vout wasn't used
  def check_end_height(nil) do
    {:ok, height} = Api.get_height
    height
  end
  def check_end_height(number) do
    number
  end

  #get total gas distribution amount for all blocks in a given range tuple
  def get_blocks_gas({min, max}) do
    query = from b in Block,
                 where: b.index >= ^min and b.index <= ^max,
                 select: map(b, [:index, :total_sys_fee, :gas_generated])

    Repo.all(query)
    |> Enum.map(
         fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->
           sys = sys * 100_000_000
                 |> round()

           gen = gen * 100_000_000
                 |> round
           %{:index => index, :gas => sys + gen}
         end
       )
  end

end


Ensure logs are silenced on endpoint test.

Code.require_file "../../support/http_client.exs", __DIR__

defmodule Phoenix.Integration.EndpointTest do
  # Cannot run async because of serve endpoints
  use ExUnit.Case
  import ExUnit.CaptureLog

  alias Phoenix.Integration.AdapterTest.ProdEndpoint
  alias Phoenix.Integration.AdapterTest.DevEndpoint

  Application.put_env(:endpoint_int, ProdEndpoint,
      http: [port: "4807"], url: [host: "example.com"], server: true)
  Application.put_env(:endpoint_int, DevEndpoint,
      http: [port: "4808"], debug_errors: true)

  defmodule Router do
    @moduledoc """
    Let's use a plug router to test this endpoint.
    """
    use Plug.Router

    plug :match
    plug :dispatch

    get "/" do
      send_resp conn, 200, "ok"
    end

    get "/router/oops" do
      _ = conn
      raise "oops"
    end

    match _ do
      raise Phoenix.Router.NoRouteError, conn: conn, router: __MODULE__
    end
  end

  defmodule Wrapper do
    @moduledoc """
    A wrapper around the endpoint call to extract information.

    This exists so we can verify that the exception handling
    in the Phoenix endpoint is working as expected. In order
    to do that, we need to wrap the endpoint.call/2 in a
    before compile callback so it wraps the whole stack,
    including render errors and debug errors functionality.
    """

    defmacro __before_compile__(_) do
      quote do
        defoverridable [call: 2]

        def call(conn, opts) do
          # Assert we never have a lingering sent message in the inbox
          refute_received {:plug_conn, :sent}

          try do
            super(conn, opts)
          after
            # When we pipe downstream, downstream will always render,
            # either because the router is responding or because the
            # endpoint error layer is kicking in.
            assert_received {:plug_conn, :sent}
            send self(), {:plug_conn, :sent}
          end
        end
      end
    end
  end

  for mod <- [ProdEndpoint, DevEndpoint] do
    defmodule mod do
      use Phoenix.Endpoint, otp_app: :endpoint_int
      @before_compile Wrapper

      plug :oops
      plug Router

      @doc """
      Verify errors from the plug stack too (before the router).
      """
      def oops(conn, _opts) do
        if conn.path_info == ~w(oops) do
          raise "oops"
        else
          conn
        end
      end
    end
  end

  @prod 4807
  @dev  4808

  alias Phoenix.Integration.HTTPClient

  test "adapters starts on configured port and serves requests and stops for prod" do
    capture_log fn ->
      # Has server: true
      {:ok, _} = ProdEndpoint.start_link()

      # Requests
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}", %{})
      assert resp.status == 200
      assert resp.body == "ok"

      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}/unknown", %{})
      assert resp.status == 404
      assert resp.body == "404.html from Phoenix.ErrorView"

      assert capture_log(fn ->
        {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}/oops", %{})
        assert resp.status == 500
        assert resp.body == "500.html from Phoenix.ErrorView"
      end) =~ "** (RuntimeError) oops"

      assert capture_log(fn ->
        {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}/router/oops", %{})
        assert resp.status == 500
        assert resp.body == "500.html from Phoenix.ErrorView"
      end) =~ "** (RuntimeError) oops"

      Supervisor.stop(ProdEndpoint)
      {:error, _reason} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}", %{})
    end
  end

  test "adapters starts on configured port and serves requests and stops for dev" do
    # Toggle globally
    serve_endpoints(true)
    on_exit(fn -> serve_endpoints(false) end)

    capture_log fn ->
      # Has server: false
      {:ok, _} = DevEndpoint.start_link

      # Requests
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}", %{})
      assert resp.status == 200
      assert resp.body == "ok"

      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}/unknown", %{})
      assert resp.status == 404
      assert resp.body =~ "NoRouteError at GET /unknown"

      assert capture_log(fn ->
        {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}/oops", %{})
        assert resp.status == 500
        assert resp.body =~ "RuntimeError at GET /oops"
      end) =~ "** (RuntimeError) oops"

      assert capture_log(fn ->
        {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}/router/oops", %{})
        assert resp.status == 500
        assert resp.body =~ "RuntimeError at GET /router/oops"
      end) =~ "** (RuntimeError) oops"

      Supervisor.stop(DevEndpoint)
      {:error, _reason} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}", %{})
    end
  end

  defp serve_endpoints(bool) do
    Application.put_env(:phoenix, :serve_endpoints, bool)
  end
end

Code.require_file "../../support/http_client.exs", __DIR__

defmodule Phoenix.Integration.EndpointTest do
  # Cannot run async because of serve endpoints
  use ExUnit.Case
  import ExUnit.CaptureLog

  alias Phoenix.Integration.AdapterTest.ProdEndpoint
  alias Phoenix.Integration.AdapterTest.DevEndpoint

  Application.put_env(:endpoint_int, ProdEndpoint,
      http: [port: "4807"], url: [host: "example.com"], server: true)
  Application.put_env(:endpoint_int, DevEndpoint,
      http: [port: "4808"], debug_errors: true)

  defmodule Router do
    @moduledoc """
    Let's use a plug router to test this endpoint.
    """
    use Plug.Router

    plug :match
    plug :dispatch

    get "/" do
      send_resp conn, 200, "ok"
    end

    get "/router/oops" do
      _ = conn
      raise "oops"
    end

    match _ do
      raise Phoenix.Router.NoRouteError, conn: conn, router: __MODULE__
    end
  end

  defmodule Wrapper do
    @moduledoc """
    A wrapper around the endpoint call to extract information.

    This exists so we can verify that the exception handling
    in the Phoenix endpoint is working as expected. In order
    to do that, we need to wrap the endpoint.call/2 in a
    before compile callback so it wraps the whole stack,
    including render errors and debug errors functionality.
    """

    defmacro __before_compile__(_) do
      quote do
        defoverridable [call: 2]

        def call(conn, opts) do
          # Assert we never have a lingering sent message in the inbox
          refute_received {:plug_conn, :sent}

          try do
            super(conn, opts)
          after
            # When we pipe downstream, downstream will always render,
            # either because the router is responding or because the
            # endpoint error layer is kicking in.
            assert_received {:plug_conn, :sent}
            send self(), {:plug_conn, :sent}
          end
        end
      end
    end
  end

  for mod <- [ProdEndpoint, DevEndpoint] do
    defmodule mod do
      use Phoenix.Endpoint, otp_app: :endpoint_int
      @before_compile Wrapper

      plug :oops
      plug Router

      @doc """
      Verify errors from the plug stack too (before the router).
      """
      def oops(conn, _opts) do
        if conn.path_info == ~w(oops) do
          raise "oops"
        else
          conn
        end
      end
    end
  end

  @prod 4807
  @dev  4808

  alias Phoenix.Integration.HTTPClient

  test "adapters starts on configured port and serves requests and stops for prod" do
    capture_log fn ->
      # Has server: true
      {:ok, _} = ProdEndpoint.start_link()

      # Requests
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}", %{})
      assert resp.status == 200
      assert resp.body == "ok"

      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}/unknown", %{})
      assert resp.status == 404
      assert resp.body == "404.html from Phoenix.ErrorView"
    end

    assert capture_log(fn ->
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}/oops", %{})
      assert resp.status == 500
      assert resp.body == "500.html from Phoenix.ErrorView"
    end) =~ "** (RuntimeError) oops"

    assert capture_log(fn ->
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}/router/oops", %{})
      assert resp.status == 500
      assert resp.body == "500.html from Phoenix.ErrorView"
    end) =~ "** (RuntimeError) oops"

    Supervisor.stop(ProdEndpoint)
    {:error, _reason} = HTTPClient.request(:get, "http://127.0.0.1:#{@prod}", %{})
  end

  test "adapters starts on configured port and serves requests and stops for dev" do
    # Has server: false
    {:ok, _} = DevEndpoint.start_link
    {:error, _reason} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}", %{})
    Supervisor.stop(DevEndpoint)

    # Toggle globally
    serve_endpoints(true)
    on_exit(fn -> serve_endpoints(false) end)
    capture_log fn -> {:ok, _} = DevEndpoint.start_link end

    # Requests
    {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}", %{})
    assert resp.status == 200
    assert resp.body == "ok"

    capture_log(fn ->
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}/unknown", %{})
      assert resp.status == 404
      assert resp.body =~ "NoRouteError at GET /unknown"
    end)

    assert capture_log(fn ->
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}/oops", %{})
      assert resp.status == 500
      assert resp.body =~ "RuntimeError at GET /oops"
    end) =~ "** (RuntimeError) oops"

    assert capture_log(fn ->
      {:ok, resp} = HTTPClient.request(:get, "http://127.0.0.1:#{@dev}/router/oops", %{})
      assert resp.status == 500
      assert resp.body =~ "RuntimeError at GET /router/oops"
    end) =~ "** (RuntimeError) oops"
  end

  defp serve_endpoints(bool) do
    Application.put_env(:phoenix, :serve_endpoints, bool)
  end
end