hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
7970f648146d734e4bc2243bd5d46cb29f40f57a
472
ex
Elixir
containers/chat/lib/chat_web/router.ex
shiftyp/awayteam
297e21305a109af3aee9ac3dc5820f8220c1b380
[ "MIT" ]
null
null
null
containers/chat/lib/chat_web/router.ex
shiftyp/awayteam
297e21305a109af3aee9ac3dc5820f8220c1b380
[ "MIT" ]
6
2021-03-09T19:50:06.000Z
2022-02-26T18:41:08.000Z
containers/chat/lib/chat_web/router.ex
shiftyp/awayteam
297e21305a109af3aee9ac3dc5820f8220c1b380
[ "MIT" ]
null
null
null
defmodule ChatWeb.Router do use ChatWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", ChatWeb do pipe_through :browser # Use the default browser stack end # Other scopes may use custom stacks. # scope "/api", ChatWeb do # pipe_through :api # end end
18.88
57
0.677966
797100faf5366920a1fc53957fdcc0f62105a024
1,014
ex
Elixir
lib/future_made_concerts/spotify/schema/track.ex
Future-Made/concerts-for-impact
5532cd1be5252fa0ccb0b956f0961be8701e0e04
[ "MIT" ]
null
null
null
lib/future_made_concerts/spotify/schema/track.ex
Future-Made/concerts-for-impact
5532cd1be5252fa0ccb0b956f0961be8701e0e04
[ "MIT" ]
null
null
null
lib/future_made_concerts/spotify/schema/track.ex
Future-Made/concerts-for-impact
5532cd1be5252fa0ccb0b956f0961be8701e0e04
[ "MIT" ]
null
null
null
defmodule FutureMadeConcerts.Spotify.Schema.Track do @moduledoc """ Represents an album track. """ alias FutureMadeConcerts.{Duration, Spotify.Schema} alias Schema.{Album, Artist} @enforce_keys [ :id, :uri, :name, :spotify_url, :duration_ms, :track_number, :disc_number, :artists, :album ] defstruct [ :id, :uri, :name, :spotify_url, :duration_ms, :track_number, :disc_number, :artists, :album ] @type t :: %__MODULE__{ id: Schema.id(), uri: Schema.uri(), name: String.t(), spotify_url: String.t(), duration_ms: Duration.milliseconds(), track_number: pos_integer(), disc_number: pos_integer(), artists: [Artist.t()], album: Album.t() } @spec artist_ids([t()]) :: [Schema.id()] def artist_ids(tracks) do tracks |> Enum.flat_map(fn t -> Enum.map(t.artists, & &1.id) end) |> Enum.uniq() end end
19.132075
53
0.556213
7971047bfc04f94175de7f437ba120347f608230
384
ex
Elixir
web/views/session_view.ex
kensupermen/trello
00eba2165ac32663319679271dcc56ac6cfe4cad
[ "MIT" ]
null
null
null
web/views/session_view.ex
kensupermen/trello
00eba2165ac32663319679271dcc56ac6cfe4cad
[ "MIT" ]
3
2018-10-03T16:59:21.000Z
2018-10-06T09:53:51.000Z
web/views/session_view.ex
kensupermen/trello
00eba2165ac32663319679271dcc56ac6cfe4cad
[ "MIT" ]
1
2018-10-03T17:06:47.000Z
2018-10-03T17:06:47.000Z
defmodule Trello.SessionView do use Trello.Web, :view def render("show.json", %{jwt: jwt, user: user}) do %{ jwt: jwt, user: user } end def render("error.json", _) do %{error: "Invalid email or password"} end def render("delete.json", _) do %{ok: true} end def render("forbidden.json", %{error: error}) do %{error: error} end end
16.695652
53
0.588542
79711e87c1e7520003bf04ebe5a2332c8f3c4053
1,821
ex
Elixir
clients/display_video/lib/google_api/display_video/v1/model/custom_list.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/display_video/lib/google_api/display_video/v1/model/custom_list.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/display_video/lib/google_api/display_video/v1/model/custom_list.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DisplayVideo.V1.Model.CustomList do @moduledoc """ Describes a custom list entity, such as a custom affinity or custom intent audience list. ## Attributes * `customListId` (*type:* `String.t`, *default:* `nil`) - Output only. The unique ID of the custom list. Assigned by the system. * `displayName` (*type:* `String.t`, *default:* `nil`) - Output only. The display name of the custom list. . * `name` (*type:* `String.t`, *default:* `nil`) - Output only. The resource name of the custom list. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :customListId => String.t(), :displayName => String.t(), :name => String.t() } field(:customListId) field(:displayName) field(:name) end defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.CustomList do def decode(value, options) do GoogleApi.DisplayVideo.V1.Model.CustomList.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.CustomList do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.358491
132
0.712246
797154c4fcfbb0ea248159ed2844ff0585f64c9e
562
ex
Elixir
lib/copadelrey_api_web/model/game.ex
trestini/copadelrey-api
d042ae5535c2a8860cb34e59078b2af15aec4c09
[ "Apache-2.0" ]
null
null
null
lib/copadelrey_api_web/model/game.ex
trestini/copadelrey-api
d042ae5535c2a8860cb34e59078b2af15aec4c09
[ "Apache-2.0" ]
2
2021-03-09T18:24:01.000Z
2021-05-10T15:20:30.000Z
lib/copadelrey_api_web/model/game.ex
trestini/copadelrey-api
d042ae5535c2a8860cb34e59078b2af15aec4c09
[ "Apache-2.0" ]
null
null
null
defmodule CupWeb.Game do @derive Jason.Encoder defstruct [:id, :date, :stage, :players, :balls_remaining, :rule, :ended, :winner_team, :teams] @spec from_schema(Cup.Game.t) :: CupWeb.Game.t def from_schema(game) do %CupWeb.Game{ id: game.id, date: game.inserted_at, stage: game.stage |> CupWeb.Stage.from_schema, players: game.players |> Enum.map(&CupWeb.Player.from_schema(&1)), balls_remaining: game.balls_remaining, rule: game.rule, ended: game.ended, winner_team: game.winner_team } end end
29.578947
97
0.66548
7971681d27b631ff5af800567a58cc6f17e9ff7c
2,273
ex
Elixir
lib/ethereumex/config.ex
InoMurko/ethereumex
f8e18f8aa2d2f1719a67c69f11486621416ac324
[ "MIT" ]
null
null
null
lib/ethereumex/config.ex
InoMurko/ethereumex
f8e18f8aa2d2f1719a67c69f11486621416ac324
[ "MIT" ]
null
null
null
lib/ethereumex/config.ex
InoMurko/ethereumex
f8e18f8aa2d2f1719a67c69f11486621416ac324
[ "MIT" ]
null
null
null
defmodule Ethereumex.Config do @moduledoc false alias Ethereumex.IpcServer def setup_children do setup_children(client_type()) end defp setup_children(:ipc) do path = Enum.join([System.user_home!(), ipc_path()]) [ :poolboy.child_spec(:worker, poolboy_config(), path: path, ipc_request_timeout: ipc_request_timeout() ) ] end defp setup_children(:http), do: [] defp setup_children(opt) do raise "Invalid :client option (#{opt}) in config" end @spec poolboy_config() :: keyword() defp poolboy_config() do [ {:name, {:local, :ipc_worker}}, {:worker_module, IpcServer}, {:size, ipc_worker_size()}, {:max_overflow, ipc_max_worker_overflow()} ] end @spec rpc_url() :: binary() def rpc_url do case Application.get_env(:ethereumex, :url) do url when is_binary(url) and url != "" -> url els -> raise ArgumentError, message: "Please set config variable `config :ethereumex, :url, \"http://...\", got: `#{ inspect(els) }``" end end @spec http_options() :: keyword() def http_options do Application.get_env(:ethereumex, :http_options, []) end @spec client_type() :: atom() def client_type do Application.get_env(:ethereumex, :client_type, :http) end @spec ipc_path() :: binary() def ipc_path do case Application.get_env(:ethereumex, :ipc_path, "") do path when is_binary(path) and path != "" -> path not_a_path -> raise ArgumentError, message: "Please set config variable `config :ethereumex, :ipc_path, \"path/to/ipc\", got `#{ not_a_path }`. Note: System.user_home! will be prepended to path for you on initialization" end end @spec ipc_worker_size() :: integer() defp ipc_worker_size() do Application.get_env(:ethereumex, :ipc_worker_size, 5) end @spec ipc_max_worker_overflow() :: integer() defp ipc_max_worker_overflow() do Application.get_env(:ethereumex, :ipc_max_worker_overflow, 2) end @spec ipc_request_timeout() :: integer() defp ipc_request_timeout() do Application.get_env(:ethereumex, :ipc_request_timeout, 60_000) end end
24.978022
96
0.632644
797168dbfd1b3bfbcce6bbeb51d404d2ed12425c
1,514
exs
Elixir
mix.exs
filipecabaco/Ace
e5497f182c103f62ba42d8bccf429e016d4efe73
[ "MIT" ]
null
null
null
mix.exs
filipecabaco/Ace
e5497f182c103f62ba42d8bccf429e016d4efe73
[ "MIT" ]
null
null
null
mix.exs
filipecabaco/Ace
e5497f182c103f62ba42d8bccf429e016d4efe73
[ "MIT" ]
null
null
null
defmodule Ace.Mixfile do use Mix.Project def project do [ app: :ace, version: "0.19.0", elixir: "~> 1.9", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), elixirc_options: [ # Will be done when switching to ssl handshake # warnings_as_errors: true ], description: description(), docs: [ main: "readme", source_url: "https://github.com/crowdhailer/ace", extras: [ "README.md" ] ], test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ], package: package() ] end def application do [ extra_applications: [:logger, :ssl] ] end defp deps do [ {:hpack, "~> 0.2.3", hex: :hpack_erl}, {:raxx, "~> 0.17.0 or ~> 0.18.0 or ~> 1.0"}, {:excoveralls, "~> 0.12", only: :test}, {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}, {:credo, "~> 1.0", only: [:dev, :test], runtime: false}, {:ex_doc, ">= 0.0.0", only: [:dev, :test], runtime: false} ] end defp description do """ HTTP web server and client, supports http1 and http2 """ end defp package do [ maintainers: ["Peter Saxton"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/crowdhailer/ace"} ] end end
22.939394
65
0.519155
79717b7abcbf571f50f2a189c4a79d714aaf7926
750
exs
Elixir
apps/firestorm_data/test/firestorm_data/schema/follow_test.exs
CircleCI-Public/firestorm
9ca2c46a2b2377370347ad94d6003eeb77be38d6
[ "MIT" ]
10
2017-06-28T08:06:52.000Z
2022-03-19T17:49:21.000Z
apps/firestorm_data/test/firestorm_data/schema/follow_test.exs
CircleCI-Public/firestorm
9ca2c46a2b2377370347ad94d6003eeb77be38d6
[ "MIT" ]
null
null
null
apps/firestorm_data/test/firestorm_data/schema/follow_test.exs
CircleCI-Public/firestorm
9ca2c46a2b2377370347ad94d6003eeb77be38d6
[ "MIT" ]
2
2017-10-21T12:01:02.000Z
2021-01-29T10:26:22.000Z
defmodule FirestormData.Schema.FollowTest do alias FirestormData.{Follow, Repo} use ExUnit.Case @valid_attributes %{ user_id: 1, assoc_id: 2 } setup do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo) end test "it requires an user_id" do changeset = %Follow{} |> Follow.changeset(Map.delete(@valid_attributes, :user_id)) refute changeset.valid? assert changeset.errors[:user_id] == {"can't be blank", [validation: :required]} end test "it requires an assoc_id" do changeset = %Follow{} |> Follow.changeset(Map.delete(@valid_attributes, :assoc_id)) refute changeset.valid? assert changeset.errors[:assoc_id] == {"can't be blank", [validation: :required]} end end
23.4375
85
0.666667
7971add3c3e2113f76dc5974be2a04c61c7285ef
2,801
ex
Elixir
lib/mix/tasks/cotton.lint.ex
ne-sachirou/inner_cotton
f98880cca4bfe5557e9ea6287ed1b3acf5090465
[ "Unlicense" ]
24
2018-03-21T07:17:21.000Z
2021-03-29T13:49:56.000Z
lib/mix/tasks/cotton.lint.ex
ne-sachirou/inner_cotton
f98880cca4bfe5557e9ea6287ed1b3acf5090465
[ "Unlicense" ]
107
2017-11-01T04:55:45.000Z
2022-03-24T01:17:09.000Z
lib/mix/tasks/cotton.lint.ex
ne-sachirou/inner_cotton
f98880cca4bfe5557e9ea6287ed1b3acf5090465
[ "Unlicense" ]
null
null
null
defmodule Mix.Tasks.Cotton.Lint do @moduledoc """ Lint by Credo & check types by Dialyzer. Run following checks. ``` mix format --check-formatted mix credo --strict mix dialyzer mix inch --pedantic ``` Option: * `--fix`: Auto correct errors if available. """ use Mix.Task @shortdoc "Lint by Credo & check types by Dialyzer" @type facts :: map @type results :: keyword(integer) @type tasks :: keyword(Task.t()) @impl Mix.Task def run(args) do Mix.Task.run("cmd", ["mix compile"]) {[], gather_facts(args)} |> check_async(:format, &check_format/1) |> check_async(:credo, &check_credo/1) |> check_async( :dialyzer, Task.async(Mix.Shell.IO, :cmd, ["mix dialyzer"]) ) # |> check_async(:inch, &check_inch/1) |> await_checks |> print_check_results end defp check_format(facts) do if facts.fix?, do: Mix.Shell.IO.cmd("mix format --check-equivalent") Mix.Shell.IO.cmd("mix format --check-formatted") end defp check_credo(_) do alias Credo.Execution alias Credo.Execution.Task.WriteDebugReport {:ok, _} = Application.ensure_all_started(:credo) Credo.Application.start(nil, nil) ["--strict"] |> Execution.build() |> Execution.run() |> WriteDebugReport.call([]) |> Execution.get_assign("credo.exit_status", 0) end # defp check_inch(%{docs?: false}), do: -1 # defp check_inch(_) do # alias InchEx.CLI # Mix.Task.run("compile") # {:ok, _} = Application.ensure_all_started(:inch_ex) # CLI.main(["--pedantic"]) # 0 # end @spec gather_facts([binary]) :: facts defp gather_facts(args) do %{ docs?: Mix.Tasks.Docs in Mix.Task.load_all(), fix?: "--fix" in args } end @spec check_async({tasks, facts}, atom, (facts -> integer) | Task.t()) :: {tasks, facts} defp check_async({tasks, facts}, name, %Task{} = task), do: {[{name, task} | tasks], facts} defp check_async({tasks, facts}, name, fun), do: check_async({tasks, facts}, name, Task.async(fn -> fun.(facts) end)) @spec await_checks({tasks, facts}) :: results defp await_checks({tasks, _}), do: for({name, task} <- Enum.reverse(tasks), do: {name, Task.await(task, :infinity)}) @spec print_check_results(results) :: any defp print_check_results(results) do label_length = results |> Keyword.keys() |> Enum.map(&(&1 |> to_string |> String.length())) |> Enum.max() for {name, status} <- results, status >= 0 do IO.puts( String.pad_trailing(to_string(name), label_length + 1) <> ":\t" <> if(0 === status, do: "ok", else: "ng") ) end case results |> Keyword.values() |> Enum.map(&max(&1, 0)) |> Enum.sum() do 0 -> nil exit_status -> :erlang.halt(exit_status) end end end
26.17757
96
0.615851
7971c797058f69abf3fe1b1719f50541f55af5cf
2,551
ex
Elixir
lib/mix/tasks/ecto.gen.repo.ex
jccf091/ecto
42d47a6da0711f842e1a0e6724a89b318b9b2144
[ "Apache-2.0" ]
1
2017-11-27T06:00:32.000Z
2017-11-27T06:00:32.000Z
lib/mix/tasks/ecto.gen.repo.ex
jccf091/ecto
42d47a6da0711f842e1a0e6724a89b318b9b2144
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/ecto.gen.repo.ex
jccf091/ecto
42d47a6da0711f842e1a0e6724a89b318b9b2144
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Ecto.Gen.Repo do use Mix.Task import Mix.Ecto import Mix.Generator @shortdoc "Generates a new repository" @moduledoc """ Generates a new repository. The repository will be placed in the `lib` directory. ## Examples mix ecto.gen.repo -r Custom.Repo This generator will automatically open the config/config.exs after generation if you have `ECTO_EDITOR` set in your environment variable. ## Command line options * `-r`, `--repo` - the repo to generate """ @doc false def run(args) do no_umbrella!("ecto.gen.repo") repo = case parse_repo(args) do [] -> Mix.raise "ecto.gen.repo expects the repository to be given as -r MyApp.Repo" [repo] -> repo [_ | _] -> Mix.raise "ecto.gen.repo expects a single repository to be given" end config = Mix.Project.config underscored = Macro.underscore(inspect(repo)) base = Path.basename(underscored) file = Path.join("lib", underscored) <> ".ex" app = config[:app] || :YOUR_APP_NAME opts = [mod: repo, app: app, base: base] create_directory Path.dirname(file) create_file file, repo_template(opts) case File.read "config/config.exs" do {:ok, contents} -> Mix.shell.info [:green, "* updating ", :reset, "config/config.exs"] File.write! "config/config.exs", String.replace(contents, "use Mix.Config", config_template(opts)) {:error, _} -> create_file "config/config.exs", config_template(opts) end open?("config/config.exs") Mix.shell.info """ Don't forget to add your new repo to your supervision tree (typically in #{mixfile_loc(app)}): supervisor(#{inspect repo}, []) And to add it to the list of ecto repositories in your configuration files (so Ecto tasks work as expected): config #{inspect app}, ecto_repos: [#{inspect repo}] """ end defp mixfile_loc(app) do case Elixir.Version.compare(System.version, "1.4.0") do :gt -> "lib/#{app}/application.ex" :eq -> "lib/#{app}/application.ex" :lt -> "lib/#{app}.ex" end end embed_template :repo, """ defmodule <%= inspect @mod %> do use Ecto.Repo, otp_app: <%= inspect @app %> end """ embed_template :config, """ use Mix.Config config <%= inspect @app %>, <%= inspect @mod %>, adapter: Ecto.Adapters.Postgres, database: "<%= @app %>_<%= @base %>", username: "user", password: "pass", hostname: "localhost" """ end
25.257426
91
0.619757
7971c7e140bb06a4449b336b8a8a29b59fb7b81f
1,099
ex
Elixir
lib/Bank.ex
mithereal/ex_softbank
8e64143e0056861c84ed71001929bbb5a10a55bf
[ "MIT" ]
1
2020-01-26T23:28:44.000Z
2020-01-26T23:28:44.000Z
lib/Bank.ex
mithereal/ex_softbank
8e64143e0056861c84ed71001929bbb5a10a55bf
[ "MIT" ]
1
2018-12-02T05:35:28.000Z
2019-03-14T22:42:30.000Z
lib/Bank.ex
mithereal/elixir-softbank
2e63b72c4f25d651f4aee654ee41c25ac938fda3
[ "MIT" ]
null
null
null
defmodule SoftBank do @moduledoc """ The Main Interface for the Application """ alias SoftBank.Accountant.Supervisor, as: SUPERVISOR alias SoftBank.Accountant, as: ACCOUNTANT defdelegate transfer(amount, from_account_struct, to_account_struct), to: ACCOUNTANT defdelegate withdrawl(amount, from_account_number), to: ACCOUNTANT defdelegate deposit(amount, to_account_number), to: ACCOUNTANT defdelegate convert(amount, dest_currency), to: ACCOUNTANT defdelegate balance(account_number), to: ACCOUNTANT @doc """ Login to the account This will start a genserver to act as an accountant to abstract transactions, accountants auto shutdown after a ttl. """ def login(account_number) do SUPERVISOR.start_child(account_number) end def show(account_number) do ACCOUNTANT.show_state(account_number) end @doc """ Create a new account """ def create(name) do SoftBank.Account.new(name) end @doc """ Add a currency to the db and load into the ledger system """ def add_currency(params) do SoftBank.Currencies.new(params) end end
24.422222
118
0.745223
7971edb38487fea010aec978810f2512829faee4
1,915
ex
Elixir
lib/hexpm_web/controllers/login_controller.ex
thiamsantos/hexpm
790bae9e761fe9b2dd6901618054ad533ef24599
[ "Apache-2.0" ]
null
null
null
lib/hexpm_web/controllers/login_controller.ex
thiamsantos/hexpm
790bae9e761fe9b2dd6901618054ad533ef24599
[ "Apache-2.0" ]
null
null
null
lib/hexpm_web/controllers/login_controller.ex
thiamsantos/hexpm
790bae9e761fe9b2dd6901618054ad533ef24599
[ "Apache-2.0" ]
null
null
null
defmodule HexpmWeb.LoginController do use HexpmWeb, :controller plug :nillify_params, ["return"] def show(conn, _params) do if logged_in?(conn) do redirect_return(conn, conn.assigns.current_user) else render_show(conn) end end def create(conn, %{"username" => username, "password" => password}) do case password_auth(username, password) do {:ok, user} -> conn |> configure_session(renew: true) |> put_session("user_id", user.id) |> redirect_return(user) {:error, reason} -> conn |> put_flash(:error, auth_error_message(reason)) |> put_status(400) |> render_show() end end def delete(conn, _params) do conn |> delete_session("user_id") |> redirect(to: Routes.page_path(HexpmWeb.Endpoint, :index)) end defp redirect_return(%{params: %{"hexdocs" => organization}} = conn, user) do case generate_hexdocs_key(user, organization) do {:ok, key} -> docs_url = Application.get_env(:hexpm, :docs_url) |> String.replace("://", "://#{organization}.") url = "#{docs_url}#{conn.params["return"]}?key=#{key.user_secret}" redirect(conn, external: url) {:error, _changeset} -> conn |> put_flash(:error, "You don't have access to organization #{organization}") |> put_status(400) |> render_show() end end defp redirect_return(conn, user) do path = conn.params["return"] || Routes.user_path(conn, :show, user) redirect(conn, to: path) end defp generate_hexdocs_key(user, organization) do Keys.create_for_docs(user, organization) end defp render_show(conn) do render( conn, "show.html", title: "Log in", container: "container page page-xs login", return: conn.params["return"], hexdocs: conn.params["hexdocs"] ) end end
25.878378
85
0.61201
7971f8ed1b90b1ed1d931270191338b595994199
444
exs
Elixir
test/quantum_storage_mnesia/mnesia/helper_test.exs
sezaru/quantum_storage_mnesia
3e6707d1f9d82c7069fc84f894041b4936b92eaf
[ "MIT" ]
2
2020-08-04T15:37:31.000Z
2021-02-16T11:07:12.000Z
test/quantum_storage_mnesia/mnesia/helper_test.exs
sezaru/quantum_storage_mnesia
3e6707d1f9d82c7069fc84f894041b4936b92eaf
[ "MIT" ]
null
null
null
test/quantum_storage_mnesia/mnesia/helper_test.exs
sezaru/quantum_storage_mnesia
3e6707d1f9d82c7069fc84f894041b4936b92eaf
[ "MIT" ]
1
2021-08-06T05:09:44.000Z
2021-08-06T05:09:44.000Z
defmodule Test.QuantumStorageMnesia.Mnesia.HelperTest do @moduledoc false alias QuantumStorageMnesia.Mnesia alias Memento.Transaction use ExUnit.Case setup [:setup_mnesia] describe "transaction/2" do test "returns `error_default` when transaction fails" do assert :failed = Mnesia.Helper.transaction(fn -> Transaction.abort("error") end, :failed) end end defp setup_mnesia(_), do: Helper.setup_mnesia!() end
22.2
95
0.743243
797240e405eecb969e938bca6f5ad43dc8cca9a0
6,045
ex
Elixir
lib/request_cache/plug.ex
MikaAK/request_cache_plug
de5c413b686e4dc71cf2bb7c8784353a404acf32
[ "MIT" ]
3
2022-03-27T22:42:09.000Z
2022-03-28T17:50:37.000Z
lib/request_cache/plug.ex
MikaAK/request_cache_plug
de5c413b686e4dc71cf2bb7c8784353a404acf32
[ "MIT" ]
null
null
null
lib/request_cache/plug.ex
MikaAK/request_cache_plug
de5c413b686e4dc71cf2bb7c8784353a404acf32
[ "MIT" ]
1
2022-03-28T17:48:58.000Z
2022-03-28T17:48:58.000Z
defmodule RequestCache.Plug do require Logger alias RequestCache.{Util, Metrics} @moduledoc """ This plug allows you to cache GraphQL requests based off their query name and variables. This should be placed right after telemetry and before parsers so that it can stop any processing of the requests and immediately return a response. Please see `RequestCache` for more details """ @behaviour Plug # This is compile time so we can check quicker @graphql_paths RequestCache.Config.graphql_paths() @request_cache_header "rc-cache-status" @impl Plug def init(opts), do: opts @impl Plug def call(conn, _) do if RequestCache.Config.enabled?() do Util.verbose_log("[RequestCache.Plug] Hit request cache while enabled") call_for_api_type(conn) else Util.verbose_log("[RequestCache.Plug] Hit request cache while disabled") conn end end defp call_for_api_type(%Plug.Conn{request_path: path, method: "GET", query_string: query_string} = conn) when path in @graphql_paths do Util.verbose_log("[RequestCache.Plug] GraphQL query detected") maybe_return_cached_result(conn, path, query_string) end defp call_for_api_type(%Plug.Conn{request_path: path, method: "GET"} = conn) when path not in @graphql_paths do Util.verbose_log("[RequestCache.Plug] REST path detected") cache_key = rest_cache_key(conn) case request_cache_module(conn).get(cache_key) do {:ok, nil} -> Metrics.inc_rest_cache_miss(%{cache_key: cache_key}) Util.verbose_log("[RequestCache.Plug] REST enabling cache for conn and will cache if set") conn |> enable_request_cache_for_conn |> cache_before_send_if_requested(cache_key) {:ok, cached_result} -> Metrics.inc_rest_cache_hit(%{cache_key: cache_key}) Util.verbose_log("[RequestCache.Plug] Returning cached result for #{cache_key}") halt_and_return_result(conn, cached_result) {:error, e} -> Logger.error("[RequestCache.Plug] #{inspect(e)}") enable_request_cache_for_conn(conn) end end defp call_for_api_type(conn), do: conn defp maybe_return_cached_result(conn, request_path, query_string) do cache_key = Util.create_key(request_path, query_string) case request_cache_module(conn).get(cache_key) do {:ok, nil} -> Metrics.inc_graphql_cache_miss(event_metadata(conn, cache_key)) conn |> enable_request_cache_for_conn |> cache_before_send_if_requested(cache_key) {:ok, cached_result} -> Metrics.inc_graphql_cache_hit(event_metadata(conn, cache_key)) Util.verbose_log("[RequestCache.Plug] Returning cached result for #{cache_key}") halt_and_return_result(conn, cached_result) {:error, e} -> Logger.error("[RequestCache.Plug] #{inspect(e)}") enable_request_cache_for_conn(conn) end end defp halt_and_return_result(conn, result) do conn |> Plug.Conn.halt() |> Plug.Conn.put_resp_header(@request_cache_header, "HIT") |> Plug.Conn.put_resp_content_type("application/json") |> Plug.Conn.send_resp(200, result) end defp rest_cache_key(%Plug.Conn{request_path: path, query_string: query_string}) do Util.create_key(path, query_string) end defp cache_before_send_if_requested(conn, cache_key) do Plug.Conn.register_before_send(conn, fn new_conn -> if enabled_for_request?(new_conn) do Util.verbose_log("[RequestCache.Plug] Cache enabled before send, setting into cache...") ttl = request_cache_ttl(new_conn) with :ok <- request_cache_module(new_conn).put(cache_key, ttl, new_conn.resp_body) do Metrics.inc_cache_put(event_metadata(conn, cache_key)) Util.verbose_log("[RequestCache.Plug] Successfully put #{cache_key} into cache\n#{new_conn.resp_body}") end new_conn else Util.verbose_log("[RequestCache.Plug] Cache disabled in before_send callback") new_conn end end) end @spec event_metadata(Plug.Conn.t(), String.t()) :: map() defp event_metadata(conn, cache_key) do %{ cache_key: cache_key, labels: request_cache_labels(conn), ttl: request_cache_ttl(conn) } end defp request_cache_module(conn) do conn_request(conn)[:cache] || RequestCache.Config.request_cache_module() end defp request_cache_ttl(conn) do conn_request(conn)[:ttl] end defp request_cache_labels(conn) do conn_request(conn)[:labels] end defp enabled_for_request?(conn) do conn_request(conn) !== [] end defp conn_request(%{private: private}) do get_in(private, [conn_private_key(), :request]) || get_in(private, [:absinthe, :context, conn_private_key(), :request]) || [] end if RequestCache.Application.dependency_found?(:absinthe_plug) do defp enable_request_cache_for_conn(conn) do context = conn.private[:absinthe][:context] || %{} conn |> Plug.Conn.put_private(conn_private_key(), enabled?: true) |> Absinthe.Plug.put_options(context: Map.put(context, conn_private_key(), enabled?: true)) end else defp enable_request_cache_for_conn(conn) do Plug.Conn.put_private(conn, conn_private_key(), enabled?: true) end end def store_request(conn, opts) when is_list(opts) do if conn.private[conn_private_key()][:enabled?] do Plug.Conn.put_private(conn, conn_private_key(), enabled?: true, request: Util.merge_default_opts(opts) ) else Util.log_cache_disabled_message() conn end end def store_request(conn, ttl) when is_integer(ttl) do if conn.private[conn_private_key()][:enabled?] do Plug.Conn.put_private(conn, conn_private_key(), enabled?: true, request: [ttl: ttl, cache: RequestCache.Config.request_cache_module()] ) else Util.log_cache_disabled_message() conn end end defp conn_private_key do RequestCache.Config.conn_private_key() end end
30.225
137
0.697601
79724fbf050c370fe5ddcccad39f453d5dee1310
7,071
exs
Elixir
.credo.exs
paulswartz/draft
fc0653d75b39e861c4705545cfb86ad7cd0e2cd2
[ "MIT" ]
null
null
null
.credo.exs
paulswartz/draft
fc0653d75b39e861c4705545cfb86ad7cd0e2cd2
[ "MIT" ]
null
null
null
.credo.exs
paulswartz/draft
fc0653d75b39e861c4705545cfb86ad7cd0e2cd2
[ "MIT" ]
null
null
null
# This file contains the configuration for Credo and you are probably reading # this after creating it with `mix credo.gen.config`. # # If you find anything wrong or unclear in this file, please report an # issue on GitHub: https://github.com/rrrene/credo/issues # %{ # # You can have as many configs as you like in the `configs:` field. configs: [ %{ # # Run any config using `mix credo -C <name>`. If no config name is given # "default" is used. # name: "default", # # These are the files included in the analysis: files: %{ # # You can give explicit globs or simply directories. # In the latter case `**/*.{ex,exs}` will be used. # included: [ "config/", "lib/", "src/", "test/", "web/", "apps/*/lib/", "apps/*/src/", "apps/*/test/", "apps/*/web/" ], excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"] }, # # Load and configure plugins here: # plugins: [], # # If you create your own checks, you must specify the source files for # them here, so they can be loaded by Credo before running the analysis. # requires: [], # # If you want to enforce a style guide and need a more traditional linting # experience, you can change `strict` to `true` below: # strict: true, # # To modify the timeout for parsing files, change this value: # parse_timeout: 5000, # # If you want to use uncolored output by default, you can change `color` # to `false` below: # color: true, # # You can customize the parameters of any check by adding a second element # to the tuple. # # To disable a check put `false` as second element: # # {Credo.Check.Design.DuplicatedCode, []} # checks: [ # ## Consistency Checks # {Credo.Check.Consistency.ExceptionNames, []}, {Credo.Check.Consistency.LineEndings, []}, {Credo.Check.Consistency.ParameterPatternMatching, []}, {Credo.Check.Consistency.SpaceAroundOperators, []}, {Credo.Check.Consistency.SpaceInParentheses, []}, {Credo.Check.Consistency.TabsOrSpaces, []}, # ## Design Checks # # You can customize the priority of any check # Priority values are: `low, normal, high, higher` # {Credo.Check.Design.AliasUsage, [priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]}, # You can also customize the exit_status of each check. # If you don't want TODO comments to cause `mix credo` to fail, just # set this value to 0 (zero). # {Credo.Check.Design.TagTODO, [exit_status: 2]}, {Credo.Check.Design.TagFIXME, []}, # ## Readability Checks # {Credo.Check.Readability.AliasOrder, []}, {Credo.Check.Readability.FunctionNames, []}, {Credo.Check.Readability.LargeNumbers, []}, {Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]}, {Credo.Check.Readability.ModuleAttributeNames, []}, {Credo.Check.Readability.ModuleDoc, []}, {Credo.Check.Readability.ModuleNames, []}, {Credo.Check.Readability.ParenthesesInCondition, []}, {Credo.Check.Readability.ParenthesesOnZeroArityDefs, []}, {Credo.Check.Readability.PredicateFunctionNames, []}, {Credo.Check.Readability.PreferImplicitTry, []}, {Credo.Check.Readability.RedundantBlankLines, []}, {Credo.Check.Readability.Semicolons, []}, {Credo.Check.Readability.SpaceAfterCommas, []}, {Credo.Check.Readability.StringSigils, []}, {Credo.Check.Readability.TrailingBlankLine, []}, {Credo.Check.Readability.TrailingWhiteSpace, []}, {Credo.Check.Readability.UnnecessaryAliasExpansion, []}, {Credo.Check.Readability.VariableNames, []}, # ## Refactoring Opportunities # {Credo.Check.Refactor.CondStatements, []}, {Credo.Check.Refactor.CyclomaticComplexity, []}, {Credo.Check.Refactor.FunctionArity, []}, {Credo.Check.Refactor.LongQuoteBlocks, []}, {Credo.Check.Refactor.MapInto, []}, {Credo.Check.Refactor.MatchInCondition, []}, {Credo.Check.Refactor.NegatedConditionsInUnless, []}, {Credo.Check.Refactor.NegatedConditionsWithElse, []}, {Credo.Check.Refactor.Nesting, []}, {Credo.Check.Refactor.UnlessWithElse, []}, {Credo.Check.Refactor.WithClauses, []}, # ## Warnings # {Credo.Check.Warning.BoolOperationOnSameValues, []}, {Credo.Check.Warning.ExpensiveEmptyEnumCheck, []}, {Credo.Check.Warning.IExPry, []}, {Credo.Check.Warning.IoInspect, []}, {Credo.Check.Warning.LazyLogging, []}, {Credo.Check.Warning.MixEnv, false}, {Credo.Check.Warning.OperationOnSameValues, []}, {Credo.Check.Warning.OperationWithConstantResult, []}, {Credo.Check.Warning.RaiseInsideRescue, []}, {Credo.Check.Warning.UnusedEnumOperation, []}, {Credo.Check.Warning.UnusedFileOperation, []}, {Credo.Check.Warning.UnusedKeywordOperation, []}, {Credo.Check.Warning.UnusedListOperation, []}, {Credo.Check.Warning.UnusedPathOperation, []}, {Credo.Check.Warning.UnusedRegexOperation, []}, {Credo.Check.Warning.UnusedStringOperation, []}, {Credo.Check.Warning.UnusedTupleOperation, []}, {Credo.Check.Warning.UnsafeExec, []}, # # Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`) # # Controversial and experimental checks (opt-in, just replace `false` with `[]`) # {Credo.Check.Readability.StrictModuleLayout, []}, {Credo.Check.Consistency.MultiAliasImportRequireUse, []}, {Credo.Check.Consistency.UnusedVariableNames, []}, {Credo.Check.Design.DuplicatedCode, []}, {Credo.Check.Readability.AliasAs, false}, {Credo.Check.Readability.MultiAlias, []}, {Credo.Check.Readability.Specs, []}, {Credo.Check.Readability.SinglePipe, []}, {Credo.Check.Readability.WithCustomTaggedTuple, []}, {Credo.Check.Refactor.ABCSize, []}, {Credo.Check.Refactor.AppendSingleItem, []}, {Credo.Check.Refactor.DoubleBooleanNegation, []}, {Credo.Check.Refactor.ModuleDependencies, false}, {Credo.Check.Refactor.NegatedIsNil, []}, {Credo.Check.Refactor.PipeChainStart, []}, {Credo.Check.Refactor.VariableRebinding, []}, {Credo.Check.Warning.LeakyEnvironment, []}, {Credo.Check.Warning.MapGetUnsafePass, []}, {Credo.Check.Warning.UnsafeToAtom, []} # # Custom checks can be created using `mix credo.gen.check`. # ] } ] }
37.812834
97
0.601188
79726b48da5d60f996a555bccb1097f6d9fd90e7
2,368
ex
Elixir
lib/credo/check/readability/predicate_function_names.ex
jlgeering/credo
b952190ed758c262aa0d9bbee01227f9b1f0c63b
[ "MIT" ]
null
null
null
lib/credo/check/readability/predicate_function_names.ex
jlgeering/credo
b952190ed758c262aa0d9bbee01227f9b1f0c63b
[ "MIT" ]
null
null
null
lib/credo/check/readability/predicate_function_names.ex
jlgeering/credo
b952190ed758c262aa0d9bbee01227f9b1f0c63b
[ "MIT" ]
null
null
null
defmodule Credo.Check.Readability.PredicateFunctionNames do @moduledoc """ Predicate functions/macros should be named accordingly: * For functions, they should end in a question mark. # preferred defp user?(cookie) do end defp has_attachment?(mail) do end # NOT preferred defp is_user?(cookie) do end defp is_user(cookie) do end * For guard-safe macros they should have the prefix `is_` and not end in a question mark. Like all `Readability` issues, this one is not a technical concern. But you can improve the odds of others reading and liking your code by making it easier to follow. """ @explanation [check: @moduledoc] @def_ops [:def, :defp, :defmacro] use Credo.Check, base_priority: :high @doc false def run(source_file, params \\ []) do issue_meta = IssueMeta.for(source_file, params) Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta)) end for op <- @def_ops do # catch variables named e.g. `defp` defp traverse({unquote(op), _meta, nil} = ast, issues, _issue_meta) do {ast, issues} end defp traverse( {unquote(op) = op, _meta, arguments} = ast, issues, issue_meta ) do {ast, issues_for_definition(op, arguments, issues, issue_meta)} end end defp traverse(ast, issues, _issue_meta) do {ast, issues} end defp issues_for_definition(op, body, issues, issue_meta) do case Enum.at(body, 0) do {name, meta, nil} -> issues_for_name(op, name, meta, issues, issue_meta) _ -> issues end end def issues_for_name(_op, name, meta, issues, issue_meta) do name = to_string(name) cond do String.starts_with?(name, "is_") && String.ends_with?(name, "?") -> [ issue_for(issue_meta, meta[:line], name, :predicate_and_question_mark) | issues ] String.starts_with?(name, "is_") -> [issue_for(issue_meta, meta[:line], name, :only_predicate) | issues] true -> issues end end defp issue_for(issue_meta, line_no, trigger, _) do format_issue( issue_meta, message: "Predicate function names should not start with 'is', and should end in a question mark.", trigger: trigger, line_no: line_no ) end end
23.919192
98
0.631334
79726ee3c96b7bde1d51572a084faf0bbef9101d
341
ex
Elixir
lib/supabase_surface/components/icons/icon_zap_off.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
5
2021-06-08T08:02:43.000Z
2022-02-09T23:13:46.000Z
lib/supabase_surface/components/icons/icon_zap_off.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
null
null
null
lib/supabase_surface/components/icons/icon_zap_off.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
1
2021-07-14T05:20:31.000Z
2021-07-14T05:20:31.000Z
defmodule SupabaseSurface.Components.Icons.IconZapOff do use SupabaseSurface.Components.Icon @impl true def render(assigns) do icon_size = IconContainer.get_size(assigns.size) ~F""" <IconContainer assigns={assigns}> {Feathericons.zap_off(width: icon_size, height: icon_size)} </IconContainer> """ end end
22.733333
65
0.718475
7972bcffb76ab4ad0fea46ad74589d799c1cf4db
33,082
ex
Elixir
lib/dataloader/ecto.ex
gosseti/dataloader
19ca17dede4c86bbc757466a6383c82f3bccb688
[ "MIT" ]
null
null
null
lib/dataloader/ecto.ex
gosseti/dataloader
19ca17dede4c86bbc757466a6383c82f3bccb688
[ "MIT" ]
null
null
null
lib/dataloader/ecto.ex
gosseti/dataloader
19ca17dede4c86bbc757466a6383c82f3bccb688
[ "MIT" ]
null
null
null
if Code.ensure_loaded?(Ecto) do defmodule Dataloader.Ecto do @moduledoc """ Ecto source for Dataloader This defines a schema and an implementation of the `Dataloader.Source` protocol for handling Ecto related batching. A simple Ecto source only needs to know about your application's Repo. ## Basic Usage Querying by primary key (analogous to Ecto.Repo.get/3): ```elixir source = Dataloader.Ecto.new(MyApp.Repo) loader = Dataloader.new |> Dataloader.add_source(Accounts, source) |> Dataloader.load(Accounts, User, 1) |> Dataloader.load_many(Accounts, Organization, [4, 9]) |> Dataloader.run organizations = Dataloader.get_many(loader, Accounts, Organization, [4,9]) ``` Querying for associations. Here we look up the `:users` association on all the organizations, and the `:organization` for a single user. ```elixir loader = loader |> Dataloader.load(Accounts, :organization, user) |> Dataloader.load_many(Accounts, :users, organizations) |> Dataloader.run ``` Querying by a column other than the primary key: ```elixir loader = loader |> Dataloader.load(Accounts, {:one, User}, name: "admin") |> Dataloader.run ``` Here we pass a keyword list of length one. It is only possible to query by one column here; for more complex queries, see "filtering" below. Notice here that we need to also specify the cardinality in the batch_key (`:many` or `:one`), which will decide whether to return a list or a single value (or nil). This is because the column may not be a key and there may be multiple matching records. Note also that even if we are returning `:many` values here from multiple matching records, this is still a call to `Dataloader.load/4` rather than `Dataloader.load_many/4` because there is only one val specified. ## Filtering / Ordering `Dataloader.Ecto.new/2` can receive a 2 arity function that can be used to apply broad ordering and filtering rules, as well as handle parameters ```elixir source = Dataloader.Ecto.new(MyApp.Repo, query: &Accounts.query/2) loader = Dataloader.new |> Dataloader.add_source(Accounts, source) ``` When we call `Dataloader.load/4` we can pass in a tuple as the batch key with a keyword list of parameters in addition to the queryable or assoc_field ```elixir # with a queryable loader |> Dataloader.load(Accounts, {User, order: :name}, 1) # or an association loader |> Dataloader.load_many(Accounts, {:users, order: :name}, organizations) # this is still supported loader |> Dataloader.load(Accounts, User, 1) # as is this loader |> Dataloader.load(:accounts, :user, organization) ``` In all cases the `Accounts.query` function would be: ```elixir def query(User, params) do field = params[:order] || :id from u in User, order_by: [asc: field(u, ^field)] end def query(queryable, _) do queryable end ``` If we query something that ends up using the `User` schema, whether directly or via association, the `query/2` function will match on the first clause and we can handle the params. If no params are supplied, the params arg defaults to `source.default_params` which itself defaults to `%{}`. `default_params` is an extremely useful place to store values like the current user: ```elixir source = Dataloader.Ecto.new(MyApp.Repo, [ query: &Accounts.query/2, default_params: %{current_user: current_user}, ]) loader = Dataloader.new |> Dataloader.add_source(Accounts, source) |> Dataloader.load_many(Accounts, Organization, ids) |> Dataloader.run # the query function def query(Organization, %{current_user: user}) do from o in Organization, join: m in assoc(o, :memberships), where: m.user_id == ^user.id end def query(queryable, _) do queryable end ``` In our query function we are pattern matching on the current user to make sure that we are only able to lookup data in organizations that the user actually has a membership in. Additional options you specify IE `{Organization, %{order: :asc}}` are merged into the default. ## Custom batch queries There are cases where you want to run the batch function yourself. To do this we can add a custom `run_batch/5` callback to our source. The `run_batch/5` function is executed with the query returned from the `query/2` function. For example, we want to get the post count for a set of users. First we add a custom `run_batch/5` function. ``` def run_batch(_, query, :post_count, users, repo_opts) do user_ids = Enum.map(users, & &1.id) default_count = 0 result = query |> where([p], p.user_id in ^user_ids) |> group_by([p], p.user_id) |> select([p], {p.user_id, count("*")}) |> Repo.all(repo_opts) |> Map.new() for %{id: id} <- users do [Map.get(result, id, default_count)] end end # Fallback to original run_batch def run_batch(queryable, query, col, inputs, repo_opts) do Dataloader.Ecto.run_batch(Repo, queryable, query, col, inputs, repo_opts) end ``` This function is supplied with a list of users, does a query and will return the post count for each of user. If the user id is not found in the resultset, because the user has no posts, we return a post count of 0. Now we need to call `run_batch/5` from dataloader. First we add a few posts to the database. After that, the custom `run_batch/5` function is provided to the Dataloader source. Now, we can load the post count for several users. When the dataloader runs it will call the custom `run_batch/5` and we can retrieve the posts counts for each individual user. ``` [user1, user2] = [%User{id: 1}, %User{id: 2}] rows = [ %{user_id: user1.id, title: "foo", published: true}, %{user_id: user1.id, title: "baz", published: false} ] _ = Repo.insert_all(Post, rows) source = Dataloader.Ecto.new( Repo, query: &query/2, run_batch: &run_batch/5 ) loader = Dataloader.new() |> Dataloader.add_source(Posts, source) loader = loader |> Dataloader.load(Posts, {:one, Post}, post_count: user1) |> Dataloader.load(Posts, {:one, Post}, post_count: user2) |> Dataloader.run() # Returns 2 Dataloader.get(loader, Posts, {:one, Post}, post_count: user1) # Returns 0 Dataloader.get(loader, Posts, {:one, Post}, post_count: user2) ``` Additional params for the `query/2` function can be passed to the load functions with a 3-tuple. For example, to limit the above example to only return published we can add a query function to filter the published posts: ``` def query(Post, %{published: published}) do from p in Post, where: p.published == ^published end def query(queryable, _) do queryable end ``` And we can return the published posts with a 3-tuple on the loader: ``` loader = loader |> Dataloader.load(Posts, {:one, Post}, post_count: user1) |> Dataloader.load(Posts, {:one, Post, %{published: true}}, post_count: user1) |> Dataloader.run() # Returns 2 Dataloader.get(loader, Posts, {:one, Post}, post_count: user1) # Returns 1 Dataloader.get(loader, Posts, {:one, Post, %{published: true}}, post_count: user1) ``` """ defstruct [ :repo, :query, :run_batch, repo_opts: [], batches: %{}, results: %{}, default_params: %{}, options: [] ] @type t :: %__MODULE__{ repo: Ecto.Repo.t(), query: query_fun, repo_opts: repo_opts, batches: map, results: map, default_params: map, run_batch: batch_fun, options: Keyword.t() } @type query_fun :: (Ecto.Queryable.t(), any -> Ecto.Queryable.t()) @type repo_opts :: Keyword.t() @type batch_fun :: (Ecto.Queryable.t(), Ecto.Query.t(), any, [any], repo_opts -> [any]) @type opt :: {:query, query_fun} | {:default_params, map()} | {:repo_opts, repo_opts} | {:timeout, pos_integer} | {:run_batch, batch_fun()} import Ecto.Query @doc """ Create an Ecto Dataloader source. This module handles retrieving data from Ecto for dataloader. It requires a valid Ecto Repo. It also accepts a `repo_opts:` option which is handy for applying options to any calls to Repo functions that this module makes. For example, you can use this module in a multi-tenant context by using the `prefix` option: ``` Dataloader.Ecto.new(MyApp.Repo, repo_opts: [prefix: "tenant"]) ``` """ @spec new(Ecto.Repo.t(), [opt]) :: t def new(repo, opts \\ []) do data = opts |> Keyword.put_new(:query, &query/2) |> Keyword.put_new(:run_batch, &run_batch(repo, &1, &2, &3, &4, &5)) opts = Keyword.take(opts, [:timeout]) %__MODULE__{repo: repo, options: opts} |> struct(data) end @doc """ Default implementation for loading a batch. Handles looking up records by column """ @spec run_batch( repo :: Ecto.Repo.t(), queryable :: Ecto.Queryable.t(), query :: Ecto.Query.t(), col :: any, inputs :: [any], repo_opts :: repo_opts ) :: [any] def run_batch(repo, queryable, query, col, inputs, repo_opts) do results = load_rows(col, inputs, queryable, query, repo, repo_opts) grouped_results = group_results(results, col) for value <- inputs do grouped_results |> Map.get(value, []) |> Enum.reverse() end end defp load_rows(col, inputs, queryable, query, repo, repo_opts) do pk = queryable.__schema__(:primary_key) case query do %Ecto.Query{limit: limit, offset: offset} when pk != [col] and (not is_nil(limit) or not is_nil(offset)) -> load_rows_lateral(col, inputs, queryable, query, repo, repo_opts) _ -> query |> where([q], field(q, ^col) in ^inputs) |> repo.all(repo_opts) end end defp load_rows_lateral(col, inputs, queryable, query, repo, repo_opts) do # Approximate a postgres unnest with a subquery inputs_query = queryable |> where([q], field(q, ^col) in ^inputs) |> select(^[col]) |> distinct(true) inner_query = query |> where([q], field(q, ^col) == field(parent_as(:input), ^col)) |> exclude(:preload) results = from(input in subquery(inputs_query), as: :input) |> join(:inner_lateral, q in subquery(inner_query)) |> select([_input, q], q) |> repo.all(repo_opts) case query.preloads do [] -> results # Preloads can't be used in a subquery, using Repo.preload instead preloads -> repo.preload(results, preloads, repo_opts) end end defp group_results(results, col) do results |> Enum.reduce(%{}, fn result, grouped -> value = Map.get(result, col) Map.update(grouped, value, [result], &[result | &1]) end) end defp query(schema, _) do schema end defimpl Dataloader.Source do def run(source) do results = Dataloader.async_safely(__MODULE__, :run_batches, [source]) results = Map.merge(source.results, results, fn _, {:ok, v1}, {:ok, v2} -> {:ok, Map.merge(v1, v2)} end) %{source | results: results, batches: %{}} end def fetch(source, batch_key, item) do {batch_key, item_key, _item} = batch_key |> normalize_key(source.default_params) |> get_keys(item) with {:ok, batch} <- Map.fetch(source.results, batch_key) do fetch_item_from_batch(batch, item_key) else :error -> {:error, "Unable to find batch #{inspect(batch_key)}"} end end defp fetch_item_from_batch(tried_and_failed = {:error, _reason}, _item_key), do: tried_and_failed defp fetch_item_from_batch({:ok, batch}, item_key) do case Map.fetch(batch, item_key) do :error -> {:error, "Unable to find item #{inspect(item_key)} in batch"} result -> result end end def put(source, _batch, _item, %Ecto.Association.NotLoaded{}) do source end def put(source, batch, item, result) do batch = normalize_key(batch, source.default_params) {batch_key, item_key, _item} = get_keys(batch, item) results = Map.update( source.results, batch_key, {:ok, %{item_key => result}}, fn {:ok, map} -> {:ok, Map.put(map, item_key, result)} end ) %{source | results: results} end def load(source, batch, item) do {batch_key, item_key, item} = batch |> normalize_key(source.default_params) |> get_keys(item) if fetched?(source.results, batch_key, item_key) do source else entry = {item_key, item} update_in(source.batches, fn batches -> Map.update(batches, batch_key, MapSet.new([entry]), &MapSet.put(&1, entry)) end) end end defp fetched?(results, batch_key, item_key) do case results do %{^batch_key => {:ok, %{^item_key => _}}} -> true _ -> false end end def pending_batches?(%{batches: batches}) do batches != %{} end def timeout(%{options: options}) do options[:timeout] end defp chase_down_queryable([field], schema) do case schema.__schema__(:association, field) do %{queryable: queryable} -> queryable %Ecto.Association.HasThrough{through: through} -> chase_down_queryable(through, schema) val -> raise """ Valid association #{field} not found on schema #{inspect(schema)} Got: #{inspect(val)} """ end end defp chase_down_queryable([field | fields], schema) do case schema.__schema__(:association, field) do %{queryable: queryable} -> chase_down_queryable(fields, queryable) %Ecto.Association.HasThrough{through: [through_field | through_fields]} -> [through_field | through_fields ++ fields] |> chase_down_queryable(schema) end end defp get_keys({assoc_field, opts}, %schema{} = record) when is_atom(assoc_field) do validate_queryable(schema) primary_keys = schema.__schema__(:primary_key) id = Enum.map(primary_keys, &Map.get(record, &1)) queryable = chase_down_queryable([assoc_field], schema) {{:assoc, schema, self(), assoc_field, queryable, opts}, id, record} end defp get_keys({{cardinality, queryable}, opts}, value) when is_atom(queryable) do validate_queryable(queryable) {_, col, value} = normalize_value(queryable, value) {{:queryable, self(), queryable, cardinality, col, opts}, value, value} end defp get_keys({queryable, opts}, value) when is_atom(queryable) do validate_queryable(queryable) case normalize_value(queryable, value) do {:primary, col, value} -> {{:queryable, self(), queryable, :one, col, opts}, value, value} {:not_primary, col, _value} -> raise """ Cardinality required unless using primary key The non-primary key column specified was: #{inspect(col)} """ end end defp get_keys(key, item) do raise """ Invalid: #{inspect(key)} #{inspect(item)} The batch key must either be a schema module, or an association name. """ end defp validate_queryable(queryable) do unless {:__schema__, 1} in queryable.__info__(:functions) do raise "The given module - #{queryable} - is not an Ecto schema." end rescue _ in UndefinedFunctionError -> raise Dataloader.GetError, """ The given atom - #{inspect(queryable)} - is not a module. This can happen if you intend to pass an Ecto struct in your call to `dataloader/4` but pass something other than a struct. """ end defp normalize_value(queryable, [{col, value}]) do case queryable.__schema__(:primary_key) do [^col] -> {:primary, col, value} _ -> {:not_primary, col, value} end end defp normalize_value(queryable, value) do [primary_key] = queryable.__schema__(:primary_key) {:primary, primary_key, value} end # This code was totally OK until cardinalities showed up. Now it's ugly :( # It is however correct, which is nice. @cardinalities [:one, :many] defp normalize_key({cardinality, queryable}, default_params) when cardinality in @cardinalities do normalize_key({{cardinality, queryable}, []}, default_params) end defp normalize_key({cardinality, queryable, params}, default_params) when cardinality in @cardinalities do normalize_key({{cardinality, queryable}, params}, default_params) end defp normalize_key({key, params}, default_params) do {key, Enum.into(params, default_params)} end defp normalize_key(key, default_params) do {key, default_params} end def run_batches(source) do options = [ timeout: source.options[:timeout] || Dataloader.default_timeout(), on_timeout: :kill_task ] batches = Enum.to_list(source.batches) results = batches |> Task.async_stream( fn batch -> id = :erlang.unique_integer() system_time = System.system_time() start_time_mono = System.monotonic_time() emit_start_event(id, system_time, batch) batch_result = run_batch(batch, source) emit_stop_event(id, start_time_mono, batch) batch_result end, options ) |> Enum.map(fn {:ok, {_key, result}} -> {:ok, result} {:exit, reason} -> {:error, reason} end) batches |> Enum.map(fn {key, _set} -> key end) |> Enum.zip(results) |> Map.new() end defp run_batch( {{:queryable, pid, queryable, cardinality, col, opts} = key, entries}, source ) do inputs = Enum.map(entries, &elem(&1, 0)) query = source.query.(queryable, opts) repo_opts = Keyword.put(source.repo_opts, :caller, pid) cardinality_mapper = cardinality_mapper(cardinality, queryable) coerced_inputs = if type = queryable.__schema__(:type, col) do for input <- inputs do {:ok, input} = Ecto.Type.cast(type, input) input end else inputs end results = queryable |> source.run_batch.(query, col, coerced_inputs, repo_opts) |> Enum.map(cardinality_mapper) results = inputs |> Enum.zip(results) |> Map.new() {key, results} end defp run_batch({{:assoc, schema, pid, field, queryable, opts} = key, records}, source) do {ids, records} = Enum.unzip(records) query = source.query.(queryable, opts) |> Ecto.Queryable.to_query() repo_opts = Keyword.put(source.repo_opts, :caller, pid) empty = schema |> struct |> Map.fetch!(field) records = records |> Enum.map(&Map.put(&1, field, empty)) results = if query.limit || query.offset do records |> preload_lateral(field, query, source.repo, repo_opts) else records |> source.repo.preload([{field, query}], repo_opts) end results = results |> Enum.map(&Map.get(&1, field)) {key, Map.new(Enum.zip(ids, results))} end def preload_lateral([], _assoc, _query, _opts), do: [] def preload_lateral([%schema{} = struct | _] = structs, assoc, query, repo, repo_opts) do [pk] = schema.__schema__(:primary_key) # Carry the database prefix across from already-loaded records if not already set repo_opts = Keyword.put_new(repo_opts, :prefix, struct.__meta__.prefix) assocs = expand_assocs(schema, [assoc]) query_excluding_preloads = exclude(query, :preload) inner_query = assocs |> Enum.reverse() |> build_preload_lateral_query(query_excluding_preloads, :join_first) |> maybe_distinct(assocs) results = from(x in schema, as: :parent, inner_lateral_join: y in subquery(inner_query), where: field(x, ^pk) in ^Enum.map(structs, &Map.get(&1, pk)), select: {field(x, ^pk), y} ) |> repo.all(repo_opts) results = case query.preloads do [] -> results # Preloads can't be used in a subquery, using Repo.preload instead preloads -> {keys, vals} = Enum.unzip(results) vals = repo.preload(vals, preloads, repo_opts) Enum.zip(keys, vals) end {keyed, default} = case schema.__schema__(:association, assoc) do %{cardinality: :one} -> {results |> Map.new(), nil} %{cardinality: :many} -> {Enum.group_by(results, fn {k, _} -> k end, fn {_, v} -> v end), []} end structs |> Enum.map(&Map.put(&1, assoc, Map.get(keyed, Map.get(&1, pk), default))) end defp expand_assocs(_schema, []), do: [] defp expand_assocs(schema, [assoc | rest]) do case schema.__schema__(:association, assoc) do %Ecto.Association.HasThrough{through: through} -> expand_assocs(schema, through ++ rest) a -> [a | expand_assocs(a.queryable, rest)] end end defp build_preload_lateral_query( [%Ecto.Association.ManyToMany{} = assoc], query, :join_first ) do [{owner_join_key, owner_key}, {related_join_key, related_key}] = get_join_keys(assoc) join_query = query |> join(:inner, [x], y in ^assoc.join_through, on: field(x, ^related_key) == field(y, ^related_join_key) ) |> where( [..., x], field(x, ^owner_join_key) == field(parent_as(:parent), ^owner_key) ) binds_count = Ecto.Query.Builder.count_binds(join_query) join_query |> Ecto.Association.combine_joins_query(assoc.where, 0) |> Ecto.Association.combine_joins_query(assoc.join_where, binds_count - 1) end defp build_preload_lateral_query( [%Ecto.Association.ManyToMany{} = assoc], query, :join_last ) do [{owner_join_key, owner_key}, {related_join_key, related_key}] = get_join_keys(assoc) join_query = query |> join(:inner, [..., x], y in ^assoc.join_through, on: field(x, ^related_key) == field(y, ^related_join_key) ) |> where( [..., x], field(x, ^owner_join_key) == field(parent_as(:parent), ^owner_key) ) binds_count = Ecto.Query.Builder.count_binds(join_query) join_query |> Ecto.Association.combine_joins_query(assoc.where, binds_count - 2) |> Ecto.Association.combine_joins_query(assoc.join_where, binds_count - 1) end defp build_preload_lateral_query([assoc], query, :join_first) do case assoc do %{ related_key: [related_key_1, related_key_2], owner_key: [owner_key_1, owner_key_2] } -> query |> where( [x], field(x, ^related_key_1) == field(parent_as(:parent), ^owner_key_1) and field(x, ^related_key_2) == field(parent_as(:parent), ^owner_key_2) ) |> Ecto.Association.combine_assoc_query(assoc.where) %{ related_key: [related_key], owner_key: [owner_key] } -> query |> where( [x], field(x, ^related_key) == field(parent_as(:parent), ^owner_key) ) |> Ecto.Association.combine_assoc_query(assoc.where) assoc -> query |> where( [x], field(x, ^assoc.related_key) == field(parent_as(:parent), ^assoc.owner_key) ) |> Ecto.Association.combine_assoc_query(assoc.where) end end defp build_preload_lateral_query([assoc], query, :join_last) do join_query = case assoc do %{ related_key: [related_key_1, related_key_2], owner_key: [owner_key_1, owner_key_2] } -> query |> where( [..., x], field(x, ^related_key_1) == field(parent_as(:parent), ^owner_key_1) and field(x, ^related_key_2) == field(parent_as(:parent), ^owner_key_2) ) %{ related_key: [related_key], owner_key: [owner_key] } -> query |> where( [..., x], field(x, ^related_key) == field(parent_as(:parent), ^owner_key) ) assoc -> query |> where( [..., x], field(x, ^assoc.related_key) == field(parent_as(:parent), ^assoc.owner_key) ) end binds_count = Ecto.Query.Builder.count_binds(join_query) join_query |> Ecto.Association.combine_joins_query(assoc.where, binds_count - 1) end defp build_preload_lateral_query( [%Ecto.Association.ManyToMany{} = assoc | rest], query, :join_first ) do [{owner_join_key, owner_key}, {related_join_key, related_key}] = get_join_keys(assoc) join_query = query |> join(:inner, [x], y in ^assoc.join_through, on: field(x, ^related_key) == field(y, ^related_join_key) ) |> join(:inner, [..., x], y in ^assoc.owner, on: field(x, ^owner_join_key) == field(y, ^owner_key) ) binds_count = Ecto.Query.Builder.count_binds(join_query) query = join_query |> Ecto.Association.combine_joins_query(assoc.where, 0) |> Ecto.Association.combine_joins_query(assoc.join_where, binds_count - 2) build_preload_lateral_query(rest, query, :join_last) end defp build_preload_lateral_query( [%Ecto.Association.ManyToMany{} = assoc | rest], query, :join_last ) do [{owner_join_key, owner_key}, {related_join_key, related_key}] = get_join_keys(assoc) join_query = query |> join(:inner, [..., x], y in ^assoc.join_through, on: field(x, ^related_key) == field(y, ^related_join_key) ) |> join(:inner, [..., x], y in ^assoc.owner, on: field(x, ^owner_join_key) == field(y, ^owner_key) ) binds_count = Ecto.Query.Builder.count_binds(join_query) query = join_query |> Ecto.Association.combine_joins_query(assoc.where, binds_count - 3) |> Ecto.Association.combine_joins_query(assoc.join_where, binds_count - 2) build_preload_lateral_query(rest, query, :join_last) end defp build_preload_lateral_query( [assoc | rest], query, :join_first ) do query = case assoc do %{ related_key: [related_key_1, related_key_2], owner_key: [owner_key_1, owner_key_2] } -> query |> join(:inner, [x], y in ^assoc.owner, on: field(x, ^related_key_1) == field(y, ^owner_key_1) and field(x, ^related_key_2) == field(y, ^owner_key_2) ) |> Ecto.Association.combine_joins_query(assoc.where, 0) %{ related_key: [related_key], owner_key: [owner_key] } -> query |> join(:inner, [x], y in ^assoc.owner, on: field(x, ^related_key) == field(y, ^owner_key) ) |> Ecto.Association.combine_joins_query(assoc.where, 0) assoc -> query |> join(:inner, [x], y in ^assoc.owner, on: field(x, ^assoc.related_key) == field(y, ^assoc.owner_key) ) |> Ecto.Association.combine_joins_query(assoc.where, 0) end build_preload_lateral_query(rest, query, :join_last) end defp build_preload_lateral_query( [assoc | rest], query, :join_last ) do binds_count = Ecto.Query.Builder.count_binds(query) join_query = case assoc do %{ related_key: [related_key_1, related_key_2], owner_key: [owner_key_1, owner_key_2] } -> query |> Ecto.Association.combine_joins_query(assoc.where, binds_count - 1) |> join(:inner, [..., x], y in ^assoc.owner, on: field(x, ^related_key_1) == field(y, ^owner_key_1) and field(x, ^related_key_2) == field(y, ^owner_key_2) ) %{ related_key: [related_key], owner_key: [owner_key] } -> query |> Ecto.Association.combine_joins_query(assoc.where, binds_count - 1) |> join(:inner, [..., x], y in ^assoc.owner, on: field(x, ^related_key) == field(y, ^owner_key) ) assoc -> query |> Ecto.Association.combine_joins_query(assoc.where, binds_count - 1) |> join(:inner, [..., x], y in ^assoc.owner, on: field(x, ^assoc.related_key) == field(y, ^assoc.owner_key) ) end build_preload_lateral_query(rest, join_query, :join_last) end defp get_join_keys(%Ecto.Association.ManyToMany{join_keys: join_keys}) do case join_keys do [[{owner_join_key, owner_key}], [{related_join_key, related_key}]] -> [{owner_join_key, owner_key}, {related_join_key, related_key}] join_keys -> join_keys end end defp maybe_distinct(query, [%Ecto.Association.Has{}, %Ecto.Association.BelongsTo{} | _]) do distinct(query, true) end defp maybe_distinct(query, [%Ecto.Association.ManyToMany{} | _]), do: distinct(query, true) defp maybe_distinct(query, [_assoc | rest]), do: maybe_distinct(query, rest) defp maybe_distinct(query, []), do: query defp emit_start_event(id, system_time, batch) do :telemetry.execute( [:dataloader, :source, :batch, :run, :start], %{system_time: system_time}, %{id: id, batch: batch} ) end defp emit_stop_event(id, start_time_mono, batch) do :telemetry.execute( [:dataloader, :source, :batch, :run, :stop], %{duration: System.monotonic_time() - start_time_mono}, %{id: id, batch: batch} ) end defp cardinality_mapper(:many, _) do fn value when is_list(value) -> value value -> [value] end end defp cardinality_mapper(:one, queryable) do fn [] -> nil [value] -> value other when is_list(other) -> raise Ecto.MultipleResultsError, queryable: queryable, count: length(other) other -> other end end end end end
31.092105
97
0.56901
7972d7a9b78b825fe316d5b7b553ef2513c50e58
1,081
ex
Elixir
lib/credo/check/warning/unused_string_operation.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
null
null
null
lib/credo/check/warning/unused_string_operation.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
null
null
null
lib/credo/check/warning/unused_string_operation.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
1
2020-09-25T11:48:49.000Z
2020-09-25T11:48:49.000Z
defmodule Credo.Check.Warning.UnusedStringOperation do @moduledoc false @checkdoc """ The result of a call to the String module's functions has to be used. While this is correct ... def salutation(username) do username = String.downcase(username) "Hi #\{username}" end ... we forgot to save the downcased username in this example: # This is bad because it does not modify the username variable! def salutation(username) do String.downcase(username) "Hi #\{username}" end Since Elixir variables are immutable, String operations never work on the variable you pass in, but return a new variable which has to be used somehow. """ @explanation [check: @checkdoc] @checked_module :String @funs_with_return_value nil use Credo.Check, base_priority: :high alias Credo.Check.Warning.UnusedOperation def run(source_file, params \\ []) do UnusedOperation.run( source_file, params, @checked_module, @funs_with_return_value, &format_issue/2 ) end end
23.5
79
0.682701
7972e67f3e18f22ec08288a0816c7818acedd169
3,656
exs
Elixir
test/ecto/validator_test.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
1
2016-08-15T21:23:28.000Z
2016-08-15T21:23:28.000Z
test/ecto/validator_test.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
null
null
null
test/ecto/validator_test.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.ValidatorTest do use ExUnit.Case, async: true require Ecto.Validator, as: V defmodule User do defstruct name: "jose", age: 27 end test "struct with no predicate" do assert V.struct(%User{}, []) == nil end test "struct dispatches to a module predicate" do assert V.struct(%User{}, name: present()) == nil assert V.struct(%User{name: nil}, name: present()) == %{name: ["can't be blank"]} end test "struct dispatches to a remote predicate" do assert V.struct(%User{}, name: __MODULE__.present()) == nil assert V.struct(%User{name: nil}, name: __MODULE__.present()) == %{name: ["can't be blank"]} end test "struct dispatches to a local predicate" do present = &present/2 assert V.struct(%User{}, name: present.()) == nil assert V.struct(%User{name: nil}, name: present.()) == %{name: ["can't be blank"]} end test "struct handles conditionals" do user = %User{age: nil} assert V.struct(user, age: present() when user.name != "jose") == nil user = %User{name: "eric", age: nil} assert V.struct(user, age: present() when user.name != "jose") == %{age: ["can't be blank"]} end test "struct handles and" do user = %User{age: nil} assert V.struct(user, age: present() and greater_than(18)) == %{age: ["can't be blank"]} user = %User{age: 10} assert V.struct(user, age: present() and greater_than(18)) == %{age: ["too big"]} user = %User{age: 20} assert V.struct(user, age: present() and greater_than(18) and less_than(30)) == nil end test "struct handles and with conditionals" do user = %User{name: "eric", age: nil} assert V.struct(user, age: present() and greater_than(18) when user.name != "jose") == %{age: ["can't be blank"]} end test "struct passes predicate arguments" do assert V.struct(%User{name: nil}, name: present(message: "must be present")) == %{name: ["must be present"]} end test "struct is evaluated just once" do Process.put(:count, 0) assert V.struct((Process.put(:count, Process.get(:count) + 1); %User{}), name: present()) == nil assert Process.get(:count) == 1 end test "struct dispatches to also" do assert V.struct(%User{name: nil, age: nil}, name: present(), also: validate_other) == %{name: ["can't be blank"], age: ["can't be blank"]} assert V.struct(%User{name: nil, age: nil}, also: validate_other and validate_other) == %{age: ["can't be blank", "can't be blank"]} assert V.struct(%User{name: "name", age: 6}, also: validate_other) == nil end test "validates dicts" do assert V.dict([name: nil, age: 27], name: present(), age: present()) == %{name: ["can't be blank"]} end test "validates binary dicts" do assert V.bin_dict(%{"name" => nil, "age" => 27}, name: present(), age: present()) == %{name: ["can't be blank"]} end def present(_field, value, opts \\ []) def present(_field, nil, opts), do: opts[:message] || "can't be blank" def present(_field, _value, _opts), do: nil def greater_than(_field, value, min, opts \\ []) def greater_than(_field, value, min, _opts) when value > min, do: nil def greater_than(_field, _value, _min, opts), do: opts[:message] || "too big" def less_than(_field, value, max, opts \\ []) def less_than(_field, value, max, _opts) when value < max, do: nil def less_than(_field, _value, _max, opts), do: opts[:message] || "too low" defp validate_other(struct) do V.struct(struct, age: present()) end end
34.490566
117
0.607221
7972e8647efe5e5c605ff477968b5d4114e7fd75
1,687
exs
Elixir
test/tackle/multiconsumer_test.exs
renderedtext/ex-tackle
403623f9be6919998fea6871f34aa07ff2655c49
[ "MIT" ]
49
2016-07-30T13:45:12.000Z
2021-08-08T13:45:05.000Z
test/tackle/multiconsumer_test.exs
renderedtext/ex-tackle
403623f9be6919998fea6871f34aa07ff2655c49
[ "MIT" ]
20
2016-08-05T11:54:35.000Z
2021-06-02T19:43:06.000Z
test/tackle/multiconsumer_test.exs
renderedtext/ex-tackle
403623f9be6919998fea6871f34aa07ff2655c49
[ "MIT" ]
14
2016-08-05T09:39:51.000Z
2021-11-29T14:22:28.000Z
defmodule Tackle.MulticonsumerTest do use ExUnit.Case, async: false defmodule MulticonsumerExample do use Tackle.Multiconsumer, url: "amqp://localhost", service: "example_service", routes: [ {"exchange-1", "key1", :handler} ] def handler(_message) do IO.puts("Handled!") end end defmodule MulticonsumerExampleBeta do use Tackle.Multiconsumer, url: "amqp://localhost", service: "#{System.get_env("A")}.example_beta_service", routes: [ {"exchange-1", "key1", :handler} ] def handler(_message) do IO.puts("Handled!") end end test "inspect modules" do defined_consumer_modules = :code.all_loaded() |> Enum.map(fn {mod, _} -> mod end) |> Enum.filter(fn module -> String.contains?(Atom.to_string(module), "exchange-1.key1") end) |> Enum.sort() expected_consumer_modules = [ :"Elixir.Tackle.MulticonsumerTest.MulticonsumerExampleBeta.exchange-1.key1", :"Elixir.Tackle.MulticonsumerTest.MulticonsumerExample.exchange-1.key1" ] |> Enum.sort() assert defined_consumer_modules == expected_consumer_modules end test "successfully starts multiconsumers the old way" do import Supervisor.Spec opts = [strategy: :one_for_one, name: Front.Supervisor] Supervisor.start_link( [worker(MulticonsumerExample, []), worker(MulticonsumerExampleBeta, [])], opts ) end test "successfully starts multiconsumers" do opts = [strategy: :one_for_one, name: Front.Supervisor] Supervisor.start_link( [MulticonsumerExample, MulticonsumerExampleBeta], opts ) end end
25.560606
98
0.65738
7972eb1cca73ad361a257d9fd3255b9c9afcd5a8
369
exs
Elixir
.formatter.exs
eahanson/schema_assertions
35760374e2c1e837c5ea6fc0bde4baea53677c83
[ "Apache-2.0" ]
null
null
null
.formatter.exs
eahanson/schema_assertions
35760374e2c1e837c5ea6fc0bde4baea53677c83
[ "Apache-2.0" ]
null
null
null
.formatter.exs
eahanson/schema_assertions
35760374e2c1e837c5ea6fc0bde4baea53677c83
[ "Apache-2.0" ]
null
null
null
# Used by "mix format" [ import_deps: [:ecto], inputs: ["{mix,.formatter,.credo}.exs", "{config,lib,test}/**/*.{ex,exs}"], line_length: 120, subdirectories: ["priv/*/migrations"], export: [ locals_without_parens: [ assert_changeset_fields: :*, assert_changeset_invalid: :*, assert_changeset_valid: :*, assert_schema: 3 ] ] ]
23.0625
77
0.612466
7972effa20594a1d0b6ea00f4b2a975635a905e7
201
exs
Elixir
arc_playground/test/test_helper.exs
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
arc_playground/test/test_helper.exs
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
arc_playground/test/test_helper.exs
enilsen16/elixir
b4d1d45858a25e4beb39e07de8685f3d93d6a520
[ "MIT" ]
null
null
null
ExUnit.start Mix.Task.run "ecto.create", ~w(-r ArcPlayground.Repo --quiet) Mix.Task.run "ecto.migrate", ~w(-r ArcPlayground.Repo --quiet) Ecto.Adapters.SQL.begin_test_transaction(ArcPlayground.Repo)
28.714286
62
0.766169
797312daadc222644d1d3e4f93231da44524a424
577
ex
Elixir
elixir/lib/elixir_example/application.ex
kintoproj/kinto-examples
8903127efab78424da936ff1516d3872dd997aaa
[ "Apache-2.0" ]
null
null
null
elixir/lib/elixir_example/application.ex
kintoproj/kinto-examples
8903127efab78424da936ff1516d3872dd997aaa
[ "Apache-2.0" ]
null
null
null
elixir/lib/elixir_example/application.ex
kintoproj/kinto-examples
8903127efab78424da936ff1516d3872dd997aaa
[ "Apache-2.0" ]
1
2021-08-02T17:57:11.000Z
2021-08-02T17:57:11.000Z
defmodule ElixirExample.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ Plug.Cowboy.child_spec( scheme: :http, plug: ElixirExample.Endpoint, options: [port: 3000] ) ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: ElixirExample.Supervisor] Supervisor.start_link(children, opts) end end
25.086957
67
0.686308
79731425c7a99d85fecbce3057743a53324cef29
528
ex
Elixir
lib/ipc/server.ex
pshah123/elixir-simple
0b9d488769f9ef6924c8ae3753d0880d05f70015
[ "MIT" ]
null
null
null
lib/ipc/server.ex
pshah123/elixir-simple
0b9d488769f9ef6924c8ae3753d0880d05f70015
[ "MIT" ]
null
null
null
lib/ipc/server.ex
pshah123/elixir-simple
0b9d488769f9ef6924c8ae3753d0880d05f70015
[ "MIT" ]
null
null
null
defmodule IPCServer do def run n \\ 2 do peers = 1..n |> Enum.map(fn _ -> spawn Peer, :init, [ self() ] end) peers = MapSet.new(peers) peers |> Enum.map(&(send &1, {:BIND, peers})) loop peers end def loop peers do receive do {:FIN, peer} -> IO.puts("#{inspect peer} terminated.") peers = peers |> MapSet.delete(peer) if peers |> MapSet.size > 0 do loop peers else IO.puts "All processes finished." True end end end end
22.956522
71
0.534091
7973154c499a8a1c4831c3a5156d4ac9f0964b55
93
exs
Elixir
test/day21_test.exs
anamba/adventofcode2020
2a749140d5393f7c69c630102daae977be30afcc
[ "MIT" ]
null
null
null
test/day21_test.exs
anamba/adventofcode2020
2a749140d5393f7c69c630102daae977be30afcc
[ "MIT" ]
null
null
null
test/day21_test.exs
anamba/adventofcode2020
2a749140d5393f7c69c630102daae977be30afcc
[ "MIT" ]
null
null
null
defmodule Day21Test do use ExUnit.Case # doctest Day21.Part1 # doctest Day21.Part2 end
15.5
23
0.752688
797320015ba575466d8038eb67017cbef95a2b4b
8,610
ex
Elixir
lib/textwrap.ex
foxbenjaminfox/ex_textwrap
2e23b7fb63447de99edf03f745a003c45c0ffb76
[ "Apache-2.0" ]
null
null
null
lib/textwrap.ex
foxbenjaminfox/ex_textwrap
2e23b7fb63447de99edf03f745a003c45c0ffb76
[ "Apache-2.0" ]
null
null
null
lib/textwrap.ex
foxbenjaminfox/ex_textwrap
2e23b7fb63447de99edf03f745a003c45c0ffb76
[ "Apache-2.0" ]
null
null
null
defmodule Textwrap do @moduledoc """ `Textwrap` provides a set of functions for wrapping, indenting, and dedenting text. It wraps the Rust [`textwrap`](https://lib.rs/textwrap) crate. ## Wrapping Use `wrap/2` to turn a `String` into a list of `String`s each no more than `width` characters long. iex> Textwrap.wrap("foo bar baz", 3) ["foo", "bar", "baz"] iex> Textwrap.wrap("foo bar baz", 7) ["foo bar", "baz"] `fill/2` is like `wrap/2`, except that it retuns the wrapped text as a single `String`. iex> Textwrap.fill("foo bar baz", 3) "foo\\nbar\\nbaz" iex> Textwrap.fill("foo bar baz", 7) "foo bar\\nbaz" Both `wrap/2` and `fill/2` can either take the width to wrap too as their second argument, or take a keyword list including a `:width` key and any number of other options. See the docs for `wrap/2` for details. ## Displayed Width vs Byte Width `Textwrap` wraps text based on measured display width, not simply counting bytes. For ascii text this gives exactly the same result, but many non-ASCII characters take up more than one byte in the UTF-8 encoding. See the documentation of the [`textwrap` crate](https://docs.rs/textwrap/0.13.2/textwrap/index.html#displayed-width-vs-byte-size) for more details. ## Terminal Width The `width` passed to `wrap/2` or `fill/2` can either by a positive integer, or the atom `:termwidth`. When standard output is connected to a terminal, passing `:termwidth` will wrap the text to the width of the terminal. Otherwise, it will use a width of 80 characters as a fallback. ## Indenting and Dedenting Use `indent/2` and `dedent/1` to indent and dedent text: iex> Textwrap.indent("hello\\nworld\\n", " ") " hello\\n world\\n" iex> Textwrap.dedent(" hello\\n world\\n") "hello\\nworld\\n" """ use Rustler, otp_app: :textwrap, crate: "textwrap_nif" @type wrap_opts() :: pos_integer() | :termwidth | [wrap_opt()] @type wrap_opt() :: {:width, pos_integer() | :termwidth} | {:break_words, boolean()} | {:initial_indent, String.t()} | {:splitter, nil | :en_us | false} | {:subsequent_indent, String.t()} | {:wrap_algorithm, wrap_algorithm()} @type wrap_algorithm() :: :first_fit | :optimal_fit @spec wrap(text :: String.t(), opts :: wrap_opts()) :: [String.t()] @doc """ Wraps text to the given width. `wrap/2` returns a list of `Strings`, each of no more than `width` charecters. Options can be either passed as a keyword list (which must include the key `:width`), or, if using no options other than `:width`, the width can be passed on its own as the second argument. `width` can either by a positive integer or the atom `:termwidth`. See the [module docs](#module-terminal-width) on `:termwidth` for more details. ## Options - `:width` — the width to wrap at, a positive integer. - `:break_words` — allow long words to be broken, if they won't fit on a single line. Setting this to false may cause some lines to be longer than `:width`. - `:inital_indent` — will be added as a prefix to the first line of the result. - `:subsequent_indent` — will be added as a prefix to each line other than the first line of the result. - `:splitter` — when set to `false`, hyphens within words won't be treated specially as a place to split words. When set to `:en_us`, a language-aware hyphenation system will be used to try to break words in appropriate places. - `:wrap_algorithm` — by default, or when set to `:optimal_fit`, `wrap/2` will do its best to balance the gaps left at the ends of lines. When set to `:first_fit`, a simpler greedy algorithm is used instead. See the docs in the [`textwrap` crate](https://docs.rs/textwrap/0.13.2/textwrap/core/enum.WrapAlgorithm.html) for more details. ## Examples iex> Textwrap.wrap("hello world", 5) ["hello", "world"] iex> Textwrap.wrap("hello world", width: 5) ["hello", "world"] iex> Textwrap.wrap("Antidisestablishmentarianism", width: 10) ["Antidisest", "ablishment", "arianism"] iex> Textwrap.wrap("Antidisestablishmentarianism", width: 10, break_words: false) ["Antidisestablishmentarianism"] iex> Textwrap.wrap("Antidisestablishmentarianism", width: 10, splitter: :en_us) ["Antidis-", "establish-", "mentarian-", "ism"] iex> Textwrap.wrap("foo bar baz", ...> width: 5, ...> initial_indent: "> ", ...> subsequent_indent: " ") ["> foo", " bar", " baz"] iex> Textwrap.wrap("Lorem ipsum dolor sit amet, consectetur adipisicing elit", ...> width: 25, ...> wrap_algorithm: :optimal_fit) ["Lorem ipsum dolor", "sit amet, consectetur", "adipisicing elit"] iex> Textwrap.wrap("Lorem ipsum dolor sit amet, consectetur adipisicing elit", ...> width: 25, ...> wrap_algorithm: :first_fit) ["Lorem ipsum dolor sit", "amet, consectetur", "adipisicing elit"] """ def wrap(text, width_or_opts) def wrap(text, width) when is_integer(width) or width == :termwidth do wrap(text, width: width) end def wrap(text, opts) do width = fetch_width!(opts) wrap_nif(text, width, opts) end @spec fill(text :: String.t(), opts :: wrap_opts()) :: String.t() @doc """ Fills text to the given width. The result is a `String`, with lines seperated by newline. The `wrap/2` function does the same thing, except that it returns a list of `Strings`, one for each line. See the docs for `wrap/2` for details about the options it takes. ## Examples iex> Textwrap.fill("hello world", 5) "hello\\nworld" iex> Textwrap.fill("hello world", width: 5) "hello\\nworld" iex> Textwrap.fill("Antidisestablishmentarianism", width: 10) "Antidisest\\nablishment\\narianism" iex> Textwrap.fill("Antidisestablishmentarianism", width: 10, break_words: false) "Antidisestablishmentarianism" iex> Textwrap.fill("Antidisestablishmentarianism", width: 10, splitter: :en_us) "Antidis-\\nestablish-\\nmentarian-\\nism" iex> Textwrap.fill("foo bar baz", ...> width: 5, ...> initial_indent: "> ", ...> subsequent_indent: " ") "> foo\\n bar\\n baz" iex> Textwrap.fill("Lorem ipsum dolor sit amet, consectetur adipisicing elit", ...> width: 25, ...> wrap_algorithm: :optimal_fit) "Lorem ipsum dolor\\nsit amet, consectetur\\nadipisicing elit" iex> Textwrap.fill("Lorem ipsum dolor sit amet, consectetur adipisicing elit", ...> width: 25, ...> wrap_algorithm: :first_fit) "Lorem ipsum dolor sit\\namet, consectetur\\nadipisicing elit" """ def fill(text, width_or_opts) def fill(text, width) when is_integer(width) or width == :termwidth do fill(text, width: width) end def fill(text, opts) do width = fetch_width!(opts) fill_nif(text, width, opts) end @spec dedent(text :: String.t()) :: String.t() @doc """ Removes as much common leading whitespace as possible from each line. Each non-empty line has an equal amount of whitespace removed from its start. Empty lines (containing only whitespace) are normalized to a single `\\n`, with no other whitespace on the line. ## Examples: iex> Textwrap.dedent(" hello world") "hello world" iex> Textwrap.dedent(" ...> foo ...> bar ...> baz ...> ") "\\nfoo\\n bar\\nbaz\\n" """ def dedent(_text), do: :erlang.nif_error(:nif_not_loaded) @spec indent(text :: String.t(), prefix :: String.t()) :: String.t() @doc """ Adds a given prefix to each non-empty line. Empty lines (containing only whitespace) are normalized to a single `\\n`, and not indented. Any leading and trailing whitespace on non-empty lines is left unchanged. Examples: iex> Textwrap.indent("hello world", ">") ">hello world" iex> Textwrap.indent("foo\\nbar\\nbaz\\n", " ") " foo\\n bar\\n baz\\n" """ def indent(_text, _prefix), do: :erlang.nif_error(:nif_not_loaded) defp fill_nif(_text, _width, _opts), do: :erlang.nif_error(:nif_not_loaded) defp wrap_nif(_text, _width, _opts), do: :erlang.nif_error(:nif_not_loaded) defp fetch_width!(opts) do case Keyword.fetch!(opts, :width) do :termwidth -> termwidth() width -> width end end defp termwidth, do: :erlang.nif_error(:nif_not_loaded) end
35.432099
232
0.646574
797333ed3ce2271026d7bd1ae3e676e58b354a56
1,332
ex
Elixir
lib/livebook_web/live/hooks/user_hook.ex
aleDsz/livebook
3ad817ac69b8459b684ff8d00c879ae7787b6dcc
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/hooks/user_hook.ex
aleDsz/livebook
3ad817ac69b8459b684ff8d00c879ae7787b6dcc
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/hooks/user_hook.ex
aleDsz/livebook
3ad817ac69b8459b684ff8d00c879ae7787b6dcc
[ "Apache-2.0" ]
null
null
null
defmodule LivebookWeb.UserHook do import Phoenix.LiveView alias Livebook.Users.User def on_mount(:default, _params, %{"current_user_id" => current_user_id} = session, socket) do if connected?(socket) do Livebook.Users.subscribe(current_user_id) end socket = socket |> assign_new(:current_user, fn -> build_current_user(session, socket) end) |> attach_hook(:current_user_subscription, :handle_info, &info/2) {:cont, socket} end defp info( {:user_change, %{id: id} = user}, %{assigns: %{current_user: %{id: id}}} = socket ) do {:cont, assign(socket, :current_user, user)} end defp info(_message, socket), do: {:cont, socket} # Builds `Livebook.Users.User` using information from # session and socket. # # Uses `user_data` from socket `connect_params` as initial # attributes if the socket is connected. Otherwise uses # `user_data` from session. defp build_current_user(session, socket) do %{"current_user_id" => current_user_id} = session connect_params = get_connect_params(socket) || %{} user_data = connect_params["user_data"] || session["user_data"] || %{} case User.change(%{User.new() | id: current_user_id}, user_data) do {:ok, user} -> user {:error, _errors, user} -> user end end end
28.956522
95
0.662162
7973b4da64f48bb77cb0dc31d9fcbbcb4adfde13
1,606
ex
Elixir
lib/hello_web.ex
youknowcast/aiit_sp_challenge4
a5811675b77f4c496c9456a74e986ba1cfd8ef2f
[ "MIT" ]
5
2015-09-11T15:02:54.000Z
2020-10-14T05:16:18.000Z
lib/hello_web.ex
youknowcast/aiit_sp_challenge4
a5811675b77f4c496c9456a74e986ba1cfd8ef2f
[ "MIT" ]
21
2019-12-28T11:18:09.000Z
2022-01-02T10:32:36.000Z
lib/hello_web.ex
youknowcast/aiit_sp_challenge4
a5811675b77f4c496c9456a74e986ba1cfd8ef2f
[ "MIT" ]
2
2016-11-07T23:16:56.000Z
2020-10-14T05:16:49.000Z
defmodule HelloWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use HelloWeb, :controller use HelloWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: HelloWeb import Plug.Conn import HelloWeb.Gettext alias HelloWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/hello_web/templates", namespace: HelloWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import HelloWeb.ErrorHelpers import HelloWeb.Gettext alias HelloWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import HelloWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
22.942857
83
0.684309
7973e84d7d345677bd847a0ec8212745075c5403
1,317
ex
Elixir
clients/api_keys/lib/google_api/api_keys/v2/connection.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/api_keys/lib/google_api/api_keys/v2/connection.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/api_keys/lib/google_api/api_keys/v2/connection.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.APIKeys.V2.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.APIKeys.V2. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account. "https://www.googleapis.com/auth/cloud-platform", # View your data across Google Cloud services and see the email address of your Google Account "https://www.googleapis.com/auth/cloud-platform.read-only" ], otp_app: :google_api_api_keys, base_url: "https://apikeys.googleapis.com/" end
36.583333
114
0.736522
79741a58b48635746381a852bf43cc9204905f3f
3,471
ex
Elixir
lib/twemoji.ex
Ovyerus/twemoji-elixir
0f2359e1110173126d844c0c79add56f044d16f6
[ "MIT" ]
6
2021-02-27T07:23:41.000Z
2021-04-08T07:37:50.000Z
lib/twemoji.ex
Ovyerus/twemoji-elixir
0f2359e1110173126d844c0c79add56f044d16f6
[ "MIT" ]
1
2021-02-27T07:30:55.000Z
2021-02-27T07:30:55.000Z
lib/twemoji.ex
Ovyerus/twemoji-elixir
0f2359e1110173126d844c0c79add56f044d16f6
[ "MIT" ]
1
2021-02-27T07:28:59.000Z
2021-02-27T07:28:59.000Z
defmodule Twemoji do @moduledoc """ Documentation for `Twemoji`. """ @twemoji_cdn "https://twemoji.maxcdn.com/2/72x72/" @type floki_node :: String.t() | {String.t(), [] | [{String.t(), String.t()}], [] | [floki_node()]} @type earmark_node :: String.t() | {String.t(), [] | [{String.t(), String.t()}], [] | [earmark_node()], %{}} @type ast :: [floki_node() | earmark_node()] | [] # TODO: custom settings for cdn/format (e.g., svg emoji instead of png, or selfhosted/alt cdn) @spec parse(String.t() | ast()) :: String.t() def parse([]), do: "" def parse(input) do input |> parse_as_ast() |> case do {:ok, ast} -> Floki.raw_html(ast) {:error, _} -> input end end def parse_as_ast(input, opts \\ []) @spec parse_as_ast(String.t() | ast(), [any()]) :: {:ok, ast()} | {:error, String.t()} def parse_as_ast([], _opts), do: {:ok, []} def parse_as_ast([_ | _] = ast, opts) do result = with p_ast <- process_ast(ast), p when is_list(p) <- List.flatten(p_ast) do {:ok, p} else {:error, _} = e -> e end format = Keyword.get(opts, :format, :floki) with {:ok, ast} <- result, converted <- transpose_ast(ast, format) do {:ok, converted} else e -> e end end def parse_as_ast(input, opts) do with {:ok, ast} <- Floki.parse_fragment(input), {:ok, result} <- parse_as_ast(ast, opts) do {:ok, result} else {:error, _} = e -> e end end # Processor defp process_ast([_ | _] = ast) do Enum.map(ast, fn {tag, attrs, children} -> {tag, attrs, children |> process_ast() |> List.flatten()} # Case for Earmark AST {tag, attrs, children, extra} -> {tag, attrs, children |> process_ast() |> List.flatten(), extra} data when is_binary(data) -> data |> String.graphemes() |> Enum.map(fn glyph -> case Emojix.find_by_unicode(glyph) do %Emojix.Emoji{} = emoji -> process_emoji(emoji) nil -> glyph end end) |> Enum.chunk_by(&is_binary(&1)) |> Enum.reduce([], fn val, acc -> cond do # Better way to do this without appending? Enum.all?(val, &is_binary(&1)) -> acc ++ [Enum.join(val)] # Flattens the chunked list. true -> acc ++ val end end) end) end defp process_ast([]), do: [] defp process_emoji(emoji) do {"img", [ {"draggable", "false"}, {"class", "twemoji"}, {"alt", emoji.description}, {"aria-label", emoji.description}, {"src", emoji.hexcode |> String.downcase() |> to_cdn()} ], []} end # Helpers defp to_cdn(point, ext \\ ".png"), do: @twemoji_cdn <> point <> ext defp transpose_ast([_ | _] = ast, format) do Enum.map(ast, fn {tag, attr, children} -> cond do format == :floki -> {tag, attr, transpose_ast(children, format)} format == :earmark -> {tag, attr, transpose_ast(children, format), %{}} end {tag, attr, children, %{} = extra} -> cond do format == :floki -> {tag, attr, transpose_ast(children, format)} format == :earmark -> {tag, attr, transpose_ast(children, format), extra} end x -> x end) end defp transpose_ast([], _format), do: [] end
25.902985
96
0.52204
797427bbccc38ab627868156d49f137d4712ec53
24,396
exs
Elixir
test/phoenix/controller/controller_test.exs
jesseshieh/phoenix
1776e9df0a71de67374ed488b3f00ccb434045b3
[ "MIT" ]
1
2020-04-14T09:49:46.000Z
2020-04-14T09:49:46.000Z
test/phoenix/controller/controller_test.exs
jesseshieh/phoenix
1776e9df0a71de67374ed488b3f00ccb434045b3
[ "MIT" ]
1
2020-05-26T19:38:18.000Z
2020-05-26T19:38:18.000Z
test/phoenix/controller/controller_test.exs
jesseshieh/phoenix
1776e9df0a71de67374ed488b3f00ccb434045b3
[ "MIT" ]
null
null
null
defmodule Phoenix.Controller.ControllerTest do use ExUnit.Case, async: true use RouterHelper import Phoenix.Controller alias Plug.Conn setup do Logger.disable(self()) :ok end defp get_resp_content_type(conn) do [header] = get_resp_header(conn, "content-type") header |> String.split(";") |> Enum.fetch!(0) end test "action_name/1" do conn = put_private(%Conn{}, :phoenix_action, :show) assert action_name(conn) == :show end test "controller_module/1" do conn = put_private(%Conn{}, :phoenix_controller, Hello) assert controller_module(conn) == Hello end test "router_module/1" do conn = put_private(%Conn{}, :phoenix_router, Hello) assert router_module(conn) == Hello end test "endpoint_module/1" do conn = put_private(%Conn{}, :phoenix_endpoint, Hello) assert endpoint_module(conn) == Hello end test "view_template/1" do conn = put_private(%Conn{}, :phoenix_template, "hello.html") assert view_template(conn) == "hello.html" assert view_template(%Conn{}) == nil end test "status_message_from_template/1" do assert status_message_from_template("404.html") == "Not Found" assert status_message_from_template("whatever.html") == "Internal Server Error" end test "put_layout_formats/2 and layout_formats/1" do conn = conn(:get, "/") assert layout_formats(conn) == ~w(html) conn = put_layout_formats conn, ~w(json xml) assert layout_formats(conn) == ~w(json xml) assert_raise Plug.Conn.AlreadySentError, fn -> put_layout_formats sent_conn(), ~w(json) end end test "put_layout/2 and layout/1" do conn = conn(:get, "/") assert layout(conn) == false conn = put_layout conn, {AppView, "app.html"} assert layout(conn) == {AppView, "app.html"} conn = put_layout conn, "print.html" assert layout(conn) == {AppView, "print.html"} conn = put_layout conn, :print assert layout(conn) == {AppView, :print} conn = put_layout conn, false assert layout(conn) == false assert_raise RuntimeError, fn -> put_layout conn, "print" end assert_raise Plug.Conn.AlreadySentError, fn -> put_layout sent_conn(), {AppView, :print} end end test "put_root_layout/2 and root_layout/1" do conn = conn(:get, "/") assert root_layout(conn) == false conn = put_root_layout(conn, {AppView, "root.html"}) assert root_layout(conn) == {AppView, "root.html"} conn = put_root_layout(conn, "bare.html") assert root_layout(conn) == {AppView, "bare.html"} conn = put_root_layout(conn, :print) assert root_layout(conn) == {AppView, :print} conn = put_root_layout(conn, false) assert root_layout(conn) == false assert_raise RuntimeError, fn -> put_root_layout(conn, "print") end assert_raise Plug.Conn.AlreadySentError, fn -> put_layout sent_conn(), {AppView, :print} end end test "put_new_layout/2" do conn = put_new_layout(conn(:get, "/"), false) assert layout(conn) == false conn = put_new_layout(conn, {AppView, "app.html"}) assert layout(conn) == false conn = put_new_layout(conn(:get, "/"), {AppView, "app.html"}) assert layout(conn) == {AppView, "app.html"} conn = put_new_layout(conn, false) assert layout(conn) == {AppView, "app.html"} assert_raise Plug.Conn.AlreadySentError, fn -> put_new_layout sent_conn(), {AppView, "app.html"} end end test "put_view/2 and put_new_view/2" do conn = put_new_view(conn(:get, "/"), Hello) assert view_module(conn) == Hello conn = put_new_view(conn, World) assert view_module(conn) == Hello conn = put_view(conn, World) assert view_module(conn) == World assert_raise Plug.Conn.AlreadySentError, fn -> put_new_view sent_conn(), Hello end assert_raise Plug.Conn.AlreadySentError, fn -> put_view sent_conn(), Hello end end describe "json/2" do test "encodes content to json" do conn = json(conn(:get, "/"), %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = json(conn, %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert conn.status == 400 end test "allows content-type injection on connection" do conn = conn(:get, "/") |> put_resp_content_type("application/vnd.api+json") conn = json(conn, %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert Conn.get_resp_header(conn, "content-type") == ["application/vnd.api+json; charset=utf-8"] end test "with allow_jsonp/2 returns json when no callback param is present" do conn = conn(:get, "/") |> fetch_query_params() |> allow_jsonp() |> json(%{foo: "bar"}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "with allow_jsonp/2 returns json when callback name is left empty" do conn = conn(:get, "/?callback=") |> fetch_query_params() |> allow_jsonp() |> json(%{foo: "bar"}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "with allow_jsonp/2 returns javascript when callback param is present" do conn = conn(:get, "/?callback=cb") |> fetch_query_params |> allow_jsonp |> json(%{foo: "bar"}) assert conn.resp_body == "/**/ typeof cb === 'function' && cb({\"foo\":\"bar\"});" assert get_resp_content_type(conn) == "application/javascript" refute conn.halted end test "with allow_jsonp/2 allows to override the callback param" do conn = conn(:get, "/?cb=cb") |> fetch_query_params |> allow_jsonp(callback: "cb") |> json(%{foo: "bar"}) assert conn.resp_body == "/**/ typeof cb === 'function' && cb({\"foo\":\"bar\"});" assert get_resp_content_type(conn) == "application/javascript" refute conn.halted end test "with allow_jsonp/2 raises ArgumentError when callback contains invalid characters" do conn = conn(:get, "/?cb=_c*b!()[0]") |> fetch_query_params() assert_raise ArgumentError, "the JSONP callback name contains invalid characters", fn -> allow_jsonp(conn, callback: "cb") end end test "with allow_jsonp/2 escapes invalid javascript characters" do conn = conn(:get, "/?cb=cb") |> fetch_query_params |> allow_jsonp(callback: "cb") |> json(%{foo: <<0x2028::utf8, 0x2029::utf8>>}) assert conn.resp_body == "/**/ typeof cb === 'function' && cb({\"foo\":\"\\u2028\\u2029\"});" assert get_resp_content_type(conn) == "application/javascript" refute conn.halted end end describe "text/2" do test "sends the content as text" do conn = text(conn(:get, "/"), "foobar") assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/plain" refute conn.halted conn = text(conn(:get, "/"), :foobar) assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/plain" refute conn.halted end test "allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = text(conn, :foobar) assert conn.resp_body == "foobar" assert conn.status == 400 end end describe "html/2" do test "sends the content as html" do conn = html(conn(:get, "/"), "foobar") assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/html" refute conn.halted end test "allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = html(conn, "foobar") assert conn.resp_body == "foobar" assert conn.status == 400 end end describe "redirect/2" do test "with :to" do conn = redirect(conn(:get, "/"), to: "/foobar") assert conn.resp_body =~ "/foobar" assert get_resp_content_type(conn) == "text/html" assert get_resp_header(conn, "location") == ["/foobar"] refute conn.halted conn = redirect(conn(:get, "/"), to: "/<foobar>") assert conn.resp_body =~ "/&lt;foobar&gt;" assert_raise ArgumentError, ~r/the :to option in redirect expects a path/, fn -> redirect(conn(:get, "/"), to: "http://example.com") end assert_raise ArgumentError, ~r/the :to option in redirect expects a path/, fn -> redirect(conn(:get, "/"), to: "//example.com") end assert_raise ArgumentError, ~r/unsafe/, fn -> redirect(conn(:get, "/"), to: "/\\example.com") end end test "with :external" do conn = redirect(conn(:get, "/"), external: "http://example.com") assert conn.resp_body =~ "http://example.com" assert get_resp_header(conn, "location") == ["http://example.com"] refute conn.halted end test "with put_status/2 uses previously set status or defaults to 302" do conn = conn(:get, "/") |> redirect(to: "/") assert conn.status == 302 conn = conn(:get, "/") |> put_status(301) |> redirect(to: "/") assert conn.status == 301 end end defp with_accept(header) do conn(:get, "/", []) |> put_req_header("accept", header) end describe "accepts/2" do test "uses params[\"_format\"] when available" do conn = accepts conn(:get, "/", _format: "json"), ~w(json) assert get_format(conn) == "json" assert conn.params["_format"] == "json" exception = assert_raise Phoenix.NotAcceptableError, ~r/unknown format "json"/, fn -> accepts conn(:get, "/", _format: "json"), ~w(html) end assert Plug.Exception.status(exception) == 406 assert exception.accepts == ["html"] end test "uses first accepts on empty or catch-all header" do conn = accepts conn(:get, "/", []), ~w(json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("*/*"), ~w(json) assert get_format(conn) == "json" assert conn.params["_format"] == nil end test "uses first matching accepts on empty subtype" do conn = accepts with_accept("text/*"), ~w(json text css) assert get_format(conn) == "text" assert conn.params["_format"] == nil end test "on non-empty */*" do # Fallbacks to HTML due to browsers behavior conn = accepts with_accept("application/json, */*"), ~w(html json) assert get_format(conn) == "html" assert conn.params["_format"] == nil conn = accepts with_accept("*/*, application/json"), ~w(html json) assert get_format(conn) == "html" assert conn.params["_format"] == nil # No HTML is treated normally conn = accepts with_accept("*/*, text/plain, application/json"), ~w(json text) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("text/plain, application/json, */*"), ~w(json text) assert get_format(conn) == "text" assert conn.params["_format"] == nil conn = accepts with_accept("text/*, application/*, */*"), ~w(json text) assert get_format(conn) == "text" assert conn.params["_format"] == nil end test "ignores invalid media types" do conn = accepts with_accept("foo/bar, bar baz, application/json"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("foo/*, */bar, text/*"), ~w(json html) assert get_format(conn) == "html" assert conn.params["_format"] == nil end test "considers q params" do conn = accepts with_accept("text/html; q=0.7, application/json"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json, text/html; q=0.7"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json; q=1.0, text/html; q=0.7"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json; q=0.8, text/html; q=0.7"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("text/html; q=0.7, application/json; q=0.8"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("text/*; q=0.7, application/json"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json; q=0.7, text/*; q=0.8"), ~w(json html) assert get_format(conn) == "html" assert conn.params["_format"] == nil exception = assert_raise Phoenix.NotAcceptableError, ~r/no supported media type in accept/, fn -> accepts with_accept("text/html; q=0.7, application/json; q=0.8"), ~w(xml) end assert Plug.Exception.status(exception) == 406 assert exception.accepts == ["xml"] end end describe "send_download/3" do @hello_txt Path.expand("../../fixtures/hello.txt", __DIR__) test "sends file for download" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}) assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["attachment; filename=\"hello.txt\""] assert get_resp_header(conn, "content-type") == ["text/plain"] assert conn.resp_body == "world" end test "sends file for download with custom :filename" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}, filename: "hello world.json") assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["attachment; filename=\"hello+world.json\""] assert get_resp_header(conn, "content-type") == ["application/json"] assert conn.resp_body == "world" end test "sends file for download with custom :filename and :encode false" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}, filename: "dev's hello world.json", encode: false) assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["attachment; filename=\"dev's hello world.json\""] assert get_resp_header(conn, "content-type") == ["application/json"] assert conn.resp_body == "world" end test "sends file for download with custom :content_type and :charset" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}, content_type: "application/json", charset: "utf8") assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["attachment; filename=\"hello.txt\""] assert get_resp_header(conn, "content-type") == ["application/json; charset=utf8"] assert conn.resp_body == "world" end test "sends file for download with custom :disposition" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}, disposition: :inline) assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["inline; filename=\"hello.txt\""] assert conn.resp_body == "world" end test "sends file for download with custom :offset" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}, offset: 2) assert conn.status == 200 assert conn.resp_body == "rld" end test "sends file for download with custom :length" do conn = send_download(conn(:get, "/"), {:file, @hello_txt}, length: 2) assert conn.status == 200 assert conn.resp_body == "wo" end test "sends binary for download with :filename" do conn = send_download(conn(:get, "/"), {:binary, "world"}, filename: "hello world.json") assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["attachment; filename=\"hello+world.json\""] assert get_resp_header(conn, "content-type") == ["application/json"] assert conn.resp_body == "world" end test "sends binary as download with custom :content_type and :charset" do conn = send_download(conn(:get, "/"), {:binary, "world"}, filename: "hello.txt", content_type: "application/json", charset: "utf8") assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["attachment; filename=\"hello.txt\""] assert get_resp_header(conn, "content-type") == ["application/json; charset=utf8"] assert conn.resp_body == "world" end test "sends binary for download with custom :disposition" do conn = send_download(conn(:get, "/"), {:binary, "world"}, filename: "hello.txt", disposition: :inline) assert conn.status == 200 assert get_resp_header(conn, "content-disposition") == ["inline; filename=\"hello.txt\""] assert conn.resp_body == "world" end test "raises ArgumentError for :disposition other than :attachment or :inline" do assert_raise(ArgumentError, ~r"expected :disposition to be :attachment or :inline, got: :foo", fn -> send_download(conn(:get, "/"), {:file, @hello_txt}, disposition: :foo) end) assert_raise(ArgumentError, ~r"expected :disposition to be :attachment or :inline, got: :foo", fn -> send_download(conn(:get, "/"), {:binary, "world"}, filename: "hello.txt", disposition: :foo) end) end end describe "scrub_params/2" do test "raises Phoenix.MissingParamError for missing key" do assert_raise(Phoenix.MissingParamError, ~r"expected key \"foo\" to be present in params", fn -> conn(:get, "/") |> fetch_query_params |> scrub_params("foo") end) assert_raise(Phoenix.MissingParamError, ~r"expected key \"foo\" to be present in params", fn -> conn(:get, "/?foo=") |> fetch_query_params |> scrub_params("foo") end) end test "keeps populated keys intact" do conn = conn(:get, "/?foo=bar") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == "bar" end test "nils out all empty values for the passed in key if it is a list" do conn = conn(:get, "/?foo[]=&foo[]=++&foo[]=bar") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == [nil, nil, "bar"] end test "nils out all empty keys in value for the passed in key if it is a map" do conn = conn(:get, "/?foo[bar]=++&foo[baz]=&foo[bat]=ok") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == %{"bar" => nil, "baz" => nil, "bat" => "ok"} end test "nils out all empty keys in value for the passed in key if it is a nested map" do conn = conn(:get, "/?foo[bar][baz]=") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == %{"bar" => %{"baz" => nil}} end test "ignores the keys that don't match the passed in key" do conn = conn(:get, "/?foo=bar&baz=") |> fetch_query_params |> scrub_params("foo") assert conn.params["baz"] == "" end test "keeps structs intact" do conn = conn(:get, "/", %{"foo" => %{"bar" => %Plug.Upload{}}}) |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"]["bar"] == %Plug.Upload{} end end test "protect_from_forgery/2 sets token" do conn(:get, "/") |> init_test_session(%{}) |> protect_from_forgery([]) assert is_binary get_csrf_token() assert is_binary delete_csrf_token() end test "put_secure_browser_headers/2" do conn = conn(:get, "/") |> put_secure_browser_headers() assert get_resp_header(conn, "x-frame-options") == ["SAMEORIGIN"] assert get_resp_header(conn, "x-xss-protection") == ["1; mode=block"] assert get_resp_header(conn, "x-content-type-options") == ["nosniff"] assert get_resp_header(conn, "x-download-options") == ["noopen"] assert get_resp_header(conn, "x-permitted-cross-domain-policies") == ["none"] assert get_resp_header(conn, "cross-origin-window-policy") == ["deny"] custom_headers = %{"x-frame-options" => "custom", "foo" => "bar"} conn = conn(:get, "/") |> put_secure_browser_headers(custom_headers) assert get_resp_header(conn, "x-frame-options") == ["custom"] assert get_resp_header(conn, "x-xss-protection") == ["1; mode=block"] assert get_resp_header(conn, "x-download-options") == ["noopen"] assert get_resp_header(conn, "x-permitted-cross-domain-policies") == ["none"] assert get_resp_header(conn, "cross-origin-window-policy") == ["deny"] assert get_resp_header(conn, "foo") == ["bar"] end test "__view__ returns the view module based on controller module" do assert Phoenix.Controller.__view__(MyApp.UserController) == MyApp.UserView assert Phoenix.Controller.__view__(MyApp.Admin.UserController) == MyApp.Admin.UserView end test "__layout__ returns the layout module based on controller module" do assert Phoenix.Controller.__layout__(UserController, []) == LayoutView assert Phoenix.Controller.__layout__(MyApp.UserController, []) == MyApp.LayoutView assert Phoenix.Controller.__layout__(MyApp.Admin.UserController, []) == MyApp.LayoutView assert Phoenix.Controller.__layout__(MyApp.Admin.UserController, namespace: MyApp.Admin) == MyApp.Admin.LayoutView end defp sent_conn do conn(:get, "/") |> send_resp(:ok, "") end describe "path and url generation" do def url(), do: "https://www.example.com" def build_conn_for_path(path) do conn(:get, path) |> fetch_query_params() |> put_private(:phoenix_endpoint, __MODULE__) |> put_private(:phoenix_router, __MODULE__) end test "current_path/1 uses the conn's query params" do conn = build_conn_for_path("/") assert current_path(conn) == "/" conn = build_conn_for_path("/foo?one=1&two=2") assert current_path(conn) == "/foo?one=1&two=2" end test "current_path/2 allows custom query params" do conn = build_conn_for_path("/") assert current_path(conn, %{}) == "/" conn = build_conn_for_path("/foo?one=1&two=2") assert current_path(conn, %{}) == "/foo" conn = build_conn_for_path("/foo?one=1&two=2") assert current_path(conn, %{three: 3}) == "/foo?three=3" end test "current_path/2 allows custom nested query params" do conn = build_conn_for_path("/") assert current_path(conn, %{foo: %{bar: [:baz], baz: :qux}}) == "/?foo[bar][]=baz&foo[baz]=qux" end test "current_url/1 with root path includes trailing slash" do conn = build_conn_for_path("/") assert current_url(conn) == "https://www.example.com/" end test "current_url/1 users conn's endpoint and query params" do conn = build_conn_for_path("/?foo=bar") assert current_url(conn) == "https://www.example.com/?foo=bar" conn = build_conn_for_path("/foo?one=1&two=2") assert current_url(conn) == "https://www.example.com/foo?one=1&two=2" end test "current_url/2 allows custom query params" do conn = build_conn_for_path("/") assert current_url(conn, %{}) == "https://www.example.com/" conn = build_conn_for_path("/foo?one=1&two=2") assert current_url(conn, %{}) == "https://www.example.com/foo" conn = build_conn_for_path("/foo?one=1&two=2") assert current_url(conn, %{three: 3}) == "https://www.example.com/foo?three=3" end end end
35.510917
115
0.619241
79743f8cec7ea342f51c13cdf2a1f692bd9ed51e
1,518
ex
Elixir
server/lib/adapters/changes.ex
sthagen/phoenix-postgres-realtime
0f0cad033b24c090b5014f38f4eca9333b965694
[ "Apache-2.0" ]
1
2020-06-03T10:49:40.000Z
2020-06-03T10:49:40.000Z
server/lib/adapters/changes.ex
bojanskr/realtime
c0deb95a41e1293192582c16b966ff0beead1b89
[ "Apache-2.0" ]
null
null
null
server/lib/adapters/changes.ex
bojanskr/realtime
c0deb95a41e1293192582c16b966ff0beead1b89
[ "Apache-2.0" ]
null
null
null
# This file draws heavily from https://github.com/cainophile/cainophile # License: https://github.com/cainophile/cainophile/blob/master/LICENSE require Protocol defmodule Realtime.Adapters.Changes do defmodule(Transaction, do: defstruct([:changes, :commit_timestamp])) defmodule NewRecord do @derive {Jason.Encoder, except: [:is_rls_enabled, :subscription_ids]} defstruct [ :columns, :commit_timestamp, :errors, :schema, :table, :record, :subscription_ids, :type, is_rls_enabled: true ] end defmodule UpdatedRecord do @derive {Jason.Encoder, except: [:is_rls_enabled, :subscription_ids]} defstruct [ :columns, :commit_timestamp, :errors, :schema, :table, :old_record, :record, :subscription_ids, :type, is_rls_enabled: true ] end defmodule DeletedRecord do @derive {Jason.Encoder, except: [:is_rls_enabled, :subscription_ids]} defstruct [ :columns, :commit_timestamp, :errors, :schema, :table, :old_record, :subscription_ids, :type, is_rls_enabled: true ] end defmodule(TruncatedRelation, do: defstruct([:type, :schema, :table, :commit_timestamp])) end Protocol.derive(Jason.Encoder, Realtime.Adapters.Changes.Transaction) Protocol.derive(Jason.Encoder, Realtime.Adapters.Changes.TruncatedRelation) Protocol.derive(Jason.Encoder, Realtime.Adapters.Postgres.Decoder.Messages.Relation.Column)
24.885246
91
0.676548
79744eb022ec5e069f46198e1475cc48a11d8a88
1,888
ex
Elixir
lib/phoenix_starter/release_tasks.ex
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
3
2021-03-19T10:39:02.000Z
2021-07-25T19:54:09.000Z
lib/phoenix_starter/release_tasks.ex
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
204
2020-11-27T06:00:31.000Z
2022-03-25T08:08:16.000Z
lib/phoenix_starter/release_tasks.ex
newaperio/phoenix_starter
02f2f5550a94b940bb4e9c61042b032f54af8b72
[ "MIT" ]
null
null
null
defmodule PhoenixStarter.ReleaseTasks do @moduledoc """ Server tasks to be run inside the production release container. """ @app :phoenix_starter require Logger @spec migrate :: [any] def migrate do load_app() for repo <- repos() do {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true)) end end @spec migrations :: [any] def migrations do load_app() for repo <- repos() do {:ok, migrations, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.migrations(&1)) migrations |> format_migrations(repo) |> Logger.info() end end @spec rollback :: [any] def rollback do load_app() for repo <- repos() do {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, step: 1)) end end @spec seeds :: [any] def seeds do load_app() for repo <- repos() do {:ok, _, _} = Ecto.Migrator.with_repo(repo, fn repo -> seeds_path = Ecto.Migrator.migrations_path(repo, "/seeds.exs") if File.exists?(seeds_path) do Logger.info("Running seeds for #{repo}: #{seeds_path}") Code.eval_file(seeds_path) end end) end end defp repos do Application.fetch_env!(@app, :ecto_repos) end defp load_app do Application.load(@app) Application.ensure_all_started(:ssl) end defp format_migrations(migrations, repo) do # Borrowed from mix ecto.migrations """ Repo: #{inspect(repo)} Status Migration ID Migration Name -------------------------------------------------- """ <> Enum.map_join(migrations, "\n", fn {status, number, description} -> " #{format(status, 10)}#{format(number, 16)}#{description}" end) end defp format(content, pad) do content |> to_string |> String.pad_trailing(pad) end end
22.746988
89
0.592691
7974969c89110c7202688867607d244a8673b2ab
132,149
ex
Elixir
lib/nostrum/api.ex
brettkolodny/nostrum
3e26af6c106558bfe3fd48dcf3064fbc361605b5
[ "MIT" ]
null
null
null
lib/nostrum/api.ex
brettkolodny/nostrum
3e26af6c106558bfe3fd48dcf3064fbc361605b5
[ "MIT" ]
null
null
null
lib/nostrum/api.ex
brettkolodny/nostrum
3e26af6c106558bfe3fd48dcf3064fbc361605b5
[ "MIT" ]
null
null
null
defmodule Nostrum.Api do @moduledoc ~S""" Interface for Discord's rest API. By default all methods in this module are ran synchronously. If you wish to have async rest operations I recommend you execute these functions inside of a task. **Examples** ```Elixir # Async Task t = Task.async fn -> Nostrum.Api.get_channel_messages(12345678912345, :infinity, {}) end messages = Task.await t # A lot of times we don't care about the return value of the function Task.start fn -> messages = ["in", "the", "end", "it", "doesn't", "even", "matter"] Enum.each messages, &Nostrum.Api.create_message!(12345678912345, &1) end ``` #### A note about Strings and Ints Currently, responses from the REST api will have `id` fields as `string`. Everything received from the WS connection will have `id` fields as `int`. If you're processing a response from the API and trying to access something in the cache based off of an `id` in the response, you will need to conver it to an `int` using `String.to_integer/1`. I'm open to suggestions for how this should be handled going forward. **Example** ```Elixir messages = Nostrum.Api.get_pinned_messages!(12345678912345) authors = Enum.map messages, fn msg -> author_id = String.to_integer(msg.author.id) Nostrum.Cache.User.get!(id: author_id) end ``` """ use Bitwise import Nostrum.Snowflake, only: [is_snowflake: 1] alias Nostrum.Cache.Me alias Nostrum.{Constants, Snowflake, Util} alias Nostrum.Struct.{ ApplicationCommand, Channel, Embed, Emoji, Guild, Interaction, Invite, Message, User, Webhook } alias Nostrum.Struct.Guild.{AuditLog, AuditLogEntry, Member, Role, ScheduledEvent} alias Nostrum.Shard.{Session, Supervisor} @typedoc """ Represents a failed response from the API. This occurs when `:gun` fails, or when the API doesn't respond with `200` or `204`. """ @type error :: {:error, Nostrum.Error.ApiError.t()} @typedoc """ Represents a limit used to retrieve messages. Integer number of messages, or :infinity to retrieve all messages. """ @type limit :: integer | :infinity @typedoc """ Represents a tuple used to locate messages. The first element of the tuple is an atom. The second element will be a message_id as an integer. The tuple can also be empty to search from the most recent message in the channel """ @type locator :: {:before, integer} | {:after, integer} | {:around, integer} | {} @typedoc """ Represents different statuses the bot can have. - `:dnd` - Red circle. - `:idle` - Yellow circle. - `:online` - Green circle. - `:invisible` - The bot will appear offline. """ @type status :: :dnd | :idle | :online | :invisible @typedoc """ Represents an emoji for interacting with reaction endpoints. """ @type emoji :: Emoji.t() | Emoji.api_name() @typedoc """ Represents optional parameters for Api functions. Each function has documentation regarding what parameters it supports or needs. """ @type options :: keyword | map @doc """ Updates the status of the bot for a certain shard. ## Parameters - `pid` - Pid of the shard. - `status` - Status of the bot. - `game` - The 'playing' text of the bot. Empty will clear. - `type` - The type of status to show. 0 (Playing) | 1 (Streaming) | 2 (Listening) | 3 (Watching) - `stream` - URL of twitch.tv stream """ @spec update_shard_status(pid, status, String.t(), integer, String.t() | nil) :: :ok def update_shard_status(pid, status, game, type \\ 0, stream \\ nil) do Session.update_status(pid, to_string(status), game, stream, type) :ok end @doc """ Updates the status of the bot for all shards. See `update_shard_status/5` for usage. """ @spec update_status(status, String.t(), integer, String.t() | nil) :: :ok def update_status(status, game, type \\ 0, stream \\ nil) do Supervisor.update_status(to_string(status), game, stream, type) :ok end @doc """ Joins, moves, or disconnects the bot from a voice channel. The correct shard to send the update to will be inferred from the `guild_id`. If a corresponding `guild_id` is not found a cache error will be raised. To disconnect from a channel, `channel_id` should be set to `nil`. """ @spec update_voice_state(Guild.id(), Channel.id() | nil, boolean, boolean) :: no_return | :ok def update_voice_state(guild_id, channel_id, self_mute \\ false, self_deaf \\ false) do Supervisor.update_voice_state(guild_id, channel_id, self_mute, self_deaf) end @doc ~S""" Posts a message to a guild text or DM channel. This endpoint requires the `VIEW_CHANNEL` and `SEND_MESSAGES` permissions. It may situationally need the `SEND_MESSAGES_TTS` permission. It fires the `t:Nostrum.Consumer.message_create/0` event. If `options` is a string, `options` will be used as the message's content. If successful, returns `{:ok, message}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:content` (string) - the message contents (up to 2000 characters) * `:nonce` (`t:Nostrum.Snowflake.t/0`) - a nonce that can be used for optimistic message sending * `:tts` (boolean) - true if this is a TTS message * `:file` (`t:Path.t/0` | map) - the path of the file being sent, or a map with the following keys if sending a binary from memory * `:name` (string) - the name of the file * `:body` (string) - binary you wish to send * `:files` - a list of files where each element is the same format as the `:file` option. If both `:file` and `:files` are specified, `:file` will be prepended to the `:files` list. * `:embed` (`t:Nostrum.Struct.Embed.t/0`) - embedded rich content * `:allowed_mentions` - See "Allowed mentions" below * `:message_reference` (`map`) - See "Message references" below At least one of the following is required: `:content`, `:file`, `:embed`. ## Allowed mentions With this option you can control when content from a message should trigger a ping. Consider using this option when you are going to display user_generated content. ### Allowed values * `:all` (default) - Ping everything as usual * `:none` - Nobody will be pinged * `:everyone` - Allows to ping @here and @everone * `:users` - Allows to ping users * `:roles` - Allows to ping roles * `{:users, list}` - Allows to ping list of users. Can contain up to 100 ids of users. * `{:roles, list}` - Allows to ping list of roles. Can contain up to 100 ids of roles. * list - a list containing the values above. ### Message reference You can create a reply to another message on guilds using this option, given that you have the ``VIEW_MESSAGE_HISTORY`` permission. To do so, include the ``message_reference`` field in your call. The complete structure documentation can be found [on the Discord Developer Portal](https://discord.com/developers/docs/resources/channel#message-object-message-reference-structure), but simply passing ``message_id`` will suffice: ```elixir def my_command(msg) do # Reply to the author - ``msg`` is a ``Nostrum.Struct.Message`` Nostrum.Api.create_message( msg.channel_id, content: "Hello", message_reference: %{message_id: msg.id} ) end ``` Passing a list will merge the settings provided ## Examples ```Elixir Nostrum.Api.create_message(43189401384091, content: "hello world!") Nostrum.Api.create_message(43189401384091, "hello world!") import Nostrum.Struct.Embed embed = %Nostrum.Struct.Embed{} |> put_title("embed") |> put_description("new desc") Nostrum.Api.create_message(43189401384091, embed: embed) Nostrum.Api.create_message(43189401384091, file: "/path/to/file.txt") Nostrum.Api.create_message(43189401384091, content: "hello world!", embed: embed, file: "/path/to/file.txt") Nostrum.Api.create_message(43189401384091, content: "Hello @everyone", allowed_mentions: :none) ``` """ @spec create_message(Channel.id() | Message.t(), options | String.t()) :: error | {:ok, Message.t()} def create_message(channel_id, options) def create_message(%Message{} = message, options), do: create_message(message.channel_id, options) def create_message(channel_id, options) when is_list(options), do: create_message(channel_id, Map.new(options)) def create_message(channel_id, %{} = options) when is_snowflake(channel_id) do options = prepare_allowed_mentions(options) case options do %{file: _} -> create_message_with_multipart(channel_id, options) %{files: _} -> create_message_with_multipart(channel_id, options) _ -> create_message_with_json(channel_id, options) end end def create_message(channel_id, content) when is_snowflake(channel_id) and is_binary(content), do: create_message_with_json(channel_id, %{content: content}) # If both `:file` and `:files`, move `:file` to existing `:files` list defp create_message_with_multipart(channel_id, %{file: file, files: files} = options) do options = %{options | files: [file | files]} |> Map.delete(:file) create_message_with_multipart(channel_id, options) end # If only one file, move it to new list with `:files` key defp create_message_with_multipart(channel_id, %{file: file} = options) do options = options |> Map.put(:files, [file]) |> Map.delete(:file) create_message_with_multipart(channel_id, options) end defp create_message_with_multipart(channel_id, %{files: files} = options) do payload_json = options |> Map.delete(:files) |> Jason.encode_to_iodata!() boundary = generate_boundary() request = %{ method: :post, route: Constants.channel_messages(channel_id), body: create_multipart(files, payload_json, boundary), params: [], headers: [ {"content-type", "multipart/form-data; boundary=#{boundary}"} ] } GenServer.call(Ratelimiter, {:queue, request, nil}, :infinity) |> handle_request_with_decode({:struct, Message}) end defp create_message_with_json(channel_id, options) do request(:post, Constants.channel_messages(channel_id), options) |> handle_request_with_decode({:struct, Message}) end @doc ~S""" Same as `create_message/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_message!(Channel.id() | Message.t(), options | String.t()) :: no_return | Message.t() def create_message!(channel_id, options) do create_message(channel_id, options) |> bangify end @doc ~S""" Edits a previously sent message in a channel. This endpoint requires the `VIEW_CHANNEL` permission. It fires the `t:Nostrum.Consumer.message_update/0` event. If `options` is a string, `options` will be used as the message's content. If successful, returns `{:ok, message}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:content` (string) - the message contents (up to 2000 characters) * `:embed` (`t:Nostrum.Struct.Embed.t/0`) - embedded rich content ## Examples ```Elixir Nostrum.Api.edit_message(43189401384091, 1894013840914098, content: "hello world!") Nostrum.Api.edit_message(43189401384091, 1894013840914098, "hello world!") import Nostrum.Struct.Embed embed = %Nostrum.Struct.Embed{} |> put_title("embed") |> put_description("new desc") Nostrum.Api.edit_message(43189401384091, 1894013840914098, embed: embed) Nostrum.Api.edit_message(43189401384091, 1894013840914098, content: "hello world!", embed: embed) ``` """ @spec edit_message(Channel.id(), Message.id(), options | String.t()) :: error | {:ok, Message.t()} def edit_message(channel_id, message_id, options) def edit_message(channel_id, message_id, options) when is_list(options), do: edit_message(channel_id, message_id, Map.new(options)) def edit_message(channel_id, message_id, %{} = options) when is_snowflake(channel_id) and is_snowflake(message_id) do request(:patch, Constants.channel_message(channel_id, message_id), options) |> handle_request_with_decode({:struct, Message}) end def edit_message(channel_id, message_id, content) when is_snowflake(channel_id) and is_snowflake(message_id) and is_binary(content) do request(:patch, Constants.channel_message(channel_id, message_id), %{content: content}) |> handle_request_with_decode({:struct, Message}) end @doc ~S""" Same as `edit_message/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec edit_message!(Channel.id(), Message.id(), options) :: no_return | Message.t() def edit_message!(channel_id, message_id, options) do edit_message(channel_id, message_id, options) |> bangify end @doc ~S""" Same as `edit_message/3`, but takes a `Nostrum.Struct.Message` instead of a `channel_id` and `message_id`. """ @spec edit_message(Message.t(), options) :: error | {:ok, Message.t()} def edit_message(%Message{id: id, channel_id: c_id}, options) do edit_message(c_id, id, options) end @doc ~S""" Same as `edit_message/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec edit_message!(Message.t(), options) :: no_return | Message.t() def edit_message!(message, options) do edit_message(message, options) |> bangify end @doc ~S""" Same as `delete_message/2`, but takes a `Nostrum.Struct.Message` instead of a `channel_id` and `message_id`. """ @spec delete_message(Message.t()) :: error | {:ok} def delete_message(%Message{id: id, channel_id: c_id}) do delete_message(c_id, id) end @doc ~S""" Deletes a message. This endpoint requires the 'VIEW_CHANNEL' and 'MANAGE_MESSAGES' permission. It fires the `MESSAGE_DELETE` event. If successful, returns `{:ok}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.delete_message(43189401384091, 43189401384091) ``` """ @spec delete_message(Channel.id(), Message.id()) :: error | {:ok} def delete_message(channel_id, message_id) when is_snowflake(channel_id) and is_snowflake(message_id) do request(:delete, Constants.channel_message(channel_id, message_id)) end @doc ~S""" Same as `delete_message/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_message!(Message.t()) :: error | {:ok} def delete_message!(%Message{id: id, channel_id: c_id}) do delete_message(c_id, id) |> bangify end @doc ~S""" Same as `delete_message/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_message!(Channel.id(), Message.id()) :: no_return | {:ok} def delete_message!(channel_id, message_id) do delete_message(channel_id, message_id) |> bangify end @doc ~S""" Creates a reaction for a message. This endpoint requires the `VIEW_CHANNEL` and `READ_MESSAGE_HISTORY` permissions. Additionally, if nobody else has reacted to the message with the `emoji`, this endpoint requires the `ADD_REACTIONS` permission. It fires a `t:Nostrum.Consumer.message_reaction_add/0` event. If successful, returns `{:ok}`. Otherwise, returns `t:Nostrum.Api.error/0`. ## Examples ```Elixir # Using a Nostrum.Struct.Emoji. emoji = %Nostrum.Struct.Emoji{id: 43819043108, name: "foxbot"} Nostrum.Api.create_reaction(123123123123, 321321321321, emoji) # Using a base 16 emoji string. Nostrum.Api.create_reaction(123123123123, 321321321321, "\xF0\x9F\x98\x81") ``` For other emoji string examples, see `t:Nostrum.Struct.Emoji.api_name/0`. """ @spec create_reaction(Channel.id(), Message.id(), emoji) :: error | {:ok} def create_reaction(channel_id, message_id, emoji) def create_reaction(channel_id, message_id, %Emoji{} = emoji), do: create_reaction(channel_id, message_id, Emoji.api_name(emoji)) def create_reaction(channel_id, message_id, emoji_api_name) do request(:put, Constants.channel_reaction_me(channel_id, message_id, emoji_api_name)) end @doc ~S""" Same as `create_reaction/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_reaction!(Channel.id(), Message.id(), emoji) :: no_return | {:ok} def create_reaction!(channel_id, message_id, emoji) do create_reaction(channel_id, message_id, emoji) |> bangify end @doc ~S""" Deletes a reaction the current user has made for the message. This endpoint requires the `VIEW_CHANNEL` and `READ_MESSAGE_HISTORY` permissions. It fires a `t:Nostrum.Consumer.message_reaction_remove/0` event. If successful, returns `{:ok}`. Otherwise, returns `t:Nostrum.Api.error/0`. See `create_reaction/3` for similar examples. """ @spec delete_own_reaction(Channel.id(), Message.id(), emoji) :: error | {:ok} def delete_own_reaction(channel_id, message_id, emoji) def delete_own_reaction(channel_id, message_id, %Emoji{} = emoji), do: delete_own_reaction(channel_id, message_id, Emoji.api_name(emoji)) def delete_own_reaction(channel_id, message_id, emoji_api_name) do request(:delete, Constants.channel_reaction_me(channel_id, message_id, emoji_api_name)) end @doc ~S""" Same as `delete_own_reaction/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_own_reaction!(Channel.id(), Message.id(), emoji) :: no_return | {:ok} def delete_own_reaction!(channel_id, message_id, emoji) do delete_own_reaction(channel_id, message_id, emoji) |> bangify end @doc ~S""" Deletes another user's reaction from a message. This endpoint requires the `VIEW_CHANNEL`, `READ_MESSAGE_HISTORY`, and `MANAGE_MESSAGES` permissions. It fires a `t:Nostrum.Consumer.message_reaction_remove/0` event. If successful, returns `{:ok}`. Otherwise, returns `t:Nostrum.Api.error/0`. See `create_reaction/3` for similar examples. """ @spec delete_user_reaction(Channel.id(), Message.id(), emoji, User.id()) :: error | {:ok} def delete_user_reaction(channel_id, message_id, emoji, user_id) def delete_user_reaction(channel_id, message_id, %Emoji{} = emoji, user_id), do: delete_user_reaction(channel_id, message_id, Emoji.api_name(emoji), user_id) def delete_user_reaction(channel_id, message_id, emoji_api_name, user_id) do request(:delete, Constants.channel_reaction(channel_id, message_id, emoji_api_name, user_id)) end @doc ~S""" Same as `delete_user_reaction/4`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_user_reaction!(Channel.id(), Message.id(), emoji, User.id()) :: no_return | {:ok} def delete_user_reaction!(channel_id, message_id, emoji, user_id) do delete_user_reaction(channel_id, message_id, emoji, user_id) |> bangify end @doc ~S""" Deletes all reactions of a given emoji from a message. This endpoint requires the `MANAGE_MESSAGES` permissions. It fires a `t:Nostrum.Consumer.message_reaction_remove_emoji/0` event. If successful, returns `{:ok}`. Otherwise, returns `t:Nostrum.Api.error/0`. See `create_reaction/3` for similar examples. """ @spec delete_reaction(Channel.id(), Message.id(), emoji) :: error | {:ok} def delete_reaction(channel_id, message_id, emoji) def delete_reaction(channel_id, message_id, %Emoji{} = emoji), do: delete_reaction(channel_id, message_id, Emoji.api_name(emoji)) def delete_reaction(channel_id, message_id, emoji_api_name) do request( :delete, Constants.channel_reactions_delete_emoji(channel_id, message_id, emoji_api_name) ) end @doc ~S""" Same as `delete_reaction/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_reaction!(Channel.id(), Message.id(), emoji) :: no_return | {:ok} def delete_reaction!(channel_id, message_id, emoji) do delete_reaction(channel_id, message_id, emoji) |> bangify end @doc ~S""" Gets all users who reacted with an emoji. This endpoint requires the `VIEW_CHANNEL` and `READ_MESSAGE_HISTORY` permissions. If successful, returns `{:ok, users}`. Otherwise, returns `t:Nostrum.Api.error/0`. See `create_reaction/3` for similar examples. """ @spec get_reactions(Channel.id(), Message.id(), emoji) :: error | {:ok, [User.t()]} def get_reactions(channel_id, message_id, emoji) def get_reactions(channel_id, message_id, %Emoji{} = emoji), do: get_reactions(channel_id, message_id, Emoji.api_name(emoji)) def get_reactions(channel_id, message_id, emoji_api_name) do request(:get, Constants.channel_reactions_get(channel_id, message_id, emoji_api_name)) |> handle_request_with_decode({:list, {:struct, User}}) end @doc ~S""" Same as `get_reactions/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_reactions!(Channel.id(), Message.id(), emoji) :: no_return | [User.t()] def get_reactions!(channel_id, message_id, emoji) do get_reactions(channel_id, message_id, emoji) |> bangify end @doc ~S""" Deletes all reactions from a message. This endpoint requires the `VIEW_CHANNEL`, `READ_MESSAGE_HISTORY`, and `MANAGE_MESSAGES` permissions. It fires a `t:Nostrum.Consumer.message_reaction_remove_all/0` event. If successful, returns `{:ok}`. Otherwise, return `t:Nostrum.Api.error/0`. """ @spec delete_all_reactions(Channel.id(), Message.id()) :: error | {:ok} def delete_all_reactions(channel_id, message_id) do request(:delete, Constants.channel_reactions_delete(channel_id, message_id)) end @doc ~S""" Same as `delete_all_reactions/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_all_reactions!(Channel.id(), Message.id()) :: no_return | {:ok} def delete_all_reactions!(channel_id, message_id) do delete_all_reactions(channel_id, message_id) |> bangify end @doc ~S""" Gets a channel. If successful, returns `{:ok, channel}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_channel(381889573426429952) {:ok, %Nostrum.Struct.Channel{id: 381889573426429952}} ``` """ @spec get_channel(Channel.id()) :: error | {:ok, Channel.t()} def get_channel(channel_id) when is_snowflake(channel_id) do request(:get, Constants.channel(channel_id)) |> handle_request_with_decode({:struct, Channel}) end @doc ~S""" Same as `get_channel/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_channel!(Channel.id()) :: no_return | Channel.t() def get_channel!(channel_id) do get_channel(channel_id) |> bangify end @doc ~S""" Modifies a channel's settings. An optional `reason` can be given for the guild audit log. If a `t:Nostrum.Struct.Channel.guild_channel/0` is being modified, this endpoint requires the `MANAGE_CHANNEL` permission. It fires a `t:Nostrum.Consumer.channel_update/0` event. If a `t:Nostrum.Struct.Channel.guild_category_channel/0` is being modified, then this endpoint fires multiple `t:Nostrum.Consumer.channel_update/0` events. If successful, returns `{:ok, channel}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - 2-100 character channel name * `:position` (integer) - the position of the channel in the left-hand listing * `:topic` (string) (`t:Nostrum.Struct.Channel.text_channel/0` only) - 0-1024 character channel topic * `:nsfw` (boolean) (`t:Nostrum.Struct.Channel.text_channel/0` only) - if the channel is nsfw * `:bitrate` (integer) (`t:Nostrum.Struct.Channel.voice_channel/0` only) - the bitrate (in bits) of the voice channel; 8000 to 96000 (128000 for VIP servers) * `:user_limit` (integer) (`t:Nostrum.Struct.Channel.voice_channel/0` only) - the user limit of the voice channel; 0 refers to no limit, 1 to 99 refers to a user limit * `:permission_overwrites` (list of `t:Nostrum.Struct.Overwrite.t/0` or equivalent map) - channel or category-specific permissions * `:parent_id` (`t:Nostrum.Struct.Channel.id/0`) (`t:Nostrum.Struct.Channel.guild_channel/0` only) - id of the new parent category for a channel ## Examples ```Elixir Nostrum.Api.modify_channel(41771983423143933, name: "elixir-nostrum", topic: "nostrum discussion") {:ok, %Nostrum.Struct.Channel{id: 41771983423143933, name: "elixir-nostrum", topic: "nostrum discussion"}} Nostrum.Api.modify_channel(41771983423143933) {:ok, %Nostrum.Struct.Channel{id: 41771983423143933}} ``` """ @spec modify_channel(Channel.id(), options, AuditLogEntry.reason()) :: error | {:ok, Channel.t()} def modify_channel(channel_id, options, reason \\ nil) def modify_channel(channel_id, options, reason) when is_list(options), do: modify_channel(channel_id, Map.new(options), reason) def modify_channel(channel_id, %{} = options, reason) when is_snowflake(channel_id) do %{ method: :patch, route: Constants.channel(channel_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request |> handle_request_with_decode({:struct, Channel}) end @doc ~S""" Same as `modify_channel/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_channel!(Channel.id(), options, AuditLogEntry.reason()) :: no_return | Channel.t() def modify_channel!(channel_id, options, reason \\ nil) do modify_channel(channel_id, options, reason) |> bangify end @doc ~S""" Deletes a channel. An optional `reason` can be provided for the guild audit log. If deleting a `t:Nostrum.Struct.Channel.guild_channel/0`, this endpoint requires the `MANAGE_CHANNELS` permission. It fires a `t:Nostrum.Consumer.channel_delete/0`. If a `t:Nostrum.Struct.Channel.guild_category_channel/0` is deleted, then a `t:Nostrum.Consumer.channel_update/0` event will fire for each channel under the category. If successful, returns `{:ok, channel}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.delete_channel(421533712753360896) {:ok, %Nostrum.Struct.Channel{id: 421533712753360896}} ``` """ @spec delete_channel(Channel.id(), AuditLogEntry.reason()) :: error | {:ok, Channel.t()} def delete_channel(channel_id, reason \\ nil) when is_snowflake(channel_id) do %{ method: :delete, route: Constants.channel(channel_id), body: "", params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Channel}) end @doc ~S""" Same as `delete_channel/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_channel!(Channel.id(), AuditLogEntry.reason()) :: no_return | Channel.t() def delete_channel!(channel_id, reason \\ nil) do delete_channel(channel_id, reason) |> bangify end @doc ~S""" Retrieves a channel's messages around a `locator` up to a `limit`. This endpoint requires the 'VIEW_CHANNEL' permission. If the current user is missing the 'READ_MESSAGE_HISTORY' permission, then this function will return no messages. If successful, returns `{:ok, messages}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_channel_messages(43189401384091, 5, {:before, 130230401384}) ``` """ @spec get_channel_messages(Channel.id(), limit, locator) :: error | {:ok, [Message.t()]} def get_channel_messages(channel_id, limit, locator \\ {}) when is_snowflake(channel_id) do get_messages_sync(channel_id, limit, [], locator) end defp get_messages_sync(channel_id, limit, messages, locator) when limit <= 100 do case get_channel_messages_call(channel_id, limit, locator) do {:ok, new_messages} -> {:ok, messages ++ new_messages} other -> other end end defp get_messages_sync(channel_id, limit, messages, locator) do case get_channel_messages_call(channel_id, 100, locator) do {:error, message} -> {:error, message} {:ok, []} -> {:ok, messages} {:ok, new_messages} -> new_limit = get_new_limit(limit, length(new_messages)) new_locator = get_new_locator(locator, List.last(new_messages)) get_messages_sync(channel_id, new_limit, messages ++ new_messages, new_locator) end end defp get_new_locator({}, last_message), do: {:before, last_message.id} defp get_new_locator(locator, last_message), do: put_elem(locator, 1, last_message.id) defp get_new_limit(:infinity, _new_message_count), do: :infinity defp get_new_limit(limit, message_count), do: limit - message_count # We're decoding the response at each call to catch any errors @doc false def get_channel_messages_call(channel_id, limit, locator) do qs_params = case locator do {} -> [{:limit, limit}] non_empty_locator -> [{:limit, limit}, non_empty_locator] end request(:get, Constants.channel_messages(channel_id), "", qs_params) |> handle_request_with_decode({:list, {:struct, Message}}) end @doc ~S""" Same as `get_channel_messages/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_channel_messages!(Channel.id(), limit, locator) :: no_return | [Message.t()] def get_channel_messages!(channel_id, limit, locator \\ {}) do get_channel_messages(channel_id, limit, locator) |> bangify end @doc ~S""" Retrieves a message from a channel. This endpoint requires the 'VIEW_CHANNEL' and 'READ_MESSAGE_HISTORY' permissions. If successful, returns `{:ok, message}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_channel_message(43189401384091, 198238475613443) ``` """ @spec get_channel_message(Channel.id(), Message.id()) :: error | {:ok, Message.t()} def get_channel_message(channel_id, message_id) when is_snowflake(channel_id) and is_snowflake(message_id) do request(:get, Constants.channel_message(channel_id, message_id)) |> handle_request_with_decode({:struct, Message}) end @doc ~S""" Same as `get_channel_message/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_channel_message!(Channel.id(), Message.id()) :: no_return | Message.t() def get_channel_message!(channel_id, message_id) do get_channel_message(channel_id, message_id) |> bangify end @doc """ Deletes multiple messages from a channel. `messages` is a list of `Nostrum.Struct.Message.id` that you wish to delete. When given more than 100 messages, this function will chunk the given message list into blocks of 100 and send them off to the API. It will stop deleting on the first error that occurs. Keep in mind that deleting thousands of messages will take a pretty long time and it may be proper to just delete the channel you want to bulk delete in and recreate it. This method can only delete messages sent within the last two weeks. `Filter` is an optional parameter that specifies whether messages sent over two weeks ago should be filtered out; defaults to `true`. """ @spec bulk_delete_messages(integer, [Nostrum.Struct.Message.id()], boolean) :: error | {:ok} def bulk_delete_messages(channel_id, messages, filter \\ true) def bulk_delete_messages(channel_id, messages, false), do: send_chunked_delete(messages, channel_id) def bulk_delete_messages(channel_id, messages, true) do alias Nostrum.Snowflake snowflake_two_weeks_ago = DateTime.utc_now() |> DateTime.to_unix() # 60 seconds * 60 * 24 * 14 = 14 days / 2 weeks |> Kernel.-(60 * 60 * 24 * 14) |> DateTime.from_unix!() |> Snowflake.from_datetime!() messages |> Stream.filter(&(&1 > snowflake_two_weeks_ago)) |> send_chunked_delete(channel_id) end @spec send_chunked_delete( [Nostrum.Struct.Message.id()] | Enum.t(), Nostrum.Snowflake.t() ) :: error | {:ok} defp send_chunked_delete(messages, channel_id) do messages |> Stream.chunk_every(100) |> Stream.map(fn message_chunk -> request( :post, Constants.channel_bulk_delete(channel_id), %{messages: message_chunk} ) end) |> Enum.find({:ok}, &match?({:error, _}, &1)) end @doc """ Same as `bulk_delete_messages/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec bulk_delete_messages!(integer, [Nostrum.Struct.Message.id()], boolean) :: no_return | {:ok} def bulk_delete_messages!(channel_id, messages, filter \\ true) do bulk_delete_messages(channel_id, messages, filter) |> bangify end @doc """ Edit the permission overwrites for a user or role. Role or user to overwrite is specified by `overwrite_id`. `permission_info` is a map with the following keys: * `type` - Required; `member` if editing a user, `role` if editing a role. * `allow` - Bitwise value of allowed permissions. * `deny` - Bitwise value of denied permissions. * `type` - `member` if editing a user, `role` if editing a role. An optional `reason` can be provided for the audit log. `allow` and `deny` are defaulted to `0`, meaning that even if you don't specify them, they will override their respective former values in an existing overwrite. """ @spec edit_channel_permissions( integer, integer, %{ required(:type) => String.t(), optional(:allow) => integer, optional(:deny) => integer }, AuditLogEntry.reason() ) :: error | {:ok} def edit_channel_permissions(channel_id, overwrite_id, permission_info, reason \\ nil) do request(%{ method: :put, route: Constants.channel_permission(channel_id, overwrite_id), body: permission_info, params: [], headers: maybe_add_reason(reason) }) end @doc """ Same as `edit_channel_permissions/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec edit_channel_permissions!( integer, integer, %{ required(:type) => String.t(), optional(:allow) => integer, optional(:deny) => integer }, AuditLogEntry.reason() ) :: no_return | {:ok} def edit_channel_permissions!(channel_id, overwrite_id, permission_info, reason \\ nil) do edit_channel_permissions(channel_id, overwrite_id, permission_info, reason) |> bangify end @doc """ Delete a channel permission for a user or role. Role or user overwrite to delete is specified by `channel_id` and `overwrite_id`. An optional `reason` can be given for the audit log. """ @spec delete_channel_permissions(integer, integer, AuditLogEntry.reason()) :: error | {:ok} def delete_channel_permissions(channel_id, overwrite_id, reason \\ nil) do request(%{ method: :delete, route: Constants.channel_permission(channel_id, overwrite_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @doc ~S""" Gets a list of invites for a channel. This endpoint requires the 'VIEW_CHANNEL' and 'MANAGE_CHANNELS' permissions. If successful, returns `{:ok, invite}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_channel_invites(43189401384091) {:ok, [%Nostrum.Struct.Invite{} | _]} ``` """ @spec get_channel_invites(Channel.id()) :: error | {:ok, [Invite.detailed_invite()]} def get_channel_invites(channel_id) when is_snowflake(channel_id) do request(:get, Constants.channel_invites(channel_id)) |> handle_request_with_decode({:list, {:struct, Invite}}) end @doc ~S""" Same as `get_channel_invites/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_channel_invites!(Channel.id()) :: no_return | [Invite.detailed_invite()] def get_channel_invites!(channel_id) do get_channel_invites(channel_id) |> bangify end @doc ~S""" Creates an invite for a guild channel. An optional `reason` can be provided for the audit log. This endpoint requires the `CREATE_INSTANT_INVITE` permission. If successful, returns `{:ok, invite}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:max_age` (integer) - duration of invite in seconds before expiry, or 0 for never. (default: `86400`) * `:max_uses` (integer) - max number of uses or 0 for unlimited. (default: `0`) * `:temporary` (boolean) - Whether the invite should grant temporary membership. (default: `false`) * `:unique` (boolean) - used when creating unique one time use invites. (default: `false`) ## Examples ```Elixir Nostrum.Api.create_channel_invite(41771983423143933) {:ok, Nostrum.Struct.Invite{}} Nostrum.Api.create_channel_invite(41771983423143933, max_uses: 20) {:ok, %Nostrum.Struct.Invite{}} ``` """ @spec create_channel_invite(Channel.id(), options, AuditLogEntry.reason()) :: error | {:ok, Invite.detailed_invite()} def create_channel_invite(channel_id, options \\ [], reason \\ nil) def create_channel_invite(channel_id, options, reason) when is_list(options), do: create_channel_invite(channel_id, Map.new(options), reason) def create_channel_invite(channel_id, options, reason) when is_snowflake(channel_id) and is_map(options) do %{ method: :post, route: Constants.channel_invites(channel_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Invite}) end @doc ~S""" Same as `create_channel_invite/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_channel_invite!(Channel.id(), options, AuditLogEntry.reason()) :: no_return | Invite.detailed_invite() def create_channel_invite!(channel_id, options \\ [], reason \\ nil) do create_channel_invite(channel_id, options, reason) |> bangify end @doc """ Triggers the typing indicator. Triggers the typing indicator in the channel specified by `channel_id`. The typing indicator lasts for about 8 seconds and then automatically stops. Returns `{:ok}` if successful. `error` otherwise. """ @spec start_typing(integer) :: error | {:ok} def start_typing(channel_id) do request(:post, Constants.channel_typing(channel_id)) end @doc """ Same as `start_typing/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec start_typing!(integer) :: no_return | {:ok} def start_typing!(channel_id) do start_typing(channel_id) |> bangify end @doc ~S""" Retrieves all pinned messages from a channel. This endpoint requires the 'VIEW_CHANNEL' and 'READ_MESSAGE_HISTORY' permissions. If successful, returns `{:ok, messages}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_pinned_messages(43189401384091) ``` """ @spec get_pinned_messages(Channel.id()) :: error | {:ok, [Message.t()]} def get_pinned_messages(channel_id) when is_snowflake(channel_id) do request(:get, Constants.channel_pins(channel_id)) |> handle_request_with_decode({:list, {:struct, Message}}) end @doc ~S""" Same as `get_pinned_messages/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_pinned_messages!(Channel.id()) :: no_return | [Message.t()] def get_pinned_messages!(channel_id) do get_pinned_messages(channel_id) |> bangify end @doc ~S""" Pins a message in a channel. This endpoint requires the 'VIEW_CHANNEL', 'READ_MESSAGE_HISTORY', and 'MANAGE_MESSAGES' permissions. It fires the `t:Nostrum.Consumer.message_update/0` and `t:Nostrum.Consumer.channel_pins_update/0` events. If successful, returns `{:ok}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.add_pinned_channel_message(43189401384091, 18743893102394) ``` """ @spec add_pinned_channel_message(Channel.id(), Message.id()) :: error | {:ok} def add_pinned_channel_message(channel_id, message_id) when is_snowflake(channel_id) and is_snowflake(message_id) do request(:put, Constants.channel_pin(channel_id, message_id)) end @doc ~S""" Same as `add_pinned_channel_message/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec add_pinned_channel_message!(Channel.id(), Message.id()) :: no_return | {:ok} def add_pinned_channel_message!(channel_id, message_id) do add_pinned_channel_message(channel_id, message_id) |> bangify end @doc """ Unpins a message in a channel. This endpoint requires the 'VIEW_CHANNEL', 'READ_MESSAGE_HISTORY', and 'MANAGE_MESSAGES' permissions. It fires the `t:Nostrum.Consumer.message_update/0` and `t:Nostrum.Consumer.channel_pins_update/0` events. Returns `{:ok}` if successful. `error` otherwise. """ @spec delete_pinned_channel_message(Channel.id(), Message.id()) :: error | {:ok} def delete_pinned_channel_message(channel_id, message_id) when is_snowflake(channel_id) and is_snowflake(message_id) do request(:delete, Constants.channel_pin(channel_id, message_id)) end @doc ~S""" Same as `delete_pinned_channel_message/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_pinned_channel_message!(Channel.id(), Message.id()) :: no_return | {:ok} def delete_pinned_channel_message!(channel_id, message_id) do delete_pinned_channel_message(channel_id, message_id) |> bangify end @doc ~S""" Gets a list of emojis for a given guild. This endpoint requires the `MANAGE_EMOJIS` permission. If successful, returns `{:ok, emojis}`. Otherwise, returns `t:Nostrum.Api.error/0`. """ @spec list_guild_emojis(Guild.id()) :: error | {:ok, [Emoji.t()]} def list_guild_emojis(guild_id) do request(:get, Constants.guild_emojis(guild_id)) |> handle_request_with_decode({:list, {:struct, Emoji}}) end @doc ~S""" Same as `list_guild_emojis/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec list_guild_emojis!(Guild.id()) :: no_return | [Emoji.t()] def list_guild_emojis!(guild_id) do list_guild_emojis(guild_id) |> bangify end @doc ~S""" Gets an emoji for the given guild and emoji ids. This endpoint requires the `MANAGE_EMOJIS` permission. If successful, returns `{:ok, emoji}`. Otherwise, returns `t:Nostrum.Api.error/0`. """ @spec get_guild_emoji(Guild.id(), Emoji.id()) :: error | {:ok, Emoji.t()} def get_guild_emoji(guild_id, emoji_id) do request(:get, Constants.guild_emoji(guild_id, emoji_id)) |> handle_request_with_decode({:struct, Emoji}) end @doc ~S""" Same as `get_guild_emoji/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild_emoji!(Guild.id(), Emoji.id()) :: no_return | Emoji.t() def get_guild_emoji!(guild_id, emoji_id) do get_guild_emoji(guild_id, emoji_id) |> bangify end @doc ~S""" Creates a new emoji for the given guild. This endpoint requires the `MANAGE_EMOJIS` permission. It fires a `t:Nostrum.Consumer.guild_emojis_update/0` event. An optional `reason` can be provided for the audit log. If successful, returns `{:ok, emoji}`. Otherwise, returns `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - name of the emoji * `:image` (base64 data URI) - the 128x128 emoji image. Maximum size of 256kb * `:roles` (list of `t:Nostrum.Snowflake.t/0`) - roles for which this emoji will be whitelisted (default: []) `:name` and `:image` are always required. ## Examples ```Elixir image = "data:image/png;base64,YXl5IGJieSB1IGx1a2luIDQgc3VtIGZ1az8=" Nostrum.Api.create_guild_emoji(43189401384091, name: "nostrum", image: image, roles: []) ``` """ @spec create_guild_emoji(Guild.id(), options, AuditLogEntry.reason()) :: error | {:ok, Emoji.t()} def create_guild_emoji(guild_id, options, reason \\ nil) def create_guild_emoji(guild_id, options, reason) when is_list(options), do: create_guild_emoji(guild_id, Map.new(options), reason) def create_guild_emoji(guild_id, %{} = options, reason) do %{ method: :post, route: Constants.guild_emojis(guild_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Emoji}) end @doc ~S""" Same as `create_guild_emoji/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_guild_emoji!(Guild.id(), options, AuditLogEntry.reason()) :: no_return | Emoji.t() def create_guild_emoji!(guild_id, params, reason \\ nil) do create_guild_emoji(guild_id, params, reason) |> bangify end @doc ~S""" Modify the given emoji. This endpoint requires the `MANAGE_EMOJIS` permission. It fires a `t:Nostrum.Consumer.guild_emojis_update/0` event. An optional `reason` can be provided for the audit log. If successful, returns `{:ok, emoji}`. Otherwise, returns `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - name of the emoji * `:roles` (list of `t:Nostrum.Snowflake.t/0`) - roles to which this emoji will be whitelisted ## Examples ```Elixir Nostrum.Api.modify_guild_emoji(43189401384091, 4314301984301, name: "elixir", roles: []) ``` """ @spec modify_guild_emoji(Guild.id(), Emoji.id(), options, AuditLogEntry.reason()) :: error | {:ok, Emoji.t()} def modify_guild_emoji(guild_id, emoji_id, options \\ %{}, reason \\ nil) def modify_guild_emoji(guild_id, emoji_id, options, reason) when is_list(options), do: modify_guild_emoji(guild_id, emoji_id, Map.new(options), reason) def modify_guild_emoji(guild_id, emoji_id, %{} = options, reason) do %{ method: :patch, route: Constants.guild_emoji(guild_id, emoji_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Emoji}) end @doc ~S""" Same as `modify_guild_emoji/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_guild_emoji!(Guild.id(), Emoji.id(), options, AuditLogEntry.reason()) :: no_return | Emoji.t() def modify_guild_emoji!(guild_id, emoji_id, options, reason \\ nil) do modify_guild_emoji(guild_id, emoji_id, options, reason) |> bangify end @doc ~S""" Deletes the given emoji. An optional `reason` can be provided for the audit log. This endpoint requires the `MANAGE_EMOJIS` permission. It fires a `t:Nostrum.Consumer.guild_emojis_update/0` event. If successful, returns `{:ok}`. Otherwise, returns `t:Nostrum.Api.error/0`. """ @spec delete_guild_emoji(Guild.id(), Emoji.id(), AuditLogEntry.reason()) :: error | {:ok} def delete_guild_emoji(guild_id, emoji_id, reason \\ nil), do: request(%{ method: :delete, route: Constants.guild_emoji(guild_id, emoji_id), body: "", params: [], headers: maybe_add_reason(reason) }) @doc ~S""" Same as `delete_guild_emoji/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_guild_emoji!(Guild.id(), Emoji.id(), AuditLogEntry.reason()) :: no_return | {:ok} def delete_guild_emoji!(guild_id, emoji_id, reason \\ nil) do delete_guild_emoji(guild_id, emoji_id, reason) |> bangify end @doc ~S""" Get the `t:Nostrum.Struct.Guild.AuditLog.t/0` for the given `guild_id`. ## Options * `:user_id` (`t:Nostrum.Struct.User.id/0`) - filter the log for a user ID * `:action_type` (`t:integer/0`) - filter the log by audit log type, see [Audit Log Events](https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-events) * `:before` (`t:Nostrum.Struct.Snowflake.t/0`) - filter the log before a certain entry ID * `:limit` (`t:pos_integer/0`) - how many entries are returned (default 50, minimum 1, maximum 100) """ @spec get_guild_audit_log(Guild.id(), options) :: {:ok, AuditLog.t()} | error def get_guild_audit_log(guild_id, options \\ []) do request(:get, Constants.guild_audit_logs(guild_id), "", options) |> handle_request_with_decode({:struct, AuditLog}) end @doc ~S""" Gets a guild. If successful, returns `{:ok, guild}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_guild(81384788765712384) {:ok, %Nostrum.Struct.Guild{id: 81384788765712384}} ``` """ @spec get_guild(Guild.id()) :: error | {:ok, Guild.rest_guild()} def get_guild(guild_id) when is_snowflake(guild_id) do request(:get, Constants.guild(guild_id)) |> handle_request_with_decode({:struct, Guild}) end @doc """ Same as `get_guild/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild!(Guild.id()) :: no_return | Guild.rest_guild() def get_guild!(guild_id) do get_guild(guild_id) |> bangify end @doc """ Modifies a guild's settings. This endpoint requires the `MANAGE_GUILD` permission. It fires the `t:Nostrum.Consumer.guild_update/0` event. An optional `reason` can be provided for the audit log. If successful, returns `{:ok, guild}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - guild name * `:region` (string) - guild voice region id * `:verification_level` (integer) - verification level * `:default_message_notifications` (integer) - default message notification level * `:explicit_content_filter` (integer) - explicit content filter level * `:afk_channel_id` (`t:Nostrum.Snowflake.t/0`) - id for afk channel * `:afk_timeout` (integer) - afk timeout in seconds * `:icon` (base64 data URI) - 128x128 jpeg image for the guild icon * `:owner_id` (`t:Nostrum.Snowflake.t/0`) - user id to transfer guild ownership to (must be owner) * `:splash` (base64 data URI) - 128x128 jpeg image for the guild splash (VIP only) * `:system_channel_id` (`t:Nostrum.Snowflake.t/0`) - the id of the channel to which system messages are sent * `:rules_channel_id` (`t:Nostrum.Snowflake.t/0`) - the id of the channel that is used for rules in public guilds * `:public_updates_channel_id` (`t:Nostrum.Snowflake.t/0`) - the id of the channel where admins and moderators receive notices from Discord in public guilds ## Examples ```elixir Nostrum.Api.modify_guild(451824027976073216, name: "Nose Drum") {:ok, %Nostrum.Struct.Guild{id: 451824027976073216, name: "Nose Drum", ...}} ``` """ @spec modify_guild(Guild.id(), options, AuditLogEntry.reason()) :: error | {:ok, Guild.rest_guild()} def modify_guild(guild_id, options \\ [], reason \\ nil) def modify_guild(guild_id, options, reason) when is_list(options), do: modify_guild(guild_id, Map.new(options), reason) def modify_guild(guild_id, options, reason) when is_snowflake(guild_id) and is_map(options) do options = Map.new(options) %{ method: :patch, route: Constants.guild(guild_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Guild}) end @doc """ Same as `modify_guild/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_guild!(Guild.id(), options) :: no_return | Guild.rest_guild() def modify_guild!(guild_id, options \\ []) do modify_guild(guild_id, options) |> bangify end @doc ~S""" Deletes a guild. This endpoint requires that the current user is the owner of the guild. It fires the `t:Nostrum.Consumer.guild_delete/0` event. If successful, returns `{:ok}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.delete_guild(81384788765712384) {:ok} ``` """ @spec delete_guild(Guild.id()) :: error | {:ok} def delete_guild(guild_id) when is_snowflake(guild_id) do request(:delete, Constants.guild(guild_id)) end @doc ~S""" Same as `delete_guild/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_guild!(Guild.id()) :: no_return | {:ok} def delete_guild!(guild_id) do delete_guild(guild_id) |> bangify end @doc ~S""" Gets a list of guild channels. If successful, returns `{:ok, channels}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_guild_channels(81384788765712384) {:ok, [%Nostrum.Struct.Channel{guild_id: 81384788765712384} | _]} ``` """ @spec get_guild_channels(Guild.id()) :: error | {:ok, [Channel.guild_channel()]} def get_guild_channels(guild_id) when is_snowflake(guild_id) do request(:get, Constants.guild_channels(guild_id)) |> handle_request_with_decode({:list, {:struct, Channel}}) end @doc ~S""" Same as `get_guild_channels/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild_channels!(Guild.id()) :: no_return | [Channel.guild_channel()] def get_guild_channels!(guild_id) do get_guild_channels(guild_id) |> bangify end @doc """ Creates a channel for a guild. This endpoint requires the `MANAGE_CHANNELS` permission. It fires a `t:Nostrum.Consumer.channel_create/0` event. If successful, returns `{:ok, channel}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - channel name (2-100 characters) * `:type` (integer) - the type of channel (See `Nostrum.Struct.Channel`) * `:topic` (string) - channel topic (0-1024 characters) * `:bitrate` (integer) - the bitrate (in bits) of the voice channel (voice only) * `:user_limit` (integer) - the user limit of the voice channel (voice only) * `:permission_overwrites` (list of `t:Nostrum.Struct.Overwrite.t/0` or equivalent map) - the channel's permission overwrites * `:parent_id` (`t:Nostrum.Struct.Channel.id/0`) - id of the parent category for a channel * `:nsfw` (boolean) - if the channel is nsfw `:name` is always required. ## Examples ```Elixir Nostrum.Api.create_guild_channel(81384788765712384, name: "elixir-nostrum", topic: "craig's domain") {:ok, %Nostrum.Struct.Channel{guild_id: 81384788765712384}} ``` """ @spec create_guild_channel(Guild.id(), options) :: error | {:ok, Channel.guild_channel()} def create_guild_channel(guild_id, options) def create_guild_channel(guild_id, options) when is_list(options), do: create_guild_channel(guild_id, Map.new(options)) def create_guild_channel(guild_id, %{} = options) when is_snowflake(guild_id) do request(:post, Constants.guild_channels(guild_id), options) |> handle_request_with_decode({:struct, Channel}) end @doc ~S""" Same as `create_guild_channel/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_guild_channel!(Guild.id(), options) :: no_return | Channel.guild_channel() def create_guild_channel!(guild_id, options) do create_guild_channel(guild_id, options) |> bangify end @doc """ Reorders a guild's channels. This endpoint requires the `MANAGE_CHANNELS` permission. It fires multiple `t:Nostrum.Consumer.channel_update/0` events. If successful, returns `{:ok, channels}`. Otherwise, returns a `t:Nostrum.Api.error/0`. `positions` is a list of maps that each map a channel id with a position. ## Examples ```Elixir Nostrum.Api.modify_guild_channel_positions(279093381723062272, [%{id: 351500354581692420, position: 2}]) {:ok} ``` """ @spec modify_guild_channel_positions(Guild.id(), [%{id: integer, position: integer}]) :: error | {:ok} def modify_guild_channel_positions(guild_id, positions) when is_snowflake(guild_id) and is_list(positions) do request(:patch, Constants.guild_channels(guild_id), positions) end @doc ~S""" Same as `modify_guild_channel_positions/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_guild_channel_positions!(Guild.id(), [%{id: integer, position: integer}]) :: no_return | {:ok} def modify_guild_channel_positions!(guild_id, positions) do modify_guild_channel_positions(guild_id, positions) |> bangify end @doc """ Gets a guild member. If successful, returns `{:ok, member}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_guild_member(4019283754613, 184937267485) ``` """ @spec get_guild_member(Guild.id(), User.id()) :: error | {:ok, Member.t()} def get_guild_member(guild_id, user_id) when is_snowflake(guild_id) and is_snowflake(user_id) do request(:get, Constants.guild_member(guild_id, user_id)) |> handle_request_with_decode({:struct, Member}) end @doc """ Same as `get_guild_member/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild_member!(Guild.id(), User.id()) :: no_return | Member.t() def get_guild_member!(guild_id, user_id) do get_guild_member(guild_id, user_id) |> bangify end @doc """ Gets a list of a guild's members. If successful, returns `{:ok, members}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:limit` (integer) - max number of members to return (1-1000) (default: 1) * `:after` (`t:Nostrum.Struct.User.id/0`) - the highest user id in the previous page (default: 0) ## Examples ```Elixir Nostrum.Api.list_guild_members(41771983423143937, limit: 1) ``` """ @spec list_guild_members(Guild.id(), options) :: error | {:ok, [Member.t()]} def list_guild_members(guild_id, options \\ %{}) def list_guild_members(guild_id, options) when is_list(options), do: list_guild_members(guild_id, Map.new(options)) def list_guild_members(guild_id, %{} = options) when is_snowflake(guild_id) do request(:get, Constants.guild_members(guild_id), "", options) |> handle_request_with_decode({:list, {:struct, Member}}) end @doc """ Same as `list_guild_members/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec list_guild_members!(Guild.id(), options) :: no_return | [Member.t()] def list_guild_members!(guild_id, options \\ %{}) do list_guild_members(guild_id, options) |> bangify end @doc ~S""" Puts a user in a guild. This endpoint fires the `t:Nostrum.Consumer.guild_member_add/0` event. It requires the `CREATE_INSTANT_INVITE` permission. Additionally, it situationally requires the `MANAGE_NICKNAMES`, `MANAGE_ROLES`, `MUTE_MEMBERS`, and `DEAFEN_MEMBERS` permissions. If successful, returns `{:ok, member}` or `{:ok}` if the user was already a member of the guild. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:access_token` (string) - the user's oauth2 access token * `:nick` (string) - value to set users nickname to * `:roles` (list of `t:Nostrum.Struct.Guild.Role.id/0`) - array of role ids the member is assigned * `:mute` (boolean) - if the user is muted * `:deaf` (boolean) - if the user is deafened `:access_token` is always required. ## Examples ```Elixir Nostrum.Api.add_guild_member( 41771983423143937, 18374719829378473, access_token: "6qrZcUqja7812RVdnEKjpzOL4CvHBFG", nick: "nostrum", roles: [431849301, 913809431] ) ``` """ @spec add_guild_member(Guild.id(), User.id(), options) :: error | {:ok, Member.t()} | {:ok} def add_guild_member(guild_id, user_id, options) def add_guild_member(guild_id, user_id, options) when is_list(options), do: add_guild_member(guild_id, user_id, Map.new(options)) def add_guild_member(guild_id, user_id, %{} = options) when is_snowflake(guild_id) and is_snowflake(user_id) do request(:put, Constants.guild_member(guild_id, user_id), options) |> handle_request_with_decode({:struct, Member}) end @doc """ Same as `add_guild_member/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec add_guild_member!(Guild.id(), User.id(), options) :: no_return | Member.t() | {:ok} def add_guild_member!(guild_id, user_id, options) do add_guild_member(guild_id, user_id, options) |> bangify end @doc ~S""" Modifies a guild member's attributes. This endpoint fires the `t:Nostrum.Consumer.guild_member_update/0` event. It situationally requires the `MANAGE_NICKNAMES`, `MANAGE_ROLES`, `MUTE_MEMBERS`, `DEAFEN_MEMBERS`, and `MOVE_MEMBERS` permissions. If successful, returns `{:ok, member}`. Otherwise, returns a `t:Nostrum.Api.error/0`. An optional `reason` argument can be given for the audit log. ## Options * `:nick` (string) - value to set users nickname to * `:roles` (list of `t:Nostrum.Snowflake.t/0`) - array of role ids the member is assigned * `:mute` (boolean) - if the user is muted * `:deaf` (boolean) - if the user is deafened * `:channel_id` (`t:Nostrum.Snowflake.t/0`) - id of channel to move user to (if they are connected to voice) * `:communication_disabled_until` (`t:DateTime.t/0` or `nil`) - datetime to disable user communication (timeout) until, or `nil` to remove timeout. ## Examples ```Elixir Nostrum.Api.modify_guild_member(41771983423143937, 637162356451, nick: "Nostrum") {:ok, %Nostrum.Struct.Member{}} ``` """ @spec modify_guild_member(Guild.id(), User.id(), options, AuditLogEntry.reason()) :: error | {:ok, Member.t()} def modify_guild_member(guild_id, user_id, options \\ %{}, reason \\ nil) def modify_guild_member(guild_id, user_id, options, reason) when is_list(options), do: modify_guild_member(guild_id, user_id, Map.new(options), reason) def modify_guild_member(guild_id, user_id, %{} = options, reason) when is_snowflake(guild_id) and is_snowflake(user_id) do options = options |> maybe_convert_date_time(:communication_disabled_until) request(%{ method: :patch, route: Constants.guild_member(guild_id, user_id), body: options, params: [], headers: maybe_add_reason(reason) }) |> handle_request_with_decode({:struct, Member}) end @doc """ Same as `modify_guild_member/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_guild_member!(Guild.id(), User.id(), options, AuditLogEntry.reason()) :: error | {:ok} def modify_guild_member!(guild_id, user_id, options \\ %{}, reason \\ nil) do modify_guild_member(guild_id, user_id, options, reason) |> bangify end @doc """ Modifies the nickname of the current user in a guild. If successful, returns `{:ok, %{nick: nick}}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:nick` (string) - value to set users nickname to ## Examples ```Elixir Nostrum.Api.modify_current_user_nick(41771983423143937, nick: "Nostrum") {:ok, %{nick: "Nostrum"}} ``` """ @spec modify_current_user_nick(Guild.id(), options) :: error | {:ok, %{nick: String.t()}} def modify_current_user_nick(guild_id, options \\ %{}) do request(:patch, Constants.guild_me_nick(guild_id), options) |> handle_request_with_decode() end @doc """ Same as `modify_current_user_nick/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_current_user_nick!(Guild.id(), options) :: no_return | %{nick: String.t()} def modify_current_user_nick!(guild_id, options \\ %{}) do modify_current_user_nick(guild_id, options) |> bangify() end @doc """ Adds a role to a member. Role to add is specified by `role_id`. User to add role to is specified by `guild_id` and `user_id`. An optional `reason` can be given for the audit log. """ @spec add_guild_member_role(integer, integer, integer, AuditLogEntry.reason()) :: error | {:ok} def add_guild_member_role(guild_id, user_id, role_id, reason \\ nil) do request(%{ method: :put, route: Constants.guild_member_role(guild_id, user_id, role_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @doc """ Removes a role from a member. Role to remove is specified by `role_id`. User to remove role from is specified by `guild_id` and `user_id`. An optional `reason` can be given for the audit log. """ @spec remove_guild_member_role(integer, integer, integer, AuditLogEntry.reason()) :: error | {:ok} def remove_guild_member_role(guild_id, user_id, role_id, reason \\ nil) do request(%{ method: :delete, route: Constants.guild_member_role(guild_id, user_id, role_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @doc """ Removes a member from a guild. This event requires the `KICK_MEMBERS` permission. It fires a `t:Nostrum.Consumer.guild_member_remove/0` event. An optional reason can be provided for the audit log with `reason`. If successful, returns `{:ok}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.remove_guild_member(1453827904102291, 18739485766253) {:ok} ``` """ @spec remove_guild_member(Guild.id(), User.id(), AuditLogEntry.reason()) :: error | {:ok} def remove_guild_member(guild_id, user_id, reason \\ nil) when is_snowflake(guild_id) and is_snowflake(user_id) do request(%{ method: :delete, route: Constants.guild_member(guild_id, user_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @doc """ Same as `remove_guild_member/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec remove_guild_member!(Guild.id(), User.id(), AuditLogEntry.reason()) :: no_return | {:ok} def remove_guild_member!(guild_id, user_id, reason \\ nil) do remove_guild_member(guild_id, user_id, reason) |> bangify end @doc """ Gets a ban object for the given user from a guild. """ @doc since: "0.5.0" @spec get_guild_ban(integer, integer) :: error | {:ok, Guild.Ban.t()} def get_guild_ban(guild_id, user_id) do request(:get, Constants.guild_ban(guild_id, user_id)) |> handle_request_with_decode({:struct, Guild.Ban}) end @doc """ Gets a list of users banned from a guild. Guild to get bans for is specified by `guild_id`. """ @spec get_guild_bans(integer) :: error | {:ok, [Nostrum.Struct.User.t()]} def get_guild_bans(guild_id) do request(:get, Constants.guild_bans(guild_id)) |> handle_request_with_decode end @doc """ Bans a user from a guild. User to delete is specified by `guild_id` and `user_id`. An optional `reason` can be specified for the audit log. """ @spec create_guild_ban(integer, integer, integer, AuditLogEntry.reason()) :: error | {:ok} def create_guild_ban(guild_id, user_id, days_to_delete, reason \\ nil) do request(%{ method: :put, route: Constants.guild_ban(guild_id, user_id), body: %{delete_message_days: days_to_delete}, params: [], headers: maybe_add_reason(reason) }) end @doc """ Removes a ban for a user. User to unban is specified by `guild_id` and `user_id`. An optional `reason` can be specified for the audit log. """ @spec remove_guild_ban(integer, integer, AuditLogEntry.reason()) :: error | {:ok} def remove_guild_ban(guild_id, user_id, reason \\ nil) do request(%{ method: :delete, route: Constants.guild_ban(guild_id, user_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @doc ~S""" Gets a guild's roles. If successful, returns `{:ok, roles}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_guild_roles(147362948571673) ``` """ @spec get_guild_roles(Guild.id()) :: error | {:ok, [Role.t()]} def get_guild_roles(guild_id) when is_snowflake(guild_id) do request(:get, Constants.guild_roles(guild_id)) |> handle_request_with_decode({:list, {:struct, Role}}) end @doc ~S""" Same as `get_guild_roles/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild_roles!(Guild.id()) :: no_return | [Role.t()] def get_guild_roles!(guild_id) do get_guild_roles(guild_id) |> bangify end @doc ~S""" Creates a guild role. An optional reason for the audit log can be provided via `reason`. This endpoint requires the `MANAGE_ROLES` permission. It fires a `t:Nostrum.Consumer.guild_role_create/0` event. If successful, returns `{:ok, role}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - name of the role (default: "new role") * `:permissions` (integer) - bitwise of the enabled/disabled permissions (default: @everyone perms) * `:color` (integer) - RGB color value (default: 0) * `:hoist` (boolean) - whether the role should be displayed separately in the sidebar (default: false) * `:mentionable` (boolean) - whether the role should be mentionable (default: false) ## Examples ```Elixir Nostrum.Api.create_guild_role(41771983423143937, name: "nostrum-club", hoist: true) ``` """ @spec create_guild_role(Guild.id(), options, AuditLogEntry.reason()) :: error | {:ok, Role.t()} def create_guild_role(guild_id, options, reason \\ nil) def create_guild_role(guild_id, options, reason) when is_list(options), do: create_guild_role(guild_id, Map.new(options), reason) def create_guild_role(guild_id, %{} = options, reason) when is_snowflake(guild_id) do %{ method: :post, route: Constants.guild_roles(guild_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Role}) end @doc ~S""" Same as `create_guild_role/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_guild_role!(Guild.id(), options, AuditLogEntry.reason()) :: no_return | Role.t() def create_guild_role!(guild_id, options, reason \\ nil) do create_guild_role(guild_id, options, reason) |> bangify end @doc ~S""" Reorders a guild's roles. This endpoint requires the `MANAGE_ROLES` permission. It fires multiple `t:Nostrum.Consumer.guild_role_update/0` events. If successful, returns `{:ok, roles}`. Otherwise, returns a `t:Nostrum.Api.error/0`. `positions` is a list of maps that each map a role id with a position. ## Examples ```Elixir Nostrum.Api.modify_guild_role_positions(41771983423143937, [%{id: 41771983423143936, position: 2}]) ``` """ @spec modify_guild_role_positions( Guild.id(), [%{id: Role.id(), position: integer}], AuditLogEntry.reason() ) :: error | {:ok, [Role.t()]} def modify_guild_role_positions(guild_id, positions, reason \\ nil) when is_snowflake(guild_id) and is_list(positions) do %{ method: :patch, route: Constants.guild_roles(guild_id), body: positions, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:list, {:struct, Role}}) end @doc ~S""" Same as `modify_guild_role_positions/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_guild_role_positions!( Guild.id(), [%{id: Role.id(), position: integer}], AuditLogEntry.reason() ) :: no_return | [Role.t()] def modify_guild_role_positions!(guild_id, positions, reason \\ nil) do modify_guild_role_positions(guild_id, positions, reason) |> bangify end @doc ~S""" Modifies a guild role. This endpoint requires the `MANAGE_ROLES` permission. It fires a `t:Nostrum.Consumer.guild_role_update/0` event. An optional `reason` can be specified for the audit log. If successful, returns `{:ok, role}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:name` (string) - name of the role * `:permissions` (integer) - bitwise of the enabled/disabled permissions * `:color` (integer) - RGB color value (default: 0) * `:hoist` (boolean) - whether the role should be displayed separately in the sidebar * `:mentionable` (boolean) - whether the role should be mentionable ## Examples ```Elixir Nostrum.Api.modify_guild_role(41771983423143937, 392817238471936, hoist: false, name: "foo-bar") ``` """ @spec modify_guild_role(Guild.id(), Role.id(), options, AuditLogEntry.reason()) :: error | {:ok, Role.t()} def modify_guild_role(guild_id, role_id, options, reason \\ nil) def modify_guild_role(guild_id, role_id, options, reason) when is_list(options), do: modify_guild_role(guild_id, role_id, Map.new(options), reason) def modify_guild_role(guild_id, role_id, %{} = options, reason) when is_snowflake(guild_id) and is_snowflake(role_id) do %{ method: :patch, route: Constants.guild_role(guild_id, role_id), body: options, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode({:struct, Role}) end @doc ~S""" Same as `modify_guild_role/3`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_guild_role!(Guild.id(), Role.id(), options, AuditLogEntry.reason()) :: no_return | Role.t() def modify_guild_role!(guild_id, role_id, options, reason \\ nil) do modify_guild_role(guild_id, role_id, options, reason) |> bangify end @doc ~S""" Deletes a role from a guild. An optional `reason` can be specified for the audit log. This endpoint requires the `MANAGE_ROLES` permission. It fires a `t:Nostrum.Consumer.guild_role_delete/0` event. If successful, returns `{:ok}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.delete_guild_role(41771983423143937, 392817238471936) ``` """ @spec delete_guild_role(Guild.id(), Role.id(), AuditLogEntry.reason()) :: error | {:ok} def delete_guild_role(guild_id, role_id, reason \\ nil) when is_snowflake(guild_id) and is_snowflake(role_id) do request(%{ method: :delete, route: Constants.guild_role(guild_id, role_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @doc ~S""" Same as `delete_guild_role/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_guild_role!(Guild.id(), Role.id(), AuditLogEntry.reason()) :: no_return | {:ok} def delete_guild_role!(guild_id, role_id, reason \\ nil) do delete_guild_role(guild_id, role_id, reason) |> bangify end @doc """ Gets the number of members that would be removed in a prune given `days`. This endpoint requires the `KICK_MEMBERS` permission. If successful, returns `{:ok, %{pruned: pruned}}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_guild_prune_count(81384788765712384, 1) {:ok, %{pruned: 0}} ``` """ @spec get_guild_prune_count(Guild.id(), 1..30) :: error | {:ok, %{pruned: integer}} def get_guild_prune_count(guild_id, days) when is_snowflake(guild_id) and days in 1..30 do request(:get, Constants.guild_prune(guild_id), "", days: days) |> handle_request_with_decode end @doc ~S""" Same as `get_guild_prune_count/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild_prune_count!(Guild.id(), 1..30) :: no_return | %{pruned: integer} def get_guild_prune_count!(guild_id, days) do get_guild_prune_count(guild_id, days) |> bangify end @doc """ Begins a guild prune to prune members within `days`. An optional `reason` can be provided for the guild audit log. This endpoint requires the `KICK_MEMBERS` permission. It fires multiple `t:Nostrum.Consumer.guild_member_remove/0` events. If successful, returns `{:ok, %{pruned: pruned}}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.begin_guild_prune(81384788765712384, 1) {:ok, %{pruned: 0}} ``` """ @spec begin_guild_prune(Guild.id(), 1..30, AuditLogEntry.reason()) :: error | {:ok, %{pruned: integer}} def begin_guild_prune(guild_id, days, reason \\ nil) when is_snowflake(guild_id) and days in 1..30 do %{ method: :post, route: Constants.guild_prune(guild_id), body: "", params: [days: days], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode end @doc ~S""" Same as `begin_guild_prune/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec begin_guild_prune!(Guild.id(), 1..30, AuditLogEntry.reason()) :: no_return | %{pruned: integer} def begin_guild_prune!(guild_id, days, reason) do begin_guild_prune(guild_id, days, reason) |> bangify end @doc """ Gets a list of voice regions for the guild. Guild to get voice regions for is specified by `guild_id`. """ @spec get_voice_region(integer) :: error | {:ok, [Nostrum.Struct.VoiceRegion.t()]} def get_voice_region(guild_id) do request(:get, Constants.guild_voice_regions(guild_id)) |> handle_request_with_decode end @doc ~S""" Gets a list of invites for a guild. This endpoint requires the `MANAGE_GUILD` permission. If successful, returns `{:ok, invites}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_guild_invites(81384788765712384) {:ok, [%Nostrum.Struct.Invite{} | _]} ``` """ @spec get_guild_invites(Guild.id()) :: error | {:ok, [Invite.detailed_invite()]} def get_guild_invites(guild_id) when is_snowflake(guild_id) do request(:get, Constants.guild_invites(guild_id)) |> handle_request_with_decode({:list, {:struct, Invite}}) end @doc ~S""" Same as `get_guild_invites/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_guild_invites!(Guild.id()) :: no_return | [Invite.detailed_invite()] def get_guild_invites!(guild_id) do get_guild_invites(guild_id) |> bangify end @doc """ Gets a list of guild integerations. Guild to get integrations for is specified by `guild_id`. """ @spec get_guild_integrations(Guild.id()) :: error | {:ok, [Nostrum.Struct.Guild.Integration.t()]} def get_guild_integrations(guild_id) do request(:get, Constants.guild_integrations(guild_id)) |> handle_request_with_decode end @doc """ Creates a new guild integeration. Guild to create integration with is specified by `guild_id`. `options` is a map with the following requires keys: * `type` - Integration type. * `id` - Integeration id. """ @spec create_guild_integrations(integer, %{ type: String.t(), id: integer }) :: error | {:ok} def create_guild_integrations(guild_id, options) do request(:post, Constants.guild_integrations(guild_id), options) end @doc """ Changes the settings and behaviours for a guild integeration. Integration to modify is specified by `guild_id` and `integeration_id`. `options` is a map with the following keys: * `expire_behavior` - Expiry behavior. * `expire_grace_period` - Period where the integration will ignore elapsed subs. * `enable_emoticons` - Whether emoticons should be synced. """ @spec modify_guild_integrations(integer, integer, %{ expire_behaviour: integer, expire_grace_period: integer, enable_emoticons: boolean }) :: error | {:ok} def modify_guild_integrations(guild_id, integration_id, options) do request(:patch, Constants.guild_integration(guild_id, integration_id), options) end @doc """ Deletes a guild integeration. Integration to delete is specified by `guild_id` and `integeration_id`. """ @spec delete_guild_integrations(integer, integer) :: error | {:ok} def delete_guild_integrations(guild_id, integration_id) do request(:delete, Constants.guild_integration(guild_id, integration_id)) end @doc """ Syncs a guild integration. Integration to sync is specified by `guild_id` and `integeration_id`. """ @spec sync_guild_integrations(integer, integer) :: error | {:ok} def sync_guild_integrations(guild_id, integration_id) do request(:post, Constants.guild_integration_sync(guild_id, integration_id)) end @doc """ Gets a guild embed. """ @spec get_guild_widget(integer) :: error | {:ok, map} def get_guild_widget(guild_id) do request(:get, Constants.guild_widget(guild_id)) end @doc """ Modifies a guild embed. """ @spec modify_guild_widget(integer, map) :: error | {:ok, map} def modify_guild_widget(guild_id, options) do request(:patch, Constants.guild_widget(guild_id), options) |> handle_request_with_decode end @doc """ Creates a new scheduled event for the guild. ## Options * `:channel_id` - (`t:Nostrum.Snowflake.t/0`) optional channel id for the event * `:entity_metadata` - (`t:Nostrum.Struct.Guild.ScheduledEvent.EntityMetadata.t/0`) metadata for the event * `:name` - (string) required name for the event * `:privacy_level` - (integer) at the time of writing, this must always be 2 for `GUILD_ONLY` * `:scheduled_start_time` - required time for the event to start as a `DateTime` or (ISO8601 timestamp)[`DateTime.to_iso8601/3`] * `:scheduled_end_time` - optional time for the event to end as a `DateTime` or (ISO8601 timestamp)[`DateTime.to_iso8601/3`] * `:description` - (string) optional description for the event * `:entity_type` - (integer) an integer representing the type of entity the event is for * `1` - `STAGE_INSTANCE` * `2` - `VOICE` * `3` - `EXTERNAL` See the (official documentation)[https://discord.com/developers/docs/resources/guild-scheduled-event] for more information. An optional `reason` can be specified for the audit log. """ @spec create_guild_scheduled_event(Guild.id(), reason :: AuditLogEntry.reason(), options) :: {:ok, ScheduledEvent.t()} | error def create_guild_scheduled_event(guild_id, reason \\ nil, options) def create_guild_scheduled_event(guild_id, reason, options) when is_list(options), do: create_guild_scheduled_event(guild_id, reason, Map.new(options)) def create_guild_scheduled_event(guild_id, reason, %{} = options) do options = options |> maybe_convert_date_time(:scheduled_start_time) |> maybe_convert_date_time(:scheduled_end_time) request(%{ method: :post, route: Constants.guild_scheduled_events(guild_id), body: options, params: [], headers: maybe_add_reason(reason) }) |> handle_request_with_decode({:struct, ScheduledEvent}) end @doc """ Get a list of scheduled events for a guild. """ @spec get_guild_scheduled_events(Guild.id()) :: error | {:ok, [ScheduledEvent.t()]} def get_guild_scheduled_events(guild_id) do request(:get, Constants.guild_scheduled_events(guild_id)) |> handle_request_with_decode({:list, {:struct, ScheduledEvent}}) end @doc """ Get a scheduled event for a guild. """ @spec get_guild_scheduled_event(Guild.id(), ScheduledEvent.id()) :: error | {:ok, ScheduledEvent.t()} def get_guild_scheduled_event(guild_id, event_id) do request(:get, Constants.guild_scheduled_event(guild_id, event_id)) |> handle_request_with_decode({:struct, ScheduledEvent}) end @doc """ Delete a scheduled event for a guild. """ @spec delete_guild_scheduled_event(Guild.id(), ScheduledEvent.id()) :: error | {:ok} def delete_guild_scheduled_event(guild_id, event_id) do request(:delete, Constants.guild_scheduled_event(guild_id, event_id)) end @doc """ Modify a scheduled event for a guild. Options are the same as for `create_guild_scheduled_event/2` except all fields are optional, with the additional optional integer field `:status` which can be one of: * `1` - `SCHEDULED * `2` - `ACTIVE` * `3` - `COMPLETED` * `4` - `CANCELLED` Copied from the official documentation: *If updating entity_type to `EXTERNAL`: * `channel_id` is required and must be set to null * `entity_metadata` with a `location` field must be provided * `scheduled_end_time` must be provided """ @spec modify_guild_scheduled_event( Guild.id(), ScheduledEvent.id(), reason :: AuditLogEntry.reason(), options ) :: error | {:ok, ScheduledEvent.t()} def modify_guild_scheduled_event(guild_id, event_id, reason \\ nil, options) def modify_guild_scheduled_event(guild_id, event_id, reason, options) when is_list(options), do: modify_guild_scheduled_event(guild_id, event_id, reason, Map.new(options)) def modify_guild_scheduled_event(guild_id, event_id, reason, %{} = options) do options = options |> maybe_convert_date_time(:scheduled_start_time) |> maybe_convert_date_time(:scheduled_end_time) request(%{ method: :patch, route: Constants.guild_scheduled_event(guild_id, event_id), body: options, params: [], headers: maybe_add_reason(reason) }) |> handle_request_with_decode({:struct, ScheduledEvent}) end @doc """ Get a list of users who have subscribed to an event. ## Options All are optional, with their default values listed. * `:limit` (integer) maximum number of users to return, defaults to `100` * `:with_member` (boolean) whether to include the member object for each user, defaults to `false` * `:before` (`t:Nostrum.Snowflake.t/0`) return only users before this user id, defaults to `nil` * `:after` (`t:Nostrum.Snowflake.t/0`) return only users after this user id, defaults to `nil` """ @spec get_guild_scheduled_event_users(Guild.id(), ScheduledEvent.id(), options) :: error | {:ok, [ScheduledEvent.User.t()]} def get_guild_scheduled_event_users(guild_id, event_id, params \\ []) do request(:get, Constants.guild_scheduled_event_users(guild_id, event_id), "", params) |> handle_request_with_decode({:list, {:struct, ScheduledEvent.User}}) end @doc ~S""" Gets an invite by its `invite_code`. If successful, returns `{:ok, invite}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:with_counts` (boolean) - whether to include member count fields ## Examples ```Elixir Nostrum.Api.get_invite("zsjUsC") Nostrum.Api.get_invite("zsjUsC", with_counts: true) ``` """ @spec get_invite(Invite.code(), options) :: error | {:ok, Invite.simple_invite()} def get_invite(invite_code, options \\ []) when is_binary(invite_code) do request(:get, Constants.invite(invite_code), "", options) |> handle_request_with_decode({:struct, Invite}) end @doc ~S""" Same as `get_invite/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_invite!(Invite.code(), options) :: no_return | Invite.simple_invite() def get_invite!(invite_code, options \\ []) do get_invite(invite_code, options) |> bangify end @doc ~S""" Deletes an invite by its `invite_code`. This endpoint requires the `MANAGE_CHANNELS` permission. If successful, returns `{:ok, invite}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.delete_invite("zsjUsC") ``` """ @spec delete_invite(Invite.code()) :: error | {:ok, Invite.simple_invite()} def delete_invite(invite_code) when is_binary(invite_code) do request(:delete, Constants.invite(invite_code)) |> handle_request_with_decode({:struct, Invite}) end @doc ~S""" Same as `delete_invite/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec delete_invite!(Invite.code()) :: no_return | Invite.simple_invite() def delete_invite!(invite_code) do delete_invite(invite_code) |> bangify end @doc """ Gets a user by its `t:Nostrum.Struct.User.id/0`. If the request is successful, this function returns `{:ok, user}`, where `user` is a `Nostrum.Struct.User`. Otherwise, returns `{:error, reason}`. """ @spec get_user(User.id()) :: error | {:ok, User.t()} def get_user(user_id) do request(:get, Constants.user(user_id)) |> handle_request_with_decode({:struct, User}) end @doc """ Same as `get_user/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_user!(User.id()) :: no_return | User.t() def get_user!(user_id) do get_user(user_id) |> bangify end @doc """ Gets info on the current user. If nostrum's caching is enabled, it is recommended to use `Me.get/0` instead of this function. This is because sending out an API request is much slower than pulling from our cache. If the request is successful, this function returns `{:ok, user}`, where `user` is nostrum's `Nostrum.Struct.User`. Otherwise, returns `{:error, reason}`. """ @spec get_current_user() :: error | {:ok, User.t()} def get_current_user do request(:get, Constants.me()) |> handle_request_with_decode({:struct, User}) end @doc """ Same as `get_current_user/0`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_current_user!() :: no_return | User.t() def get_current_user! do get_current_user() |> bangify end @doc ~S""" Changes the username or avatar of the current user. ## Options * `:username` (string) - new username * `:avatar` (string) - the user's avatar as [avatar data](https://discord.com/developers/docs/resources/user#avatar-data) ## Examples ```Elixir Nostrum.Api.modify_current_user(avatar: "data:image/jpeg;base64,YXl5IGJieSB1IGx1a2luIDQgc3VtIGZ1az8=") ``` """ @spec modify_current_user(options) :: error | {:ok, User.t()} def modify_current_user(options) def modify_current_user(options) when is_list(options), do: modify_current_user(Map.new(options)) def modify_current_user(%{} = options) do request(:patch, Constants.me(), options) |> handle_request_with_decode({:struct, User}) end @doc """ Same as `modify_current_user/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec modify_current_user!(options) :: no_return | User.t() def modify_current_user!(options) do modify_current_user(options) |> bangify end @doc """ Gets a list of guilds the user is currently in. This endpoint requires the `guilds` OAuth2 scope. If successful, returns `{:ok, guilds}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Options * `:before` (`t:Nostrum.Snowflake.t/0`) - get guilds before this guild ID * `:after` (`t:Nostrum.Snowflake.t/0`) - get guilds after this guild ID * `:limit` (integer) - max number of guilds to return (1-100) ## Examples ```Elixir iex> Nostrum.Api.get_current_user_guilds(limit: 1) {:ok, [%Nostrum.Struct.Guild{}]} ``` """ @spec get_current_user_guilds(options) :: error | {:ok, [Guild.user_guild()]} def get_current_user_guilds(options \\ []) def get_current_user_guilds(options) when is_list(options), do: get_current_user_guilds(Map.new(options)) def get_current_user_guilds(options) when is_map(options) do request(:get, Constants.me_guilds(), "", options) |> handle_request_with_decode({:list, {:struct, Guild}}) end @doc ~S""" Same as `get_current_user_guilds/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_current_user_guilds!(options) :: no_return | [Guild.user_guild()] def get_current_user_guilds!(options \\ []) do get_current_user_guilds(options) |> bangify end @doc """ Leaves a guild. Guild to leave is specified by `guild_id`. """ @spec leave_guild(integer) :: error | {:ok} def leave_guild(guild_id) do request(%{ method: :delete, route: Constants.me_guild(guild_id), body: "", params: [], headers: [] }) end @doc """ Gets a list of our user's DM channels. If successful, returns `{:ok, dm_channels}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.get_user_dms() {:ok, [%Nostrum.Struct.Channel{type: 1} | _]} ``` """ @spec get_user_dms() :: error | {:ok, [Channel.dm_channel()]} def get_user_dms do request(:get, Constants.me_channels()) |> handle_request_with_decode({:list, {:struct, Channel}}) end @doc ~S""" Same as `get_user_dms/0`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec get_user_dms!() :: no_return | [Channel.dm_channel()] def get_user_dms! do get_user_dms() |> bangify end @doc ~S""" Create a new DM channel with a user. If successful, returns `{:ok, dm_channel}`. Otherwise, returns a `t:Nostrum.Api.error/0`. ## Examples ```Elixir Nostrum.Api.create_dm(150061853001777154) {:ok, %Nostrum.Struct.Channel{type: 1}} ``` """ @spec create_dm(User.id()) :: error | {:ok, Channel.dm_channel()} def create_dm(user_id) when is_snowflake(user_id) do request(:post, Constants.me_channels(), %{recipient_id: user_id}) |> handle_request_with_decode({:struct, Channel}) end @doc ~S""" Same as `create_dm/1`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_dm!(User.id()) :: no_return | Channel.dm_channel() def create_dm!(user_id) do create_dm(user_id) |> bangify end @doc """ Creates a new group DM channel. If successful, returns `{:ok, group_dm_channel}`. Otherwise, returns a `t:Nostrum.Api.error/0`. `access_tokens` are user oauth2 tokens. `nicks` is a map that maps a user id to a nickname. ## Examples ```Elixir Nostrum.Api.create_group_dm(["6qrZcUqja7812RVdnEKjpzOL4CvHBFG"], %{41771983423143937 => "My Nickname"}) {:ok, %Nostrum.Struct.Channel{type: 3}} ``` """ @spec create_group_dm([String.t()], %{optional(User.id()) => String.t()}) :: error | {:ok, Channel.group_dm_channel()} def create_group_dm(access_tokens, nicks) when is_list(access_tokens) and is_map(nicks) do request(:post, Constants.me_channels(), %{access_tokens: access_tokens, nicks: nicks}) |> handle_request_with_decode({:struct, Channel}) end @doc ~S""" Same as `create_group_dm/2`, but raises `Nostrum.Error.ApiError` in case of failure. """ @spec create_group_dm!([String.t()], %{optional(User.id()) => String.t()}) :: no_return | Channel.group_dm_channel() def create_group_dm!(access_tokens, nicks) do create_group_dm(access_tokens, nicks) |> bangify end @doc """ Gets a list of user connections. """ @spec get_user_connections() :: error | {:ok, list()} def get_user_connections do request(:get, Constants.me_connections()) |> handle_request_with_decode end @doc """ Gets a list of voice regions. """ @spec list_voice_regions() :: error | {:ok, [Nostrum.Struct.VoiceRegion.t()]} def list_voice_regions do request(:get, Constants.regions()) |> handle_request_with_decode end @doc """ Creates a webhook. ## Parameters - `channel_id` - Id of the channel to send the message to. - `args` - Map with the following **required** keys: - `name` - Name of the webhook. - `avatar` - Base64 128x128 jpeg image for the default avatar. - `reason` - An optional reason for the guild audit log. """ @spec create_webhook( Channel.id(), %{ name: String.t(), avatar: String.t() }, AuditLogEntry.reason() ) :: error | {:ok, Nostrum.Struct.Webhook.t()} def create_webhook(channel_id, args, reason \\ nil) do %{ method: :post, route: Constants.webhooks_channel(channel_id), body: args, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode end @doc """ Gets a list of webook for a channel. ## Parameters - `channel_id` - Channel to get webhooks for. """ @spec get_channel_webhooks(Channel.id()) :: error | {:ok, [Nostrum.Struct.Webhook.t()]} def get_channel_webhooks(channel_id) do request(:get, Constants.webhooks_channel(channel_id)) |> handle_request_with_decode end @doc """ Gets a list of webooks for a guild. ## Parameters - `guild_id` - Guild to get webhooks for. """ @spec get_guild_webhooks(Guild.id()) :: error | {:ok, [Nostrum.Struct.Webhook.t()]} def get_guild_webhooks(guild_id) do request(:get, Constants.webhooks_guild(guild_id)) |> handle_request_with_decode end @doc """ Gets a webhook by id. ## Parameters - `webhook_id` - Id of the webhook to get. """ @spec get_webhook(Webhook.id()) :: error | {:ok, Nostrum.Struct.Webhook.t()} def get_webhook(webhook_id) do request(:get, Constants.webhook(webhook_id)) |> handle_request_with_decode end @doc """ Gets a webhook by id and token. This method is exactly like `get_webhook/1` but does not require authentication. ## Parameters - `webhook_id` - Id of the webhook to get. - `webhook_token` - Token of the webhook to get. """ @spec get_webhook_with_token(Webhook.id(), Webhook.token()) :: error | {:ok, Nostrum.Struct.Webhook.t()} def get_webhook_with_token(webhook_id, webhook_token) do request(:get, Constants.webhook_token(webhook_id, webhook_token)) |> handle_request_with_decode end @doc """ Modifies a webhook. ## Parameters - `webhook_id` - Id of the webhook to modify. - `args` - Map with the following *optional* keys: - `name` - Name of the webhook. - `avatar` - Base64 128x128 jpeg image for the default avatar. - `reason` - An optional reason for the guild audit log. """ @spec modify_webhook( Webhook.id(), %{ name: String.t(), avatar: String.t() }, AuditLogEntry.reason() ) :: error | {:ok, Nostrum.Struct.Webhook.t()} def modify_webhook(webhook_id, args, reason \\ nil) do %{ method: :patch, route: Constants.webhook(webhook_id), body: args, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode end @doc """ Modifies a webhook with a token. This method is exactly like `modify_webhook/1` but does not require authentication. ## Parameters - `webhook_id` - Id of the webhook to modify. - `webhook_token` - Token of the webhook to get. - `args` - Map with the following *optional* keys: - `name` - Name of the webhook. - `avatar` - Base64 128x128 jpeg image for the default avatar. - `reason` - An optional reason for the guild audit log. """ @spec modify_webhook_with_token( Webhook.id(), Webhook.token(), %{ name: String.t(), avatar: String.t() }, AuditLogEntry.reason() ) :: error | {:ok, Nostrum.Struct.Webhook.t()} def modify_webhook_with_token(webhook_id, webhook_token, args, reason \\ nil) do %{ method: :patch, route: Constants.webhook_token(webhook_id, webhook_token), body: args, params: [], headers: maybe_add_reason(reason) } |> request() |> handle_request_with_decode end @doc """ Deletes a webhook. ## Parameters - `webhook_id` - Id of webhook to delete. - `reason` - An optional reason for the guild audit log. """ @spec delete_webhook(Webhook.id(), AuditLogEntry.reason()) :: error | {:ok} def delete_webhook(webhook_id, reason \\ nil) do request(%{ method: :delete, route: Constants.webhook(webhook_id), body: "", params: [], headers: maybe_add_reason(reason) }) end @typep m1 :: %{ required(:content) => String.t(), :username => String.t(), :avatar_url => String.t(), :tts => boolean, optional(:file) => String.t() | nil, optional(:embeds) => nonempty_list(Embed.t()) | nil } @typep m2 :: %{ optional(:content) => String.t() | nil, :username => String.t(), :avatar_url => String.t(), :tts => boolean, required(:file) => String.t(), optional(:embeds) => nonempty_list(Embed.t()) | nil } @typep m3 :: %{ optional(:content) => String.t() | nil, :username => String.t(), :avatar_url => String.t(), :tts => boolean, optional(:file) => String.t() | nil, required(:embeds) => nonempty_list(Embed.t()) } @type matrix :: m1 | m2 | m3 @spec execute_webhook( Webhook.id() | User.id(), Webhook.token() | Interaction.token(), matrix, boolean ) :: error | {:ok} | {:ok, Message.t()} @doc """ Executes a webhook. ## Parameters - `webhook_id` - Id of the webhook to execute. - `webhook_token` - Token of the webhook to execute. - `args` - Map with the following required keys: - `content` - Message content. - `file` - File to send. - `embeds` - List of embeds to send. - `username` - Overrides the default name of the webhook. - `avatar_url` - Overrides the default avatar of the webhook. - `tts` - Whether the message should be read over text to speech. - `wait` - Whether to return an error or not. Defaults to `false`. **Note**: If `wait` is `true`, this method will return a `Message.t()` on success. Only one of `content`, `file` or `embeds` should be supplied in the `args` parameter. """ def execute_webhook(webhook_id, webhook_token, args, wait \\ false) def execute_webhook(webhook_id, webhook_token, %{file: _} = args, wait) do request_multipart( :post, Constants.webhook_token(webhook_id, webhook_token), args, wait: wait ) end def execute_webhook(webhook_id, webhook_token, %{content: _} = args, wait) do request( :post, Constants.webhook_token(webhook_id, webhook_token), args, wait: wait ) end @doc """ Edits a message previously created by the same webhook, args are the same as `execute_webhook/3`, however all fields are optional. """ @spec edit_webhook_message( Webhook.id(), Webhook.token(), Message.id(), map() ) :: error | {:ok, Message.t()} def edit_webhook_message(webhook_id, webhook_token, message_id, %{file: _} = args) do request_multipart( :patch, Constants.webhook_message_edit(webhook_id, webhook_token, message_id), args ) end def edit_webhook_message(webhook_id, webhook_token, message_id, args) do request( :patch, Constants.webhook_message_edit(webhook_id, webhook_token, message_id), args ) end @doc """ Executes a slack webhook. ## Parameters - `webhook_id` - Id of the webhook to execute. - `webhook_token` - Token of the webhook to execute. """ @spec execute_slack_webhook(Webhook.id(), Webhook.token(), boolean) :: error | {:ok} def execute_slack_webhook(webhook_id, webhook_token, wait \\ false) do request(:post, Constants.webhook_slack(webhook_id, webhook_token), wait: wait) end @doc """ Executes a git webhook. ## Parameters - `webhook_id` - Id of the webhook to execute. - `webhook_token` - Token of the webhook to execute. """ @spec execute_git_webhook(Webhook.id(), Webhook.token(), boolean) :: error | {:ok} def execute_git_webhook(webhook_id, webhook_token, wait \\ false) do request(:post, Constants.webhook_git(webhook_id, webhook_token), wait: wait) end @doc """ Gets the bot's OAuth2 application info. ## Example ```elixir Nostrum.Api.get_application_information {:ok, %{ bot_public: false, bot_require_code_grant: false, description: "Test", icon: nil, id: "172150183260323840", name: "Baba O-Riley", owner: %{ avatar: nil, discriminator: "0042", id: "172150183260323840", username: "i own a bot" }, }} ``` """ @spec get_application_information() :: error | {:ok, map()} def get_application_information do request(:get, Constants.application_information()) |> handle_request_with_decode end @doc """ Fetch all global commands. ## Parameters - `application_id`: Application ID for which to search commands. If not given, this will be fetched from `Me`. ## Return value A list of ``ApplicationCommand``s on success. See the official reference: https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure ## Example ```elixir iex> Nostrum.Api.get_global_application_commands {:ok, [ %{ application_id: "455589479713865749", description: "ed, man! man, ed", id: "789841753196331029", name: "edit" } ]} ``` """ @spec get_global_application_commands() :: {:ok, [map()]} | error @spec get_global_application_commands(User.id()) :: {:ok, [map()]} | error def get_global_application_commands(application_id \\ Me.get().id) do request(:get, Constants.global_application_commands(application_id)) |> handle_request_with_decode end @doc """ Create a new global application command. The new command will be available on all guilds in around an hour. If you want to test commands, use `create_guild_application_command/2` instead, as commands will become available instantly there. If an existing command with the same name exists, it will be overwritten. ## Parameters - `application_id`: Application ID for which to create the command. If not given, this will be fetched from `Me`. - `command`: Command configuration, see the linked API documentation for reference. ## Return value The created command. See the official reference: https://discord.com/developers/docs/interactions/application-commands#create-global-application-command ## Example ```elixir Nostrum.Api.create_application_command( %{name: "edit", description: "ed, man! man, ed", options: []} ) ``` """ @spec create_global_application_command(ApplicationCommand.application_command_map()) :: {:ok, map()} | error @spec create_global_application_command(User.id(), ApplicationCommand.application_command_map()) :: {:ok, map()} | error def create_global_application_command(application_id \\ Me.get().id, command) do request(:post, Constants.global_application_commands(application_id), command) |> handle_request_with_decode end @doc """ Update an existing global application command. The updated command will be available on all guilds in around an hour. ## Parameters - `application_id`: Application ID for which to edit the command. If not given, this will be fetched from `Me`. - `command_id`: The current snowflake of the command. - `command`: Command configuration, see the linked API documentation for reference. ## Return value The updated command. See the official reference: https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command """ @spec edit_global_application_command( Snowflake.t(), ApplicationCommand.application_command_edit_map() ) :: {:ok, map()} | error @spec edit_global_application_command( User.id(), Snowflake.t(), ApplicationCommand.application_command_edit_map() ) :: {:ok, map()} | error def edit_global_application_command( application_id \\ Me.get().id, command_id, command ) do request(:patch, Constants.global_application_command(application_id, command_id), command) |> handle_request_with_decode end @doc """ Delete an existing global application command. ## Parameters - `application_id`: Application ID for which to create the command. If not given, this will be fetched from `Me`. - `command_id`: The current snowflake of the command. """ @spec delete_global_application_command(Snowflake.t()) :: {:ok} | error @spec delete_global_application_command(User.id(), Snowflake.t()) :: {:ok} | error def delete_global_application_command(application_id \\ Me.get().id, command_id) do request(:delete, Constants.global_application_command(application_id, command_id)) end @doc """ Overwrite the existing global application commands. This action will: - Create any command that was provided and did not already exist - Update any command that was provided and already existed if its configuration changed - Delete any command that was not provided but existed on Discord's end Updates will be available in all guilds after 1 hour. Commands that do not already exist will count toward daily application command create limits. ## Parameters - `application_id`: Application ID for which to overwrite the commands. If not given, this will be fetched from `Me`. - `commands`: List of command configurations, see the linked API documentation for reference. ## Return value Updated list of global application commands. See the official reference: https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands """ @doc since: "0.5.0" @spec bulk_overwrite_global_application_commands([ApplicationCommand.application_command_map()]) :: {:ok, [map()]} | error @spec bulk_overwrite_global_application_commands(User.id(), [ ApplicationCommand.application_command_map() ]) :: {:ok, [map()]} | error def bulk_overwrite_global_application_commands(application_id \\ Me.get().id, commands) do request(:put, Constants.global_application_commands(application_id), commands) |> handle_request_with_decode end @doc """ Fetch all guild application commands for the given guild. ## Parameters - `application_id`: Application ID for which to fetch commands. If not given, this will be fetched from `Me`. - `guild_id`: The guild ID for which guild application commands should be requested. ## Return value A list of ``ApplicationCommand``s on success. See the official reference: https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure """ @spec get_guild_application_commands(Guild.id()) :: {:ok, [map()]} | error @spec get_guild_application_commands(User.id(), Guild.id()) :: {:ok, [map()]} | error def get_guild_application_commands(application_id \\ Me.get().id, guild_id) do request(:get, Constants.guild_application_commands(application_id, guild_id)) |> handle_request_with_decode end @doc """ Create a guild application command on the specified guild. The new command will be available immediately. ## Parameters - `application_id`: Application ID for which to create the command. If not given, this will be fetched from `Me`. - `guild_id`: Guild on which to create the command. - `command`: Command configuration, see the linked API documentation for reference. ## Return value The created command. See the official reference: https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command """ @spec create_guild_application_command(Guild.id(), ApplicationCommand.application_command_map()) :: {:ok, map()} | error @spec create_guild_application_command( User.id(), Guild.id(), ApplicationCommand.application_command_map() ) :: {:ok, map()} | error def create_guild_application_command( application_id \\ Me.get().id, guild_id, command ) do request(:post, Constants.guild_application_commands(application_id, guild_id), command) |> handle_request_with_decode end @doc """ Update an existing guild application command. The updated command will be available immediately. ## Parameters - `application_id`: Application ID for which to edit the command. If not given, this will be fetched from `Me`. - `guild_id`: Guild for which to update the command. - `command_id`: The current snowflake of the command. - `command`: Command configuration, see the linked API documentation for reference. ## Return value The updated command. See the official reference: https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command """ @spec edit_guild_application_command( Guild.id(), Snowflake.t(), ApplicationCommand.application_command_edit_map() ) :: {:ok, map()} | error @spec edit_guild_application_command( User.id(), Guild.id(), Snowflake.t(), ApplicationCommand.application_command_edit_map() ) :: {:ok, map()} | error def edit_guild_application_command( application_id \\ Me.get().id, guild_id, command_id, command ) do request( :patch, Constants.guild_application_command(application_id, guild_id, command_id), command ) |> handle_request_with_decode end @doc """ Delete an existing guild application command. ## Parameters - `application_id`: Application ID for which to create the command. If not given, this will be fetched from `Me`. - `guild_id`: The guild on which the command exists. - `command_id`: The current snowflake of the command. """ @spec delete_guild_application_command(Guild.id(), Snowflake.t()) :: {:ok} | error @spec delete_guild_application_command(User.id(), Guild.id(), Snowflake.t()) :: {:ok} | error def delete_guild_application_command( application_id \\ Me.get().id, guild_id, command_id ) do request(:delete, Constants.guild_application_command(application_id, guild_id, command_id)) end @doc """ Overwrite the existing guild application commands on the specified guild. This action will: - Create any command that was provided and did not already exist - Update any command that was provided and already existed if its configuration changed - Delete any command that was not provided but existed on Discord's end ## Parameters - `application_id`: Application ID for which to overwrite the commands. If not given, this will be fetched from `Me`. - `guild_id`: Guild on which to overwrite the commands. - `commands`: List of command configurations, see the linked API documentation for reference. ## Return value Updated list of guild application commands. See the official reference: https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands """ @doc since: "0.5.0" @spec bulk_overwrite_guild_application_commands(Guild.id(), [ ApplicationCommand.application_command_map() ]) :: {:ok, [map()]} | error @spec bulk_overwrite_guild_application_commands(User.id(), Guild.id(), [ ApplicationCommand.application_command_map() ]) :: {:ok, [map()]} | error def bulk_overwrite_guild_application_commands( application_id \\ Me.get().id, guild_id, commands ) do request(:put, Constants.guild_application_commands(application_id, guild_id), commands) |> handle_request_with_decode end # Why the two separate functions here? # For the standard use case of "responding to an interaction retrieved # from the gateway", `create_interaction_response/2` is perfectly # sufficient. However, when one, for instance, uses Nostrum in a web # service, or wants to respond to interactions at a later point in time, # we do not want the user to manually have to reconstruct interactions. @doc """ Same as `create_interaction_response/3`, but directly takes the `t:Nostrum.Struct.Interaction.t/0` received from the gateway. """ @spec create_interaction_response(Interaction.t(), map()) :: {:ok} | error def create_interaction_response(interaction, response) do create_interaction_response(interaction.id, interaction.token, response) end @doc """ Create a response to an interaction received from the gateway. ## Parameters - `id`: The interaction ID to which the response should be created. - `token`: The interaction token. - `response`: An [`InteractionResponse`](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object) object. See the linked documentation. ## Example ```elixir response = %{ type: 4, data: %{ content: "I copy and pasted this code." } } Nostrum.Api.create_interaction_response(interaction, response) ``` As an alternative to passing the interaction ID and token, the original `t:Nostrum.Struct.Interaction.t/0` can also be passed directly. See `create_interaction_response/2`. """ @spec create_interaction_response(Interaction.id(), Interaction.token(), map()) :: {:ok} | error def create_interaction_response(id, token, response) do request(:post, Constants.interaction_callback(id, token), response) end @doc """ Same as `edit_interaction_response/3`, but directly takes the `t:Nostrum.Struct.Interaction.t/0` received from the gateway. """ @spec edit_interaction_response(Interaction.t(), map()) :: {:ok, Message.t()} | error def edit_interaction_response(%Interaction{} = interaction, response) do edit_interaction_response(interaction.application_id, interaction.token, response) end @doc """ Edits the original interaction response. Functions the same as `edit_webhook_message/3` """ @spec edit_interaction_response(User.id(), Interaction.token(), map()) :: {:ok, Message.t()} | error def edit_interaction_response(id \\ Me.get().id, token, response) do request(:patch, Constants.interaction_callback_original(id, token), response) |> handle_request_with_decode({:struct, Message}) end @doc """ Same as `delete_interaction_response/3`, but directly takes the `t:Nostrum.Struct.Interaction.t/0` received from the gateway. """ @spec delete_interaction_response(Interaction.t()) :: {:ok} | error def delete_interaction_response(%Interaction{} = interaction) do delete_interaction_response(interaction.application_id, interaction.token) end @doc """ Deletes the original interaction response. """ @spec delete_interaction_response(User.id(), Interaction.token()) :: {:ok} | error def delete_interaction_response(id \\ Me.get().id, token) do request(:delete, Constants.interaction_callback_original(id, token)) end @doc """ Create a followup message for an interaction. Delegates to ``execute_webhook/3``, see the function for more details. """ @spec create_followup_message(Interaction.token(), map()) :: {:ok} | error @spec create_followup_message(User.id(), Interaction.token(), map()) :: {:ok} | error def create_followup_message(application_id \\ Me.get().id, token, webhook_payload) do execute_webhook(application_id, token, webhook_payload) end @doc """ Delete a followup message for an interaction. ## Parameters - `application_id`: Application ID for which to create the command. If not given, this will be fetched from `Me`. - `token`: Interaction token. - `message_id`: Followup message ID. """ @spec delete_interaction_followup_message(Interaction.token(), Message.id()) :: {:ok} | error @spec delete_interaction_followup_message(User.id(), Interaction.token(), Message.id()) :: {:ok} | error def delete_interaction_followup_message( application_id \\ Me.get().id, token, message_id ) do request(:delete, Constants.interaction_followup_message(application_id, token, message_id)) end @doc """ Fetches command permissions for all commands for your application in a guild. ## Parameters - `application_id`: Application ID commands are registered under. If not given, this will be fetched from `Me`. - `guild_id`: Guild ID to fetch command permissions from. ## Return value This method returns a list of guild application command permission objects, see all available values on the [Discord API docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure). """ @doc since: "0.5.0" @spec get_guild_application_command_permissions(Guild.id()) :: {:ok, [map()]} | error @spec get_guild_application_command_permissions(User.id(), Guild.id()) :: {:ok, [map()]} | error def get_guild_application_command_permissions( application_id \\ Me.get().id, guild_id ) do request(:get, Constants.guild_application_command_permissions(application_id, guild_id)) |> handle_request_with_decode end @doc """ Fetches command permissions for a specific command for your application in a guild. ## Parameters - `application_id`: Application ID commands are registered under. If not given, this will be fetched from `Me`. - `guild_id`: Guild ID to fetch command permissions from. - `command_id`: Command ID to fetch permissions for. ## Return value This method returns a single guild application command permission object, see all available values on the [Discord API docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure). """ @doc since: "0.5.0" @spec get_application_command_permissions(Guild.id(), Snowflake.t()) :: {:ok, map()} | error @spec get_application_command_permissions(User.id(), Guild.id(), Snowflake.t()) :: {:ok, map()} | error def get_application_command_permissions( application_id \\ Me.get().id, guild_id, command_id ) do request( :get, Constants.guild_application_command_permissions(application_id, guild_id, command_id) ) |> handle_request_with_decode end @doc """ Edits command permissions for a specific command for your application in a guild. You can only add up to 10 permission overwrites for a command. ## Parameters - `application_id`: Application ID commands are registered under. If not given, this will be fetched from `Me`. - `guild_id`: Guild ID to fetch command permissions from. - `command_id`: Command ID to fetch permissions for. - `permissions`: List of [application command permissions](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure) ## Return value This method returns a guild application command permission object, see all available values on the [Discord API docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure). """ @doc since: "0.5.0" @spec edit_application_command_permissions(Guild.id(), Snowflake.t(), [ ApplicationCommand.application_command_permissions() ]) :: {:ok, map()} | error @spec edit_application_command_permissions(User.id(), Guild.id(), Snowflake.t(), [ ApplicationCommand.application_command_permissions() ]) :: {:ok, map()} | error def edit_application_command_permissions( application_id \\ Me.get().id, guild_id, command_id, permissions ) do request( :put, Constants.guild_application_command_permissions(application_id, guild_id, command_id), %{ permissions: permissions } ) |> handle_request_with_decode end @doc """ Edits command permissions for a specific command for your application in a guild. You can only add up to 10 permission overwrites for a command. ## Parameters - `application_id`: Application ID commands are registered under. If not given, this will be fetched from `Me`. - `guild_id`: Guild ID to fetch command permissions from. - `command_id`: Command ID to fetch permissions for. - `permissions`: List of partial [guild application command permissions](hhttps://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure) with `id` and `permissions`. You can add up to 10 overwrites per command. ## Return value This method returns a guild application command permission object, see all available values on the [Discord API docs](https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure). """ @doc since: "0.5.0" @spec batch_edit_application_command_permissions(Guild.id(), [ %{ id: Snowflake.t(), permissions: [ApplicationCommand.application_command_permissions()] } ]) :: {:ok, map()} | error @spec batch_edit_application_command_permissions(User.id(), Guild.id(), [ %{ id: Snowflake.t(), permissions: [ApplicationCommand.application_command_permissions()] } ]) :: {:ok, map()} | error def batch_edit_application_command_permissions( application_id \\ Me.get().id, guild_id, permissions ) do request( :put, Constants.guild_application_command_permissions(application_id, guild_id), permissions ) |> handle_request_with_decode end @spec maybe_add_reason(String.t() | nil) :: list() defp maybe_add_reason(reason) do maybe_add_reason(reason, [{"content-type", "application/json"}]) end @spec maybe_add_reason(String.t() | nil, list()) :: list() defp maybe_add_reason(nil, headers) do headers end defp maybe_add_reason(reason, headers) do [{"x-audit-log-reason", reason} | headers] end @spec request(map()) :: {:ok} | {:ok, String.t()} | error def request(request) do GenServer.call(Ratelimiter, {:queue, request, nil}, :infinity) end @spec request(atom(), String.t(), any, keyword() | map()) :: {:ok} | {:ok, String.t()} | error def request(method, route, body \\ "", params \\ []) do request = %{ method: method, route: route, body: body, params: params, headers: [{"content-type", "application/json"}] } GenServer.call(Ratelimiter, {:queue, request, nil}, :infinity) end @spec request_multipart(atom(), String.t(), any, keyword() | map()) :: {:ok} | error def request_multipart(method, route, body, params \\ []) do boundary = generate_boundary() request = %{ method: method, route: route, # Hello :gun test suite :^) body: create_multipart(body, boundary), params: params, headers: [ {"content-type", "multipart/form-data; boundary=#{boundary}"} ] } GenServer.call(Ratelimiter, {:queue, request, nil}, :infinity) end @doc false def bangify(to_bang) do case to_bang do {:error, error} -> raise(error) {:ok, body} -> body {:ok} -> {:ok} end end @doc """ Returns the token of the bot. """ @spec get_token() :: String.t() def get_token do Application.get_env(:nostrum, :token) end defp handle_request_with_decode(response) defp handle_request_with_decode({:ok, body}), do: {:ok, Jason.decode!(body, keys: :atoms)} defp handle_request_with_decode({:error, _} = error), do: error defp handle_request_with_decode(response, type) # add_guild_member/3 can return both a 201 and a 204 defp handle_request_with_decode({:ok}, _type), do: {:ok} defp handle_request_with_decode({:error, _} = error, _type), do: error defp handle_request_with_decode({:ok, body}, type) do convert = body |> Jason.decode!(keys: :atoms) |> Util.cast(type) {:ok, convert} end defp prepare_allowed_mentions(options) do with raw_options when raw_options != :all <- Map.get(options, :allowed_mentions, :all), allowed_mentions when is_map(allowed_mentions) <- parse_allowed_mentions(raw_options) do Map.put(options, :allowed_mentions, allowed_mentions) else _ -> Map.delete(options, :allowed_mentions) end end defp create_multipart(files, json, boundary) do {:multipart, create_multipart_body(files, json, boundary)} end defp create_multipart(options, boundary) do {:multipart, create_multipart_body(options, boundary)} end @crlf "\r\n" defp create_multipart_body(files, json, boundary) do json_mime = MIME.type("json") json_size = :erlang.iolist_size(json) file_parts = files |> Enum.with_index(1) |> Enum.reduce([~s|--#{boundary}#{@crlf}|], fn {f, i}, acc -> [ acc | [ create_file_part_for_multipart(f, i), ~s|#{@crlf}--#{boundary}#{@crlf}| ] ] end) [ file_parts | [ ~s|content-length: #{json_size}#{@crlf}|, ~s|content-type: #{json_mime}#{@crlf}|, ~s|content-disposition: form-data; name="payload_json"#{@crlf}#{@crlf}|, json, ~s|#{@crlf}--#{boundary}--#{@crlf}| ] ] end defp create_multipart_body(%{content: content, tts: tts, file: file}, boundary) do file_mime = MIME.from_path(file) file_size = byte_size(content) tts_mime = MIME.type("") tts_size = byte_size(tts) [ ~s|--#{boundary}#{@crlf}|, ~s|content-length: #{file_size}#{@crlf}|, ~s|content-type: #{file_mime}#{@crlf}|, ~s|content-disposition: form-data; name="file"; filename="#{file}"#{@crlf}#{@crlf}|, content, ~s|#{@crlf}--#{boundary}#{@crlf}|, ~s|content-length: #{tts_size}#{@crlf}|, ~s|content-type: #{tts_mime}#{@crlf}|, ~s|content-disposition: form-data; name="tts"#{@crlf}#{@crlf}|, tts, ~s|#{@crlf}--#{boundary}--#{@crlf}| ] end def create_file_part_for_multipart(file, index) do {body, name} = get_file_contents(file) file_mime = MIME.from_path(name) file_size = byte_size(body) [ ~s|content-length: #{file_size}#{@crlf}|, ~s|content-type: #{file_mime}#{@crlf}|, ~s|content-disposition: form-data; name="file#{index}"; filename="#{name}"#{@crlf}#{@crlf}|, body ] end defp get_file_contents(path) when is_binary(path) do {File.read!(path), Path.basename(path)} end defp get_file_contents(%{body: body, name: name}), do: {body, name} defp generate_boundary do String.duplicate("-", 20) <> "KraigieNostrumCat_" <> Base.encode16(:crypto.strong_rand_bytes(10)) end defp parse_allowed_mentions(:none), do: %{parse: []} defp parse_allowed_mentions(:everyone), do: %{parse: [:everyone]} # Parse users defp parse_allowed_mentions(:users), do: %{parse: [:users]} defp parse_allowed_mentions({:users, users}) when is_list(users), do: %{users: users} # Parse roles defp parse_allowed_mentions(:roles), do: %{parse: [:roles]} defp parse_allowed_mentions({:roles, roles}) when is_list(roles), do: %{roles: roles} # Parse many defp parse_allowed_mentions(options) when is_list(options) or is_map(options) do options |> Enum.map(&parse_allowed_mentions/1) |> Enum.reduce(fn a, b -> Map.merge(a, b, fn key, parse_a, parse_b when key in [:parse, :users, :roles] -> Enum.uniq(parse_a ++ parse_b) _k, _v1, v2 -> v2 end) end) |> Map.put_new(:parse, []) end # ignore defp parse_allowed_mentions(options), do: options @spec maybe_convert_date_time(map(), atom()) :: map() defp maybe_convert_date_time(options, key) do case options do %{^key => %DateTime{} = date_time} -> timestamp = DateTime.to_iso8601(date_time) %{options | key => timestamp} _ -> options end end end
33.858314
307
0.682676
797563b8a4048052fbc6d1db9d62f8df7f03ab8e
869
ex
Elixir
lib/order_api/buyer.ex
gissandrogama/delivery_order
8642453b03f590fe828225fc13aa58a5f79b2117
[ "MIT" ]
null
null
null
lib/order_api/buyer.ex
gissandrogama/delivery_order
8642453b03f590fe828225fc13aa58a5f79b2117
[ "MIT" ]
6
2021-01-22T15:23:04.000Z
2021-01-28T07:56:01.000Z
lib/order_api/buyer.ex
gissandrogama/delivery_order
8642453b03f590fe828225fc13aa58a5f79b2117
[ "MIT" ]
null
null
null
defmodule OrderApi.Buyer do @moduledoc """ table bank schema buyers """ use Ecto.Schema import Ecto.Changeset alias OrderApi.{BillingInfos, Order, Phone} schema "buyers" do field :email, :string field :external_code, :integer field :first_name, :string field :last_name, :string field :nickname, :string has_many :phones, Phone has_many :orders, Order has_one :billing_infos, BillingInfos timestamps() end @doc false def changeset(buyer, attrs) do buyer |> cast(attrs, [:last_name, :first_name, :external_code, :email, :nickname]) |> cast_assoc(:phones, with: &Phone.changeset/2) |> cast_assoc(:billing_infos, with: &BillingInfos.changeset/2) |> cast_assoc(:orders, with: &Order.changeset/2) |> validate_required([:last_name, :first_name, :external_code, :email, :nickname]) end end
26.333333
86
0.686997
79756ba80249b18dd159669b1d53af717ed0c802
592
exs
Elixir
test/bus_kiosk_web/live/kiosk_live_test.exs
mitchellhenke/bus_kiosk
9814b0b10190bb06c823b00315616391100c5bfa
[ "BSD-3-Clause" ]
2
2020-02-21T15:40:27.000Z
2020-12-06T21:50:39.000Z
test/bus_kiosk_web/live/kiosk_live_test.exs
mitchellhenke/bus_kiosk
9814b0b10190bb06c823b00315616391100c5bfa
[ "BSD-3-Clause" ]
3
2020-02-19T17:06:24.000Z
2020-04-20T14:33:07.000Z
test/bus_kiosk_web/live/kiosk_live_test.exs
mitchellhenke/bus_kiosk
9814b0b10190bb06c823b00315616391100c5bfa
[ "BSD-3-Clause" ]
null
null
null
defmodule BusKioskWeb.KioskLiveTest do use BusKioskWeb.ConnCase import Phoenix.LiveViewTest @endpoint BusKioskWeb.Endpoint test "GET /live with no parameters shows error", %{conn: conn} do conn = get(conn, "/live") assert html_response(conn, 200) =~ "Oops" {:ok, _view, _html} = live(conn) end test "GET /live with parameters renders some stuff", %{conn: conn} do conn = get(conn, "/live", stop_ids: "123456,987654") assert html_response(conn, 200) =~ "123456" assert html_response(conn, 200) =~ "987654" {:ok, _view, _html} = live(conn) end end
28.190476
71
0.675676
7975722527c1948c724ba8dd359b92b5d69afef5
9,137
exs
Elixir
test/queuetopia/queue/job_test.exs
annatel/queuetopia
dd4be7390382c203821ab88388f0c31ba5538edf
[ "MIT" ]
7
2020-08-06T21:58:13.000Z
2021-08-07T18:32:44.000Z
test/queuetopia/queue/job_test.exs
annatel/queuetopia
dd4be7390382c203821ab88388f0c31ba5538edf
[ "MIT" ]
2
2020-10-22T11:53:45.000Z
2021-06-22T05:45:27.000Z
test/queuetopia/queue/job_test.exs
annatel/queuetopia
dd4be7390382c203821ab88388f0c31ba5538edf
[ "MIT" ]
2
2020-11-04T00:23:43.000Z
2021-04-30T07:25:01.000Z
defmodule Queuetopia.Queue.JobTest do use Queuetopia.DataCase alias Queuetopia.Queue.Job describe "create_changeset/2" do test "only permitted_keys are casted" do params = Factory.params_for(:job, timeout: 100, max_backoff: 100, max_attempts: 1 ) changeset = Job.create_changeset(Map.merge(params, %{new_key: "value"})) changes_keys = changeset.changes |> Map.keys() assert :sequence in changes_keys assert :scope in changes_keys assert :queue in changes_keys assert :performer in changes_keys assert :action in changes_keys assert :params in changes_keys assert :timeout in changes_keys assert :max_backoff in changes_keys assert :max_attempts in changes_keys assert :scheduled_at in changes_keys refute :new_key in changes_keys assert Enum.count(changes_keys) == 10 assert changeset.valid? end test "timing params default values" do params = Factory.params_for(:job, timeout: nil, max_backoff: nil, max_attempts: nil ) changeset = Job.create_changeset(Map.merge(params, %{new_key: "value"})) assert Ecto.Changeset.get_field(changeset, :timeout) == Job.default_timeout() assert Ecto.Changeset.get_field(changeset, :max_backoff) == Job.default_max_backoff() assert Ecto.Changeset.get_field(changeset, :max_attempts) == Job.default_max_attempts() assert changeset.valid? end test "when required params are missing, returns an invalid changeset" do changeset = Job.create_changeset(%{timeout: nil, max_backoff: nil, max_attempts: nil}) refute changeset.valid? assert %{sequence: ["can't be blank"]} = errors_on(changeset) assert %{scope: ["can't be blank"]} = errors_on(changeset) assert %{queue: ["can't be blank"]} = errors_on(changeset) assert %{performer: ["can't be blank"]} = errors_on(changeset) assert %{action: ["can't be blank"]} = errors_on(changeset) assert %{params: ["can't be blank"]} = errors_on(changeset) assert %{scheduled_at: ["can't be blank"]} = errors_on(changeset) assert %{timeout: ["can't be blank"]} = errors_on(changeset) assert %{max_backoff: ["can't be blank"]} = errors_on(changeset) assert %{max_attempts: ["can't be blank"]} = errors_on(changeset) end test "when timing params are lesser than or equal to 0 are not valid, return a invalid changeset" do params = Factory.params_for(:job, timeout: -1, max_backoff: -1, max_attempts: -1 ) changeset = Job.create_changeset(params) refute changeset.valid? assert %{timeout: ["must be greater than or equal to 0"]} = errors_on(changeset) assert %{max_backoff: ["must be greater than or equal to 0"]} = errors_on(changeset) assert %{max_attempts: ["must be greater than or equal to 0"]} = errors_on(changeset) end test "when timing params are not valid, return a invalid changeset" do params = Factory.params_for(:job, timeout: 0.4, max_backoff: 0.4, max_attempts: 0.4 ) changeset = Job.create_changeset(params) refute changeset.valid? assert %{timeout: ["is invalid"]} = errors_on(changeset) assert %{max_backoff: ["is invalid"]} = errors_on(changeset) assert %{max_attempts: ["is invalid"]} = errors_on(changeset) end test "when params are valid, return a valid changeset" do params = Factory.params_for(:job, timeout: 100, max_backoff: 100, max_attempts: 1 ) changeset = Job.create_changeset(params) assert changeset.valid? assert get_field(changeset, :queue) == params.queue assert get_field(changeset, :scope) == params.scope assert get_field(changeset, :performer) == params.performer assert get_field(changeset, :action) == params.action assert get_field(changeset, :params) == params.params assert get_field(changeset, :timeout) == params.timeout assert get_field(changeset, :max_backoff) == params.max_backoff assert get_field(changeset, :max_attempts) == params.max_attempts end end describe "failed_job_changeset/2" do test "only permitted_keys are casted" do job = Factory.insert!(:job) params = Factory.params_for(:job, attempts: 6, attempted_at: Factory.utc_now(), attempted_by: Atom.to_string(Node.self()), next_attempt_at: Factory.utc_now(), error: "error" ) changeset = Job.failed_job_changeset(job, Map.merge(params, %{new_key: "value"})) changes_keys = changeset.changes |> Map.keys() assert :attempts in changes_keys assert :attempted_at in changes_keys assert :attempted_by in changes_keys assert :next_attempt_at in changes_keys assert :error in changes_keys assert Enum.count(changes_keys) == 5 refute :new_key in changes_keys end test "when required params are missing, returns an invalid changeset" do job = Factory.insert!(:job) changeset = Job.failed_job_changeset(job, %{attempts: nil, scheduled_at: nil}) refute changeset.valid? assert %{attempts: ["can't be blank"]} = errors_on(changeset) assert %{attempted_at: ["can't be blank"]} = errors_on(changeset) assert %{attempted_by: ["can't be blank"]} = errors_on(changeset) assert %{next_attempt_at: ["can't be blank"]} = errors_on(changeset) assert %{error: ["can't be blank"]} = errors_on(changeset) end test "when params are valid, return a valid changeset" do utc_now = Factory.utc_now() job = Factory.insert!(:job) changeset = Job.failed_job_changeset(job, %{ attempts: 1, attempted_at: utc_now, attempted_by: Atom.to_string(Node.self()), next_attempt_at: utc_now, error: "error" }) assert changeset.valid? end end describe "succeeded_job_changeset/2" do test "only permitted_keys are casted" do job = Factory.insert!(:job) params = Factory.params_for(:job, attempts: 6, attempted_at: Factory.utc_now(), attempted_by: Atom.to_string(Node.self()), done_at: Factory.utc_now() ) changeset = Job.succeeded_job_changeset(job, Map.merge(params, %{new_key: "value"})) changes_keys = changeset.changes |> Map.keys() assert :attempts in changes_keys assert :attempted_at in changes_keys assert :attempted_by in changes_keys assert :done_at in changes_keys assert Enum.count(changes_keys) == 4 refute :new_key in changes_keys end test "when required params are missing, returns an invalid changeset" do job = Factory.insert!(:job) changeset = Job.succeeded_job_changeset(job, %{attempts: nil}) refute changeset.valid? assert %{attempts: ["can't be blank"]} = errors_on(changeset) assert %{attempted_at: ["can't be blank"]} = errors_on(changeset) assert %{attempted_by: ["can't be blank"]} = errors_on(changeset) assert %{done_at: ["can't be blank"]} = errors_on(changeset) end test "nillifies error field" do job = Factory.insert!(:job, error: "error") params = Factory.params_for(:job, attempts: 6, attempted_at: Factory.utc_now(), attempted_by: Atom.to_string(Node.self()), done_at: Factory.utc_now() ) changeset = Job.succeeded_job_changeset(job, params) assert is_nil(changeset.changes.error) end test "when params are valid, return a valid changeset" do utc_now = Factory.utc_now() job = Factory.insert!(:job) changeset = Job.succeeded_job_changeset(job, %{ attempts: 1, attempted_at: utc_now, attempted_by: Atom.to_string(Node.self()), done_at: utc_now }) assert changeset.valid? end end test "email_subject/1" do job = Factory.insert!(:job) assert Job.email_subject(job) == "[#{job.scope} #{job.queue} job failure]" end test "email_html_body/1" do job = Factory.insert!(:job) assert Job.email_html_body(job) == """ ==============================<br/> Hi,<br/> <br/> Here is a report about a failed job <br/> <br/> <b>Queue:</b> #{job.scope} #{job.queue}<br/> <br/> <br/> <b>Action:</b> #{job.action}<br/> <b>Params:</b> <pre> #{job.params |> Jason.encode!(pretty: true)} </pre> <br/> <b>Attempts:</b> #{job.attempts} <b>Next attempt at:</b> #{job.next_attempt_at} <br/> <b>Please, fix the failure in order to unlock the queue.</b> <br/> ============================== """ end end
32.400709
104
0.618365
7975c9ca21d4d45f599633c2b3a8055349df91bb
425
ex
Elixir
test/support/mock_storage.ex
capsule-ex/capsule
2ffcdf5f0c4f7596af392aad56f2da6913eda9bf
[ "Apache-2.0" ]
null
null
null
test/support/mock_storage.ex
capsule-ex/capsule
2ffcdf5f0c4f7596af392aad56f2da6913eda9bf
[ "Apache-2.0" ]
null
null
null
test/support/mock_storage.ex
capsule-ex/capsule
2ffcdf5f0c4f7596af392aad56f2da6913eda9bf
[ "Apache-2.0" ]
null
null
null
defmodule Capsule.Storages.Mock do alias Capsule.{Storage, Encapsulation} @behaviour Storage @impl Storage def put(_upload, opts \\ []) do encapsulation = %Encapsulation{id: opts[:id], storage: __MODULE__} {:ok, encapsulation} end @impl Storage def delete(%Encapsulation{}, _opts \\ []), do: {:ok, nil} @impl Storage def read(%Encapsulation{}, _opts \\ []), do: {:ok, "mock file contents"} end
22.368421
74
0.661176
7975e0c451ce304894f8032f4b817337ea47e078
609
exs
Elixir
test/cybersource_sdk_test.exs
CrazyEggInc/cybersource-sdk-1
14251e681752a055e941d01186b23acddbddcdb0
[ "MIT" ]
null
null
null
test/cybersource_sdk_test.exs
CrazyEggInc/cybersource-sdk-1
14251e681752a055e941d01186b23acddbddcdb0
[ "MIT" ]
null
null
null
test/cybersource_sdk_test.exs
CrazyEggInc/cybersource-sdk-1
14251e681752a055e941d01186b23acddbddcdb0
[ "MIT" ]
1
2020-02-24T14:54:00.000Z
2020-02-24T14:54:00.000Z
defmodule CyberSourceSDKTest do use ExUnit.Case, async: true doctest CyberSourceSDK doctest CyberSourceSDK.Helper test "Test bill_to generated parameters" do expected_parameters = [ first_name: "John", last_name: "Doe", street1: "Maryland Street", street2: "34", city: "New York", post_code: "12345", state: "NY", country: "USA", email: "[email protected]" ] parameters = CyberSourceSDK.bill_to("John", "Doe", "Maryland Street", "34", "New York", "12345", "NY", "USA", "[email protected]") assert expected_parameters == parameters end end
25.375
131
0.651888
7975ecd01ab8a7442d0c52f41e19dacfd9a34927
1,123
ex
Elixir
lib/livebook_web/live/settings_live/remove_file_system_component.ex
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/settings_live/remove_file_system_component.ex
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/settings_live/remove_file_system_component.ex
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
1
2021-12-18T03:42:04.000Z
2021-12-18T03:42:04.000Z
defmodule LivebookWeb.SettingsLive.RemoveFileSystemComponent do use LivebookWeb, :live_component @impl true def render(assigns) do ~H""" <div class="p-6 pb-4 flex flex-col space-y-8"> <h3 class="text-2xl font-semibold text-gray-800"> Detach file system </h3> <p class="text-gray-700"> Are you sure you want to detach this file system? Any sessions using it will keep the access until they get closed. </p> <div class="mt-8 flex justify-end space-x-2"> <button class="button button-red" phx-click="detach" phx-target={@myself}> <.remix_icon icon="close-circle-line" class="align-middle mr-1" /> Detach </button> <%= live_patch "Cancel", to: @return_to, class: "button button-outlined-gray" %> </div> </div> """ end @impl true def handle_event("detach", %{}, socket) do file_systems = Livebook.Config.remove_file_system(socket.assigns.file_system) send(self(), {:file_systems_updated, file_systems}) {:noreply, push_patch(socket, to: socket.assigns.return_to)} end end
33.029412
88
0.64114
7975f8cfe534255061872f7405fa33c78b78406c
1,152
exs
Elixir
rel/config.exs
dariodf/GuitarBotex
a8e4d9244dca7e90fedbb0db9c7376a156d220db
[ "MIT" ]
1
2018-07-26T00:59:45.000Z
2018-07-26T00:59:45.000Z
rel/config.exs
dariodf/GuitarBotex
a8e4d9244dca7e90fedbb0db9c7376a156d220db
[ "MIT" ]
null
null
null
rel/config.exs
dariodf/GuitarBotex
a8e4d9244dca7e90fedbb0db9c7376a156d220db
[ "MIT" ]
null
null
null
use Mix.Releases.Config, # This sets the default release built by `mix release` default_release: :default, # This sets the default environment used by `mix release` default_environment: :dev # For a full list of config options for both releases # and environments, visit https://hexdocs.pm/distillery/configuration.html # You may define one or more environments in this file, # an environment's settings will override those of a release # when building in that environment, this combination of release # and environment configuration is called a profile environment :dev do set dev_mode: true set include_erts: false set cookie: :"k~ZU&cMyn3085Vj<!5VCjTAkkGCs0/fln(u]qiEcnbBxg?i5xZ9wS4`2_JbH6t=2" end environment :prod do set include_erts: true set include_src: false set cookie: :"tH>]<RO^9zf^YHX*B7,N!fh>9Yvo87i2IZl!u{196q,J}*!mv)Y{tSV{?~(w*zKN" end # You may define one or more releases in this file. # If you have not set a default release, or selected one # when running `mix release`, the first release in the file # will be used by default release :guitarbot do set version: current_version(:guitarbot) end
31.135135
81
0.75434
797603335287bb697b87233de2681dd2341c16a0
212
ex
Elixir
lib/blog_api/accounts/encryption.ex
vbrazo/blog_api
8a3e15c666beef8f33b6d323627f92379267ecd9
[ "MIT" ]
null
null
null
lib/blog_api/accounts/encryption.ex
vbrazo/blog_api
8a3e15c666beef8f33b6d323627f92379267ecd9
[ "MIT" ]
null
null
null
lib/blog_api/accounts/encryption.ex
vbrazo/blog_api
8a3e15c666beef8f33b6d323627f92379267ecd9
[ "MIT" ]
null
null
null
defmodule BlogApi.Accounts.Encryption do alias Comeonin.Bcrypt def password_hashing(password), do: Bcrypt.hashpwsalt(password) def validate_password(password, hash), do: Bcrypt.checkpw(password, hash) end
30.285714
75
0.801887
797606f96cd13df0af7bb554a641c6f32f2c9ccb
2,462
ex
Elixir
test/process_managers/support/error/error_aggregate.ex
mquickform/commanded
260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2
[ "MIT" ]
null
null
null
test/process_managers/support/error/error_aggregate.ex
mquickform/commanded
260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2
[ "MIT" ]
1
2018-12-05T18:17:08.000Z
2018-12-05T18:17:08.000Z
test/process_managers/support/error/error_aggregate.ex
mquickform/commanded
260b1ec28c2fb3c1fcbb61b8c4abacabd7dc7ed2
[ "MIT" ]
1
2018-12-05T18:15:03.000Z
2018-12-05T18:15:03.000Z
defmodule Commanded.ProcessManagers.ErrorAggregate do @moduledoc false defstruct [:process_uuid] defmodule Commands do defmodule(StartProcess, do: defstruct([:process_uuid, :strategy, :delay, :reply_to])) defmodule(RaiseError, do: defstruct([:process_uuid, :message, :reply_to])) defmodule(RaiseException, do: defstruct([:process_uuid, :message, :reply_to])) defmodule(AttemptProcess, do: defstruct([:process_uuid, :strategy, :delay, :reply_to])) defmodule(ContinueProcess, do: defstruct([:process_uuid, :reply_to])) end defmodule Events do defmodule(ProcessStarted, do: defstruct([:process_uuid, :strategy, :delay, :reply_to])) defmodule(ProcessContinued, do: defstruct([:process_uuid, :reply_to])) defmodule(ProcessError, do: defstruct([:process_uuid, :message, :reply_to])) defmodule(ProcessException, do: defstruct([:process_uuid, :message, :reply_to])) end alias Commanded.ProcessManagers.ErrorAggregate alias Commands.{AttemptProcess, ContinueProcess, RaiseError, RaiseException, StartProcess} alias Events.{ProcessContinued, ProcessError, ProcessException, ProcessStarted} def execute(%ErrorAggregate{}, %StartProcess{} = command) do %StartProcess{ process_uuid: process_uuid, strategy: strategy, delay: delay, reply_to: reply_to } = command %ProcessStarted{ process_uuid: process_uuid, strategy: strategy, delay: delay, reply_to: reply_to } end def execute(%ErrorAggregate{}, %RaiseError{} = command) do %RaiseError{process_uuid: process_uuid, message: message, reply_to: reply_to} = command %ProcessError{process_uuid: process_uuid, message: message, reply_to: reply_to} end def execute(%ErrorAggregate{}, %RaiseException{} = command) do %RaiseException{process_uuid: process_uuid, message: message, reply_to: reply_to} = command %ProcessException{process_uuid: process_uuid, message: message, reply_to: reply_to} end def execute(%ErrorAggregate{}, %AttemptProcess{}), do: {:error, :failed} def execute(%ErrorAggregate{}, %ContinueProcess{process_uuid: process_uuid, reply_to: reply_to}), do: %ProcessContinued{process_uuid: process_uuid, reply_to: reply_to} def apply(%ErrorAggregate{} = aggregate, %ProcessStarted{process_uuid: process_uuid}), do: %ErrorAggregate{aggregate | process_uuid: process_uuid} def apply(%ErrorAggregate{} = aggregate, _event), do: aggregate end
39.079365
99
0.736799
797617f0a9f5aceb66a59853e87685fa4ef710a6
3,222
ex
Elixir
apps/ello_core/lib/ello_core/network/user/settings.ex
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
16
2017-06-21T21:31:20.000Z
2021-05-09T03:23:26.000Z
apps/ello_core/lib/ello_core/network/user/settings.ex
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
25
2017-06-07T12:18:28.000Z
2018-06-08T13:27:43.000Z
apps/ello_core/lib/ello_core/network/user/settings.ex
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
3
2018-06-14T15:34:07.000Z
2022-02-28T21:06:13.000Z
defmodule Ello.Core.Network.User.Settings do use Ecto.Schema # A required field for all embedded documents, shouldn't be an interop issue @primary_key {:id, :binary_id, autogenerate: true} schema "" do field :is_public, :boolean, default: true field :is_hireable, :boolean, default: false field :is_collaborateable, :boolean, default: false field :is_brand, :boolean, default: false field :discoverable, :boolean, default: true # NSFW content (porn) field :posts_adult_content, :boolean, default: false field :views_adult_content, :boolean, default: false # Nudity content (artistic nudity) field :posts_nudity, :boolean, default: false # Enabled features field :has_commenting_enabled, :boolean, default: true field :has_loves_enabled, :boolean, default: true field :has_sharing_enabled, :boolean, default: true field :has_reposting_enabled, :boolean, default: true field :has_ad_notifications_enabled, :boolean, default: false field :has_auto_watch_enabled, :boolean, default: true field :has_announcements_enabled, :boolean, default: true # email notification field :notify_of_mentions_via_email, :boolean, default: true field :notify_of_new_followers_via_email, :boolean, default: true field :notify_of_comments_via_email, :boolean, default: true field :notify_of_comments_on_post_watch_via_email, :boolean, default: true field :notify_of_loves_via_email, :boolean, default: true field :notify_of_invitation_acceptances_via_email, :boolean, default: true field :notify_of_reposts_via_email, :boolean, default: true field :notify_of_watches_via_email, :boolean, default: true # push notifications field :notify_of_mentions_via_push, :boolean, default: true field :notify_of_new_followers_via_push, :boolean, default: true field :notify_of_comments_via_push, :boolean, default: true field :notify_of_comments_on_post_watch_via_push, :boolean, default: true field :notify_of_loves_via_push, :boolean, default: true field :notify_of_invitation_acceptances_via_push, :boolean, default: true field :notify_of_reposts_via_push, :boolean, default: true field :notify_of_watches_via_push, :boolean, default: true field :notify_of_announcements_via_push, :boolean, default: true field :notify_of_approved_submissions_from_following_via_email, :boolean, default: true field :notify_of_approved_submissions_via_push, :boolean, default: true field :notify_of_featured_category_post_via_email, :boolean, default: true field :notify_of_featured_category_post_via_push, :boolean, default: true field :notify_of_approved_submissions_from_following_via_push, :boolean, default: true field :notify_of_what_you_missed_via_email, :boolean, default: true # misc field :allows_analytics, :boolean, default: true # Product Updates field :subscribe_to_users_email_list, :boolean, default: true # Knowtify Tops & Tricks field :subscribe_to_onboarding_drip, :boolean, default: true # Newsletters field :subscribe_to_weekly_ello, :boolean, default: true field :subscribe_to_daily_ello, :boolean, default: true end end
46.028571
91
0.767846
79761b6c724018d6f0fc4f0d56cf0058a4609555
3,422
ex
Elixir
clients/file/lib/google_api/file/v1/model/network_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/file/lib/google_api/file/v1/model/network_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/file/lib/google_api/file/v1/model/network_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.File.V1.Model.NetworkConfig do @moduledoc """ Network configuration for the instance. ## Attributes * `connectMode` (*type:* `String.t`, *default:* `nil`) - The network connect mode of the Filestore instance. If not provided, the connect mode defaults to DIRECT_PEERING. * `ipAddresses` (*type:* `list(String.t)`, *default:* `nil`) - Output only. IPv4 addresses in the format `{octet1}.{octet2}.{octet3}.{octet4}` or IPv6 addresses in the format `{block1}:{block2}:{block3}:{block4}:{block5}:{block6}:{block7}:{block8}`. * `modes` (*type:* `list(String.t)`, *default:* `nil`) - Internet protocol versions for which the instance has IP addresses assigned. For this version, only MODE_IPV4 is supported. * `network` (*type:* `String.t`, *default:* `nil`) - The name of the Google Compute Engine [VPC network](https://cloud.google.com/vpc/docs/vpc) to which the instance is connected. * `reservedIpRange` (*type:* `String.t`, *default:* `nil`) - Optional, reserved_ip_range can have one of the following two types of values. * CIDR range value when using DIRECT_PEERING connect mode. * [Allocated IP address range](https://cloud.google.com/compute/docs/ip-addresses/reserve-static-internal-ip-address) when using PRIVATE_SERVICE_ACCESS connect mode. When the name of an allocated IP address range is specified, it must be one of the ranges associated with the private service access connection. When specified as a direct CIDR value, it must be a /29 CIDR block for Basic tier or a /24 CIDR block for High Scale or Enterprise tier in one of the [internal IP address ranges](https://www.arin.net/reference/research/statistics/address_filters/) that identifies the range of IP addresses reserved for this instance. For example, 10.0.0.0/29 or 192.168.0.0/24. The range you specify can't overlap with either existing subnets or assigned IP address ranges for other Cloud Filestore instances in the selected VPC network. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :connectMode => String.t() | nil, :ipAddresses => list(String.t()) | nil, :modes => list(String.t()) | nil, :network => String.t() | nil, :reservedIpRange => String.t() | nil } field(:connectMode) field(:ipAddresses, type: :list) field(:modes, type: :list) field(:network) field(:reservedIpRange) end defimpl Poison.Decoder, for: GoogleApi.File.V1.Model.NetworkConfig do def decode(value, options) do GoogleApi.File.V1.Model.NetworkConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.File.V1.Model.NetworkConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
58
1,035
0.728521
79762a9f77be187941bc78cd2762d130a08ed1cd
7,793
ex
Elixir
lib/rbmq/connection/helper.ex
Lean5/rbmq
c6e746c212e103fc4ada53969e88fc1f32a357a6
[ "MIT" ]
null
null
null
lib/rbmq/connection/helper.ex
Lean5/rbmq
c6e746c212e103fc4ada53969e88fc1f32a357a6
[ "MIT" ]
1
2019-02-13T14:26:22.000Z
2019-02-13T14:26:22.000Z
lib/rbmq/connection/helper.ex
Lean5/rbmq
c6e746c212e103fc4ada53969e88fc1f32a357a6
[ "MIT" ]
null
null
null
defmodule RBMQ.Connection.Helper do @moduledoc """ Helper functions to manage connections with AMQP. This module produces verbose debug logs. """ use AMQP require Logger # Default settings for AMQP connection. @defaults [ host: {:system, "AMQP_HOST", "localhost"}, port: {:system, :integer, "AMQP_PORT", 5672}, username: {:system, "AMQP_USER", "guest"}, password: {:system, "AMQP_PASSWORD", "guest"}, virtual_host: {:system, "AMQP_VHOST", "/"}, connection_timeout: {:system, :integer, "AMQP_TIMEOUT", 15_000}, ] @doc """ Open AMQP connection. # Options * `:username` - The name of a user registered with the broker (defaults to \"guest\"); * `:password` - The password of user (defaults to \"guest\"); * `:virtual_host` - The name of a virtual host in the broker (defaults to \"/\"); * `:host` - The hostname of the broker (defaults to \"localhost\"); * `:port` - The port the broker is listening on (defaults to `5672`); * `:channel_max` - The channel_max handshake parameter (defaults to `0`); * `:frame_max` - The frame_max handshake parameter (defaults to `0`); * `:heartbeat` - The hearbeat interval in seconds (defaults to `0` - turned off); * `:connection_timeout` - The connection timeout in milliseconds (defaults to `15_000`); * `:ssl_options` - Enable SSL by setting the location to cert files (defaults to `none`); * `:client_properties` - A list of extra client properties to be sent to the server, defaults to `[]`; * `:socket_options` - Extra socket options. These are appended to the default options. \ See http://www.erlang.org/doc/man/inet.html#setopts-2 \ and http://www.erlang.org/doc/man/gen_tcp.html#connect-4 \ for descriptions of the available options. See: https://hexdocs.pm/amqp/AMQP.Connection.html#open/1 """ def open_connection!(conn_opts) do case open_connection(conn_opts) do {:ok, %Connection{} = conn} -> conn {:error, message} -> raise message end end @doc """ Same as `open_connection!/1`, but returns {:ok, conn} or {:error, reason} tuples. """ def open_connection(conn_opts) do Logger.debug "Establishing new AMQP connection, with opts: #{inspect Keyword.put(conn_opts, :password, "*****")}" new_opts = @defaults |> Keyword.merge(conn_opts) |> env Logger.debug "Establishing new AMQP connection, with merged opts: #{inspect Keyword.put(new_opts, :password, "*****")}" conn = new_opts |> Connection.open case conn do {:ok, %Connection{}} = res -> res {:error, :not_allowed} -> Logger.error "AMQP refused connection, opts: #{inspect conn_opts}" {:error, "AMQP vhost not allowed"} {:error, :econnrefused} -> Logger.error "AMQP refused connection, opts: #{inspect conn_opts}" {:error, "AMQP connection was refused"} {:error, :timeout} -> Logger.error "AMQP connection timeout, opts: #{inspect conn_opts}" {:error, "AMQP connection timeout"} {:error, {:auth_failure, message}} -> Logger.error "AMQP authorization failed, opts: #{inspect conn_opts}" {:error, "AMQP authorization failed: #{inspect message}"} {:error, reason} -> Logger.error "Error during AMQP connection establishing, opts: #{inspect conn_opts}" {:error, inspect(reason)} end end @doc """ Open new AMQP channel inside a connection. See: https://hexdocs.pm/amqp/AMQP.Channel.html#open/1 """ def open_channel!(%Connection{} = conn) do case open_channel(conn) do {:ok, %Channel{} = chan} -> chan {:error, message} -> raise message end end @doc """ Same as `open_channel!/1`, but returns {:ok, conn} or {:error, reason} tuples. """ def open_channel(%Connection{} = conn) do Logger.debug "Opening new AMQP channel for conn #{inspect conn.pid}" case Process.alive?(conn.pid) do false -> {:error, :conn_dead} true -> _open_channel(conn) end end defp _open_channel(conn) do case Channel.open(conn) do {:ok, %Channel{} = chan} -> {:ok, chan} :closing -> Logger.debug "Channel is closing, retry.." :timer.sleep(1_000) open_channel(conn) {:error, reason} -> Logger.error "Can't create new AMQP channel" {:error, inspect(reason)} end end @doc """ Gracefully close AMQP channel. """ def close_channel(%Channel{} = chan) do Logger.debug "Closing AMQP channel" Channel.close(chan) end @doc """ Set channel QOS policy. Especially useful when you want to limit number of unacknowledged request per worker. # Options * `:prefetch_size` - Limit of unacknowledged messages (in bytes). * `:prefetch_count` - Limit of unacknowledged messages (count). * `:global` - If `global` is set to `true` this applies to the \ entire Connection, otherwise it applies only to the specified Channel. See: https://hexdocs.pm/amqp/AMQP.Basic.html#qos/2 """ def set_channel_qos(%Channel{} = chan, opts) do Logger.debug "Changing channel QOS to #{inspect opts}" Basic.qos(chan, env(opts)) chan end @doc """ Declare AMQP queue. You can omit `error_queue`, then dead letter queue won't be created. Dead letter queue is hardcoded to be durable. # Options * `:durable` - If set, keeps the Queue between restarts of the broker * `:auto-delete` - If set, deletes the Queue once all subscribers disconnect * `:exclusive` - If set, only one subscriber can consume from the Queue * `:passive` - If set, raises an error unless the queue already exists See: https://hexdocs.pm/amqp/AMQP.Queue.html#declare/3 """ def declare_queue(%Channel{} = chan, queue, error_queue, opts) when is_binary(error_queue) and error_queue != "" do Logger.debug "Declaring new queue '#{queue}' with dead letter queue '#{error_queue}'. Options: #{inspect opts}" opts = [arguments: [ {"x-dead-letter-exchange", :longstr, ""}, {"x-dead-letter-routing-key", :longstr, error_queue} ]] |> Keyword.merge(opts) |> env() Queue.declare(chan, env(error_queue), durable: true) Queue.declare(chan, env(queue), opts) chan end def declare_queue(%Channel{} = chan, queue, _, opts) do Logger.debug "Declaring new queue '#{queue}' without dead letter queue. Options: #{inspect opts}" Queue.declare(chan, env(queue), env(opts)) chan end @doc """ Declare AMQP exchange. Exchange is durable whenever queue is durable. # Types: * `:direct` - direct exchange. * `:fanout` - fanout exchange. * `:topic` - topic exchange. * `:headers` - headers exchange. See: https://hexdocs.pm/amqp/AMQP.Queue.html#declare/3 """ def declare_exchange(%Channel{} = chan, exchange, type \\ :direct, opts \\ []) do Logger.debug "Declaring new exchange '#{exchange}' of type '#{inspect type}'. Options: #{inspect opts}" Exchange.declare(chan, env(exchange), env(type), env(opts)) chan end @doc """ Bind AMQP queue to Exchange. See: https://hexdocs.pm/amqp/AMQP.Queue.html#bind/4 """ def bind_queue(%Channel{} = chan, queue, exchange, opts) do Logger.debug "Binding new queue '#{queue}' to exchange '#{exchange}'. Options: #{inspect opts}" queue = env(queue) exchange = env(exchange) opts = env(opts) case opts[:routing_key] |> List.wrap do [] -> [nil] keys -> keys end |> Enum.each(&Queue.bind(chan, queue, exchange, Keyword.merge(opts, routing_key: &1))) chan end defp env(var) do Confex.process_env(var) end end
33.446352
123
0.634672
79762d5ec7974c28570776363c97a18e339ee7f9
3,996
exs
Elixir
test/toy_robot/runner_test.exs
lowski/toy-robot
107e5c68c1ba0813be9efb3949f6fde348aaa05b
[ "MIT" ]
null
null
null
test/toy_robot/runner_test.exs
lowski/toy-robot
107e5c68c1ba0813be9efb3949f6fde348aaa05b
[ "MIT" ]
null
null
null
test/toy_robot/runner_test.exs
lowski/toy-robot
107e5c68c1ba0813be9efb3949f6fde348aaa05b
[ "MIT" ]
null
null
null
defmodule ToyRobot.RunnerTest do use ExUnit.Case, async: true alias ToyRobot.{Runner, Simulation} import ExUnit.CaptureIO doctest ToyRobot.Runner test "it handles a valid place command" do %Simulation{robot: robot} = Runner.run([{:place, %{east: 1, north: 2, facing: :north}}]) assert robot.east == 1 assert robot.north == 2 assert robot.facing == :north end test "it handles an invalid place command" do simulation = Runner.run([{:place, %{east: 10, north: 10, facing: :north}}]) assert simulation == nil end test "it ignores commands until a valid placement" do %Simulation{robot: robot} = Runner.run([ :move, {:place, %{east: 1, north: 2, facing: :north}} ]) assert robot.east == 1 assert robot.north == 2 assert robot.facing == :north end test "it handles a place + move command" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 1, north: 2, facing: :north}}, :move ]) assert robot.east == 1 assert robot.north == 3 assert robot.facing == :north end test "it handles a place + invalid move command" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 1, north: 4, facing: :north}}, :move ]) assert robot.east == 1 assert robot.north == 4 assert robot.facing == :north end test "it handles a place + turn_left command" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 1, north: 2, facing: :north}}, :turn_left ]) assert robot.east == 1 assert robot.north == 2 assert robot.facing == :west end test "it handles a place + turn_right command" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 1, north: 2, facing: :north}}, :turn_right ]) assert robot.east == 1 assert robot.north == 2 assert robot.facing == :east end test "it handles a place + uturn command" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 1, north: 2, facing: :north}}, :uturn ]) assert robot.east == 1 assert robot.north == 2 assert robot.facing == :south end test "it handles a place + report command" do output = capture_io(fn -> Runner.run([ {:place, %{east: 1, north: 2, facing: :north}}, :report ]) end) assert String.trim(output) == "The robot is at (1,2) and is facing NORTH" end test "it handles a place + invalid command" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 1, north: 2, facing: :north}}, {:invalid, "EXTERMINATE"} ]) assert robot.east == 1 assert robot.north == 2 assert robot.facing == :north end test "it prevents robot from moving outside of north boundary" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 0, north: 4, facing: :north}}, :move ]) assert robot.east == 0 assert robot.north == 4 assert robot.facing == :north end test "it prevents robot from moving outside of east boundary" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 4, north: 0, facing: :east}}, :move ]) assert robot.east == 4 assert robot.north == 0 assert robot.facing == :east end test "it prevents robot from moving outside of south boundary" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 0, north: 0, facing: :south}}, :move ]) assert robot.east == 0 assert robot.north == 0 assert robot.facing == :south end test "it prevents robot from moving outside of west boundary" do %Simulation{robot: robot} = Runner.run([ {:place, %{east: 0, north: 0, facing: :west}}, :move ]) assert robot.east == 0 assert robot.north == 0 assert robot.facing == :west end end
24.072289
92
0.579329
79765979d93c144de75acc6ca6107d525a59c91a
3,869
ex
Elixir
clients/text_to_speech/lib/google_api/text_to_speech/v1/model/audio_config.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/text_to_speech/lib/google_api/text_to_speech/v1/model/audio_config.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/text_to_speech/lib/google_api/text_to_speech/v1/model/audio_config.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.TextToSpeech.V1.Model.AudioConfig do @moduledoc """ Description of audio data to be synthesized. ## Attributes * `audioEncoding` (*type:* `String.t`, *default:* `nil`) - Required. The format of the audio byte stream. * `effectsProfileId` (*type:* `list(String.t)`, *default:* `nil`) - Optional. Input only. An identifier which selects 'audio effects' profiles that are applied on (post synthesized) text to speech. Effects are applied on top of each other in the order they are given. See [audio profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for current supported profile ids. * `pitch` (*type:* `float()`, *default:* `nil`) - Optional. Input only. Speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20 semitones from the original pitch. -20 means decrease 20 semitones from the original pitch. * `sampleRateHertz` (*type:* `integer()`, *default:* `nil`) - Optional. The synthesis sample rate (in hertz) for this audio. When this is specified in SynthesizeSpeechRequest, if this is different from the voice's natural sample rate, then the synthesizer will honor this request by converting to the desired sample rate (which might result in worse audio quality), unless the specified sample rate is not supported for the encoding chosen, in which case it will fail the request and return google.rpc.Code.INVALID_ARGUMENT. * `speakingRate` (*type:* `float()`, *default:* `nil`) - Optional. Input only. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 is the normal native speed supported by the specific voice. 2.0 is twice as fast, and 0.5 is half as fast. If unset(0.0), defaults to the native 1.0 speed. Any other values < 0.25 or > 4.0 will return an error. * `volumeGainDb` (*type:* `float()`, *default:* `nil`) - Optional. Input only. Volume gain (in dB) of the normal native volume supported by the specific voice, in the range [-96.0, 16.0]. If unset, or set to a value of 0.0 (dB), will play at normal native signal amplitude. A value of -6.0 (dB) will play at approximately half the amplitude of the normal native signal amplitude. A value of +6.0 (dB) will play at approximately twice the amplitude of the normal native signal amplitude. Strongly recommend not to exceed +10 (dB) as there's usually no effective increase in loudness for any value greater than that. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :audioEncoding => String.t(), :effectsProfileId => list(String.t()), :pitch => float(), :sampleRateHertz => integer(), :speakingRate => float(), :volumeGainDb => float() } field(:audioEncoding) field(:effectsProfileId, type: :list) field(:pitch) field(:sampleRateHertz) field(:speakingRate) field(:volumeGainDb) end defimpl Poison.Decoder, for: GoogleApi.TextToSpeech.V1.Model.AudioConfig do def decode(value, options) do GoogleApi.TextToSpeech.V1.Model.AudioConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.TextToSpeech.V1.Model.AudioConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
62.403226
618
0.726544
797689e9da0f1455e11f2420b870f7f5b077e247
485
ex
Elixir
echo/lib/echo_web/views/error_view.ex
lamboap/liveview_sept_2021
495731c20484a0e63e5fb768956b98d57b44be8f
[ "MIT" ]
1
2021-09-14T01:52:42.000Z
2021-09-14T01:52:42.000Z
echo/lib/echo_web/views/error_view.ex
lamboap/liveview_sept_2021
495731c20484a0e63e5fb768956b98d57b44be8f
[ "MIT" ]
1
2021-09-17T11:30:04.000Z
2021-09-17T11:30:04.000Z
echo/lib/echo_web/views/error_view.ex
lamboap/liveview_sept_2021
495731c20484a0e63e5fb768956b98d57b44be8f
[ "MIT" ]
4
2021-09-14T00:04:39.000Z
2021-09-15T15:14:52.000Z
defmodule EchoWeb.ErrorView do use EchoWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
28.529412
61
0.731959
7976b5e4280e185ba5ae099f7f47e267d3debca4
2,493
exs
Elixir
apps/ewallet_db/priv/repo/migrations/20180613034653_add_cross_token_support_to_transfers.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/ewallet_db/priv/repo/migrations/20180613034653_add_cross_token_support_to_transfers.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/ewallet_db/priv/repo/migrations/20180613034653_add_cross_token_support_to_transfers.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule EWalletDB.Repo.Migrations.AddCrossTokenSupportToTransfers do use Ecto.Migration import Ecto.Query alias Ecto.MigrationError alias EWalletDB.Repo def up do _ = add_fields() _ = flush() _ = populate_fields() _ = turn_off_nullables() _ = remove_old_fields() end def add_fields do # Fields are added with `null:true` so we can populate data in. alter table(:transfer) do add :from_amount, :decimal, precision: 81, scale: 0, null: true add :from_token_uuid, references(:token, column: :uuid, type: :uuid), null: true add :to_amount, :decimal, precision: 81, scale: 0, null: true add :to_token_uuid, references(:token, column: :uuid, type: :uuid), null: true add :exchange_account_uuid, references(:account, column: :uuid, type: :uuid), null: true end end defp populate_fields do query = from(t in "transfer", update: [set: [from_amount: t.amount, from_token_uuid: t.token_uuid, to_amount: t.amount, to_token_uuid: t.token_uuid]]) _ = Repo.update_all(query, []) end defp turn_off_nullables do alter table(:transfer) do modify :from_amount, :decimal, null: false modify :from_token_uuid, :uuid, null: false modify :to_amount, :decimal, null: false modify :to_token_uuid, :uuid, null: false end end defp remove_old_fields do alter table(:transfer) do remove :amount remove :token_uuid end end def down do raise MigrationError, message: "This migration cannot be rolled back due to potential loss of transfer data." end end
31.961538
94
0.618532
7976ba10352f1456193966eaffa08dd9c5f4df99
809
ex
Elixir
lib/distcount/counters/counter_log.ex
cabol/distcount
b0b42f66dcc130ec6e349ab8b915cfb6f5b77c7b
[ "MIT" ]
null
null
null
lib/distcount/counters/counter_log.ex
cabol/distcount
b0b42f66dcc130ec6e349ab8b915cfb6f5b77c7b
[ "MIT" ]
null
null
null
lib/distcount/counters/counter_log.ex
cabol/distcount
b0b42f66dcc130ec6e349ab8b915cfb6f5b77c7b
[ "MIT" ]
null
null
null
defmodule Distcount.Counters.CounterLog do @moduledoc """ CounterLog schema. """ use Ecto.Schema import Ecto.Changeset @typedoc "Counter's type" @type t :: %__MODULE__{ key: binary | nil, value: integer | nil } schema "counters_log" do field :key, :string field :value, :integer timestamps() end @doc false @spec changeset(t, map) :: Ecto.Changeset.t() def changeset(t, attrs) do t |> cast(attrs, [:key, :value]) |> validate_required([:key, :value]) end @doc false @spec validate(map) :: {:ok, t} | {:error, Ecto.Changeset.t()} def validate(attrs) do changeset = changeset(%__MODULE__{}, attrs) if changeset.valid? do {:ok, apply_changes(changeset)} else {:error, changeset} end end end
18.813953
64
0.605686
7976c224d75947d01f2e442ac2cef4571f965122
88
exs
Elixir
apps/evm/test/evm/sub_state_test.exs
atoulme/ethereum
cebb0756c7292ac266236636d2ab5705cb40a52e
[ "MIT" ]
105
2017-08-02T07:55:17.000Z
2021-12-23T21:49:57.000Z
apps/evm/test/evm/sub_state_test.exs
atoulme/ethereum
cebb0756c7292ac266236636d2ab5705cb40a52e
[ "MIT" ]
19
2017-08-21T22:28:39.000Z
2018-05-01T13:33:12.000Z
apps/evm/test/evm/sub_state_test.exs
atoulme/ethereum
cebb0756c7292ac266236636d2ab5705cb40a52e
[ "MIT" ]
17
2017-08-10T15:50:47.000Z
2021-11-19T04:29:59.000Z
defmodule EVM.SubStateTest do use ExUnit.Case, async: true doctest EVM.SubState end
17.6
30
0.784091
797706a71a2627a17bf3e443f43599253d87bfe3
41
ex
Elixir
lib/elixir/lib/tuple.ex
Nicd/elixir
e62ef92a4be1b562033d35b2d822cc9d6c661077
[ "Apache-2.0" ]
4
2016-04-05T05:51:36.000Z
2019-10-31T06:46:35.000Z
lib/elixir/lib/tuple.ex
Nicd/elixir
e62ef92a4be1b562033d35b2d822cc9d6c661077
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/tuple.ex
Nicd/elixir
e62ef92a4be1b562033d35b2d822cc9d6c661077
[ "Apache-2.0" ]
5
2015-02-01T06:01:19.000Z
2019-08-29T09:02:35.000Z
defmodule Tuple do @moduledoc false end
13.666667
18
0.804878
79772e58fd1dc62938106a9883c69467b6a481f6
8,723
ex
Elixir
lib/gym_client/api.ex
arpieb/annex_rl_demo
8115ac5ec21a22d1caf041c561af3330a0350fea
[ "Unlicense" ]
1
2020-02-10T02:50:34.000Z
2020-02-10T02:50:34.000Z
lib/gym_client/api.ex
arpieb/annex_rl_demo
8115ac5ec21a22d1caf041c561af3330a0350fea
[ "Unlicense" ]
null
null
null
lib/gym_client/api.ex
arpieb/annex_rl_demo
8115ac5ec21a22d1caf041c561af3330a0350fea
[ "Unlicense" ]
null
null
null
defmodule GymClient.Api do @moduledoc ~S""" Lotsa code shamelessly copied from: https://medium.com/@a4word/oh-the-api-clients-youll-build-in-elixir-f9140e2acfb6 """ @default_service_url "http://127.0.0.1:5000" @doc""" Send a GET request to the API ## Examples iex> Myclient.Api.get("http://localhost:4849") {:error, :econnrefused} iex> Myclient.Api.get("http://localhost:4000") {200, %{version: "0.1.0"}} iex> Myclient.Api.get("http://localhost:4000", %{user: "andrew"}) {200, %{version: "0.1.0", user: "andrew"}} iex> Myclient.Api.get("http://localhost:4000/droids/bb10") {404, %{error: "unknown_resource", reason: "/droids/bb10 is not the path you are looking for"}} """ def get(url, query_params \\ %{}, headers \\ []) do call(url, :get, "", query_params, headers) end @doc""" Send a POST request to the API ## Examples iex> Myclient.Api.post("http://localhost:4000", %{version: "2.0.0"}) {201, %{version: "2.0.0"}} """ def post(url, body \\ nil, headers \\ []) do call(url, :post, body, %{}, headers) end @doc""" Call the API service ## Examples iex> Myclient.Api.call("http://localhost:4000", :post, %{version: "2.0.0"}, %{user: "james"}) {201, %{version: "2.0.0", user: "james"}} """ def call(url, method, body \\ "", query_params \\ %{}, headers \\ []) do HTTPoison.request( method, url |> clean_url, body |> encode(content_type(headers)), headers |> clean_headers, query_params |> clean_params ) |> case do {:ok, %{body: raw_body, status_code: code, headers: headers}} -> {code, raw_body, headers} {:error, %{reason: reason}} -> {:error, reason, []} end |> content_type |> decode end @doc""" Resolve the shared secret token, if provided then simply return itself, otherwise lookup in the configs. ## Examples iex> Myclient.Api.authorization_header("def456") {"Authorization", "Bearer def456"} iex> Myclient.Api.authorization_header() {"Authorization", "Bearer abc123"} """ def authorization_header(token \\ nil) do token |> case do nil -> Application.get_env(:myclient, :token) t -> t end |> case do {:system, lookup} -> System.get_env(lookup) t -> t end |> (fn t -> {"Authorization", "Bearer #{t}"} end).() end @doc""" The service's default URL, it will lookup the config, possibly check the env variables and default if still not found ## Examples iex> Myclient.Api.service_url() "http://localhost:4000" """ def service_url() do Application.get_env(:myclient, :service_url) |> case do {:system, lookup} -> System.get_env(lookup) nil -> @default_service_url url -> url end end @doc""" Extract the content type of the headers ## Examples iex> Myclient.Api.content_type({:ok, "<xml />", [{"Server", "GitHub.com"}, {"Content-Type", "application/xml; charset=utf-8"}]}) {:ok, "<xml />", "application/xml"} iex> Myclient.Api.content_type([]) "application/json" iex> Myclient.Api.content_type([{"Content-Type", "plain/text"}]) "plain/text" iex> Myclient.Api.content_type([{"Content-Type", "application/xml; charset=utf-8"}]) "application/xml" iex> Myclient.Api.content_type([{"Server", "GitHub.com"}, {"Content-Type", "application/xml; charset=utf-8"}]) "application/xml" """ def content_type({ok, body, headers}), do: {ok, body, content_type(headers)} def content_type([]), do: "application/json" def content_type([{ "Content-Type", val } | _]), do: val |> String.split(";") |> List.first def content_type([_ | t]), do: t |> content_type @doc""" Encode the body to pass along to the server ## Examples iex> Myclient.Api.encode(%{a: 1}, "application/json") "{\\"a\\":1}" iex> Myclient.Api.encode("<xml/>", "application/xml") "<xml/>" iex> Myclient.Api.encode(%{a: "o ne"}, "application/x-www-form-urlencoded") "a=o+ne" iex> Myclient.Api.encode("goop", "application/mytsuff") "goop" """ def encode(data, "application/json"), do: Poison.encode!(data) def encode(data, "application/xml"), do: data def encode(data, "application/x-www-form-urlencoded"), do: URI.encode_query(data) def encode(data, _), do: data @doc""" Decode the response body ## Examples iex> Myclient.Api.decode({:ok, "{\\\"a\\\": 1}", "application/json"}) {:ok, %{a: 1}} iex> Myclient.Api.decode({500, "", "application/json"}) {500, ""} iex> Myclient.Api.decode({:error, "{\\\"a\\\": 1}", "application/json"}) {:error, %{a: 1}} iex> Myclient.Api.decode({:ok, "{goop}", "application/json"}) {:error, "{goop}"} iex> Myclient.Api.decode({:error, "{goop}", "application/json"}) {:error, "{goop}"} iex> Myclient.Api.decode({:error, :nxdomain, "application/dontcare"}) {:error, :nxdomain} """ def decode({ok, body, _}) when is_atom(body), do: {ok, body} def decode({ok, "", _}), do: {ok, ""} def decode({ok, body, "application/json"}) when is_binary(body) do body |> Poison.decode(keys: :atoms) |> case do {:ok, parsed} -> {ok, parsed} _ -> {:error, body} end end def decode({ok, body, "application/xml"}) do try do {ok, body |> :binary.bin_to_list |> :xmerl_scan.string} catch :exit, _e -> {:error, body} end end def decode({ok, body, _}), do: {ok, body} @doc""" Clean the URL, if there is a port, but nothing after, then ensure there's a ending '/' otherwise you will encounter something like hackney_url.erl:204: :hackney_url.parse_netloc/2 ## Examples iex> Myclient.Api.clean_url() "http://localhost:4000/" iex> Myclient.Api.clean_url(nil) "http://localhost:4000/" iex> Myclient.Api.clean_url("") "http://localhost:4000/" iex> Myclient.Api.clean_url("/profile") "http://localhost:4000/profile" iex> Myclient.Api.clean_url("http://localhost") "http://localhost" iex> Myclient.Api.clean_url("http://localhost:4000/b") "http://localhost:4000/b" iex> Myclient.Api.clean_url("http://localhost:4000") "http://localhost:4000/" """ def clean_url(url \\ nil) do url |> endpoint_url |> slash_cleanup end defp endpoint_url(endpoint) do case endpoint do nil -> service_url() "" -> service_url() "/" <> _ -> service_url() <> endpoint _ -> endpoint end end defp slash_cleanup(url) do url |> String.split(":") |> List.last |> Integer.parse |> case do {_, ""} -> url <> "/" _ -> url end end @doc""" Clean the URL, if there is a port, but nothing after, then ensure there's a ending '/' otherwise you will encounter something like hackney_url.erl:204: :hackney_url.parse_netloc/2 Also allow headers to be provided as a %{}, makes it easier to ensure defaults are set ## Examples iex> Myclient.Api.clean_headers(%{}) [{"Content-Type", "application/json; charset=utf-8"}] iex> Myclient.Api.clean_headers(%{"Content-Type" => "application/xml"}) [{"Content-Type", "application/xml"}] iex> Myclient.Api.clean_headers(%{"Authorization" => "Bearer abc123"}) [{"Authorization","Bearer abc123"}, {"Content-Type", "application/json; charset=utf-8"}] iex> Myclient.Api.clean_headers(%{"Authorization" => "Bearer abc123", "Content-Type" => "application/xml"}) [{"Authorization","Bearer abc123"}, {"Content-Type", "application/xml"}] iex> Myclient.Api.clean_headers([]) [{"Content-Type", "application/json; charset=utf-8"}] iex> Myclient.Api.clean_headers([{"apples", "delicious"}]) [{"Content-Type", "application/json; charset=utf-8"}, {"apples", "delicious"}] iex> Myclient.Api.clean_headers([{"apples", "delicious"}, {"Content-Type", "application/xml"}]) [{"apples", "delicious"}, {"Content-Type", "application/xml"}] """ def clean_headers(h) when is_map(h) do %{"Content-Type" => "application/json; charset=utf-8"} |> Map.merge(h) |> Enum.map(&(&1)) end def clean_headers(h) when is_list(h) do h |> Enum.filter(fn {k,_v} -> k == "Content-Type" end) |> case do [] -> [{"Content-Type", "application/json; charset=utf-8"} | h ] _ -> h end end def clean_params(query_params) when query_params == %{}, do: [] def clean_params(query_params), do: [{:params, query_params}] end
28.048232
134
0.594062
79778fbf8a2437d6cd9e4485514f8a8662027a05
1,530
ex
Elixir
lib/termDirectory_web/controllers/module_controller.ex
nliechti/termDirectory
267b3025c14e26575c7a9483692e94a7bf29e5fe
[ "MIT" ]
1
2019-03-15T15:40:24.000Z
2019-03-15T15:40:24.000Z
lib/termDirectory_web/controllers/module_controller.ex
nliechti/termDirectory
267b3025c14e26575c7a9483692e94a7bf29e5fe
[ "MIT" ]
null
null
null
lib/termDirectory_web/controllers/module_controller.ex
nliechti/termDirectory
267b3025c14e26575c7a9483692e94a7bf29e5fe
[ "MIT" ]
null
null
null
defmodule TermDirectoryWeb.ModuleController do use TermDirectoryWeb, :controller alias TermDirectory.Modules alias TermDirectory.Modules.Module action_fallback TermDirectoryWeb.FallbackController @doc """ This catches the search url param and performs a search for the given search string in the database """ def index(conn, %{"search" => searchString}) do modules = Modules.searchModule(searchString) conn |> render("all_modules_simple.json", modules: modules) end def index(conn, _params) do modules = Modules.list_modules() render(conn, "all_modules_simple.json", modules: modules) end def create(conn, module_params) do with {:ok, %Module{} = module} <- Modules.create_module(module_params) do conn |> put_status(:created) |> put_resp_header("location", module_path(conn, :show, module)) |> render("one_simple_module.json", module: module) end end def show(conn, %{"id" => id}) do module = Modules.get_module!(id) render(conn, "one_extended_module.json", module: module) end def update(conn, module_params = %{"id" => id}) do module = Modules.get_module!(id) with {:ok, %Module{} = module} <- Modules.update_module(module, module_params) do render(conn, "one_simple_module.json", module: module) end end def delete(conn, %{"id" => id}) do module = Modules.get_module!(id) with {:ok, %Module{}} <- Modules.delete_module(module) do send_resp(conn, :no_content, "") end end end
28.867925
85
0.681699
797790737ac81f45abed61b7a57fe0bf68287eb7
3,881
ex
Elixir
lib/aoc/day_14.ex
CraigCottingham/advent-of-code-2019
76a1545e4cca14fe1e9e0de475de253170da1645
[ "Apache-2.0" ]
null
null
null
lib/aoc/day_14.ex
CraigCottingham/advent-of-code-2019
76a1545e4cca14fe1e9e0de475de253170da1645
[ "Apache-2.0" ]
null
null
null
lib/aoc/day_14.ex
CraigCottingham/advent-of-code-2019
76a1545e4cca14fe1e9e0de475de253170da1645
[ "Apache-2.0" ]
null
null
null
defmodule AoC.Day14 do @moduledoc false def part_1 do ## disabled for now, as it takes a long time to run _all_reactions = "data/day14-input.txt" |> File.stream!() |> Enum.map(&String.trim/1) |> parse_input_data() # stockpile = run_reaction([find_reaction(all_reactions, "FUEL")], %{}, true, all_reactions) # Map.get(stockpile, "ORE") 1_967_319 end def part_2 do ## disabled for now, as this code brute-forces the answer and takes 8+ hours to run _all_reactions = "data/day14-input.txt" |> File.stream!() |> Enum.map(&String.trim/1) |> parse_input_data() # stockpile = # AoC.Day14.run_to_exhaustion( # AoC.Day14.find_reaction(all_reactions, "FUEL"), # %{"ORE" => 1_000_000_000_000, :counter => 0}, # all_reactions # ) # # Map.get(stockpile, "FUEL") 1_122_036 end def find_reaction(all_reactions, desired_chemical), do: Enum.find(all_reactions, fn {{_, chemical}, _} -> chemical == desired_chemical end) def parse_component(str) do [[amount, chemical]] = Regex.scan(~r/(\d+)\s+(\S+)/, str, capture: :all_but_first) {String.to_integer(amount), chemical} end def parse_line(line) do # 59 CQGW, 15 MSNG, 6 XGKRF, 10 LJRQ, 1 HRKGV, 15 RKVC => 1 FUEL [all_reactants_str, product_str] = String.split(line, ~r/\s*=>\s*/, trim: true) reactants = all_reactants_str |> String.split(~r/\s*,\s*/, trim: true) |> Enum.map(&parse_component/1) product = parse_component(product_str) {product, reactants} end def run_reaction([], stockpile, false, _), do: stockpile def run_reaction([], stockpile, true, _), do: Map.update!(stockpile, "ORE", fn amount -> -amount end) def run_reaction( [{{product_amount, product_chemical}, reactants} | rest] = stack, stockpile, borrow_ore, all_reactions ) do # IO.puts("Running #{reaction_to_string(reaction)}") case Enum.find(reactants, fn reactant -> !sufficient_reactant?(reactant, stockpile, borrow_ore) end) do nil -> # IO.puts("Everything we need is in #{inspect stockpile}") updated_stockpile = reactants |> Enum.reduce(stockpile, fn {amount, chemical}, s -> remove_from_stockpile(s, chemical, amount) end) |> add_to_stockpile(product_chemical, product_amount) run_reaction(rest, updated_stockpile, borrow_ore, all_reactions) {_, "ORE"} when borrow_ore == false -> {:insufficient_ore, stockpile} {_, needed_chemical} -> subreaction = find_reaction(all_reactions, needed_chemical) run_reaction([subreaction | stack], stockpile, borrow_ore, all_reactions) end end def run_to_exhaustion(reaction, stockpile, all_reactions) do case run_reaction([reaction], stockpile, false, all_reactions) do {:insufficient_ore, final_stockpile} -> final_stockpile new_stockpile -> run_to_exhaustion(reaction, new_stockpile, all_reactions) end end defp add_to_stockpile(stockpile, chemical, amount), do: Map.update(stockpile, chemical, amount, fn old_amount -> old_amount + amount end) defp parse_input_data(lines), do: Enum.map(lines, &parse_line/1) defp remove_from_stockpile(stockpile, chemical, amount), do: Map.update(stockpile, chemical, -amount, fn old_amount -> old_amount - amount end) defp sufficient_reactant?({_, "ORE"}, _, true), do: true defp sufficient_reactant?({desired_amount, chemical}, stockpile, _), do: Map.get(stockpile, chemical, 0) >= desired_amount # defp reaction_to_string({{amount, chemical}, reactants}) do # "#{amount} #{chemical} <- #{ # reactants # |> Enum.map(fn {a, c} -> "#{a} #{c}" end) # |> Enum.join(", ") # }" # end end
30.801587
96
0.639011
7977ef12032ab99f6501397610d68c78360ebe67
1,735
ex
Elixir
lib/oli_web/live/common/listing.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli_web/live/common/listing.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli_web/live/common/listing.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule OliWeb.Common.Listing do use Surface.Component alias OliWeb.Common.SortableTable.Table alias OliWeb.Common.{CardListing, Paging} prop total_count, :integer, required: true prop filter, :string, required: true prop limit, :integer, required: true prop offset, :integer, required: true prop table_model, :struct, required: true prop sort, :event, required: true prop page_change, :event, required: true prop show_bottom_paging, :boolean, default: true prop additional_table_class, :string, default: "table-sm" prop cards_view, :boolean, default: false prop selected, :event prop context, :any def render(assigns) do ~F""" <div class="pb-5"> {#if @filter != ""} <strong>Results filtered on &quot;{@filter}&quot;</strong> {/if} {#if @total_count > 0 and @total_count > @limit} <Paging id="header_paging" total_count={@total_count} offset={@offset} limit={@limit} click={@page_change}/> {render_table(assigns)} {#if @show_bottom_paging} <Paging id="footer_paging" total_count={@total_count} offset={@offset} limit={@limit} click={@page_change}/> {/if} {#elseif @total_count > 0} <div>Showing all results ({@total_count} total)</div> <br> {render_table(assigns)} {#else} <p>None exist</p> {/if} </div> """ end defp render_table(assigns) do ~F""" {#if @cards_view} <CardListing model={@table_model} selected={@selected} context={@context}/> {#else} <Table model={@table_model} sort={@sort} additional_table_class={@additional_table_class} context={@context}/> {/if} """ end end
32.735849
120
0.628818
79783252f9d1d75a23cdc1bd0c8b6dd7f831c537
5,755
ex
Elixir
server/lib/prepply/employees.ex
jeepers3327/prepply
64b6be3b832fddf429faa31f5f7c1b93b842f821
[ "MIT" ]
2
2021-03-04T15:21:14.000Z
2021-03-21T13:43:07.000Z
server/lib/prepply/employees.ex
jeepers3327/prepply
64b6be3b832fddf429faa31f5f7c1b93b842f821
[ "MIT" ]
null
null
null
server/lib/prepply/employees.ex
jeepers3327/prepply
64b6be3b832fddf429faa31f5f7c1b93b842f821
[ "MIT" ]
null
null
null
defmodule Prepply.Employees do @moduledoc """ The Employees context. """ import Ecto.Query, warn: false alias Prepply.Repo alias Ecto.Multi alias Prepply.Employees.{EmployeeProfile, EmployeeChecklist} alias Prepply.Onboarding.Checklist alias Prepply.Accounts.User @doc """ Returns the list of employee_profiles. ## Examples iex> list_employee_profiles() [%EmployeeProfile{}, ...] """ def list_employee_profiles do Repo.all(EmployeeProfile) end @doc """ Gets a single employee_profile. Raises `Ecto.NoResultsError` if the Employee profile does not exist. ## Examples iex> get_employee_profile!(123) %EmployeeProfile{} iex> get_employee_profile!(456) ** (Ecto.NoResultsError) """ def get_employee_profile!(id), do: Repo.get!(EmployeeProfile, id) @doc """ Creates a employee_profile. ## Examples iex> create_employee_profile(%{field: value}) {:ok, %EmployeeProfile{}} iex> create_employee_profile(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_employee_profile(attrs \\ %{}) do %EmployeeProfile{} |> EmployeeProfile.changeset(attrs) |> Repo.insert() end @doc """ Updates a employee_profile. ## Examples iex> update_employee_profile(employee_profile, %{field: new_value}) {:ok, %EmployeeProfile{}} iex> update_employee_profile(employee_profile, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_employee_profile(%EmployeeProfile{} = employee_profile, attrs) do employee_profile |> EmployeeProfile.changeset(attrs) |> Repo.update() end @doc """ Deletes a employee_profile. ## Examples iex> delete_employee_profile(employee_profile) {:ok, %EmployeeProfile{}} iex> delete_employee_profile(employee_profile) {:error, %Ecto.Changeset{}} """ def delete_employee_profile(%EmployeeProfile{} = employee_profile) do Repo.delete(employee_profile) end @doc """ Returns an `%Ecto.Changeset{}` for tracking employee_profile changes. ## Examples iex> change_employee_profile(employee_profile) %Ecto.Changeset{data: %EmployeeProfile{}} """ def change_employee_profile(%EmployeeProfile{} = employee_profile, attrs \\ %{}) do EmployeeProfile.changeset(employee_profile, attrs) end alias Prepply.Employees.EmployeeChecklist @doc """ Returns the list of employee_checklists. ## Examples iex> list_employee_checklists() [%EmployeeChecklist{}, ...] """ def list_employee_checklists do Repo.all(EmployeeChecklist) end @doc """ Gets a single employee_checklist. Raises `Ecto.NoResultsError` if the Employee checklist does not exist. ## Examples iex> get_employee_checklist!(123) %EmployeeChecklist{} iex> get_employee_checklist!(456) ** (Ecto.NoResultsError) """ def get_employee_checklist!(id), do: Repo.get!(EmployeeChecklist, id) @doc """ Creates a employee_checklist. ## Examples iex> create_employee_checklist(%{field: value}) {:ok, %EmployeeChecklist{}} iex> create_employee_checklist(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_employee_checklist(attrs \\ %{}) do %EmployeeChecklist{} |> EmployeeChecklist.changeset(attrs) |> Repo.insert() end @doc """ Updates a employee_checklist. ## Examples iex> update_employee_checklist(employee_checklist, %{field: new_value}) {:ok, %EmployeeChecklist{}} iex> update_employee_checklist(employee_checklist, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_employee_checklist(%EmployeeChecklist{} = employee_checklist, attrs) do employee_checklist |> EmployeeChecklist.changeset(attrs) |> Repo.update() end @doc """ Deletes a employee_checklist. ## Examples iex> delete_employee_checklist(employee_checklist) {:ok, %EmployeeChecklist{}} iex> delete_employee_checklist(employee_checklist) {:error, %Ecto.Changeset{}} """ def delete_employee_checklist(%EmployeeChecklist{} = employee_checklist) do Repo.delete(employee_checklist) end @doc """ Returns an `%Ecto.Changeset{}` for tracking employee_checklist changes. ## Examples iex> change_employee_checklist(employee_checklist) %Ecto.Changeset{data: %EmployeeChecklist{}} """ def change_employee_checklist(%EmployeeChecklist{} = employee_checklist, attrs \\ %{}) do EmployeeChecklist.changeset(employee_checklist, attrs) end def list_employees do Repo.all(EmployeeProfile) end def create_employee(attrs \\ %{}) do Multi.new() |> Multi.insert(:account, User.changeset(%User{}, attrs)) |> Multi.insert(:profile, fn %{account: account} -> EmployeeProfile.changeset(%EmployeeProfile{user_id: account.id}, attrs) end) |> Multi.merge(fn %{profile: profile} -> get_item_ids_from_template(attrs) |> Enum.reduce(Multi.new(), fn id, multi -> employee = %EmployeeChecklist{employee_profile_id: profile.id, checklist_item_id: id} Multi.insert( multi, {:employee_checklist, id}, EmployeeChecklist.changeset(employee, attrs) ) end) end) |> Repo.transaction() end defp get_item_ids_from_template(attrs) do id = Map.get(attrs, :template_id) || Map.get(attrs, "template_id") Checklist |> where([c], c.checklist_template_id == ^id) |> select([c], c.checklist_item_id) |> Repo.all() end # For Absinthe Dataloader def datasource() do Dataloader.Ecto.new(Prepply.Repo, query: &query/2) end def query(queryable, _params) do queryable end end
23.299595
93
0.677672
797835d75676fa08a3674a5b3c948dd8bd37a48d
1,098
exs
Elixir
mix.exs
fast-radius/ex_dimensions
fe2c548d363cdce2dad9152e6ebc19fb0166efa3
[ "BSD-3-Clause" ]
5
2019-11-23T23:51:47.000Z
2021-12-08T20:48:01.000Z
mix.exs
fast-radius/ex_dimensions
fe2c548d363cdce2dad9152e6ebc19fb0166efa3
[ "BSD-3-Clause" ]
2
2020-03-03T18:53:33.000Z
2021-11-16T17:54:24.000Z
mix.exs
fast-radius/ex_dimensions
fe2c548d363cdce2dad9152e6ebc19fb0166efa3
[ "BSD-3-Clause" ]
null
null
null
defmodule Units.MixProject do use Mix.Project def project do [ app: :ex_dimensions, version: "0.2.2", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), name: "ExDimensions", docs: [main: "ExDimensions"], package: package(), description: "Dimensional analysis and unit conversions for Elixir.", source_url: "https://github.com/fast-radius/ex_dimensions" ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:ecto_sql, "~> 3.4"}, {:excheck, "~> 0.6", only: :test}, {:ex_doc, "~> 0.19", only: :dev}, {:jason, "~> 1.0"}, {:libgraph, "~> 0.13.3"}, {:nimble_parsec, "~> 0.5.1"}, {:triq, "~> 1.3.0", only: :test} ] end defp package do [ name: "ex_dimensions", licenses: ["BSD-3-Clause"], links: %{"GitHub" => "https://github.com/fast-radius/ex_dimensions"} ] end end
23.361702
75
0.553734
79784f88c07a815e45753b762ff9183e4696a4ee
233
exs
Elixir
config/prod.exs
decursus/neko-achievements
306d32f9d0caf508e4fb531ae3254d8a4ef6d222
[ "MIT" ]
21
2017-05-11T19:19:22.000Z
2021-06-15T23:43:18.000Z
config/prod.exs
decursus/neko-achievements
306d32f9d0caf508e4fb531ae3254d8a4ef6d222
[ "MIT" ]
41
2017-11-20T18:43:31.000Z
2021-12-09T18:17:25.000Z
config/prod.exs
decursus/neko-achievements
306d32f9d0caf508e4fb531ae3254d8a4ef6d222
[ "MIT" ]
97
2017-10-11T15:38:11.000Z
2022-01-21T09:56:01.000Z
use Mix.Config config :neko, :cowboy, listen_address: {127, 0, 0, 1} config :neko, :cowboy, listen_port: 4000 # Do not include time - it's printed by systemd journal config :logger, :console, format: "$metadata[$level] $message\n"
29.125
64
0.716738
7978565332fb4ab6e6b12933de6e35d6a23aaa2d
2,476
ex
Elixir
core/sup_tree_core/startup_manager.ex
IvanPereyra-23/PaaS
0179c7b57645473308b0a295a70b6284ed220fbf
[ "Apache-2.0" ]
1
2020-08-27T18:43:11.000Z
2020-08-27T18:43:11.000Z
core/sup_tree_core/startup_manager.ex
IvanPereyra-23/PaaS
0179c7b57645473308b0a295a70b6284ed220fbf
[ "Apache-2.0" ]
null
null
null
core/sup_tree_core/startup_manager.ex
IvanPereyra-23/PaaS
0179c7b57645473308b0a295a70b6284ed220fbf
[ "Apache-2.0" ]
1
2020-08-27T18:43:21.000Z
2020-08-27T18:43:21.000Z
# Copyright(c) 2015-2020 ACCESS CO., LTD. All rights reserved. use Croma defmodule AntikytheraCore.StartupManager do @moduledoc """ Manages progress of startup procedure of antikythera. Most of initialization steps are done within `AntikytheraCore.start/2`. However, the following step is not done in `AntikytheraCore.start/2` and delayed: - Installing gears: Starting a gear requires that the antikythera instance (as an OTP application) has started; this step is delegated to `AntikytheraCore.VersionSynchronizer`. This `GenServer` waits for the above procedures to complete and then changes the cowboy routing rules so that the current node can receive web requests from its upstream load balancer. """ use GenServer alias Antikythera.GearName alias AntikytheraCore.GearManager alias AntikytheraCore.Handler.CowboyRouting require AntikytheraCore.Logger, as: L @typep step :: :all_gears_installed @typep state :: %{step => boolean} def start_link([]) do GenServer.start_link(__MODULE__, :ok, [name: __MODULE__]) end @impl true def init(:ok) do {:ok, %{all_gears_installed: false}} end @impl true def handle_call(:initialized?, _from, state) do {:reply, all_initialization_steps_finished?(state), state} end @impl true def handle_cast({:update_routing, gear_names}, state) do CowboyRouting.update_routing(gear_names, all_initialization_steps_finished?(state)) {:noreply, state} end def handle_cast(:all_gears_installed, state) do handle_completion_notice(:all_gears_installed, state) end defunp handle_completion_notice(completed_step :: v[atom], old_state :: state) :: {:noreply, state} do L.info("received #{completed_step}") new_state = Map.put(old_state, completed_step, true) if !all_initialization_steps_finished?(old_state) and all_initialization_steps_finished?(new_state) do CowboyRouting.update_routing(GearManager.running_gear_names(), true) end {:noreply, new_state} end defunp all_initialization_steps_finished?(state :: state) :: boolean do Enum.all?(Map.values(state)) end # # Public API # defun initialized?() :: boolean do GenServer.call(__MODULE__, :initialized?) end defun update_routing(gear_names :: [GearName.t]) :: :ok do GenServer.cast(__MODULE__, {:update_routing, gear_names}) end defun all_gears_installed() :: :ok do GenServer.cast(__MODULE__, :all_gears_installed) end end
30.95
106
0.742326
7978596a2a819dc731b89d59c9aa7ccc41446be7
463
ex
Elixir
lib/reaper/partitioners/path_partitioner.ex
bbalser/reaper
7a2e8808c877b33ffa63a745179118f938460989
[ "Apache-2.0" ]
26
2019-09-20T23:54:45.000Z
2020-08-20T14:23:32.000Z
lib/reaper/partitioners/path_partitioner.ex
bbalser/reaper
7a2e8808c877b33ffa63a745179118f938460989
[ "Apache-2.0" ]
757
2019-08-15T18:15:07.000Z
2020-09-18T20:55:31.000Z
lib/reaper/partitioners/path_partitioner.ex
bbalser/reaper
7a2e8808c877b33ffa63a745179118f938460989
[ "Apache-2.0" ]
9
2019-11-12T16:43:46.000Z
2020-03-25T16:23:16.000Z
defmodule Reaper.Partitioners.PathPartitioner do @moduledoc false @behaviour Reaper.Partitioner def partition(payload, path) do filter = path |> String.split(".") |> Enum.map(&format_key(payload, &1)) |> Enum.map(&Access.key/1) payload |> get_in(filter) |> to_string() end defp format_key(%_struct{}, path_elem) do String.to_atom(path_elem) end defp format_key(_payload, path_elem), do: path_elem end
20.130435
53
0.658747
7978cec3c7c09128a338af137a68bf23bae2151d
381
exs
Elixir
weather/test/cli_test.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
weather/test/cli_test.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
weather/test/cli_test.exs
benjohns1/elixer-app
6e866ec084c5e75442c0b70f66e35f61b5b74d34
[ "MIT" ]
null
null
null
defmodule WeatherTest do use ExUnit.Case import Weather.CLI, only: [ parse_args: 1 ] test ":help returned by option parsing with -h and --help options" do assert parse_args(["-h", "anything"]) == :help assert parse_args(["--help", "anything"]) == :help end test "return correct values" do assert parse_args(["city name"]) == { "city name" } end end
23.8125
71
0.643045
7978f1c80e1eaa487629d810e0079ccd3e996a8f
1,576
ex
Elixir
clients/tag_manager/lib/google_api/tag_manager/v2/model/list_tags_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/tag_manager/lib/google_api/tag_manager/v2/model/list_tags_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/tag_manager/lib/google_api/tag_manager/v2/model/list_tags_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.TagManager.V2.Model.ListTagsResponse do @moduledoc """ List Tags Response. ## Attributes - nextPageToken (String): Continuation token for fetching the next page of results. Defaults to: `null`. - tag (List[Tag]): All GTM Tags of a GTM Container. Defaults to: `null`. """ defstruct [ :"nextPageToken", :"tag" ] end defimpl Poison.Decoder, for: GoogleApi.TagManager.V2.Model.ListTagsResponse do import GoogleApi.TagManager.V2.Deserializer def decode(value, options) do value |> deserialize(:"tag", :list, GoogleApi.TagManager.V2.Model.Tag, options) end end defimpl Poison.Encoder, for: GoogleApi.TagManager.V2.Model.ListTagsResponse do def encode(value, options) do GoogleApi.TagManager.V2.Deserializer.serialize_non_nil(value, options) end end
31.52
106
0.747462
79790932b05473ac7f08f2a4393e0b6d1b726484
9,062
exs
Elixir
test/p_handler_test.exs
idabmat/httparrot
1bc15bf4c7330341b36f7dc7d933285cda7bbf67
[ "MIT" ]
null
null
null
test/p_handler_test.exs
idabmat/httparrot
1bc15bf4c7330341b36f7dc7d933285cda7bbf67
[ "MIT" ]
null
null
null
test/p_handler_test.exs
idabmat/httparrot
1bc15bf4c7330341b36f7dc7d933285cda7bbf67
[ "MIT" ]
null
null
null
defmodule HTTParrot.PHandlerTest do use ExUnit.Case import :meck import HTTParrot.PHandler setup do new HTTParrot.GeneralRequestInfo new JSX new :cowboy_req on_exit fn -> unload() end :ok end Enum.each [{"/post", "POST"}, {"/patch", "PATCH"}, {"/put", "PUT"}], fn {path, verb} -> test "allowed_methods return verb related to #{path}" do expect(:cowboy_req, :path, 1, {unquote(path), :req2}) assert allowed_methods(:req1, :state) == {[unquote(verb)], :req2, :state} assert validate :cowboy_req end end test "returns json with general info and P[OST, ATCH, UT] form data" do expect(:cowboy_req, :body_qs, 1, {:ok, :body_qs, :req2}) expect(:cowboy_req, :set_resp_body, [{[:response, :req3], :req4}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req3}) expect(JSX, :encode!, [{[[:info, {:form, :body_qs}, {:data, ""}, {:json, nil}]], :response}]) assert post_form(:req1, :state) == {true, :req4, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, ATCH, UT] JSON body data" do expect(:cowboy_req, :body, 1, {:ok, "body", :req2}) expect(:cowboy_req, :set_resp_body, [{[:response, :req3], :req4}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req3}) expect(JSX, :is_json?, 1, true) expect(JSX, :decode!, 1, :decoded_json) expect(JSX, :encode!, [{[[:info, {:form, [{}]}, {:data, "body"}, {:json, :decoded_json}]], :response}]) assert post_binary(:req1, :state) == {true, :req4, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, ATCH, UT] non-JSON body data" do expect(:cowboy_req, :body, 1, {:ok, "body", :req2}) expect(:cowboy_req, :set_resp_body, [{[:response, :req3], :req4}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req3}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{}]}, {:data, "body"}, {:json, nil}]], :response}]) assert post_binary(:req1, :state) == {true, :req4, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, ATCH, UT] octet-stream body data" do expect(:cowboy_req, :body, 1, {:ok, <<0xffff :: 16>>, :req2}) expect(:cowboy_req, :set_resp_body, [{[:response, :req3], :req4}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req3}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{}]}, {:data, "data:application/octet-stream;base64,//8="}, {:json, nil}]], :response}]) assert post_binary(:req1, :state) == {true, :req4, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, UT, ATCH] non-JSON body data for a chunked request" do first_chunk = "first chunk" second_chunk = "second chunk" expect(:cowboy_req, :body, fn req -> case req do :req1 -> {:more, first_chunk, :req2} :req2 -> {:ok, second_chunk, :req3} end end) expect(:cowboy_req, :set_resp_body, [{[:response, :req4], :req5}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req4}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{}]}, {:data, first_chunk <> second_chunk}, {:json, nil}]], :response}]) assert post_binary(:req1, :state) == {true, :req5, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, UT, ATCH] octect-stream body data for a chunked request" do first_chunk = "first chunk" <> <<0xffff :: 16>> second_chunk = "second chunk" expect(:cowboy_req, :body, fn req -> case req do :req1 -> {:more, first_chunk, :req2} :req2 -> {:ok, second_chunk, :req3} end end) expect(:cowboy_req, :set_resp_body, [{[:response, :req4], :req5}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req4}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{}]}, {:data, "data:application/octet-stream;base64,#{Base.encode64(first_chunk <> second_chunk)}"}, {:json, nil}]], :response}]) assert post_binary(:req1, :state) == {true, :req5, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, ATCH, UT] form data for multipart request (simple)" do expect(:cowboy_req, :part, fn req -> case req do :req1 -> {:ok, [{"content-disposition", "form-data; name=\"key1\""}], :req2} :req3 -> {:done, :req4} end end) expect(:cowboy_req, :part_body, [{[:req2], {:ok, "value1", :req3}}]) expect(:cowboy_req, :parse_header, [{["content-type", :req4], {:ok, {"multipart", "form-data", [{"boundary", "----WebKitFormBoundary8BEQxJvZANFsvRV9"}]}, :req5}}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req6}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{"key1", "value1"}]}, {:files, [{}]}, {:data, ""}, {:json, nil}]], :response}]) expect(:cowboy_req, :set_resp_body, [{[:response, :req6], :req7}]) assert post_multipart(:req1, :state) == {true, :req7, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, ATCH, UT] form data for multipart requests (multiple parts)" do expect(:cowboy_req, :part, fn req -> case req do :req1 -> {:ok, [{"content-disposition", "form-data; name=\"key1\""}], :req2} :req3 -> {:ok, [{"content-disposition", "form-data; name=\"key2\""}], :req4} :req5 -> {:done, :req6} end end) expect(:cowboy_req, :part_body, fn req -> case req do :req2 -> {:ok, "value1", :req3} :req4 -> {:ok, "value2", :req5} end end) expect(:cowboy_req, :parse_header, [{["content-type", :req6], {:ok, {"multipart", "form-data", [{"boundary", "----WebKitFormBoundary8BEQxJvZANFsvRV9"}]}, :req7}}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req8}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{"key1", "value1"}, {"key2", "value2"}]}, {:files, [{}]}, {:data, ""}, {:json, nil}]], :response}]) expect(:cowboy_req, :set_resp_body, [{[:response, :req8], :req9}]) assert post_multipart(:req1, :state) == {true, :req9, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, UT, ATCH] file data (one file)" do expect(:cowboy_req, :part, fn req -> case req do :req1 -> {:ok, [{"content-disposition", "form-data; name=\"file1\"; filename=\"testdata.txt\""}, {"content-type", "text/plain"}], :req2} :req3 -> {:done, :req4} end end) expect(:cowboy_req, :part_body, [{[:req2], {:ok, "here is some cool\ntest data.", :req3}}]) expect(:cowboy_req, :parse_header, [{["content-type", :req4], {:ok, {"multipart", "form-data", [{"boundary", "----WebKitFormBoundary8BEQxJvZANFsvRV9"}]}, :req5}}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req6}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{}]}, {:files, [{"file1", "here is some cool\ntest data."}]}, {:data, ""}, {:json, nil}]], :response}]) expect(:cowboy_req, :set_resp_body, [{[:response, :req6], :req7}]) assert post_multipart(:req1, :state) == {true, :req7, nil} assert validate HTTParrot.GeneralRequestInfo end test "returns json with general info and P[OST, UT, ATCH] form data and file data (form-data plus one file)" do expect(:cowboy_req, :part, fn req -> case req do :req1 -> {:ok, [{"content-disposition", "form-data; name=\"key1\""}], :req2} :req3 -> {:ok, [{"content-disposition", "form-data; name=\"file1\"; filename=\"testdata.txt\""}, {"content-type", "text/plain"}], :req4} :req5 -> {:done, :req6} end end) expect(:cowboy_req, :part_body, fn req -> case req do :req2 -> {:ok, "value1", :req3} :req4 -> {:ok, "here is some cool\ntest data", :req5} end end) expect(:cowboy_req, :parse_header, [{["content-type", :req6], {:ok, {"multipart", "form-data", [{"boundary", "----WebKitFormBoundary8BEQxJvZANFsvRV9"}]}, :req7}}]) expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {[:info], :req8}) expect(JSX, :is_json?, 1, false) expect(JSX, :encode!, [{[[:info, {:form, [{"key1", "value1"}]}, {:files, [{"file1", "here is some cool\ntest data"}]}, {:data, ""}, {:json, nil}]], :response}]) expect(:cowboy_req, :set_resp_body, [{[:response, :req8], :req9}]) assert post_multipart(:req1, :state) == {true, :req9, nil} assert validate HTTParrot.GeneralRequestInfo end end
38.726496
175
0.595454
79791477ea9b839e6104ef679537059718ded6c8
205
ex
Elixir
lib/hl7/2.2/datatypes/ck_pat_id.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.2/datatypes/ck_pat_id.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.2/datatypes/ck_pat_id.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
defmodule HL7.V2_2.DataTypes.Ckpatid do @moduledoc false use HL7.DataType, fields: [ patient_id: nil, check_digit: nil, check_digit_scheme: nil, facility_id: nil ] end
17.083333
39
0.64878
7979197c56c157d92e7a0ff9a5ae9289a36dc2c4
69
exs
Elixir
test/navigator_test.exs
fremantle-industries/navigator
55131096fce1d89f025dbcce7ee2669917b45d94
[ "MIT" ]
14
2021-04-14T15:37:21.000Z
2021-07-22T11:45:54.000Z
test/navigator_test.exs
fremantle-industries/navigator
55131096fce1d89f025dbcce7ee2669917b45d94
[ "MIT" ]
null
null
null
test/navigator_test.exs
fremantle-industries/navigator
55131096fce1d89f025dbcce7ee2669917b45d94
[ "MIT" ]
1
2021-05-13T16:49:51.000Z
2021-05-13T16:49:51.000Z
defmodule NavigatorTest do use ExUnit.Case doctest Navigator end
13.8
26
0.811594
79796781fb5376ce47a58e5f0deb4c3c23597095
1,694
ex
Elixir
lib/auto_api/capabilities/windscreen_capability.ex
nonninz/auto-api-elixir
53e11542043285e94bbb5a0a3b8ffff0b1b47167
[ "MIT" ]
null
null
null
lib/auto_api/capabilities/windscreen_capability.ex
nonninz/auto-api-elixir
53e11542043285e94bbb5a0a3b8ffff0b1b47167
[ "MIT" ]
null
null
null
lib/auto_api/capabilities/windscreen_capability.ex
nonninz/auto-api-elixir
53e11542043285e94bbb5a0a3b8ffff0b1b47167
[ "MIT" ]
null
null
null
# AutoAPI # The MIT License # # Copyright (c) 2018- High-Mobility GmbH (https://high-mobility.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. defmodule AutoApi.WindscreenCapability do @moduledoc """ Basic settings for Windscreen Capability iex> alias AutoApi.WindscreenCapability, as: W iex> W.identifier <<0x00, 0x42>> iex> W.name :windscreen iex> W.description "Windscreen" iex> length(W.properties) 13 iex> List.first(W.properties) {0x01, :wipers_status} """ @command_module AutoApi.WindscreenCommand @state_module AutoApi.WindscreenState use AutoApi.Capability, spec_file: "windscreen.json" end
37.644444
79
0.744982
79799cca3f4e41ab4abee2fb98e5b96ad32010c1
2,113
ex
Elixir
clients/api_keys/lib/google_api/api_keys/v2/model/v2_api_target.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/api_keys/lib/google_api/api_keys/v2/model/v2_api_target.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/api_keys/lib/google_api/api_keys/v2/model/v2_api_target.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.APIKeys.V2.Model.V2ApiTarget do @moduledoc """ A restriction for a specific service and optionally one or multiple specific methods. Both fields are case insensitive. ## Attributes * `methods` (*type:* `list(String.t)`, *default:* `nil`) - Optional. List of one or more methods that can be called. If empty, all methods for the service are allowed. A wildcard (*) can be used as the last symbol. Valid examples: `google.cloud.translate.v2.TranslateService.GetSupportedLanguage` `TranslateText` `Get*` `translate.googleapis.com.Get*` * `service` (*type:* `String.t`, *default:* `nil`) - The service for this restriction. It should be the canonical service name, for example: `translate.googleapis.com`. You can use [`gcloud services list`](/sdk/gcloud/reference/services/list) to get a list of services that are enabled in the project. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :methods => list(String.t()) | nil, :service => String.t() | nil } field(:methods, type: :list) field(:service) end defimpl Poison.Decoder, for: GoogleApi.APIKeys.V2.Model.V2ApiTarget do def decode(value, options) do GoogleApi.APIKeys.V2.Model.V2ApiTarget.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.APIKeys.V2.Model.V2ApiTarget do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.26
355
0.733554
7979cffb75db5bb988f6292d6ad9417bc40c4f08
1,135
ex
Elixir
utilities/lib/persistence/persistence.ex
w0rd-driven/livebook_notebooks
4d164f8d568291412ac64ed7dd472e987a1be0c9
[ "MIT" ]
1
2022-02-25T10:32:41.000Z
2022-02-25T10:32:41.000Z
utilities/lib/persistence/persistence.ex
w0rd-driven/livebook_notebooks
4d164f8d568291412ac64ed7dd472e987a1be0c9
[ "MIT" ]
null
null
null
utilities/lib/persistence/persistence.ex
w0rd-driven/livebook_notebooks
4d164f8d568291412ac64ed7dd472e987a1be0c9
[ "MIT" ]
null
null
null
defmodule Utilities.Persistence do @base_directory Path.join([".", "data", "jobs"]) def get_path(url, extension \\ "html") do parts = URI.parse(url) hash = :crypto.hash(:sha, url) |> Base.encode16(case: :lower) {parts.host, "#{hash}.#{extension}"} end def save(url, contents, extension \\ "html") do {directory, filename} = get_path(url, extension) directory_path = Path.join([@base_directory, directory]) file_path = Path.join(directory_path, filename) File.mkdir_p!(directory_path) io_device = File.open!(file_path, [:write, :binary, :utf8]) :ok = IO.write(io_device, contents) :ok = File.close(io_device) contents end defp get_from_url(url, extension) do request = Req.new(http_errors: :raise) contents = Req.get!(request, url: url).body save(url, contents, extension) end def read(url, extension \\ "html") do {directory, filename} = get_path(url, extension) file_path = Path.join([@base_directory, directory, filename]) if File.exists?(file_path) do File.read!(file_path) else get_from_url(url, extension) end end end
29.102564
65
0.663436
797a17f845e807b181377a5f36ccbf11e016fabd
950
ex
Elixir
5-1/geom.ex
lucianferoiu/Etudes-Elixir
16eb4bd3109b64a8012e827c2f2713ca0b307364
[ "MIT" ]
null
null
null
5-1/geom.ex
lucianferoiu/Etudes-Elixir
16eb4bd3109b64a8012e827c2f2713ca0b307364
[ "MIT" ]
null
null
null
5-1/geom.ex
lucianferoiu/Etudes-Elixir
16eb4bd3109b64a8012e827c2f2713ca0b307364
[ "MIT" ]
null
null
null
defmodule Geom do def area(shape,p1,p2) when p1>=0 and p2>=0 do _area(shape,p1,p2) end def area(_,_,_), do: 0 def main do prompt_user end def prompt_user do shape = prompt_shape |> shape_to_atom IO.puts "Shape is #{shape}" if shape != :quit do p1 = prompt_number(1) |> String.to_integer p2 = prompt_number(2) |> String.to_integer val = area(shape,p1,p2) IO.puts "Result: #{val}" prompt_user end end def prompt_shape do ch = IO.gets "Shape: R)ectangle / E)llipse / T)riangle / Q)uit: " String.strip(ch,?\n) |> String.upcase end def shape_to_atom(ch) do case ch do "R" -> :rectangle "E" -> :ellipsis "T" -> :triangle _ -> :quit end end def prompt_number(ord) do nr = IO.gets "Parameter #{ord}: " String.strip nr,?\n end defp _area(:rectangle, w, h), do: w*h defp _area(:triangle,b,h), do: b*h/2.0 defp _area(:ellipsis,r1,r2), do: :math.pi()*r1*r2 defp _area(_,_,_), do: 0 end
20.212766
67
0.631579
797a8b10ee2b9dd5a5f3cbdd5507d7b91275d6ff
2,373
ex
Elixir
lib/ueberauth/strategy/apple/oauth.ex
cloverfoodlab/ueberauth_apple
b2fdd37b2a531b727fdb27db4104e72bf0125c80
[ "MIT" ]
null
null
null
lib/ueberauth/strategy/apple/oauth.ex
cloverfoodlab/ueberauth_apple
b2fdd37b2a531b727fdb27db4104e72bf0125c80
[ "MIT" ]
null
null
null
lib/ueberauth/strategy/apple/oauth.ex
cloverfoodlab/ueberauth_apple
b2fdd37b2a531b727fdb27db4104e72bf0125c80
[ "MIT" ]
null
null
null
defmodule Ueberauth.Strategy.Apple.OAuth do @moduledoc """ OAuth2 for Apple. Add `client_id` and `client_secret` to your configuration: config :ueberauth, Ueberauth.Strategy.Apple.OAuth, client_id: System.get_env("APPLE_CLIENT_ID"), client_secreat: System.get_env("APPLE_CLIENT_SECRET") """ use OAuth2.Strategy @defaults [ strategy: __MODULE__, site: "https://appleid.apple.com", authorize_url: "/auth/authorize", token_url: "/auth/token" ] @doc """ Construct a client for requests to Apple. This will be setup automatically for you in `Ueberauth.Strategy.Apple`. These options are only useful for usage outside the normal callback phase of Ueberauth. """ def client(opts \\ []) do config = Application.get_env(:ueberauth, __MODULE__, []) opts = @defaults |> Keyword.merge(opts) |> Keyword.merge(config) |> resolve_values() OAuth2.Client.new(opts) end @doc """ Provides the authorize url for the request phase of Ueberauth. No need to call this usually. """ def authorize_url!(params \\ [], opts \\ []) do opts |> client |> OAuth2.Client.authorize_url!(params) end def get(token, url, headers \\ [], opts \\ []) do [token: token] |> client |> put_param("client_secret", client().client_secret) |> OAuth2.Client.get(url, headers, opts) end def get_access_token(params \\ [], opts \\ []) do case opts |> client |> OAuth2.Client.get_token(params) do {:error, %{body: %{"error" => error}}} -> {:error, {error, "error requesting token"}} {:ok, %{token: %{access_token: nil} = token}} -> %{"error" => error} = token.other_params {:error, {error, "no access token"}} {:ok, %{token: token}} -> {:ok, token} end end # Strategy Callbacks def authorize_url(client, params) do OAuth2.Strategy.AuthCode.authorize_url(client, params) end def get_token(client, params, headers) do client |> put_param("client_secret", client.client_secret) |> put_header("Accept", "application/json") |> OAuth2.Strategy.AuthCode.get_token(params, headers) end defp resolve_values(list) do for {key, value} <- list do {key, resolve_value(value)} end end defp resolve_value({m, f, a}) when is_atom(m) and is_atom(f), do: apply(m, f, a) defp resolve_value(v), do: v end
27.917647
94
0.650232
797a9b27de7382e2bbe6dac1819304e501b58617
863
exs
Elixir
priv/sandbox/migrations/00000000000000_add_yourbot_project_table.exs
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
3
2021-11-08T15:19:19.000Z
2021-11-11T03:18:35.000Z
priv/sandbox/migrations/00000000000000_add_yourbot_project_table.exs
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
priv/sandbox/migrations/00000000000000_add_yourbot_project_table.exs
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
defmodule YourBot.Bots.Project.Repo.Migrations.AddYourbotProjectTable do use Ecto.Migration def change do create table(:yourbot_project, primary_key: false) do add :id, :tinyint, null: false, default: 0, primary_key: true add :version, :integer, default: 0 timestamps() end execute """ CREATE TRIGGER yourbot_project_no_insert BEFORE INSERT ON yourbot_project WHEN (SELECT COUNT(*) FROM yourbot_project) >= 1 -- limit here BEGIN SELECT RAISE(FAIL, 'Only One Project may exist'); END; """, """ DROP TRIGGER 'yourbot_project_no_insert'; """ now = NaiveDateTime.to_iso8601(NaiveDateTime.utc_now()) execute """ INSERT INTO yourbot_project(id, inserted_at, updated_at) VALUES(0, \'#{now}\', \'#{now}\'); """, """ DELETE FROM yourbot_project; """ end end
26.151515
95
0.651217
797a9d47e2715679b91998f5d3da7901865366d5
2,025
ex
Elixir
apps/testing/lib/assert_async.ex
calebcarroll1/smartcitiesdata
b0f03496f6c592c82ba14aebf6c5996311cf3cd0
[ "Apache-2.0" ]
26
2019-09-20T23:54:45.000Z
2020-08-20T14:23:32.000Z
apps/testing/lib/assert_async.ex
calebcarroll1/smartcitiesdata
b0f03496f6c592c82ba14aebf6c5996311cf3cd0
[ "Apache-2.0" ]
757
2019-08-15T18:15:07.000Z
2020-09-18T20:55:31.000Z
apps/testing/lib/assert_async.ex
calebcarroll1/smartcitiesdata
b0f03496f6c592c82ba14aebf6c5996311cf3cd0
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule AssertAsync do @moduledoc """ Helper macro for making assertions on async actions. This is particularly useful for testing GenServers and other processes that may be synchronously processing messages. The macro will retry an assertion until it passes or times out. ## Example defmodule Foo do use GenServer def init(opts) do {:ok, state, {:continue, :sleep}} end def handle_continue(:sleep, state) do Process.sleep(2_000) {:noreply, state} end def handle_call(:bar, _, state) do Map.get(state, :bar) end end import AssertAsync {:ok, pid} = GenServer.start_link(Foo, %{bar: 42}) assert_async do assert GenServer.call(pid, :bar) == 42 end ## Configuration * `sleep` - Time in milliseconds to wait before next retry. Defaults to `200`. * `max_tries` - Number of attempts to make before flunking assertion. Defaults to `10`. * `debug` - Boolean for producing `DEBUG` messages on failing iterations. Defaults `false`. """ defmodule Impl do @moduledoc false require Logger @defaults %{ sleep: 200, max_tries: 10, debug: false } def assert(function, opts) do state = Map.merge(@defaults, Map.new(opts)) do_assert(function, state) end defp do_assert(function, %{max_tries: 1}) do function.() end defp do_assert(function, %{max_tries: max_tries} = opts) do try do function.() rescue e in ExUnit.AssertionError -> if opts.debug do Logger.debug(fn -> "AssertAsync(remaining #{max_tries - 1}): #{ExUnit.AssertionError.message(e)}" end) end Process.sleep(opts.sleep) do_assert(function, %{opts | max_tries: max_tries - 1}) end end end defmacro assert_async(opts \\ [], do: do_block) do quote do AssertAsync.Impl.assert(fn -> unquote(do_block) end, unquote(opts)) end end end
24.107143
93
0.619259
797af6c1f74d1314c45894186842f33b4acf730e
2,764
exs
Elixir
test/phoenix_pubsub_redis_z_test.exs
cctiger36/phoenix_pubsub_redis_z
27ed1a60fcbcec4bced37e7b45493c16f8fa816d
[ "MIT" ]
5
2018-05-27T15:45:16.000Z
2019-02-12T12:56:31.000Z
test/phoenix_pubsub_redis_z_test.exs
cctiger36/phoenix_pubsub_redis_z
27ed1a60fcbcec4bced37e7b45493c16f8fa816d
[ "MIT" ]
45
2018-09-11T00:29:09.000Z
2022-03-23T21:39:38.000Z
test/phoenix_pubsub_redis_z_test.exs
cctiger36/phoenix_pubsub_redis_z
27ed1a60fcbcec4bced37e7b45493c16f8fa816d
[ "MIT" ]
1
2018-05-23T11:54:55.000Z
2018-05-23T11:54:55.000Z
defmodule PhoenixPubsubRedisZTest do alias Phoenix.PubSub alias Phoenix.PubSub.RedisZ alias Phoenix.PubSub.RedisZ.Local use ExUnit.Case, async: true def spawn_pid do spawn(fn -> :timer.sleep(:infinity) end) end setup_all do pubsub_server = TestApp.PubSub {:ok, _} = RedisZ.start_link( name: pubsub_server, redis_urls: [ "redis://localhost:6379/0", "redis://localhost:6379/1", "redis://localhost:6379/2" ], node_name: "test@localhost" ) {:ok, pubsub_server: pubsub_server} end test "#subscribe, #unsubscribe", %{pubsub_server: pubsub_server} do pid = spawn_pid() assert Local.subscribers(pubsub_server, "topic01", 0) == [] assert PubSub.subscribe(pubsub_server, pid, "topic01") == :ok assert Local.subscribers(pubsub_server, "topic01", 0) == [pid] assert PubSub.unsubscribe(pubsub_server, pid, "topic01") == :ok assert Local.subscribers(pubsub_server, "topic01", 0) == [] end test "broadcast/3 and broadcast!/3", %{pubsub_server: pubsub_server} do :ok = PubSub.subscribe(pubsub_server, self(), "topic02") # wait until Redix subscribed Process.sleep(100) :ok = PubSub.broadcast(pubsub_server, "topic02", :ping) assert_receive :ping :ok = PubSub.broadcast!(pubsub_server, "topic02", :ping) assert_receive :ping :ok = PubSub.unsubscribe(pubsub_server, self(), "topic02") assert Local.subscribers(pubsub_server, "topic02", 0) == [] end test "broadcast_from/4 and broadcast_from!/4", %{pubsub_server: pubsub_server} do pid = spawn_pid() :ok = PubSub.subscribe(pubsub_server, self(), "topic03") # wait until Redix subscribed Process.sleep(100) :ok = PubSub.broadcast_from(pubsub_server, pid, "topic03", :ping) assert_receive :ping :ok = PubSub.broadcast_from!(pubsub_server, pid, "topic03", :ping) assert_receive :ping end test "broadcast_from/4 and broadcast_from!/4 skips sender", %{pubsub_server: pubsub_server} do :ok = PubSub.subscribe(pubsub_server, self(), "topic04") # wait until Redix subscribed Process.sleep(100) :ok = PubSub.broadcast_from(pubsub_server, self(), "topic04", :ping) refute_receive :ping :ok = PubSub.broadcast_from!(pubsub_server, self(), "topic04", :ping) refute_receive :ping end test "processes automatically removed from topic when killed", %{pubsub_server: pubsub_server} do pid = spawn_pid() :ok = PubSub.subscribe(pubsub_server, pid, "topic05") assert Local.subscribers(pubsub_server, "topic05", 0) == [pid] Process.exit(pid, :kill) # wait until GC removes dead pid Process.sleep(100) assert Local.subscribers(pubsub_server, "topic05", 0) == [] end end
34.123457
99
0.678003
797affef3c771a6a778c03aeb8e16af110955695
35,035
ex
Elixir
clients/ad_sense_host/lib/google_api/ad_sense_host/v41/api/accounts.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/ad_sense_host/lib/google_api/ad_sense_host/v41/api/accounts.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/ad_sense_host/lib/google_api/ad_sense_host/v41/api/accounts.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AdSenseHost.V41.Api.Accounts do @moduledoc """ API calls for all endpoints tagged `Accounts`. """ alias GoogleApi.AdSenseHost.V41.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Get information about the selected associated AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account to get information about. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.Account{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AdSenseHost.V41.Model.Account.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_get(connection, account_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.Account{}]) end @doc """ List hosted accounts associated with this AdSense account by ad client id. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `filter_ad_client_id` (*type:* `list(String.t)`) - Ad clients to list accounts for. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.Accounts{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_list(Tesla.Env.client(), list(String.t()), keyword(), keyword()) :: {:ok, GoogleApi.AdSenseHost.V41.Model.Accounts.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_list( connection, filter_ad_client_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts", %{}) |> Request.add_param(:query, :filterAdClientId, filter_ad_client_id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.Accounts{}]) end @doc """ Get information about one of the ad clients in the specified publisher's AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad client. * `ad_client_id` (*type:* `String.t`) - Ad client to get. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdClient{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adclients_get( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdClient.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adclients_get( connection, account_id, ad_client_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}/adclients/{adClientId}", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdClient{}]) end @doc """ List all hosted ad clients in the specified hosted account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account for which to list ad clients. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:maxResults` (*type:* `integer()`) - The maximum number of ad clients to include in the response, used for paging. * `:pageToken` (*type:* `String.t`) - A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdClients{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adclients_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdClients.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adclients_list( connection, account_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :maxResults => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}/adclients", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdClients{}]) end @doc """ Delete the specified ad unit from the specified publisher AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad unit. * `ad_client_id` (*type:* `String.t`) - Ad client for which to get ad unit. * `ad_unit_id` (*type:* `String.t`) - Ad unit to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdUnit{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdUnit.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_delete( connection, account_id, ad_client_id, ad_unit_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1), "adUnitId" => URI.encode(ad_unit_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdUnit{}]) end @doc """ Get the specified host ad unit in this AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad unit. * `ad_client_id` (*type:* `String.t`) - Ad client for which to get ad unit. * `ad_unit_id` (*type:* `String.t`) - Ad unit to get. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdUnit{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdUnit.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_get( connection, account_id, ad_client_id, ad_unit_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1), "adUnitId" => URI.encode(ad_unit_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdUnit{}]) end @doc """ Get ad code for the specified ad unit, attaching the specified host custom channels. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad client. * `ad_client_id` (*type:* `String.t`) - Ad client with contains the ad unit. * `ad_unit_id` (*type:* `String.t`) - Ad unit to get the code for. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:hostCustomChannelId` (*type:* `list(String.t)`) - Host custom channel to attach to the ad code. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdCode{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_get_ad_code( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdCode.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_get_ad_code( connection, account_id, ad_client_id, ad_unit_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :hostCustomChannelId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}/adcode", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1), "adUnitId" => URI.encode(ad_unit_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdCode{}]) end @doc """ Insert the supplied ad unit into the specified publisher AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which will contain the ad unit. * `ad_client_id` (*type:* `String.t`) - Ad client into which to insert the ad unit. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.AdSenseHost.V41.Model.AdUnit.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdUnit{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdUnit.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_insert( connection, account_id, ad_client_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdUnit{}]) end @doc """ List all ad units in the specified publisher's AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad client. * `ad_client_id` (*type:* `String.t`) - Ad client for which to list ad units. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:includeInactive` (*type:* `boolean()`) - Whether to include inactive ad units. Default: true. * `:maxResults` (*type:* `integer()`) - The maximum number of ad units to include in the response, used for paging. * `:pageToken` (*type:* `String.t`) - A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdUnits{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdUnits.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_list( connection, account_id, ad_client_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :includeInactive => :query, :maxResults => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdUnits{}]) end @doc """ Update the supplied ad unit in the specified publisher AdSense account. This method supports patch semantics. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad client. * `ad_client_id` (*type:* `String.t`) - Ad client which contains the ad unit. * `ad_unit_id` (*type:* `String.t`) - Ad unit to get. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.AdSenseHost.V41.Model.AdUnit.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdUnit{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_patch( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdUnit.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_patch( connection, account_id, ad_client_id, ad_unit_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :adUnitId, ad_unit_id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdUnit{}]) end @doc """ Update the supplied ad unit in the specified publisher AdSense account. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Account which contains the ad client. * `ad_client_id` (*type:* `String.t`) - Ad client which contains the ad unit. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.AdSenseHost.V41.Model.AdUnit.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.AdUnit{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_adunits_update( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.AdUnit.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_adunits_update( connection, account_id, ad_client_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/accounts/{accountId}/adclients/{adClientId}/adunits", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1), "adClientId" => URI.encode(ad_client_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.AdUnit{}]) end @doc """ Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. ## Parameters * `connection` (*type:* `GoogleApi.AdSenseHost.V41.Connection.t`) - Connection to server * `account_id` (*type:* `String.t`) - Hosted account upon which to report. * `start_date` (*type:* `String.t`) - Start of the date range to report on in "YYYY-MM-DD" format, inclusive. * `end_date` (*type:* `String.t`) - End of the date range to report on in "YYYY-MM-DD" format, inclusive. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:dimension` (*type:* `list(String.t)`) - Dimensions to base the report on. * `:filter` (*type:* `list(String.t)`) - Filters to be run on the report. * `:locale` (*type:* `String.t`) - Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. * `:maxResults` (*type:* `integer()`) - The maximum number of rows of report data to return. * `:metric` (*type:* `list(String.t)`) - Numeric columns to include in the report. * `:sort` (*type:* `list(String.t)`) - The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending. * `:startIndex` (*type:* `integer()`) - Index of the first row of report data to return. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdSenseHost.V41.Model.Report{}}` on success * `{:error, info}` on failure """ @spec adsensehost_accounts_reports_generate( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.AdSenseHost.V41.Model.Report.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def adsensehost_accounts_reports_generate( connection, account_id, start_date, end_date, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :dimension => :query, :filter => :query, :locale => :query, :maxResults => :query, :metric => :query, :sort => :query, :startIndex => :query } request = Request.new() |> Request.method(:get) |> Request.url("/accounts/{accountId}/reports", %{ "accountId" => URI.encode(account_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :startDate, start_date) |> Request.add_param(:query, :endDate, end_date) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AdSenseHost.V41.Model.Report{}]) end end
42.363966
246
0.617097
797b0ce6df7bdae2c7adadbbd0d7a49558ded57b
8,737
exs
Elixir
test/tag_cloud/compiler/ast_style_test.exs
RobertDober/tag_cloud
e3f1fca47b32691c54870d6f8b66a7f66bbd53d6
[ "Apache-2.0" ]
null
null
null
test/tag_cloud/compiler/ast_style_test.exs
RobertDober/tag_cloud
e3f1fca47b32691c54870d6f8b66a7f66bbd53d6
[ "Apache-2.0" ]
3
2021-10-03T16:48:49.000Z
2022-02-06T10:26:36.000Z
test/tag_cloud/compiler/ast_style_test.exs
RobertDober/tag_cloud
e3f1fca47b32691c54870d6f8b66a7f66bbd53d6
[ "Apache-2.0" ]
null
null
null
defmodule Test.TagCloud.Compiler.AstStyleTest do use ExUnit.Case import TagCloud.Compiler, only: [ast_style: 1] describe "colors: gamma corrected gray scales" do test "0" do result = ast_style("0 12 100") expected = {"style", "color: #ffffff; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "1" do result = ast_style("1 16pt 100") expected = {"style", "color: #f5f5f5; font-size: 16pt; font-weight: 100;"} assert result == [expected] end test "2" do result = ast_style("2 3em 100") expected = {"style", "color: #ebebeb; font-size: 3em; font-weight: 100;"} assert result == [expected] end test "3" do result = ast_style("3 12 100") expected = {"style", "color: #e0e0e0; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "4" do result = ast_style("4 12 100") expected = {"style", "color: #d4d4d4; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "5" do result = ast_style("5 12 100") expected = {"style", "color: #c8c8c8; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "6" do result = ast_style("6 12 100") expected = {"style", "color: #bababa; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "7" do result = ast_style("7 12 100") expected = {"style", "color: #ababab; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "8" do result = ast_style("8 12 100") expected = {"style", "color: #9b9b9b; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "9" do result = ast_style("9 12 100") expected = {"style", "color: #888888; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "10" do result = ast_style("10 12 100") expected = {"style", "color: #717171; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "11" do result = ast_style("11 12 100") expected = {"style", "color: #525252; font-size: 12pt; font-weight: 100;"} assert result == [expected] end test "12" do result = ast_style("12 12 100") expected = {"style", "color: #000000; font-size: 12pt; font-weight: 100;"} assert result == [expected] end end # <%= for color <- ~w[red lime blue] do %> # <% color_map =[ "ff", "f5", "eb", "e0", "d4", "c8", "ba", "ab", "9b", "88", "71", "52", "00" ] %> # <% color_pos = %{"red" => "ffxx", "lime" => "xffx", "blue" => "xxff"} %> # describe "color shades <%= color %>" do # <%= for shade <- 0..12 do %> # test "<%= shade %>" do # result = ast_style("<%= shade %>/<%= color %>") # <% hexcolor = Map.get(color_pos, color) |> String.replace("x", Enum.at(color_map, shade)) %> # expected = {"style", "color: #<%= hexcolor %>;"} # assert result == [expected] # end # <% end %> # end # <% end %> describe "color shades red" do test "0" do result = ast_style("0/red") expected = {"style", "color: #ffffff;"} assert result == [expected] end test "1" do result = ast_style("1/red") expected = {"style", "color: #fff5f5;"} assert result == [expected] end test "2" do result = ast_style("2/red") expected = {"style", "color: #ffebeb;"} assert result == [expected] end test "3" do result = ast_style("3/red") expected = {"style", "color: #ffe0e0;"} assert result == [expected] end test "4" do result = ast_style("4/red") expected = {"style", "color: #ffd4d4;"} assert result == [expected] end test "5" do result = ast_style("5/red") expected = {"style", "color: #ffc8c8;"} assert result == [expected] end test "6" do result = ast_style("6/red") expected = {"style", "color: #ffbaba;"} assert result == [expected] end test "7" do result = ast_style("7/red") expected = {"style", "color: #ffabab;"} assert result == [expected] end test "8" do result = ast_style("8/red") expected = {"style", "color: #ff9b9b;"} assert result == [expected] end test "9" do result = ast_style("9/red") expected = {"style", "color: #ff8888;"} assert result == [expected] end test "10" do result = ast_style("10/red") expected = {"style", "color: #ff7171;"} assert result == [expected] end test "11" do result = ast_style("11/red") expected = {"style", "color: #ff5252;"} assert result == [expected] end test "12" do result = ast_style("12/red") expected = {"style", "color: #ff0000;"} assert result == [expected] end end describe "color shades lime" do test "0" do result = ast_style("0/lime") expected = {"style", "color: #ffffff;"} assert result == [expected] end test "1" do result = ast_style("1/lime") expected = {"style", "color: #f5fff5;"} assert result == [expected] end test "2" do result = ast_style("2/lime") expected = {"style", "color: #ebffeb;"} assert result == [expected] end test "3" do result = ast_style("3/lime") expected = {"style", "color: #e0ffe0;"} assert result == [expected] end test "4" do result = ast_style("4/lime") expected = {"style", "color: #d4ffd4;"} assert result == [expected] end test "5" do result = ast_style("5/lime") expected = {"style", "color: #c8ffc8;"} assert result == [expected] end test "6" do result = ast_style("6/lime") expected = {"style", "color: #baffba;"} assert result == [expected] end test "7" do result = ast_style("7/lime") expected = {"style", "color: #abffab;"} assert result == [expected] end test "8" do result = ast_style("8/lime") expected = {"style", "color: #9bff9b;"} assert result == [expected] end test "9" do result = ast_style("9/lime") expected = {"style", "color: #88ff88;"} assert result == [expected] end test "10" do result = ast_style("10/lime") expected = {"style", "color: #71ff71;"} assert result == [expected] end test "11" do result = ast_style("11/lime") expected = {"style", "color: #52ff52;"} assert result == [expected] end test "12" do result = ast_style("12/lime") expected = {"style", "color: #00ff00;"} assert result == [expected] end end describe "color shades blue" do test "0" do result = ast_style("0/blue") expected = {"style", "color: #ffffff;"} assert result == [expected] end test "1" do result = ast_style("1/blue") expected = {"style", "color: #f5f5ff;"} assert result == [expected] end test "2" do result = ast_style("2/blue") expected = {"style", "color: #ebebff;"} assert result == [expected] end test "3" do result = ast_style("3/blue") expected = {"style", "color: #e0e0ff;"} assert result == [expected] end test "4" do result = ast_style("4/blue") expected = {"style", "color: #d4d4ff;"} assert result == [expected] end test "5" do result = ast_style("5/blue") expected = {"style", "color: #c8c8ff;"} assert result == [expected] end test "6" do result = ast_style("6/blue") expected = {"style", "color: #babaff;"} assert result == [expected] end test "7" do result = ast_style("7/blue") expected = {"style", "color: #ababff;"} assert result == [expected] end test "8" do result = ast_style("8/blue") expected = {"style", "color: #9b9bff;"} assert result == [expected] end test "9" do result = ast_style("9/blue") expected = {"style", "color: #8888ff;"} assert result == [expected] end test "10" do result = ast_style("10/blue") expected = {"style", "color: #7171ff;"} assert result == [expected] end test "11" do result = ast_style("11/blue") expected = {"style", "color: #5252ff;"} assert result == [expected] end test "12" do result = ast_style("12/blue") expected = {"style", "color: #0000ff;"} assert result == [expected] end end end
23.298667
101
0.5384
797b1aaea21e9b315ba7ef3f845b293d6c7405ba
238
exs
Elixir
priv/repo/migrations/20181230071929_create_id_suffixes_on_assoc_fields_on_transfers.exs
o-marchi/o-bank-api
fd4595a6fbffb89a0ca4c2dd9aa8b4f92e700aa4
[ "MIT" ]
null
null
null
priv/repo/migrations/20181230071929_create_id_suffixes_on_assoc_fields_on_transfers.exs
o-marchi/o-bank-api
fd4595a6fbffb89a0ca4c2dd9aa8b4f92e700aa4
[ "MIT" ]
null
null
null
priv/repo/migrations/20181230071929_create_id_suffixes_on_assoc_fields_on_transfers.exs
o-marchi/o-bank-api
fd4595a6fbffb89a0ca4c2dd9aa8b4f92e700aa4
[ "MIT" ]
null
null
null
defmodule Obank.Repo.Migrations.CreateIdSuffixesOnAssocFieldsOnTransfers do use Ecto.Migration def change do alter table(:transfers) do add :to_id, references(:users) add :from_id, references(:users) end end end
21.636364
75
0.735294
797b2bb5a98b1a3b36bac48237f2e54644d0ac79
12,710
ex
Elixir
clients/storage_transfer/lib/google_api/storage_transfer/v1/api/transfer_jobs.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/lib/google_api/storage_transfer/v1/api/transfer_jobs.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/lib/google_api/storage_transfer/v1/api/transfer_jobs.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.StorageTransfer.V1.Api.TransferJobs do @moduledoc """ API calls for all endpoints tagged `TransferJobs`. """ alias GoogleApi.StorageTransfer.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Creates a transfer job that runs periodically. ## Parameters * `connection` (*type:* `GoogleApi.StorageTransfer.V1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.StorageTransfer.V1.Model.TransferJob.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.StorageTransfer.V1.Model.TransferJob{}}` on success * `{:error, info}` on failure """ @spec storagetransfer_transfer_jobs_create(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.StorageTransfer.V1.Model.TransferJob.t()} | {:error, Tesla.Env.t()} def storagetransfer_transfer_jobs_create(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/transferJobs", %{}) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.StorageTransfer.V1.Model.TransferJob{}]) end @doc """ Gets a transfer job. ## Parameters * `connection` (*type:* `GoogleApi.StorageTransfer.V1.Connection.t`) - Connection to server * `job_name` (*type:* `String.t`) - Required. The job to get. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:projectId` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform Console project that owns the job. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.StorageTransfer.V1.Model.TransferJob{}}` on success * `{:error, info}` on failure """ @spec storagetransfer_transfer_jobs_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.StorageTransfer.V1.Model.TransferJob.t()} | {:error, Tesla.Env.t()} def storagetransfer_transfer_jobs_get(connection, job_name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :projectId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+jobName}", %{ "jobName" => URI.encode(job_name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.StorageTransfer.V1.Model.TransferJob{}]) end @doc """ Lists transfer jobs. ## Parameters * `connection` (*type:* `GoogleApi.StorageTransfer.V1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - Required. A list of query parameters specified as JSON text in the form of: {"project_id":"my_project_id", "job_names":["jobid1","jobid2",...], "job_statuses":["status1","status2",...]}. Since `job_names` and `job_statuses` support multiple values, their values must be specified with array notation. `project_id` is required. `job_names` and `job_statuses` are optional. The valid values for `job_statuses` are case-insensitive: `ENABLED`, `DISABLED`, and `DELETED`. * `:pageSize` (*type:* `integer()`) - The list page size. The max allowed value is 256. * `:pageToken` (*type:* `String.t`) - The list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.StorageTransfer.V1.Model.ListTransferJobsResponse{}}` on success * `{:error, info}` on failure """ @spec storagetransfer_transfer_jobs_list(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.StorageTransfer.V1.Model.ListTransferJobsResponse.t()} | {:error, Tesla.Env.t()} def storagetransfer_transfer_jobs_list(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/transferJobs", %{}) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.StorageTransfer.V1.Model.ListTransferJobsResponse{}] ) end @doc """ Updates a transfer job. Updating a job's transfer spec does not affect transfer operations that are running already. Updating the scheduling of a job is not allowed. ## Parameters * `connection` (*type:* `GoogleApi.StorageTransfer.V1.Connection.t`) - Connection to server * `job_name` (*type:* `String.t`) - Required. The name of job to update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.StorageTransfer.V1.Model.UpdateTransferJobRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.StorageTransfer.V1.Model.TransferJob{}}` on success * `{:error, info}` on failure """ @spec storagetransfer_transfer_jobs_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.StorageTransfer.V1.Model.TransferJob.t()} | {:error, Tesla.Env.t()} def storagetransfer_transfer_jobs_patch(connection, job_name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+jobName}", %{ "jobName" => URI.encode(job_name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.StorageTransfer.V1.Model.TransferJob{}]) end end
47.249071
196
0.631314
797b2bed75b1b31eacf55c367146fa8eee8bd0eb
1,395
exs
Elixir
phone-number/phone_number_test.exs
ravanscafi/exercism-elixir
0f5c8c923166a0a795c323c7e2d6ccc9da572fcf
[ "MIT" ]
null
null
null
phone-number/phone_number_test.exs
ravanscafi/exercism-elixir
0f5c8c923166a0a795c323c7e2d6ccc9da572fcf
[ "MIT" ]
null
null
null
phone-number/phone_number_test.exs
ravanscafi/exercism-elixir
0f5c8c923166a0a795c323c7e2d6ccc9da572fcf
[ "MIT" ]
null
null
null
if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("phone_number.exs", __DIR__) end ExUnit.start() ExUnit.configure(exclude: :pending, trace: true) defmodule PhoneTest do use ExUnit.Case test "cleans number" do assert Phone.number("(123) 456-7890") == "1234567890" end # @tag :pending test "cleans number with dots" do assert Phone.number("123.456.7890") == "1234567890" end # @tag :pending test "valid when 11 digits and first is 1" do assert Phone.number("11234567890") == "1234567890" end # @tag :pending test "invalid when 11 digits" do assert Phone.number("21234567890") == "0000000000" end # @tag :pending test "invalid when 9 digits" do assert Phone.number("123456789") == "0000000000" end # @tag :pending test "invalid when proper number of digits but letters mixed in" do assert Phone.number("1a2a3a4a5a6a7a8a9a0a") == "0000000000" end # @tag :pending test "area code" do assert Phone.area_code("1234567890") == "123" end # @tag :pending test "area code with full US phone number" do assert Phone.area_code("11234567890") == "123" end # @tag :pending test "pretty print" do assert Phone.pretty("1234567890") == "(123) 456-7890" end # @tag :pending test "pretty print with full US phone number" do assert Phone.pretty("11234567890") == "(123) 456-7890" end end
23.25
69
0.675269
797b3b615e5c19a9d3ffe5bccf97d203cb941fd1
233
exs
Elixir
priv/repo/migrations/20180806212804_create_todos.exs
sneako/distillery-aws-example
75cd687791701aee17a19e48978a06495b102037
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20180806212804_create_todos.exs
sneako/distillery-aws-example
75cd687791701aee17a19e48978a06495b102037
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20180806212804_create_todos.exs
sneako/distillery-aws-example
75cd687791701aee17a19e48978a06495b102037
[ "Apache-2.0" ]
null
null
null
defmodule Example.Repo.Migrations.CreateTodos do use Ecto.Migration def change do create table(:todos) do add(:title, :string) add(:completed, :boolean) timestamps(type: :naive_datetime) end end end
17.923077
48
0.678112
797b6b9ca0ed1c7ddc02b8d7880b2a2269e07078
1,761
ex
Elixir
lib/militerm/systems/aliases.ex
jgsmith/militerm
c4252d0a93f5620b90750ac2b61baf282e9ef7eb
[ "Apache-2.0" ]
6
2017-06-16T10:26:35.000Z
2021-04-07T15:01:00.000Z
lib/militerm/systems/aliases.ex
jgsmith/militerm
c4252d0a93f5620b90750ac2b61baf282e9ef7eb
[ "Apache-2.0" ]
2
2020-04-14T02:17:46.000Z
2021-03-10T11:09:05.000Z
lib/militerm/systems/aliases.ex
jgsmith/militerm
c4252d0a93f5620b90750ac2b61baf282e9ef7eb
[ "Apache-2.0" ]
null
null
null
defmodule Militerm.Systems.Aliases do use Militerm.ECS.System alias Militerm.Systems.Entity defcommand alias_(arg), for: %{"this" => {:thing, entity_id} = this}, as: "alias" do case String.split(arg, ~r{\s+}, parts: 2, trim: true) do [word, definition] -> Militerm.Components.Aliases.set(entity_id, word, definition) Entity.receive_message(this, "cmd", "Added definition for #{word}.") [word] -> case Militerm.Components.Aliases.get(entity_id) do nil -> Entity.receive_message(this, "cmd", "There is no such alias.") map -> case Map.get(map, word) do nil -> Entity.receive_message(this, "cmd", "There is no such alias.") definition -> show_alias(this, word, definition) end end [] -> list_aliases(this) end end defcommand unalias(word), for: %{"this" => {:thing, entity_id} = this} do Militerm.Components.Aliases.remove(entity_id, word) Entity.receive_message(this, "cmd", "Removed definition of #{word}.") end defcommand aliases(_), for: %{"this" => this} do list_aliases(this) end def list_aliases({:thing, entity_id} = this) do case Militerm.Components.Aliases.get(entity_id) do nil -> Entity.receive_message(this, "cmd", "You have no aliases.") map when map_size(map) == 0 -> Entity.receive_message(this, "cmd", "You have no aliases.") map -> for {word, definition} <- Enum.sort(map) do show_alias(this, word, definition) end end end def show_alias(this, word, definition) do Entity.receive_message(this, "cmd", "#{word} : #{definition}") end end
28.403226
78
0.59682
797b9b57d72d7dfcb9f50eb52590f389dc767f47
152,829
ex
Elixir
lib/elixir/lib/kernel.ex
goalves/elixir
75726d5611413ee45cb5235b1698944b72efa244
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel.ex
goalves/elixir
75726d5611413ee45cb5235b1698944b72efa244
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel.ex
goalves/elixir
75726d5611413ee45cb5235b1698944b72efa244
[ "Apache-2.0" ]
null
null
null
# Use elixir_bootstrap module to be able to bootstrap Kernel. # The bootstrap module provides simpler implementations of the # functions removed, simple enough to bootstrap. import Kernel, except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2] import :elixir_bootstrap defmodule Kernel do @moduledoc """ `Kernel` is Elixir's default environment. It mainly consists of: * basic language primitives, such as arithmetic operators, spawning of processes, data type handling, and others * macros for control-flow and defining new functionality (modules, functions, and the like) * guard checks for augmenting pattern matching You can invoke `Kernel` functions and macros anywhere in Elixir code without the use of the `Kernel.` prefix since they have all been automatically imported. For example, in IEx, you can call: iex> is_number(13) true If you don't want to import a function or macro from `Kernel`, use the `:except` option and then list the function/macro by arity: import Kernel, except: [if: 2, unless: 2] See `Kernel.SpecialForms.import/2` for more information on importing. Elixir also has special forms that are always imported and cannot be skipped. These are described in `Kernel.SpecialForms`. ## The standard library `Kernel` provides the basic capabilities the Elixir standard library is built on top of. It is recommended to explore the standard library for advanced functionality. Here are the main groups of modules in the standard library (this list is not a complete reference, see the documentation sidebar for all entries). ### Built-in types The following modules handle Elixir built-in data types: * `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms) * `Float` - numbers with floating point precision * `Function` - a reference to code chunk, created with the `fn/1` special form * `Integer` - whole numbers (not fractions) * `List` - collections of a variable number of elements (linked lists) * `Map` - collections of key-value pairs * `Process` - light-weight threads of execution * `Port` - mechanisms to interact with the external world * `Tuple` - collections of a fixed number of elements There are two data types without an accompanying module: * Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>/1`. When the number of bits is divisible by 8, they are called binaries and can be manipulated with Erlang's `:binary` module * Reference - a unique value in the runtime system, created with `make_ref/0` ### Data types Elixir also provides other data types that are built on top of the types listed above. Some of them are: * `Date` - `year-month-day` structs in a given calendar * `DateTime` - date and time with time zone in a given calendar * `Exception` - data raised from errors and unexpected scenarios * `MapSet` - unordered collections of unique elements * `NaiveDateTime` - date and time without time zone in a given calendar * `Keyword` - lists of two-element tuples, often representing optional values * `Range` - inclusive ranges between two integers * `Regex` - regular expressions * `String` - UTF-8 encoded binaries representing characters * `Time` - `hour:minute:second` structs in a given calendar * `URI` - representation of URIs that identify resources * `Version` - representation of versions and requirements ### System modules Modules that interface with the underlying system, such as: * `IO` - handles input and output * `File` - interacts with the underlying file system * `Path` - manipulates file system paths * `System` - reads and writes system information ### Protocols Protocols add polymorphic dispatch to Elixir. They are contracts implementable by data types. See `Protocol` for more information on protocols. Elixir provides the following protocols in the standard library: * `Collectable` - collects data into a data type * `Enumerable` - handles collections in Elixir. The `Enum` module provides eager functions for working with collections, the `Stream` module provides lazy functions * `Inspect` - converts data types into their programming language representation * `List.Chars` - converts data types to their outside world representation as charlists (non-programming based) * `String.Chars` - converts data types to their outside world representation as strings (non-programming based) ### Process-based and application-centric functionality The following modules build on top of processes to provide concurrency, fault-tolerance, and more. * `Agent` - a process that encapsulates mutable state * `Application` - functions for starting, stopping and configuring applications * `GenServer` - a generic client-server API * `Registry` - a key-value process-based storage * `Supervisor` - a process that is responsible for starting, supervising and shutting down other processes * `Task` - a process that performs computations * `Task.Supervisor` - a supervisor for managing tasks exclusively ### Supporting documents Elixir documentation also includes supporting documents under the "Pages" section. Those are: * [Compatibility and Deprecations](compatibility-and-deprecations.md) - lists compatibility between every Elixir version and Erlang/OTP, release schema; lists all deprecated functions, when they were deprecated and alternatives * [Library Guidelines](library-guidelines.md) - general guidelines, anti-patterns, and rules for those writing libraries * [Naming Conventions](naming-conventions.md) - naming conventions for Elixir code * [Operators](operators.md) - lists all Elixir operators and their precedences * [Patterns and Guards](patterns-and-guards.md) - an introduction to patterns, guards, and extensions * [Syntax Reference](syntax-reference.md) - the language syntax reference * [Typespecs](typespecs.md)- types and function specifications, including list of types * [Unicode Syntax](unicode-syntax.md) - outlines Elixir support for Unicode * [Writing Documentation](writing-documentation.md) - guidelines for writing documentation in Elixir ## Guards This module includes the built-in guards used by Elixir developers. They are a predefined set of functions and macros that augment pattern matching, typically invoked after the `when` operator. For example: def drive(%User{age: age}) when age >= 16 do ... end The clause above will only be invoked if the user's age is more than or equal to 16. Guards also support joining multiple conditions with `and` and `or`. The whole guard is true if all guard expressions will evaluate to `true`. A more complete introduction to guards is available [in the "Patterns and Guards" page](patterns-and-guards.md). ## Inlining Some of the functions described in this module are inlined by the Elixir compiler into their Erlang counterparts in the [`:erlang` module](http://www.erlang.org/doc/man/erlang.html). Those functions are called BIFs (built-in internal functions) in Erlang-land and they exhibit interesting properties, as some of them are allowed in guards and others are used for compiler optimizations. Most of the inlined functions can be seen in effect when capturing the function: iex> &Kernel.is_atom/1 &:erlang.is_atom/1 Those functions will be explicitly marked in their docs as "inlined by the compiler". ## Truthy and falsy values Besides the booleans `true` and `false`, Elixir has the concept of a "truthy" or "falsy" value. * a value is truthy when it is neither `false` nor `nil` * a value is falsy when it is either `false` or `nil` Elixir has functions, like `and/2`, that *only* work with booleans, but also functions that work with these truthy/falsy values, like `&&/2` and `!/1`. ### Examples We can check the truthiness of a value by using the `!/1` function twice. Truthy values: iex> !!true true iex> !!5 true iex> !![1,2] true iex> !!"foo" true Falsy values (of which there are exactly two): iex> !!false false iex> !!nil false """ # We need this check only for bootstrap purposes. # Once Kernel is loaded and we recompile, it is a no-op. @compile {:inline, bootstrapped?: 1} case :code.ensure_loaded(Kernel) do {:module, _} -> defp bootstrapped?(_), do: true {:error, _} -> defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module} end ## Delegations to Erlang with inlining (macros) @doc """ Returns an integer or float which is the arithmetical absolute value of `number`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> abs(-3.33) 3.33 iex> abs(-3) 3 """ @doc guard: true @spec abs(number) :: number def abs(number) do :erlang.abs(number) end @doc """ Invokes the given anonymous function `fun` with the list of arguments `args`. Inlined by the compiler. ## Examples iex> apply(fn x -> x * 2 end, [2]) 4 """ @spec apply(fun, [any]) :: any def apply(fun, args) do :erlang.apply(fun, args) end @doc """ Invokes the given function from `module` with the list of arguments `args`. `apply/3` is used to invoke functions where the module, function name or arguments are defined dynamically at runtime. For this reason, you can't invoke macros using `apply/3`, only functions. Inlined by the compiler. ## Examples iex> apply(Enum, :reverse, [[1, 2, 3]]) [3, 2, 1] """ @spec apply(module, function_name :: atom, [any]) :: any def apply(module, function_name, args) do :erlang.apply(module, function_name, args) end @doc """ Extracts the part of the binary starting at `start` with length `length`. Binaries are zero-indexed. If `start` or `length` reference in any way outside the binary, an `ArgumentError` exception is raised. Allowed in guard tests. Inlined by the compiler. ## Examples iex> binary_part("foo", 1, 2) "oo" A negative `length` can be used to extract bytes that come *before* the byte at `start`: iex> binary_part("Hello", 5, -3) "llo" """ @doc guard: true @spec binary_part(binary, non_neg_integer, integer) :: binary def binary_part(binary, start, length) do :erlang.binary_part(binary, start, length) end @doc """ Returns an integer which is the size in bits of `bitstring`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> bit_size(<<433::16, 3::3>>) 19 iex> bit_size(<<1, 2, 3>>) 24 """ @doc guard: true @spec bit_size(bitstring) :: non_neg_integer def bit_size(bitstring) do :erlang.bit_size(bitstring) end @doc """ Returns the number of bytes needed to contain `bitstring`. That is, if the number of bits in `bitstring` is not divisible by 8, the resulting number of bytes will be rounded up (by excess). This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> byte_size(<<433::16, 3::3>>) 3 iex> byte_size(<<1, 2, 3>>) 3 """ @doc guard: true @spec byte_size(bitstring) :: non_neg_integer def byte_size(bitstring) do :erlang.byte_size(bitstring) end @doc """ Returns the smallest integer greater than or equal to `number`. If you want to perform ceil operation on other decimal places, use `Float.ceil/2` instead. Allowed in guard tests. Inlined by the compiler. """ @doc since: "1.8.0", guard: true @spec ceil(number) :: integer def ceil(number) do :erlang.ceil(number) end @doc """ Performs an integer division. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. `div/2` performs *truncated* integer division. This means that the result is always rounded towards zero. If you want to perform floored integer division (rounding towards negative infinity), use `Integer.floor_div/2` instead. Allowed in guard tests. Inlined by the compiler. ## Examples div(5, 2) #=> 2 div(6, -4) #=> -1 div(-99, 2) #=> -49 div(100, 0) ** (ArithmeticError) bad argument in arithmetic expression """ @doc guard: true @spec div(integer, neg_integer | pos_integer) :: integer def div(dividend, divisor) do :erlang.div(dividend, divisor) end @doc """ Stops the execution of the calling process with the given reason. Since evaluating this function causes the process to terminate, it has no return value. Inlined by the compiler. ## Examples When a process reaches its end, by default it exits with reason `:normal`. You can also call `exit/1` explicitly if you want to terminate a process but not signal any failure: exit(:normal) In case something goes wrong, you can also use `exit/1` with a different reason: exit(:seems_bad) If the exit reason is not `:normal`, all the processes linked to the process that exited will crash (unless they are trapping exits). ## OTP exits Exits are used by the OTP to determine if a process exited abnormally or not. The following exits are considered "normal": * `exit(:normal)` * `exit(:shutdown)` * `exit({:shutdown, term})` Exiting with any other reason is considered abnormal and treated as a crash. This means the default supervisor behaviour kicks in, error reports are emitted, and so forth. This behaviour is relied on in many different places. For example, `ExUnit` uses `exit(:shutdown)` when exiting the test process to signal linked processes, supervision trees and so on to politely shut down too. ## CLI exits Building on top of the exit signals mentioned above, if the process started by the command line exits with any of the three reasons above, its exit is considered normal and the Operating System process will exit with status 0. It is, however, possible to customize the operating system exit signal by invoking: exit({:shutdown, integer}) This will cause the operating system process to exit with the status given by `integer` while signaling all linked Erlang processes to politely shut down. Any other exit reason will cause the operating system process to exit with status `1` and linked Erlang processes to crash. """ @spec exit(term) :: no_return def exit(reason) do :erlang.exit(reason) end @doc """ Returns the largest integer smaller than or equal to `number`. If you want to perform floor operation on other decimal places, use `Float.floor/2` instead. Allowed in guard tests. Inlined by the compiler. """ @doc since: "1.8.0", guard: true @spec floor(number) :: integer def floor(number) do :erlang.floor(number) end @doc """ Returns the head of a list. Raises `ArgumentError` if the list is empty. It works with improper lists. Allowed in guard tests. Inlined by the compiler. ## Examples hd([1, 2, 3, 4]) #=> 1 hd([]) ** (ArgumentError) argument error hd([1 | 2]) #=> 1 """ @doc guard: true @spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term def hd(list) do :erlang.hd(list) end @doc """ Returns `true` if `term` is an atom; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_atom(term) :: boolean def is_atom(term) do :erlang.is_atom(term) end @doc """ Returns `true` if `term` is a binary; otherwise returns `false`. A binary always contains a complete number of bytes. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_binary("foo") true iex> is_binary(<<1::3>>) false """ @doc guard: true @spec is_binary(term) :: boolean def is_binary(term) do :erlang.is_binary(term) end @doc """ Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_bitstring("foo") true iex> is_bitstring(<<1::3>>) true """ @doc guard: true @spec is_bitstring(term) :: boolean def is_bitstring(term) do :erlang.is_bitstring(term) end @doc """ Returns `true` if `term` is either the atom `true` or the atom `false` (i.e., a boolean); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_boolean(term) :: boolean def is_boolean(term) do :erlang.is_boolean(term) end @doc """ Returns `true` if `term` is a floating-point number; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_float(term) :: boolean def is_float(term) do :erlang.is_float(term) end @doc """ Returns `true` if `term` is a function; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_function(term) :: boolean def is_function(term) do :erlang.is_function(term) end @doc """ Returns `true` if `term` is a function that can be applied with `arity` number of arguments; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_function(fn x -> x * 2 end, 1) true iex> is_function(fn x -> x * 2 end, 2) false """ @doc guard: true @spec is_function(term, non_neg_integer) :: boolean def is_function(term, arity) do :erlang.is_function(term, arity) end @doc """ Returns `true` if `term` is an integer; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_integer(term) :: boolean def is_integer(term) do :erlang.is_integer(term) end @doc """ Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_list(term) :: boolean def is_list(term) do :erlang.is_list(term) end @doc """ Returns `true` if `term` is either an integer or a floating-point number; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_number(term) :: boolean def is_number(term) do :erlang.is_number(term) end @doc """ Returns `true` if `term` is a PID (process identifier); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_pid(term) :: boolean def is_pid(term) do :erlang.is_pid(term) end @doc """ Returns `true` if `term` is a port identifier; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_port(term) :: boolean def is_port(term) do :erlang.is_port(term) end @doc """ Returns `true` if `term` is a reference; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_reference(term) :: boolean def is_reference(term) do :erlang.is_reference(term) end @doc """ Returns `true` if `term` is a tuple; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_tuple(term) :: boolean def is_tuple(term) do :erlang.is_tuple(term) end @doc """ Returns `true` if `term` is a map; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_map(term) :: boolean def is_map(term) do :erlang.is_map(term) end @doc """ Returns `true` if `key` is a key in `map`; otherwise returns `false`. It raises `BadMapError` if the first element is not a map. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true, since: "1.10.0" @spec is_map_key(map, term) :: boolean def is_map_key(map, key) do :erlang.is_map_key(key, map) end @doc """ Returns the length of `list`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9]) 9 """ @doc guard: true @spec length(list) :: non_neg_integer def length(list) do :erlang.length(list) end @doc """ Returns an almost unique reference. The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes. Inlined by the compiler. ## Examples make_ref() #=> #Reference<0.0.0.135> """ @spec make_ref() :: reference def make_ref() do :erlang.make_ref() end @doc """ Returns the size of a map. The size of a map is the number of key-value pairs that the map contains. This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> map_size(%{a: "foo", b: "bar"}) 2 """ @doc guard: true @spec map_size(map) :: non_neg_integer def map_size(map) do :erlang.map_size(map) end @doc """ Returns the biggest of the two given terms according to Erlang's term ordering. If the terms compare equal, the first one is returned. Inlined by the compiler. ## Examples iex> max(1, 2) 2 iex> max(:a, :b) :b Using Erlang's term ordering means that comparisons are structural and not semantic. For example, when comparing dates: iex> max(~D[2017-03-31], ~D[2017-04-01]) ~D[2017-03-31] In the example above, `max/2` returned March 31st instead of April 1st because the structural comparison compares the day before the year. In such cases it is common for modules to provide functions such as `Date.compare/2` that perform semantic comparison. """ @spec max(first, second) :: first | second when first: term, second: term def max(first, second) do :erlang.max(first, second) end @doc """ Returns the smallest of the two given terms according to Erlang's term ordering. If the terms compare equal, the first one is returned. Inlined by the compiler. ## Examples iex> min(1, 2) 1 iex> min("foo", "bar") "bar" Using Erlang's term ordering means that comparisons are structural and not semantic. For example, when comparing dates: iex> min(~D[2017-03-31], ~D[2017-04-01]) ~D[2017-04-01] In the example above, `min/2` returned April 1st instead of March 31st because the structural comparison compares the day before the year. In such cases it is common for modules to provide functions such as `Date.compare/2` that perform semantic comparison. """ @spec min(first, second) :: first | second when first: term, second: term def min(first, second) do :erlang.min(first, second) end @doc """ Returns an atom representing the name of the local node. If the node is not alive, `:nonode@nohost` is returned instead. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec node() :: node def node do :erlang.node() end @doc """ Returns the node where the given argument is located. The argument can be a PID, a reference, or a port. If the local node is not alive, `:nonode@nohost` is returned. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec node(pid | reference | port) :: node def node(arg) do :erlang.node(arg) end @doc """ Computes the remainder of an integer division. `rem/2` uses truncated division, which means that the result will always have the sign of the `dividend`. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> rem(5, 2) 1 iex> rem(6, -4) 2 """ @doc guard: true @spec rem(integer, neg_integer | pos_integer) :: integer def rem(dividend, divisor) do :erlang.rem(dividend, divisor) end @doc """ Rounds a number to the nearest integer. If the number is equidistant to the two nearest integers, rounds away from zero. Allowed in guard tests. Inlined by the compiler. ## Examples iex> round(5.6) 6 iex> round(5.2) 5 iex> round(-9.9) -10 iex> round(-9) -9 iex> round(2.5) 3 iex> round(-2.5) -3 """ @doc guard: true @spec round(number) :: integer def round(number) do :erlang.round(number) end @doc """ Sends a message to the given `dest` and returns the message. `dest` may be a remote or local PID, a local port, a locally registered name, or a tuple in the form of `{registered_name, node}` for a registered name at another node. Inlined by the compiler. ## Examples iex> send(self(), :hello) :hello """ @spec send(dest :: Process.dest(), message) :: message when message: any def send(dest, message) do :erlang.send(dest, message) end @doc """ Returns the PID (process identifier) of the calling process. Allowed in guard clauses. Inlined by the compiler. """ @doc guard: true @spec self() :: pid def self() do :erlang.self() end @doc """ Spawns the given function and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() child = spawn(fn -> send(current, {self(), 1 + 2}) end) receive do {^child, 3} -> IO.puts("Received 3 back") end """ @spec spawn((() -> any)) :: pid def spawn(fun) do :erlang.spawn(fun) end @doc """ Spawns the given function `fun` from the given `module` passing it the given `args` and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. Inlined by the compiler. ## Examples spawn(SomeModule, :function, [1, 2, 3]) """ @spec spawn(module, atom, list) :: pid def spawn(module, fun, args) do :erlang.spawn(module, fun, args) end @doc """ Spawns the given function, links it to the current process, and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. For more information on linking, check `Process.link/1`. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() child = spawn_link(fn -> send(current, {self(), 1 + 2}) end) receive do {^child, 3} -> IO.puts("Received 3 back") end """ @spec spawn_link((() -> any)) :: pid def spawn_link(fun) do :erlang.spawn_link(fun) end @doc """ Spawns the given function `fun` from the given `module` passing it the given `args`, links it to the current process, and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. For more information on linking, check `Process.link/1`. Inlined by the compiler. ## Examples spawn_link(SomeModule, :function, [1, 2, 3]) """ @spec spawn_link(module, atom, list) :: pid def spawn_link(module, fun, args) do :erlang.spawn_link(module, fun, args) end @doc """ Spawns the given function, monitors it and returns its PID and monitoring reference. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() spawn_monitor(fn -> send(current, {self(), 1 + 2}) end) """ @spec spawn_monitor((() -> any)) :: {pid, reference} def spawn_monitor(fun) do :erlang.spawn_monitor(fun) end @doc """ Spawns the given module and function passing the given args, monitors it and returns its PID and monitoring reference. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. Inlined by the compiler. ## Examples spawn_monitor(SomeModule, :function, [1, 2, 3]) """ @spec spawn_monitor(module, atom, list) :: {pid, reference} def spawn_monitor(module, fun, args) do :erlang.spawn_monitor(module, fun, args) end @doc """ A non-local return from a function. Check `Kernel.SpecialForms.try/1` for more information. Inlined by the compiler. """ @spec throw(term) :: no_return def throw(term) do :erlang.throw(term) end @doc """ Returns the tail of a list. Raises `ArgumentError` if the list is empty. It works with improper lists. Allowed in guard tests. Inlined by the compiler. ## Examples tl([1, 2, 3, :go]) #=> [2, 3, :go] tl([]) ** (ArgumentError) argument error tl([:one]) #=> [] tl([:a, :b | :c]) #=> [:b | :c] tl([:a | %{b: 1}]) #=> %{b: 1} """ @doc guard: true @spec tl(nonempty_maybe_improper_list(elem, tail)) :: maybe_improper_list(elem, tail) | tail when elem: term, tail: term def tl(list) do :erlang.tl(list) end @doc """ Returns the integer part of `number`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> trunc(5.4) 5 iex> trunc(-5.99) -5 iex> trunc(-5) -5 """ @doc guard: true @spec trunc(number) :: integer def trunc(number) do :erlang.trunc(number) end @doc """ Returns the size of a tuple. This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> tuple_size({:a, :b, :c}) 3 """ @doc guard: true @spec tuple_size(tuple) :: non_neg_integer def tuple_size(tuple) do :erlang.tuple_size(tuple) end @doc """ Arithmetic addition operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 + 2 3 """ @doc guard: true @spec integer + integer :: integer @spec float + float :: float @spec integer + float :: float @spec float + integer :: float def left + right do :erlang.+(left, right) end @doc """ Arithmetic subtraction operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 - 2 -1 """ @doc guard: true @spec integer - integer :: integer @spec float - float :: float @spec integer - float :: float @spec float - integer :: float def left - right do :erlang.-(left, right) end @doc """ Arithmetic positive unary operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> +1 1 """ @doc guard: true @spec +integer :: integer @spec +float :: float def +value do :erlang.+(value) end @doc """ Arithmetic negative unary operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> -2 -2 """ @doc guard: true @spec -0 :: 0 @spec -pos_integer :: neg_integer @spec -neg_integer :: pos_integer @spec -float :: float def -value do :erlang.-(value) end @doc """ Arithmetic multiplication operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 * 2 2 """ @doc guard: true @spec integer * integer :: integer @spec float * float :: float @spec integer * float :: float @spec float * integer :: float def left * right do :erlang.*(left, right) end @doc """ Arithmetic division operator. The result is always a float. Use `div/2` and `rem/2` if you want an integer division or the remainder. Raises `ArithmeticError` if `right` is 0 or 0.0. Allowed in guard tests. Inlined by the compiler. ## Examples 1 / 2 #=> 0.5 -3.0 / 2.0 #=> -1.5 5 / 1 #=> 5.0 7 / 0 ** (ArithmeticError) bad argument in arithmetic expression """ @doc guard: true @spec number / number :: float def left / right do :erlang./(left, right) end @doc """ List concatenation operator. Concatenates a proper list and a term, returning a list. The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly appending to lists of arbitrary length, for example, `list ++ [element]`. Instead, consider prepending via `[element | rest]` and then reversing. If the `right` operand is not a proper list, it returns an improper list. If the `left` operand is not a proper list, it raises `ArgumentError`. Inlined by the compiler. ## Examples iex> [1] ++ [2, 3] [1, 2, 3] iex> 'foo' ++ 'bar' 'foobar' # returns an improper list iex> [1] ++ 2 [1 | 2] # returns a proper list iex> [1] ++ [2] [1, 2] # improper list on the right will return an improper list iex> [1] ++ [2 | 3] [1, 2 | 3] """ @spec list ++ term :: maybe_improper_list def left ++ right do :erlang.++(left, right) end @doc """ List subtraction operator. Removes the first occurrence of an element on the left list for each element on the right. Before Erlang/OTP 22, the complexity of `a -- b` was proportional to `length(a) * length(b)`, meaning that it would be very slow if both `a` and `b` were long lists. In such cases, consider converting each list to a `MapSet` and using `MapSet.difference/2`. As of Erlang/OTP 22, this operation is significantly faster even if both lists are very long, and using `--/2` is usually faster and uses less memory than using the `MapSet`-based alternative mentioned above. See also the [Erlang efficiency guide](https://erlang.org/doc/efficiency_guide/retired_myths.html). Inlined by the compiler. ## Examples iex> [1, 2, 3] -- [1, 2] [3] iex> [1, 2, 3, 2, 1] -- [1, 2, 2] [3, 1] The `--/2` operator is right associative, meaning: iex> [1, 2, 3] -- [2] -- [3] [1, 3] As it is equivalent to: iex> [1, 2, 3] -- ([2] -- [3]) [1, 3] """ @spec list -- list :: list def left -- right do :erlang.--(left, right) end @doc """ Strictly boolean "not" operator. `value` must be a boolean; if it's not, an `ArgumentError` exception is raised. Allowed in guard tests. Inlined by the compiler. ## Examples iex> not false true """ @doc guard: true @spec not true :: false @spec not false :: true def not value do :erlang.not(value) end @doc """ Less-than operator. Returns `true` if `left` is less than `right`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 < 2 true """ @doc guard: true @spec term < term :: boolean def left < right do :erlang.<(left, right) end @doc """ Greater-than operator. Returns `true` if `left` is more than `right`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 > 2 false """ @doc guard: true @spec term > term :: boolean def left > right do :erlang.>(left, right) end @doc """ Less-than or equal to operator. Returns `true` if `left` is less than or equal to `right`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 <= 2 true """ @doc guard: true @spec term <= term :: boolean def left <= right do :erlang."=<"(left, right) end @doc """ Greater-than or equal to operator. Returns `true` if `left` is more than or equal to `right`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 >= 2 false """ @doc guard: true @spec term >= term :: boolean def left >= right do :erlang.>=(left, right) end @doc """ Equal to operator. Returns `true` if the two terms are equal. This operator considers 1 and 1.0 to be equal. For stricter semantics, use `===/2` instead. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 == 2 false iex> 1 == 1.0 true """ @doc guard: true @spec term == term :: boolean def left == right do :erlang.==(left, right) end @doc """ Not equal to operator. Returns `true` if the two terms are not equal. This operator considers 1 and 1.0 to be equal. For match comparison, use `!==/2` instead. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 != 2 true iex> 1 != 1.0 false """ @doc guard: true @spec term != term :: boolean def left != right do :erlang."/="(left, right) end @doc """ Strictly equal to operator. Returns `true` if the two terms are exactly equal. The terms are only considered to be exactly equal if they have the same value and are of the same type. For example, `1 == 1.0` returns `true`, but since they are of different types, `1 === 1.0` returns `false`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 === 2 false iex> 1 === 1.0 false """ @doc guard: true @spec term === term :: boolean def left === right do :erlang."=:="(left, right) end @doc """ Strictly not equal to operator. Returns `true` if the two terms are not exactly equal. See `===/2` for a definition of what is considered "exactly equal". All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 !== 2 true iex> 1 !== 1.0 true """ @doc guard: true @spec term !== term :: boolean def left !== right do :erlang."=/="(left, right) end @doc """ Gets the element at the zero-based `index` in `tuple`. It raises `ArgumentError` when index is negative or it is out of range of the tuple elements. Allowed in guard tests. Inlined by the compiler. ## Examples tuple = {:foo, :bar, 3} elem(tuple, 1) #=> :bar elem({}, 0) ** (ArgumentError) argument error elem({:foo, :bar}, 2) ** (ArgumentError) argument error """ @doc guard: true @spec elem(tuple, non_neg_integer) :: term def elem(tuple, index) do :erlang.element(index + 1, tuple) end @doc """ Puts `value` at the given zero-based `index` in `tuple`. Inlined by the compiler. ## Examples iex> tuple = {:foo, :bar, 3} iex> put_elem(tuple, 0, :baz) {:baz, :bar, 3} """ @spec put_elem(tuple, non_neg_integer, term) :: tuple def put_elem(tuple, index, value) do :erlang.setelement(index + 1, tuple, value) end ## Implemented in Elixir defp optimize_boolean({:case, meta, args}) do {:case, [{:optimize_boolean, true} | meta], args} end @doc """ Strictly boolean "or" operator. If `left` is `true`, returns `true`; otherwise returns `right`. Requires only the `left` operand to be a boolean since it short-circuits. If the `left` operand is not a boolean, an `ArgumentError` exception is raised. Allowed in guard tests. ## Examples iex> true or false true iex> false or 42 42 iex> 42 or false ** (BadBooleanError) expected a boolean on left-side of "or", got: 42 """ @doc guard: true defmacro left or right do case __CALLER__.context do nil -> build_boolean_check(:or, left, true, right) :match -> invalid_match!(:or) :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right))) end end @doc """ Strictly boolean "and" operator. If `left` is `false`, returns `false`; otherwise returns `right`. Requires only the `left` operand to be a boolean since it short-circuits. If the `left` operand is not a boolean, an `ArgumentError` exception is raised. Allowed in guard tests. ## Examples iex> true and false false iex> true and "yay!" "yay!" iex> "yay!" and true ** (BadBooleanError) expected a boolean on left-side of "and", got: "yay!" """ @doc guard: true defmacro left and right do case __CALLER__.context do nil -> build_boolean_check(:and, left, right, false) :match -> invalid_match!(:and) :guard -> quote(do: :erlang.andalso(unquote(left), unquote(right))) end end defp build_boolean_check(operator, check, true_clause, false_clause) do optimize_boolean( quote do case unquote(check) do false -> unquote(false_clause) true -> unquote(true_clause) other -> :erlang.error({:badbool, unquote(operator), other}) end end ) end @doc """ Boolean "not" operator. Receives any value (not just booleans) and returns `true` if `value` is `false` or `nil`; returns `false` otherwise. Not allowed in guard clauses. ## Examples iex> !Enum.empty?([]) false iex> !List.first([]) true """ defmacro !value defmacro !{:!, _, [value]} do assert_no_match_or_guard_scope(__CALLER__.context, "!") optimize_boolean( quote do case unquote(value) do x when :"Elixir.Kernel".in(x, [false, nil]) -> false _ -> true end end ) end defmacro !value do assert_no_match_or_guard_scope(__CALLER__.context, "!") optimize_boolean( quote do case unquote(value) do x when :"Elixir.Kernel".in(x, [false, nil]) -> true _ -> false end end ) end @doc """ Binary concatenation operator. Concatenates two binaries. ## Examples iex> "foo" <> "bar" "foobar" The `<>/2` operator can also be used in pattern matching (and guard clauses) as long as the left argument is a literal binary: iex> "foo" <> x = "foobar" iex> x "bar" `x <> "bar" = "foobar"` would have resulted in a `CompileError` exception. """ defmacro left <> right do concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__) quote(do: <<unquote_splicing(concats)>>) end # Extracts concatenations in order to optimize many # concatenations into one single clause. defp extract_concatenations({:<>, _, [left, right]}, caller) do [wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)] end defp extract_concatenations(other, caller) do [wrap_concatenation(other, :right, caller)] end defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do binary end defp wrap_concatenation(literal, _side, _caller) when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do :erlang.error( ArgumentError.exception( "expected binary argument in <> operator but got: #{Macro.to_string(literal)}" ) ) end defp wrap_concatenation(other, side, caller) do expanded = expand_concat_argument(other, side, caller) {:"::", [], [expanded, {:binary, [], nil}]} end defp expand_concat_argument(arg, :left, %{context: :match} = caller) do expanded_arg = case bootstrapped?(Macro) do true -> Macro.expand(arg, caller) false -> arg end case expanded_arg do {var, _, nil} when is_atom(var) -> invalid_concat_left_argument_error(Atom.to_string(var)) {:^, _, [{var, _, nil}]} when is_atom(var) -> invalid_concat_left_argument_error("^#{Atom.to_string(var)}") _ -> expanded_arg end end defp expand_concat_argument(arg, _, _) do arg end defp invalid_concat_left_argument_error(arg) do :erlang.error( ArgumentError.exception( "the left argument of <> operator inside a match should always be a literal " <> "binary because its size can't be verified. Got: #{arg}" ) ) end @doc """ Raises an exception. If the argument `msg` is a binary, it raises a `RuntimeError` exception using the given argument as message. If `msg` is an atom, it just calls `raise/2` with the atom as the first argument and `[]` as the second argument. If `msg` is an exception struct, it is raised as is. If `msg` is anything else, `raise` will fail with an `ArgumentError` exception. ## Examples iex> raise "oops" ** (RuntimeError) oops try do 1 + :foo rescue x in [ArithmeticError] -> IO.puts("that was expected") raise x end """ defmacro raise(message) do # Try to figure out the type at compilation time # to avoid dead code and make Dialyzer happy. message = case not is_binary(message) and bootstrapped?(Macro) do true -> Macro.expand(message, __CALLER__) false -> message end case message do message when is_binary(message) -> quote do :erlang.error(RuntimeError.exception(unquote(message))) end {:<<>>, _, _} = message -> quote do :erlang.error(RuntimeError.exception(unquote(message))) end alias when is_atom(alias) -> quote do :erlang.error(unquote(alias).exception([])) end _ -> quote do :erlang.error(Kernel.Utils.raise(unquote(message))) end end end @doc """ Raises an exception. Calls the `exception/1` function on the given argument (which has to be a module name like `ArgumentError` or `RuntimeError`) passing `attrs` as the attributes in order to retrieve the exception struct. Any module that contains a call to the `defexception/1` macro automatically implements the `c:Exception.exception/1` callback expected by `raise/2`. For more information, see `defexception/1`. ## Examples iex> raise(ArgumentError, "Sample") ** (ArgumentError) Sample """ defmacro raise(exception, attributes) do quote do :erlang.error(unquote(exception).exception(unquote(attributes))) end end @doc """ Raises an exception preserving a previous stacktrace. Works like `raise/1` but does not generate a new stacktrace. Note that `__STACKTRACE__` can be used inside catch/rescue to retrieve the current stacktrace. ## Examples try do raise "oops" rescue exception -> reraise exception, __STACKTRACE__ end """ defmacro reraise(message, stacktrace) do # Try to figure out the type at compilation time # to avoid dead code and make Dialyzer happy. case Macro.expand(message, __CALLER__) do message when is_binary(message) -> quote do :erlang.error( :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) ) end {:<<>>, _, _} = message -> quote do :erlang.error( :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) ) end alias when is_atom(alias) -> quote do :erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace))) end message -> quote do :erlang.error( :erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace)) ) end end end @doc """ Raises an exception preserving a previous stacktrace. `reraise/3` works like `reraise/2`, except it passes arguments to the `exception/1` function as explained in `raise/2`. ## Examples try do raise "oops" rescue exception -> reraise WrapperError, [exception: exception], __STACKTRACE__ end """ defmacro reraise(exception, attributes, stacktrace) do quote do :erlang.raise( :error, unquote(exception).exception(unquote(attributes)), unquote(stacktrace) ) end end @doc """ Text-based match operator. Matches the term on the `left` against the regular expression or string on the `right`. If `right` is a regular expression, returns `true` if `left` matches right. If `right` is a string, returns `true` if `left` contains `right`. ## Examples iex> "abcd" =~ ~r/c(d)/ true iex> "abcd" =~ ~r/e/ false iex> "abcd" =~ ~r// true iex> "abcd" =~ "bc" true iex> "abcd" =~ "ad" false iex> "abcd" =~ "abcd" true iex> "abcd" =~ "" true """ @spec String.t() =~ (String.t() | Regex.t()) :: boolean def left =~ "" when is_binary(left), do: true def left =~ right when is_binary(left) and is_binary(right) do :binary.match(left, right) != :nomatch end def left =~ right when is_binary(left) do Regex.match?(right, left) end @doc ~S""" Inspects the given argument according to the `Inspect` protocol. The second argument is a keyword list with options to control inspection. ## Options `inspect/2` accepts a list of options that are internally translated to an `Inspect.Opts` struct. Check the docs for `Inspect.Opts` to see the supported options. ## Examples iex> inspect(:foo) ":foo" iex> inspect([1, 2, 3, 4, 5], limit: 3) "[1, 2, 3, ...]" iex> inspect([1, 2, 3], pretty: true, width: 0) "[1,\n 2,\n 3]" iex> inspect("olá" <> <<0>>) "<<111, 108, 195, 161, 0>>" iex> inspect("olá" <> <<0>>, binaries: :as_strings) "\"olá\\0\"" iex> inspect("olá", binaries: :as_binaries) "<<111, 108, 195, 161>>" iex> inspect('bar') "'bar'" iex> inspect([0 | 'bar']) "[0, 98, 97, 114]" iex> inspect(100, base: :octal) "0o144" iex> inspect(100, base: :hex) "0x64" Note that the `Inspect` protocol does not necessarily return a valid representation of an Elixir term. In such cases, the inspected result must start with `#`. For example, inspecting a function will return: inspect(fn a, b -> a + b end) #=> #Function<...> The `Inspect` protocol can be derived to hide certain fields from structs, so they don't show up in logs, inspects and similar. See the "Deriving" section of the documentation of the `Inspect` protocol for more information. """ @spec inspect(Inspect.t(), keyword) :: String.t() def inspect(term, opts \\ []) when is_list(opts) do opts = struct(Inspect.Opts, opts) limit = case opts.pretty do true -> opts.width false -> :infinity end doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts)) IO.iodata_to_binary(Inspect.Algebra.format(doc, limit)) end @doc """ Creates and updates a struct. The `struct` argument may be an atom (which defines `defstruct`) or a `struct` itself. The second argument is any `Enumerable` that emits two-element tuples (key-value pairs) during enumeration. Keys in the `Enumerable` that don't exist in the struct are automatically discarded. Note that keys must be atoms, as only atoms are allowed when defining a struct. If keys in the `Enumerable` are duplicated, the last entry will be taken (same behaviour as `Map.new/1`). This function is useful for dynamically creating and updating structs, as well as for converting maps to structs; in the latter case, just inserting the appropriate `:__struct__` field into the map may not be enough and `struct/2` should be used instead. ## Examples defmodule User do defstruct name: "john" end struct(User) #=> %User{name: "john"} opts = [name: "meg"] user = struct(User, opts) #=> %User{name: "meg"} struct(user, unknown: "value") #=> %User{name: "meg"} struct(User, %{name: "meg"}) #=> %User{name: "meg"} # String keys are ignored struct(User, %{"name" => "meg"}) #=> %User{name: "john"} """ @spec struct(module | struct, Enum.t()) :: struct def struct(struct, fields \\ []) do struct(struct, fields, fn {:__struct__, _val}, acc -> acc {key, val}, acc -> case acc do %{^key => _} -> %{acc | key => val} _ -> acc end end) end @doc """ Similar to `struct/2` but checks for key validity. The function `struct!/2` emulates the compile time behaviour of structs. This means that: * when building a struct, as in `struct!(SomeStruct, key: :value)`, it is equivalent to `%SomeStruct{key: :value}` and therefore this function will check if every given key-value belongs to the struct. If the struct is enforcing any key via `@enforce_keys`, those will be enforced as well; * when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`, it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this function will check if every given key-value belongs to the struct. However, updating structs does not enforce keys, as keys are enforced only when building; """ @spec struct!(module | struct, Enum.t()) :: struct def struct!(struct, fields \\ []) def struct!(struct, fields) when is_atom(struct) do validate_struct!(struct.__struct__(fields), struct, 1) end def struct!(struct, fields) when is_map(struct) do struct(struct, fields, fn {:__struct__, _}, acc -> acc {key, val}, acc -> Map.replace!(acc, key, val) end) end defp struct(struct, [], _fun) when is_atom(struct) do validate_struct!(struct.__struct__(), struct, 0) end defp struct(struct, fields, fun) when is_atom(struct) do struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun) end defp struct(%_{} = struct, [], _fun) do struct end defp struct(%_{} = struct, fields, fun) do Enum.reduce(fields, struct, fun) end defp validate_struct!(%{__struct__: module} = struct, module, _arity) do struct end defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do error_message = "expected struct name returned by #{inspect(module)}.__struct__/#{arity} to be " <> "#{inspect(module)}, got: #{inspect(struct_name)}" :erlang.error(ArgumentError.exception(error_message)) end defp validate_struct!(expr, module, arity) do error_message = "expected #{inspect(module)}.__struct__/#{arity} to return a map with a :__struct__ " <> "key that holds the name of the struct (atom), got: #{inspect(expr)}" :erlang.error(ArgumentError.exception(error_message)) end @doc """ Returns true if `term` is a struct; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_struct(URI.parse("/")) true iex> is_struct(%{}) false """ @doc since: "1.10.0", guard: true defmacro is_struct(term) do case __CALLER__.context do nil -> quote do case unquote(term) do %_{} -> true _ -> false end end :match -> invalid_match!(:is_struct) :guard -> quote do is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and is_atom(:erlang.map_get(:__struct__, unquote(term))) end end end @doc """ Returns true if `term` is a struct of `name`; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_struct(URI.parse("/"), URI) true iex> is_struct(URI.parse("/"), Macro.Env) false """ @doc since: "1.11.0", guard: true defmacro is_struct(term, name) do case __CALLER__.context do nil -> quote do case unquote(name) do name when is_atom(name) -> case unquote(term) do %{__struct__: ^name} -> true _ -> false end _ -> raise ArgumentError end end :match -> invalid_match!(:is_struct) :guard -> quote do is_map(unquote(term)) and (is_atom(unquote(name)) or :fail) and :erlang.is_map_key(:__struct__, unquote(term)) and :erlang.map_get(:__struct__, unquote(term)) == unquote(name) end end end @doc """ Returns true if `term` is an exception; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_exception(%RuntimeError{}) true iex> is_exception(%{}) false """ @doc since: "1.11.0", guard: true defmacro is_exception(term) do case __CALLER__.context do nil -> quote do case unquote(term) do %_{__exception__: true} -> true _ -> false end end :match -> invalid_match!(:is_exception) :guard -> quote do is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and is_atom(:erlang.map_get(:__struct__, unquote(term))) and :erlang.is_map_key(:__exception__, unquote(term)) and :erlang.map_get(:__exception__, unquote(term)) == true end end end @doc """ Returns true if `term` is an exception of `name`; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_exception(%RuntimeError{}, RuntimeError) true iex> is_exception(%RuntimeError{}, Macro.Env) false """ @doc since: "1.11.0", guard: true defmacro is_exception(term, name) do case __CALLER__.context do nil -> quote do case unquote(name) do name when is_atom(name) -> case unquote(term) do %{__struct__: ^name, __exception__: true} -> true _ -> false end _ -> raise ArgumentError end end :match -> invalid_match!(:is_exception) :guard -> quote do is_map(unquote(term)) and (is_atom(unquote(name)) or :fail) and :erlang.is_map_key(:__struct__, unquote(term)) and :erlang.map_get(:__struct__, unquote(term)) == unquote(name) and :erlang.is_map_key(:__exception__, unquote(term)) and :erlang.map_get(:__exception__, unquote(term)) == true end end end @doc """ Gets a value from a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function, which is detailed in a later section. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_in(users, ["john", :age]) 27 In case any of the keys returns `nil`, `nil` will be returned: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_in(users, ["unknown", :age]) nil ## Functions as keys If a key is a function, the function will be invoked passing three arguments: * the operation (`:get`) * the data to be accessed * a function to be invoked next This means `get_in/2` can be extended to provide custom lookups. In the example below, we use a function to get all the maps inside a list: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> all = fn :get, data, next -> Enum.map(data, next) end iex> get_in(users, [all, :age]) [27, 23] If the previous value before invoking the function is `nil`, the function *will* receive `nil` as a value and must handle it accordingly. The `Access` module ships with many convenience accessor functions, like the `all` anonymous function defined above. See `Access.all/0`, `Access.key/2`, and others as examples. """ @spec get_in(Access.t(), nonempty_list(term)) :: term def get_in(data, keys) def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1) def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t)) def get_in(nil, [_]), do: nil def get_in(nil, [_ | t]), do: get_in(nil, t) def get_in(data, [h]), do: Access.get(data, h) def get_in(data, [h | t]), do: get_in(Access.get(data, h), t) @doc """ Puts a value in a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users, ["john", :age], 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} In case any of the entries in the middle returns `nil`, an error will be raised when trying to access it next. """ @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t() def put_in(data, [_ | _] = keys, value) do elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1) end @doc """ Updates a key in a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. `data` is a nested structure (that is, a map, keyword list, or struct that implements the `Access` behaviour). The `fun` argument receives the value of `key` (or `nil` if `key` is not present) and the result replaces the value in the structure. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users, ["john", :age], &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} In case any of the entries in the middle returns `nil`, an error will be raised when trying to access it next. """ @spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t() def update_in(data, [_ | _] = keys, fun) when is_function(fun) do elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1) end @doc """ Gets a value and updates a nested structure. `data` is a nested structure (that is, a map, keyword list, or struct that implements the `Access` behaviour). The `fun` argument receives the value of `key` (or `nil` if `key` is not present) and must return one of the following values: * a two-element tuple `{get_value, new_value}`. In this case, `get_value` is the retrieved value which can possibly be operated on before being returned. `new_value` is the new value to be stored under `key`. * `:pop`, which implies that the current value under `key` should be removed from the structure and returned. This function uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function, which is detailed in a later section. ## Examples This function is useful when there is a need to retrieve the current value (or something calculated in function of the current value) and update it at the same time. For example, it could be used to read the current age of a user while increasing it by one in one pass: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1}) {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} ## Functions as keys If a key is a function, the function will be invoked passing three arguments: * the operation (`:get_and_update`) * the data to be accessed * a function to be invoked next This means `get_and_update_in/3` can be extended to provide custom lookups. The downside is that functions cannot be stored as keys in the accessed data structures. When one of the keys is a function, the function is invoked. In the example below, we use a function to get and increment all ages inside a list: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> all = fn :get_and_update, data, next -> ...> data |> Enum.map(next) |> Enum.unzip() ...> end iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1}) {[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]} If the previous value before invoking the function is `nil`, the function *will* receive `nil` as a value and must handle it accordingly (be it by failing or providing a sane default). The `Access` module ships with many convenience accessor functions, like the `all` anonymous function defined above. See `Access.all/0`, `Access.key/2`, and others as examples. """ @spec get_and_update_in( structure :: Access.t(), keys, (term -> {get_value, update_value} | :pop) ) :: {get_value, structure :: Access.t()} when keys: nonempty_list(any), get_value: var, update_value: term def get_and_update_in(data, keys, fun) def get_and_update_in(data, [head], fun) when is_function(head, 3), do: head.(:get_and_update, data, fun) def get_and_update_in(data, [head | tail], fun) when is_function(head, 3), do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun)) def get_and_update_in(data, [head], fun) when is_function(fun, 1), do: Access.get_and_update(data, head, fun) def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1), do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun)) @doc """ Pops a key from the given nested structure. Uses the `Access` protocol to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users, ["john", :age]) {27, %{"john" => %{}, "meg" => %{age: 23}}} In case any entry returns `nil`, its key will be removed and the deletion will be considered a success. iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users, ["jane", :age]) {nil, %{"john" => %{age: 27}, "meg" => %{age: 23}}} """ @spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data} when data: Access.container() def pop_in(data, keys) def pop_in(nil, [key | _]) do raise ArgumentError, "could not pop key #{inspect(key)} on a nil value" end def pop_in(data, [_ | _] = keys) do pop_in_data(data, keys) end defp pop_in_data(nil, [_ | _]), do: :pop defp pop_in_data(data, [fun]) when is_function(fun), do: fun.(:get_and_update, data, fn _ -> :pop end) defp pop_in_data(data, [fun | tail]) when is_function(fun), do: fun.(:get_and_update, data, &pop_in_data(&1, tail)) defp pop_in_data(data, [key]), do: Access.pop(data, key) defp pop_in_data(data, [key | tail]), do: Access.get_and_update(data, key, &pop_in_data(&1, tail)) @doc """ Puts a value in a nested structure via the given `path`. This is similar to `put_in/3`, except the path is extracted via a macro rather than passing a list. For example: put_in(opts[:foo][:bar], :baz) Is equivalent to: put_in(opts, [:foo, :bar], :baz) This also works with nested structs and the `struct.path.to.value` way to specify paths: put_in(struct.foo.bar, :baz) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users["john"][:age], 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users["john"].age, 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} """ defmacro put_in(path, value) do case unnest(path, [], true, "put_in/2") do {[h | t], true} -> nest_update_in(h, t, quote(do: fn _ -> unquote(value) end)) {[h | t], false} -> expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end)) quote(do: :erlang.element(2, unquote(expr))) end end @doc """ Pops a key from the nested structure via the given `path`. This is similar to `pop_in/2`, except the path is extracted via a macro rather than passing a list. For example: pop_in(opts[:foo][:bar]) Is equivalent to: pop_in(opts, [:foo, :bar]) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users["john"][:age]) {27, %{"john" => %{}, "meg" => %{age: 23}}} iex> users = %{john: %{age: 27}, meg: %{age: 23}} iex> pop_in(users.john[:age]) {27, %{john: %{}, meg: %{age: 23}}} In case any entry returns `nil`, its key will be removed and the deletion will be considered a success. """ defmacro pop_in(path) do {[h | t], _} = unnest(path, [], true, "pop_in/1") nest_pop_in(:map, h, t) end @doc """ Updates a nested structure via the given `path`. This is similar to `update_in/3`, except the path is extracted via a macro rather than passing a list. For example: update_in(opts[:foo][:bar], &(&1 + 1)) Is equivalent to: update_in(opts, [:foo, :bar], &(&1 + 1)) This also works with nested structs and the `struct.path.to.value` way to specify paths: update_in(struct.foo.bar, &(&1 + 1)) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users["john"][:age], &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users["john"].age, &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} """ defmacro update_in(path, fun) do case unnest(path, [], true, "update_in/2") do {[h | t], true} -> nest_update_in(h, t, fun) {[h | t], false} -> expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end)) quote(do: :erlang.element(2, unquote(expr))) end end @doc """ Gets a value and updates a nested data structure via the given `path`. This is similar to `get_and_update_in/3`, except the path is extracted via a macro rather than passing a list. For example: get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1}) Is equivalent to: get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1}) This also works with nested structs and the `struct.path.to.value` way to specify paths: get_and_update_in(struct.foo.bar, &{&1, &1 + 1}) Note that in order for this macro to work, the complete path must always be visible by this macro. See the "Paths" section below. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users["john"].age, &{&1, &1 + 1}) {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} ## Paths A path may start with a variable, local or remote call, and must be followed by one or more: * `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil, `nil` is returned * `foo.bar` - accesses a map/struct field; in case the field is not present, an error is raised Here are some valid paths: users["john"][:age] users["john"].age User.all()["john"].age all_users()["john"].age Here are some invalid ones: # Does a remote call after the initial value users["john"].do_something(arg1, arg2) # Does not access any key or field users """ defmacro get_and_update_in(path, fun) do {[h | t], _} = unnest(path, [], true, "get_and_update_in/2") nest_get_and_update_in(h, t, fun) end defp nest_update_in([], fun), do: fun defp nest_update_in(list, fun) do quote do fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end end end defp nest_update_in(h, [{:map, key} | t], fun) do quote do Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun))) end end defp nest_get_and_update_in([], fun), do: fun defp nest_get_and_update_in(list, fun) do quote do fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end end end defp nest_get_and_update_in(h, [{:access, key} | t], fun) do quote do Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) end end defp nest_get_and_update_in(h, [{:map, key} | t], fun) do quote do Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) end end defp nest_pop_in(kind, list) do quote do fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end end end defp nest_pop_in(:map, h, [{:access, key}]) do quote do case unquote(h) do nil -> {nil, nil} h -> Access.pop(h, unquote(key)) end end end defp nest_pop_in(_, _, [{:map, key}]) do raise ArgumentError, "cannot use pop_in when the last segment is a map/struct field. " <> "This would effectively remove the field #{inspect(key)} from the map/struct" end defp nest_pop_in(_, h, [{:map, key} | t]) do quote do Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t))) end end defp nest_pop_in(_, h, [{:access, key}]) do quote do case unquote(h) do nil -> :pop h -> Access.pop(h, unquote(key)) end end end defp nest_pop_in(_, h, [{:access, key} | t]) do quote do Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t))) end end defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do unnest(expr, [{:access, key} | acc], false, kind) end defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind) when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and :erlang.element(1, expr) != :__MODULE__ do unnest(expr, [{:map, key} | acc], all_map?, kind) end defp unnest(other, [], _all_map?, kind) do raise ArgumentError, "expected expression given to #{kind} to access at least one element, " <> "got: #{Macro.to_string(other)}" end defp unnest(other, acc, all_map?, kind) do case proper_start?(other) do true -> {[other | acc], all_map?} false -> raise ArgumentError, "expression given to #{kind} must start with a variable, local or remote call " <> "and be followed by an element access, got: #{Macro.to_string(other)}" end end defp proper_start?({{:., _, [expr, _]}, _, _args}) when is_atom(expr) when :erlang.element(1, expr) == :__aliases__ when :erlang.element(1, expr) == :__MODULE__, do: true defp proper_start?({atom, _, _args}) when is_atom(atom), do: true defp proper_start?(other), do: not is_tuple(other) @doc """ Converts the argument to a string according to the `String.Chars` protocol. This is the function invoked when there is string interpolation. ## Examples iex> to_string(:foo) "foo" """ defmacro to_string(term) do quote(do: :"Elixir.String.Chars".to_string(unquote(term))) end @doc """ Converts the given term to a charlist according to the `List.Chars` protocol. ## Examples iex> to_charlist(:foo) 'foo' """ defmacro to_charlist(term) do quote(do: List.Chars.to_charlist(unquote(term))) end @doc """ Returns `true` if `term` is `nil`, `false` otherwise. Allowed in guard clauses. ## Examples iex> is_nil(1) false iex> is_nil(nil) true """ @doc guard: true defmacro is_nil(term) do quote(do: unquote(term) == nil) end @doc """ A convenience macro that checks if the right side (an expression) matches the left side (a pattern). ## Examples iex> match?(1, 1) true iex> match?({1, _}, {1, 2}) true iex> map = %{a: 1, b: 2} iex> match?(%{a: _}, map) true iex> a = 1 iex> match?(^a, 1) true `match?/2` is very useful when filtering or finding a value in an enumerable: iex> list = [a: 1, b: 2, a: 3] iex> Enum.filter(list, &match?({:a, _}, &1)) [a: 1, a: 3] Guard clauses can also be given to the match: iex> list = [a: 1, b: 2, a: 3] iex> Enum.filter(list, &match?({:a, x} when x < 2, &1)) [a: 1] However, variables assigned in the match will not be available outside of the function call (unlike regular pattern matching with the `=` operator): iex> match?(_x, 1) true iex> binding() [] """ defmacro match?(pattern, expr) do success = quote do unquote(pattern) -> true end failure = quote generated: true do _ -> false end {:case, [], [expr, [do: success ++ failure]]} end @doc """ Module attribute unary operator. Reads and writes attributes in the current module. The canonical example for attributes is annotating that a module implements an OTP behaviour, such as `GenServer`: defmodule MyServer do @behaviour GenServer # ... callbacks ... end By default Elixir supports all the module attributes supported by Erlang, but custom attributes can be used as well: defmodule MyServer do @my_data 13 IO.inspect(@my_data) #=> 13 end Unlike Erlang, such attributes are not stored in the module by default since it is common in Elixir to use custom attributes to store temporary data that will be available at compile-time. Custom attributes may be configured to behave closer to Erlang by using `Module.register_attribute/3`. Finally, note that attributes can also be read inside functions: defmodule MyServer do @my_data 11 def first_data, do: @my_data @my_data 13 def second_data, do: @my_data end MyServer.first_data() #=> 11 MyServer.second_data() #=> 13 It is important to note that reading an attribute takes a snapshot of its current value. In other words, the value is read at compilation time and not at runtime. Check the `Module` module for other functions to manipulate module attributes. """ defmacro @expr defmacro @{:__aliases__, _meta, _args} do raise ArgumentError, "module attributes set via @ cannot start with an uppercase letter" end defmacro @{name, meta, args} do assert_module_scope(__CALLER__, :@, 1) function? = __CALLER__.function != nil cond do # Check for Macro as it is compiled later than Kernel not bootstrapped?(Macro) -> nil not function? and __CALLER__.context == :match -> raise ArgumentError, "invalid write attribute syntax, you probably meant to use: @#{name} expression" # Typespecs attributes are currently special cased by the compiler is_list(args) and typespec?(name) -> case bootstrapped?(Kernel.Typespec) do false -> :ok true -> pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.deftypespec( unquote(name), unquote(Macro.escape(hd(args), unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos) ) end end true -> do_at(args, meta, name, function?, __CALLER__) end end # @attribute(value) defp do_at([arg], meta, name, function?, env) do line = case :lists.keymember(:context, 1, meta) do true -> nil false -> env.line end cond do function? -> raise ArgumentError, "cannot set attribute @#{name} inside function/macro" name == :behavior -> warn_message = "@behavior attribute is not supported, please use @behaviour instead" IO.warn(warn_message, Macro.Env.stacktrace(env)) :lists.member(name, [:moduledoc, :typedoc, :doc]) -> arg = {env.line, arg} quote do Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) end true -> quote do Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) end end end # @attribute() defp do_at([], _meta, name, _function?, env) do IO.warn( "the @#{name}() notation (with parenthesis) is deprecated, please use @#{name} (without parenthesis) instead", Macro.Env.stacktrace(env) ) end # @attribute defp do_at(args, _meta, name, function?, env) when is_atom(args) do line = env.line doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc]) case function? do true -> value = case Module.__get_attribute__(env.module, name, line) do {_, doc} when doc_attr? -> doc other -> other end try do :elixir_quote.escape(value, :default, false) rescue ex in [ArgumentError] -> raise ArgumentError, "cannot inject attribute @#{name} into function/macro because " <> Exception.message(ex) end false when doc_attr? -> quote do case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do {_, doc} -> doc other -> other end end false -> quote do Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) end end end # All other cases defp do_at(args, _meta, name, _function?, _env) do raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}" end defp typespec?(:type), do: true defp typespec?(:typep), do: true defp typespec?(:opaque), do: true defp typespec?(:spec), do: true defp typespec?(:callback), do: true defp typespec?(:macrocallback), do: true defp typespec?(_), do: false @doc """ Returns the binding for the given context as a keyword list. In the returned result, keys are variable names and values are the corresponding variable values. If the given `context` is `nil` (by default it is), the binding for the current context is returned. ## Examples iex> x = 1 iex> binding() [x: 1] iex> x = 2 iex> binding() [x: 2] iex> binding(:foo) [] iex> var!(x, :foo) = 1 1 iex> binding(:foo) [x: 1] """ defmacro binding(context \\ nil) do in_match? = Macro.Env.in_match?(__CALLER__) bindings = for {v, c} <- Macro.Env.vars(__CALLER__), c == context do {v, wrap_binding(in_match?, {v, [generated: true], c})} end :lists.sort(bindings) end defp wrap_binding(true, var) do quote(do: ^unquote(var)) end defp wrap_binding(_, var) do var end @doc """ Provides an `if/2` macro. This macro expects the first argument to be a condition and the second argument to be a keyword list. ## One-liner examples if(foo, do: bar) In the example above, `bar` will be returned if `foo` evaluates to a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be returned. An `else` option can be given to specify the opposite: if(foo, do: bar, else: baz) ## Blocks examples It's also possible to pass a block to the `if/2` macro. The first example above would be translated to: if foo do bar end Note that `do/end` become delimiters. The second example would translate to: if foo do bar else baz end In order to compare more than two clauses, the `cond/1` macro has to be used. """ defmacro if(condition, clauses) do build_if(condition, clauses) end defp build_if(condition, do: do_clause) do build_if(condition, do: do_clause, else: nil) end defp build_if(condition, do: do_clause, else: else_clause) do optimize_boolean( quote do case unquote(condition) do x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(else_clause) _ -> unquote(do_clause) end end ) end defp build_if(_condition, _arguments) do raise ArgumentError, "invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted" end @doc """ Provides an `unless` macro. This macro evaluates and returns the `do` block passed in as the second argument if `condition` evaluates to a falsy value (`false` or `nil`). Otherwise, it returns the value of the `else` block if present or `nil` if not. See also `if/2`. ## Examples iex> unless(Enum.empty?([]), do: "Hello") nil iex> unless(Enum.empty?([1, 2, 3]), do: "Hello") "Hello" iex> unless Enum.sum([2, 2]) == 5 do ...> "Math still works" ...> else ...> "Math is broken" ...> end "Math still works" """ defmacro unless(condition, clauses) do build_unless(condition, clauses) end defp build_unless(condition, do: do_clause) do build_unless(condition, do: do_clause, else: nil) end defp build_unless(condition, do: do_clause, else: else_clause) do quote do if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause)) end end defp build_unless(_condition, _arguments) do raise ArgumentError, "invalid or duplicate keys for unless, " <> "only \"do\" and an optional \"else\" are permitted" end @doc """ Destructures two lists, assigning each term in the right one to the matching term in the left one. Unlike pattern matching via `=`, if the sizes of the left and right lists don't match, destructuring simply stops instead of raising an error. ## Examples iex> destructure([x, y, z], [1, 2, 3, 4, 5]) iex> {x, y, z} {1, 2, 3} In the example above, even though the right list has more entries than the left one, destructuring works fine. If the right list is smaller, the remaining elements are simply set to `nil`: iex> destructure([x, y, z], [1]) iex> {x, y, z} {1, nil, nil} The left-hand side supports any expression you would use on the left-hand side of a match: x = 1 destructure([^x, y, z], [1, 2, 3]) The example above will only work if `x` matches the first value in the right list. Otherwise, it will raise a `MatchError` (like the `=` operator would do). """ defmacro destructure(left, right) when is_list(left) do quote do unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left))) end end @doc """ Range creation operator. Returns a range with the specified `first` and `last` integers. If last is larger than first, the range will be increasing from first to last. If first is larger than last, the range will be decreasing from first to last. If first is equal to last, the range will contain one element, which is the number itself. ## Examples iex> 0 in 1..3 false iex> 1 in 1..3 true iex> 2 in 1..3 true iex> 3 in 1..3 true """ defmacro first..last do case bootstrapped?(Macro) do true -> first = Macro.expand(first, __CALLER__) last = Macro.expand(last, __CALLER__) range(__CALLER__.context, first, last) false -> range(__CALLER__.context, first, last) end end defp range(_context, first, last) when is_integer(first) and is_integer(last) do {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} end defp range(_context, first, last) when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do raise ArgumentError, "ranges (first..last) expect both sides to be integers, " <> "got: #{Macro.to_string({:.., [], [first, last]})}" end defp range(nil, first, last) do quote(do: Elixir.Range.new(unquote(first), unquote(last))) end defp range(_, first, last) do {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} end @doc """ Boolean "and" operator. Provides a short-circuit operator that evaluates and returns the second expression only if the first one evaluates to a truthy value (neither `false` nor `nil`). Returns the first expression otherwise. Not allowed in guard clauses. ## Examples iex> Enum.empty?([]) && Enum.empty?([]) true iex> List.first([]) && true nil iex> Enum.empty?([]) && List.first([1]) 1 iex> false && throw(:bad) false Note that, unlike `and/2`, this operator accepts any expression as the first argument, not only booleans. """ defmacro left && right do assert_no_match_or_guard_scope(__CALLER__.context, "&&") quote do case unquote(left) do x when :"Elixir.Kernel".in(x, [false, nil]) -> x _ -> unquote(right) end end end @doc """ Boolean "or" operator. Provides a short-circuit operator that evaluates and returns the second expression only if the first one does not evaluate to a truthy value (that is, it is either `nil` or `false`). Returns the first expression otherwise. Not allowed in guard clauses. ## Examples iex> Enum.empty?([1]) || Enum.empty?([1]) false iex> List.first([]) || true true iex> Enum.empty?([1]) || 1 1 iex> Enum.empty?([]) || throw(:bad) true Note that, unlike `or/2`, this operator accepts any expression as the first argument, not only booleans. """ defmacro left || right do assert_no_match_or_guard_scope(__CALLER__.context, "||") quote do case unquote(left) do x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(right) x -> x end end end @doc """ Pipe operator. This operator introduces the expression on the left-hand side as the first argument to the function call on the right-hand side. ## Examples iex> [1, [2], 3] |> List.flatten() [1, 2, 3] The example above is the same as calling `List.flatten([1, [2], 3])`. The `|>` operator is mostly useful when there is a desire to execute a series of operations resembling a pipeline: iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end) [2, 4, 6] In the example above, the list `[1, [2], 3]` is passed as the first argument to the `List.flatten/1` function, then the flattened list is passed as the first argument to the `Enum.map/2` function which doubles each element of the list. In other words, the expression above simply translates to: Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end) ## Pitfalls There are two common pitfalls when using the pipe operator. The first one is related to operator precedence. For example, the following expression: String.graphemes "Hello" |> Enum.reverse Translates to: String.graphemes("Hello" |> Enum.reverse()) which results in an error as the `Enumerable` protocol is not defined for binaries. Adding explicit parentheses resolves the ambiguity: String.graphemes("Hello") |> Enum.reverse() Or, even better: "Hello" |> String.graphemes() |> Enum.reverse() The second pitfall is that the `|>` operator works on calls. For example, when you write: "Hello" |> some_function() Elixir sees the right-hand side is a function call and pipes to it. This means that, if you want to pipe to an anonymous or captured function, it must also be explicitly called. Given the anonymous function: fun = fn x -> IO.puts(x) end fun.("Hello") This won't work as it will rather try to invoke the local function `fun`: "Hello" |> fun() This works: "Hello" |> fun.() As you can see, the `|>` operator retains the same semantics as when the pipe is not used since both require the `fun.(...)` notation. """ defmacro left |> right do [{h, _} | t] = Macro.unpipe({:|>, [], [left, right]}) fun = fn {x, pos}, acc -> Macro.pipe(acc, x, pos) end :lists.foldl(fun, h, t) end @doc """ Returns `true` if `module` is loaded and contains a public `function` with the given `arity`, otherwise `false`. Note that this function does not load the module in case it is not loaded. Check `Code.ensure_loaded/1` for more information. Inlined by the compiler. ## Examples iex> function_exported?(Enum, :map, 2) true iex> function_exported?(Enum, :map, 10) false iex> function_exported?(List, :to_string, 1) true """ @spec function_exported?(module, atom, arity) :: boolean def function_exported?(module, function, arity) do :erlang.function_exported(module, function, arity) end @doc """ Returns `true` if `module` is loaded and contains a public `macro` with the given `arity`, otherwise `false`. Note that this function does not load the module in case it is not loaded. Check `Code.ensure_loaded/1` for more information. If `module` is an Erlang module (as opposed to an Elixir module), this function always returns `false`. ## Examples iex> macro_exported?(Kernel, :use, 2) true iex> macro_exported?(:erlang, :abs, 1) false """ @spec macro_exported?(module, atom, arity) :: boolean def macro_exported?(module, macro, arity) when is_atom(module) and is_atom(macro) and is_integer(arity) and (arity >= 0 and arity <= 255) do function_exported?(module, :__info__, 1) and :lists.member({macro, arity}, module.__info__(:macros)) end @doc """ Membership operator. Checks if the element on the left-hand side is a member of the collection on the right-hand side. ## Examples iex> x = 1 iex> x in [1, 2, 3] true This operator (which is a macro) simply translates to a call to `Enum.member?/2`. The example above would translate to: Enum.member?([1, 2, 3], x) Elixir also supports `left not in right`, which evaluates to `not(left in right)`: iex> x = 1 iex> x not in [1, 2, 3] false ## Guards The `in/2` operator (as well as `not in`) can be used in guard clauses as long as the right-hand side is a range or a list. In such cases, Elixir will expand the operator to a valid guard expression. For example: when x in [1, 2, 3] translates to: when x === 1 or x === 2 or x === 3 When using ranges: when x in 1..3 translates to: when is_integer(x) and x >= 1 and x <= 3 Note that only integers can be considered inside a range by `in`. ### AST considerations `left not in right` is parsed by the compiler into the AST: {:not, _, [{:in, _, [left, right]}]} This is the same AST as `not(left in right)`. Additionally, `Macro.to_string/2` will translate all occurrences of this AST to `left not in right`. """ @doc guard: true defmacro left in right do in_body? = __CALLER__.context == nil expand = case bootstrapped?(Macro) do true -> &Macro.expand(&1, __CALLER__) false -> & &1 end case expand.(right) do [] when not in_body? -> false [] -> quote do _ = unquote(left) false end [head | tail] = list when not in_body? -> in_list(left, head, tail, expand, list, in_body?) [_ | _] = list when in_body? -> case ensure_evaled(list, {0, []}, expand) do {[head | tail], {_, []}} -> in_var(in_body?, left, &in_list(&1, head, tail, expand, list, in_body?)) {[head | tail], {_, vars_values}} -> {vars, values} = :lists.unzip(:lists.reverse(vars_values)) is_in_list = &in_list(&1, head, tail, expand, list, in_body?) quote do {unquote_splicing(vars)} = {unquote_splicing(values)} unquote(in_var(in_body?, left, is_in_list)) end end {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last]} -> in_var(in_body?, left, &in_range(&1, expand.(first), expand.(last))) right when in_body? -> quote(do: Elixir.Enum.member?(unquote(right), unquote(left))) %{__struct__: Elixir.Range, first: _, last: _} -> raise ArgumentError, "non-literal range in guard should be escaped with Macro.escape/2" right -> raise_on_invalid_args_in_2(right) end end defp raise_on_invalid_args_in_2(right) do raise ArgumentError, << "invalid right argument for operator \"in\", it expects a compile-time proper list ", "or compile-time range on the right side when used in guard expressions, got: ", Macro.to_string(right)::binary >> end defp in_var(false, ast, fun), do: fun.(ast) defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context), do: fun.(var) defp in_var(true, ast, fun) do quote do var = unquote(ast) unquote(fun.(quote(do: var))) end end # Called as ensure_evaled(list, {0, []}). Note acc is reversed. defp ensure_evaled(list, acc, expand) do fun = fn {:|, meta, [head, tail]}, acc -> {head, acc} = ensure_evaled_element(head, acc) {tail, acc} = ensure_evaled_tail(expand.(tail), acc, expand) {{:|, meta, [head, tail]}, acc} elem, acc -> ensure_evaled_element(elem, acc) end :lists.mapfoldl(fun, acc, list) end defp ensure_evaled_element(elem, acc) when is_number(elem) or is_atom(elem) or is_binary(elem) do {elem, acc} end defp ensure_evaled_element(elem, acc) do ensure_evaled_var(elem, acc) end defp ensure_evaled_tail(elem, acc, expand) when is_list(elem) do ensure_evaled(elem, acc, expand) end defp ensure_evaled_tail(elem, acc, _expand) do ensure_evaled_var(elem, acc) end defp ensure_evaled_var(elem, {index, ast}) do var = {String.to_atom("arg" <> Integer.to_string(index)), [], __MODULE__} {var, {index + 1, [{var, elem} | ast]}} end defp in_range(left, first, last) do case is_integer(first) and is_integer(last) do true -> in_range_literal(left, first, last) false -> quote do :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and :erlang.is_integer(unquote(last)) and ((:erlang."=<"(unquote(first), unquote(last)) and unquote(increasing_compare(left, first, last))) or (:erlang.<(unquote(last), unquote(first)) and unquote(decreasing_compare(left, first, last)))) end end end defp in_range_literal(left, first, first) do quote do :erlang."=:="(unquote(left), unquote(first)) end end defp in_range_literal(left, first, last) when first < last do quote do :erlang.andalso( :erlang.is_integer(unquote(left)), unquote(increasing_compare(left, first, last)) ) end end defp in_range_literal(left, first, last) do quote do :erlang.andalso( :erlang.is_integer(unquote(left)), unquote(decreasing_compare(left, first, last)) ) end end defp in_list(left, head, tail, expand, right, in_body?) do [head | tail] = :lists.map(&comp(left, &1, expand, right, in_body?), [head | tail]) :lists.foldl(&quote(do: :erlang.orelse(unquote(&2), unquote(&1))), head, tail) end defp comp(left, {:|, _, [head, tail]}, expand, right, in_body?) do case expand.(tail) do [] -> quote(do: :erlang."=:="(unquote(left), unquote(head))) [tail_head | tail] -> quote do :erlang.orelse( :erlang."=:="(unquote(left), unquote(head)), unquote(in_list(left, tail_head, tail, expand, right, in_body?)) ) end tail when in_body? -> quote do :erlang.orelse( :erlang."=:="(unquote(left), unquote(head)), :lists.member(unquote(left), unquote(tail)) ) end _ -> raise_on_invalid_args_in_2(right) end end defp comp(left, right, _expand, _right, _in_body?) do quote(do: :erlang."=:="(unquote(left), unquote(right))) end defp increasing_compare(var, first, last) do quote do :erlang.andalso( :erlang.>=(unquote(var), unquote(first)), :erlang."=<"(unquote(var), unquote(last)) ) end end defp decreasing_compare(var, first, last) do quote do :erlang.andalso( :erlang."=<"(unquote(var), unquote(first)), :erlang.>=(unquote(var), unquote(last)) ) end end @doc """ Marks that the given variable should not be hygienized. This macro expects a variable and it is typically invoked inside `Kernel.SpecialForms.quote/2` to mark that a variable should not be hygienized. See `Kernel.SpecialForms.quote/2` for more information. ## Examples iex> Kernel.var!(example) = 1 1 iex> Kernel.var!(example) 1 """ defmacro var!(var, context \\ nil) defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do # Remove counter and force them to be vars meta = :lists.keydelete(:counter, 1, meta) meta = :lists.keystore(:var, 1, meta, {:var, true}) case Macro.expand(context, __CALLER__) do context when is_atom(context) -> {name, meta, context} other -> raise ArgumentError, "expected var! context to expand to an atom, got: #{Macro.to_string(other)}" end end defmacro var!(other, _context) do raise ArgumentError, "expected a variable to be given to var!, got: #{Macro.to_string(other)}" end @doc """ When used inside quoting, marks that the given alias should not be hygienized. This means the alias will be expanded when the macro is expanded. Check `Kernel.SpecialForms.quote/2` for more information. """ defmacro alias!(alias) when is_atom(alias) do alias end defmacro alias!({:__aliases__, meta, args}) do # Simply remove the alias metadata from the node # so it does not affect expansion. {:__aliases__, :lists.keydelete(:alias, 1, meta), args} end ## Definitions implemented in Elixir @doc ~S""" Defines a module given by name with the given contents. This macro defines a module with the given `alias` as its name and with the given contents. It returns a tuple with four elements: * `:module` * the module name * the binary contents of the module * the result of evaluating the contents block ## Examples defmodule Number do def one, do: 1 def two, do: 2 end #=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}} Number.one() #=> 1 Number.two() #=> 2 ## Nesting Nesting a module inside another module affects the name of the nested module: defmodule Foo do defmodule Bar do end end In the example above, two modules - `Foo` and `Foo.Bar` - are created. When nesting, Elixir automatically creates an alias to the inner module, allowing the second module `Foo.Bar` to be accessed as `Bar` in the same lexical scope where it's defined (the `Foo` module). This only happens if the nested module is defined via an alias. If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or an alias has to be explicitly set in the `Foo` module with the help of `Kernel.SpecialForms.alias/2`. defmodule Foo.Bar do # code end defmodule Foo do alias Foo.Bar # code here can refer to "Foo.Bar" as just "Bar" end ## Dynamic names Elixir module names can be dynamically generated. This is very useful when working with macros. For instance, one could write: defmodule String.to_atom("Foo#{1}") do # contents ... end Elixir will accept any module name as long as the expression passed as the first argument to `defmodule/2` evaluates to an atom. Note that, when a dynamic name is used, Elixir won't nest the name under the current module nor automatically set up an alias. ## Reserved module names If you attempt to define a module that already exists, you will get a warning saying that a module has been redefined. There are some modules that Elixir does not currently implement but it may be implement in the future. Those modules are reserved and defining them will result in a compilation error: defmodule Any do # code end ** (CompileError) iex:1: module Any is reserved and cannot be defined Elixir reserves the following module names: `Elixir`, `Any`, `BitString`, `PID`, and `Reference`. """ defmacro defmodule(alias, do_block) defmacro defmodule(alias, do: block) do env = __CALLER__ boot? = bootstrapped?(Macro) expanded = case boot? do true -> Macro.expand(alias, env) false -> alias end {expanded, with_alias} = case boot? and is_atom(expanded) do true -> # Expand the module considering the current environment/nesting {full, old, new} = expand_module(alias, expanded, env) meta = [defined: full, context: env.module] ++ alias_meta(alias) {full, {:alias, meta, [old, [as: new, warn: false]]}} false -> {expanded, nil} end # We do this so that the block is not tail-call optimized and stacktraces # are not messed up. Basically, we just insert something between the return # value of the block and what is returned by defmodule. Using just ":ok" or # similar doesn't work because it's likely optimized away by the compiler. block = quote do result = unquote(block) :elixir_utils.noop() result end escaped = case env do %{function: nil, lexical_tracker: pid} when is_pid(pid) -> integer = Kernel.LexicalTracker.write_cache(pid, block) quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer))) %{} -> :elixir_quote.escape(block, :default, false) end module_vars = :lists.map(&module_var/1, :maps.keys(elem(env.current_vars, 0))) quote do unquote(with_alias) :elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__) end end defp alias_meta({:__aliases__, meta, _}), do: meta defp alias_meta(_), do: [] # defmodule Elixir.Alias defp expand_module({:__aliases__, _, [:"Elixir", _ | _]}, module, _env), do: {module, module, nil} # defmodule Alias in root defp expand_module({:__aliases__, _, _}, module, %{module: nil}), do: {module, module, nil} # defmodule Alias nested defp expand_module({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do module = :elixir_aliases.concat([env.module, h]) alias = String.to_atom("Elixir." <> Atom.to_string(h)) case t do [] -> {module, module, alias} _ -> {String.to_atom(Enum.join([module | t], ".")), module, alias} end end # defmodule _ defp expand_module(_raw, module, _env) do {module, module, nil} end defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind} defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil} @doc ~S""" Defines a public function with the given name and body. ## Examples defmodule Foo do def bar, do: :baz end Foo.bar() #=> :baz A function that expects arguments can be defined as follows: defmodule Foo do def sum(a, b) do a + b end end In the example above, a `sum/2` function is defined; this function receives two arguments and returns their sum. ## Default arguments `\\` is used to specify a default value for a parameter of a function. For example: defmodule MyMath do def multiply_by(number, factor \\ 2) do number * factor end end MyMath.multiply_by(4, 3) #=> 12 MyMath.multiply_by(4) #=> 8 The compiler translates this into multiple functions with different arities, here `MyMath.multiply_by/1` and `MyMath.multiply_by/2`, that represent cases when arguments for parameters with default values are passed or not passed. When defining a function with default arguments as well as multiple explicitly declared clauses, you must write a function head that declares the defaults. For example: defmodule MyString do def join(string1, string2 \\ nil, separator \\ " ") def join(string1, nil, _separator) do string1 end def join(string1, string2, separator) do string1 <> separator <> string2 end end Note that `\\` can't be used with anonymous functions because they can only have a sole arity. ## Function and variable names Function and variable names have the following syntax: A _lowercase ASCII letter_ or an _underscore_, followed by any number of _lowercase or uppercase ASCII letters_, _numbers_, or _underscores_. Optionally they can end in either an _exclamation mark_ or a _question mark_. For variables, any identifier starting with an underscore should indicate an unused variable. For example: def foo(bar) do [] end #=> warning: variable bar is unused def foo(_bar) do [] end #=> no warning def foo(_bar) do _bar end #=> warning: the underscored variable "_bar" is used after being set ## `rescue`/`catch`/`after`/`else` Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try/1` does (known as "implicit try"). For example, the following two functions are equivalent: def convert(number) do try do String.to_integer(number) rescue e in ArgumentError -> {:error, e.message} end end def convert(number) do String.to_integer(number) rescue e in ArgumentError -> {:error, e.message} end """ defmacro def(call, expr \\ nil) do define(:def, call, expr, __CALLER__) end @doc """ Defines a private function with the given name and body. Private functions are only accessible from within the module in which they are defined. Trying to access a private function from outside the module it's defined in results in an `UndefinedFunctionError` exception. Check `def/2` for more information. ## Examples defmodule Foo do def bar do sum(1, 2) end defp sum(a, b), do: a + b end Foo.bar() #=> 3 Foo.sum(1, 2) ** (UndefinedFunctionError) undefined function Foo.sum/2 """ defmacro defp(call, expr \\ nil) do define(:defp, call, expr, __CALLER__) end @doc """ Defines a public macro with the given name and body. Macros must be defined before its usage. Check `def/2` for rules on naming and default arguments. ## Examples defmodule MyLogic do defmacro unless(expr, opts) do quote do if !unquote(expr), unquote(opts) end end end require MyLogic MyLogic.unless false do IO.puts("It works") end """ defmacro defmacro(call, expr \\ nil) do define(:defmacro, call, expr, __CALLER__) end @doc """ Defines a private macro with the given name and body. Private macros are only accessible from the same module in which they are defined. Private macros must be defined before its usage. Check `defmacro/2` for more information, and check `def/2` for rules on naming and default arguments. """ defmacro defmacrop(call, expr \\ nil) do define(:defmacrop, call, expr, __CALLER__) end defp define(kind, call, expr, env) do module = assert_module_scope(env, kind, 2) assert_no_function_scope(env, kind, 2) unquoted_call = :elixir_quote.has_unquotes(call) unquoted_expr = :elixir_quote.has_unquotes(expr) escaped_call = :elixir_quote.escape(call, :default, true) escaped_expr = case unquoted_expr do true -> :elixir_quote.escape(expr, :default, true) false -> key = :erlang.unique_integer() :elixir_module.write_cache(module, key, expr) quote(do: :elixir_module.read_cache(unquote(module), unquote(key))) end # Do not check clauses if any expression was unquoted check_clauses = not (unquoted_expr or unquoted_call) pos = :elixir_locals.cache_env(env) quote do :elixir_def.store_definition( unquote(kind), unquote(check_clauses), unquote(escaped_call), unquote(escaped_expr), unquote(pos) ) end end @doc """ Defines a struct. A struct is a tagged map that allows developers to provide default values for keys, tags to be used in polymorphic dispatches and compile time assertions. To define a struct, a developer must define both `__struct__/0` and `__struct__/1` functions. `defstruct/1` is a convenience macro which defines such functions with some conveniences. For more information about structs, please check `Kernel.SpecialForms.%/2`. ## Examples defmodule User do defstruct name: nil, age: nil end Struct fields are evaluated at compile-time, which allows them to be dynamic. In the example below, `10 + 11` is evaluated at compile-time and the age field is stored with value `21`: defmodule User do defstruct name: nil, age: 10 + 11 end The `fields` argument is usually a keyword list with field names as atom keys and default values as corresponding values. `defstruct/1` also supports a list of atoms as its argument: in that case, the atoms in the list will be used as the struct's field names and they will all default to `nil`. defmodule Post do defstruct [:title, :content, :author] end ## Deriving Although structs are maps, by default structs do not implement any of the protocols implemented for maps. For example, attempting to use a protocol with the `User` struct leads to an error: john = %User{name: "John"} MyProtocol.call(john) ** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...} `defstruct/1`, however, allows protocol implementations to be *derived*. This can be done by defining a `@derive` attribute as a list before invoking `defstruct/1`: defmodule User do @derive [MyProtocol] defstruct name: nil, age: 10 + 11 end MyProtocol.call(john) # it works! For each protocol in the `@derive` list, Elixir will assert the protocol has been implemented for `Any`. If the `Any` implementation defines a `__deriving__/3` callback, the callback will be invoked and it should define the implementation module. Otherwise an implementation that simply points to the `Any` implementation is automatically derived. For more information on the `__deriving__/3` callback, see `Protocol.derive/3`. ## Enforcing keys When building a struct, Elixir will automatically guarantee all keys belongs to the struct: %User{name: "john", unknown: :key} ** (KeyError) key :unknown not found in: %User{age: 21, name: nil} Elixir also allows developers to enforce certain keys must always be given when building the struct: defmodule User do @enforce_keys [:name] defstruct name: nil, age: 10 + 11 end Now trying to build a struct without the name key will fail: %User{age: 21} ** (ArgumentError) the following keys must also be given when building struct User: [:name] Keep in mind `@enforce_keys` is a simple compile-time guarantee to aid developers when building structs. It is not enforced on updates and it does not provide any sort of value-validation. ## Types It is recommended to define types for structs. By convention such type is called `t`. To define a struct inside a type, the struct literal syntax is used: defmodule User do defstruct name: "John", age: 25 @type t :: %__MODULE__{name: String.t(), age: non_neg_integer} end It is recommended to only use the struct syntax when defining the struct's type. When referring to another struct it's better to use `User.t` instead of `%User{}`. The types of the struct fields that are not included in `%User{}` default to `term()` (see `t:term/0`). Structs whose internal structure is private to the local module (pattern matching them or directly accessing their fields should not be allowed) should use the `@opaque` attribute. Structs whose internal structure is public should use `@type`. """ defmacro defstruct(fields) do builder = case bootstrapped?(Enum) do true -> quote do case @enforce_keys do [] -> def __struct__(kv) do Enum.reduce(kv, @__struct__, fn {key, val}, map -> Map.replace!(map, key, val) end) end _ -> def __struct__(kv) do {map, keys} = Enum.reduce(kv, {@__struct__, @enforce_keys}, fn {key, val}, {map, keys} -> {Map.replace!(map, key, val), List.delete(keys, key)} end) case keys do [] -> map _ -> raise ArgumentError, "the following keys must also be given when building " <> "struct #{inspect(__MODULE__)}: #{inspect(keys)}" end end end end false -> quote do _ = @enforce_keys def __struct__(kv) do :lists.foldl(fn {key, val}, acc -> Map.replace!(acc, key, val) end, @__struct__, kv) end end end quote do if Module.has_attribute?(__MODULE__, :__struct__) do raise ArgumentError, "defstruct has already been called for " <> "#{Kernel.inspect(__MODULE__)}, defstruct can only be called once per module" end {struct, keys, derive} = Kernel.Utils.defstruct(__MODULE__, unquote(fields)) @__struct__ struct @enforce_keys keys case derive do [] -> :ok _ -> Protocol.__derive__(derive, __MODULE__, __ENV__) end def __struct__() do @__struct__ end unquote(builder) Kernel.Utils.announce_struct(__MODULE__) struct end end @doc ~S""" Defines an exception. Exceptions are structs backed by a module that implements the `Exception` behaviour. The `Exception` behaviour requires two functions to be implemented: * [`exception/1`](`c:Exception.exception/1`) - receives the arguments given to `raise/2` and returns the exception struct. The default implementation accepts either a set of keyword arguments that is merged into the struct or a string to be used as the exception's message. * [`message/1`](`c:Exception.message/1`) - receives the exception struct and must return its message. Most commonly exceptions have a message field which by default is accessed by this function. However, if an exception does not have a message field, this function must be explicitly implemented. Since exceptions are structs, the API supported by `defstruct/1` is also available in `defexception/1`. ## Raising exceptions The most common way to raise an exception is via `raise/2`: defmodule MyAppError do defexception [:message] end value = [:hello] raise MyAppError, message: "did not get what was expected, got: #{inspect(value)}" In many cases it is more convenient to pass the expected value to `raise/2` and generate the message in the `c:Exception.exception/1` callback: defmodule MyAppError do defexception [:message] @impl true def exception(value) do msg = "did not get what was expected, got: #{inspect(value)}" %MyAppError{message: msg} end end raise MyAppError, value The example above shows the preferred strategy for customizing exception messages. """ defmacro defexception(fields) do quote bind_quoted: [fields: fields] do @behaviour Exception struct = defstruct([__exception__: true] ++ fields) if Map.has_key?(struct, :message) do @impl true def message(exception) do exception.message end defoverridable message: 1 @impl true def exception(msg) when Kernel.is_binary(msg) do exception(message: msg) end end # Calls to Kernel functions must be fully-qualified to ensure # reproducible builds; otherwise, this macro will generate ASTs # with different metadata (:import, :context) depending on if # it is the bootstrapped version or not. # TODO: Change the implementation on v2.0 to simply call Kernel.struct!/2 @impl true def exception(args) when Kernel.is_list(args) do struct = __struct__() {valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end) case invalid do [] -> :ok _ -> IO.warn( "the following fields are unknown when raising " <> "#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. " <> "Please make sure to only give known fields when raising " <> "or redefine #{Kernel.inspect(__MODULE__)}.exception/1 to " <> "discard unknown fields. Future Elixir versions will raise on " <> "unknown fields given to raise/2" ) end Kernel.struct!(struct, valid) end defoverridable exception: 1 end end @doc """ Defines a protocol. See the `Protocol` module for more information. """ defmacro defprotocol(name, do_block) defmacro defprotocol(name, do: block) do Protocol.__protocol__(name, do: block) end @doc """ Defines an implementation for the given protocol. See the `Protocol` module for more information. """ defmacro defimpl(name, opts, do_block \\ []) do merged = Keyword.merge(opts, do_block) merged = Keyword.put_new(merged, :for, __CALLER__.module) Protocol.__impl__(name, merged) end @doc """ Makes the given functions in the current module overridable. An overridable function is lazily defined, allowing a developer to override it. Macros cannot be overridden as functions and vice-versa. ## Example defmodule DefaultMod do defmacro __using__(_opts) do quote do def test(x, y) do x + y end defoverridable test: 2 end end end defmodule InheritMod do use DefaultMod def test(x, y) do x * y + super(x, y) end end As seen as in the example above, `super` can be used to call the default implementation. If `@behaviour` has been defined, `defoverridable` can also be called with a module as an argument. All implemented callbacks from the behaviour above the call to `defoverridable` will be marked as overridable. ## Example defmodule Behaviour do @callback foo :: any end defmodule DefaultMod do defmacro __using__(_opts) do quote do @behaviour Behaviour def foo do "Override me" end defoverridable Behaviour end end end defmodule InheritMod do use DefaultMod def foo do "Overridden" end end """ defmacro defoverridable(keywords_or_behaviour) do quote do Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour)) end end @doc """ Generates a macro suitable for use in guard expressions. It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a macro that can be used both inside or outside guards. Note the convention in Elixir is to name functions/macros allowed in guards with the `is_` prefix, such as `is_list/1`. If, however, the function/macro returns a boolean and is not allowed in guards, it should have no prefix and end with a question mark, such as `Keyword.keyword?/1`. ## Example defmodule Integer.Guards do defguard is_even(value) when is_integer(value) and rem(value, 2) == 0 end defmodule Collatz do @moduledoc "Tools for working with the Collatz sequence." import Integer.Guards @doc "Determines the number of steps `n` takes to reach `1`." # If this function never converges, please let me know what `n` you used. def converge(n) when n > 0, do: step(n, 0) defp step(1, step_count) do step_count end defp step(n, step_count) when is_even(n) do step(div(n, 2), step_count + 1) end defp step(n, step_count) do step(3 * n + 1, step_count + 1) end end """ @doc since: "1.6.0" @spec defguard(Macro.t()) :: Macro.t() defmacro defguard(guard) do define_guard(:defmacro, guard, __CALLER__) end @doc """ Generates a private macro suitable for use in guard expressions. It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a private macro that can be used both inside or outside guards in the current module. Similar to `defmacrop/2`, `defguardp/1` must be defined before its use in the current module. """ @doc since: "1.6.0" @spec defguardp(Macro.t()) :: Macro.t() defmacro defguardp(guard) do define_guard(:defmacrop, guard, __CALLER__) end defp define_guard(kind, guard, env) do case :elixir_utils.extract_guards(guard) do {call, [_, _ | _]} -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}, " <> "only a single when clause is allowed" {call, impls} -> case Macro.decompose_call(call) do {_name, args} -> validate_variable_only_args!(call, args) macro_definition = case impls do [] -> define(kind, call, nil, env) [guard] -> quoted = quote do require Kernel.Utils Kernel.Utils.defguard(unquote(args), unquote(guard)) end define(kind, call, [do: quoted], env) end quote do @doc guard: true unquote(macro_definition) end _invalid_definition -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" end end end defp validate_variable_only_args!(call, args) do Enum.each(args, fn {ref, _meta, context} when is_atom(ref) and is_atom(context) -> :ok {:\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) -> :ok _match -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" end) end @doc """ Uses the given module in the current context. When calling: use MyModule, some: :options the `__using__/1` macro from the `MyModule` module is invoked with the second argument passed to `use` as its argument. Since `__using__/1` is a macro, all the usual macro rules apply, and its return value should be quoted code that is then inserted where `use/2` is called. ## Examples For example, to write test cases using the `ExUnit` framework provided with Elixir, a developer should `use` the `ExUnit.Case` module: defmodule AssertionTest do use ExUnit.Case, async: true test "always pass" do assert true end end In this example, Elixir will call the `__using__/1` macro in the `ExUnit.Case` module with the keyword list `[async: true]` as its argument. In other words, `use/2` translates to: defmodule AssertionTest do require ExUnit.Case ExUnit.Case.__using__(async: true) test "always pass" do assert true end end where `ExUnit.Case` defines the `__using__/1` macro: defmodule ExUnit.Case do defmacro __using__(opts) do # do something with opts quote do # return some code to inject in the caller end end end ## Best practices `__using__/1` is typically used when there is a need to set some state (via module attributes) or callbacks (like `@before_compile`, see the documentation for `Module` for more information) into the caller. `__using__/1` may also be used to alias, require, or import functionality from different modules: defmodule MyModule do defmacro __using__(_opts) do quote do import MyModule.Foo import MyModule.Bar import MyModule.Baz alias MyModule.Repo end end end However, do not provide `__using__/1` if all it does is to import, alias or require the module itself. For example, avoid this: defmodule MyModule do defmacro __using__(_opts) do quote do import MyModule end end end In such cases, developers should instead import or alias the module directly, so that they can customize those as they wish, without the indirection behind `use/2`. Finally, developers should also avoid defining functions inside the `__using__/1` callback, unless those functions are the default implementation of a previously defined `@callback` or are functions meant to be overridden (see `defoverridable/1`). Even in these cases, defining functions should be seen as a "last resort". In case you want to provide some existing functionality to the user module, please define it in a module which will be imported accordingly; for example, `ExUnit.Case` doesn't define the `test/3` macro in the module that calls `use ExUnit.Case`, but it defines `ExUnit.Case.test/3` and just imports that into the caller when used. """ defmacro use(module, opts \\ []) do calls = Enum.map(expand_aliases(module, __CALLER__), fn expanded when is_atom(expanded) -> quote do require unquote(expanded) unquote(expanded).__using__(unquote(opts)) end _otherwise -> raise ArgumentError, "invalid arguments for use, " <> "expected a compile time atom or alias, got: #{Macro.to_string(module)}" end) quote(do: (unquote_splicing(calls))) end defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do base = Macro.expand(base, env) Enum.map(refs, fn {:__aliases__, _, ref} -> Module.concat([base | ref]) ref when is_atom(ref) -> Module.concat(base, ref) other -> other end) end defp expand_aliases(module, env) do [Macro.expand(module, env)] end @doc """ Defines a function that delegates to another module. Functions defined with `defdelegate/2` are public and can be invoked from outside the module they're defined in, as if they were defined using `def/2`. Therefore, `defdelegate/2` is about extending the current module's public API. If what you want is to invoke a function defined in another module without using its full module name, then use `alias/2` to shorten the module name or use `import/2` to be able to invoke the function without the module name altogether. Delegation only works with functions; delegating macros is not supported. Check `def/2` for rules on naming and default arguments. ## Options * `:to` - the module to dispatch to. * `:as` - the function to call on the target given in `:to`. This parameter is optional and defaults to the name being delegated (`funs`). ## Examples defmodule MyList do defdelegate reverse(list), to: Enum defdelegate other_reverse(list), to: Enum, as: :reverse end MyList.reverse([1, 2, 3]) #=> [3, 2, 1] MyList.other_reverse([1, 2, 3]) #=> [3, 2, 1] """ defmacro defdelegate(funs, opts) do funs = Macro.escape(funs, unquote: true) # don't add compile-time dependency on :to opts = with true <- is_list(opts), {:ok, target} <- Keyword.fetch(opts, :to), {:__aliases__, _, _} <- target do target = Macro.expand(target, %{__CALLER__ | function: {:__info__, 1}}) Keyword.replace!(opts, :to, target) else _ -> opts end quote bind_quoted: [funs: funs, opts: opts] do target = Keyword.get(opts, :to) || raise ArgumentError, "expected to: to be given as argument" if is_list(funs) do IO.warn( "passing a list to Kernel.defdelegate/2 is deprecated, please define each delegate separately", Macro.Env.stacktrace(__ENV__) ) end if Keyword.has_key?(opts, :append_first) do IO.warn( "Kernel.defdelegate/2 :append_first option is deprecated", Macro.Env.stacktrace(__ENV__) ) end for fun <- List.wrap(funs) do {name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts) @doc delegate_to: {target, as, :erlang.length(as_args)} def unquote(name)(unquote_splicing(args)) do unquote(target).unquote(as)(unquote_splicing(as_args)) end end end end ## Sigils @doc ~S""" Handles the sigil `~S` for strings. It returns a string without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Examples iex> ~S(foo) "foo" iex> ~S(f#{o}o) "f\#{o}o" iex> ~S(\o/) "\\o/" However, if you want to re-use the sigil character itself on the string, you need to escape it: iex> ~S((\)) "()" """ defmacro sigil_S(term, modifiers) defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary @doc ~S""" Handles the sigil `~s` for strings. It returns a string as if it was a double quoted string, unescaping characters and replacing interpolations. ## Examples iex> ~s(foo) "foo" iex> ~s(f#{:o}o) "foo" iex> ~s(f\#{:o}o) "f\#{:o}o" """ defmacro sigil_s(term, modifiers) defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do :elixir_interpolation.unescape_chars(piece) end defmacro sigil_s({:<<>>, line, pieces}, []) do {:<<>>, line, unescape_tokens(pieces)} end @doc ~S""" Handles the sigil `~C` for charlists. It returns a charlist without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Examples iex> ~C(foo) 'foo' iex> ~C(f#{o}o) 'f\#{o}o' """ defmacro sigil_C(term, modifiers) defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do String.to_charlist(string) end @doc ~S""" Handles the sigil `~c` for charlists. It returns a charlist as if it was a single quoted string, unescaping characters and replacing interpolations. ## Examples iex> ~c(foo) 'foo' iex> ~c(f#{:o}o) 'foo' iex> ~c(f\#{:o}o) 'f\#{:o}o' """ defmacro sigil_c(term, modifiers) # We can skip the runtime conversion if we are # creating a binary made solely of series of chars. defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do String.to_charlist(:elixir_interpolation.unescape_chars(string)) end defmacro sigil_c({:<<>>, _meta, pieces}, []) do quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces)))) end @doc """ Handles the sigil `~r` for regular expressions. It returns a regular expression pattern, unescaping characters and replacing interpolations. More information on regular expressions can be found in the `Regex` module. ## Examples iex> Regex.match?(~r(foo), "foo") true iex> Regex.match?(~r/a#{:b}c/, "abc") true """ defmacro sigil_r(term, modifiers) defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do binary = :elixir_interpolation.unescape_chars(string, &Regex.unescape_map/1) regex = Regex.compile!(binary, :binary.list_to_bin(options)) Macro.escape(regex) end defmacro sigil_r({:<<>>, meta, pieces}, options) do binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map/1)} quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))) end @doc ~S""" Handles the sigil `~R` for regular expressions. It returns a regular expression pattern without interpolations and without escape characters. Note it still supports escape of Regex tokens (such as escaping `+` or `?`) and it also requires you to escape the closing sigil character itself if it appears on the Regex. More information on regexes can be found in the `Regex` module. ## Examples iex> Regex.match?(~R(f#{1,3}o), "f#o") true """ defmacro sigil_R(term, modifiers) defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do regex = Regex.compile!(string, :binary.list_to_bin(options)) Macro.escape(regex) end @doc ~S""" Handles the sigil `~D` for dates. By default, this sigil uses the built-in `Calendar.ISO`, which requires dates to be written in the ISO8601 format: ~D[yyyy-mm-dd] such as: ~D[2015-01-13] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~D[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~d` variant does not exist as interpolation and escape characters are not useful for date sigils. More information on dates can be found in the `Date` module. ## Examples iex> ~D[2015-01-13] ~D[2015-01-13] """ defmacro sigil_D(date_string, modifiers) defmacro sigil_D({:<<>>, _, [string]}, []) do {{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, "Date") to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day) end @doc ~S""" Handles the sigil `~T` for times. By default, this sigil uses the built-in `Calendar.ISO`, which requires times to be written in the ISO8601 format: ~T[hh:mm:ss] ~T[hh:mm:ss.ssssss] such as: ~T[13:00:07] ~T[13:00:07.123] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~T[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~t` variant does not exist as interpolation and escape characters are not useful for time sigils. More information on times can be found in the `Time` module. ## Examples iex> ~T[13:00:07] ~T[13:00:07] iex> ~T[13:00:07.001] ~T[13:00:07.001] """ defmacro sigil_T(time_string, modifiers) defmacro sigil_T({:<<>>, _, [string]}, []) do {{:ok, {hour, minute, second, microsecond}}, calendar} = parse_with_calendar!(string, :parse_time, "Time") to_calendar_struct(Time, calendar: calendar, hour: hour, minute: minute, second: second, microsecond: microsecond ) end @doc ~S""" Handles the sigil `~N` for naive date times. By default, this sigil uses the built-in `Calendar.ISO`, which requires naive date times to be written in the ISO8601 format: ~N[yyyy-mm-dd hh:mm:ss] ~N[yyyy-mm-dd hh:mm:ss.ssssss] ~N[yyyy-mm-ddThh:mm:ss.ssssss] such as: ~N[2015-01-13 13:00:07] ~N[2015-01-13T13:00:07.123] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~N[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~n` variant does not exist as interpolation and escape characters are not useful for date time sigils. More information on naive date times can be found in the `NaiveDateTime` module. ## Examples iex> ~N[2015-01-13 13:00:07] ~N[2015-01-13 13:00:07] iex> ~N[2015-01-13T13:00:07.001] ~N[2015-01-13 13:00:07.001] """ defmacro sigil_N(naive_datetime_string, modifiers) defmacro sigil_N({:<<>>, _, [string]}, []) do {{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} = parse_with_calendar!(string, :parse_naive_datetime, "NaiveDateTime") to_calendar_struct(NaiveDateTime, calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond ) end @doc ~S""" Handles the sigil `~U` to create a UTC `DateTime`. By default, this sigil uses the built-in `Calendar.ISO`, which requires UTC date times to be written in the ISO8601 format: ~U[yyyy-mm-dd hh:mm:ssZ] ~U[yyyy-mm-dd hh:mm:ss.ssssssZ] ~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00] such as: ~U[2015-01-13 13:00:07Z] ~U[2015-01-13T13:00:07.123+00:00] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~U[SOME-REPRESENTATION My.Alternative.Calendar] The given `datetime_string` must include "Z" or "00:00" offset which marks it as UTC, otherwise an error is raised. The lower case `~u` variant does not exist as interpolation and escape characters are not useful for date time sigils. More information on date times can be found in the `DateTime` module. ## Examples iex> ~U[2015-01-13 13:00:07Z] ~U[2015-01-13 13:00:07Z] iex> ~U[2015-01-13T13:00:07.001+00:00] ~U[2015-01-13 13:00:07.001Z] """ @doc since: "1.9.0" defmacro sigil_U(datetime_string, modifiers) defmacro sigil_U({:<<>>, _, [string]}, []) do {{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} = parse_with_calendar!(string, :parse_utc_datetime, "UTC DateTime") if offset != 0 do raise ArgumentError, "cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset" end to_calendar_struct(DateTime, calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond, time_zone: "Etc/UTC", zone_abbr: "UTC", utc_offset: 0, std_offset: 0 ) end defp parse_with_calendar!(string, fun, context) do {calendar, string} = extract_calendar(string) result = apply(calendar, fun, [string]) {maybe_raise!(result, calendar, context, string), calendar} end defp extract_calendar(string) do case :binary.split(string, " ", [:global]) do [_] -> {Calendar.ISO, string} parts -> maybe_atomize_calendar(List.last(parts), string) end end defp maybe_atomize_calendar(<<alias, _::binary>> = last_part, string) when alias >= ?A and alias <= ?Z do string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1) {String.to_atom("Elixir." <> last_part), string} end defp maybe_atomize_calendar(_last_part, string) do {Calendar.ISO, string} end defp maybe_raise!({:error, reason}, calendar, type, string) do raise ArgumentError, "cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, " <> "reason: #{inspect(reason)}" end defp maybe_raise!(other, _calendar, _type, _string), do: other defp to_calendar_struct(type, fields) do quote do %{unquote_splicing([__struct__: type] ++ fields)} end end @doc ~S""" Handles the sigil `~w` for list of words. It returns a list of "words" split by whitespace. Character unescaping and interpolation happens for each word. ## Modifiers * `s`: words in the list are strings (default) * `a`: words in the list are atoms * `c`: words in the list are charlists ## Examples iex> ~w(foo #{:bar} baz) ["foo", "bar", "baz"] iex> ~w(foo #{" bar baz "}) ["foo", "bar", "baz"] iex> ~w(--source test/enum_test.exs) ["--source", "test/enum_test.exs"] iex> ~w(foo bar baz)a [:foo, :bar, :baz] """ defmacro sigil_w(term, modifiers) defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do split_words(:elixir_interpolation.unescape_chars(string), modifiers, __CALLER__) end defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do binary = {:<<>>, meta, unescape_tokens(pieces)} split_words(binary, modifiers, __CALLER__) end @doc ~S""" Handles the sigil `~W` for list of words. It returns a list of "words" split by whitespace without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Modifiers * `s`: words in the list are strings (default) * `a`: words in the list are atoms * `c`: words in the list are charlists ## Examples iex> ~W(foo #{bar} baz) ["foo", "\#{bar}", "baz"] """ defmacro sigil_W(term, modifiers) defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do split_words(string, modifiers, __CALLER__) end defp split_words(string, [], caller) do split_words(string, [?s], caller) end defp split_words(string, [mod], caller) when mod == ?s or mod == ?a or mod == ?c do case is_binary(string) do true -> parts = String.split(string) parts_with_trailing_comma = :lists.filter(&(byte_size(&1) > 1 and :binary.last(&1) == ?,), parts) if parts_with_trailing_comma != [] do stacktrace = Macro.Env.stacktrace(caller) IO.warn( "the sigils ~w/~W do not allow trailing commas at the end of each word. " <> "If the comma is necessary, define a regular list with [...], otherwise remove the comma.", stacktrace ) end case mod do ?s -> parts ?a -> :lists.map(&String.to_atom/1, parts) ?c -> :lists.map(&String.to_charlist/1, parts) end false -> parts = quote(do: String.split(unquote(string))) case mod do ?s -> parts ?a -> quote(do: :lists.map(&String.to_atom/1, unquote(parts))) ?c -> quote(do: :lists.map(&String.to_charlist/1, unquote(parts))) end end end defp split_words(_string, _mods, _caller) do raise ArgumentError, "modifier must be one of: s, a, c" end ## Shared functions defp assert_module_scope(env, fun, arity) do case env.module do nil -> raise ArgumentError, "cannot invoke #{fun}/#{arity} outside module" mod -> mod end end defp assert_no_function_scope(env, fun, arity) do case env.function do nil -> :ok _ -> raise ArgumentError, "cannot invoke #{fun}/#{arity} inside function/macro" end end defp assert_no_match_or_guard_scope(context, exp) do case context do :match -> invalid_match!(exp) :guard -> raise ArgumentError, "invalid expression in guard, #{exp} is not allowed in guards. " <> "To learn more about guards, visit: https://hexdocs.pm/elixir/patterns-and-guards.html" _ -> :ok end end defp invalid_match!(exp) do raise ArgumentError, "invalid expression in match, #{exp} is not allowed in patterns " <> "such as function clauses, case clauses or on the left side of the = operator" end # Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens defp unescape_tokens(tokens) do case :elixir_interpolation.unescape_tokens(tokens) do {:ok, unescaped_tokens} -> unescaped_tokens {:error, reason} -> raise ArgumentError, to_string(reason) end end defp unescape_tokens(tokens, unescape_map) do case :elixir_interpolation.unescape_tokens(tokens, unescape_map) do {:ok, unescaped_tokens} -> unescaped_tokens {:error, reason} -> raise ArgumentError, to_string(reason) end end defp unescape_list_tokens(tokens) do escape = fn {:"::", _, [expr, _]} -> expr binary when is_binary(binary) -> :elixir_interpolation.unescape_chars(binary) end :lists.map(escape, tokens) end @doc false defmacro to_char_list(arg) do IO.warn( "Kernel.to_char_list/1 is deprecated, use Kernel.to_charlist/1 instead", Macro.Env.stacktrace(__CALLER__) ) quote(do: Kernel.to_charlist(unquote(arg))) end end
26.812105
116
0.6338
797bc0d43218d2cc3e9e891cfa894762922efd0e
71
exs
Elixir
test/test_helper.exs
Swuber/Epik-Club
0e56e602f0934e0e6225c7456bcb37f5b852be2d
[ "Apache-2.0" ]
2
2017-04-23T17:31:55.000Z
2017-07-22T12:54:24.000Z
test/test_helper.exs
Swuber/Epik-Club
0e56e602f0934e0e6225c7456bcb37f5b852be2d
[ "Apache-2.0" ]
7
2017-04-11T18:42:57.000Z
2017-04-16T22:54:11.000Z
test/test_helper.exs
MichaelDimmitt/unf-swuber
7c205c6e80bcc3ef4ee55490ad497061253bcc61
[ "Apache-2.0" ]
3
2017-08-10T22:54:28.000Z
2018-10-18T22:32:55.000Z
ExUnit.start Ecto.Adapters.SQL.Sandbox.mode(UnfSwuber.Repo, :manual)
14.2
55
0.788732
797bc8397974ca48846ba3c0d69ffd7f9bd9c422
2,421
ex
Elixir
lib/livebook_web/live/session_live/export_live_markdown_component.ex
mgibowski/livebook
bfb9dc371e386597219a398a180d69c0bfa2f384
[ "Apache-2.0" ]
1,846
2021-04-13T14:46:36.000Z
2021-07-14T20:37:40.000Z
lib/livebook_web/live/session_live/export_live_markdown_component.ex
mgibowski/livebook
bfb9dc371e386597219a398a180d69c0bfa2f384
[ "Apache-2.0" ]
411
2021-07-15T07:41:54.000Z
2022-03-31T21:34:22.000Z
lib/livebook_web/live/session_live/export_live_markdown_component.ex
mgibowski/livebook
bfb9dc371e386597219a398a180d69c0bfa2f384
[ "Apache-2.0" ]
130
2021-04-13T15:43:55.000Z
2021-07-12T16:57:46.000Z
defmodule LivebookWeb.SessionLive.ExportLiveMarkdownComponent do use LivebookWeb, :live_component @impl true def update(assigns, socket) do socket = assign(socket, assigns) {:ok, socket |> assign_new(:include_outputs, fn -> socket.assigns.notebook.persist_outputs end) |> assign_source()} end defp assign_source(%{assigns: assigns} = socket) do source = Livebook.LiveMarkdown.Export.notebook_to_markdown(assigns.notebook, include_outputs: assigns.include_outputs ) assign(socket, :source, source) end @impl true def render(assigns) do ~H""" <div class="flex flex-col space-y-6"> <div class="flex"> <form phx-change="set_options" onsubmit="return false;" phx-target={@myself}> <.switch_checkbox name="include_outputs" label="Include outputs" checked={@include_outputs} /> </form> </div> <div class="flex flex-col space-y-1"> <div class="flex justify-between items-center"> <span class="text-sm text-gray-700 font-semibold"> .livemd </span> <div class="flex justify-end space-x-2"> <span class="tooltip left" data-tooltip="Copy source"> <button class="icon-button" aria-label="copy source" phx-click={JS.dispatch("lb:clipcopy", to: "#export-notebook-source")}> <.remix_icon icon="clipboard-line" class="text-lg" /> </button> </span> <span class="tooltip left" data-tooltip="Download source"> <a class="icon-button" aria-label="download source" href={Routes.session_path(@socket, :download_source, @session.id, "livemd", include_outputs: @include_outputs)}> <.remix_icon icon="download-2-line" class="text-lg" /> </a> </span> </div> </div> <div class="markdown"> <.code_preview source_id="export-notebook-source" language="markdown" source={@source} /> </div> </div> </div> """ end @impl true def handle_event("set_options", %{"include_outputs" => include_outputs}, socket) do include_outputs = include_outputs == "true" {:noreply, socket |> assign(include_outputs: include_outputs) |> assign_source()} end end
32.716216
128
0.586948
797c73a8b13842381aae447bd06bf6f33fb0531b
436
exs
Elixir
test/well_test.exs
lupinthe14th/codewars
5c71a1be6dd5c42a6217d70e5cfcd43c6c016ac7
[ "MIT" ]
null
null
null
test/well_test.exs
lupinthe14th/codewars
5c71a1be6dd5c42a6217d70e5cfcd43c6c016ac7
[ "MIT" ]
70
2020-01-07T01:21:38.000Z
2021-06-18T02:57:39.000Z
test/well_test.exs
lupinthe14th/codewars
5c71a1be6dd5c42a6217d70e5cfcd43c6c016ac7
[ "MIT" ]
null
null
null
defmodule TestWell do use ExUnit.Case defp testing(x, exp) do act = Well.well(x) assert act == exp, "Given list #{inspect(x)}, expected #{exp}, got #{act}" end test "basic tests" do testing(["bad", "bad", "bad"], "Fail!") testing(["good", "bad", "bad", "bad", "bad"], "Publish!") testing( ["good", "bad", "bad", "bad", "bad", "good", "bad", "bad", "good"], "I smell a series!" ) end end
22.947368
78
0.53211
797c7580b3ce48afd4d7084ae108f87146a4e139
378
ex
Elixir
plugins/one_pages/lib/one_pages_web/views/error_view.ex
smpallen99/ucx_ucc
47225f205a6ac4aacdb9bb4f7512dcf4092576ad
[ "MIT" ]
11
2017-05-15T18:35:05.000Z
2018-02-05T18:27:40.000Z
plugins/one_pages/lib/one_pages_web/views/error_view.ex
anndream/infinity_one
47225f205a6ac4aacdb9bb4f7512dcf4092576ad
[ "MIT" ]
15
2017-11-27T10:38:05.000Z
2018-02-09T20:42:08.000Z
plugins/one_pages/lib/one_pages_web/views/error_view.ex
anndream/infinity_one
47225f205a6ac4aacdb9bb4f7512dcf4092576ad
[ "MIT" ]
4
2017-09-13T11:34:16.000Z
2018-02-26T13:37:06.000Z
defmodule OnePagesWeb.ErrorView do use OnePagesWeb, :view def render("404.html", _assigns) do "Page not found" end def render("500.html", _assigns) do "Internal server error" end # In case no render clause matches or no # template is found, let's render it as 500 def template_not_found(_template, assigns) do render "500.html", assigns end end
21
47
0.703704
797c7a354effacad4162bb8177468a1f07e066bf
212
ex
Elixir
lib/hexpm/web/views/docs_view.ex
hubertpompecki/hexpm
5cd4208b07a70bf2e1490930bf5d577978793b50
[ "Apache-2.0" ]
null
null
null
lib/hexpm/web/views/docs_view.ex
hubertpompecki/hexpm
5cd4208b07a70bf2e1490930bf5d577978793b50
[ "Apache-2.0" ]
null
null
null
lib/hexpm/web/views/docs_view.ex
hubertpompecki/hexpm
5cd4208b07a70bf2e1490930bf5d577978793b50
[ "Apache-2.0" ]
null
null
null
defmodule Hexpm.Web.DocsView do use Hexpm.Web, :view alias Hexpm.Web.DocsView def selected_docs(conn, view) do if conn.assigns.view_name == view do "selected" else "" end end end
16.307692
40
0.650943
797c7b52507c5d040c39140116ff5495c76b78e4
30,629
ex
Elixir
clients/alert_center/lib/google_api/alert_center/v1beta1/api/alerts.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/alert_center/lib/google_api/alert_center/v1beta1/api/alerts.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/alert_center/lib/google_api/alert_center/v1beta1/api/alerts.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AlertCenter.V1beta1.Api.Alerts do @moduledoc """ API calls for all endpoints tagged `Alerts`. """ alias GoogleApi.AlertCenter.V1beta1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Performs batch delete operation on alerts. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AlertCenter.V1beta1.Model.BatchDeleteAlertsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.BatchDeleteAlertsResponse{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_batch_delete(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.BatchDeleteAlertsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_batch_delete(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1beta1/alerts:batchDelete", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.BatchDeleteAlertsResponse{}] ) end @doc """ Performs batch undelete operation on alerts. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AlertCenter.V1beta1.Model.BatchUndeleteAlertsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.BatchUndeleteAlertsResponse{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_batch_undelete(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.BatchUndeleteAlertsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_batch_undelete(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1beta1/alerts:batchUndelete", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.BatchUndeleteAlertsResponse{}] ) end @doc """ Marks the specified alert for deletion. An alert that has been marked for deletion is removed from Alert Center after 30 days. Marking an alert for deletion has no effect on an alert which has already been marked for deletion. Attempting to mark a nonexistent alert for deletion results in a `NOT_FOUND` error. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `alert_id` (*type:* `String.t`) - Required. The identifier of the alert to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:customerId` (*type:* `String.t`) - Optional. The unique identifier of the Google Workspace organization account of the customer the alert is associated with. Inferred from the caller identity if not provided. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_delete(connection, alert_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :customerId => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1beta1/alerts/{alertId}", %{ "alertId" => URI.encode(alert_id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.Empty{}]) end @doc """ Gets the specified alert. Attempting to get a nonexistent alert returns `NOT_FOUND` error. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `alert_id` (*type:* `String.t`) - Required. The identifier of the alert to retrieve. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:customerId` (*type:* `String.t`) - Optional. The unique identifier of the Google Workspace organization account of the customer the alert is associated with. Inferred from the caller identity if not provided. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.Alert{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.Alert.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_get(connection, alert_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :customerId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1beta1/alerts/{alertId}", %{ "alertId" => URI.encode(alert_id, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.Alert{}]) end @doc """ Returns the metadata of an alert. Attempting to get metadata for a non-existent alert returns `NOT_FOUND` error. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `alert_id` (*type:* `String.t`) - Required. The identifier of the alert this metadata belongs to. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:customerId` (*type:* `String.t`) - Optional. The unique identifier of the Google Workspace organization account of the customer the alert metadata is associated with. Inferred from the caller identity if not provided. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.AlertMetadata{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_get_metadata(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.AlertMetadata.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_get_metadata(connection, alert_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :customerId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1beta1/alerts/{alertId}/metadata", %{ "alertId" => URI.encode(alert_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.AlertMetadata{}]) end @doc """ Lists the alerts. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:customerId` (*type:* `String.t`) - Optional. The unique identifier of the Google Workspace organization account of the customer the alerts are associated with. Inferred from the caller identity if not provided. * `:filter` (*type:* `String.t`) - Optional. A query string for filtering alert results. For more details, see [Query filters](https://developers.google.com/admin-sdk/alertcenter/guides/query-filters) and [Supported query filter fields](https://developers.google.com/admin-sdk/alertcenter/reference/filter-fields#alerts.list). * `:orderBy` (*type:* `String.t`) - Optional. The sort order of the list results. If not specified results may be returned in arbitrary order. You can sort the results in descending order based on the creation timestamp using `order_by="create_time desc"`. Currently, supported sorting are `create_time asc`, `create_time desc`, `update_time desc` * `:pageSize` (*type:* `integer()`) - Optional. The requested page size. Server may return fewer items than requested. If unspecified, server picks an appropriate default. * `:pageToken` (*type:* `String.t`) - Optional. A token identifying a page of results the server should return. If empty, a new iteration is started. To continue an iteration, pass in the value from the previous ListAlertsResponse's next_page_token field. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.ListAlertsResponse{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_list(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.ListAlertsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_list(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :customerId => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1beta1/alerts", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.ListAlertsResponse{}] ) end @doc """ Restores, or "undeletes", an alert that was marked for deletion within the past 30 days. Attempting to undelete an alert which was marked for deletion over 30 days ago (which has been removed from the Alert Center database) or a nonexistent alert returns a `NOT_FOUND` error. Attempting to undelete an alert which has not been marked for deletion has no effect. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `alert_id` (*type:* `String.t`) - Required. The identifier of the alert to undelete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.AlertCenter.V1beta1.Model.UndeleteAlertRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.Alert{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_undelete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.Alert.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_undelete(connection, alert_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1beta1/alerts/{alertId}:undelete", %{ "alertId" => URI.encode(alert_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.Alert{}]) end @doc """ Creates new feedback for an alert. Attempting to create a feedback for a non-existent alert returns `NOT_FOUND` error. Attempting to create a feedback for an alert that is marked for deletion returns `FAILED_PRECONDITION' error. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `alert_id` (*type:* `String.t`) - Required. The identifier of the alert this feedback belongs to. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:customerId` (*type:* `String.t`) - Optional. The unique identifier of the Google Workspace organization account of the customer the alert is associated with. Inferred from the caller identity if not provided. * `:body` (*type:* `GoogleApi.AlertCenter.V1beta1.Model.AlertFeedback.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.AlertFeedback{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_feedback_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.AlertFeedback.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_feedback_create(connection, alert_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :customerId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1beta1/alerts/{alertId}/feedback", %{ "alertId" => URI.encode(alert_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.AlertFeedback{}]) end @doc """ Lists all the feedback for an alert. Attempting to list feedbacks for a non-existent alert returns `NOT_FOUND` error. ## Parameters * `connection` (*type:* `GoogleApi.AlertCenter.V1beta1.Connection.t`) - Connection to server * `alert_id` (*type:* `String.t`) - Required. The alert identifier. The "-" wildcard could be used to represent all alerts. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:customerId` (*type:* `String.t`) - Optional. The unique identifier of the Google Workspace organization account of the customer the alert feedback are associated with. Inferred from the caller identity if not provided. * `:filter` (*type:* `String.t`) - Optional. A query string for filtering alert feedback results. For more details, see [Query filters](https://developers.google.com/admin-sdk/alertcenter/guides/query-filters) and [Supported query filter fields](https://developers.google.com/admin-sdk/alertcenter/reference/filter-fields#alerts.feedback.list). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AlertCenter.V1beta1.Model.ListAlertFeedbackResponse{}}` on success * `{:error, info}` on failure """ @spec alertcenter_alerts_feedback_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.AlertCenter.V1beta1.Model.ListAlertFeedbackResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def alertcenter_alerts_feedback_list(connection, alert_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :customerId => :query, :filter => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1beta1/alerts/{alertId}/feedback", %{ "alertId" => URI.encode(alert_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AlertCenter.V1beta1.Model.ListAlertFeedbackResponse{}] ) end end
51.304858
363
0.637305
797c8fe9c418bb91cb0c59d3c1880502de9e15b4
812
ex
Elixir
lib/ex_polygon/rest/crypto/exchanges.ex
aai/ex_polygon
3bd6d8d0f1fbe4cd3fa939751c5ff00813eeeba3
[ "MIT" ]
null
null
null
lib/ex_polygon/rest/crypto/exchanges.ex
aai/ex_polygon
3bd6d8d0f1fbe4cd3fa939751c5ff00813eeeba3
[ "MIT" ]
null
null
null
lib/ex_polygon/rest/crypto/exchanges.ex
aai/ex_polygon
3bd6d8d0f1fbe4cd3fa939751c5ff00813eeeba3
[ "MIT" ]
null
null
null
defmodule ExPolygon.Rest.Crypto.Exchanges do @moduledoc """ Returns a call to "Crypto Exchanges" Polygon.io """ @type crypto :: ExPolygon.CryptoExchange.t() @type api_key :: ExPolygon.Rest.HTTPClient.api_key() @type shared_error_reasons :: ExPolygon.Rest.HTTPClient.shared_error_reasons() @path "/v1/meta/crypto-exchanges" @spec query(api_key) :: {:ok, [crypto]} | {:error, shared_error_reasons} def query(api_key) do with {:ok, data} <- ExPolygon.Rest.HTTPClient.get(@path, %{}, api_key) do parse_response(data) end end defp parse_response(data) do list_crypto = data |> Enum.map( &Mapail.map_to_struct(&1, ExPolygon.CryptoExchange, transformations: [:snake_case]) ) |> Enum.map(fn {:ok, t} -> t end) {:ok, list_crypto} end end
27.066667
91
0.666256
797c9d13226242cba99285b9f0c459c022108b04
702
ex
Elixir
lib/cadet_web/gettext.ex
Hou-Rui/cadet
f9036d76005bf3b267b632dce176067ae1a19f71
[ "Apache-2.0" ]
27
2018-01-20T05:56:24.000Z
2021-05-24T03:21:55.000Z
lib/cadet_web/gettext.ex
Hou-Rui/cadet
f9036d76005bf3b267b632dce176067ae1a19f71
[ "Apache-2.0" ]
731
2018-04-16T13:25:49.000Z
2021-06-22T07:16:12.000Z
lib/cadet_web/gettext.ex
Hou-Rui/cadet
f9036d76005bf3b267b632dce176067ae1a19f71
[ "Apache-2.0" ]
43
2018-01-20T06:35:46.000Z
2021-05-05T03:22:35.000Z
defmodule CadetWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import CadetWeb.Gettext # Simple translation gettext "Here is the string to translate" # Plural translation ngettext "Here is the string to translate", "Here are the strings to translate", 3 # Domain-based translation dgettext "errors", "Here is the error message to translate" See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :cadet end
28.08
72
0.678063
797cbb3500d165352d7e8e3e892ca507a9f6603e
185
ex
Elixir
lib/http_behaviour.ex
karlosmid/exkeycdn
4f8a756b2ea7b5bcb2d2821509250004ed8850ea
[ "MIT" ]
null
null
null
lib/http_behaviour.ex
karlosmid/exkeycdn
4f8a756b2ea7b5bcb2d2821509250004ed8850ea
[ "MIT" ]
null
null
null
lib/http_behaviour.ex
karlosmid/exkeycdn
4f8a756b2ea7b5bcb2d2821509250004ed8850ea
[ "MIT" ]
null
null
null
defmodule ExKeyCDN.HTTPBehaviour do @moduledoc """ HTTP Behaviour """ @doc """ Sends http request """ @callback request(atom, binary, binary | map) :: HTTP.response() end
18.5
66
0.659459
797cc416720483a2d4623b30be146d2a6842c299
514
exs
Elixir
test/arfficionado_test.exs
patrick7777776/arfficionado
8684a918f2f6c89023bd484965d0e19fa82a57ff
[ "Apache-2.0" ]
null
null
null
test/arfficionado_test.exs
patrick7777776/arfficionado
8684a918f2f6c89023bd484965d0e19fa82a57ff
[ "Apache-2.0" ]
null
null
null
test/arfficionado_test.exs
patrick7777776/arfficionado
8684a918f2f6c89023bd484965d0e19fa82a57ff
[ "Apache-2.0" ]
null
null
null
defmodule ArfficionadoTest do use ExUnit.Case import Arfficionado, only: [read: 2] doctest Arfficionado test "a fine short arff file" do assert read(~s""" @relation foo @attribute a1 integer @attribute a2 integer @data 1,2 3,4, {5} """) == {:ok, [{[1, 2], 1}, {[3, 4], 5}]} end defp read(s) do {:ok, stream} = StringIO.open(s) stream |> IO.binstream(:line) |> read(Arfficionado.ListHandler) end end
19.769231
52
0.533074
797ccd57d605b8c5392fdcc13ba89fa1c0e285dd
1,175
exs
Elixir
instrumentation/opentelemetry_phoenix/config/config.exs
RudolfMan/opentelemetry-erlang-contrib
44fd2a6871742380dd6adc112f9776cda501ff1f
[ "Apache-2.0" ]
24
2021-05-07T18:37:11.000Z
2022-03-13T06:21:00.000Z
instrumentation/opentelemetry_phoenix/config/config.exs
RudolfMan/opentelemetry-erlang-contrib
44fd2a6871742380dd6adc112f9776cda501ff1f
[ "Apache-2.0" ]
42
2021-05-10T20:19:22.000Z
2022-03-31T17:48:13.000Z
instrumentation/opentelemetry_phoenix/config/config.exs
RudolfMan/opentelemetry-erlang-contrib
44fd2a6871742380dd6adc112f9776cda501ff1f
[ "Apache-2.0" ]
19
2021-08-30T01:33:54.000Z
2022-03-20T22:01:15.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. import Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # third-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :opentelemetry_ecto, key: :value # # and access this configuration in your application as: # # Application.get_env(:opentelemetry_ecto, :key) # # You can also configure a third-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # try do import_config "#{Mix.env()}.exs" rescue _ -> :ok end
33.571429
73
0.754894
797cf43f36a355257de8b998754ac77811877d6f
242
exs
Elixir
priv/repo/migrations/20180210120511_create_topics.exs
a-sac/HighTopics
e99b2cc517d5b552bc7f44aae9774357c8bb427b
[ "MIT" ]
null
null
null
priv/repo/migrations/20180210120511_create_topics.exs
a-sac/HighTopics
e99b2cc517d5b552bc7f44aae9774357c8bb427b
[ "MIT" ]
null
null
null
priv/repo/migrations/20180210120511_create_topics.exs
a-sac/HighTopics
e99b2cc517d5b552bc7f44aae9774357c8bb427b
[ "MIT" ]
null
null
null
defmodule Hightopics.Repo.Migrations.CreateTopics do use Ecto.Migration def change do create table(:topics) do add :name, :string add :description, :text add :rating, :integer timestamps() end end end
16.133333
52
0.657025
797cfeaee70120596b19cb6d9411d69216cfc464
683
exs
Elixir
apps/thumbnail_server/mix.exs
salmanebah/gen_thumbnail
58e8e0ce8661b18725704c04cf2f33d7edd6e51e
[ "MIT" ]
1
2019-06-06T12:03:37.000Z
2019-06-06T12:03:37.000Z
apps/thumbnail_server/mix.exs
salmanebah/gen_thumbnail
58e8e0ce8661b18725704c04cf2f33d7edd6e51e
[ "MIT" ]
null
null
null
apps/thumbnail_server/mix.exs
salmanebah/gen_thumbnail
58e8e0ce8661b18725704c04cf2f33d7edd6e51e
[ "MIT" ]
null
null
null
defmodule ThumbnailServer.MixProject do use Mix.Project def project do [ app: :thumbnail_server, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.8", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {ThumbnailServer.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:elixir_uuid, "~> 1.2"} ] end end
20.69697
59
0.566618
797d11a463362a0b501039ae9b0c42897ffed59d
3,009
ex
Elixir
apps/engine/lib/engine/ethereum/event/coordinator.ex
omgnetwork/omg-childchain-v2
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
[ "Apache-2.0" ]
4
2020-11-30T17:38:57.000Z
2021-01-23T21:29:41.000Z
apps/engine/lib/engine/ethereum/event/coordinator.ex
omgnetwork/omg-childchain-v2
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
[ "Apache-2.0" ]
24
2020-11-30T17:32:48.000Z
2021-02-22T06:25:22.000Z
apps/engine/lib/engine/ethereum/event/coordinator.ex
omgnetwork/omg-childchain-v2
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
[ "Apache-2.0" ]
null
null
null
defmodule Engine.Ethereum.Event.Coordinator do @moduledoc """ Synchronizes services on root chain height, see `Coordinator.Core` """ use GenServer alias Engine.Ethereum.Event.Coordinator.Core alias Engine.Ethereum.Event.Coordinator.SyncGuide alias Engine.Ethereum.Height require Logger # use Spandex.Decorators @doc """ Notifies that calling service with name `service_name` is synced up to height `synced_height`. `synced_height` is the height that the service is synced when calling this function. """ # @decorate span(service: :ethereum_event_listener, type: :backend, name: "check_in/2") @spec check_in(non_neg_integer(), atom()) :: :ok def check_in(synced_height, service_name) do GenServer.call(__MODULE__, {:check_in, synced_height, service_name}) end @doc """ Gets Ethereum height that services can synchronize up to. """ # @decorate span(service: :ethereum_event_listener, type: :backend, name: "get_sync_info/0") @spec get_sync_info() :: SyncGuide.t() | :nosync def get_sync_info() do GenServer.call(__MODULE__, :get_sync_info) end @spec start_link(Core.configs_services()) :: GenServer.on_start() def start_link(configs_services) do GenServer.start_link(__MODULE__, configs_services, name: __MODULE__) end def init({args, configs_services}) do {:ok, {args, configs_services}, {:continue, :setup}} end def handle_continue(:setup, {args, configs_services}) do _ = Logger.info("Starting #{__MODULE__} service. #{inspect({args, configs_services})}") metrics_collection_interval = Keyword.fetch!(args, :metrics_collection_interval) {:ok, rootchain_height} = Height.get() :ok = Bus.subscribe({:root_chain, "ethereum_new_height"}, link: true) state = Core.init(configs_services, rootchain_height) configs_services |> Map.keys() |> request_sync() {:ok, _} = :timer.send_interval(metrics_collection_interval, self(), :send_metrics) _ = Logger.info("Started #{inspect(__MODULE__)}") {:noreply, state} end def handle_info(:send_metrics, state) do :ok = :telemetry.execute([:process, __MODULE__], %{}, state) {:noreply, state} end def handle_info({:internal_event_bus, :ethereum_new_height, root_chain_height}, state) do {:ok, state} = Core.update_root_chain_height(state, root_chain_height) {:noreply, state} end def handle_call({:check_in, synced_height, service_name}, {pid, _ref}, state) do _ = Logger.debug("#{inspect(service_name)} checks in on height #{inspect(synced_height)}") {:ok, state} = Core.check_in(state, pid, synced_height, service_name) {:reply, :ok, state} end def handle_call(:get_sync_info, {pid, _}, state) do {:reply, Core.get_synced_info(state, pid), state} end def handle_call(:get_ethereum_heights, _from, state) do {:reply, {:ok, Core.get_ethereum_heights(state)}, state} end defp request_sync(services) do Enum.each(services, fn service -> GenServer.cast(service, :sync) end) end end
34.193182
96
0.717182
797d19b2ae507d1cd6545b19e46ce62d621aedfe
609
exs
Elixir
priv/repo/migrations/20190327104558_migrate_repeating_trigger_embedded_field.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
priv/repo/migrations/20190327104558_migrate_repeating_trigger_embedded_field.exs
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
priv/repo/migrations/20190327104558_migrate_repeating_trigger_embedded_field.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Repo.Migrations.MigrateRepeatingTriggerEmbeddedField do use Ecto.Migration def up do Application.ensure_all_started(:timex) execute(""" UPDATE user_triggers SET trigger = trigger - 'repeating' || jsonb_build_object('is_repeating', trigger->'repeating') WHERE trigger ? 'repeating' """) end def down do Application.ensure_all_started(:timex) execute(""" UPDATE user_triggers SET trigger = trigger - 'is_repeating' || jsonb_build_object('repeating', trigger->'is_repeating') WHERE trigger ? 'is_repeating' """) end end
25.375
104
0.691297
797d1a8c8628a1b2a9e34b4a2c0a852fe75a6e7a
12,856
exs
Elixir
test/streams/single_stream_test.exs
LeartS/eventstore
f0431bfefcaa1a6fa8251eb6dd0ae8def1d82961
[ "MIT" ]
null
null
null
test/streams/single_stream_test.exs
LeartS/eventstore
f0431bfefcaa1a6fa8251eb6dd0ae8def1d82961
[ "MIT" ]
null
null
null
test/streams/single_stream_test.exs
LeartS/eventstore
f0431bfefcaa1a6fa8251eb6dd0ae8def1d82961
[ "MIT" ]
null
null
null
defmodule EventStore.Streams.SingleStreamTest do use EventStore.StorageCase alias EventStore.EventData alias EventStore.EventFactory alias EventStore.Streams.Stream alias TestEventStore, as: EventStore @subscription_name "test_subscription" describe "append events to stream" do setup [:append_events_to_stream] test "should persist events", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do {:ok, events} = Stream.read_stream_forward(conn, stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) assert length(events) == 3 end test "should set created at datetime", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do utc_now = DateTime.utc_now() {:ok, [event]} = Stream.read_stream_forward(conn, stream_uuid, 0, 1, schema: schema, serializer: serializer) created_at = event.created_at assert created_at != nil assert created_at.time_zone == utc_now.time_zone assert created_at.zone_abbr == utc_now.zone_abbr assert created_at.utc_offset == utc_now.utc_offset assert created_at.std_offset == utc_now.std_offset diff = DateTime.diff(utc_now, created_at, :millisecond) assert 0 <= diff assert diff < 60_000 end test "for wrong expected version should error", %{ conn: conn, schema: schema, serializer: serializer, events: events, stream_uuid: stream_uuid } do assert {:error, :wrong_expected_version} = Stream.append_to_stream(conn, stream_uuid, 0, events, schema: schema, serializer: serializer ) end end describe "link events to stream" do setup [ :append_events_to_stream, :append_event_to_another_stream ] test "should link events", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: source_stream_uuid, other_stream_uuid: target_stream_uuid } do {:ok, source_events} = Stream.read_stream_forward(conn, source_stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) assert :ok = Stream.link_to_stream(conn, target_stream_uuid, 1, source_events, schema: schema) assert {:ok, events} = Stream.read_stream_forward(conn, target_stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) assert length(events) == 4 assert Enum.map(events, & &1.event_number) == [1, 2, 3, 4] assert Enum.map(events, & &1.stream_version) == [1, 1, 2, 3] for {source, linked} <- Enum.zip(source_events, Enum.drop(events, 1)) do assert source.event_id == linked.event_id assert source.stream_uuid == linked.stream_uuid assert source.stream_version == linked.stream_version assert source.causation_id == linked.causation_id assert source.correlation_id == linked.correlation_id assert source.event_type == linked.event_type assert source.data == linked.data assert source.metadata == linked.metadata assert source.created_at == linked.created_at end end test "should link events with `:any_version` expected version", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: source_stream_uuid, other_stream_uuid: target_stream_uuid } do {:ok, source_events} = Stream.read_stream_forward(conn, source_stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) assert :ok = Stream.link_to_stream(conn, target_stream_uuid, :any_version, source_events, schema: schema ) end test "should fail when wrong expected version", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: source_stream_uuid, other_stream_uuid: target_stream_uuid } do {:ok, source_events} = Stream.read_stream_forward(conn, source_stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) assert {:error, :wrong_expected_version} = Stream.link_to_stream(conn, target_stream_uuid, 0, source_events, schema: schema) end test "should fail linking events that don't exist", %{conn: conn, schema: schema} do stream_uuid = UUID.uuid4() event_ids = [UUID.uuid4()] assert {:error, :not_found} = Stream.link_to_stream(conn, stream_uuid, 0, event_ids, schema: schema) end test "should prevent duplicate linked events", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: source_stream_uuid, other_stream_uuid: target_stream_uuid } do {:ok, source_events} = Stream.read_stream_forward(conn, source_stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) :ok = Stream.link_to_stream(conn, target_stream_uuid, 1, source_events, schema: schema) assert {:error, :duplicate_event} = Stream.link_to_stream(conn, target_stream_uuid, 4, source_events, schema: schema) end test "should guess the event type when not passed", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do {:ok, _subscription} = EventStore.subscribe_to_stream( stream_uuid, @subscription_name, self(), start_from: :current ) event = %EventData{data: %EventFactory.Event{event: "foo"}} :ok = Stream.append_to_stream(conn, stream_uuid, :any_version, [event], schema: schema, serializer: serializer ) assert_receive {:events, [received_event | _]} assert received_event.event_type == "Elixir.EventStore.EventFactory.Event" end end test "attempt to read an unknown stream forward should error stream not found", %{ conn: conn, schema: schema, serializer: serializer } do unknown_stream_uuid = UUID.uuid4() assert {:error, :stream_not_found} = Stream.read_stream_forward(conn, unknown_stream_uuid, 0, 1, schema: schema, serializer: serializer ) end test "attempt to stream an unknown stream should error stream not found", %{ conn: conn, schema: schema, serializer: serializer } do unknown_stream_uuid = UUID.uuid4() assert {:error, :stream_not_found} = Stream.stream_forward(conn, unknown_stream_uuid, 0, read_batch_size: 1, schema: schema, serializer: serializer ) end describe "read stream forward" do setup [:append_events_to_stream] test "should fetch all events", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do {:ok, read_events} = Stream.read_stream_forward(conn, stream_uuid, 0, 1_000, schema: schema, serializer: serializer ) assert length(read_events) == 3 end end describe "stream forward" do setup [:append_events_to_stream] test "should stream events from single stream using single event batch size", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do read_events = Stream.stream_forward(conn, stream_uuid, 0, read_batch_size: 1, schema: schema, serializer: serializer ) |> Enum.to_list() assert length(read_events) == 3 assert pluck(read_events, :event_number) == [1, 2, 3] assert pluck(read_events, :stream_version) == [1, 2, 3] end test "should stream events from single stream using two event batch size", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do read_events = Stream.stream_forward(conn, stream_uuid, 0, read_batch_size: 2, schema: schema, serializer: serializer ) |> Enum.to_list() assert length(read_events) == 3 end test "should stream events from single stream uisng large batch size", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do read_events = Stream.stream_forward(conn, stream_uuid, 0, read_batch_size: 1_000, schema: schema, serializer: serializer ) |> Enum.to_list() assert length(read_events) == 3 end test "should stream events from single stream with starting version offset", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do read_events = Stream.stream_forward(conn, stream_uuid, 2, read_batch_size: 1, schema: schema, serializer: serializer ) |> Enum.to_list() assert length(read_events) == 2 assert pluck(read_events, :event_number) == [2, 3] assert pluck(read_events, :stream_version) == [2, 3] end test "should stream events from single stream with starting version offset outside range", %{conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid} do read_events = Stream.stream_forward(conn, stream_uuid, 4, read_batch_size: 1, schema: schema, serializer: serializer ) |> Enum.to_list() assert length(read_events) == 0 end end describe "subscribe to stream" do setup [:append_events_to_stream] test "from origin should receive all events", %{stream_uuid: stream_uuid} do {:ok, _subscription} = EventStore.subscribe_to_stream( stream_uuid, @subscription_name, self(), start_from: :origin, buffer_size: 3 ) assert_receive {:events, received_events} assert length(received_events) == 3 end test "from current should receive only new events", %{ conn: conn, schema: schema, serializer: serializer, stream_uuid: stream_uuid } do {:ok, _subscription} = EventStore.subscribe_to_stream( stream_uuid, @subscription_name, self(), start_from: :current ) refute_receive {:events, _received_events} events = EventFactory.create_events(1, 4) :ok = Stream.append_to_stream(conn, stream_uuid, 3, events, schema: schema, serializer: serializer ) assert_receive {:events, received_events} assert length(received_events) == 1 end test "from given stream version should receive only later events", %{stream_uuid: stream_uuid} do {:ok, _subscription} = EventStore.subscribe_to_stream(stream_uuid, @subscription_name, self(), start_from: 2) assert_receive {:events, received_events} assert length(received_events) == 1 end end test "should return stream version", %{conn: conn, schema: schema, serializer: serializer} do stream_uuid = UUID.uuid4() events = EventFactory.create_events(3) :ok = Stream.append_to_stream(conn, stream_uuid, 0, events, schema: schema, serializer: serializer) # stream above needed for preventing accidental event_number/stream_version match stream_uuid = UUID.uuid4() events = EventFactory.create_events(3) :ok = Stream.append_to_stream(conn, stream_uuid, 0, events, schema: schema, serializer: serializer) assert {:ok, 3} = Stream.stream_version(conn, stream_uuid, schema: schema) end defp append_events_to_stream(context) do %{conn: conn, schema: schema, serializer: serializer} = context stream_uuid = UUID.uuid4() events = EventFactory.create_events(3) :ok = Stream.append_to_stream(conn, stream_uuid, 0, events, schema: schema, serializer: serializer) [ stream_uuid: stream_uuid, events: events ] end defp append_event_to_another_stream(context) do %{conn: conn, schema: schema, serializer: serializer} = context stream_uuid = UUID.uuid4() events = EventFactory.create_events(1) :ok = Stream.append_to_stream(conn, stream_uuid, 0, events, schema: schema, serializer: serializer) [ other_stream_uuid: stream_uuid, other_events: events ] end defp pluck(enumerable, field), do: Enum.map(enumerable, &Map.get(&1, field)) end
29.020316
101
0.631145