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
9ed82616356821c46fe4faaa9ef42fd908b46392
3,864
exs
Elixir
chapter1/module02/reports_generator/test/reports_generator_test.exs
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
1
2021-07-23T19:48:27.000Z
2021-07-23T19:48:27.000Z
chapter1/module02/reports_generator/test/reports_generator_test.exs
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
null
null
null
chapter1/module02/reports_generator/test/reports_generator_test.exs
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
null
null
null
defmodule ReportsGeneratorTest do use ExUnit.Case describe "build/1" do test "builds the report" do file_name = "report_test.csv" response = ReportsGenerator.build(file_name) expected_response = %{ "foods" => %{ "açaí" => 1, "churrasco" => 2, "esfirra" => 3, "hambúrguer" => 2, "pastel" => 0, "pizza" => 2, "prato_feito" => 0, "sushi" => 0 }, "users" => %{ "1" => 48, "10" => 36, "11" => 0, "12" => 0, "13" => 0, "14" => 0, "15" => 0, "16" => 0, "17" => 0, "18" => 0, "19" => 0, "2" => 45, "20" => 0, "21" => 0, "22" => 0, "23" => 0, "24" => 0, "25" => 0, "26" => 0, "27" => 0, "28" => 0, "29" => 0, "3" => 31, "30" => 0, "4" => 42, "5" => 49, "6" => 18, "7" => 27, "8" => 25, "9" => 24 } } assert response == expected_response end end describe "build_from_many/1" do test "when a filesit is provided, builds the report" do filenames = ["report_test.csv", "report_test.csv"] response = ReportsGenerator.build_from_many(filenames) expected_response = {:ok, %{ "foods" => %{ "açaí" => 2, "churrasco" => 4, "esfirra" => 6, "hambúrguer" => 4, "pastel" => 0, "pizza" => 4, "prato_feito" => 0, "sushi" => 0 }, "users" => %{ "1" => 96, "10" => 72, "11" => 0, "12" => 0, "13" => 0, "14" => 0, "15" => 0, "16" => 0, "17" => 0, "18" => 0, "19" => 0, "2" => 90, "20" => 0, "21" => 0, "22" => 0, "23" => 0, "24" => 0, "25" => 0, "26" => 0, "27" => 0, "28" => 0, "29" => 0, "3" => 62, "30" => 0, "4" => 84, "5" => 98, "6" => 36, "7" => 54, "8" => 50, "9" => 48 } }} assert response == expected_response end test "when a file list is not provided, returns an error" do response = ReportsGenerator.build_from_many("it is not a list") expected_response = {:error, "Please provide a list of strings"} assert response == expected_response end end describe "fetch_higher_cost/2" do test "when the options is 'users', returns the user who spent most" do file_name = "report_test.csv" response = file_name |> ReportsGenerator.build() |> ReportsGenerator.fetch_higher_cost("users") expected_response = {:ok, {"5", 49}} assert response == expected_response end test "when the options is 'foods', returns the must consumed food" do file_name = "report_test.csv" response = file_name |> ReportsGenerator.build() |> ReportsGenerator.fetch_higher_cost("foods") expected_response = {:ok, {"esfirra", 3}} assert response == expected_response end test "when an invalid option is given" do file_name = "report_test.csv" response = file_name |> ReportsGenerator.build() |> ReportsGenerator.fetch_higher_cost("not_exists") expected_response = {:error, "Invalid options"} assert response == expected_response end end end
23.418182
74
0.408644
9ed856fcb9fe025900a460bb5785bdf728b96088
2,882
ex
Elixir
deps/ecto/lib/mix/tasks/ecto.rollback.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
deps/ecto/lib/mix/tasks/ecto.rollback.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
deps/ecto/lib/mix/tasks/ecto.rollback.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Ecto.Rollback do use Mix.Task import Mix.Ecto @shortdoc "Rolls back the repository migrations" @recursive true @moduledoc """ Reverts applied migrations in the given repository. The repository must be set under `:ecto_repos` in the current app configuration or given via the `-r` option. By default, migrations are expected at "priv/YOUR_REPO/migrations" directory of the current application but it can be configured by specifying the `:priv` key under the repository configuration. Runs the latest applied migration by default. To roll back to to a version number, supply `--to version_number`. To roll back a specific number of times, use `--step n`. To undo all applied migrations, provide `--all`. If the repository has not been started yet, one will be started outside our application supervision tree and shutdown afterwards. ## Examples mix ecto.rollback mix ecto.rollback -r Custom.Repo mix ecto.rollback -n 3 mix ecto.rollback --step 3 mix ecto.rollback -v 20080906120000 mix ecto.rollback --to 20080906120000 ## Command line options * `-r`, `--repo` - the repo to rollback * `--all` - revert all applied migrations * `--step` / `-n` - revert n number of applied migrations * `--to` / `-v` - revert all migrations down to and including version * `--quiet` - do not log migration commands * `--prefix` - the prefix to run migrations on * `--pool-size` - the pool size if the repository is started only for the task (defaults to 1) """ @doc false def run(args, migrator \\ &Ecto.Migrator.run/4) do repos = parse_repo(args) {opts, _, _} = OptionParser.parse args, switches: [all: :boolean, step: :integer, to: :integer, start: :boolean, quiet: :boolean, prefix: :string, pool_size: :integer], aliases: [n: :step, v: :to] opts = if opts[:to] || opts[:step] || opts[:all], do: opts, else: Keyword.put(opts, :step, 1) opts = if opts[:quiet], do: Keyword.put(opts, :log, false), else: opts Enum.each repos, fn repo -> ensure_repo(repo, args) ensure_migrations_path(repo) {:ok, pid, apps} = ensure_started(repo, opts) sandbox? = repo.config[:pool] == Ecto.Adapters.SQL.Sandbox # If the pool is Ecto.Adapters.SQL.Sandbox, # let's make sure we get a connection outside of a sandbox. if sandbox? do Ecto.Adapters.SQL.Sandbox.checkin(repo) Ecto.Adapters.SQL.Sandbox.checkout(repo, sandbox: false) end migrated = try do migrator.(repo, migrations_path(repo), :down, opts) after sandbox? && Ecto.Adapters.SQL.Sandbox.checkin(repo) end pid && repo.stop(pid) restart_apps_if_migrated(apps, migrated) end end end
30.336842
98
0.649896
9ed8688b161168a5a34b7d09b405a549a2953b5b
3,093
exs
Elixir
test/bamboo_phoenix_test.exs
rozanov61/bamboo_phoenix
d8eb300e04caa9f753238ac4a82538ecfec67b65
[ "MIT" ]
5
2021-03-08T19:08:22.000Z
2022-01-11T21:37:01.000Z
test/bamboo_phoenix_test.exs
rozanov61/bamboo_phoenix
d8eb300e04caa9f753238ac4a82538ecfec67b65
[ "MIT" ]
1
2021-04-14T19:11:24.000Z
2021-04-19T13:52:06.000Z
test/bamboo_phoenix_test.exs
rozanov61/bamboo_phoenix
d8eb300e04caa9f753238ac4a82538ecfec67b65
[ "MIT" ]
4
2021-02-28T10:28:21.000Z
2021-12-03T19:04:49.000Z
defmodule Bamboo.PhoenixTest do use ExUnit.Case defmodule PhoenixLayoutView do use Phoenix.View, root: "test/support/templates", namespace: Bamboo.PhoenixLayoutView end defmodule EmailView do use Phoenix.View, root: "test/support/templates", namespace: Bamboo.EmailView def function_in_view do "function used in Bamboo.TemplateTest but needed because template is compiled" end end defmodule Email do use Bamboo.Phoenix, view: EmailView def text_and_html_email_with_layout do new_email() |> put_layout({PhoenixLayoutView, :app}) |> render(:text_and_html_email) end def text_and_html_email do new_email() |> render(:text_and_html_email) end def email_with_assigns(user) do new_email() |> render(:email_with_assigns, user: user) end def email_with_already_assigned_user(user) do new_email() |> assign(:user, user) |> render(:email_with_assigns) end def html_email do new_email() |> render("html_email.html") end def text_email do new_email() |> render("text_email.text") end def no_template do new_email() |> render(:non_existent) end def invalid_template do new_email() |> render("template.foobar") end end test "render/2 allows setting a custom layout" do email = Email.text_and_html_email_with_layout() assert email.html_body =~ "HTML layout" assert email.html_body =~ "HTML body" assert email.text_body =~ "TEXT layout" assert email.text_body =~ "TEXT body" end test "render/2 renders html and text emails" do email = Email.text_and_html_email() assert email.html_body =~ "HTML body" assert email.text_body =~ "TEXT body" end test "render/2 renders html and text emails with assigns" do name = "Paul" email = Email.email_with_assigns(%{name: name}) assert email.html_body =~ "<strong>#{name}</strong>" assert email.text_body =~ name name = "Paul" email = Email.email_with_already_assigned_user(%{name: name}) assert email.html_body =~ "<strong>#{name}</strong>" assert email.text_body =~ name end test "render/2 renders html body if template extension is .html" do email = Email.html_email() assert email.html_body =~ "HTML body" assert email.text_body == nil end test "render/2 renders text body if template extension is .text" do email = Email.text_email() assert email.html_body == nil assert email.text_body =~ "TEXT body" end test "render/2 raises if template doesn't exist" do assert_raise Phoenix.Template.UndefinedError, fn -> Email.no_template() end end test "render/2 raises if you pass an invalid template extension" do assert_raise ArgumentError, ~r/must end in either ".html" or ".text"/, fn -> Email.invalid_template() end end test "render raises if called directly" do assert_raise RuntimeError, ~r/documentation only/, fn -> Bamboo.Phoenix.render(:foo, :foo, :foo) end end end
25.352459
89
0.675396
9ed87602057e80933e6e709a2f1fbc5be1aaa7b0
3,703
ex
Elixir
lib/paper_trail/version_queries.ex
dimitridewit/paper_trail
e1b710740c0b4fe4190cc5ea8e8c81b6793d37da
[ "MIT" ]
null
null
null
lib/paper_trail/version_queries.ex
dimitridewit/paper_trail
e1b710740c0b4fe4190cc5ea8e8c81b6793d37da
[ "MIT" ]
null
null
null
lib/paper_trail/version_queries.ex
dimitridewit/paper_trail
e1b710740c0b4fe4190cc5ea8e8c81b6793d37da
[ "MIT" ]
null
null
null
defmodule PaperTrail.VersionQueries do import Ecto.Query alias PaperTrail.Version @doc """ Gets all the versions of a record. A list of options is optional, so you can set for example the :prefix of the query, wich allows you to change between different tenants. # Usage examples: iex(1)> PaperTrail.VersionQueries.get_versions(record) iex(1)> PaperTrail.VersionQueries.get_versions(record, [prefix: "tenant_id"]) iex(1)> PaperTrail.VersionQueries.get_versions(ModelName, id) iex(1)> PaperTrail.VersionQueries.get_versions(ModelName, id, [prefix: "tenant_id"]) """ @spec get_versions(record :: Ecto.Schema.t()) :: [Version.t()] def get_versions(record), do: get_versions(record, []) @doc """ Gets all the versions of a record given a module and its id """ @spec get_versions(model :: module, id :: pos_integer) :: [Version.t()] def get_versions(model, id) when is_atom(model) and is_integer(id), do: get_versions(model, id, []) @spec get_versions(record :: Ecto.Schema.t(), options :: keyword | []) :: [Version.t()] def get_versions(record, options) when is_map(record) do item_type = record.__struct__ |> Module.split() |> List.last() version_query(item_type, PaperTrail.get_model_id(record), options) |> PaperTrail.RepoClient.repo().all end @spec get_versions(model :: module, id :: pos_integer, options :: keyword | []) :: [Version.t()] def get_versions(model, id, options) do item_type = model |> Module.split() |> List.last() version_query(item_type, id, options) |> PaperTrail.RepoClient.repo().all end @doc """ Gets the last version of a record. A list of options is optional, so you can set for example the :prefix of the query, wich allows you to change between different tenants. # Usage examples: iex(1)> PaperTrail.VersionQueries.get_version(record, id) iex(1)> PaperTrail.VersionQueries.get_version(record, [prefix: "tenant_id"]) iex(1)> PaperTrail.VersionQueries.get_version(ModelName, id) iex(1)> PaperTrail.VersionQueries.get_version(ModelName, id, [prefix: "tenant_id"]) """ @spec get_version(record :: Ecto.Schema.t()) :: Version.t() | nil def get_version(record), do: get_version(record, []) @spec get_version(model :: module, id :: pos_integer) :: Version.t() | nil def get_version(model, id) when is_atom(model) and is_integer(id), do: get_version(model, id, []) @spec get_version(record :: Ecto.Schema.t(), options :: keyword | []) :: Version.t() | nil def get_version(record, options) when is_map(record) do item_type = record.__struct__ |> Module.split() |> List.last() last(version_query(item_type, PaperTrail.get_model_id(record), options)) |> PaperTrail.RepoClient.repo().one end @spec get_version(model :: module, id :: pos_integer, options :: keyword | []) :: Version.t() | nil def get_version(model, id, options) do item_type = model |> Module.split() |> List.last() last(version_query(item_type, id, options)) |> PaperTrail.RepoClient.repo().one end @doc """ Gets the current model record/struct of a version """ @spec get_current_model(version :: Version.t()) :: Ecto.Schema.t() | nil def get_current_model(version) do PaperTrail.RepoClient.repo().get( ("Elixir." <> version.item_type) |> String.to_existing_atom(), version.item_id ) end defp version_query(item_type, id) do from(v in Version, where: v.item_type == ^item_type and v.item_id == ^id) end defp version_query(item_type, id, options) do with opts <- Enum.into(options, %{}) do version_query(item_type, id) |> Ecto.Queryable.to_query() |> Map.merge(opts) end end end
37.40404
101
0.688361
9ed88c0870e4e478f742e30ba20ddfcac280c96c
1,360
exs
Elixir
test/example_test.exs
sdrew/protox
c28d02f1626b5cd39bad7de2b415d20ebbdf76ee
[ "MIT" ]
null
null
null
test/example_test.exs
sdrew/protox
c28d02f1626b5cd39bad7de2b415d20ebbdf76ee
[ "MIT" ]
null
null
null
test/example_test.exs
sdrew/protox
c28d02f1626b5cd39bad7de2b415d20ebbdf76ee
[ "MIT" ]
null
null
null
defmodule ExampleTest do use ExUnit.Case # This example shows how most protobuf types are translated into Elixir code. use Protox, schema: """ syntax = "proto3"; enum FooOrBar { FOO = 0; BAR = 1; } message SubMsg { int32 a = 1; string b = 2; int64 c = 3; double d = 4; bytes e = 5; bool f = 6; FooOrBar g = 7; repeated int32 h = 8; map<string, int32> i = 9; } message Envelope { oneof envelope { string str = 1; SubMsg sub_msg = 2; } } """ test "Example" do # Here the oneof is set to a SubMsg. sub_msg = %Envelope{ envelope: {:sub_msg, %SubMsg{ a: 1, b: "foo", c: 42, d: 3.3, e: <<1, 2, 3>>, f: true, g: :FOO, h: [1, 2, 3], i: %{"foo" => 42, "bar" => 33} }} } # Here the oneof is set to a string. str = %Envelope{ envelope: {:str, "some string"} } encoded_sub_msg = sub_msg |> Envelope.encode!() |> :binary.list_to_bin() assert Envelope.decode!(encoded_sub_msg) == sub_msg encoded_str = str |> Envelope.encode!() |> :binary.list_to_bin() assert Envelope.decode!(encoded_str) == str end end
21.25
79
0.475735
9ed8a6af500b12f6157d9de5be654db1bd7265cd
405
exs
Elixir
apps/omg_watcher/priv/repo/migrations/20190408131000_add_missing_indices_to_txoutputs.exs
PinkDiamond1/elixir-omg
70dfd24a0a1ddf5d1d9d71aab61ea25300f889f7
[ "Apache-2.0" ]
1
2020-05-01T12:30:09.000Z
2020-05-01T12:30:09.000Z
apps/omg_watcher/priv/repo/migrations/20190408131000_add_missing_indices_to_txoutputs.exs
PinkDiamond1/elixir-omg
70dfd24a0a1ddf5d1d9d71aab61ea25300f889f7
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/priv/repo/migrations/20190408131000_add_missing_indices_to_txoutputs.exs
PinkDiamond1/elixir-omg
70dfd24a0a1ddf5d1d9d71aab61ea25300f889f7
[ "Apache-2.0" ]
1
2021-12-04T00:37:46.000Z
2021-12-04T00:37:46.000Z
defmodule OMG.Watcher.Repo.Migrations.AddMissingIndicesToTxOuputs do use Ecto.Migration def change do create index(:txoutputs, [:creating_txhash, :spending_txhash]) create index(:txoutputs, [:creating_deposit]) create index(:txoutputs, [:spending_txhash]) create index(:txoutputs, [:spending_exit], where: "spending_exit IS NOT NULL") create index(:txoutputs, [:owner]) end end
33.75
82
0.74321
9ed8ed1f737a53a3dcba0012e9c6a1474ff831f4
3,165
ex
Elixir
app_builder/examples/wx_demo/lib/wx_demo.ex
aleDsz/livebook
3ad817ac69b8459b684ff8d00c879ae7787b6dcc
[ "Apache-2.0" ]
null
null
null
app_builder/examples/wx_demo/lib/wx_demo.ex
aleDsz/livebook
3ad817ac69b8459b684ff8d00c879ae7787b6dcc
[ "Apache-2.0" ]
null
null
null
app_builder/examples/wx_demo/lib/wx_demo.ex
aleDsz/livebook
3ad817ac69b8459b684ff8d00c879ae7787b6dcc
[ "Apache-2.0" ]
null
null
null
defmodule WxDemo.Application do @moduledoc false use Application @impl true def start(_type, _args) do children = [ WxDemo.Window ] opts = [strategy: :one_for_one, name: WxDemo.Supervisor] Supervisor.start_link(children, opts) end end defmodule WxDemo.Window do @moduledoc false @behaviour :wx_object # https://github.com/erlang/otp/blob/OTP-24.1.2/lib/wx/include/wx.hrl#L1314 @wx_id_exit 5006 @wx_id_osx_hide 5250 def start_link(_) do {:wx_ref, _, _, pid} = :wx_object.start_link(__MODULE__, [], []) {:ok, pid} end def child_spec(init_arg) do %{ id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]}, restart: :transient } end def windows_connected(url) do url |> String.trim() |> String.trim_leading("\"") |> String.trim_trailing("\"") |> windows_to_wx() end @impl true def init(_) do app_name = "WxDemo" true = Process.register(self(), __MODULE__) os = os() wx = :wx.new() frame = :wxFrame.new(wx, -1, app_name, size: {100, 100}) if os == :macos do fixup_macos_menubar(frame, app_name) end :wxFrame.show(frame) :wxFrame.connect(frame, :command_menu_selected, skip: true) :wxFrame.connect(frame, :close_window, skip: true) case os do :macos -> :wx.subscribe_events() :windows -> windows_to_wx(System.get_env("WXDEMO_URL") || "") end state = %{frame: frame} {frame, state} end @impl true def handle_event({:wx, @wx_id_exit, _, _, _}, state) do :init.stop() {:stop, :shutdown, state} end @impl true def handle_event({:wx, _, _, _, {:wxClose, :close_window}}, state) do :init.stop() {:stop, :shutdown, state} end # ignore other menu events @impl true def handle_event({:wx, _, _, _, {:wxCommand, :command_menu_selected, _, _, _}}, state) do {:noreply, state} end @impl true def handle_info(event, state) do show_dialog(state, inspect(event)) {:noreply, state} end # Helpers defp show_dialog(state, data) do :wxMessageDialog.new(state.frame, data) |> :wxDialog.showModal() end # 1. WxeApp attaches event handler to "Quit" menu item that does nothing (to not accidentally bring # down the VM). Let's create a fresh menu bar without that caveat. # 2. Fix app name defp fixup_macos_menubar(frame, app_name) do menubar = :wxMenuBar.new() :wxFrame.setMenuBar(frame, menubar) menu = :wxMenuBar.oSXGetAppleMenu(menubar) menu |> :wxMenu.findItem(@wx_id_osx_hide) |> :wxMenuItem.setItemLabel("Hide #{app_name}\tCtrl+H") menu |> :wxMenu.findItem(@wx_id_exit) |> :wxMenuItem.setItemLabel("Quit #{app_name}\tCtrl+Q") end defp os() do case :os.type() do {:unix, :darwin} -> :macos {:win32, _} -> :windows end end defp windows_to_wx("") do send(__MODULE__, {:new_file, ''}) end defp windows_to_wx("wxdemo://" <> _ = url) do send(__MODULE__, {:open_url, String.to_charlist(url)}) end defp windows_to_wx(path) do send(__MODULE__, {:open_file, String.to_charlist(path)}) end end
22.132867
101
0.633175
9ed8eeb0cd4d466cc02876d5961d8f6b89318e91
952
ex
Elixir
test/event/support/appending_event_handler.ex
edwardzhou/commanded
f104cbf5ff3a37a6e9b637bc07ccde1d79c0725d
[ "MIT" ]
1
2018-12-28T20:48:23.000Z
2018-12-28T20:48:23.000Z
test/event/support/appending_event_handler.ex
edwardzhou/commanded
f104cbf5ff3a37a6e9b637bc07ccde1d79c0725d
[ "MIT" ]
1
2018-12-05T18:17:08.000Z
2018-12-05T18:17:08.000Z
test/event/support/appending_event_handler.ex
edwardzhou/commanded
f104cbf5ff3a37a6e9b637bc07ccde1d79c0725d
[ "MIT" ]
1
2018-12-05T18:15:03.000Z
2018-12-05T18:15:03.000Z
defmodule Commanded.Event.AppendingEventHandler do @moduledoc false use Commanded.Event.Handler, name: __MODULE__ @agent_name {:global, __MODULE__} def init do with {:ok, _pid} <- Agent.start_link(fn -> %{events: [], metadata: []} end, name: @agent_name) do :ok end end def handle(event, event_metadata) do Agent.update(@agent_name, fn %{events: events, metadata: metadata} -> %{events: events ++ [event], metadata: metadata ++ [event_metadata]} end) end def subscribed? do try do Agent.get(@agent_name, fn _ -> true end) catch :exit, _reason -> false end end def received_events do try do Agent.get(@agent_name, fn %{events: events} -> events end) catch :exit, _reason -> [] end end def received_metadata do try do Agent.get(@agent_name, fn %{metadata: metadata} -> metadata end) catch :exit, _reason -> [] end end end
22.139535
101
0.627101
9ed8f63353ca95932f82d275017146cfcccaa625
1,721
exs
Elixir
test/database_test.exs
mager/discogs-ex
f5df10d32d1a6c31f241e91a997adff555b89861
[ "BSD-3-Clause" ]
2
2018-05-13T20:42:20.000Z
2020-08-02T19:57:15.000Z
test/database_test.exs
mager/discogs-ex
f5df10d32d1a6c31f241e91a997adff555b89861
[ "BSD-3-Clause" ]
null
null
null
test/database_test.exs
mager/discogs-ex
f5df10d32d1a6c31f241e91a997adff555b89861
[ "BSD-3-Clause" ]
null
null
null
defmodule DiscogsEx.DatabaseTest do use ExUnit.Case, async: false use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney import DiscogsEx.Database doctest DiscogsEx.Database @client DiscogsEx.Client.new %{key: "key", secret: "secret"} setup_all do HTTPoison.start end describe "search/1" do test "success" do use_cassette "database#search" do response = search "Demi Lovato", %{"title": "sorry not sorry"}, @client assert Map.get(response, "pagination") == %{ "items" => 3, "page" => 1, "pages" => 1, "per_page" => 50, "urls" => %{} } assert is_list(Map.get(response, "results")) first = Map.get(response, "results") |> Enum.at(0) assert first == %{ "barcode" => ["1256232718"], "catno" => "none", "community" => %{ "have" => 2, "want" => 0, }, "country" => "Unknown", "format" => [ "File", "AAC", "Single" ], "genre" => ["Pop"], "id" => 10559613, "label" => [ "Hollywood Records", "Island Records", "Safehouse Records", "Hollywood Records, Inc." ], "resource_url" => "https://api.discogs.com/releases/10559613", "style" => ["Vocal"], "thumb" => "https://api-img.discogs.com/F2I6nvCRGxZUoJuws-ouhonFfIA=/fit-in/150x150/filters:strip_icc():format(jpeg):mode_rgb():quality(40)/discogs-images/R-10559613-1499887916-1414.jpeg.jpg", "title" => "Demi Lovato - Sorry Not Sorry", "type" => "release", "uri" => "/Demi-Lovato-Sorry-Not-Sorry/release/10559613", "year" => "2017" } end end end end
31.87037
202
0.538059
9ed9037be7b8840eb65af6eb8c362560738b4ca9
3,153
exs
Elixir
test/xlsxir_test.exs
getong/xlsxir
c91851cf5248ae91e08bcb5ae06d9d5309f8f98f
[ "MIT" ]
null
null
null
test/xlsxir_test.exs
getong/xlsxir
c91851cf5248ae91e08bcb5ae06d9d5309f8f98f
[ "MIT" ]
null
null
null
test/xlsxir_test.exs
getong/xlsxir
c91851cf5248ae91e08bcb5ae06d9d5309f8f98f
[ "MIT" ]
1
2019-01-03T01:41:37.000Z
2019-01-03T01:41:37.000Z
defmodule XlsxirTest do use ExUnit.Case import Xlsxir def path(), do: "./test/test_data/test.xlsx" def rb_path(), do: "./test/test_data/red_black.xlsx" test "second worksheet is parsed with index argument of 1" do {:ok, pid} = extract(path(), 1) assert get_list(pid) == [[1, 2], [3, 4]] close(pid) end test "able to parse maximum number of columns" do {:ok, pid} = extract(path(), 2) assert get_cell(pid, "XFD1") == 16384 close(pid) end test "able to parse maximum number of rows" do {:ok, pid} = extract(path(), 3) assert get_cell(pid, "A1048576") == 1_048_576 close(pid) end test "able to parse cells with errors" do {:ok, pid} = extract(path(), 4) assert get_list(pid) == [["#DIV/0!", "#REF!", "#NUM!", "#VALUE!"]] close(pid) end test "able to parse custom formats" do {:ok, pid} = extract(path(), 5) assert get_list(pid) == [ [-123.45, 67.89, {2015, 1, 1}, {2016, 12, 31}, {15, 12, 45}, ~N[2012-12-18 14:26:00]] ] close(pid) end test "able to parse with conditional formatting" do {:ok, pid} = extract(path(), 6) assert get_list(pid) == [["Conditional"]] close(pid) end test "able to parse with boolean values" do {:ok, pid} = extract(path(), 7) assert get_list(pid) == [[true, false]] close(pid) end test "peek file contents" do {:ok, pid} = peek(path(), 8, 10) assert get_cell(pid, "G10") == 8437 assert get_info(pid, :rows) == 10 close(pid) end test "get_cell returns nil for non-existent cells" do {:ok, pid} = extract(path(), 0) assert get_cell(pid, "A2") == nil assert get_cell(pid, "F1") == nil close(pid) end test "get_cell returns correct content even with rich text" do {:ok, pid} = extract(rb_path(), 0) assert get_cell(pid, "A1") == "RED: BLACK" assert get_cell(pid, "A2") == "Data" close(pid) end test "multi_extract/4" do res = multi_extract(path()) {:ok, tid} = hd(res) assert 11 == Enum.count(res) assert [["string one", "string two", 10, 20, {2016, 1, 1}]] == get_list(tid) end def error_cell_path(), do: "./test/test_data/error-date.xlsx" test "error cells can be parsed properly1" do {:ok, pid} = extract(error_cell_path(), 0) close(pid) end test "empty cells are filled with nil" do {:ok, pid} = multi_extract(path(), 9) assert get_list(pid) == [ [1, nil, 1, nil, 1, nil, nil, 1], [nil, 1, nil, nil, 1, nil, 1], [nil, nil, nil, nil, nil, 1, nil, nil, nil, 1], [1, 1, nil, 1] ] end test "empty reference cells are filled with nil" do {:ok, pid} = multi_extract(path(), 10) assert get_list(pid) == [ [1, nil, 1, nil, 1, nil, nil, 1, nil, nil], [nil, 1, nil, nil, 1, nil, 1, nil, nil, nil], [nil, nil, nil, nil, nil, 1, nil, nil, nil, 1], [1, 1, nil, 1, nil, nil, nil, nil, nil, nil] ] end test "handles non-existent xlsx file gracefully" do {:error, _err} = multi_extract("this/file/does/not/exist.xlsx") end end
27.181034
98
0.569299
9ed90b47aa82421a9b36c81f380ee50d7d5b926a
585
exs
Elixir
train_shunting/mix.exs
lucas-larsson/ID1019
b21a79bfa7fbbaaba0b4db88ec8b44fc5e9f291c
[ "MIT" ]
null
null
null
train_shunting/mix.exs
lucas-larsson/ID1019
b21a79bfa7fbbaaba0b4db88ec8b44fc5e9f291c
[ "MIT" ]
null
null
null
train_shunting/mix.exs
lucas-larsson/ID1019
b21a79bfa7fbbaaba0b4db88ec8b44fc5e9f291c
[ "MIT" ]
null
null
null
defmodule TrainShunting.MixProject do use Mix.Project def project do [ app: :train_shunting, version: "0.1.0", elixir: "~> 1.11", start_permanent: Mix.env() == :prod, deps: deps() ] 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 [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end end
20.172414
87
0.586325
9ed94356cc7304c33d7146168f17ff9faee7c47c
3,369
exs
Elixir
apps/aecore/test/aecore_persistence_test.exs
SingularityMatrix/elixir-node
ad126aa97931165185cf35454718ed2eee40ceed
[ "ISC" ]
null
null
null
apps/aecore/test/aecore_persistence_test.exs
SingularityMatrix/elixir-node
ad126aa97931165185cf35454718ed2eee40ceed
[ "ISC" ]
2
2018-10-01T16:46:26.000Z
2018-10-01T19:45:42.000Z
apps/aecore/test/aecore_persistence_test.exs
gspasov/dogs-blockchain
884c14cfc98de2c3793a204da069630d090bbc90
[ "0BSD" ]
null
null
null
defmodule PersistenceTest do use ExUnit.Case doctest Aecore.Persistence.Worker alias Aecore.Persistence.Worker, as: Persistence alias Aecore.Keys alias Aecore.Miner.Worker, as: Miner alias Aecore.Chain.Worker, as: Chain alias Aecore.Chain.Header alias Aecore.Account.{Account, AccountStateTree} setup do Code.require_file("test_utils.ex", "./test") TestUtils.clean_blockchain() :ok = Miner.mine_sync_block_to_chain() :ok = Miner.mine_sync_block_to_chain() :ok = Miner.mine_sync_block_to_chain() on_exit(fn -> TestUtils.clean_blockchain() end) end setup do account1 = elem(Keys.keypair(:sign), 0) account2 = <<198, 218, 48, 178, 127, 24, 201, 115, 3, 29, 188, 220, 222, 189, 132, 139, 168, 1, 64, 134, 103, 38, 151, 213, 195, 5, 219, 138, 29, 137, 119, 229>> [account1: account1, account2: account2] end @tag timeout: 30_000 @tag :persistence test "Get last mined block by his hash from the rocksdb" do hash = Header.hash(Chain.top_block().header) assert {:ok, %{header: _header}} = Persistence.get_block_by_hash(hash) end @tag timeout: 30_000 @tag :persistence test "Get all blocks from the rocksdb" do assert Aecore.Chain.Worker.top_block() == Persistence.get_all_blocks()[Aecore.Chain.Worker.top_block_hash()] end @tag timeout: 30_000 @tag :persistence test "Get chain state from the rocksdb", persistance_state do correct_balance = Chain.chain_state().accounts |> Account.balance(persistance_state.account1) # For specific account assert match?(%{balance: ^correct_balance}, get_account_state(persistance_state.account1)) # Non existant accounts are empty assert :not_found = get_account_state(persistance_state.account2) # For all accounts {:ok, all_accounts} = Persistence.get_all_chainstates(Chain.top_block_hash()) assert false == Enum.empty?(Map.keys(all_accounts)) end @tag timeout: 20_000 @tag :persistence test "Get latest two blocks from rocksdb" do top_height = Chain.top_height() assert length(Map.values(Persistence.get_all_blocks())) == 4 assert length(Map.values(Persistence.get_blocks(2))) == 2 [block1, block2] = Enum.sort(Map.values(Persistence.get_blocks(2)), fn b1, b2 -> b1.header.height < b2.header.height end) assert block1.header.height == top_height - 1 assert block2.header.height == top_height end @tag timeout: 20_000 @tag :persistence test "Failure cases", persistance_state do assert {:error, "#{Persistence}: Bad block structure: :wrong_input_type"} == Persistence.add_block_by_hash(:wrong_input_type) assert {:error, "#{Persistence}: Bad hash value: :wrong_input_type"} == Persistence.get_block_by_hash(:wrong_input_type) assert :not_found = get_account_state(persistance_state.account2) assert "Blocks number must be greater than one" == Persistence.get_blocks(0) end defp get_account_state(account) do root_hashes_map = Persistence.get_all_chainstates(Chain.top_block_hash()) chainstate = Chain.transform_chainstate(:to_chainstate, root_hashes_map) empty_account = Account.empty() case AccountStateTree.get(chainstate.accounts, account) do ^empty_account -> :not_found value -> value end end end
31.194444
94
0.703473
9ed9c46457fc0b543988ff2c1514c508c741dee0
129
exs
Elixir
test/unit/validators/time_test.exs
tomciopp/ecto_commons
75ca493739a54b2f73b753c3d2623dc61781d91d
[ "MIT" ]
null
null
null
test/unit/validators/time_test.exs
tomciopp/ecto_commons
75ca493739a54b2f73b753c3d2623dc61781d91d
[ "MIT" ]
null
null
null
test/unit/validators/time_test.exs
tomciopp/ecto_commons
75ca493739a54b2f73b753c3d2623dc61781d91d
[ "MIT" ]
null
null
null
defmodule EctoCommons.TimeValidatorTest do use ExUnit.Case, async: true doctest EctoCommons.TimeValidator, import: true end
21.5
49
0.813953
9ed9d2071ccaa0f6f94c45ba97f7b8993d7b6a5f
1,629
ex
Elixir
lib/bank_stone/accounts/user.ex
theguuholi/bank_stone
150a7c7ac9eb2d9bb977d1d784518b39df5c5ab5
[ "MIT" ]
3
2020-04-25T11:35:06.000Z
2021-10-06T19:59:47.000Z
lib/bank_stone/accounts/user.ex
theguuholi/bank_stone
150a7c7ac9eb2d9bb977d1d784518b39df5c5ab5
[ "MIT" ]
12
2019-11-04T11:06:37.000Z
2019-11-21T11:03:57.000Z
lib/bank_stone/accounts/user.ex
theguuholi/bank_stone
150a7c7ac9eb2d9bb977d1d784518b39df5c5ab5
[ "MIT" ]
1
2020-12-11T07:05:04.000Z
2020-12-11T07:05:04.000Z
defmodule BankStone.Accounts.User do @moduledoc """ The Main reaso of this module is to manipulate Account User """ use Ecto.Schema import Ecto.Changeset @primary_key {:id, :binary_id, autogenerate: true} @derive {Phoenix.Param, key: :id} schema "users" do field :email, :string, unique: true field :first_name, :string field :last_name, :string field :password, :string, virtual: true field :password_confirmation, :string, virtual: true field :password_hash, :string field :role, :string, default: "user" has_one :accounts, BankStone.Accounts.Account timestamps() end @doc false def changeset(user, attrs) do user |> cast(attrs, [ :email, :first_name, :last_name, :password, :password_confirmation, :role ]) |> validate_required([ :email, :first_name, :last_name, :password, :password_confirmation, :role ]) |> validate_format(:email, ~r/@/, message: "Invalid email format!") |> update_change(:email, &String.downcase(&1)) |> validate_length(:password, min: 6, max: 100, message: "Password should have between 6 until 100 chars" ) |> validate_confirmation(:password, message: "Password does not match") |> unique_constraint(:email, message: "There is an user with this email") |> hash_password() end defp hash_password(%Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset) do change(changeset, Comeonin.Argon2.add_hash(password)) end defp hash_password(changeset) do changeset end end
26.274194
98
0.651934
9ed9d41c89f35ef08db2032b6af1c82fd7076f69
3,839
exs
Elixir
test/openid_connect/worker_test.exs
CrankWheel/openid_connect
0d63a3c27d85cae2de93d67d3bc77adcf5d6110a
[ "MIT" ]
null
null
null
test/openid_connect/worker_test.exs
CrankWheel/openid_connect
0d63a3c27d85cae2de93d67d3bc77adcf5d6110a
[ "MIT" ]
null
null
null
test/openid_connect/worker_test.exs
CrankWheel/openid_connect
0d63a3c27d85cae2de93d67d3bc77adcf5d6110a
[ "MIT" ]
null
null
null
defmodule OpenIDConnect.WorkerTest do use ExUnit.Case import Mox setup :set_mox_global setup :verify_on_exit! @google_document Fixtures.load(:google, :discovery_document) @google_certs Fixtures.load(:google, :certs) alias OpenIDConnect.{HTTPClientMock} test "starting with :ignore does nothing" do :ignore = OpenIDConnect.Worker.start_link(:ignore) end test "starting with a single provider will retrieve the necessary documents" do mock_http_requests() config = Application.get_env(:openid_connect, :providers) {:ok, pid} = start_supervised({OpenIDConnect.Worker, config}) state = :sys.get_state(pid) expected_document = @google_document |> elem(1) |> Map.get(:body) |> Jason.decode!() |> OpenIDConnect.normalize_discovery_document() expected_jwk = @google_certs |> elem(1) |> Map.get(:body) |> Jason.decode!() |> JOSE.JWK.from() assert expected_document == get_in(state, [:google, :documents, :discovery_document]) assert expected_jwk == get_in(state, [:google, :documents, :jwk]) end test "worker can respond to a call for the config" do mock_http_requests() config = Application.get_env(:openid_connect, :providers) {:ok, pid} = start_supervised({OpenIDConnect.Worker, config}) google_config = GenServer.call(pid, {:config, :google}) assert get_in(config, [:google]) == google_config end test "worker started using callback function can respond to a call for the config" do mock_http_requests() config = Application.get_env(:openid_connect, :providers) {:ok, pid} = start_supervised({OpenIDConnect.Worker, {:callback, fn -> config end}}) google_config = GenServer.call(pid, {:config, :google}) assert get_in(config, [:google]) == google_config end test "worker can respond to a call for a provider's discovery document" do mock_http_requests() config = Application.get_env(:openid_connect, :providers) {:ok, pid} = start_supervised({OpenIDConnect.Worker, config}) discovery_document = GenServer.call(pid, {:discovery_document, :google}) expected_document = @google_document |> elem(1) |> Map.get(:body) |> Jason.decode!() |> OpenIDConnect.normalize_discovery_document() assert expected_document == discovery_document end test "worker can respond to a call for a provider's jwk" do mock_http_requests() config = Application.get_env(:openid_connect, :providers) {:ok, pid} = start_supervised({OpenIDConnect.Worker, config}) jwk = GenServer.call(pid, {:jwk, :google}) expected_jwk = @google_certs |> elem(1) |> Map.get(:body) |> Jason.decode!() |> JOSE.JWK.from() assert expected_jwk == jwk end test "worker can start without internet connectivity, initialization is deferred" do mock_http_internet_down() config = Application.get_env(:openid_connect, :providers) {:error, :update_documents, _} = OpenIDConnect.update_documents(config) config = Application.get_env(:openid_connect, :providers) {:ok, pid} = start_supervised({OpenIDConnect.Worker, config}) catch_exit(GenServer.call(pid, {:jwk, :google})) end defp mock_http_requests do HTTPClientMock |> expect(:get, fn "https://accounts.google.com/.well-known/openid-configuration", _headers, _opts -> @google_document end) |> expect(:get, fn "https://www.googleapis.com/oauth2/v3/certs", _headers, _opts -> @google_certs end) end defp mock_http_internet_down do HTTPClientMock |> expect(:get, fn _, _, _ -> {:error, %HTTPoison.Error{id: nil, reason: :nxdomain}} end) |> expect(:get, fn _, _, _ -> {:error, %HTTPoison.Error{id: nil, reason: :nxdomain}} end) end end
27.818841
106
0.678823
9ed9df4f814df727b49714dcb62cde1667f998ce
2,906
exs
Elixir
test/gossip/socket/players_test.exs
oestrich/gossip-elixir
ad2195968c19f905f713790250a0b462503fc4b4
[ "MIT" ]
19
2018-07-13T04:34:00.000Z
2021-09-18T17:11:00.000Z
test/gossip/socket/players_test.exs
oestrich/gossip-elixir
ad2195968c19f905f713790250a0b462503fc4b4
[ "MIT" ]
5
2018-07-13T02:47:31.000Z
2018-10-11T00:05:54.000Z
test/gossip/socket/players_test.exs
oestrich/gossip-elixir
ad2195968c19f905f713790250a0b462503fc4b4
[ "MIT" ]
2
2018-07-13T03:55:26.000Z
2021-02-12T20:12:47.000Z
defmodule Gossip.Socket.PlayersTest do use ExUnit.Case alias Gossip.Socket.Players alias Test.Callbacks.PlayerCallbacks setup [:with_state] describe "player sign in" do test "generates the event", %{state: state} do {:reply, message, _state} = Players.sign_in(state, "Player") assert message["event"] == "players/sign-in" assert message["payload"]["name"] == "Player" end end describe "player sign out" do test "generates the event", %{state: state} do {:reply, message, _state} = Players.sign_out(state, "Player") assert message["event"] == "players/sign-out" assert message["payload"]["name"] == "Player" end end describe "player status" do test "generates the event", %{state: state} do {:reply, message, _state} = Players.status(state) assert message["event"] == "players/status" assert message["ref"] end end describe "process an incoming players/sign-in event" do test "sends to the players callback", %{state: state} do payload = %{"game" => "ExVenture", "name" => "Player"} {:ok, _state} = Players.process_sign_in(state, %{"payload" => payload}) assert [{"ExVenture", "Player"}] = PlayerCallbacks.sign_ins() end test "handle receive", %{state: state} do payload = %{"game" => "ExVenture", "name" => "Player"} {:ok, _state} = Players.handle_receive(state, %{"event" => "players/sign-in", "payload" => payload}) end end describe "process an incoming players/sign-out event" do test "sends to the players callback", %{state: state} do payload = %{"game" => "ExVenture", "name" => "Player"} {:ok, _state} = Players.process_sign_out(state, %{"payload" => payload}) assert [{"ExVenture", "Player"}] = PlayerCallbacks.sign_outs() end test "handle receive", %{state: state} do payload = %{"game" => "ExVenture", "name" => "Player"} {:ok, _state} = Players.handle_receive(state, %{"event" => "players/sign-out", "payload" => payload}) end end describe "process an incoming players/status event" do test "sends to the players callback", %{state: state} do payload = %{"game" => "ExVenture", "players" => ["Player"]} {:ok, _state} = Players.process_status(state, %{"payload" => payload}) assert [{"ExVenture", ["Player"]}] = PlayerCallbacks.player_updates() end test "missing a payload - when requesting a single game and that failed", %{state: state} do {:ok, _state} = Players.process_status(state, %{}) end test "handle receive", %{state: state} do payload = %{"game" => "ExVenture", "players" => ["Player"]} {:ok, _state} = Players.handle_receive(state, %{"event" => "players/status", "payload" => payload}) end end def with_state(_) do %{state: %{modules: %{players: Test.Callbacks.PlayerCallbacks}}} end end
31.586957
107
0.62457
9ed9fbe97485995620ed4734f671d319f6bd2639
6,914
ex
Elixir
lib/webbkoll_web/plugs/locale.ex
bfg1981/webbkoll
ec7c6167e46fe1e27f01f5d98f3daa068af40f63
[ "MIT" ]
268
2016-07-08T17:14:58.000Z
2022-02-15T19:41:24.000Z
lib/webbkoll_web/plugs/locale.ex
bfg1981/webbkoll
ec7c6167e46fe1e27f01f5d98f3daa068af40f63
[ "MIT" ]
29
2016-08-23T19:19:01.000Z
2022-02-01T16:28:23.000Z
lib/webbkoll_web/plugs/locale.ex
bfg1981/webbkoll
ec7c6167e46fe1e27f01f5d98f3daa068af40f63
[ "MIT" ]
37
2016-08-24T21:52:45.000Z
2021-09-08T11:27:15.000Z
defmodule WebbkollWeb.Plugs.Locale do # Some code/inspiration from # http://code.parent.co/practical-i18n-with-phoenix-and-elixir/ import Plug.Conn @locales Map.keys(Application.get_env(:webbkoll, :locales)) def init(default), do: default def call(%Plug.Conn{params: %{"locale" => loc}} = conn, _default) when loc in @locales do Gettext.put_locale(WebbkollWeb.Gettext, loc) assign(conn, :locale, loc) end def call(conn, default) do locale_to_use = conn |> extract_accept_language() |> Enum.find(nil, fn accepted_locale -> Enum.member?(@locales, accepted_locale) end) |> case do nil -> default lang -> lang end path = if conn.params["locale"] != nil and String.downcase(conn.params["locale"]) in ietf_codes() do ~r/(\/)#{conn.params["locale"]}(\/(?:.+)?|\?(?:.+)?|$)/ |> Regex.replace(conn.request_path, "\\1#{locale_to_use}\\2") else "/#{locale_to_use}#{conn.request_path}" end path = if conn.query_string == "" do path else path <> "?#{conn.query_string}" end # If user hits / and preferred browser language isn't supported, don't # redirect to /en/ - just show the English page on /. If we redirect to # /en/ by default then that's what many links/bookmarks will point to, # making it harder for users to discover when we DO have a relevant # translation, as we also don't want to force another language on a user # who's fetching an URL with a language explicitly set (such as /en/). if conn.request_path == "/" and path == "/en/" do Gettext.put_locale(WebbkollWeb.Gettext, "en") assign(conn, :locale, "en") else Phoenix.Controller.redirect(conn, to: path) |> halt end end # extract_accept_language(), parse_language_option() and ensure_language_fallbacks() # are from https://github.com/smeevil/set_locale by smeevil, WTFPL v2 def extract_accept_language(conn) do case Plug.Conn.get_req_header(conn, "accept-language") do [value | _] -> value |> String.split(",") |> Enum.map(&parse_language_option/1) |> Enum.sort(&(&1.quality > &2.quality)) |> Enum.map(& &1.tag) |> Enum.reject(&is_nil/1) |> ensure_language_fallbacks() _ -> [] end end defp parse_language_option(string) do captures = Regex.named_captures(~r/^\s?(?<tag>[\w\-]+)(?:;q=(?<quality>[\d\.]+))?$/i, string) quality = case Float.parse(captures["quality"] || "1.0") do {val, _} -> val _ -> 1.0 end %{tag: captures["tag"], quality: quality} end defp ensure_language_fallbacks(tags) do Enum.flat_map(tags, fn tag -> [language | _] = String.split(tag, "-") if Enum.member?(tags, language), do: [tag], else: [tag, language] end) end defp ietf_codes do ~w(af af-na af-za agq agq-cm ak ak-gh am am-et ar ar-001 ar-ae ar-bh ar-dj ar-dz ar-eg ar-eh ar-er ar-il ar-iq ar-jo ar-km ar-kw ar-lb ar-ly ar-ma ar-mr ar-om ar-ps ar-qa ar-sa ar-sd ar-so ar-ss ar-sy ar-td ar-tn ar-ye as as-in asa asa-tz ast ast-es az az-cyrl az-cyrl-az az-latn az-latn-az bas bas-cm be be-by bem bem-zm bez bez-tz bg bg-bg bm bm-latn bm-latn-ml bn bn-bd bn-in bo bo-cn bo-in br br-fr brx brx-in bs bs-cyrl bs-cyrl-ba bs-latn bs-latn-ba ca ca-ad ca-es ca-es-valencia ca-fr ca-it cgg cgg-ug chr chr-us cs cs-cz cy cy-gb da da-dk da-gl dav dav-ke de de-at de-be de-ch de-de de-li de-lu dje dje-ne dsb dsb-de dua dua-cm dyo dyo-sn dz dz-bt ebu ebu-ke ee ee-gh ee-tg el el-cy el-gr en en-001 en-150 en-ag en-ai en-as en-au en-bb en-be en-bm en-bs en-bw en-bz en-ca en-cc en-ck en-cm en-cx en-dg en-dm en-er en-fj en-fk en-fm en-gb en-gd en-gg en-gh en-gi en-gm en-gu en-gy en-hk en-ie en-im en-in en-io en-je en-jm en-ke en-ki en-kn en-ky en-lc en-lr en-ls en-mg en-mh en-mo en-mp en-ms en-mt en-mu en-mw en-my en-na en-nf en-ng en-nr en-nu en-nz en-pg en-ph en-pk en-pn en-pr en-pw en-rw en-sb en-sc en-sd en-sg en-sh en-sl en-ss en-sx en-sz en-tc en-tk en-to en-tt en-tv en-tz en-ug en-um en-us en-us-posix en-vc en-vg en-vi en-vu en-ws en-za en-zm en-zw eo eo-001 es es-419 es-ar es-bo es-cl es-co es-cr es-cu es-do es-ea es-ec es-es es-gq es-gt es-hn es-ic es-mx es-ni es-pa es-pe es-ph es-pr es-py es-sv es-us es-uy es-ve et et-ee eu eu-es ewo ewo-cm fa fa-af fa-ir ff ff-cm ff-gn ff-mr ff-sn fi fi-fi fil fil-ph fo fo-fo fr fr-be fr-bf fr-bi fr-bj fr-bl fr-ca fr-cd fr-cf fr-cg fr-ch fr-ci fr-cm fr-dj fr-dz fr-fr fr-ga fr-gf fr-gn fr-gp fr-gq fr-ht fr-km fr-lu fr-ma fr-mc fr-mf fr-mg fr-ml fr-mq fr-mr fr-mu fr-nc fr-ne fr-pf fr-pm fr-re fr-rw fr-sc fr-sn fr-sy fr-td fr-tg fr-tn fr-vu fr-wf fr-yt fur fur-it fy fy-nl ga ga-ie gd gd-gb gl gl-es gsw gsw-ch gsw-fr gsw-li gu gu-in guz guz-ke gv gv-im ha ha-latn ha-latn-gh ha-latn-ne ha-latn-ng haw haw-us he he-il hi hi-in hr hr-ba hr-hr hsb hsb-de hu hu-hu hy hy-am id id-id ig ig-ng ii ii-cn is is-is it it-ch it-it it-sm ja ja-jp jgo jgo-cm jmc jmc-tz ka ka-ge kab kab-dz kam kam-ke kde kde-tz kea kea-cv khq khq-ml ki ki-ke kk kk-cyrl kk-cyrl-kz kkj kkj-cm kl kl-gl kln kln-ke km km-kh kn kn-in ko ko-kp ko-kr kok kok-in ks ks-arab ks-arab-in ksb ksb-tz ksf ksf-cm ksh ksh-de kw kw-gb ky ky-cyrl ky-cyrl-kg lag lag-tz lb lb-lu lg lg-ug lkt lkt-us ln ln-ao ln-cd ln-cf ln-cg lo lo-la lt lt-lt lu lu-cd luo luo-ke luy luy-ke lv lv-lv mas mas-ke mas-tz mer mer-ke mfe mfe-mu mg mg-mg mgh mgh-mz mgo mgo-cm mk mk-mk ml ml-in mn mn-cyrl mn-cyrl-mn mr mr-in ms ms-latn ms-latn-bn ms-latn-my ms-latn-sg mt mt-mt mua mua-cm my my-mm naq naq-na nb nb-no nb-sj nd nd-zw ne ne-in ne-np nl nl-aw nl-be nl-bq nl-cw nl-nl nl-sr nl-sx nmg nmg-cm nn nn-no nnh nnh-cm nus nus-sd nyn nyn-ug om om-et om-ke or or-in os os-ge os-ru pa pa-arab pa-arab-pk pa-guru pa-guru-in pl pl-pl ps ps-af pt pt-ao pt-br pt-cv pt-gw pt-mo pt-mz pt-pt pt-st pt-tl qu qu-bo qu-ec qu-pe rm rm-ch rn rn-bi ro ro-md ro-ro rof rof-tz root ru ru-by ru-kg ru-kz ru-md ru-ru ru-ua rw rw-rw rwk rwk-tz sah sah-ru saq saq-ke sbp sbp-tz se se-fi se-no se-se seh seh-mz ses ses-ml sg sg-cf shi shi-latn shi-latn-ma shi-tfng shi-tfng-ma si si-lk sk sk-sk sl sl-si smn smn-fi sn sn-zw so so-dj so-et so-ke so-so sq sq-al sq-mk sq-xk sr sr-cyrl sr-cyrl-ba sr-cyrl-me sr-cyrl-rs sr-cyrl-xk sr-latn sr-latn-ba sr-latn-me sr-latn-rs sr-latn-xk sv sv-ax sv-fi sv-se sw sw-cd sw-ke sw-tz sw-ug ta ta-in ta-lk ta-my ta-sg te te-in teo teo-ke teo-ug th th-th ti ti-er ti-et to to-to tr tr-cy tr-tr twq twq-ne tzm tzm-latn tzm-latn-ma ug ug-arab ug-arab-cn uk uk-ua ur ur-in ur-pk uz uz-arab uz-arab-af uz-cyrl uz-cyrl-uz uz-latn uz-latn-uz vai vai-latn vai-latn-lr vai-vaii vai-vaii-lr vi vi-vn vun vun-tz wae wae-ch xog xog-ug yav yav-cm yi yi-001 yo yo-bj yo-ng zgh zgh-ma zh zh-hans zh-hans-cn zh-hans-hk zh-hans-mo zh-hans-sg zh-hant zh-hant-hk zh-hant-mo zh-hant-tw zu zu-za) end end
73.553191
4,001
0.65823
9eda0479a7b7ff1cc5d2488ccd8d367084da0bbd
13,073
ex
Elixir
apps/cms/lib/api/static.ex
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
42
2019-05-29T16:05:30.000Z
2021-08-09T16:03:37.000Z
apps/cms/lib/api/static.ex
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
872
2019-05-29T17:55:50.000Z
2022-03-30T09:28:43.000Z
apps/cms/lib/api/static.ex
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
12
2019-07-01T18:33:21.000Z
2022-03-10T02:13:57.000Z
defmodule CMS.API.Static do @moduledoc """ Emulates Drupal REST API (both native and Views-based) """ @behaviour CMS.API alias CMS.Helpers alias CMS.Page.NewsEntry alias Poison.Parser # Views REST export responses with fully-loaded objects def events_response do parse_json("cms/events.json") end def banners_response do parse_json("cms/banners.json") end def search_response do parse_json("cms/search.json") end def search_response_empty do parse_json("cms/search-empty.json") end def whats_happening_response do parse_json("cms/whats-happening.json") end def route_pdfs_response do parse_json("cms/route-pdfs.json") end # Teaser responses from CMS API (minimal data) def teaser_response do parse_json("cms/teasers.json") end def teaser_basic_page_response do parse_json("cms/teasers_page.json") end def teaser_news_entry_response do parse_json("cms/teasers_news_entry.json") end def teaser_event_response do parse_json("cms/teasers_event.json") end def teaser_project_response do parse_json("cms/teasers_project.json") end def teaser_featured_projects_response do parse_json("cms/teasers_project_featured.json") end def teaser_project_update_response do parse_json("cms/teasers_project_update.json") end def teaser_diversion_response do parse_json("cms/teasers_diversion.json") end def teaser_empty_response do [] end # Repositories of multiple, full-object responses (maximum data) def news_repo do parse_json("repo/news.json") end def project_repo do parse_json("repo/projects.json") end def project_update_repo do parse_json("repo/project-updates.json") end # Core (entity:node) responses def all_paragraphs_response do parse_json("landing_page_with_all_paragraphs.json") end def event_agenda_response do parse_json("event_agenda.json") end def basic_page_response do parse_json("basic_page_no_sidebar.json") end def basic_page_with_sidebar_response do parse_json("basic_page_with_sidebar.json") end def basic_page_no_alias_response do parse_json("basic_page_with_sidebar_no_alias.json") end def diversion_response do parse_json("diversion.json") end def landing_page_response do parse_json("landing_page.json") end def person_response do parse_json("person.json") end def redirect_response do parse_json("redirect.json") end def redirect_with_query_response do parse_json("redirect_with_query%3Fid%3D5.json") end # Partials (paragraph library) response def paragraph_response do parse_json("_paragraph.json") end @impl true def view(path, params) def view("/cms/recent-news", current_id: id) do filtered_recent_news = Enum.reject(news_repo(), &match?(%{"nid" => [%{"value" => ^id}]}, &1)) recent_news = Enum.take(filtered_recent_news, NewsEntry.number_of_recent_news_suggestions()) {:ok, recent_news} end def view("/cms/recent-news", _) do {:ok, Enum.take(news_repo(), NewsEntry.number_of_recent_news_suggestions())} end def view("/basic_page_no_sidebar", _) do {:ok, basic_page_response()} end def view("/event_agenda", _) do {:ok, event_agenda_response()} end def view("/cms/news", id: id) do news_entry = filter_by(news_repo(), "nid", id) {:ok, news_entry} end def view("/cms/news", migration_id: "multiple-records") do {:ok, news_repo()} end def view("/cms/news", migration_id: id) do news = filter_by(news_repo(), "field_migration_id", id) {:ok, news} end def view("/cms/news", page: _page) do record = List.first(news_repo()) {:ok, [record]} end def view("/news/incorrect-pattern", _) do {:ok, Enum.at(news_repo(), 1)} end def view("/news/date/title", _) do {:ok, Enum.at(news_repo(), 1)} end def view("/news/2018/news-entry", _) do {:ok, List.first(news_repo())} end def view("/news/redirected-url", params) do redirect("/news/date/title", params, 301) end def view("/cms/events", meeting_id: "multiple-records") do {:ok, events_response()} end def view("/cms/events", meeting_id: id) do events = filter_by(events_response(), "field_meeting_id", id) {:ok, events} end def view("/cms/events", id: id) do {:ok, filter_by(events_response(), "nid", id)} end def view("/events/incorrect-pattern", _) do {:ok, Enum.at(events_response(), 1)} end def view("/events/date/title", _) do {:ok, Enum.at(events_response(), 1)} end def view("/events/redirected-url", params) do redirect("/events/date/title", params, 301) end def view("/cms/events", _opts) do {:ok, events_response()} end def view("/cms/search", q: "empty", page: 0) do {:ok, search_response_empty()} end def view("/cms/search", _opts) do {:ok, search_response()} end def view("/projects/project-name", _) do {:ok, Enum.at(project_repo(), 1)} end def view("/projects/project-with-paragraphs", _) do {:ok, Enum.at(project_repo(), 0)} end def view("/porjects/project-name", _) do {:ok, Enum.at(project_repo(), 1)} end def view("/projects/redirected-project", params) do redirect("/projects/project-name", params, 301) end def view("/projects/3004/update/3174", _) do {:ok, Enum.at(project_update_repo(), 1)} end def view("/projects/project-name/update/project-progress", _) do {:ok, Enum.at(project_update_repo(), 1)} end def view("/projects/project-name/update/update-with-paragraphs", _) do {:ok, Enum.at(project_update_repo(), 5)} end def view("/projects/redirected-project/update/update-with-paragraphs", _) do {:ok, Enum.at(project_update_repo(), 7)} end def view("/projects/project-name/update/redirected-update-with-paragraphs", params) do redirect("/projects/project-name/update/update-with-paragraphs", params, 301) end def view("/projects/DNE/update/update-no-project-with-paragraphs", _) do {:ok, Enum.at(project_update_repo(), 6)} end def view("/projects/project-deleted/update/project-deleted-progress", _) do project_info = %{ "field_project" => [ %{ "target_id" => 3004, "target_type" => "node", "target_uuid" => "5d55a7f8-22da-4ce8-9861-09602c64c7e4", "url" => "/projects/project-deleted" } ] } {:ok, project_update_repo() |> Enum.at(0) |> Map.merge(project_info)} end def view("/projects/redirected-project/update/not-redirected-update", _) do {:ok, Enum.at(project_update_repo(), 2)} end def view("/projects/project-name/update/redirected-update", params) do redirect("/projects/project-name/update/project-progress", params, 301) end def view("/cms/whats-happening", _) do {:ok, whats_happening_response()} end def view("/cms/important-notices", _) do {:ok, banners_response()} end def view("/landing_page_with_all_paragraphs", _) do {:ok, all_paragraphs_response()} end def view("/landing_page", _) do {:ok, landing_page_response()} end def view("/basic_page_with_sidebar", _) do {:ok, basic_page_with_sidebar_response()} end def view("/diversions/diversion", _) do {:ok, diversion_response()} end def view("/redirect_node", _) do {:ok, redirect_response()} end def view("/redirect_node_with_query%3Fid%3D5", _) do {:ok, redirect_with_query_response()} end def view("/redirect_node_with_query", %{"id" => "6"}) do {:ok, redirect_with_query_response()} end def view("/person", _) do {:ok, person_response()} end # Nodes without a path alias OR CMS redirect def view("/node/3183", _) do {:ok, basic_page_no_alias_response()} end def view("/node/3519", _) do {:ok, Enum.at(news_repo(), 0)} end def view("/node/3268", _) do {:ok, Enum.at(events_response(), 0)} end def view("/node/3004", _) do {:ok, Enum.at(project_repo(), 0)} end def view("/node/3005", _) do {:ok, Enum.at(project_update_repo(), 0)} end # Paths that return CMS redirects (path alias exists) def view("/node/3518", params) do redirect("/news/2018/news-entry", params, 301) end def view("/node/3458", params) do redirect("/events/date/title", params, 301) end def view("/node/3480", params) do redirect("/projects/project-name", params, 301) end def view("/node/3174", params) do redirect("/projects/project-name/updates/project-progress", params, 301) end def view("/cms/route-pdfs/87", _) do {:ok, route_pdfs_response()} end def view("/cms/route-pdfs/error", _) do {:error, :invalid_response} end def view("/cms/route-pdfs/" <> _route_id, _) do {:ok, []} end def view("/cms/teasers/guides" <> _, _) do {:ok, teaser_basic_page_response()} end def view("/cms/teasers/guides/red", sticky: 0) do {:ok, []} end def view("/cms/teasers", %{type: [:project], sticky: 1}) do {:ok, teaser_featured_projects_response()} end def view("/cms/teasers", %{type: [:project]}) do {:ok, teaser_project_response()} end def view("/cms/teasers", %{type: [:project_update]}) do {:ok, teaser_project_update_response()} end def view("/cms/teasers", %{type: [:project, :project_update]}) do {:ok, teaser_project_response() ++ teaser_project_update_response()} end def view("/cms/teasers", %{promoted: 0}) do {:ok, teaser_empty_response()} end def view("/cms/teasers", %{type: [:diversion]}) do {:ok, teaser_diversion_response()} end def view("/cms/teasers", %{type: [:news_entry], except: 3518, items_per_page: 4}) do {:ok, teaser_news_entry_response() |> Enum.take(4)} end def view("/cms/teasers", %{type: [:news_entry]}) do {:ok, teaser_news_entry_response()} end def view("/cms/teasers", %{type: [:event]}) do {:ok, teaser_event_response()} end def view("/cms/teasers/" <> arguments, params) when arguments != "any/NotFound" do filtered = teaser_response() |> filter_teasers(params) case Map.fetch(params, :items_per_page) do {:ok, count} -> {:ok, Enum.take(filtered, count)} :error -> {:ok, filtered} end end def view("/admin/content/paragraphs/25", params) do redirect("/paragraphs/custom-html/projects-index", params, 301) end def view("/paragraphs/custom-html/projects-index", _) do {:ok, paragraph_response()} end def view("/redirected-url", params) do redirect("/different-url", params, 302) end def view("/invalid", _) do {:error, :invalid_response} end def view("/timeout", _) do {:error, :timeout} end def view(_, _) do {:error, :not_found} end @impl true def preview(node_id, revision_id) def preview(3518, vid), do: {:ok, do_preview(Enum.at(news_repo(), 1), vid)} def preview(5, vid), do: {:ok, do_preview(Enum.at(events_response(), 1), vid)} def preview(3480, vid), do: {:ok, do_preview(Enum.at(project_repo(), 1), vid)} def preview(3174, vid), do: {:ok, do_preview(Enum.at(project_update_repo(), 1), vid)} def preview(6, vid), do: {:ok, do_preview(basic_page_response(), vid)} defp filter_by(map, key, value) do Enum.filter(map, &match?(%{^key => [%{"value" => ^value}]}, &1)) end defp parse_json(filename) do file_path = [Path.dirname(__ENV__.file), "../../priv/", filename] file_path |> Path.join() |> File.read!() |> Parser.parse!() end # Generates multiple revisions on the fly for a single fixture @spec do_preview(map, integer | String.t() | nil) :: [map] defp do_preview(%{"title" => [%{"value" => title}]} = response, vid) do vid = Helpers.int_or_string_to_int(vid) revisions = for v <- [113, 112, 111] do %{response | "vid" => [%{"value" => v}], "title" => [%{"value" => "#{title} #{v}"}]} end cms_revision_filter(revisions, vid) end # Performs the CMS-side revision ID filtering @spec cms_revision_filter([map], integer | nil) :: [map] defp cms_revision_filter(revisions, vid) # When no vid is specified, all results are returned defp cms_revision_filter(revisions, nil) do revisions end # CMS will filter results to single matching result with vid defp cms_revision_filter(revisions, vid) do Enum.filter(revisions, &match?(%{"vid" => [%{"value" => ^vid}]}, &1)) end def redirect(path, params, code) when params == %{}, do: {:error, {:redirect, code, [to: path]}} def redirect(path, params, code), do: redirect(path <> "?" <> URI.encode_query(params), %{}, code) defp filter_teasers(teasers, %{type: [type], type_op: "not in"}) do Enum.reject(teasers, &filter_teaser?(&1, type)) end defp filter_teasers(teasers, %{type: [type]}) do Enum.filter(teasers, &filter_teaser?(&1, type)) end defp filter_teasers(teasers, %{}) do teasers end defp filter_teaser?(%{"type" => type}, type_atom), do: Atom.to_string(type_atom) === type end
24.254174
98
0.658303
9eda0692e4302678f985b647f8c41f1cc2c13af7
1,977
ex
Elixir
lib/ex_dns_client.ex
kagux/ex_dns_client
f1bd8033dda54b77b2b1b699aa02d015bffe64d5
[ "MIT" ]
5
2017-02-01T15:18:11.000Z
2020-09-10T14:20:50.000Z
lib/ex_dns_client.ex
kagux/ex_dns_client
f1bd8033dda54b77b2b1b699aa02d015bffe64d5
[ "MIT" ]
null
null
null
lib/ex_dns_client.ex
kagux/ex_dns_client
f1bd8033dda54b77b2b1b699aa02d015bffe64d5
[ "MIT" ]
null
null
null
defmodule ExDnsClient do @moduledoc """ A rudimentary DNS client. Thin wrapper around erlang's `inet_res` library """ @type ip4_address :: {0..255, 0..255, 0..255, 0..255} @type ip6_address :: {0..65535, 0..65535, 0..65535, 0..65535, 0..65535, 0..65535, 0..65535, 0..65535} @type ip_address :: ip4_address | ip6_address @type nameserver :: {ip_address, {:port, 1..65535}} @type dns_record_class :: [:in | :chaos | :hs | :any] @type dns_record_type :: [ :a | :aaaa | :cname | :gid | :hinfo | :ns | :mb | :md | :mg | :mf | :minfo | :mx | :naptr | :null | :ptr | :soa | :spf | :srv | :txt | :uid | :uinfo | :unspec | :wks ] @doc """ Resolves the DNS data for the record of the specified type and class for the specified name. On success, filters out the answer records with the correct Class and Type, and returns a list of their data fields. So, a lookup for type any gives an empty answer, as the answer records have specific types that are not any. An empty answer or a failed lookup returns an empty list. """ @type lookup_opts :: [ {:class, dns_record_class} | {:type, dns_record_type} | {:alt_nameservers, [nameserver, ...]} | {:edns, 0 | false} | {:inet6, boolean} | {:nameservers, [nameserver, ...]} | {:recurse, boolean} | {:retry, integer} | {:timeout, integer} | {:udp_payload_size, integer} | {:usevc, boolean} ] @type dns_data :: [String.t] | [ip4_address] | [ip6_address] @spec lookup(name :: String.t, opts :: lookup_opts) :: dns_data def lookup(name, opts \\ []) do {class, opts} = opts |> Keyword.pop_first(:class, :in) {type, opts} = opts |> Keyword.pop_first(:type, :a) name |> to_charlist |> :inet_res.lookup(class, type, opts) |> Enum.map(&charlist_to_string/1) end defp charlist_to_string(list) when is_list(list) do list |> to_string end defp charlist_to_string(arg), do: arg end
38.019231
118
0.616085
9eda079cedb4e9bfad272b5c79ccd4e32ed11996
4,576
exs
Elixir
test/table_test.exs
landonwilkins/ex_admin
bc6fa5c5e82add16b90e92f9abf388f5b04f67ec
[ "MIT" ]
null
null
null
test/table_test.exs
landonwilkins/ex_admin
bc6fa5c5e82add16b90e92f9abf388f5b04f67ec
[ "MIT" ]
1
2021-07-08T17:24:01.000Z
2021-11-02T09:49:33.000Z
test/table_test.exs
landonwilkins/ex_admin
bc6fa5c5e82add16b90e92f9abf388f5b04f67ec
[ "MIT" ]
2
2020-01-14T21:10:46.000Z
2021-07-07T16:36:49.000Z
defmodule ExAdminTest.TableTest do use ExUnit.Case, async: true alias ExAdmin.Table def index_actions(_, _, _), do: nil setup do table_options = %{ fields: [:id, :name, :inserted_at], filter: "", order: nil, page: %{page_number: 1}, path_prefix: "/admin/users?order=", scope: nil, selectable: true, selectable_column: true, sort: "desc" } {:ok, %{table_opts: table_options}} end describe "build_th" do test "actions", %{table_opts: table_options} do expected = {:safe, "<th class='th-actions'>Actions</th>"} opts = {"Actions", %{fun: &index_actions/3}} assert Table.build_th(opts, table_options) == expected end test "link field", %{table_opts: table_options} do expected = {:safe, "<th class='sortable th-id'><a href='/admin/users?order=id_desc&amp;page=1'>Id</a></th>"} opts = {:id, %{link: true}} assert Table.build_th(opts, table_options) == expected end test "date field", %{table_opts: table_options} do expected = {:safe, "<th class='sortable th-inserted_at'><a href='/admin/users?order=inserted_at_desc&amp;page=1'>Inserted At</a></th>"} opts = {:inserted_at, %{}} assert Table.build_th(opts, table_options) == expected end test "sortable with scope", %{table_opts: table_options} do expected = {:safe, "<th class='sortable th-id'><a href='/admin/users?order=id_desc&amp;page=1&amp;scope=complete'>Id</a></th>"} table_options = put_in(table_options, [:scope], "complete") opts = {:id, %{}} assert Table.build_th(opts, table_options) == expected end test "filtered", %{table_opts: table_options} do expected = {:safe, "<th class='sortable sorted-desc th-id'><a href='/admin/users?order=id_asc&amp;page=1&amp;q%5Btotal_price_gt%5D=100'>Id</a></th>"} table_options = %{ table_options | filter: "&q%5Btotal_price_gt%5D=100", order: {"id", "desc"} } opts = {:id, %{}} assert Table.build_th(opts, table_options) == expected end test "order asc", %{table_opts: table_options} do expected = {:safe, "<th class='sortable sorted-asc th-id'><a href='/admin/users?order=id_desc&amp;page=1'>Id</a></th>"} table_options = %{table_options | order: {"id", "asc"}} opts = {:id, %{}} assert Table.build_th(opts, table_options) == expected end test "atom field_name binary label", %{table_opts: table_options} do expected = {:safe, "<th class='th-id'>Record Id</th>"} opts = {:id, %{label: "Record Id"}} assert Table.build_th(opts, table_options) == expected end test "binary field_name binary label", %{table_opts: table_options} do expected = {:safe, "<th class='th-record'>Record Id</th>"} opts = {"record", %{label: "Record Id"}} assert Table.build_th(opts, table_options) == expected end test "field name and table opts - no tuple", %{table_opts: table_options} do expected = {:safe, "<th class='th-id'>Id</th>"} assert Table.build_th(:id, table_options) == expected assert Table.build_th("id", table_options) == expected end test "field name, opts and table opts - no tuple", %{table_opts: table_options} do expected = {:safe, "<th class='th-id'>Record Id</th>"} opts = %{label: "Record Id"} assert Table.build_th("id", opts, table_options) == expected end test "field name, fields in table_options - no tuple", %{table_opts: table_options} do expected = {:safe, "<th class='sortable th-id'><a href='/admin/users?order=id_desc&amp;page=1'>Id</a></th>"} table_options = put_in(table_options, [:fields], [:id]) assert Table.build_th("id", %{link: true}, table_options) == expected assert Table.build_th("id", %{}, table_options) == expected end test "field name, no field in table_options - no tuple", %{table_opts: table_options} do expected = {:safe, "<th class='th-id'>Id</th>"} table_options = put_in(table_options, [:fields], [:name]) assert Table.build_th("id", %{link: true}, table_options) == expected assert Table.build_th("id", %{}, table_options) == expected end test "parameterize binary field", %{table_opts: table_options} do expected = {:safe, "<th class='th-some_field'>Some Field</th>"} assert Table.build_th("some field", %{}, table_options) == expected end end end
35.2
139
0.612762
9eda6de889366cdf265f8775976dcd7e64ba4eb2
2,686
exs
Elixir
test/cachex/actions/decr_test.exs
botwerk/cachex
d37996d3be35b0d8281e347d44c024ecf2735131
[ "MIT" ]
946
2017-06-26T00:36:58.000Z
2022-03-29T19:52:31.000Z
test/cachex/actions/decr_test.exs
botwerk/cachex
d37996d3be35b0d8281e347d44c024ecf2735131
[ "MIT" ]
152
2017-06-28T10:01:24.000Z
2022-03-24T18:46:13.000Z
test/cachex/actions/decr_test.exs
botwerk/cachex
d37996d3be35b0d8281e347d44c024ecf2735131
[ "MIT" ]
84
2017-06-30T05:30:31.000Z
2022-03-01T20:23:16.000Z
defmodule Cachex.Actions.DecrTest do use CachexCase # This test covers various combinations of decrementing cache items, by tweaking # the options provided alongside the calls. We validate the flags and values # coming back, as well as the fact they're forwarded to the hooks correctly. test "decrementing cache items" do # create a forwarding hook hook = ForwardHook.create() # create a test cache cache = Helper.create_cache([ hooks: [ hook ] ]) # define write options opts1 = [ initial: 10 ] # decrement some items decr1 = Cachex.decr(cache, "key1") decr2 = Cachex.decr(cache, "key1", 2) decr3 = Cachex.decr(cache, "key2", 1, opts1) # the first result should be -1 assert(decr1 == { :ok, -1 }) # the second result should be -3 assert(decr2 == { :ok, -3 }) # the third result should be 9 assert(decr3 == { :ok, 9 }) # verify the hooks were updated with the decrement assert_receive({ { :decr, [ "key1", 1, [] ] }, ^decr1 }) assert_receive({ { :decr, [ "key1", 2, [] ] }, ^decr2 }) assert_receive({ { :decr, [ "key2", 1, ^opts1 ] }, ^decr3 }) # retrieve all items value1 = Cachex.get(cache, "key1") value2 = Cachex.get(cache, "key2") # verify the items match assert(value1 == { :ok, -3 }) assert(value2 == { :ok, 9 }) end # This test covers the negative case where a value exists but is not an integer, # which naturally means we can't decrement it properly. We just check for an # error flag in this case. test "decrementing a non-numeric value" do # create a test cache cache = Helper.create_cache() # set a non-numeric value { :ok, true } = Cachex.put(cache, "key", "value") # try to increment the value result = Cachex.decr(cache, "key", 1) # we should receive an error assert(result == { :error, :non_numeric_value }) end # This test verifies that this action is correctly distributed across # a cache cluster, instead of just the local node. We're not concerned # about the actual behaviour here, only the routing of the action. @tag distributed: true test "decrementing items in a cache cluster" do # create a new cache cluster for cleaning { cache, _nodes } = Helper.create_cache_cluster(2) # we know that 1 & 2 hash to different nodes { :ok, -1 } = Cachex.decr(cache, 1, 1) { :ok, -2 } = Cachex.decr(cache, 2, 2) # check the results of the calls across nodes size1 = Cachex.size(cache, [ local: true ]) size2 = Cachex.size(cache, [ local: false ]) # one local, two total assert(size1 == { :ok, 1 }) assert(size2 == { :ok, 2 }) end end
32.361446
82
0.638124
9eda7b69eca285d287497f65decadc849eb760b9
503
ex
Elixir
lib/spotify/object_model.ex
chippers/spotify_web_api
221a197dbac4971f87e9917d02cb335e6a42b726
[ "MIT" ]
null
null
null
lib/spotify/object_model.ex
chippers/spotify_web_api
221a197dbac4971f87e9917d02cb335e6a42b726
[ "MIT" ]
null
null
null
lib/spotify/object_model.ex
chippers/spotify_web_api
221a197dbac4971f87e9917d02cb335e6a42b726
[ "MIT" ]
null
null
null
defmodule Spotify.ObjectModel do @moduledoc """ A behavior for implementing the `c:as/0` callback for Spotify object models that are returned from the web api. """ @doc """ Returns each Object Models' model for json decoding. This callback is passed into `Poison.decode` `:as` option for formatting incoming json as structs. Each Object Model should implement it, and nest other Object Models' `as` functions in their own as needed. """ @callback as() :: struct end
31.4375
79
0.705765
9edab40b38f059a0f92551121c5ac11688a4dfd0
1,367
ex
Elixir
test/support/mocks.ex
antonioparisi/rihanna
81aca463419111aa3e761dbbd5862ac986d3ec7a
[ "MIT" ]
null
null
null
test/support/mocks.ex
antonioparisi/rihanna
81aca463419111aa3e761dbbd5862ac986d3ec7a
[ "MIT" ]
null
null
null
test/support/mocks.ex
antonioparisi/rihanna
81aca463419111aa3e761dbbd5862ac986d3ec7a
[ "MIT" ]
1
2019-10-10T23:24:10.000Z
2019-10-10T23:24:10.000Z
defmodule Rihanna.Mocks do defmodule LongJob do @behaviour Rihanna.Job def perform(_) do LongJob.Counter.increment() :timer.sleep(500) :ok end end defmodule LongJob.Counter do use Agent def start_link(_) do Agent.start_link(fn -> 0 end, name: __MODULE__) end def increment() do Agent.update(__MODULE__, fn count -> count + 1 end) end def get_count() do Agent.get(__MODULE__, & &1) end end defmodule BehaviourMock do @behaviour Rihanna.Job def perform([pid, msg]) do Process.send(pid, {msg, self()}, []) :ok end end defmodule ErrorTupleBehaviourMock do @behaviour Rihanna.Job def perform([pid, msg]) do Process.send(pid, {msg, self()}, []) {:error, "failed for some reason"} end end defmodule ErrorBehaviourMock do @behaviour Rihanna.Job def perform([pid, msg]) do Process.send(pid, {msg, self()}, []) {:error, "failed for some reason"} end end defmodule MFAMock do def fun(pid, msg) do Process.send(pid, {msg, self()}, []) end end defmodule BadMFAMock do @behaviour Rihanna.Job def perform(_) do raise "Kaboom!" end end defmodule MockJob do @behaviour Rihanna.Job def perform(arg) do {:ok, arg} end end end
17.303797
53
0.600585
9edb0d0d692f1fd380fb7aad684967f9896ab5d5
181
ex
Elixir
lib/mix/tasks/travis.ex
gitter-badger/tirexs
0625f2e4090e3d06a9d5483f17ab5f0a5177e719
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/travis.ex
gitter-badger/tirexs
0625f2e4090e3d06a9d5483f17ab5f0a5177e719
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/travis.ex
gitter-badger/tirexs
0625f2e4090e3d06a9d5483f17ab5f0a5177e719
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Travis do use Mix.Task @shortdoc "Runs only unit tests whereas acceptances are skipped" def run(_) do Mix.Task.run("test", ["test/tirexs"]) end end
20.111111
66
0.701657
9edb1087264f78778c9c34fd57fe777bf5f9a885
1,237
ex
Elixir
apps/ewallet/lib/ewallet/permissions/bouncer/targets/exchange_pair_target.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/ewallet/lib/ewallet/permissions/bouncer/targets/exchange_pair_target.ex
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/ewallet/lib/ewallet/permissions/bouncer/targets/exchange_pair_target.ex
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 EWallet.Bouncer.ExchangePairTarget do @moduledoc """ A policy helper containing the actual authorization. """ @behaviour EWallet.Bouncer.TargetBehaviour alias EWalletDB.ExchangePair @spec get_owner_uuids(ExchangePair.t()) :: [Ecto.UUID.t()] def get_owner_uuids(_) do [] end @spec get_target_types() :: [:exchange_pairs] def get_target_types, do: [:exchange_pairs] @spec get_target_type(ExchangePair.t()) :: :exchange_pairs def get_target_type(_), do: :exchange_pairs @spec get_target_accounts(ExchangePair.t(), any()) :: [Account.t()] def get_target_accounts(%ExchangePair{}, _dispatch_config), do: [] end
34.361111
74
0.746968
9edb18bef539ddbe074db575128d9a92026e00fc
1,988
ex
Elixir
lib/my_app/clrt_manager.ex
normanpatrick/elixir-python-task-api
84a12eff26ddf98a29526630e4ce9fa1076545cb
[ "MIT" ]
null
null
null
lib/my_app/clrt_manager.ex
normanpatrick/elixir-python-task-api
84a12eff26ddf98a29526630e4ce9fa1076545cb
[ "MIT" ]
null
null
null
lib/my_app/clrt_manager.ex
normanpatrick/elixir-python-task-api
84a12eff26ddf98a29526630e4ce9fa1076545cb
[ "MIT" ]
null
null
null
defmodule MyApp.CLRTManager do @moduledoc """ The CLRTManager context. """ import Ecto.Query, warn: false alias MyApp.Repo alias MyApp.CLRTManager.SLRTask @doc """ Returns the list of slrtasks. ## Examples iex> list_slrtasks() [%SLRTask{}, ...] """ def list_slrtasks do Repo.all(SLRTask) end @doc """ Gets a single slr_task. Raises `Ecto.NoResultsError` if the Slr task does not exist. ## Examples iex> get_slr_task!(123) %SLRTask{} iex> get_slr_task!(456) ** (Ecto.NoResultsError) """ def get_slr_task!(id), do: Repo.get!(SLRTask, id) @doc """ Gets a single slr_task. Returns :error the Slr task does not exist. """ def get_slr_task(id), do: Repo.get(SLRTask, id) @doc """ Creates a slr_task. ## Examples iex> create_slr_task(%{field: value}) {:ok, %SLRTask{}} iex> create_slr_task(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_slr_task(attrs \\ %{}) do %SLRTask{} |> SLRTask.changeset(attrs) |> Repo.insert() end @doc """ Updates a slr_task. ## Examples iex> update_slr_task(slr_task, %{field: new_value}) {:ok, %SLRTask{}} iex> update_slr_task(slr_task, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_slr_task(%SLRTask{} = slr_task, attrs) do slr_task |> SLRTask.changeset(attrs) |> Repo.update() end @doc """ Deletes a SLRTask. ## Examples iex> delete_slr_task(slr_task) {:ok, %SLRTask{}} iex> delete_slr_task(slr_task) {:error, %Ecto.Changeset{}} """ def delete_slr_task(%SLRTask{} = slr_task) do Repo.delete(slr_task) end @doc """ Returns an `%Ecto.Changeset{}` for tracking slr_task changes. ## Examples iex> change_slr_task(slr_task) %Ecto.Changeset{source: %SLRTask{}} """ def change_slr_task(%SLRTask{} = slr_task) do SLRTask.changeset(slr_task, %{}) end end
17.59292
63
0.610664
9edbe326154c51379ebfd17c32d323c22bb07938
1,613
exs
Elixir
apps/tai/test/tai/orders/search_transitions_test.exs
ccamateur/tai
41c4b3e09dafc77987fa3f6b300c15461d981e16
[ "MIT" ]
276
2018-01-16T06:36:06.000Z
2021-03-20T21:48:01.000Z
apps/tai/test/tai/orders/search_transitions_test.exs
ccamateur/tai
41c4b3e09dafc77987fa3f6b300c15461d981e16
[ "MIT" ]
73
2018-10-05T18:45:06.000Z
2021-02-08T05:46:33.000Z
apps/tai/test/tai/orders/search_transitions_test.exs
ccamateur/tai
41c4b3e09dafc77987fa3f6b300c15461d981e16
[ "MIT" ]
43
2018-06-09T09:54:51.000Z
2021-03-07T07:35:17.000Z
defmodule Tai.Orders.SearchTransitionsTest do use Tai.TestSupport.DataCase, async: false test "returns the oldest 25 order transitions by default" do {:ok, order} = create_order() order_transitions = create_test_order_transitions(order, 26) search_order_transitions = Tai.Orders.search_transitions(order.client_id, nil) assert length(search_order_transitions) == 25 assert Enum.at(search_order_transitions, 0) == Enum.at(order_transitions, 0) assert Enum.at(search_order_transitions, 24) == Enum.at(order_transitions, 24) end test "can paginate results with a custom page & size" do {:ok, order} = create_order() order_transitions = create_test_order_transitions(order, 4) search_order_transitions_1 = Tai.Orders.search_transitions(order.client_id, nil, page: 1, page_size: 2) assert length(search_order_transitions_1) == 2 assert Enum.at(search_order_transitions_1, 0) == Enum.at(order_transitions, 0) assert Enum.at(search_order_transitions_1, 1) == Enum.at(order_transitions, 1) search_order_transitions_2 = Tai.Orders.search_transitions(order.client_id, nil, page: 2, page_size: 2) assert length(search_order_transitions_2) == 2 assert Enum.at(search_order_transitions_2, 0) == Enum.at(order_transitions, 2) assert Enum.at(search_order_transitions_2, 1) == Enum.at(order_transitions, 3) end defp create_test_order_transitions(order, count) do 1 |> Range.new(count) |> Enum.map(fn _n -> {:ok, order_transition} = create_order_transition(order.client_id, %{}, :cancel) order_transition end) end end
42.447368
107
0.745815
9edbe944d5c0b1ab4e3f0d90190647ca284c7730
5,676
ex
Elixir
lib/aph/tts.ex
tometoproject/tometo
ed91069b11a020723edb9a143de29d9bac86a2b0
[ "BlueOak-1.0.0", "Apache-2.0" ]
8
2019-09-26T13:59:25.000Z
2020-03-30T21:26:48.000Z
lib/aph/tts.ex
tometoproject/tometo
ed91069b11a020723edb9a143de29d9bac86a2b0
[ "BlueOak-1.0.0", "Apache-2.0" ]
39
2019-11-16T02:24:28.000Z
2020-01-14T16:40:28.000Z
lib/aph/tts.ex
tometoproject/tometo
ed91069b11a020723edb9a143de29d9bac86a2b0
[ "BlueOak-1.0.0", "Apache-2.0" ]
2
2019-12-16T07:55:14.000Z
2020-06-11T04:14:00.000Z
defmodule Aph.TTS do @moduledoc """ TTS generation and alignment functions. This module takes care of everything related to TTS (text-to-speech) generation and parsing/aligning. It's also the module that introduces the most side effects in the entire app, because it has to shell out to various programs and make HTTP calls. """ # This is the language map for the Google TTS API @g_lang_map %{ ar: "ar-XA", nl: "nl-NL", en: "en-US", fr: "fr-FR", de: "de-DE", hi: "hi-IN", id: "id-ID", it: "it-IT", ja: "ja-JP", ko: "ko-KR", zh: "cmn-CN", nb: "nb-NO", pl: "pl-PL", pt: "pt-PT", ru: "ru-RU", tr: "tr-TR", vi: "vi-VN" } # This is the language map for `aeneas` @a_lang_map %{ ar: :ara, nl: :nld, en: :eng, fr: :fra, de: :deu, hi: :hin, id: :ind, it: :ita, ja: :jpn, ko: :kor, zh: :cmn, nb: :nor, pl: :pol, pt: :por, ru: :rus, tr: :tur, vi: :vie } @doc """ Generates a TTS message. Takes a database entity, a file prefix and a Aph.Main.Avatar. The database entity can be generic, but must at least have an ID and a `content` field. The file prefix is used to prevent filename collisions, since IDs can be the same across multiple database tables. First creates a temporary directory under `gentts/`, then depending on the TTS synthesis configuration option pulls the audio from somewhere and saves it in the temporary directory. Then calls TTS.align/3. """ def synthesize(entity, prefix, av) do File.mkdir_p!("gentts/#{prefix}-#{entity.id}") File.mkdir_p!("priv/static/tts/") if Application.get_env(:aph, :tts) == "google" do synthesize_google(entity, prefix, av) else synthesize_espeak(entity, prefix, av) end end # Synthesize TTS with Google Text-to-Speech API. defp synthesize_google(entity, prefix, av) do api_key = Application.get_env(:aph, :google_key) lang = @g_lang_map[String.to_atom(av.language)] gender_num = cond do # en-US has no Standard-A voice for some reason lang == "en-US" and av.gender == "FEMALE" -> "C" lang == "en-US" and av.gender == "MALE" -> "B" av.gender == "FEMALE" -> "A" true -> "B" end body = Jason.encode!(%{ input: %{text: entity.content}, voice: %{languageCode: lang, name: "#{lang}-Standard-#{gender_num}"}, audioConfig: %{ audioEncoding: "OGG_OPUS", pitch: av.pitch || 0, speakingRate: av.speed || 1.0 } }) headers = [{"content-type", "application/json"}] with {:ok, res} <- HTTPoison.post( "https://texttospeech.googleapis.com/v1/text:synthesize?key=#{api_key}", body, headers ), {:ok, json} <- Jason.decode(res.body), {:ok, content} <- Base.decode64(json["audioContent"]), :ok <- File.write("gentts/#{prefix}-#{entity.id}/temp.ogg", content), :ok <- align(entity.id, entity.content, prefix, av.language) do :ok else {:error, err} -> {:tts_error, err} end end # Synthesizes TTS using espeak. defp synthesize_espeak(entity, prefix, av) do # Since espeak doesn't accept the same values that the Google TTS api does, # we have to convert them from one scale to another. scale_pitch = (av.pitch + 20) / 40 * 99 scale_speed = floor((av.speed - 0.25) / 3.75 * 370.0 + 80.0) with {_, 0} <- System.cmd("espeak", [ "-p", to_string(scale_pitch), "-s", to_string(scale_speed), "-w", "gentts/#{prefix}-#{entity.id}/temp.wav", entity.content ]), {_, 0} <- System.cmd("ffmpeg", [ "-i", "gentts/#{prefix}-#{entity.id}/temp.wav", "-c:a", "libopus", "-b:a", "96K", "gentts/#{prefix}-#{entity.id}/temp.ogg" ]), :ok <- align(entity.id, entity.content, prefix, av.language) do :ok else {_error, 1} -> {:tts_error, "espeak failed to create audio!"} end end @doc """ Removes temporary directory and moves files to a permanent location. Takes the name of the temporary directory. """ def clean(name) do with :ok <- File.cp("gentts/#{name}/out.json", "priv/static/tts/#{name}.json"), :ok <- File.cp("gentts/#{name}/temp.ogg", "priv/static/tts/#{name}.ogg"), {:ok, _} <- File.rm_rf("gentts/#{name}") do :ok else e -> {:tts_error, e} end end @doc """ Forcibly aligns an existing TTS message. Takes the name/ID, the TTS text, and the language. This shells out to `aeneas` and obtains a JSON file that contains timestamps of when in the audio file which word is said. """ def align(name, text, prefix, lang) do lang = @a_lang_map[String.to_atom(lang)] with :ok <- File.write( "gentts/#{prefix}-#{name}/temp.txt", text |> String.split(" ") |> Enum.join("\n") ), {_, 0} <- System.cmd("python3", [ "-m", "aeneas.tools.execute_task", "gentts/#{prefix}-#{name}/temp.ogg", "gentts/#{prefix}-#{name}/temp.txt", "task_language=#{Atom.to_string(lang)}|os_task_file_format=json|is_text_type=plain", "gentts/#{prefix}-#{name}/out.json" ]) do :ok else {:error, err} -> {:error, err} {err, 1} -> {:error, err} end end end
28.238806
97
0.552678
9edbed6564e2d4c9dadabc158e63ea18cf6d0944
356
exs
Elixir
priv/repo/seeds.exs
timrourke/colorstorm-api
fee60a52701a4f773fcd2c8c5c70a472d0d52f09
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
timrourke/colorstorm-api
fee60a52701a4f773fcd2c8c5c70a472d0d52f09
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
timrourke/colorstorm-api
fee60a52701a4f773fcd2c8c5c70a472d0d52f09
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Colorstorm.Repo.insert!(%Colorstorm.SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
29.666667
61
0.710674
9edc348a2c53d5804fcf72ed0e1db1975d1142c6
2,616
exs
Elixir
test/secret_grinch_web/controllers/match_controller_test.exs
clorofila-league/secret_grinch
b06ac85ff5f06d5405d190ccc9966b01f0406b87
[ "Apache-2.0" ]
3
2017-08-03T16:49:18.000Z
2018-10-03T03:30:26.000Z
test/secret_grinch_web/controllers/match_controller_test.exs
clorofila-league/secret_grinch
b06ac85ff5f06d5405d190ccc9966b01f0406b87
[ "Apache-2.0" ]
18
2017-08-04T12:43:08.000Z
2017-08-05T14:15:41.000Z
test/secret_grinch_web/controllers/match_controller_test.exs
clorofila-league/secret_grinch
b06ac85ff5f06d5405d190ccc9966b01f0406b87
[ "Apache-2.0" ]
1
2018-10-03T03:30:29.000Z
2018-10-03T03:30:29.000Z
defmodule SecretGrinchWeb.MatchControllerTest do use SecretGrinchWeb.ConnCase alias SecretGrinch.Matches @create_attrs %{name: "some name"} @update_attrs %{name: "some updated name"} @invalid_attrs %{name: nil} def fixture(:match) do {:ok, match} = Matches.create_match(@create_attrs) match end describe "index" do test "lists all matches", %{conn: conn} do conn = get conn, match_path(conn, :index) assert html_response(conn, 200) =~ "Listing Matches" end end describe "new match" do test "renders form", %{conn: conn} do conn = get conn, match_path(conn, :new) assert html_response(conn, 200) =~ "New Match" end end describe "create match" do test "redirects to show when data is valid", %{conn: conn} do conn = post conn, match_path(conn, :create), match: @create_attrs assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == match_path(conn, :show, id) conn = get conn, match_path(conn, :show, id) assert html_response(conn, 200) =~ "Show Match" end test "renders errors when data is invalid", %{conn: conn} do conn = post conn, match_path(conn, :create), match: @invalid_attrs assert html_response(conn, 200) =~ "New Match" end end describe "edit match" do setup [:create_match] test "renders form for editing chosen match", %{conn: conn, match: match} do conn = get conn, match_path(conn, :edit, match) assert html_response(conn, 200) =~ "Edit Match" end end describe "update match" do setup [:create_match] test "redirects when data is valid", %{conn: conn, match: match} do conn = put conn, match_path(conn, :update, match), match: @update_attrs assert redirected_to(conn) == match_path(conn, :show, match) conn = get conn, match_path(conn, :show, match) assert html_response(conn, 200) =~ "some updated name" end test "renders errors when data is invalid", %{conn: conn, match: match} do conn = put conn, match_path(conn, :update, match), match: @invalid_attrs assert html_response(conn, 200) =~ "Edit Match" end end describe "delete match" do setup [:create_match] test "deletes chosen match", %{conn: conn, match: match} do conn = delete conn, match_path(conn, :delete, match) assert redirected_to(conn) == match_path(conn, :index) assert_error_sent 404, fn -> get conn, match_path(conn, :show, match) end end end defp create_match(_) do match = fixture(:match) {:ok, match: match} end end
29.393258
80
0.65367
9edc68b0696e7770f553568f4883350bbdebb29c
4,009
ex
Elixir
lib/livebook_web/live/session_live/mix_standalone_live.ex
benjreinhart/livebook
0500ad5c6237167ce9769d8cc78fca360834f576
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/session_live/mix_standalone_live.ex
benjreinhart/livebook
0500ad5c6237167ce9769d8cc78fca360834f576
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/session_live/mix_standalone_live.ex
benjreinhart/livebook
0500ad5c6237167ce9769d8cc78fca360834f576
[ "Apache-2.0" ]
1
2021-07-07T06:18:36.000Z
2021-07-07T06:18:36.000Z
defmodule LivebookWeb.SessionLive.MixStandaloneLive do use LivebookWeb, :live_view alias Livebook.{Session, Runtime, Utils} @type status :: :initial | :initializing | :finished @impl true def mount(_params, %{"session_id" => session_id, "current_runtime" => current_runtime}, socket) do if connected?(socket) do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") end {:ok, assign(socket, session_id: session_id, status: :initial, current_runtime: current_runtime, path: initial_path(current_runtime), outputs: [], emitter: nil ), temporary_assigns: [outputs: []]} end @impl true def render(assigns) do ~L""" <div class="flex-col space-y-5"> <p class="text-gray-700"> Start a new local node in the context of a Mix project. This way all your code and dependencies will be available within the notebook. </p> <p class="text-gray-700"> <span class="font-semibold">Warning:</span> Notebooks that use <code>Mix.install/1</code> do not work inside a Mix project because the dependencies of the project itself have been installed instead. </p> <%= if @status == :initial do %> <div class="h-full h-52"> <%= live_component LivebookWeb.PathSelectComponent, id: "path_select", path: @path, extnames: [], running_paths: [], phx_target: nil, phx_submit: if(disabled?(@path), do: nil, else: "init") %> </div> <%= content_tag :button, if(matching_runtime?(@current_runtime, @path), do: "Reconnect", else: "Connect"), class: "button button-blue", phx_click: "init", disabled: disabled?(@path) %> <% end %> <%= if @status != :initial do %> <div class="markdown"> <pre><code class="max-h-40 overflow-y-auto tiny-scrollbar" id="mix-standalone-init-output" phx-update="append" phx-hook="ScrollOnUpdate" ><%= for {output, i} <- @outputs do %><span id="output-<%= i %>"><%= ansi_string_to_html(output) %></span><% end %></code></pre> </div> <% end %> </div> """ end @impl true def handle_event("set_path", %{"path" => path}, socket) do {:noreply, assign(socket, path: path)} end def handle_event("init", _params, socket) do emitter = Utils.Emitter.new(self()) Runtime.MixStandalone.init_async(socket.assigns.path, emitter) {:noreply, assign(socket, status: :initializing, emitter: emitter)} end @impl true def handle_info({:emitter, ref, message}, %{assigns: %{emitter: %{ref: ref}}} = socket) do case message do {:output, output} -> {:noreply, add_output(socket, output)} {:ok, runtime} -> Session.connect_runtime(socket.assigns.session_id, runtime) {:noreply, socket |> assign(status: :finished) |> add_output("Connected successfully")} {:error, error} -> {:noreply, socket |> assign(status: :finished) |> add_output("Error: #{error}")} end end def handle_info({:operation, {:set_runtime, _pid, runtime}}, socket) do {:noreply, assign(socket, current_runtime: runtime)} end def handle_info(_, socket), do: {:noreply, socket} defp add_output(socket, output) do assign(socket, outputs: socket.assigns.outputs ++ [{output, Utils.random_id()}]) end defp initial_path(%Runtime.MixStandalone{} = current_runtime) do current_runtime.project_path end defp initial_path(_runtime), do: File.cwd!() <> "/" defp mix_project_root?(path) do File.dir?(path) and File.exists?(Path.join(path, "mix.exs")) end defp matching_runtime?(%Runtime.MixStandalone{} = runtime, path) do Path.expand(runtime.project_path) == Path.expand(path) end defp matching_runtime?(_runtime, _path), do: false defp disabled?(path) do not mix_project_root?(path) end end
32.330645
140
0.619356
9edc76e13ce6d71ae5d819f95ccf5b4c7fc535b4
1,599
ex
Elixir
clients/storage_transfer/lib/google_api/storage_transfer/v1/model/aws_access_key.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/lib/google_api/storage_transfer/v1/model/aws_access_key.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/lib/google_api/storage_transfer/v1/model/aws_access_key.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.StorageTransfer.V1.Model.AwsAccessKey do @moduledoc """ AWS access key (see [AWS Security Credentials](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)). ## Attributes - accessKeyId (String): AWS access key ID. Required. Defaults to: `null`. - secretAccessKey (String): AWS secret access key. This field is not returned in RPC responses. Required. Defaults to: `null`. """ defstruct [ :"accessKeyId", :"secretAccessKey" ] end defimpl Poison.Decoder, for: GoogleApi.StorageTransfer.V1.Model.AwsAccessKey do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.StorageTransfer.V1.Model.AwsAccessKey do def encode(value, options) do GoogleApi.StorageTransfer.V1.Deserializer.serialize_non_nil(value, options) end end
33.3125
128
0.754221
9edc77ffd7757fefda95539cab6697d102baa3a3
25,564
ex
Elixir
lib/ecto/query.ex
victorsolis/ecto
6c0dbf1ee2afd9b5bdf1f3feee8d361c8197c99a
[ "Apache-2.0" ]
null
null
null
lib/ecto/query.ex
victorsolis/ecto
6c0dbf1ee2afd9b5bdf1f3feee8d361c8197c99a
[ "Apache-2.0" ]
null
null
null
lib/ecto/query.ex
victorsolis/ecto
6c0dbf1ee2afd9b5bdf1f3feee8d361c8197c99a
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Query do @moduledoc ~S""" Provides the Query DSL. Queries are used to retrieve and manipulate data in a repository (see `Ecto.Repo`). Although this module provides a complete API, supporting expressions like `where/3`, `select/3` and so forth, most of the time developers need to import only the `from/2` macro. # Imports only from/2 of Ecto.Query import Ecto.Query, only: [from: 2] # Create a query query = from w in Weather, where: w.prcp > 0, select: w.city # Send the query to the repository Repo.all(query) ## Composition Ecto queries are composable. For example, the query above can actually be defined in two parts: # Create a query query = from w in Weather, where: w.prcp > 0 # Extend the query query = from w in query, select: w.city Keep in mind though the variable names used on the left-hand side of `in` are just a convenience, they are not taken into account in the query generation. Any value can be used on the right-side of `in` as long as it implements the `Ecto.Queryable` protocol. ## Query expressions Ecto allows a limited set of expressions inside queries. In the query below, for example, we use `w.prcp` to access a field, the `>` comparison operator and the literal `0`: query = from w in Weather, where: w.prcp > 0 You can find the full list of operations in `Ecto.Query.API`. Besides the operations listed here, the following literals are supported in queries: * Integers: `1`, `2`, `3` * Floats: `1.0`, `2.0`, `3.0` * Booleans: `true`, `false` * Binaries: `<<1, 2, 3>>` * Strings: `"foo bar"`, `~s(this is a string)` * Arrays: `[1, 2, 3]`, `~w(interpolate words)` All other types must be passed as a parameter using interpolation as explained below. ## Interpolation External values and Elixir expressions can be injected into a query expression with `^`: def with_minimum(age, height_ft) do from u in User, where: u.age > ^age and u.height > ^(height_ft * 3.28) end with_minimum(18, 5.0) Interpolation can also be used with the `field/2` function which allows developers to dynamically choose a field to query: def at_least_four(doors_or_tires) do from c in Car, where: field(c, ^doors_or_tires) >= 4 end In the example above, both `at_least_four(:doors)` and `at_least_four(:tires)` would be valid calls as the field is dynamically inserted. ## Casting Ecto is able to cast interpolated values in queries: age = "1" Repo.all(from u in User, where: u.age > ^age) The example above works because `u.age` is tagged as an :integer in the User schema and therefore Ecto will attempt to cast the interpolated `^age` to integer. When a value cannot be cast, `Ecto.CastError` is raised. ## Fragments If you need a escape hatch, Ecto provides fragments (see `Ecto.Query.API.fragment/1`) to inject SQL (and non-SQL) fragments into queries. For example, to get all posts while running the "downcase(?)" function in the database where `p.title` is interpolated in place of `?`, one can write: from p in Post, where: is_nil(p.published_at) and fragment("downcase(?)", p.title) == ^title Also, most adapters provide direct APIs for queries, like `Ecto.Adapters.SQL.query/4`, allowing developers to completely bypass Ecto queries. ## Macro API In all examples so far we have used the **keywords query syntax** to create a query: import Ecto.Query from w in Weather, where: w.prcp > 0, select: w.city Remember that keywords is a syntax sugar in Elixir for passing a list of two-item tuples where the first element is an atom. The code above is equivalent to: from(w in Weather, [{:where, w.prcp > 0}, {:select, w.city}]) Due to the prevalence of the pipe operator in Elixir, Ecto also supports a pipe-based syntax: from(w in Weather) |> where([w], w.prcp > 0) |> select([w], w.city) The keyword-based and pipe-based examples are equivalent. This module documents each of those macros, providing examples in both the keywords query and pipe expression formats. ## Query Prefix It is possible to set a prefix for the table name in queries. For Postgres users, this will specify the schema where the table is located, while for MySQL users this will specify the database where the table is located. When no prefix is set, Postgres queries are assumed to be in the public schema, while MySQL queries are assumed to be in the database set in the config for the repo. Set the prefix on a query: query = from u in User, select: u queryable = %{query | prefix: "foo"} results = Repo.all(queryable) Set the prefix without the query syntax: results = User |> Ecto.Queryable.to_query |> Map.put(:prefix, "foo") |> Repo.all When a prefix is set in a query, all loaded structs will belong to that prefix, so operations like update and delete will be applied to the proper prefix. In case you want to manually set the prefix for new data, specially on insert, use `Ecto.put_meta/2`. """ defstruct [prefix: nil, sources: nil, from: nil, joins: [], wheres: [], select: nil, order_bys: [], limit: nil, offset: nil, group_bys: [], updates: [], havings: [], preloads: [], assocs: [], distinct: nil, lock: nil] @opaque t :: %__MODULE__{} defmodule QueryExpr do @moduledoc false defstruct [:expr, :file, :line, params: %{}] end defmodule SelectExpr do @moduledoc false defstruct [:expr, :file, :line, fields: [], params: %{}, take: %{}] end defmodule JoinExpr do @moduledoc false defstruct [:qual, :source, :on, :file, :line, :assoc, :ix, params: %{}] end defmodule Tagged do @moduledoc false # * value is the tagged value # * tag is the directly tagged value, like Ecto.DateTime # * type is the underlying tag type, like :datetime defstruct [:value, :tag, :type] end alias Ecto.Query.Builder alias Ecto.Query.Builder.From alias Ecto.Query.Builder.Filter alias Ecto.Query.Builder.Select alias Ecto.Query.Builder.Distinct alias Ecto.Query.Builder.OrderBy alias Ecto.Query.Builder.LimitOffset alias Ecto.Query.Builder.GroupBy alias Ecto.Query.Builder.Preload alias Ecto.Query.Builder.Join alias Ecto.Query.Builder.Lock alias Ecto.Query.Builder.Update @doc """ Resets a previously set field on a query. It can reset any query field except the query source (`from`). ## Example query |> Ecto.Query.exclude(:select) """ def exclude(%Ecto.Query{} = query, field), do: do_exclude(query, field) def exclude(query, field), do: do_exclude(Ecto.Queryable.to_query(query), field) defp do_exclude(%Ecto.Query{} = query, :join), do: %{query | joins: []} defp do_exclude(%Ecto.Query{} = query, :where), do: %{query | wheres: []} defp do_exclude(%Ecto.Query{} = query, :order_by), do: %{query | order_bys: []} defp do_exclude(%Ecto.Query{} = query, :group_by), do: %{query | group_bys: []} defp do_exclude(%Ecto.Query{} = query, :having), do: %{query | havings: []} defp do_exclude(%Ecto.Query{} = query, :distinct), do: %{query | distinct: nil} defp do_exclude(%Ecto.Query{} = query, :select), do: %{query | select: nil} defp do_exclude(%Ecto.Query{} = query, :limit), do: %{query | limit: nil} defp do_exclude(%Ecto.Query{} = query, :offset), do: %{query | offset: nil} defp do_exclude(%Ecto.Query{} = query, :lock), do: %{query | lock: nil} defp do_exclude(%Ecto.Query{} = query, :preload), do: %{query | preloads: [], assocs: []} @doc """ Creates a query. It can either be a keyword query or a query expression. If it is a keyword query the first argument should be an `in` expression and the second argument a keyword query where the keys are expression types and the values are expressions. If it is a query expression the first argument is the original query and the second argument the expression. ## Keywords example from(City, select: c) ## Expressions example City |> select([c], c) ## Examples def paginate(query, page, size) do from query, limit: ^size, offset: ^((page-1) * size) end The example above does not use `in` because `limit` and `offset` do not require such. However, extending a query with a where expression would require the use of `in`: def published(query) do from p in query, where: not(is_nil(p.published_a)) end Notice we have created a `p` variable to represent each item in the query. When the given query has more than one `from` expression, a variable must be given for each in the order they were bound: def published_multi(query) do from [p,o] in query, where: not(is_nil(p.published_at)) and not(is_nil(o.published_at)) end Note the variables `p` and `o` can be named whatever you like as they have no importance in the query sent to the database. """ defmacro from(expr, kw \\ []) do unless Keyword.keyword?(kw) do raise ArgumentError, "second argument to `from` must be a keyword list" end {quoted, binds, count_bind} = From.build(expr, __CALLER__) from(kw, __CALLER__, count_bind, quoted, binds) end @binds [:where, :select, :distinct, :order_by, :group_by, :having, :limit, :offset, :preload, :update] @no_binds [:lock] @joins [:join, :inner_join, :left_join, :right_join, :full_join] defp from([{type, expr}|t], env, count_bind, quoted, binds) when type in @binds do # If all bindings are integer indexes keep AST Macro.expand'able to %Query{}, # otherwise ensure that quoted code is evaluated before macro call quoted = if Enum.all?(binds, fn {_, value} -> is_integer(value) end) do quote do Ecto.Query.unquote(type)(unquote(quoted), unquote(binds), unquote(expr)) end else quote do query = unquote(quoted) Ecto.Query.unquote(type)(query, unquote(binds), unquote(expr)) end end from(t, env, count_bind, quoted, binds) end defp from([{type, expr}|t], env, count_bind, quoted, binds) when type in @no_binds do quoted = quote do Ecto.Query.unquote(type)(unquote(quoted), unquote(expr)) end from(t, env, count_bind, quoted, binds) end defp from([{join, expr}|t], env, count_bind, quoted, binds) when join in @joins do qual = case join do :join -> :inner :inner_join -> :inner :left_join -> :left :right_join -> :right :full_join -> :full end {t, on} = collect_on(t, nil) {quoted, binds, count_bind} = Join.build(quoted, qual, binds, expr, on, count_bind, env) from(t, env, count_bind, quoted, binds) end defp from([{:on, _value}|_], _env, _count_bind, _quoted, _binds) do Builder.error! "`on` keyword must immediately follow a join" end defp from([{key, _value}|_], _env, _count_bind, _quoted, _binds) do Builder.error! "unsupported #{inspect key} in keyword query expression" end defp from([], _env, _count_bind, quoted, _binds) do quoted end defp collect_on([{:on, expr}|t], nil), do: collect_on(t, expr) defp collect_on([{:on, expr}|t], acc), do: collect_on(t, {:and, [], [acc, expr]}) defp collect_on(other, acc), do: {other, acc} @doc """ A join query expression. Receives a source that is to be joined to the query and a condition for the join. The join condition can be any expression that evaluates to a boolean value. The join is by default an inner join, the qualifier can be changed by giving the atoms: `:inner`, `:left`, `:right` or `:full`. For a keyword query the `:join` keyword can be changed to: `:inner_join`, `:left_join`, `:right_join` or `:full_join`. Currently it is possible to join on an Ecto.Schema (a module), an existing source (a binary representing a table), an association or a fragment. See the examples below. ## Keywords examples from c in Comment, join: p in Post, on: c.post_id == p.id, select: {p.title, c.text} from p in Post, left_join: c in assoc(p, :comments), select: {p, c} ## Expressions examples Comment |> join(:inner, [c], p in Post, c.post_id == p.id) |> select([c, p], {p.title, c.text}) Post |> join(:left, [p], c in assoc(p, :comments)) |> select([p, c], {p, c}) ## Joining with fragments When you need to join on a complex expression that cannot be expressed via Ecto associations, Ecto supports fragments in joins: Comment |> join(:inner, [c], p in fragment("SOME COMPLEX QUERY", c.id, ^some_param)) This style discouraged due to its complexity. """ defmacro join(query, qual, binding \\ [], expr, on \\ nil) do Join.build(query, qual, binding, expr, on, nil, __CALLER__) |> elem(0) end @doc """ A select query expression. Selects which fields will be selected from the schema and any transformations that should be performed on the fields. Any expression that is accepted in a query can be a select field. The sub-expressions in the query can be wrapped in lists, tuples or maps as shown in the examples. A full schema can also be selected. There can only be one select expression in a query, if the select expression is omitted, the query will by default select the full schema. ## Keywords examples from(c in City, select: c) # selects the entire schema from(c in City, select: {c.name, c.population}) from(c in City, select: [c.name, c.county]) from(c in City, select: {c.name, ^to_string(40 + 2), 43}) from(c in City, select: %{n: c.name, answer: 42}) ## Expressions examples City |> select([c], c) City |> select([c], {c.name, c.country}) City |> select([c], %{"name" => c.name}) """ defmacro select(query, binding \\ [], expr) do Select.build(query, binding, expr, __CALLER__) end @doc """ A distinct query expression. When true, only keeps distinct values from the resulting select expression. If supported by your database, you can also pass query expressions to distinct and it will generate a query with DISTINCT ON. In such cases, the row that is being kept depends on the ordering of the rows. When an `order_by` expression is also added to the query, all fields in the `distinct` expression are automatically referenced `order_by` too. `distinct` also accepts a list of atoms where each atom refers to a field in source. ## Keywords examples # Returns the list of different categories in the Post schema from(p in Post, distinct: true, select: p.category) # If your database supports DISTINCT ON(), # you can pass expressions to distinct too from(p in Post, distinct: p.category, order_by: [p.date]) # Using atoms from(p in Post, distinct: :category, order_by: :date) ## Expressions example Post |> distinct(true) |> order_by([p], [p.category, p.author]) """ defmacro distinct(query, binding \\ [], expr) do Distinct.build(query, binding, expr, __CALLER__) end @doc """ A where query expression. `where` expressions are used to filter the result set. If there is more than one where expression, they are combined with an `and` operator. All where expressions have to evaluate to a boolean value. `where` also accepts a keyword list where the field given as key is going to be compared with the given value. The fields will always refer to the source given in `from`. ## Keywords example from(c in City, where: c.state == "Sweden") from(c in City, where: [state: "Sweden"]) It is also possible to interpolate the whole keyword list, allowing you to dynamically filter the source: filters = [state: "Sweden"] from(c in City, where: ^filters) ## Expressions example City |> where([c], c.state == "Sweden") City |> where(state: "Sweden") """ defmacro where(query, binding \\ [], expr) do Filter.build(:where, query, binding, expr, __CALLER__) end @doc """ An order by query expression. Orders the fields based on one or more fields. It accepts a single field or a list of fields. The direction can be specified in a keyword list as shown in the examples. There can be several order by expressions in a query. `order_by` also accepts a list of atoms where each atom refers to a field in source or a keyword list where the direction is given as key and the field to order as value. ## Keywords examples from(c in City, order_by: c.name, order_by: c.population) from(c in City, order_by: [c.name, c.population]) from(c in City, order_by: [asc: c.name, desc: c.population]) from(c in City, order_by: [:name, :population]) from(c in City, order_by: [asc: :name, desc: :population]) A keyword list can also be interpolated: values = [asc: :name, desc: :population] from(c in City, order_by: ^values) ## Expressions example City |> order_by([c], asc: c.name, desc: c.population) City |> order_by(asc: :name) # Sorts by the cities name """ defmacro order_by(query, binding \\ [], expr) do OrderBy.build(query, binding, expr, __CALLER__) end @doc """ A limit query expression. Limits the number of rows returned from the result. Can be any expression but has to evaluate to an integer value and it can't include any field. If `limit` is given twice, it overrides the previous value. ## Keywords example from(u in User, where: u.id == ^current_user, limit: 1) ## Expressions example User |> where([u], u.id == ^current_user) |> limit(1) """ defmacro limit(query, binding \\ [], expr) do LimitOffset.build(:limit, query, binding, expr, __CALLER__) end @doc """ An offset query expression. Offsets the number of rows selected from the result. Can be any expression but it must evaluate to an integer value and it can't include any field. If `offset` is given twice, it overrides the previous value. ## Keywords example # Get all posts on page 4 from(p in Post, limit: 10, offset: 30) ## Expressions example Post |> limit(10) |> offset(30) """ defmacro offset(query, binding \\ [], expr) do LimitOffset.build(:offset, query, binding, expr, __CALLER__) end @doc ~S""" A lock query expression. Provides support for row-level pessimistic locking using `SELECT ... FOR UPDATE` or other, database-specific, locking clauses. `expr` can be any expression but has to evaluate to a boolean value or to a string and it can't include any fields. If `lock` is used more than once, the last one used takes precedence. Ecto also supports [optimistic locking](http://en.wikipedia.org/wiki/Optimistic_concurrency_control) but not through queries. For more information on optimistic locking, have a look at the `Ecto.Changeset.optimistic_lock/3` function ## Keywords example from(u in User, where: u.id == ^current_user, lock: "FOR SHARE NOWAIT") ## Expressions example User |> where(u.id == ^current_user) |> lock("FOR SHARE NOWAIT") """ defmacro lock(query, expr) do Lock.build(query, expr, __CALLER__) end @doc ~S""" An update query expression. Updates are used to update the filtered entries. In order for updates to be applied, `Ecto.Repo.update_all/3` must be invoked. ## Keywords example from(u in User, update: [set: [name: "new name"]]) ## Expressions example User |> update([u], set: [name: "new name"]) User |> update(set: [name: "new name"]) ## Operators The update expression in Ecto supports the following operators: * `set` - sets the given field in the table to the given value from(u in User, update: [set: [name: "new name"]]) * `inc` - increments (or decrements if the value is negative) the given field in the table by the given value from(u in User, update: [inc: [accesses: 1]]) * `push` - pushes (appends) the given value to the end of the array field from(u in User, update: [push: [tags: "cool"]]) * `pull` - pulls (removes) the given value from the array field from(u in User, update: [pull: [tags: "not cool"]]) """ defmacro update(query, binding \\ [], expr) do Update.build(query, binding, expr, __CALLER__) end @doc """ A group by query expression. Groups together rows from the schema that have the same values in the given fields. Using `group_by` "groups" the query giving it different semantics in the `select` expression. If a query is grouped, only fields that were referenced in the `group_by` can be used in the `select` or if the field is given as an argument to an aggregate function. `group_by` also accepts a list of atoms where each atom refers to a field in source. ## Keywords examples # Returns the number of posts in each category from(p in Post, group_by: p.category, select: {p.category, count(p.id)}) # Group on all fields on the Post schema from(p in Post, group_by: p, select: p) # Using atoms from(p in Post, group_by: :category, select: {p.category, count(p.id)}) ## Expressions example Post |> group_by([p], p.category) |> select([p], count(p.id)) """ defmacro group_by(query, binding \\ [], expr) do GroupBy.build(query, binding, expr, __CALLER__) end @doc """ A having query expression. Like `where`, `having` filters rows from the schema, but after the grouping is performed giving it the same semantics as `select` for a grouped query (see `group_by/3`). `having` groups the query even if the query has no `group_by` expression. ## Keywords example # Returns the number of posts in each category where the # average number of comments is above ten from(p in Post, group_by: p.category, having: avg(p.num_comments) > 10, select: {p.category, count(p.id)}) ## Expressions example Post |> group_by([p], p.category) |> having([p], avg(p.num_comments) > 10) |> select([p], count(p.id)) """ defmacro having(query, binding \\ [], expr) do Filter.build(:having, query, binding, expr, __CALLER__) end @doc """ Preloads the associations into the given struct. Preloading allows developers to specify associations that are preloaded into the struct. Consider this example: Repo.all from p in Post, preload: [:comments] The example above will fetch all posts from the database and then do a separate query returning all comments associated to the given posts. However, often times, you want posts and comments to be selected and filtered in the same query. For such cases, you can explicitly tell the association to be preloaded into the struct: Repo.all from p in Post, join: c in assoc(p, :comments), where: c.published_at > p.updated_at, preload: [comments: c] In the example above, instead of issuing a separate query to fetch comments, Ecto will fetch posts and comments in a single query. Nested associations can also be preloaded in both formats: Repo.all from p in Post, preload: [comments: :likes] Repo.all from p in Post, join: c in assoc(p, :comments), join: l in assoc(c, :likes), where: l.inserted_at > c.updated_at, preload: [comments: {c, likes: l}] Keep in mind neither format can be nested arbitrarily. For example, the query below is invalid because we cannot preload likes with the join association `c`. Repo.all from p in Post, join: c in assoc(p, :comments), preload: [comments: {c, :likes}] ## Preload queries Preload also allows queries to be given, allowing you to filter or customize how the preloads are fetched: comments_query = from c in Comment, order_by: c.published_at Repo.all from p in Post, preload: [comments: ^comments_query] The example above will issue two queries, one for loading posts and then another for loading the comments associated with the posts. Comments will be ordered by `published_at`. Note: keep in mind operations like limit and offset in the preload query will affect the whole result set and not each association. For example, the query below: comments_query = from c in Comment, order_by: c.popularity, limit: 5 Repo.all from p in Post, preload: [comments: ^comments_query] won't bring the top of comments per post. Rather, it will only bring the 5 top comments across all posts. ## Keywords example # Returns all posts and their associated comments from(p in Post, preload: [:comments, comments: :likes], select: p) ## Expressions examples Post |> preload(:comments) |> select([p], p) Post |> preload([p, c], [:user, comments: c]) |> select([p], p) """ defmacro preload(query, bindings \\ [], expr) do Preload.build(query, bindings, expr, __CALLER__) end end
31.875312
113
0.662377
9edc7de7979b778ac2f3b5d0e2e891e406f815f3
1,643
ex
Elixir
lib/koans/08_maps.ex
wilandrade/elixir-koans
4d7f90299edb0bb0b1895c437a16fbdd320ec572
[ "MIT" ]
1
2018-08-09T17:29:02.000Z
2018-08-09T17:29:02.000Z
lib/koans/08_maps.ex
wilandrade/elixir-koans
4d7f90299edb0bb0b1895c437a16fbdd320ec572
[ "MIT" ]
null
null
null
lib/koans/08_maps.ex
wilandrade/elixir-koans
4d7f90299edb0bb0b1895c437a16fbdd320ec572
[ "MIT" ]
1
2019-03-24T23:56:21.000Z
2019-03-24T23:56:21.000Z
defmodule Maps do use Koans @intro "Maps" @person %{ first_name: "Jon", last_name: "Snow", age: 27 } koan "Maps represent structured data, like a person" do assert @person == %{first_name: "Jon", last_name: "Snow", age: 27} end koan "Fetching a value returns a tuple with ok when it exists" do assert Map.fetch(@person, :age) == {:ok, 27} end koan "Or the atom :error when it doesn't" do assert Map.fetch(@person, :family) == :error end koan "Extending a map is as simple as adding a new pair" do person_with_hobby = Map.put(@person, :hobby, "Kayaking") assert Map.fetch(person_with_hobby, :hobby) == {:ok, "Kayaking"} end koan "Put can also overwrite existing values" do older_person = Map.put(@person, :age, 37) assert Map.fetch(older_person, :age) == {:ok, 37} end koan "Or you can use some syntactic sugar for existing elements" do younger_person = %{@person | age: 16} assert Map.fetch(younger_person, :age) == {:ok, 16} end koan "Can remove pairs by key" do without_age = Map.delete(@person, :age) assert Map.has_key?(without_age, :age) == false end koan "Can merge maps" do assert Map.merge(%{first_name: "Jon"}, %{last_name: "Snow"}) == %{first_name: "Jon", last_name: "Snow"} end koan "When merging, the last map wins" do merged = Map.merge(@person, %{last_name: "Baratheon"}) assert Map.fetch(merged, :last_name) == {:ok, "Baratheon"} end koan "You can also select sub-maps out of a larger map" do assert Map.take(@person, [:first_name, :last_name]) == %{first_name: "Jon", last_name: "Snow"} end end
28.824561
107
0.65003
9edc8175098200de2b95c530a24f3c7b9bff7288
73
ex
Elixir
lib/instant_poll_web/views/cms/poll_view.ex
workgena/instant_poll
94be29da99cfcb54576ae0ce34d395fff7b8ca39
[ "MIT" ]
1
2018-11-30T09:08:09.000Z
2018-11-30T09:08:09.000Z
lib/instant_poll_web/views/cms/poll_view.ex
workgena/instant_poll
94be29da99cfcb54576ae0ce34d395fff7b8ca39
[ "MIT" ]
5
2021-01-28T19:08:56.000Z
2021-05-07T22:43:54.000Z
lib/instant_poll_web/views/cms/poll_view.ex
workgena/instant_poll
94be29da99cfcb54576ae0ce34d395fff7b8ca39
[ "MIT" ]
null
null
null
defmodule InstantPollWeb.CMS.PollView do use InstantPollWeb, :view end
18.25
40
0.821918
9edcc56fd8866156c297eb175e4b576b161c26dd
1,533
exs
Elixir
test/phoenix_client/message_test.exs
yangukmo/phoenix_client
c0851fa47116d306eb39518ebeabf913b30493be
[ "Apache-2.0" ]
126
2019-01-30T12:55:17.000Z
2022-03-23T13:06:38.000Z
test/phoenix_client/message_test.exs
yangukmo/phoenix_client
c0851fa47116d306eb39518ebeabf913b30493be
[ "Apache-2.0" ]
16
2019-03-08T14:56:48.000Z
2022-02-05T20:24:59.000Z
test/phoenix_client/message_test.exs
yangukmo/phoenix_client
c0851fa47116d306eb39518ebeabf913b30493be
[ "Apache-2.0" ]
28
2015-07-27T18:01:53.000Z
2018-11-17T20:19:43.000Z
defmodule PhoenixClient.MessageTest do use ExUnit.Case, async: false alias PhoenixClient.Message describe "v1 serializer" do test "encode" do msg = %{ ref: "1", topic: "1234", event: "new:thing", payload: %{"a" => "b"} } v1_msg = Message.V1.encode!(struct(Message, msg)) assert msg == v1_msg end test "decode" do msg = %{ "ref" => "1", "topic" => "1234", "event" => "new:thing", "payload" => %{"a" => "b"} } v1_msg = Message.V1.decode!(msg) assert to_struct(Message, msg) == v1_msg end end describe "v2 serializer" do test "encode" do msg = %{ join_ref: "1", ref: "1", topic: "1234", event: "new:thing", payload: %{"a" => "b"} } v2_msg = Message.V2.encode!(struct(Message, msg)) assert ["1", "1", "1234", "new:thing", %{"a" => "b"}] == v2_msg end test "decode" do msg = %{ join_ref: "1", ref: "1", topic: "1234", event: "new:thing", payload: %{"a" => "b"} } v2_msg = Message.V2.decode!(["1", "1", "1234", "new:thing", %{"a" => "b"}]) assert struct(Message, msg) == v2_msg end end def to_struct(kind, attrs) do struct = struct(kind) Enum.reduce(Map.to_list(struct), struct, fn {k, _}, acc -> case Map.fetch(attrs, Atom.to_string(k)) do {:ok, v} -> %{acc | k => v} :error -> acc end end) end end
21.591549
81
0.482061
9edccd7f21ead5d14c03d211c2958f38565919d3
2,206
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/list_filtered_bid_requests_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/list_filtered_bid_requests_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/list_filtered_bid_requests_response.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.AdExchangeBuyer.V2beta1.Model.ListFilteredBidRequestsResponse do @moduledoc """ Response message for listing all reasons that bid requests were filtered and not sent to the buyer. ## Attributes * `calloutStatusRows` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow.t)`, *default:* `nil`) - List of rows, with counts of filtered bid requests aggregated by callout status. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A token to retrieve the next page of results. Pass this value in the ListFilteredBidRequestsRequest.pageToken field in the subsequent call to the filteredBidRequests.list method to retrieve the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :calloutStatusRows => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow.t()), :nextPageToken => String.t() } field(:calloutStatusRows, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.CalloutStatusRow, type: :list ) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ListFilteredBidRequestsResponse do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.ListFilteredBidRequestsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ListFilteredBidRequestsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.701754
278
0.758386
9edcce44b5eebb39238e9aaaeee428bd97d3b5c4
940
exs
Elixir
mix.exs
KalvinHom/uinta
c02ea83b92305d4b009853232292c94bd26bba25
[ "MIT" ]
4
2020-09-03T17:34:47.000Z
2022-03-13T21:49:28.000Z
mix.exs
KalvinHom/uinta
c02ea83b92305d4b009853232292c94bd26bba25
[ "MIT" ]
2
2021-11-22T17:39:48.000Z
2022-03-08T22:16:15.000Z
mix.exs
KalvinHom/uinta
c02ea83b92305d4b009853232292c94bd26bba25
[ "MIT" ]
4
2020-11-04T22:08:24.000Z
2022-01-11T19:54:49.000Z
defmodule Uinta.MixProject do use Mix.Project @project_url "https://github.com/podium/uinta" def project do [ app: :uinta, name: "Uinta", description: "Simpler structured logs and lower log volume for Elixir apps", version: "0.9.0", elixir: "~> 1.8", source_url: @project_url, homepage_url: @project_url, start_permanent: Mix.env() == :prod, deps: deps(), docs: docs(), package: package() ] end def application do [ extra_applications: [:logger] ] end defp deps do [ {:ex_doc, "~> 0.21", only: :dev, runtime: false}, {:jason, "~> 1.1"}, {:plug, ">= 0.0.0", optional: true} ] end defp docs do [ main: "Uinta", api_reference: false ] end defp package do [ maintainers: ["Dennis Beatty"], licenses: ["MIT"], links: %{"GitHub" => @project_url} ] end end
18.431373
82
0.543617
9edcf8fb5974f4a18a7537d05fc3aad0aa43bb2e
2,137
exs
Elixir
mix.exs
simonprev/phoenix_live_view
55a54726650e53ac68c30fc9b49d2a5895ce2053
[ "MIT" ]
null
null
null
mix.exs
simonprev/phoenix_live_view
55a54726650e53ac68c30fc9b49d2a5895ce2053
[ "MIT" ]
null
null
null
mix.exs
simonprev/phoenix_live_view
55a54726650e53ac68c30fc9b49d2a5895ce2053
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.MixProject do use Mix.Project @version "0.4.1" def project do [ app: :phoenix_live_view, version: @version, elixir: "~> 1.7", start_permanent: Mix.env() == :prod, elixirc_paths: elixirc_paths(Mix.env()), package: package(), xref: [exclude: [Floki]], deps: deps(), docs: docs(), homepage_url: "http://www.phoenixframework.org", description: """ Rich, real-time user experiences with server-rendered HTML """ ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help compile.app" to learn about applications. def application do [ mod: {Phoenix.LiveView.Application, []}, extra_applications: [:logger] ] end defp deps do [ {:phoenix, "~> 1.4.9"}, {:phoenix_html, "~> 2.13.2"}, {:jason, "~> 1.0", optional: true}, {:ex_doc, "~> 0.20", only: :docs}, {:floki, "~> 0.23.0", only: :test} ] end defp docs do [ main: "Phoenix.LiveView", source_ref: "v#{@version}", source_url: "https://github.com/phoenixframework/phoenix_live_view", extra_section: "GUIDES", extras: extras(), groups_for_extras: groups_for_extras(), groups_for_modules: groups_for_modules() ] end defp extras do [ "guides/introduction/installation.md" ] end defp groups_for_extras do [ Introduction: ~r/guides\/introduction\/.?/ ] end defp groups_for_modules do [ "Live EEx Engine": [ Phoenix.LiveView.Engine, Phoenix.LiveView.Component, Phoenix.LiveView.Rendered, Phoenix.LiveView.Comprehension ] ] end defp package do [ maintainers: ["Chris McCord", "José Valim", "Gary Rennie", "Alex Garibay", "Scott Newcomer"], licenses: ["MIT"], links: %{github: "https://github.com/phoenixframework/phoenix_live_view"}, files: ~w(assets/css assets/js lib priv) ++ ~w(CHANGELOG.md LICENSE.md mix.exs package.json README.md) ] end end
23.483516
99
0.590547
9edd3ab473693bf35f3c02421d63c9cd405a551a
447
ex
Elixir
lib/wechat/tags/members.ex
onionch/wechat_elixir
949ac241dbe40036e88b0438f85395bda87f3784
[ "MIT" ]
null
null
null
lib/wechat/tags/members.ex
onionch/wechat_elixir
949ac241dbe40036e88b0438f85395bda87f3784
[ "MIT" ]
null
null
null
lib/wechat/tags/members.ex
onionch/wechat_elixir
949ac241dbe40036e88b0438f85395bda87f3784
[ "MIT" ]
null
null
null
defmodule Wechat.Tags.Members do @moduledoc false alias Wechat.API def get_blacklist(openid \\ "") do API.post "/tags/members/getblacklist", %{ begin_openid: openid } end def batch_blacklist(openids) do API.post "/tags/members/batchblacklist", %{ openid_list: openids } end def batch_unblacklist(openids) do API.post "/tags/members/batchunblacklist", %{ openid_list: openids } end end
18.625
49
0.666667
9edd4d6382cb3070916abbb1b614df344f06b55e
2,348
ex
Elixir
clients/content/lib/google_api/content/v2/model/unit_invoice.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/unit_invoice.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/unit_invoice.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.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.Content.V2.Model.UnitInvoice do @moduledoc """ ## Attributes - additionalCharges ([UnitInvoiceAdditionalCharge]): Additional charges for a unit, e.g. shipping costs. Defaults to: `null`. - promotions ([Promotion]): Promotions applied to a unit. Defaults to: `null`. - unitPricePretax (Price): Price of the unit, before applying taxes. Defaults to: `null`. - unitPriceTaxes ([UnitInvoiceTaxLine]): Tax amounts to apply to the unit price. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :additionalCharges => list(GoogleApi.Content.V2.Model.UnitInvoiceAdditionalCharge.t()), :promotions => list(GoogleApi.Content.V2.Model.Promotion.t()), :unitPricePretax => GoogleApi.Content.V2.Model.Price.t(), :unitPriceTaxes => list(GoogleApi.Content.V2.Model.UnitInvoiceTaxLine.t()) } field( :additionalCharges, as: GoogleApi.Content.V2.Model.UnitInvoiceAdditionalCharge, type: :list ) field(:promotions, as: GoogleApi.Content.V2.Model.Promotion, type: :list) field(:unitPricePretax, as: GoogleApi.Content.V2.Model.Price) field(:unitPriceTaxes, as: GoogleApi.Content.V2.Model.UnitInvoiceTaxLine, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.UnitInvoice do def decode(value, options) do GoogleApi.Content.V2.Model.UnitInvoice.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.UnitInvoice do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.870968
127
0.738501
9edd84504fae0f68bf5f01dc655933455981d42f
141,055
ex
Elixir
lib/elixir/lib/kernel.ex
steven-solomon/elixir
ee83248b8dd78ad67ef1282efc791006e8712d9e
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel.ex
steven-solomon/elixir
ee83248b8dd78ad67ef1282efc791006e8712d9e
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel.ex
steven-solomon/elixir
ee83248b8dd78ad67ef1282efc791006e8712d9e
[ "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, etc. * macros for control-flow and defining new functionality (modules, functions, and so on) * guard checks for augmenting pattern matching You can use `Kernel` functions/macros without the `Kernel` prefix anywhere in Elixir code as all its functions and macros are automatically imported. For example, in IEx: 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 `defprotocol/2` 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.html) - lists compatibility between every Elixir version and Erlang/OTP, release schema; lists all deprecated functions, when they were deprecated and alternatives * [Guards](guards.html) - an introduction to guards and extensions * [Library Guidelines](library-guidelines.html) - general guidelines, anti-patterns, and rules for those writing libraries * [Naming Conventions](naming-conventions.html) - naming conventions for Elixir code * [Operators](operators.html) - lists all Elixir operators and their precedence * [Syntax Reference](syntax-reference.html) - the language syntax reference * [Typespecs](typespecs.html)- types and function specifications, including list of types * [Unicode Syntax](unicode-syntax.html) - outlines Elixir support for Unicode * [Writing Documentation](writing-documentation.html) - 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. A more complete introduction to guards is available [in the Guards page](guards.html). ## 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 also 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, etc. 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 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(float) :: integer @spec round(value) :: value when value: 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(value) :: value when value: integer @spec trunc(float) :: 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. 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. 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 unary plus. Allowed in guard tests. Inlined by the compiler. ## Examples iex> +1 1 """ @doc guard: true @spec +value :: value when value: number def +value do :erlang.+(value) end @doc """ Arithmetic unary minus. 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. 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. 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 """ 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, e.g. `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 """ Removes the first occurrence of an element on the left list for each element on the right. The complexity of `a -- b` is proportional to `length(a) * length(b)`, meaning that it will be very slow if both `a` and `b` are long lists. In such cases, consider converting each list to a `MapSet` and using `MapSet.difference/2`. Inlined by the compiler. ## Examples iex> [1, 2, 3] -- [1, 2] [3] iex> [1, 2, 3, 2, 1] -- [1, 2, 2] [3, 1] """ @spec list -- list :: list def left -- right do :erlang.--(left, right) end @doc """ Boolean not. `arg` 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 """ 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 """ 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 """ 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 """ 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 """ 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 """ 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 """ 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 """ Returns `true` if the two terms are not 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 """ Boolean or. 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 """ @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 """ Boolean and. 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!" """ @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. Receives any argument (not just booleans) and returns `true` if the argument 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 """ 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 be always a literal " <> "binary as 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. Notice 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 """ Matches the term on the `left` against the regular expression or string on the `right`. Returns `true` if `left` matches `right` (if it's a regular expression) or contains `right` (if it's a string). ## Examples iex> "abcd" =~ ~r/c(d)/ true iex> "abcd" =~ ~r/e/ false iex> "abcd" =~ "bc" true iex> "abcd" =~ "ad" false 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 structs. 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. 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 """ 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 entries in the middle returns `nil`, `nil` will be returned as per the `Access` module: 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. The downside is that functions cannot be stored as keys in the accessed data structures. 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`. ## 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, 2) false 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 quote do case unquote(expr) do unquote(pattern) -> true _ -> false end end end @doc """ Reads and writes attributes of 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, notice 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 or @attribute() defp do_at(args, _meta, name, function?, env) when is_atom(args) or 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 """ 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 """ Provides a short-circuit operator that evaluates and returns the second expression only if the first one evaluates to 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 """ 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 """ 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_module? = __CALLER__.context == nil expand = case bootstrapped?(Macro) do true -> &Macro.expand(&1, __CALLER__) false -> & &1 end case expand.(right) do [] when not in_module? -> false [] -> quote do _ = unquote(left) false end [head | tail] = list when not in_module? -> in_var(in_module?, left, &in_list(&1, head, tail, expand, list, in_module?)) [_ | _] = list when in_module? -> case ensure_evaled(list, {0, []}, expand) do {[head | tail], {_, []}} -> in_var(in_module?, left, &in_list(&1, head, tail, expand, list, in_module?)) {[head | tail], {_, vars_values}} -> {vars, values} = :lists.unzip(:lists.reverse(vars_values)) is_in_list = &in_list(&1, head, tail, expand, list, in_module?) quote do {unquote_splicing(vars)} = {unquote_splicing(values)} unquote(in_var(in_module?, left, is_in_list)) end end {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last]} -> in_var(in_module?, left, &in_range(&1, expand.(first), expand.(last))) right when in_module? -> 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_module?) do [head | tail] = :lists.foldl( &[comp(left, &1, expand, right, in_module?) | &2], [], [head | tail] ) :lists.foldl(&quote(do: :erlang.orelse(unquote(&1), unquote(&2))), head, tail) end defp comp(left, {:|, _, [head, tail]}, expand, right, in_module?) 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_module?)) ) end tail when in_module? -> 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_module?) 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 """ When used inside quoting, marks that the given variable should not be hygienized. The argument can be either a variable unquoted or in standard tuple form `{name, meta, context}`. Check `Kernel.SpecialForms.quote/2` for more information. """ 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 iex> defmodule Foo do ...> def bar, do: :baz ...> end iex> Foo.bar() :baz ## 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 # We reimplement Macro.Env.vars/1 due to bootstrap concerns. module_vars = module_vars(:maps.keys(elem(env.current_vars, 0)), 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 # quote vars to be injected into the module definition defp module_vars([{key, kind} | vars], counter) do var = case is_atom(kind) do true -> {key, [generated: true], kind} false -> {key, [counter: kind, generated: true], nil} end under = String.to_atom(<<"_@", :erlang.integer_to_binary(counter)::binary>>) args = [key, kind, under, var] [{:{}, [], args} | module_vars(vars, counter + 1)] end defp module_vars([], _counter) do [] end @doc ~S""" Defines a 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. For example, the following two functions are equivalent: def format(value) do try do format!(value) catch :exit, reason -> {:error, reason} end end def format(value) do format!(value) catch :exit, reason -> {:error, reason} 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 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) #=> 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 is_binary(msg) do exception(message: msg) end end # TODO: Change the implementation on v2.0 to simply call Kernel.struct!/2 @impl true def exception(args) when 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 " <> "#{inspect(__MODULE__)}: #{inspect(invalid)}. " <> "Please make sure to only give known fields when raising " <> "or redefine #{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, in order 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, `ExUnit.Case.__using__/1` is called with the keyword list `[async: true]` as its argument; `use/2` translates to: defmodule AssertionTest do require ExUnit.Case ExUnit.Case.__using__(async: true) test "always pass" do assert true end end `ExUnit.Case` will then define 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) 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 simply returns a string without escaping characters and without interpolations. ## Examples iex> ~S(foo) "foo" iex> ~S(f#{o}o) "f\#{o}o" """ 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 simply returns a charlist without escaping characters and without interpolations. ## 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 escaping nor interpreting interpolations. 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. 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 Macro.escape(Date.from_iso8601!(string)) end @doc ~S""" Handles the sigil `~T` for times. 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 Macro.escape(Time.from_iso8601!(string)) end @doc ~S""" Handles the sigil `~N` for naive date times. 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 Macro.escape(NaiveDateTime.from_iso8601!(string)) end @doc ~S""" Handles the sigil `~U` to create a UTC `DateTime`. The lower case `~u` variant does not exist as interpolation and escape characters are not useful for date time sigils. The given `datetime_string` must include "Z" or "00:00" offset which marks it as UTC, otherwise an error is raised. 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 Macro.escape(datetime_from_utc_iso8601!(string)) end defp datetime_from_utc_iso8601!(string) do case DateTime.from_iso8601(string) do {:ok, utc_datetime, 0} -> utc_datetime {:ok, _datetime, _offset} -> raise ArgumentError, "cannot parse #{inspect(string)} as UTC datetime, reason: :non_utc_offset" {:error, reason} -> raise ArgumentError, "cannot parse #{inspect(string)} as UTC datetime, reason: #{inspect(reason)}" 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) end defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do binary = {:<<>>, meta, unescape_tokens(pieces)} split_words(binary, modifiers) end @doc ~S""" Handles the sigil `~W` for list of words. It returns a list of "words" split by whitespace without escaping nor interpreting interpolations. ## 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) end defp split_words(string, []) do split_words(string, [?s]) end defp split_words(string, [mod]) when mod == ?s or mod == ?a or mod == ?c do case is_binary(string) do true -> parts = String.split(string) 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) 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/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 # TODO: Remove on v2.0 (also hard-coded in elixir_dispatch) @deprecated "Use Kernel.to_charlist/1 instead" defmacro to_char_list(arg) do quote(do: Kernel.to_charlist(unquote(arg))) end end
26.679591
105
0.634511
9edda463048eed8ce309cc8cf3a9b94993f26d2b
660
ex
Elixir
lib/exirc/logger.ex
snkutkoski/exirc
4d5b1ea8fdd7c6abfaa088db0650da6fd0946309
[ "MIT" ]
null
null
null
lib/exirc/logger.ex
snkutkoski/exirc
4d5b1ea8fdd7c6abfaa088db0650da6fd0946309
[ "MIT" ]
null
null
null
lib/exirc/logger.ex
snkutkoski/exirc
4d5b1ea8fdd7c6abfaa088db0650da6fd0946309
[ "MIT" ]
null
null
null
defmodule ExIrc.Logger do @moduledoc """ A simple abstraction of :error_logger """ @doc """ Log an informational message report """ @spec info(binary) :: :ok def info(msg) do :error_logger.info_report String.to_charlist(msg) end @doc """ Log a warning message report """ @spec warning(binary) :: :ok def warning(msg) do :error_logger.warning_report String.to_charlist("#{IO.ANSI.yellow()}#{msg}#{IO.ANSI.reset()}") end @doc """ Log an error message report """ @spec error(binary) :: :ok def error(msg) do :error_logger.error_report String.to_charlist("#{IO.ANSI.red()}#{msg}#{IO.ANSI.reset()}") end end
22
98
0.651515
9eddc3734874283694c9152028423bcf2096b4d5
1,131
exs
Elixir
config/config.exs
jsmestad/tortoise311
146b4e5bcf967d0c07b43d0d029790f9f0a7d6a9
[ "Apache-2.0" ]
null
null
null
config/config.exs
jsmestad/tortoise311
146b4e5bcf967d0c07b43d0d029790f9f0a7d6a9
[ "Apache-2.0" ]
null
null
null
config/config.exs
jsmestad/tortoise311
146b4e5bcf967d0c07b43d0d029790f9f0a7d6a9
[ "Apache-2.0" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.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 # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :tortoise311, key: :value # # and access this configuration in your application as: # # Application.get_env(:tortoise311, :key) # # You can also configure a 3rd-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). # # import_config "#{Mix.env}.exs"
36.483871
73
0.753316
9eddc5495904767ebe27e4e98c25c3aa5b34a308
3,745
exs
Elixir
mix.exs
aptinio/ecto_sql
f13a0e8383428154a61a7a93d43dcb4b6f6a6fad
[ "Apache-2.0" ]
null
null
null
mix.exs
aptinio/ecto_sql
f13a0e8383428154a61a7a93d43dcb4b6f6a6fad
[ "Apache-2.0" ]
null
null
null
mix.exs
aptinio/ecto_sql
f13a0e8383428154a61a7a93d43dcb4b6f6a6fad
[ "Apache-2.0" ]
null
null
null
defmodule EctoSQL.MixProject do use Mix.Project @version "3.2.0-dev" @adapters ~w(pg myxql) def project do [ app: :ecto_sql, version: @version, elixir: "~> 1.6", deps: deps(), test_paths: test_paths(System.get_env("ECTO_ADAPTER")), xref: [ exclude: [ MyXQL, Ecto.Adapters.MyXQL.Connection, Postgrex, Ecto.Adapters.Postgres.Connection ] ], # Custom testing aliases: ["test.all": ["test", "test.adapters"], "test.adapters": &test_adapters/1], preferred_cli_env: ["test.all": :test, "test.adapters": :test], # Hex description: "SQL-based adapters for Ecto and database migrations", package: package(), # Docs name: "Ecto SQL", docs: docs() ] end def application do [ extra_applications: [:logger], env: [postgres_map_type: "jsonb"], mod: {Ecto.Adapters.SQL.Application, []} ] end defp deps do [ ecto_dep(), {:telemetry, "~> 0.4.0"}, # Drivers {:db_connection, "~> 2.1"}, postgrex_dep(), myxql_dep(), # Bring something in for JSON during tests {:jason, ">= 0.0.0", only: [:test, :docs]}, # Docs {:ex_doc, "~> 0.19", only: :docs}, # Benchmarks {:benchee, "~> 0.11.0", only: :bench}, {:benchee_json, "~> 0.4.0", only: :bench} ] end defp ecto_dep do if path = System.get_env("ECTO_PATH") do {:ecto, path: path} else {:ecto, "~> 3.2.0-dev", github: "elixir-ecto/ecto"} end end defp postgrex_dep do if path = System.get_env("POSTGREX_PATH") do {:postgrex, path: path} else {:postgrex, "~> 0.15.0", optional: true} end end defp myxql_dep do if path = System.get_env("MYXQL_PATH") do {:myxql, path: path} else {:myxql, "~> 0.2.0", optional: true} end end defp test_paths(adapter) when adapter in @adapters, do: ["integration_test/#{adapter}"] defp test_paths(_), do: ["test"] defp package do [ maintainers: ["Eric Meadows-Jönsson", "José Valim", "James Fish", "Michał Muskała"], licenses: ["Apache-2.0"], links: %{"GitHub" => "https://github.com/elixir-ecto/ecto_sql"}, files: ~w(.formatter.exs mix.exs README.md CHANGELOG.md lib) ++ ~w(integration_test/sql integration_test/support) ] end defp test_adapters(args) do for adapter <- @adapters, do: env_run(adapter, args) end defp env_run(adapter, args) do args = if IO.ANSI.enabled?(), do: ["--color" | args], else: ["--no-color" | args] IO.puts("==> Running tests for ECTO_ADAPTER=#{adapter} mix test") {_, res} = System.cmd("mix", ["test" | args], into: IO.binstream(:stdio, :line), env: [{"ECTO_ADAPTER", adapter}] ) if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end defp docs do [ main: "Ecto.Adapters.SQL", source_ref: "v#{@version}", canonical: "http://hexdocs.pm/ecto_sql", source_url: "https://github.com/elixir-ecto/ecto_sql", groups_for_modules: [ # Ecto.Adapters.SQL, # Ecto.Adapters.SQL.Sandbox, # Ecto.Migration, # Ecto.Migrator, "Built-in adapters": [ Ecto.Adapters.MyXQL, Ecto.Adapters.Postgres ], "Adapter specification": [ Ecto.Adapter.Migration, Ecto.Adapter.Structure, Ecto.Adapters.SQL.Connection, Ecto.Migration.Command, Ecto.Migration.Constraint, Ecto.Migration.Index, Ecto.Migration.Reference, Ecto.Migration.Table ] ] ] end end
24.16129
90
0.560748
9eddcb6c7806cf1fceec0eb9c053ae53df17887a
4,536
ex
Elixir
lib/logger/lib/logger/formatter.ex
alfert/elixir
4dfd08c79dc8b67e8a6d53add9e3ee47ba9be647
[ "Apache-2.0" ]
null
null
null
lib/logger/lib/logger/formatter.ex
alfert/elixir
4dfd08c79dc8b67e8a6d53add9e3ee47ba9be647
[ "Apache-2.0" ]
null
null
null
lib/logger/lib/logger/formatter.ex
alfert/elixir
4dfd08c79dc8b67e8a6d53add9e3ee47ba9be647
[ "Apache-2.0" ]
null
null
null
import Kernel, except: [inspect: 2] defmodule Logger.Formatter do @moduledoc ~S""" Conveniences for formatting data for logs. This module allows developers to specify a string that serves as template for log messages, for example: $time $metadata[$level] $message\n Will print error messages as: 18:43:12.439 user_id=13 [error] Hello\n The valid parameters you can use are: * `$time` - time the log message was sent * `$date` - date the log message was sent * `$message` - the log message * `$level` - the log level * `$node` - the node that prints the message * `$metadata` - user controlled data presented in `"key=val key2=val2"` format * `$levelpad` - set to a single space if level is 4 characters long, otherwise set to the empty space. Used to align the message after level. Backends typically allow developers to supply such control strings via configuration files. This module provides `compile/1`, which compiles the string into a format for fast operations at runtime and `format/5` to format the compiled pattern into an actual IO data. ## Metadata Metadata to be sent to the Logger can be read and written with the `Logger.metadata/0` and `Logger.metadata/1` functions. For example, you can set `Logger.metadata([user_id: 13])` to add user_id metadata to the current process. The user can configure the backend to chose which metadata it wants to print and it will replace the `$metadata` value. """ @type time :: {{1970..10000, 1..12, 1..31}, {0..23, 0..59, 0..59, 0..999}} @type pattern :: :date | :level | :levelpad | :message | :metadata | :node | :time @valid_patterns [:time, :date, :message, :level, :node, :metadata, :levelpad] @default_pattern "\n$time $metadata[$level] $levelpad$message\n" @doc ~S""" Compiles a format string into an array that the `format/5` can handle. Check the module doc for documentation on the valid parameters. If you pass `nil`, it defaults to: `$time $metadata [$level] $levelpad$message\n` If you would like to make your own custom formatter simply pass `{module, function}` to `compile/1` and the rest is handled. iex> Logger.Formatter.compile("$time $metadata [$level] $message\n") [:time, " ", :metadata, " [", :level, "] ", :message, "\n"] """ @spec compile(binary | nil) :: [pattern | binary] @spec compile({atom, atom}) :: {atom, atom} def compile(nil), do: compile(@default_pattern) def compile({mod, fun}) when is_atom(mod) and is_atom(fun), do: {mod, fun} def compile(str) do for part <- Regex.split(~r/(?<head>)\$[a-z]+(?<tail>)/, str, on: [:head, :tail], trim: true) do case part do "$" <> code -> compile_code(String.to_atom(code)) _ -> part end end end defp compile_code(key) when key in @valid_patterns, do: key defp compile_code(key) when is_atom(key) do raise(ArgumentError, message: "$#{key} is an invalid format pattern.") end @doc """ Takes a compiled format and injects the, level, timestamp, message and metadata listdict and returns a properly formatted string. """ @spec format({atom, atom} | [pattern | binary], Logger.level, Logger.message, time, Keyword.t) :: IO.chardata def format({mod, fun}, level, msg, ts, md) do apply(mod, fun, [level, msg, ts, md]) end def format(config, level, msg, ts, md) do for c <- config do output(c, level, msg, ts, md) end end defp output(:message, _, msg, _, _), do: msg defp output(:date, _, _, {date, _time}, _), do: Logger.Utils.format_date(date) defp output(:time, _, _, {_date, time}, _), do: Logger.Utils.format_time(time) defp output(:level, level, _, _, _), do: Atom.to_string(level) defp output(:node, _, _, _, _), do: Atom.to_string(node()) defp output(:metadata, _, _, _, []), do: "" defp output(:metadata, _, _, _, meta) do Enum.map(meta, fn {key, val} -> [to_string(key), ?=, metadata(val), ?\s] end) end defp output(:levelpad, level, _, _, _) do levelpad(level) end defp output(other, _, _, _, _), do: other defp levelpad(:debug), do: "" defp levelpad(:info), do: " " defp levelpad(:warn), do: " " defp levelpad(:error), do: "" defp metadata(pid) when is_pid(pid) do :erlang.pid_to_list(pid) end defp metadata(pid) when is_reference(pid) do '#Ref' ++ rest = :erlang.ref_to_list(pid) rest end defp metadata(other), do: to_string(other) end
34.892308
99
0.647928
9edde3b5eb32997d4635a10d195399a1e50a8681
2,129
ex
Elixir
lib/grizzly/connection.ex
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
76
2019-09-04T16:56:58.000Z
2022-03-29T06:54:36.000Z
lib/grizzly/connection.ex
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
124
2019-09-05T14:01:24.000Z
2022-02-28T22:58:14.000Z
lib/grizzly/connection.ex
smartrent/grizzly
65a397ea7bfedb5518fe63a3f058a0b6af473e39
[ "Apache-2.0" ]
10
2019-10-23T19:25:45.000Z
2021-11-17T13:21:20.000Z
defmodule Grizzly.Connection do @moduledoc false require Logger alias Grizzly.Connections.Supervisor alias Grizzly.Connections.{BinaryConnection, SyncConnection, AsyncConnection} alias Grizzly.ZWave alias Grizzly.ZWave.Command @type opt() :: {:mode, :sync | :async | :binary} | {:owner, pid()} @doc """ Open a connection to a node or the Z/IP Gateway If the DTLS connection cannot be opened after some time this will return `{:error, :timeout}` """ @spec open(ZWave.node_id() | :gateway, [opt()]) :: {:ok, pid()} | {:error, :timeout} def open(node_id, opts \\ []) do Supervisor.start_connection(node_id, opts) end @doc """ Close a connection to a Z-Wave node """ @spec close(ZWave.node_id()) :: :ok def close(node_id) do # only close sync connections because async connections # are only used during inclusion and are short lived. Also, # in Grizzly.send_command/4 we wont allow sending anything during # an inclusion so anything that would want a connection closed would # not hit this point unless there a bug. So, lets assume that # this is only valid for sync connections. If this assumption is false # we should get really active errors that a user can share in a bug # report to help us identify how the assumption is false and we can # explore fixing that. SyncConnection.close(node_id) end @doc """ Send a `Grizzly.ZWave.Command` to a Z-Wave device """ @spec send_command(ZWave.node_id(), Command.t(), [Grizzly.command_opt()]) :: Grizzly.send_command_response() def send_command(node_id, command, opts \\ []) do _ = Logger.debug("Sending Cmd: #{inspect(command)}") case Keyword.get(opts, :type, :sync) do :sync -> SyncConnection.send_command(node_id, command, opts) :async -> AsyncConnection.send_command(node_id, command, opts) end end def send_binary(node_id, binary, opts \\ []) do base = Keyword.get(opts, :format, :hex) _ = Logger.debug("Sending binary: #{inspect(binary, base: base)}") BinaryConnection.send_binary(node_id, binary) end end
32.753846
86
0.683419
9ede07bbdcae867db685e4a04fcb228729da3652
353
ex
Elixir
lib/insta_api/photo_comments.ex
kevinmartiniano/elixir-insta-api
5025e02f111a4952279839d92f64f960ca08026a
[ "Apache-2.0" ]
2
2021-01-07T23:46:50.000Z
2021-01-08T12:16:00.000Z
lib/insta_api/photo_comments.ex
kevinmartiniano/elixir-insta-api
5025e02f111a4952279839d92f64f960ca08026a
[ "Apache-2.0" ]
null
null
null
lib/insta_api/photo_comments.ex
kevinmartiniano/elixir-insta-api
5025e02f111a4952279839d92f64f960ca08026a
[ "Apache-2.0" ]
null
null
null
defmodule InstaApi.PhotoComments do use Ecto.Schema import Ecto.Changeset schema "photo_comments" do field :text, :string field :user_id, :integer timestamps() end @doc false def changeset(photo_comments, attrs) do photo_comments |> cast(attrs, [:text, :user_id]) |> validate_required([:text, :user_id]) end end
18.578947
43
0.685552
9ede174e8512b1e6a1db8daac64f42e469d03a2c
73
exs
Elixir
test/views/layout_view_test.exs
embik/blog
ee8e604fe0bba0bade5466cc180475dbe80bb6b6
[ "Apache-2.0" ]
null
null
null
test/views/layout_view_test.exs
embik/blog
ee8e604fe0bba0bade5466cc180475dbe80bb6b6
[ "Apache-2.0" ]
1
2017-08-14T09:00:30.000Z
2017-08-14T16:18:44.000Z
test/views/layout_view_test.exs
embik/blog
ee8e604fe0bba0bade5466cc180475dbe80bb6b6
[ "Apache-2.0" ]
null
null
null
defmodule Blog.LayoutViewTest do use BlogWeb.ConnCase, async: true end
18.25
35
0.808219
9ede29bb7b50b25b7e5524a5f539b4ad768d88de
1,181
ex
Elixir
lib/event_store/tasks/init.ex
c-moss-talk/eventstore
f02a0d8cea78608afb9ed1368c1fd26076d652b6
[ "MIT" ]
null
null
null
lib/event_store/tasks/init.ex
c-moss-talk/eventstore
f02a0d8cea78608afb9ed1368c1fd26076d652b6
[ "MIT" ]
null
null
null
lib/event_store/tasks/init.ex
c-moss-talk/eventstore
f02a0d8cea78608afb9ed1368c1fd26076d652b6
[ "MIT" ]
null
null
null
defmodule EventStore.Tasks.Init do @moduledoc """ Task to initalize the EventStore database """ import EventStore.Tasks.Output alias EventStore.Storage.Initializer @is_events_table_exists """ SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'events' ) """ @doc """ Runs task ## Parameters - config: the parsed EventStore config ## Opts - is_mix: set to `true` if running as part of a Mix task - quiet: set to `true` to silence output """ def exec(config, opts) do opts = Keyword.merge([is_mix: false, quiet: false], opts) {:ok, conn} = Postgrex.start_link(config) case run_query!(conn, @is_events_table_exists) do %{rows: [[true]]} -> write_info("The EventStore database has already been initialized.", opts) %{rows: [[false]]} -> Initializer.run!(conn) write_info("The EventStore database has been initialized.", opts) end true = Process.unlink(conn) true = Process.exit(conn, :shutdown) :ok end defp run_query!(conn, query) do Postgrex.query!(conn, query, []) end end
21.87037
81
0.641829
9ede2da16afcaae8d0d424cef4ef0dd7c0ab8761
1,655
ex
Elixir
lib/railway_ui_web.ex
SophieDeBenedetto/railway-ui
ceb253bccf63f278e93502e4dc6b113b31f6d8b2
[ "MIT" ]
2
2019-11-12T21:04:11.000Z
2020-02-09T18:07:27.000Z
lib/railway_ui_web.ex
SophieDeBenedetto/railway-ui
ceb253bccf63f278e93502e4dc6b113b31f6d8b2
[ "MIT" ]
4
2019-12-02T17:31:57.000Z
2021-03-09T22:59:48.000Z
lib/railway_ui_web.ex
SophieDeBenedetto/railway-ui
ceb253bccf63f278e93502e4dc6b113b31f6d8b2
[ "MIT" ]
2
2020-02-05T18:23:26.000Z
2020-04-26T13:50:10.000Z
defmodule RailwayUiWeb 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 RailwayUiWeb, :controller use RailwayUiWeb, :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: RailwayUiWeb import Plug.Conn import RailwayUiWeb.Gettext alias RailwayUiWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/railway_ui_web/templates", namespace: RailwayUiWeb # 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 RailwayUiWeb.ErrorHelpers import RailwayUiWeb.Gettext alias RailwayUiWeb.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 RailwayUiWeb.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
23.642857
83
0.693656
9ede556425c8ee2d84d5c1f36d2fcbae09b52733
1,121
exs
Elixir
algorithms/1. easy/1 - time-conversion/anabastos/config/config.exs
horizonfour/challenges
126bc38aba16a3c36b3543db67a73fea90db446e
[ "MIT" ]
9
2017-07-24T17:41:52.000Z
2021-04-02T02:41:25.000Z
algorithms/1. easy/1 - time-conversion/anabastos/config/config.exs
horizonfour/challenges
126bc38aba16a3c36b3543db67a73fea90db446e
[ "MIT" ]
2
2017-07-24T18:31:21.000Z
2017-08-06T04:02:44.000Z
algorithms/1. easy/1 - time-conversion/anabastos/config/config.exs
horizonfour/challenges
126bc38aba16a3c36b3543db67a73fea90db446e
[ "MIT" ]
4
2017-07-24T18:18:07.000Z
2017-12-22T22:19:50.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.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 # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :anabastos, key: :value # # And access this configuration in your application as: # # Application.get_env(:anabastos, :key) # # Or configure a 3rd-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). # # import_config "#{Mix.env}.exs"
36.16129
73
0.752007
9edeec9a3baa1f41dcc00463f919d81ff4f4e8f6
5,037
ex
Elixir
lib/strategy/fusion.ex
fsi-tech/ueberauth_fusion
335d647c95b5ec189094308e9cb06464b9bdbfc2
[ "MIT" ]
5
2020-10-07T08:05:44.000Z
2020-11-15T08:42:26.000Z
lib/strategy/fusion.ex
fsi-libs/ueberauth_fusion
335d647c95b5ec189094308e9cb06464b9bdbfc2
[ "MIT" ]
null
null
null
lib/strategy/fusion.ex
fsi-libs/ueberauth_fusion
335d647c95b5ec189094308e9cb06464b9bdbfc2
[ "MIT" ]
2
2021-11-11T07:26:27.000Z
2021-11-11T09:32:10.000Z
defmodule Ueberauth.Strategy.Fusion do use Ueberauth.Strategy, uid_field: :sub, default_scope: "email", hd: nil alias Ueberauth.Auth.Info alias Ueberauth.Auth.Credentials alias Ueberauth.Auth.Extra alias Ueberauth.Strategy.Helpers alias Ueberauth.Strategy.Fusion.OAuth @doc """ Handles initial request for Fusion authentication. """ def handle_request!(conn) do scopes = conn.params["scope"] || option(conn, :default_scope) params = [scope: scopes] |> with_optional(:hd, conn) |> with_optional(:prompt, conn) |> with_optional(:access_type, conn) |> with_optional(:login_hint, conn) |> with_param(:access_type, conn) |> with_param(:prompt, conn) |> with_param(:login_hint, conn) |> with_param(:state, conn) opts = oauth_client_options_from_conn(conn) redirect!(conn, Ueberauth.Strategy.Fusion.OAuth.authorize_url!(params, opts)) end @doc """ Handles the callback from Fusion Auth. """ def handle_callback!(%Plug.Conn{params: %{"code" => code}} = conn) do params = [code: code] opts = oauth_client_options_from_conn(conn) case Ueberauth.Strategy.Fusion.OAuth.get_access_token(params, opts) do {:ok, token} -> fetch_user(conn, token) {:error, {error_code, error_description}} -> Helpers.set_errors!(conn, [error(error_code, error_description)]) end end @doc false def handle_callback!(conn) do Helpers.set_errors!(conn, [error("missing_code", "No code received")]) end @doc false def handle_cleanup!(conn) do conn |> put_private(:fusion_user, nil) |> put_private(:fusion_token, nil) end @doc """ Fetches the uid field from the response. """ def uid(conn) do uid_field = conn |> option(:uid_field) |> to_string conn.private.fusion_user[uid_field] end @doc """ Includes the credentials from the fusion response. """ def credentials(conn) do token = conn.private.fusion_token scope_string = (token.other_params["scope"] || "") scopes = String.split(scope_string, ",") %Credentials{ expires: !!token.expires_at, expires_at: token.expires_at, scopes: scopes, token_type: Map.get(token, :token_type), refresh_token: token.refresh_token, token: token.access_token } end @doc """ Fetches the fields to populate the info section of the `Ueberauth.Auth` struct. """ def info(conn) do user = conn.private.fusion_user %Info{ email: user["email"], first_name: user["given_name"], image: user["picture"], last_name: user["family_name"], name: user["name"], birthday: user["birthdate"], phone: user["phone_number"], nickname: user["preferred_username"], urls: %{ profile: user["profile"], website: user["hd"] } } end @doc """ Stores the raw information (including the token) obtained from the fusion callback. """ def extra(conn) do %Extra{ raw_info: %{ token: conn.private.fusion_token, user: conn.private.fusion_user } } end @doc """ redirects the user to the logout url. If case of an error, it sets the error """ def logout(conn) do with {:ok, signout_url} <- OAuth.signout_url() do redirect!(conn, signout_url) else _ -> set_errors!(conn, [error("Logout Failed", "Failed to logout, please close your browser")]) end end defp fetch_user(conn, token) do conn = put_private(conn, :fusion_token, token) path = Ueberauth.Strategy.Fusion.OAuth.get_config_value(:userinfo_url) resp = Ueberauth.Strategy.Fusion.OAuth.get(token, path) case resp do {:ok, %OAuth2.Response{status_code: 401, body: _body}} -> set_errors!(conn, [error("token", "unauthorized")]) {:ok, %OAuth2.Response{status_code: status_code, body: user}} when status_code in 200..399 -> put_private(conn, :fusion_user, user) {:error, %OAuth2.Response{status_code: status_code}} -> set_errors!(conn, [error("OAuth2", to_string(status_code))]) {:error, %OAuth2.Error{reason: reason}} -> set_errors!(conn, [error("OAuth2", reason)]) end end defp with_param(opts, key, conn) do if value = conn.params[to_string(key)], do: Keyword.put(opts, key, value), else: opts end defp with_optional(opts, key, conn) do if option(conn, key), do: Keyword.put(opts, key, option(conn, key)), else: opts end defp oauth_client_options_from_conn(conn) do base_options = [redirect_uri: callback_url(conn)] request_options = conn.private[:ueberauth_request_options].options case {request_options[:client_id], request_options[:client_secret]} do {nil, _} -> base_options {_, nil} -> base_options {id, secret} -> [client_id: id, client_secret: secret] ++ base_options end end defp option(conn, key) do Keyword.get(options(conn), key, Keyword.get(default_options(), key)) end end
28.619318
99
0.651777
9edeff572b47f28b752d63bba8caa62cea96d398
2,342
ex
Elixir
lib/parser.ex
smiyabe/cwmp_ex
9db322497aa3208b5985ccf496ada5286cde3925
[ "Artistic-2.0" ]
null
null
null
lib/parser.ex
smiyabe/cwmp_ex
9db322497aa3208b5985ccf496ada5286cde3925
[ "Artistic-2.0" ]
null
null
null
lib/parser.ex
smiyabe/cwmp_ex
9db322497aa3208b5985ccf496ada5286cde3925
[ "Artistic-2.0" ]
null
null
null
defmodule CWMP.Protocol.Parser do @moduledoc """ Parsing of CWMP XML messages, and conversion to Elixir data structures. """ alias CWMP.Protocol.Parser.ElemState alias CWMP.Protocol.Parser.State alias CWMP.Protocol.Parser.ParseError @doc """ Parses a CWMP XML envelope and converts it to an Elixir data structure. """ def parse!(source) do try do {:ok, %State{curstate: %ElemState{acc: acc}}, _} = :erlsom.parse_sax(source, initial_state(), &parse_step/2) acc catch {:error, err} when is_list(err) -> raise ParseError, message: "#{err}" {:error, err} -> raise ParseError, message: "#{inspect(err)}" end end @doc """ Same as parse!, but non-throwing. """ def parse(source) do try do {:ok, parse!(source)} rescue err -> {:error, err} end end def initial_elem_state(handler) do %ElemState{handler: handler, acc: handler.initial_acc} end defp initial_state do %State{curstate: initial_elem_state(Elixir.CWMP.Protocol.Parser.Envelope), stack: [%ElemState{}]} end defp parse_step({:characters, chars}, state) do %State{state | last_text: String.trim("#{chars}")} end defp parse_step({:startElement, uri, name, _prefix, attribs}, state) do newpath = [name | state.curstate.path] newinner = %ElemState{state.curstate | path: newpath} state = %State{state | curstate: newinner} state = state.curstate.handler.start_element(state, newpath, attribs, to_string(uri)) %State{state | last_text: ""} end defp parse_step({:endElement, _uri, _name, _prefix}, state) do state = case state.curstate.path do [] -> # Empty, so pop off the handler stack case state.stack do [newcur | rest] -> %State{state | curstate: newcur, stack: rest, last_acc: state.curstate.acc} _ -> raise "Imbalanced tags" end _ -> state end curpath = state.curstate.path state = %State{state | curstate: %ElemState{state.curstate | path: Enum.drop(curpath, 1)}} state = case state.curstate.handler do nil -> %State{state | curstate: %ElemState{state.curstate | acc: state.last_acc}} handler -> handler.end_element(state, curpath) end %State{state | last_text: ""} end defp parse_step(_, state) do state end end
29.275
114
0.649018
9edf39458930d15f9196f033e695481f9d7d42bf
1,127
ex
Elixir
lib/hnlive_web/router.ex
josefrichter/hnlive
5c9953835e447c98e65e9690655f6d602bd18d32
[ "MIT" ]
4
2020-05-31T11:53:17.000Z
2021-05-25T11:30:24.000Z
lib/hnlive_web/router.ex
josefrichter/hnlive
5c9953835e447c98e65e9690655f6d602bd18d32
[ "MIT" ]
1
2020-05-31T13:08:02.000Z
2020-05-31T13:08:02.000Z
lib/hnlive_web/router.ex
josefrichter/hnlive
5c9953835e447c98e65e9690655f6d602bd18d32
[ "MIT" ]
1
2020-05-31T11:53:43.000Z
2020-05-31T11:53:43.000Z
defmodule HNLiveWeb.Router do use HNLiveWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :put_root_layout, {HNLiveWeb.LayoutView, :root} plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", HNLiveWeb do pipe_through :browser live "/", PageLive, :index end # Other scopes may use custom stacks. # scope "/api", HNLiveWeb do # pipe_through :api # end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through :browser live_dashboard "/dashboard", metrics: HNLiveWeb.Telemetry end end end
25.613636
70
0.699201
9edf3f38f95ea02227195b311e3c0e4cc2f0eb36
630
exs
Elixir
test/authoritex/loc/languages_test.exs
nulib/authoritex
a9b277e20873a886e2578f14f58acb277a501f01
[ "MIT" ]
2
2020-06-11T10:37:21.000Z
2020-10-13T18:12:42.000Z
test/authoritex/loc/languages_test.exs
nulib/authoritex
a9b277e20873a886e2578f14f58acb277a501f01
[ "MIT" ]
21
2020-05-12T21:06:32.000Z
2022-01-14T14:43:45.000Z
test/authoritex/loc/languages_test.exs
nulib/authoritex
a9b277e20873a886e2578f14f58acb277a501f01
[ "MIT" ]
null
null
null
defmodule Authoritex.LOC.LanguagesTest do use Authoritex.TestCase, module: Authoritex.LOC.Languages, code: "lclang", description: "Library of Congress MARC List for Languages", test_uris: [ "http://id.loc.gov/vocabulary/languages/ang", "info:lc/vocabulary/languages/ang" ], bad_uri: "http://id.loc.gov/vocabulary/languages/wrong-id", expected: [ id: "http://id.loc.gov/vocabulary/languages/ang", label: "English, Old (ca. 450-1100)", qualified_label: "English, Old (ca. 450-1100)", hint: nil ], search_result_term: "english", search_count_term: "" end
31.5
63
0.657143
9edf589d1f66a42efa257c315ba361eca1b85866
5,004
ex
Elixir
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remotebuildexecution_admin_v1alpha_worker_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remotebuildexecution_admin_v1alpha_worker_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remotebuildexecution_admin_v1alpha_worker_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.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig do @moduledoc """ Defines the configuration to be used for creating workers in the worker pool. ## Attributes * `accelerator` (*type:* `GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig.t`, *default:* `nil`) - The accelerator card attached to each VM. * `diskSizeGb` (*type:* `String.t`, *default:* `nil`) - Required. Size of the disk attached to the worker, in GB. See https://cloud.google.com/compute/docs/disks/ * `diskType` (*type:* `String.t`, *default:* `nil`) - Required. Disk Type to use for the worker. See [Storage options](https://cloud.google.com/compute/docs/disks/#introduction). Currently only `pd-standard` and `pd-ssd` are supported. * `labels` (*type:* `map()`, *default:* `nil`) - Labels associated with the workers. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International letters are permitted. Label keys must start with a letter. Label values are optional. There can not be more than 64 labels per resource. * `machineType` (*type:* `String.t`, *default:* `nil`) - Required. Machine type of the worker, such as `e2-standard-2`. See https://cloud.google.com/compute/docs/machine-types for a list of supported machine types. Note that `f1-micro` and `g1-small` are not yet supported. * `maxConcurrentActions` (*type:* `String.t`, *default:* `nil`) - The maximum number of actions a worker can execute concurrently. * `minCpuPlatform` (*type:* `String.t`, *default:* `nil`) - Minimum CPU platform to use when creating the worker. See [CPU Platforms](https://cloud.google.com/compute/docs/cpu-platforms). * `networkAccess` (*type:* `String.t`, *default:* `nil`) - Determines the type of network access granted to workers. Possible values: - "public": Workers can connect to the public internet. - "private": Workers can only connect to Google APIs and services. - "restricted-private": Workers can only connect to Google APIs that are reachable through `restricted.googleapis.com` (`199.36.153.4/30`). * `reserved` (*type:* `boolean()`, *default:* `nil`) - Determines whether the worker is reserved (equivalent to a Compute Engine on-demand VM and therefore won't be preempted). See [Preemptible VMs](https://cloud.google.com/preemptible-vms/) for more details. * `soleTenantNodeType` (*type:* `String.t`, *default:* `nil`) - The node type name to be used for sole-tenant nodes. * `vmImage` (*type:* `String.t`, *default:* `nil`) - The name of the image used by each VM. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accelerator => GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig.t() | nil, :diskSizeGb => String.t() | nil, :diskType => String.t() | nil, :labels => map() | nil, :machineType => String.t() | nil, :maxConcurrentActions => String.t() | nil, :minCpuPlatform => String.t() | nil, :networkAccess => String.t() | nil, :reserved => boolean() | nil, :soleTenantNodeType => String.t() | nil, :vmImage => String.t() | nil } field(:accelerator, as: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig ) field(:diskSizeGb) field(:diskType) field(:labels, type: :map) field(:machineType) field(:maxConcurrentActions) field(:minCpuPlatform) field(:networkAccess) field(:reserved) field(:soleTenantNodeType) field(:vmImage) end defimpl Poison.Decoder, for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig do def decode(value, options) do GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
55.6
400
0.718825
9edf6ae9aa4ae536f44f9b4d233ed491a7eac0bf
2,006
ex
Elixir
clients/slides/lib/google_api/slides/v1/model/text_content.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/slides/lib/google_api/slides/v1/model/text_content.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/slides/lib/google_api/slides/v1/model/text_content.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "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.Slides.V1.Model.TextContent do @moduledoc """ The general text content. The text must reside in a compatible shape (e.g. text box or rectangle) or a table cell in a page. ## Attributes * `lists` (*type:* `%{optional(String.t) => GoogleApi.Slides.V1.Model.List.t}`, *default:* `nil`) - The bulleted lists contained in this text, keyed by list ID. * `textElements` (*type:* `list(GoogleApi.Slides.V1.Model.TextElement.t)`, *default:* `nil`) - The text contents broken down into its component parts, including styling information. This property is read-only. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :lists => %{optional(String.t()) => GoogleApi.Slides.V1.Model.List.t()}, :textElements => list(GoogleApi.Slides.V1.Model.TextElement.t()) } field(:lists, as: GoogleApi.Slides.V1.Model.List, type: :map) field(:textElements, as: GoogleApi.Slides.V1.Model.TextElement, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Slides.V1.Model.TextContent do def decode(value, options) do GoogleApi.Slides.V1.Model.TextContent.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Slides.V1.Model.TextContent do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.576923
172
0.725324
9edfa19fedc9c284889327267fcc01bd5314cc89
7,398
exs
Elixir
test/ex_twiml_test.exs
danielberkompas/ex_twiml
0a32ed535396f669d98f1e2a12ce17034cf1c2bc
[ "MIT" ]
35
2015-04-17T19:06:05.000Z
2021-05-18T23:50:52.000Z
test/ex_twiml_test.exs
tsloughter/ex_twiml
693f9ac80f14b6d5717f45354cd99cab8a79512e
[ "MIT" ]
9
2015-04-17T22:27:11.000Z
2017-08-05T16:45:39.000Z
test/ex_twiml_test.exs
tsloughter/ex_twiml
693f9ac80f14b6d5717f45354cd99cab8a79512e
[ "MIT" ]
11
2015-05-31T18:42:06.000Z
2019-06-03T17:24:42.000Z
defmodule ExTwimlTest do use ExUnit.Case, async: false import ExTwiml alias ExTwiml.ReservedNameError doctest ExTwiml test "can render the <Gather> verb" do markup = twiml do gather digits: 3 do text "Phone Number" end end assert_twiml markup, "<Gather digits=\"3\">Phone Number</Gather>" end test "can render the <Gather> verb without any options" do markup = twiml do gather do text "Phone Number" end end assert_twiml markup, "<Gather>Phone Number</Gather>" end test "can render the <Say> verb" do markup = twiml do say "Hello there!", voice: "woman" end assert_twiml markup, "<Say voice=\"woman\">Hello there!</Say>" end test "can render the <Record> verb" do markup = twiml do record finish_on_key: "#", transcribe: true end assert_twiml markup, "<Record finishOnKey=\"#\" transcribe=\"true\" />" end test "can render the <Number> verb" do markup = twiml do number "1112223333" end assert_twiml markup, "<Number>1112223333</Number>" end test "can render the <Play> verb" do markup = twiml do play "https://api.twilio.com/cowbell.mp3", loop: 10 end assert_twiml markup, "<Play loop=\"10\">https://api.twilio.com/cowbell.mp3</Play>" end test "can render the <Sms> verb" do markup = twiml do sms "Hello world!", from: "1112223333", to: "2223334444" end assert_twiml markup, "<Sms from=\"1112223333\" to=\"2223334444\">Hello world!</Sms>" end test "can render the <Dial> verb" do markup = twiml do dial action: "/calls/new" do number "1112223333" end end assert_twiml markup, "<Dial action=\"/calls/new\"><Number>1112223333</Number></Dial>" end test "can render the <Sip> verb" do markup = twiml do sip "sip:[email protected]", username: "admin", password: "123" end assert_twiml markup, "<Sip username=\"admin\" password=\"123\">sip:[email protected]</Sip>" end test "can render the <Client> verb" do markup = twiml do client "Daniel" client "Bob" end assert_twiml markup, "<Client>Daniel</Client><Client>Bob</Client>" end test "can render the <Conference> verb" do markup = twiml do conference "Friendly Conference", end_conference_on_exit: true end assert_twiml markup, "<Conference endConferenceOnExit=\"true\">Friendly Conference</Conference>" end test "can render the <Queue> verb" do markup = twiml do queue "support", url: "about_to_connect.xml" end assert_twiml markup, "<Queue url=\"about_to_connect.xml\">support</Queue>" end test "can render the <Enqueue> verb" do markup = twiml do enqueue "support", wait_url: "wait-music.xml" end assert_twiml markup, "<Enqueue waitUrl=\"wait-music.xml\">support</Enqueue>" end test "can render the <Task> verb" do markup = twiml do task ~s({"selected_language": "it"}) end assert_twiml markup, ~s(<Task>{&quot;selected_language&quot;: &quot;it&quot;}</Task>) end test "can render the <Task> verb nested inside an <Enqueue> verb" do markup = twiml do enqueue do task ~s({"selected_language": "it"}) end end assert_twiml markup, ~s(<Enqueue><Task>{&quot;selected_language&quot;: &quot;it&quot;}</Task></Enqueue>) end test "can render the <Leave> verb" do markup = twiml do leave end assert_twiml markup, "<Leave />" end test "can render the <Hangup> verb" do markup = twiml do hangup end assert_twiml markup, "<Hangup />" end test "can render the <Redirect> verb" do markup = twiml do redirect "http://example.com", method: "POST" end assert_twiml markup, "<Redirect method=\"POST\">http://example.com</Redirect>" end test "can render the <Reject> verb" do markup = twiml do reject reason: "busy" end assert_twiml markup, "<Reject reason=\"busy\" />" markup = twiml do reject end assert_twiml markup, "<Reject />" end test "can render the <Pause> verb" do markup = twiml do pause length: 5 end assert_twiml markup, "<Pause length=\"5\" />" end test "can render the <Message> verb" do markup = twiml do message action: "/hello", method: "post" do end end assert_twiml markup, "<Message action=\"/hello\" method=\"post\"></Message>" end test "can render the <Body> verb" do markup = twiml do body "Store location: 203" end assert_twiml markup, "<Body>Store location: 203</Body>" end test "can render the <Media> verb" do markup = twiml do media "https://demo.twilio.com/owl.png" end assert_twiml markup, "<Media>https://demo.twilio.com/owl.png</Media>" end test ".twiml can include Enum loops" do markup = twiml do Enum.each 1..3, fn(n) -> say "Press #{n}" end end assert_twiml markup, "<Say>Press 1</Say><Say>Press 2</Say><Say>Press 3</Say>" end test ".twiml can loop through lists of maps" do people = [%{name: "Daniel"}, %{name: "Hunter"}] markup = twiml do Enum.each people, fn person -> say "Hello, #{person.name}!" end end assert_twiml markup, "<Say>Hello, Daniel!</Say><Say>Hello, Hunter!</Say>" end test ".twiml can 'say' a variable that happens to be a string" do some_var = "hello world" markup = twiml do say some_var end assert_twiml markup, "<Say>hello world</Say>" end test ".twiml can 'say' an integer variable" do integer = 123 markup = twiml do say integer end assert_twiml markup, "<Say>123</Say>" end test ".twiml simple verbs can take options as a variable" do options = [voice: "alice"] markup = twiml do say "I'm Alice", options end assert_twiml markup, "<Say voice=\"alice\">I&apos;m Alice</Say>" end test ".twiml self-closing verbs can take options as a variable" do options = [length: 31] markup = twiml do pause options end assert_twiml markup, "<Pause length=\"31\" />" end test ".twiml nested verbs can take options as a variable" do options = [method: "GET"] markup = twiml do gather options do say "Hi" end end assert_twiml markup, "<Gather method=\"GET\"><Say>Hi</Say></Gather>" end test ".twiml warns of reserved variable names" do ast = quote do twiml do Enum.each [1, 2], fn(number, text) -> say "#{number}" end end end assert_raise ReservedNameError, fn -> # Simulate compiling the macro Macro.expand(ast, __ENV__) end end test "escape message body" do markup = twiml do message do body "hello :<" end end assert_twiml markup, "<Message><Body>hello :&lt;</Body></Message>" end test "escape simple text" do markup = twiml do text "hello :<" end assert_twiml markup, "hello :&lt;" end test "escape attribute" do markup = twiml do tag :mms, to: "112345'" do text "hello" end end assert_twiml markup, "<Mms to=\"112345&apos;\">hello</Mms>" end defp assert_twiml(lhs, rhs) do assert lhs == "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>#{rhs}</Response>" end end
22.904025
108
0.619492
9edfa329f74814b47aa87e6fa3f817b79903b452
683
ex
Elixir
example_avialia/lib/example_avialia/cargos/shipment_document.ex
zetaron/Domo
2159163378f1ad8dea5cbc31dea2ed827c9024ab
[ "MIT" ]
null
null
null
example_avialia/lib/example_avialia/cargos/shipment_document.ex
zetaron/Domo
2159163378f1ad8dea5cbc31dea2ed827c9024ab
[ "MIT" ]
null
null
null
example_avialia/lib/example_avialia/cargos/shipment_document.ex
zetaron/Domo
2159163378f1ad8dea5cbc31dea2ed827c9024ab
[ "MIT" ]
null
null
null
defmodule ExampleAvialia.Cargos.ShipmentDocument do use Ecto.Schema use Domo, skip_defaults: true import Ecto.Changeset import Domo.Changeset alias ExampleAvialia.Cargos.Shipment schema "shipment_documents" do belongs_to :shipment, Shipment field :title, :string timestamps() end @type t :: %__MODULE__{title: String.t()} precond t: &validate_title(&1.title) defp validate_title(title) when byte_size(title) > 0, do: :ok defp validate_title(_title), do: {:error, "Document's title can't be empty."} def changeset(document_or_changeset, attrs) do document_or_changeset |> cast(attrs, typed_fields()) |> validate_type() end end
23.551724
79
0.72328
9ee0460598d970eb8d838d9c86bc70b242730c04
1,698
ex
Elixir
clients/display_video/lib/google_api/display_video/v1/model/device_make_model_targeting_option_details.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/display_video/lib/google_api/display_video/v1/model/device_make_model_targeting_option_details.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/display_video/lib/google_api/display_video/v1/model/device_make_model_targeting_option_details.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.DisplayVideo.V1.Model.DeviceMakeModelTargetingOptionDetails do @moduledoc """ Represents a targetable device make and model. This will be populated in the device_make_model_details field of a TargetingOption when targeting_type is `TARGETING_TYPE_DEVICE_MAKE_MODEL`. ## Attributes * `displayName` (*type:* `String.t`, *default:* `nil`) - Output only. The display name of the device make and model. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :displayName => String.t() } field(:displayName) end defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.DeviceMakeModelTargetingOptionDetails do def decode(value, options) do GoogleApi.DisplayVideo.V1.Model.DeviceMakeModelTargetingOptionDetails.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.DeviceMakeModelTargetingOptionDetails do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.294118
120
0.762073
9ee065345d24b2122f4ce6753756b0f22b4aac3a
300
exs
Elixir
priv/repo/migrations/20210225210616_create_guesses.exs
evanbattaglia/livewords
c1324cde64e6d7873942e24a473feb16482c9fbb
[ "MIT" ]
null
null
null
priv/repo/migrations/20210225210616_create_guesses.exs
evanbattaglia/livewords
c1324cde64e6d7873942e24a473feb16482c9fbb
[ "MIT" ]
null
null
null
priv/repo/migrations/20210225210616_create_guesses.exs
evanbattaglia/livewords
c1324cde64e6d7873942e24a473feb16482c9fbb
[ "MIT" ]
null
null
null
defmodule Livewords.Repo.Migrations.CreateGuesses do use Ecto.Migration def change do create table(:guesses) do add :text, :string add :game_id, references(:games, on_delete: :delete_all), null: false timestamps() end create index(:guesses, [:game_id]) end end
20
75
0.68
9ee08a4d3e7f29675072fdf7821b8f993b5f2016
525
ex
Elixir
web/router.ex
aaronvine/elm_recipes
bd68ddca0b22c7c773de1f80aa627bb58b759ccf
[ "MIT" ]
null
null
null
web/router.ex
aaronvine/elm_recipes
bd68ddca0b22c7c773de1f80aa627bb58b759ccf
[ "MIT" ]
null
null
null
web/router.ex
aaronvine/elm_recipes
bd68ddca0b22c7c773de1f80aa627bb58b759ccf
[ "MIT" ]
null
null
null
defmodule ElmRecipes.Router do use ElmRecipes.Web, :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 "/", ElmRecipes do pipe_through :browser # Use the default browser stack get "/", PageController, :index end # Other scopes may use custom stacks. # scope "/api", ElmRecipes do # pipe_through :api # end end
19.444444
57
0.68
9ee09b508fb11dae8e352b98e1f7565f19cacbe5
694
exs
Elixir
mix.exs
toshi0806/tcache
ec8a80d06074e50265233ba5ecc46a4ffe8d54e1
[ "BSD-3-Clause" ]
null
null
null
mix.exs
toshi0806/tcache
ec8a80d06074e50265233ba5ecc46a4ffe8d54e1
[ "BSD-3-Clause" ]
null
null
null
mix.exs
toshi0806/tcache
ec8a80d06074e50265233ba5ecc46a4ffe8d54e1
[ "BSD-3-Clause" ]
null
null
null
defmodule TCache.MixProject do use Mix.Project def project do [ app: :tcache, version: "0.1.0", elixir: "~> 1.12", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {TCache.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} {:tenbin_dns, git: "https://github.com/toshi0806/tenbin_dns.git", tag: "0.2.3"}, ] end end
22.387097
87
0.580692
9ee09cd802e049fa122cece4c3c3b54a3550ca47
1,191
ex
Elixir
lib/exactor/responders.ex
liveforeverx/exactor
65a2cef190d2bd654d08c6f9ea49c8533bc432f6
[ "MIT" ]
null
null
null
lib/exactor/responders.ex
liveforeverx/exactor
65a2cef190d2bd654d08c6f9ea49c8533bc432f6
[ "MIT" ]
null
null
null
lib/exactor/responders.ex
liveforeverx/exactor
65a2cef190d2bd654d08c6f9ea49c8533bc432f6
[ "MIT" ]
null
null
null
defmodule ExActor.Responders do @moduledoc """ Helper macros that can be used for simpler responses from init/call/cast/info handlers. """ @doc """ Can be used from `init` or `definit` to return the initial state. """ defmacro initial_state(state) do quote do {:ok, unquote(state)} end end @doc """ Can be used from `handle_call` or `defcall` to reply without changing the state """ defmacro reply(response) do quote do {:reply, unquote(response), var!(___generated_state)} end end @doc """ Can be used from `handle_call` or `defcall` to reply and change the state. """ defmacro set_and_reply(new_state, response) do quote do {:reply, unquote(response), unquote(new_state)} end end @doc """ Can be used from `handle_call`, `defcall`, `handle_info`, or `definfo` to set the new state. """ defmacro new_state(state) do quote do {:noreply, unquote(state)} end end @doc """ Can be used from `handle_call`, `defcall`, `handle_info`, or `definfo` to leave the state unchanged. """ defmacro noreply do quote do {:noreply, var!(___generated_state)} end end end
22.055556
79
0.649034
9ee0b04faf15c03c6488f87f0dfc367321de91ef
87
exs
Elixir
test/test_helper.exs
kumanote/phoenix_vue_webpack_template
1294eda8937c5eff4ea9ec2447b275b4a0d098fa
[ "MIT" ]
null
null
null
test/test_helper.exs
kumanote/phoenix_vue_webpack_template
1294eda8937c5eff4ea9ec2447b275b4a0d098fa
[ "MIT" ]
null
null
null
test/test_helper.exs
kumanote/phoenix_vue_webpack_template
1294eda8937c5eff4ea9ec2447b275b4a0d098fa
[ "MIT" ]
null
null
null
ExUnit.start Ecto.Adapters.SQL.Sandbox.mode(PhoenixVueWebpackTemplate.Repo, :manual)
17.4
71
0.827586
9ee0e7a4327d50f9e19f7180a254a9adbb649910
3,440
ex
Elixir
lib/tentacat/commits.ex
wesleimp/tentacat
6e4de63dd19ae719f2b59d4f289979a91e3cb5e2
[ "MIT" ]
null
null
null
lib/tentacat/commits.ex
wesleimp/tentacat
6e4de63dd19ae719f2b59d4f289979a91e3cb5e2
[ "MIT" ]
null
null
null
lib/tentacat/commits.ex
wesleimp/tentacat
6e4de63dd19ae719f2b59d4f289979a91e3cb5e2
[ "MIT" ]
null
null
null
defmodule Tentacat.Commits do import Tentacat alias Tentacat.Client @doc """ List commits on a repository ## Example Tentacat.Commits.list(client, "elixir-lang", "elixir") More info at: https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository """ @spec list(Client.t(), binary, binary) :: Tentacat.response() def list(client \\ %Client{}, owner, repo) do get("repos/#{owner}/#{repo}/commits", client) end @doc """ Filter commits on a repository. Parameters are `sha`, `path`, `author`, `since`, `until`. ## Example Tentacat.Commits.filter(client, "elixir-lang", "elixir", %{sha: "my-branch"}) More info at: https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository """ @spec filter(Client.t(), binary, binary, Keyword.t() | map) :: Tentacat.response() def filter(client \\ %Client{}, owner, repo, filters) do get("repos/#{owner}/#{repo}/commits?#{URI.encode_query(filters)}", client) end @doc """ Get a single commit ## Example Tentacat.Commits.find(client, "6dcb09b", "elixir-lang", "elixir") More info at: https://developer.github.com/v3/repos/commits/#get-a-commit """ @spec find(Client.t(), any, binary, binary) :: Tentacat.response() def find(client \\ %Client{}, sha, owner, repo) do get("repos/#{owner}/#{repo}/commits/#{sha}", client) end @doc """ Compare two commits ## Example Tentacat.Commits.compare(client, base, head, "elixir-lang", "elixir") More info at: https://developer.github.com/v3/repos/commits/#compare-two-commits """ @spec compare(Client.t(), any, any, binary, binary) :: Tentacat.response() def compare(client \\ %Client{}, base, head, owner, repo) do get("repos/#{owner}/#{repo}/compare/#{base}...#{head}", client) end @doc """ Create a commit Commit body example: %{ message: "my commit message", author: %{ name: "Mona Octocat", email: "[email protected]", date: "2008-07-09T16:13:30+12:00" }, parents: [ "7d1b31e74ee336d15cbd21741bc88a537ed063a0" ], tree: "827efc6d56897b048c772eb4087f854f46256132", signature: "-----BEGIN PGP SIGNATURE-----\n\niQIzBAABAQAdFiEESn/54jMNIrGSE6Tp6cQjvhfv7nAFAlnT71cACgkQ6cQjvhfv\n7nCWwA//XVqBKWO0zF+bZl6pggvky3Oc2j1pNFuRWZ29LXpNuD5WUGXGG209B0hI\nDkmcGk19ZKUTnEUJV2Xd0R7AW01S/YSub7OYcgBkI7qUE13FVHN5ln1KvH2all2n\n2+JCV1HcJLEoTjqIFZSSu/sMdhkLQ9/NsmMAzpf/iIM0nQOyU4YRex9eD1bYj6nA\nOQPIDdAuaTQj1gFPHYLzM4zJnCqGdRlg0sOM/zC5apBNzIwlgREatOYQSCfCKV7k\nnrU34X8b9BzQaUx48Qa+Dmfn5KQ8dl27RNeWAqlkuWyv3pUauH9UeYW+KyuJeMkU\n+NyHgAsWFaCFl23kCHThbLStMZOYEnGagrd0hnm1TPS4GJkV4wfYMwnI4KuSlHKB\njHl3Js9vNzEUQipQJbgCgTiWvRJoK3ENwBTMVkKHaqT4x9U4Jk/XZB6Q8MA09ezJ\n3QgiTjTAGcum9E9QiJqMYdWQPWkaBIRRz5cET6HPB48YNXAAUsfmuYsGrnVLYbG+\nUpC6I97VybYHTy2O9XSGoaLeMI9CsFn38ycAxxbWagk5mhclNTP5mezIq6wKSwmr\nX11FW3n1J23fWZn5HJMBsRnUCgzqzX3871IqLYHqRJ/bpZ4h20RhTyPj5c/z7QXp\neSakNQMfbbMcljkha+ZMuVQX1K9aRlVqbmv3ZMWh+OijLYVU2bc=\n=5Io4\n-----END PGP SIGNATURE-----\n" } ## Example Tentacat.Commits.create(client, "elixir-lang", "elixir", body) More info at: https://developer.github.com/v3/git/commits/#create-a-commit """ @spec create(Client.t(), binary, binary, map) :: Tentacat.response() def create(client \\ %Client{}, owner, repo, body) do post("repos/#{owner}/#{repo}/git/commits", client, body) end end
37.802198
870
0.706105
9ee101268781eebd6f85b8f58cde53c9ee557054
279
exs
Elixir
test/mailgun_ex/api_test.exs
aforward/mailgun_ex
70456f4086ff5207c9c4b184f6237447448f0f9c
[ "MIT" ]
null
null
null
test/mailgun_ex/api_test.exs
aforward/mailgun_ex
70456f4086ff5207c9c4b184f6237447448f0f9c
[ "MIT" ]
null
null
null
test/mailgun_ex/api_test.exs
aforward/mailgun_ex
70456f4086ff5207c9c4b184f6237447448f0f9c
[ "MIT" ]
1
2019-05-10T13:32:19.000Z
2019-05-10T13:32:19.000Z
defmodule MailgunEx.ApiTest do use ExUnit.Case alias MailgunEx.Api test "Make an invalid call to the Mailgun API" do {err, reason} = Api.request(:get, resource: "domains", base: "qtts://nowhere.local") assert :error == err assert :nxdomain == reason end end
25.363636
88
0.688172
9ee1041d86e59c22c546494737e23ece8e07383c
5,824
exs
Elixir
apps/omg_child_chain/test/omg_child_chain/fees/json_fee_parser_test.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
1
2020-10-06T03:07:47.000Z
2020-10-06T03:07:47.000Z
apps/omg_child_chain/test/omg_child_chain/fees/json_fee_parser_test.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
9
2020-09-16T15:31:17.000Z
2021-03-17T07:12:35.000Z
apps/omg_child_chain/test/omg_child_chain/fees/json_fee_parser_test.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
1
2020-09-30T17:17:27.000Z
2020-09-30T17:17:27.000Z
# Copyright 2019-2020 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 OMG.ChildChain.Fees.JSONFeeParserTest do @moduledoc false use ExUnitFixtures use ExUnit.Case, async: true alias OMG.ChildChain.Fees.JSONFeeParser alias OMG.Eth @moduletag :capture_log @eth Eth.zero_address() describe "parse/1" do test "successfuly parses valid data" do json = ~s( { "1": { "0x0000000000000000000000000000000000000000": { "type": "fixed", "symbol": "ETH", "amount": 43000000000000, "subunit_to_unit": 1000000000000000000, "pegged_amount": null, "pegged_currency": null, "pegged_subunit_to_unit": null, "updated_at": "2019-01-01T10:10:00+00:00" }, "0x11B7592274B344A6be0Ace7E5D5dF4348473e2fa": { "type": "fixed", "symbol": "FEE", "amount": 1000000000000000000, "subunit_to_unit": 1000000000000000000, "pegged_amount": null, "pegged_currency": null, "pegged_subunit_to_unit": null, "updated_at": "2019-01-01T10:10:00+00:00" }, "0x942f123b3587EDe66193aa52CF2bF9264C564F87": { "type": "fixed", "symbol": "OMG", "amount": 8600000000000000, "subunit_to_unit": 1000000000000000000, "pegged_amount": null, "pegged_currency": null, "pegged_subunit_to_unit": null, "updated_at": "2019-01-01T10:10:00+00:00" } }, "2": { "0x0000000000000000000000000000000000000000": { "type": "fixed", "symbol": "ETH", "amount": 41000000000000, "subunit_to_unit": 1000000000000000000, "pegged_amount": null, "pegged_currency": null, "pegged_subunit_to_unit": null, "updated_at": "2019-01-01T10:10:00+00:00" } } } ) assert {:ok, tx_type_map} = JSONFeeParser.parse(json) assert tx_type_map[1][@eth][:amount] == 43_000_000_000_000 assert tx_type_map[1][@eth][:updated_at] == "2019-01-01T10:10:00+00:00" |> DateTime.from_iso8601() |> elem(1) assert tx_type_map[1][Base.decode16!("942f123b3587EDe66193aa52CF2bF9264C564F87", case: :mixed)][:amount] == 8_600_000_000_000_000 assert tx_type_map[1][Base.decode16!("11B7592274B344A6be0Ace7E5D5dF4348473e2fa", case: :mixed)][:amount] == 1_000_000_000_000_000_000 assert tx_type_map[2][@eth][:amount] == 41_000_000_000_000 end test "successfuly parses an empty fee spec map" do assert {:ok, %{}} = JSONFeeParser.parse("{}") end test "returns an `invalid_tx_type` error when given a non integer tx type" do json = ~s({ "non_integer_key": { "0x0000000000000000000000000000000000000000": { "type": "fixed", "symbol": "ETH", "amount": 4, "subunit_to_unit": 1000000000000000000, "pegged_amount": 1, "pegged_currency": "USD", "pegged_subunit_to_unit": 100, "updated_at": "2019-01-01T10:10:00+00:00", "error_reason": "Non integer key results with :invalid_tx_type error" } } }) assert {:error, [{:error, :invalid_tx_type, "non_integer_key", 0}]} == JSONFeeParser.parse(json) end test "returns an `invalid_json_format` error when json is not in the correct format" do json = ~s({ "1": { "0x0000000000000000000000000000000000000000": { "type": "fixed", "symbol": "ETH", "subunit_to_unit": 1000000000000000000, "pegged_amount": 1, "pegged_currency": "USD", "pegged_subunit_to_unit": 100, "updated_at": "2019-01-01T10:10:00+00:00", "error_reason": "Missing `amount` key in fee specs" } } }) assert {:error, [{:error, :invalid_fee_spec, _, _}]} = JSONFeeParser.parse(json) end test "`duplicate_token` is not detected by the parser, first occurance takes precedence" do json = ~s({ "1": { "0x0000000000000000000000000000000000000000": { "type": "fixed", "symbol": "ETH", "amount": 1, "subunit_to_unit": 1000000000000000000, "pegged_amount": 1, "pegged_currency": "USD", "pegged_subunit_to_unit": 100, "updated_at": "2019-01-01T10:10:00+00:00" }, "0x0000000000000000000000000000000000000000": { "type": "fixed", "symbol": "ETH", "amount": 2, "subunit_to_unit": 1000000000000000000, "pegged_amount": 1, "pegged_currency": "USD", "pegged_subunit_to_unit": 100, "updated_at": "2019-01-01T10:10:00+00:00" } } }) assert {:ok, %{1 => %{@eth => %{amount: 1}}}} = JSONFeeParser.parse(json) end end end
36.4
115
0.559238
9ee11599e31a3e48557b5e48f7c58d1ddcf19414
1,470
ex
Elixir
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/metadata.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.FirebaseRules.V1.Model.Metadata do @moduledoc """ Metadata for a Ruleset. ## Attributes * `services` (*type:* `list(String.t)`, *default:* `nil`) - Services that this ruleset has declarations for (e.g., "cloud.firestore"). There may be 0+ of these. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :services => list(String.t()) } field(:services, type: :list) end defimpl Poison.Decoder, for: GoogleApi.FirebaseRules.V1.Model.Metadata do def decode(value, options) do GoogleApi.FirebaseRules.V1.Model.Metadata.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.FirebaseRules.V1.Model.Metadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.276596
164
0.729932
9ee14c98152d6ec8d5bbdc7599bd37bbea15e887
2,166
exs
Elixir
bowman/config/dev.exs
mudphone/bowman
e916d0921f259f2c9dcba9313a64402b0bc43f9e
[ "MIT" ]
null
null
null
bowman/config/dev.exs
mudphone/bowman
e916d0921f259f2c9dcba9313a64402b0bc43f9e
[ "MIT" ]
3
2020-07-17T01:30:50.000Z
2021-05-08T20:23:35.000Z
bowman/config/dev.exs
mudphone/bowman
e916d0921f259f2c9dcba9313a64402b0bc43f9e
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database config :bowman, Bowman.Repo, username: "postgres", password: "postgres", database: "bowman_dev", hostname: "localhost", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :bowman, BowmanWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :bowman, BowmanWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/bowman_web/{live,views}/.*(ex)$", ~r"lib/bowman_web/templates/.*(eex)$", ~r{lib/bowman_web/live/.*(ex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
27.769231
68
0.686057
9ee1707e643db6aa0dd9c034562350d2eda86595
2,066
ex
Elixir
lib/google_api/pub_sub/v1/model/list_snapshots_response.ex
albert-io/elixir-google-pub-sub
b34d11bc236b5e02ba9c1d88c44c623836363148
[ "Apache-2.0" ]
null
null
null
lib/google_api/pub_sub/v1/model/list_snapshots_response.ex
albert-io/elixir-google-pub-sub
b34d11bc236b5e02ba9c1d88c44c623836363148
[ "Apache-2.0" ]
null
null
null
lib/google_api/pub_sub/v1/model/list_snapshots_response.ex
albert-io/elixir-google-pub-sub
b34d11bc236b5e02ba9c1d88c44c623836363148
[ "Apache-2.0" ]
null
null
null
# 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.PubSub.V1.Model.ListSnapshotsResponse do @moduledoc """ Response for the &#x60;ListSnapshots&#x60; method.&lt;br&gt;&lt;br&gt; &lt;b&gt;BETA:&lt;/b&gt; This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. ## Attributes - nextPageToken (String.t): If not empty, indicates that there may be more snapshot that match the request; this value should be passed in a new &#x60;ListSnapshotsRequest&#x60;. Defaults to: `null`. - snapshots ([Snapshot]): The resulting snapshots. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :"nextPageToken" => any(), :"snapshots" => list(GoogleApi.PubSub.V1.Model.Snapshot.t()) } field(:"nextPageToken") field(:"snapshots", as: GoogleApi.PubSub.V1.Model.Snapshot, type: :list) end defimpl Poison.Decoder, for: GoogleApi.PubSub.V1.Model.ListSnapshotsResponse do def decode(value, options) do GoogleApi.PubSub.V1.Model.ListSnapshotsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PubSub.V1.Model.ListSnapshotsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.259259
288
0.747822
9ee180a49325798ab8a8ee955b945e270861e290
299
exs
Elixir
test/enum_test.exs
kernel-io/ash_postgres
e5b30d544f14737a9cf29eef220f1720051c3d0c
[ "MIT" ]
13
2020-09-04T22:31:23.000Z
2022-02-06T13:24:23.000Z
test/enum_test.exs
kernel-io/ash_postgres
e5b30d544f14737a9cf29eef220f1720051c3d0c
[ "MIT" ]
57
2019-12-04T15:23:41.000Z
2022-02-14T22:55:16.000Z
test/enum_test.exs
kernel-io/ash_postgres
e5b30d544f14737a9cf29eef220f1720051c3d0c
[ "MIT" ]
15
2020-10-22T13:26:25.000Z
2021-07-26T23:49:42.000Z
defmodule AshPostgres.EnumTest do @moduledoc false use AshPostgres.RepoCase, async: false alias AshPostgres.Test.{Api, Post} require Ash.Query test "valid values are properly inserted" do Post |> Ash.Changeset.new(%{title: "title", status: :open}) |> Api.create!() end end
21.357143
58
0.695652
9ee18b5b8a7aa0e93aee7941a54c130e4899a4f7
3,186
ex
Elixir
lib/membrane/rtp/packet_payload_type.ex
simoexpo/membrane_rtp_plugin
925053eb6ad0befbfe79ab1dad51e40f3b68ae69
[ "Apache-2.0" ]
null
null
null
lib/membrane/rtp/packet_payload_type.ex
simoexpo/membrane_rtp_plugin
925053eb6ad0befbfe79ab1dad51e40f3b68ae69
[ "Apache-2.0" ]
null
null
null
lib/membrane/rtp/packet_payload_type.ex
simoexpo/membrane_rtp_plugin
925053eb6ad0befbfe79ab1dad51e40f3b68ae69
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.RTP.Packet.PayloadType do @moduledoc """ This module contains utility to translate numerical payload type into an atom value. """ alias Membrane.RTP @doc """ Gets the name of used encoding from numerical payload type according to [RFC3551](https://tools.ietf.org/html/rfc3551#page-32). For quick reference check [datasheet](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml). """ @spec get_encoding_name(payload_type :: RTP.payload_type_t()) :: RTP.static_encoding_name_t() | :dynamic def get_encoding_name(type) def get_encoding_name(0), do: :PCMU def get_encoding_name(3), do: :GSM def get_encoding_name(4), do: :G732 def get_encoding_name(5), do: :DVI4 def get_encoding_name(6), do: :DVI4 def get_encoding_name(7), do: :LPC def get_encoding_name(8), do: :PCMA def get_encoding_name(9), do: :G722 def get_encoding_name(10), do: :L16 def get_encoding_name(11), do: :L16 def get_encoding_name(12), do: :QCELP def get_encoding_name(13), do: :CN def get_encoding_name(14), do: :MPA def get_encoding_name(15), do: :G728 def get_encoding_name(16), do: :DVI4 def get_encoding_name(17), do: :DVI4 def get_encoding_name(18), do: :G729 def get_encoding_name(25), do: :CELB def get_encoding_name(26), do: :JPEG def get_encoding_name(28), do: :NV def get_encoding_name(31), do: :H261 def get_encoding_name(32), do: :MPV def get_encoding_name(33), do: :MP2T def get_encoding_name(34), do: :H263 def get_encoding_name(payload_type) when payload_type in 96..127, do: :dynamic @doc """ Gets the clock rate from numerical payload type according to [RFC3551](https://tools.ietf.org/html/rfc3551#page-32). For quick reference check [datasheet](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml). """ @spec get_clock_rate(payload_type :: RTP.payload_type_t()) :: RTP.clock_rate_t() | :dynamic def get_clock_rate(type) def get_clock_rate(0), do: 8000 def get_clock_rate(3), do: 8000 def get_clock_rate(4), do: 8000 def get_clock_rate(5), do: 8000 def get_clock_rate(6), do: 16000 def get_clock_rate(7), do: 8000 def get_clock_rate(8), do: 8000 def get_clock_rate(9), do: 8000 def get_clock_rate(10), do: 44_100 def get_clock_rate(11), do: 44_100 def get_clock_rate(12), do: 8000 def get_clock_rate(13), do: 8000 def get_clock_rate(14), do: 90_000 def get_clock_rate(15), do: 8000 def get_clock_rate(16), do: 11_025 def get_clock_rate(17), do: 22_050 def get_clock_rate(18), do: 8000 def get_clock_rate(25), do: 90_000 def get_clock_rate(26), do: 90_000 def get_clock_rate(28), do: 90_000 def get_clock_rate(31), do: 90_000 def get_clock_rate(32), do: 90_000 def get_clock_rate(33), do: 90_000 def get_clock_rate(34), do: 90_000 def get_clock_rate(payload_type) when payload_type in 96..127, do: :dynamic @doc """ Checks if numerical payload type should be assigned to format type dynamically. """ @spec is_dynamic(payload_type :: RTP.payload_type_t()) :: boolean() def is_dynamic(payload_type) when payload_type in 96..127, do: true def is_dynamic(_payload_type), do: false end
38.385542
129
0.725989
9ee1928d456e07a88e085f59fb4a273b7d1bd877
1,607
ex
Elixir
test/support/model_case.ex
damonkelley/requestbin
1f59df73ad3e47e74ba18a2987bd0b0cce262a13
[ "MIT" ]
4
2016-05-20T04:40:21.000Z
2017-12-20T12:54:55.000Z
test/support/model_case.ex
damonkelley/requestbin
1f59df73ad3e47e74ba18a2987bd0b0cce262a13
[ "MIT" ]
null
null
null
test/support/model_case.ex
damonkelley/requestbin
1f59df73ad3e47e74ba18a2987bd0b0cce262a13
[ "MIT" ]
null
null
null
defmodule RequestBin.ModelCase do @moduledoc """ This module defines the test case to be used by model tests. You may define functions here to be used as helpers in your model tests. See `errors_on/2`'s definition as reference. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias RequestBin.Repo import Ecto import Ecto.Changeset import Ecto.Query, only: [from: 1, from: 2] import RequestBin.ModelCase end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(RequestBin.Repo, []) end :ok end @doc """ Helper for returning list of errors in model when passed certain data. ## Examples Given a User model that lists `:name` as a required field and validates `:password` to be safe, it would return: iex> errors_on(%User{}, %{password: "password"}) [password: "is unsafe", name: "is blank"] You could then write your assertion like: assert {:password, "is unsafe"} in errors_on(%User{}, %{password: "password"}) You can also create the changeset manually and retrieve the errors field directly: iex> changeset = User.changeset(%User{}, password: "password") iex> {:password, "is unsafe"} in changeset.errors true """ def errors_on(model, data) do model.__struct__.changeset(model, data).errors end end
25.919355
84
0.686994
9ee1b9531f49d90a609440da6baa46b9cb73a63f
1,294
ex
Elixir
apps/util/lib/intcode.ex
jwarwick/aoc_2019
04229b86829b72323498b57a6649fcc6f7c96406
[ "MIT" ]
2
2019-12-21T21:21:04.000Z
2019-12-27T07:00:19.000Z
apps/util/lib/intcode.ex
jwarwick/aoc_2019
04229b86829b72323498b57a6649fcc6f7c96406
[ "MIT" ]
null
null
null
apps/util/lib/intcode.ex
jwarwick/aoc_2019
04229b86829b72323498b57a6649fcc6f7c96406
[ "MIT" ]
null
null
null
defmodule Intcode do @moduledoc """ AoC 2019 Intcode emulator """ alias Intcode.State @doc """ Read an IntCode file """ @spec load(Path.t()) :: map() def load(file) do {:ok, contents} = File.read(file) parse(contents) end @doc """ Parse an IntCode string """ @spec parse(String.t()) :: map() def parse(str) do String.replace(str, ~r/\s/, "") |> String.split(",", trim: true) |> Enum.map(&String.to_integer/1) |> Enum.with_index() |> Enum.reduce(%{}, fn {val, idx}, acc -> Map.put(acc, idx, val) end) end @doc """ Write to a program memory location """ def poke(prog, addr, val) do Map.put(prog, addr, val) end @doc """ Execute an intcode program """ def run(prog, input \\ [], input_fn \\ nil, output_fn \\ &default_output/1) do s = %State{prog: prog, input: input, input_fn: input_fn, output_fn: output_fn} step(s) end @doc """ Execute an intcode program with noun, verb inputs """ def run_noun_verb(prog, noun, verb) do Map.merge(prog, %{1 => noun, 2 => verb}) |> run() end defp step(s = %State{}) do case State.eval(s) do {:halt, %State{prog: prog}} -> prog {:ok, new_state} -> step(new_state) end end defp default_output(v), do: IO.inspect(v) end
21.566667
82
0.587326
9ee1cf0c257a98672eac07bcd8d3373951cfd784
146
ex
Elixir
lib/phoenix_elm_web/controllers/page_controller.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
lib/phoenix_elm_web/controllers/page_controller.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
lib/phoenix_elm_web/controllers/page_controller.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
defmodule PhoenixElmWeb.PageController do use PhoenixElmWeb, :controller def index(conn, _params) do render conn, "index.html" end end
18.25
41
0.753425
9ee1d372e5cff3804d552d8444a16254dc74f700
1,483
ex
Elixir
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_refresh_consumer_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_refresh_consumer_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_refresh_consumer_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "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.ServiceConsumerManagement.V1.Model.V1RefreshConsumerResponse do @moduledoc """ Response message for the `RefreshConsumer` method. This response message is assigned to the `response` field of the returned Operation when that operation is done. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.V1RefreshConsumerResponse do def decode(value, options) do GoogleApi.ServiceConsumerManagement.V1.Model.V1RefreshConsumerResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.V1RefreshConsumerResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.704545
165
0.779501
9ee217412d9d40b81acfc349572f40790c8b8fbe
4,017
ex
Elixir
lib/piccdata/sdm_enc.ex
theMarinac/ntag424
421e663f6f2822e7c70cd8b188d96843e476ecb2
[ "MIT" ]
null
null
null
lib/piccdata/sdm_enc.ex
theMarinac/ntag424
421e663f6f2822e7c70cd8b188d96843e476ecb2
[ "MIT" ]
null
null
null
lib/piccdata/sdm_enc.ex
theMarinac/ntag424
421e663f6f2822e7c70cd8b188d96843e476ecb2
[ "MIT" ]
null
null
null
defmodule Ntag424.PiccData.SdmEnc do @doc """ Module for decrypting SUN messages and calculating SDMMAC from NTAG 424 DNA\n """ use Bitwise, only_operators: true defguard is_mod(x, y) when rem(byte_size(x), y) == 0 defguard both_binary(pkey, data) when is_binary(pkey) and is_binary(data) defguard dsm_guard(mk, fk, data, cmac) when both_binary(mk, fk) and both_binary(data, cmac) @ntag_head <<0x3C, 0xC3, 0x00, 0x01, 0x00, 0x80>> @ntag_head2 <<0xC3, 0x3C, 0x00, 0x01, 0x00, 0x80>> # 16 byte or 128 bit @aes_block_size 16 # Initialization vector @iv <<0::128>> # Sdmmac paramt text @spt "&sdmmac=" def decrypt_file_data(pkey, data, count, enc_data) do binary_stream = @ntag_head2 <> data padded_binary_stream = binary_stream |> pad_binary() cmac_key = :crypto.mac_init(:cmac, :aes_128_cbc, pkey) |> :crypto.mac_update(padded_binary_stream) |> :crypto.mac_final() iv = :crypto.crypto_one_time(:aes_128_ecb, cmac_key, pad_counter(count), true) :crypto.crypto_one_time(:aes_128_cbc, cmac_key, iv, enc_data, false) end def calculate_sdmmac(bin_pkey, bin_picc_data, bin_enc_data) when both_binary(bin_pkey, bin_picc_data) do binary_stream = @ntag_head <> bin_picc_data # Padding binary represented tag data is required in # order to work with aes. AES block size is 128 bit padded_binary_stream = binary_stream |> pad_binary() enc = bin_enc_data |> Base.encode16() input_buff = (enc <> @spt) |> to_ascii() cmac_one = :crypto.mac_init(:cmac, :aes_128_cbc, bin_pkey) |> :crypto.mac_update(padded_binary_stream) |> :crypto.mac_final() cmac_two = :crypto.mac_init(:cmac, :aes_128_cbc, cmac_one) |> :crypto.mac_update(input_buff) |> :crypto.mac_final() cmac_two |> :erlang.binary_to_list() |> Enum.drop_every(2) |> :erlang.list_to_binary() end def decrypt_sun_message(meta_key, file_key, data, cmac, enc_data) when dsm_guard(meta_key, file_key, data, cmac) do pstream = :crypto.crypto_one_time(:aes_128_cbc, meta_key, @iv, data, false) <<tag::binary-size(1)>> <> _ = pstream uid_len = tag |> band(<<0x0F>>) with {:ok, _} <- check_length(uid_len, file_key), data <- uid_mirroring_en({uid_len, pstream, band(tag, <<0x80>>)}), {data, count, counter} <- sdm_read_ctr_en({uid_len, {data, pstream}, band(tag, <<0x40>>)}), ^cmac <- calculate_sdmmac(file_key, data, enc_data) do file_data = decrypt_file_data(file_key, data, count, enc_data) |> parse_enc_data() {counter, file_data} else {:error, "Unsupported UID length"} -> {:error, "Unsupported UID length"} {:error, "Bad t80"} -> {:error, "Bad t80"} {:error, "Bad t40"} -> {:error, "Bad t40"} {:error, "Cmac check failed"} -> {:error, "Cmac check failed"} end end defp sdm_read_ctr_en({uid_len, {data, pstream}, t40}) when t40 == <<0x40>> do count = binary_part(pstream, decode_u(uid_len) + 1, 3) counter = :binary.decode_unsigned(count, :little) {data <> count, count, counter} end defp uid_mirroring_en({uid_len, pstream, t80}) when t80 == <<0x80>>, do: pstream |> binary_part(1, decode_u(uid_len)) defp check_length(uid_len, file_key) when uid_len != <<7>> do calculate_sdmmac(file_key, <<0::128>>, <<0::128>>) {:error, "Unsupported UID length"} end defp check_length(uid_len, _), do: {:ok, uid_len} # Helpers defp pad_binary(stream) when is_mod(stream, @aes_block_size), do: stream defp pad_binary(stream), do: pad_binary(stream <> <<0x00>>) defp band(x, y), do: (decode_u(x) &&& decode_u(y)) |> encode_u() defp decode_u(n), do: :binary.decode_unsigned(n) defp encode_u(n), do: :binary.encode_unsigned(n) defp pad_counter(x), do: x <> <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>> def to_ascii(str), do: str |> String.codepoints() |> Enum.map(&:binary.first(&1)) |> :binary.list_to_bin() defp parse_enc_data(data), do: data |> String.replace("x", "") end
37.542056
117
0.661688
9ee22567e935152b269373957444ca349ba20614
74
ex
Elixir
lib/source_academy_web/views/layout_view.ex
trewdys/source-academy2-debug
6146e1fac81472184877f47aa32dee7fdceb4fb6
[ "Unlicense" ]
null
null
null
lib/source_academy_web/views/layout_view.ex
trewdys/source-academy2-debug
6146e1fac81472184877f47aa32dee7fdceb4fb6
[ "Unlicense" ]
null
null
null
lib/source_academy_web/views/layout_view.ex
trewdys/source-academy2-debug
6146e1fac81472184877f47aa32dee7fdceb4fb6
[ "Unlicense" ]
null
null
null
defmodule SourceAcademyWeb.LayoutView do use SourceAcademyWeb, :view end
24.666667
40
0.851351
9ee247bc19c8ae2a08f297010a688d6daa3673d0
660
exs
Elixir
mix.exs
bottlenecked/presence_test
0844193d0203997a15cd8c4360e7f4b945c7b94a
[ "Apache-2.0" ]
null
null
null
mix.exs
bottlenecked/presence_test
0844193d0203997a15cd8c4360e7f4b945c7b94a
[ "Apache-2.0" ]
null
null
null
mix.exs
bottlenecked/presence_test
0844193d0203997a15cd8c4360e7f4b945c7b94a
[ "Apache-2.0" ]
null
null
null
defmodule PresenceTest.MixProject do use Mix.Project def project do [ app: :presence_test, version: "0.1.0", elixir: "~> 1.6", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ mod: {PresenceTest.Application, []}, extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}, {:phoenix_pubsub, "~> 1.1"} ] end end
21.290323
88
0.578788
9ee2d037584b2adbf560c8abf9af2810f98442ca
1,598
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_validate_agent_request.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_validate_agent_request.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_cx_v3_validate_agent_request.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.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3ValidateAgentRequest do @moduledoc """ The request message for Agents.ValidateAgent. ## Attributes * `languageCode` (*type:* `String.t`, *default:* `nil`) - If not specified, the agent's default language is used. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :languageCode => String.t() | nil } field(:languageCode) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3ValidateAgentRequest do def decode(value, options) do GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3ValidateAgentRequest.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowCxV3ValidateAgentRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.730769
117
0.749061
9ee2e11ac7d2814bf6848794ee6e95743dbcd0a2
2,104
exs
Elixir
test/floki/deep_text_test.exs
activeprospect/floki
74935f1d4e530ced36c15f9a4e1903550df24845
[ "MIT" ]
null
null
null
test/floki/deep_text_test.exs
activeprospect/floki
74935f1d4e530ced36c15f9a4e1903550df24845
[ "MIT" ]
null
null
null
test/floki/deep_text_test.exs
activeprospect/floki
74935f1d4e530ced36c15f9a4e1903550df24845
[ "MIT" ]
null
null
null
defmodule Floki.DeepTextTest do use ExUnit.Case, async: true doctest Floki.DeepText test "text from simple node" do node = {"a", [], ["Google"]} assert Floki.DeepText.get(node) == "Google" end test "text from simple node with separator" do node = {"a", [], ["Google"]} assert Floki.DeepText.get(node, " ") == "Google" end test "text from a list of deep nodes" do nodes = [{"div", [], ["This is a text", {"p", [], [" that is ", {"strong", [], ["divided into ", {"small", [], ["tiny"]}, " pieces"]}]}, "."]}, {"div", [], [" It keeps growing... ", {"span", [], ["And ends."]}]}] assert Floki.DeepText.get(nodes) == "This is a text that is divided into tiny pieces. It keeps growing... And ends." end test "text from a list of deep nodes with a separator" do nodes = [{"div", [], ["This is a text", {"p", [], [" that is ", {"strong", [], ["divided into ", {"small", [], ["tiny"]}, " pieces"]}]}, "."]}, {"div", [], [" It keeps growing... ", {"span", [], ["And ends."]}]}] assert Floki.DeepText.get(nodes, "|") == "This is a text| that is |divided into |tiny| pieces|.| It keeps growing... |And ends." end test "text when there is a comment inside the tree" do nodes = [{"a", [], ["foo"]}, {:comment, "bar"}, {"b", [], ["baz"]}] assert Floki.DeepText.get(nodes) == "foobaz" end test "text when there is a comment inside the tree with a separator" do nodes = [{"a", [], ["foo"]}, {:comment, "bar"}, {"b", [], ["baz"]}] assert Floki.DeepText.get(nodes, " ") == "foo baz" end test "text that includes a br node inside the tree" do nodes = [{"a", [], ["foo"]}, {"br", [], []}, {"b", [], ["baz"]}] assert Floki.DeepText.get(nodes) == "foo\nbaz" end test "text that includes a br node inside the tree with separator" do nodes = [{"a", [], ["foo"]}, {"br", [], []}, {"b", [], ["baz"]}] assert Floki.DeepText.get(nodes) == "foo\nbaz" end end
30.941176
133
0.507129
9ee2ff63fa7ddc147c2b71df2c38a5f8c7fa49fb
885
ex
Elixir
clients/keto/elixir/lib/keto/model/patch_relation_tuples_bad_request_body.ex
ory/sdk-generator
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
clients/keto/elixir/lib/keto/model/patch_relation_tuples_bad_request_body.ex
ory/sdk-generator
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
clients/keto/elixir/lib/keto/model/patch_relation_tuples_bad_request_body.ex
ory/sdk-generator
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule Keto.Model.PatchRelationTuplesBadRequestBody do @moduledoc """ PatchRelationTuplesBadRequestBody PatchRelationTuplesBadRequestBody PatchRelationTuplesBadRequestBody patch relation tuples bad request body """ @derive [Poison.Encoder] defstruct [ :"code", :"details", :"message", :"reason", :"request", :"status" ] @type t :: %__MODULE__{ :"code" => integer() | nil, :"details" => [map()] | nil, :"message" => String.t | nil, :"reason" => String.t | nil, :"request" => String.t | nil, :"status" => String.t | nil } end defimpl Poison.Decoder, for: Keto.Model.PatchRelationTuplesBadRequestBody do def decode(value, _options) do value end end
24.583333
142
0.670056
9ee309dfafa1d0721883bb1a4dda4e7e1137cd20
74
ex
Elixir
lib/plantar_web/views/user_reset_password_view.ex
pantanal-labs/plantar
8b119874fbddf50fe23d435462fb3238bb1d6e42
[ "MIT" ]
null
null
null
lib/plantar_web/views/user_reset_password_view.ex
pantanal-labs/plantar
8b119874fbddf50fe23d435462fb3238bb1d6e42
[ "MIT" ]
23
2020-07-29T21:03:00.000Z
2021-02-01T18:20:35.000Z
lib/plantar_web/views/user_reset_password_view.ex
pantanal-labs/plantar
8b119874fbddf50fe23d435462fb3238bb1d6e42
[ "MIT" ]
null
null
null
defmodule PlantarWeb.UserResetPasswordView do use PlantarWeb, :view end
18.5
45
0.837838
9ee32d9ef8d9f00d0a9c40c181679d02b1ea3919
2,891
ex
Elixir
apps/reaper/test/support/test_utils.ex
calebcarroll1/smartcitiesdata
b0f03496f6c592c82ba14aebf6c5996311cf3cd0
[ "Apache-2.0" ]
26
2019-09-20T23:54:45.000Z
2020-08-20T14:23:32.000Z
apps/reaper/test/support/test_utils.ex
calebcarroll1/smartcitiesdata
b0f03496f6c592c82ba14aebf6c5996311cf3cd0
[ "Apache-2.0" ]
757
2019-08-15T18:15:07.000Z
2020-09-18T20:55:31.000Z
apps/reaper/test/support/test_utils.ex
calebcarroll1/smartcitiesdata
b0f03496f6c592c82ba14aebf6c5996311cf3cd0
[ "Apache-2.0" ]
9
2019-11-12T16:43:46.000Z
2020-03-25T16:23:16.000Z
defmodule TestUtils do @moduledoc false require Elsa.Message require Logger alias SmartCity.TestDataGenerator, as: TDG def feed_supervisor_count() do Reaper.Horde.Supervisor |> Horde.DynamicSupervisor.which_children() |> Enum.filter(&is_feed_supervisor?/1) |> Enum.count() end def get_child_pids_for_feed_supervisor(name) do Reaper.Horde.Registry |> Horde.Registry.lookup(name) |> (fn [{pid, _}] -> pid end).() |> Horde.DynamicSupervisor.which_children() |> Enum.map(fn {_, pid, _, _} -> pid end) |> Enum.sort() end def child_count(module) do Reaper.Horde.Supervisor |> Horde.DynamicSupervisor.which_children() |> Enum.filter(&is_feed_supervisor?/1) |> Enum.flat_map(&get_supervisor_children/1) |> Enum.filter(fn {_, _, _, [mod]} -> mod == module end) |> Enum.count() end def bypass_file(bypass, file_name) do Bypass.stub(bypass, "HEAD", "/#{file_name}", fn conn -> Plug.Conn.resp(conn, 200, "") end) Bypass.stub(bypass, "GET", "/#{file_name}", fn conn -> Plug.Conn.resp( conn, 200, File.read!("test/support/#{file_name}") ) end) bypass end def bypass_file_with_header(bypass, file_name, header) do Bypass.stub(bypass, "HEAD", "/#{file_name}", fn conn -> Plug.Conn.resp(conn, 200, "") end) Bypass.stub(bypass, "GET", "/#{file_name}", fn conn -> conn = Plug.Conn.put_resp_header(conn, header.key, header.value) Plug.Conn.resp( conn, 200, File.read!("test/support/#{file_name}") ) end) bypass end defp is_feed_supervisor?({_, _, _, [mod]}) do mod == Reaper.FeedSupervisor end defp get_supervisor_children({_, pid, _, _}) do DynamicSupervisor.which_children(pid) end def get_dlq_messages_from_kafka(topic, endpoints) do topic |> fetch_messages(endpoints) |> Enum.map(&Jason.decode!(&1, keys: :atoms)) end def get_data_messages_from_kafka(topic, endpoints) do topic |> fetch_messages(endpoints) |> Enum.map(&SmartCity.Data.new/1) |> Enum.map(&elem(&1, 1)) |> Enum.map(&clear_timing/1) end def fetch_messages(topic, endpoints) do case :brod.fetch(endpoints, topic, 0, 0) do {:ok, {_offset, messages}} -> messages |> Enum.map(&Elsa.Message.kafka_message(&1, :value)) {:error, reason} -> Logger.warn("Failed to extract messages: #{inspect(reason)}") [] end end def create_data(overrides) do overrides |> TDG.create_data() |> clear_timing() |> clear_metadata() end def clear_metadata(%SmartCity.Data{} = data_message) do Map.update!(data_message, :_metadata, fn _ -> %{} end) end def clear_timing(%SmartCity.Data{} = data_message) do Map.update!(data_message, :operational, fn _ -> %{timing: []} end) end end
24.922414
70
0.628156
9ee34d6fa7bcaacf6cca65fbca92666f8a1897bb
7,003
ex
Elixir
lib/eth/transaction.ex
aihanrashidov/eth
fb8b2d697b63d88c2a0d326d1d54b53814e0cb6c
[ "MIT" ]
null
null
null
lib/eth/transaction.ex
aihanrashidov/eth
fb8b2d697b63d88c2a0d326d1d54b53814e0cb6c
[ "MIT" ]
null
null
null
lib/eth/transaction.ex
aihanrashidov/eth
fb8b2d697b63d88c2a0d326d1d54b53814e0cb6c
[ "MIT" ]
1
2019-02-19T09:03:36.000Z
2019-02-19T09:03:36.000Z
defmodule ETH.Transaction do import ETH.Utils alias Ethereumex.HttpClient defdelegate parse(data), to: ETH.Transaction.Parser defdelegate to_list(data), to: ETH.Transaction.Parser defdelegate build(params), to: ETH.Transaction.Builder defdelegate build(wallet, params), to: ETH.Transaction.Builder defdelegate build(sender_wallet, receiver_wallet, params_or_value), to: ETH.Transaction.Builder defdelegate hash_transaction(transaction), to: ETH.Transaction.Signer defdelegate hash_transaction(transaction, include_signature), to: ETH.Transaction.Signer defdelegate sign_transaction(transaction, private_key), to: ETH.Transaction.Signer defdelegate decode(rlp_encoded_transaction), to: ETH.Transaction.Signer defdelegate encode(signed_transaction_list), to: ETH.Transaction.Signer # NOTE: raise if private_key isnt the one in the params from? def send_transaction(wallet, params) when is_map(params) do params |> Map.merge(%{from: wallet.eth_address}) |> send_transaction(wallet.private_key) end def send_transaction(params, private_key) do set_default_from(params, private_key) |> build |> sign_transaction(private_key) |> Base.encode16() |> send end def send_transaction(sender_wallet, receiver_wallet, value) when is_number(value) do %{from: sender_wallet.eth_address, to: receiver_wallet.eth_address, value: value} |> send_transaction(sender_wallet.private_key) end def send_transaction(sender_wallet, receiver_wallet, params) when is_map(params) do params |> Map.merge(%{from: sender_wallet.eth_address, to: receiver_wallet.eth_address}) |> send_transaction(sender_wallet.private_key) end def send_transaction(sender_wallet, receiver_wallet, params) when is_list(params) do params |> Keyword.merge(from: sender_wallet.eth_address, to: receiver_wallet.eth_address) |> send_transaction(sender_wallet.private_key) end def send_transaction(sender_wallet, receiver_wallet, value, private_key) when is_number(value) do %{from: sender_wallet.eth_address, to: receiver_wallet.eth_address, value: value} |> send_transaction(private_key) end def send_transaction(sender_wallet, receiver_wallet, params, private_key) when is_map(params) do params |> Map.merge(%{from: sender_wallet.eth_address, to: receiver_wallet.eth_address}) |> send_transaction(private_key) end def send_transaction(sender_wallet, receiver_wallet, params, private_key) when is_list(params) do params |> Keyword.merge(from: sender_wallet.eth_address, to: receiver_wallet.eth_address) |> send_transaction(private_key) end def send_transaction!(wallet, params) when is_map(params) do {:ok, tx_hash} = params |> Map.merge(%{from: wallet.eth_address}) |> send_transaction(wallet.private_key) tx_hash end def send_transaction!(params, private_key) when is_list(params) do {:ok, tx_hash} = params |> send_transaction(private_key) tx_hash end def send_transaction!(params, private_key) when is_map(params) do {:ok, tx_hash} = params |> send_transaction(private_key) tx_hash end def send_transaction!(sender_wallet, receiver_wallet, value) when is_number(value) do {:ok, tx_hash} = %{from: sender_wallet.eth_address, to: receiver_wallet.eth_address, value: value} |> send_transaction(sender_wallet.private_key) tx_hash end def send_transaction!(sender_wallet, receiver_wallet, params) when is_map(params) do {:ok, tx_hash} = params |> Map.merge(%{from: sender_wallet.eth_address, to: receiver_wallet.eth_address}) |> send_transaction(sender_wallet.private_key) tx_hash end def send_transaction!(sender_wallet, receiver_wallet, params) when is_list(params) do {:ok, tx_hash} = params |> Keyword.merge(from: sender_wallet.eth_address, to: receiver_wallet.eth_address) |> send_transaction(sender_wallet.private_key) tx_hash end def send_transaction!(sender_wallet, receiver_wallet, value, private_key) when is_number(value) do {:ok, tx_hash} = %{from: sender_wallet.eth_address, to: receiver_wallet.eth_address, value: value} |> send_transaction(private_key) tx_hash end def send_transaction!(sender_wallet, receiver_wallet, params, private_key) when is_map(params) do {:ok, tx_hash} = params |> Map.merge(%{from: sender_wallet.eth_address, to: receiver_wallet.eth_address}) |> send_transaction(private_key) tx_hash end def send_transaction!(sender_wallet, receiver_wallet, params, private_key) when is_list(params) do {:ok, tx_hash} = params |> Keyword.merge(from: sender_wallet.eth_address, to: receiver_wallet.eth_address) |> send_transaction(private_key) tx_hash end def send(signature) do signature = "0x" <> signature HttpClient.eth_send_raw_transaction(signature) end def send!(signature) do {:ok, transaction_hash} = HttpClient.eth_send_raw_transaction(signature) transaction_hash end def get_senders_public_key("0x" <> rlp_encoded_transaction_list) do rlp_encoded_transaction_list |> Base.decode16!(case: :mixed) |> get_senders_public_key end def get_senders_public_key( transaction_list = [ _nonce, _gas_price, _gas_limit, _to, _value, _data, v, r, s ] ) do message_hash = hash_transaction(transaction_list, false) chain_id = get_chain_id(v, Enum.at(transaction_list, 9)) v_int = buffer_to_int(v) target_v = if chain_id > 0, do: v_int - (chain_id * 2 + 8), else: v_int signature = r <> s recovery_id = target_v - 27 {:ok, public_key} = :libsecp256k1.ecdsa_recover_compact(message_hash, signature, :uncompressed, recovery_id) public_key end def get_senders_public_key(decoded_tx_binary) do decoded_tx_binary |> ExRLP.decode() |> get_senders_public_key end def get_sender_address("0x" <> rlp_encoded_transaction_list) do rlp_encoded_transaction_list |> Base.decode16!(case: :mixed) |> ExRLP.decode() |> get_sender_address() end def get_sender_address( transaction_list = [ _nonce, _gas_price, _gas_limit, _to, _value, _data, _v, _r, _s ] ) do get_senders_public_key(transaction_list) |> get_address end def get_sender_address(decoded_tx_binary) do decoded_tx_binary |> get_senders_public_key() |> get_address end defp set_default_from(params, private_key) when is_list(params) do put_in(params, [:from], Keyword.get(params, :from, get_address(private_key))) end defp set_default_from(params, private_key) when is_map(params) do Map.merge(params, %{from: Map.get(params, :from, get_address(private_key))}) end end
30.185345
100
0.711552
9ee3569c8602925e539df145772a2fc6ac1054a6
1,481
ex
Elixir
lib/mix_test_watch/config.ex
gasparch/mix-test.watch
6be7f440bedb04ee191c187a6eeed433fd001572
[ "MIT" ]
1
2021-01-04T16:42:18.000Z
2021-01-04T16:42:18.000Z
lib/mix_test_watch/config.ex
mkaszubowski/mix-test.watch
6be7f440bedb04ee191c187a6eeed433fd001572
[ "MIT" ]
null
null
null
lib/mix_test_watch/config.ex
mkaszubowski/mix-test.watch
6be7f440bedb04ee191c187a6eeed433fd001572
[ "MIT" ]
null
null
null
defmodule MixTestWatch.Config do @moduledoc """ Responsible for gathering and packaging the configuration for the task. """ @default_runner MixTestWatch.HotRunner @default_tasks ~w(test) @default_clear false @default_exclude [] @default_extra_extensions [] defstruct tasks: @default_tasks, clear: @default_clear, runner: @default_runner, exclude: @default_exclude, extra_extensions: @default_extra_extensions, cli_args: [] @spec new([String.t]) :: %__MODULE__{} @doc """ Create a new config struct, taking values from the ENV """ def new(cli_args \\ []) do %__MODULE__{ tasks: get_tasks(), clear: get_clear(), runner: get_runner(), exclude: get_excluded(), cli_args: cli_args, extra_extensions: get_extra_extensions(), } end defp get_runner do Application.get_env(:mix_test_watch, :runner, @default_runner) end defp get_tasks do Application.get_env(:mix_test_watch, :tasks, @default_tasks) end defp get_clear do Application.get_env(:mix_test_watch, :clear, @default_clear) end defp get_excluded do Application.get_env(:mix_test_watch, :exclude, @default_exclude) end defp get_extra_extensions do Application.get_env(:mix_test_watch, :extra_extensions, @default_extra_extensions) end end
25.982456
73
0.638082
9ee35b188290a130c68f3f8ad2010a0731b33594
1,929
exs
Elixir
clients/jobs/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/jobs/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/jobs/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "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.Jobs.Mixfile do use Mix.Project @version "0.11.0" def project() do [ app: :google_api_jobs, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/jobs" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Talent Solution API client library. Cloud Talent Solution provides the capability to create, read, update, and delete job postings, as well as search jobs based on keywords and filters. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/jobs", "Homepage" => "https://cloud.google.com/talent-solution/job-search/docs/" } ] end end
28.367647
195
0.659409
9ee36c31163ffb30fbd5f37b295aa55852cd98ea
5,943
exs
Elixir
test/appsignal/appsignal_test.exs
lukerandall/appsignal-elixir
eac4a7e44354bfa2de69ea8a9b0e27157db2e4c8
[ "MIT" ]
null
null
null
test/appsignal/appsignal_test.exs
lukerandall/appsignal-elixir
eac4a7e44354bfa2de69ea8a9b0e27157db2e4c8
[ "MIT" ]
null
null
null
test/appsignal/appsignal_test.exs
lukerandall/appsignal-elixir
eac4a7e44354bfa2de69ea8a9b0e27157db2e4c8
[ "MIT" ]
null
null
null
defmodule AppsignalTest do use ExUnit.Case, async: true import AppsignalTest.Utils import ExUnit.CaptureIO alias Appsignal.{Transaction, FakeTransaction} setup do {:ok, fake_transaction} = FakeTransaction.start_link() [fake_transaction: fake_transaction] end test "set gauge" do Appsignal.set_gauge("key", 10.0) Appsignal.set_gauge("key", 10) Appsignal.set_gauge("key", 10.0, %{:a => "b"}) Appsignal.set_gauge("key", 10, %{:a => "b"}) end test "increment counter" do Appsignal.increment_counter("counter") Appsignal.increment_counter("counter", 5) Appsignal.increment_counter("counter", 5, %{:a => "b"}) Appsignal.increment_counter("counter", 5.0) Appsignal.increment_counter("counter", 5.0, %{:a => "b"}) end test "add distribution value" do Appsignal.add_distribution_value("dist_key", 10.0) Appsignal.add_distribution_value("dist_key", 10) Appsignal.add_distribution_value("dist_key", 10.0, %{:a => "b"}) Appsignal.add_distribution_value("dist_key", 10, %{:a => "b"}) end describe "plug?/0" do test "is true when Plug is loaded" do assert Appsignal.plug?() == true end end describe "phoenix?/0" do @tag :skip_env_test @tag :skip_env_test_no_nif test "is true when Phoenix is loaded" do assert Appsignal.phoenix?() == true end @tag :skip_env_test_phoenix test "is false when Phoenix is not loaded" do assert Appsignal.phoenix?() == false end end test "Agent environment variables" do with_env(%{"APPSIGNAL_APP_ENV" => "test"}, fn -> Appsignal.Config.initialize() env = Appsignal.Config.get_system_env() assert "test" = env["APPSIGNAL_APP_ENV"] config = Application.get_env(:appsignal, :config) assert :test = config[:env] end) end test "send_error", %{fake_transaction: fake_transaction} do transaction = Appsignal.send_error(%RuntimeError{message: "Exception!"}, "Error occurred", []) assert [{^transaction, "RuntimeError", "Error occurred: Exception!", []}] = FakeTransaction.errors(fake_transaction) assert [^transaction] = FakeTransaction.finished_transactions(fake_transaction) assert [^transaction] = FakeTransaction.completed_transactions(fake_transaction) end test "send_error without a stack trace", %{fake_transaction: fake_transaction} do output = capture_io(:stderr, fn -> transaction = Appsignal.send_error(%RuntimeError{message: "Exception!"}) send(self(), transaction) end) assert output =~ "Appsignal.send_error/1-7 without passing a stack trace is deprecated, and defaults to passing an empty stacktrace." transaction = receive do transaction = %Transaction{} -> transaction end assert [{^transaction, "RuntimeError", "Exception!", []}] = FakeTransaction.errors(fake_transaction) assert [^transaction] = FakeTransaction.finished_transactions(fake_transaction) assert [^transaction] = FakeTransaction.completed_transactions(fake_transaction) end test "send_error with metadata", %{fake_transaction: fake_transaction} do transaction = Appsignal.send_error(%RuntimeError{message: "Exception!"}, "Error occurred", [], %{ foo: "bar" }) assert [{^transaction, "RuntimeError", "Error occurred: Exception!", _stack}] = FakeTransaction.errors(fake_transaction) assert %{foo: "bar"} = FakeTransaction.metadata(fake_transaction) assert [^transaction] = FakeTransaction.finished_transactions(fake_transaction) assert [^transaction] = FakeTransaction.completed_transactions(fake_transaction) end test "send_error with metadata and conn", %{fake_transaction: fake_transaction} do conn = %Plug.Conn{req_headers: [{"accept", "text/plain"}]} transaction = Appsignal.send_error( %RuntimeError{message: "Exception!"}, "Error occurred", [], %{foo: "bar"}, conn ) assert [{^transaction, "RuntimeError", "Error occurred: Exception!", _stack}] = FakeTransaction.errors(fake_transaction) assert %{foo: "bar"} = FakeTransaction.metadata(fake_transaction) assert ^conn = FakeTransaction.request_metadata(fake_transaction) assert [^transaction] = FakeTransaction.finished_transactions(fake_transaction) assert [^transaction] = FakeTransaction.completed_transactions(fake_transaction) end test "send_error with a passed function", %{fake_transaction: fake_transaction} do transaction = Appsignal.send_error( %RuntimeError{message: "Exception!"}, "Error occurred", [], %{}, nil, fn t -> FakeTransaction.set_sample_data(t, "key", %{foo: "bar"}) end ) assert [{^transaction, "RuntimeError", "Error occurred: Exception!", _stack}] = FakeTransaction.errors(fake_transaction) assert %{"key" => %{foo: "bar"}} = FakeTransaction.sample_data(fake_transaction) assert [^transaction] = FakeTransaction.finished_transactions(fake_transaction) assert [^transaction] = FakeTransaction.completed_transactions(fake_transaction) end test "send_error with a custom namespace", %{fake_transaction: fake_transaction} do transaction = Appsignal.send_error( %RuntimeError{message: "Exception!"}, "Error occurred", [], %{}, nil, fn transaction -> transaction end, :background_job ) assert [{^transaction, "RuntimeError", "Error occurred: Exception!", _stack}] = FakeTransaction.errors(fake_transaction) assert [{"_123", :background_job}] = FakeTransaction.created_transactions(fake_transaction) assert [^transaction] = FakeTransaction.finished_transactions(fake_transaction) assert [^transaction] = FakeTransaction.completed_transactions(fake_transaction) end end
34.552326
129
0.682147
9ee37f64548b114a3cd001babd0dd37d21292ada
1,663
exs
Elixir
mix.exs
sntpiraquara/mapa_celulas
5e0b1206748bd5169cefb75b006a5489117bfda3
[ "MIT" ]
null
null
null
mix.exs
sntpiraquara/mapa_celulas
5e0b1206748bd5169cefb75b006a5489117bfda3
[ "MIT" ]
null
null
null
mix.exs
sntpiraquara/mapa_celulas
5e0b1206748bd5169cefb75b006a5489117bfda3
[ "MIT" ]
null
null
null
defmodule MapaCelulas.MixProject do use Mix.Project def project do [ app: :mapa_celulas, version: "0.1.0", elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {MapaCelulas.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.4.11"}, {:phoenix_pubsub, "~> 1.1"}, {:phoenix_ecto, "~> 4.0"}, {:ecto_sql, "~> 3.1"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
26.396825
79
0.580277
9ee39205108cbc17ef3b996d9d69d4e247405ea8
24,711
exs
Elixir
lib/ex_unit/test/ex_unit/assertions_test.exs
mrcasals/elixir
8cb9ebf708f2789a0e7dbf574294b82a55dd2f21
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/test/ex_unit/assertions_test.exs
mrcasals/elixir
8cb9ebf708f2789a0e7dbf574294b82a55dd2f21
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/test/ex_unit/assertions_test.exs
mrcasals/elixir
8cb9ebf708f2789a0e7dbf574294b82a55dd2f21
[ "Apache-2.0" ]
null
null
null
Code.require_file("../test_helper.exs", __DIR__) defmodule ExUnit.AssertionsTest.Value do def tuple, do: {2, 1} def falsy, do: nil def truthy, do: :truthy def binary, do: <<5, "Frank the Walrus">> end defmodule ExUnit.AssertionsTest.BrokenError do defexception [:message] @impl true def message(_) do raise "error" end end alias ExUnit.AssertionsTest.{BrokenError, Value} defmodule ExUnit.AssertionsTest do use ExUnit.Case, async: true defmacro sigil_l({:<<>>, _, [string]}, _), do: Code.string_to_quoted!(string, []) defmacro argless_macro(), do: raise("should not be invoked") defmacrop assert_ok(arg) do quote do assert {:ok, val} = ok(unquote(arg)) end end defmacrop assert_ok_with_pin_from_quoted_var(arg) do quote do kind = :ok assert {^kind, value} = unquote(arg) end end require Record Record.defrecordp(:vec, x: 0, y: 0, z: 0) defguardp is_zero(zero) when zero == 0 test "assert inside macro" do assert_ok(42) end test "assert inside macro with pins" do try do assert_ok_with_pin_from_quoted_var({:error, :oops}) rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message end end test "assert with truthy value" do :truthy = assert Value.truthy() end test "assert with message when value is falsy" do try do "This should never be tested" = assert Value.falsy(), "This should be truthy" rescue error in [ExUnit.AssertionError] -> "This should be truthy" = error.message end end test "assert when value evaluates to falsy" do try do "This should never be tested" = assert Value.falsy() rescue error in [ExUnit.AssertionError] -> "assert Value.falsy()" = error.expr |> Macro.to_string() "Expected truthy, got nil" = error.message end end test "assert arguments in special form" do true = assert (case :ok do :ok -> true end) end test "assert arguments semantics on function call" do x = 1 true = assert not_equal(x = 2, x) 2 = x end test "assert arguments are not kept for operators" do try do "This should never be tested" = assert !Value.truthy() rescue error in [ExUnit.AssertionError] -> false = is_list(error.args) end end test "assert with equality" do try do "This should never be tested" = assert 1 + 1 == 1 rescue error in [ExUnit.AssertionError] -> 1 = error.right 2 = error.left "assert 1 + 1 == 1" = error.expr |> Macro.to_string() end end test "assert with equality in reverse" do try do "This should never be tested" = assert 1 == 1 + 1 rescue error in [ExUnit.AssertionError] -> 1 = error.left 2 = error.right "assert 1 == 1 + 1" = error.expr |> Macro.to_string() end end test "assert exposes nested macro variables in matches" do assert ~l(a) = 1 assert a == 1 assert {~l(b), ~l(c)} = {2, 3} assert b == 2 assert c == 3 end test "assert does not expand variables" do assert argless_macro = 1 assert argless_macro == 1 end test "refute when value is falsy" do false = refute false nil = refute Value.falsy() end test "refute when value evaluates to truthy" do try do refute Value.truthy() raise "refute was supposed to fail" rescue error in [ExUnit.AssertionError] -> "refute Value.truthy()" = Macro.to_string(error.expr) "Expected false or nil, got :truthy" = error.message end end test "assert match when equal" do {2, 1} = assert {2, 1} = Value.tuple() # With dup vars assert {tuple, tuple} = {Value.tuple(), Value.tuple()} assert <<name_size::size(8), _::binary-size(name_size), " the ", _::binary>> = Value.binary() end test "assert match with unused var" do assert ExUnit.CaptureIO.capture_io(:stderr, fn -> Code.eval_string(""" defmodule ExSample do import ExUnit.Assertions def run do {2, 1} = assert {2, var} = ExUnit.AssertionsTest.Value.tuple() end end """) end) =~ "variable \"var\" is unused" after :code.delete(ExSample) :code.purge(ExSample) end test "assert match expands argument in match context" do {x, y, z} = {1, 2, 3} assert vec(x: ^x, y: ^y) = vec(x: x, y: y, z: z) end @test_mod_attribute %{key: :value} test "assert match with module attribute" do try do assert {@test_mod_attribute, 1} = Value.tuple() rescue error in [ExUnit.AssertionError] -> assert "{%{key: :value}, 1}" == Macro.to_string(error.left) end end test "assert match with pinned variable" do a = 1 {2, 1} = assert {2, ^a} = Value.tuple() try do assert {^a, 1} = Value.tuple() rescue error in [ExUnit.AssertionError] -> "match (=) failed\n" <> "The following variables were pinned:\n" <> " a = 1" = error.message "assert {^a, 1} = Value.tuple()" = Macro.to_string(error.expr) end end test "assert match with pinned variable from another context" do var!(a, Elixir) = 1 {2, 1} = assert {2, ^var!(a, Elixir)} = Value.tuple() try do assert {^var!(a, Elixir), 1} = Value.tuple() rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message "assert {^var!(a, Elixir), 1} = Value.tuple()" = Macro.to_string(error.expr) end end test "assert match?" do true = assert match?({2, 1}, Value.tuple()) try do "This should never be tested" = assert match?({:ok, _}, error(true)) rescue error in [ExUnit.AssertionError] -> "match (match?) failed" = error.message "assert match?({:ok, _}, error(true))" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "assert match? with guards" do true = assert match?(tuple when is_tuple(tuple), Value.tuple()) try do "This should never be tested" = assert match?(tuple when not is_tuple(tuple), error(true)) rescue error in [ExUnit.AssertionError] -> "match (match?) failed" = error.message "assert match?(tuple when not is_tuple(tuple), error(true))" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "refute match?" do false = refute match?({1, 1}, Value.tuple()) try do "This should never be tested" = refute match?({:error, _}, error(true)) rescue error in [ExUnit.AssertionError] -> "match (match?) succeeded, but should have failed" = error.message "refute match?({:error, _}, error(true))" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "assert match? with pinned variable" do a = 1 try do "This should never be tested" = assert(match?({^a, 1}, Value.tuple())) rescue error in [ExUnit.AssertionError] -> "match (match?) failed\nThe following variables were pinned:\n a = 1" = error.message "assert match?({^a, 1}, Value.tuple())" = Macro.to_string(error.expr) end end test "refute match? with pinned variable" do a = 2 try do "This should never be tested" = refute(match?({^a, 1}, Value.tuple())) rescue error in [ExUnit.AssertionError] -> """ match (match?) succeeded, but should have failed The following variables were pinned: a = 2\ """ = error.message "refute match?({^a, 1}, Value.tuple())" = Macro.to_string(error.expr) end end test "assert receive waits" do parent = self() spawn(fn -> send(parent, :hello) end) :hello = assert_receive :hello end @string "hello" test "assert receive with interpolated compile-time string" do parent = self() spawn(fn -> send(parent, "string: hello") end) "string: #{@string}" = assert_receive "string: #{@string}" end test "assert receive accepts custom failure message" do send(self(), :hello) assert_receive message, 0, "failure message" :hello = message end test "assert receive with message in mailbox after timeout, but before reading mailbox tells user to increase timeout" do parent = self() # This is testing a race condition, so it's not # guaranteed this works under all loads of the system timeout = 100 spawn(fn -> Process.send_after(parent, :hello, timeout) end) try do assert_receive :hello, timeout rescue error in [ExUnit.AssertionError] -> true = error.message =~ "Found message matching :hello after 100ms" or error.message =~ "no matching message after 100ms" end end test "assert_receive exposes nested macro variables" do send(self(), {:hello}) assert_receive {~l(a)}, 0, "failure message" assert a == :hello end test "assert_receive raises on invalid timeout" do timeout = ok(1) try do assert_receive {~l(_a)}, timeout rescue error in [ArgumentError] -> "timeout must be a non-negative integer, got: {:ok, 1}" = error.message end end test "assert_receive expands argument in match context" do {x, y, z} = {1, 2, 3} send(self(), vec(x: x, y: y, z: z)) assert_receive vec(x: ^x, y: ^y) end test "assert_receive expands argument in guard context" do send(self(), {:ok, 0, :other}) assert_receive {:ok, val, atom} when is_zero(val) and is_atom(atom) end test "assert received does not wait" do send(self(), :hello) :hello = assert_received :hello end @received :hello test "assert received with module attribute" do send(self(), :hello) :hello = assert_received @received end test "assert received with pinned variable" do status = :valid send(self(), {:status, :invalid}) try do "This should never be tested" = assert_received {:status, ^status} rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms The following variables were pinned: status = :valid Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received {:status, ^status}" = Macro.to_string(error.expr) "{:status, ^status}" = Macro.to_string(error.left) end end test "assert received with multiple identical pinned variables" do status = :valid send(self(), {:status, :invalid, :invalid}) try do "This should never be tested" = assert_received {:status, ^status, ^status} rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms The following variables were pinned: status = :valid Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received {:status, ^status, ^status}" = Macro.to_string(error.expr) "{:status, ^status, ^status}" = Macro.to_string(error.left) "\n\nAssertion failed" <> _ = Exception.message(error) end end test "assert received with multiple unique pinned variables" do status = :valid other_status = :invalid send(self(), {:status, :invalid, :invalid}) try do "This should never be tested" = assert_received {:status, ^status, ^other_status} rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms The following variables were pinned: status = :valid other_status = :invalid Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received {:status, ^status, ^other_status}" = Macro.to_string(error.expr) "{:status, ^status, ^other_status}" = Macro.to_string(error.left) end end test "assert received when empty mailbox" do try do "This should never be tested" = assert_received :hello rescue error in [ExUnit.AssertionError] -> "Assertion failed, no matching message after 0ms\nThe process mailbox is empty." = error.message "assert_received :hello" = Macro.to_string(error.expr) end end test "assert received when different message" do send(self(), {:message, :not_expected, :at_all}) try do "This should never be tested" = assert_received :hello rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received :hello" = Macro.to_string(error.expr) ":hello" = Macro.to_string(error.left) end end test "assert received when different message having more than 10 on mailbox" do for i <- 1..11, do: send(self(), {:message, i}) try do "This should never be tested" = assert_received x when x == :hello rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms Showing 10 of 11 messages in the mailbox\ """ = error.message "assert_received x when x == :hello" = Macro.to_string(error.expr) "x when x == :hello" = Macro.to_string(error.left) end end test "assert received binds variables" do send(self(), {:hello, :world}) assert_received {:hello, world} :world = world end test "assert received does not leak external variables used in guards" do send(self(), {:hello, :world}) guard_world = :world assert_received {:hello, world} when world == guard_world :world = world end test "refute received does not wait" do false = refute_received :hello end test "refute receive waits" do false = refute_receive :hello end test "refute received when equal" do send(self(), :hello) try do "This should never be tested" = refute_received :hello rescue error in [ExUnit.AssertionError] -> "Unexpectedly received message :hello (which matched :hello)" = error.message end end test "assert in when member" do true = assert 'foo' in ['foo', 'bar'] end test "assert in when is not member" do try do "This should never be tested" = assert 'foo' in 'bar' rescue error in [ExUnit.AssertionError] -> 'foo' = error.left 'bar' = error.right "assert 'foo' in 'bar'" = Macro.to_string(error.expr) end end test "refute in when is not member" do false = refute 'baz' in ['foo', 'bar'] end test "refute in when is member" do try do "This should never be tested" = refute 'foo' in ['foo', 'bar'] rescue error in [ExUnit.AssertionError] -> 'foo' = error.left ['foo', 'bar'] = error.right "refute 'foo' in ['foo', 'bar']" = Macro.to_string(error.expr) end end test "assert match" do {:ok, true} = assert {:ok, _} = ok(true) end test "assert match with bitstrings" do "foobar" = assert "foo" <> bar = "foobar" "bar" = bar end test "assert match when no match" do try do assert {:ok, _} = error(true) rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message "assert {:ok, _} = error(true)" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "assert match when falsy but not match" do try do assert {:ok, _x} = nil rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message "assert {:ok, _x} = nil" = Macro.to_string(error.expr) "nil" = Macro.to_string(error.right) end end test "assert match when falsy" do try do assert _x = nil rescue error in [ExUnit.AssertionError] -> "Expected truthy, got nil" = error.message "assert _x = nil" = Macro.to_string(error.expr) end end test "refute match when no match" do try do "This should never be tested" = refute _ = ok(true) rescue error in [ExUnit.AssertionError] -> "refute _ = ok(true)" = Macro.to_string(error.expr) "Expected false or nil, got {:ok, true}" = error.message end end test "assert regex match" do true = assert "foo" =~ ~r(o) end test "assert regex match when no match" do try do "This should never be tested" = assert "foo" =~ ~r(a) rescue error in [ExUnit.AssertionError] -> "foo" = error.left ~r{a} = error.right end end test "refute regex match" do false = refute "foo" =~ ~r(a) end test "refute regex match when match" do try do "This should never be tested" = refute "foo" =~ ~r(o) rescue error in [ExUnit.AssertionError] -> "foo" = error.left ~r"o" = error.right end end test "assert raise with no error" do "This should never be tested" = assert_raise ArgumentError, fn -> nil end rescue error in [ExUnit.AssertionError] -> "Expected exception ArgumentError but nothing was raised" = error.message end test "assert raise with error" do error = assert_raise ArgumentError, fn -> raise ArgumentError, "test error" end "test error" = error.message end @compile {:no_warn_undefined, Not.Defined} test "assert raise with some other error" do "This should never be tested" = assert_raise ArgumentError, fn -> Not.Defined.function(1, 2, 3) end rescue error in [ExUnit.AssertionError] -> "Expected exception ArgumentError but got UndefinedFunctionError " <> "(function Not.Defined.function/3 is undefined (module Not.Defined is not available))" = error.message end test "assert raise with some other error includes stacktrace from original error" do "This should never be tested" = assert_raise ArgumentError, fn -> Not.Defined.function(1, 2, 3) end rescue ExUnit.AssertionError -> [{Not.Defined, :function, [1, 2, 3], _} | _] = __STACKTRACE__ end test "assert raise with Erlang error" do assert_raise SyntaxError, fn -> List.flatten(1) end rescue error in [ExUnit.AssertionError] -> "Expected exception SyntaxError but got FunctionClauseError (no function clause matching in :lists.flatten/1)" = error.message end test "assert raise comparing messages (for equality)" do assert_raise RuntimeError, "foo", fn -> raise RuntimeError, "bar" end rescue error in [ExUnit.AssertionError] -> """ Wrong message for RuntimeError expected: "foo" actual: "bar"\ """ = error.message end test "assert raise comparing messages (with a regex)" do assert_raise RuntimeError, ~r/ba[zk]/, fn -> raise RuntimeError, "bar" end rescue error in [ExUnit.AssertionError] -> """ Wrong message for RuntimeError expected: ~r/ba[zk]/ actual: "bar"\ """ = error.message end test "assert raise with an exception with bad message/1 implementation" do assert_raise BrokenError, fn -> raise BrokenError end rescue error in [ExUnit.AssertionError] -> """ Got exception ExUnit.AssertionsTest.BrokenError but it failed to produce a message with: ** (RuntimeError) error """ <> _ = error.message end test "assert greater-than operator" do true = assert 2 > 1 end test "assert greater-than operator error" do "This should never be tested" = assert 1 > 2 rescue error in [ExUnit.AssertionError] -> 1 = error.left 2 = error.right "assert 1 > 2" = Macro.to_string(error.expr) end test "assert less or equal than operator" do true = assert 1 <= 2 end test "assert less or equal than operator error" do "This should never be tested" = assert 2 <= 1 rescue error in [ExUnit.AssertionError] -> "assert 2 <= 1" = Macro.to_string(error.expr) 2 = error.left 1 = error.right end test "assert operator with expressions" do greater = 5 true = assert 1 + 2 < greater end test "assert operator with custom message" do "This should never be tested" = assert 1 > 2, "assertion" rescue error in [ExUnit.AssertionError] -> "assertion" = error.message end test "assert lack of equality" do try do "This should never be tested" = assert "one" != "one" rescue error in [ExUnit.AssertionError] -> "Assertion with != failed, both sides are exactly equal" = error.message "one" = error.left end try do "This should never be tested" = assert 2 != 2.0 rescue error in [ExUnit.AssertionError] -> "Assertion with != failed" = error.message 2 = error.left 2.0 = error.right end end test "refute equality" do try do "This should never be tested" = refute "one" == "one" rescue error in [ExUnit.AssertionError] -> "Refute with == failed, both sides are exactly equal" = error.message "one" = error.left end try do "This should never be tested" = refute 2 == 2.0 rescue error in [ExUnit.AssertionError] -> "Refute with == failed" = error.message 2 = error.left 2.0 = error.right end end test "assert in delta" do true = assert_in_delta(1.1, 1.2, 0.2) end test "assert in delta raises when passing a negative delta" do assert_raise ArgumentError, fn -> assert_in_delta(1.1, 1.2, -0.2) end end test "assert in delta works with equal values and a delta of zero" do assert_in_delta(10, 10, 0) end test "assert in delta error" do "This should never be tested" = assert_in_delta(10, 12, 1) rescue error in [ExUnit.AssertionError] -> "Expected the difference between 10 and 12 (2) to be less than or equal to 1" = error.message end test "assert in delta with message" do "This should never be tested" = assert_in_delta(10, 12, 1, "test message") rescue error in [ExUnit.AssertionError] -> "test message" = error.message end test "refute in delta" do false = refute_in_delta(1.1, 1.5, 0.2) end test "refute in delta error" do "This should never be tested" = refute_in_delta(10, 11, 2) rescue error in [ExUnit.AssertionError] -> "Expected the difference between 10 and 11 (1) to be more than 2" = error.message end test "refute in delta with message" do "This should never be tested" = refute_in_delta(10, 11, 2, "test message") rescue error in [ExUnit.AssertionError] -> "test message (difference between 10 and 11 is less than 2)" = error.message end test "catch_throw with no throw" do catch_throw(1) rescue error in [ExUnit.AssertionError] -> "Expected to catch throw, got nothing" = error.message end test "catch_error with no error" do catch_error(1) rescue error in [ExUnit.AssertionError] -> "Expected to catch error, got nothing" = error.message end test "catch_exit with no exit" do catch_exit(1) rescue error in [ExUnit.AssertionError] -> "Expected to catch exit, got nothing" = error.message end test "catch_throw with throw" do 1 = catch_throw(throw(1)) end test "catch_exit with exit" do 1 = catch_exit(exit(1)) end test "catch_error with error" do :function_clause = catch_error(List.flatten(1)) end test "flunk" do "This should never be tested" = flunk() rescue error in [ExUnit.AssertionError] -> "Flunked!" = error.message end test "flunk with message" do "This should never be tested" = flunk("This should raise an error") rescue error in [ExUnit.AssertionError] -> "This should raise an error" = error.message end test "flunk with wrong argument type" do "This should never be tested" = flunk(["flunk takes a binary, not a list"]) rescue error -> "no function clause matching in ExUnit.Assertions.flunk/1" = FunctionClauseError.message(error) end test "AssertionError.message/1 is nicely formatted" do assert :a = :b rescue error in [ExUnit.AssertionError] -> """ match (=) failed code: assert :a = :b left: :a right: :b """ = Exception.message(error) end defp ok(val), do: {:ok, val} defp error(val), do: {:error, val} defp not_equal(left, right), do: left != right end
27.365449
123
0.623123
9ee3a419ffb50329967ffbf73894270bae030a74
4,619
ex
Elixir
lib/strava/auth.ex
manhtai/strava
ceb54b1c8540a1eb498f99e4fba2cef7b6e3cb08
[ "MIT" ]
null
null
null
lib/strava/auth.ex
manhtai/strava
ceb54b1c8540a1eb498f99e4fba2cef7b6e3cb08
[ "MIT" ]
null
null
null
lib/strava/auth.ex
manhtai/strava
ceb54b1c8540a1eb498f99e4fba2cef7b6e3cb08
[ "MIT" ]
null
null
null
defmodule Strava.Auth do @moduledoc """ An OAuth2 strategy for Strava. """ use OAuth2.Strategy def new do OAuth2.Client.new( strategy: __MODULE__, client_id: Strava.client_id(), client_secret: Strava.client_secret(), redirect_uri: Strava.redirect_uri(), site: "https://www.strava.com", authorize_url: "https://www.strava.com/oauth/authorize", token_url: "https://www.strava.com/oauth/token" ) |> OAuth2.Client.put_serializer("application/json", Poison) end @doc """ Returns the authorize url based on the client configuration. - approval_prompt: string optional "force" or "auto", use "force" to always show the authorization prompt even if the user has already authorized the current application, default is "auto" - scope: string required Requested scopes, as a comma delimited string, e.g. "activity:read_all,activity:write". Applications should request only the scopes required for the application to function normally. - `read` - read public segments, public routes, public profile data, public posts, public events, club feeds, and leaderboards - `read_all` - read private routes, private segments, and private events for the user - `profile:read_all` - read all profile information even if the user has set their profile visibility to Followers or Only You - `profile:write` - update the user's weight and Functional Threshold Power (FTP), and access to star or unstar segments on their behalf - `activity:read` - read the user's activity data for activities that are visible to Everyone and Followers, excluding privacy zone data - `activity:read_all` - the same access as activity:read, plus privacy zone data and access to read the user's activities with visibility set to Only You - `activity:write` - access to create manual activities and uploads, and access to edit any activities that are visible to the app, based on activity read access level - state: string optional returned to your application, useful if the authentication is done from various points in an app """ def authorize_url!(params \\ []) do OAuth2.Client.authorize_url!(new(), params) end @doc """ Fetches an `OAuth2.AccessToken` struct by making a request to the token endpoint. Returns the `OAuth2.Client` struct loaded with the access token which can then be used to make authenticated requests to an OAuth2 provider's API. You can pass options to the underlying http library via `options` parameter """ def get_token(params \\ [], headers \\ []) do OAuth2.Client.get_token(new(), params, headers) end @doc """ Fetches an `OAuth2.AccessToken` struct by making a request to the token endpoint. Returns the `OAuth2.Client` struct loaded with the access token which can then be used to make authenticated requests to an OAuth2 provider's API. You can pass options to the underlying http library via `options` parameter """ def get_token!(params \\ [], headers \\ []) do OAuth2.Client.get_token!(new(), params, headers) end @doc """ Parse the detailed representation of the current athlete from the OAuth2 client or access token. """ def get_athlete!(client_or_access_token) def get_athlete!(%OAuth2.Client{token: %OAuth2.AccessToken{} = access_token}), do: get_athlete!(access_token) def get_athlete!(%OAuth2.AccessToken{other_params: %{"athlete" => athlete}}) do Strava.Deserializer.transform(athlete, %{:as => %Strava.DetailedAthlete{}}) end # OAuth2 strategy callbacks @doc """ The authorization URL endpoint of the provider. - `params` additional query parameters for the URL """ def authorize_url(client, params) do client |> put_param(:response_type, "code") |> put_param(:client_id, client.client_id) |> put_param(:redirect_uri, client.redirect_uri) |> merge_params(params) end @doc """ Retrieve an access token given the specified validation code. """ def get_token(client, params, headers) do {code, params} = Keyword.pop(params, :code, client.params["code"]) {grant_type, params} = Keyword.pop(params, :grant_type) client |> put_param(:code, code) |> put_param(:grant_type, grant_type) |> put_param(:client_id, client.client_id) |> put_param(:redirect_uri, client.redirect_uri) |> put_param(:client_secret, client.client_secret) |> merge_params(params) |> put_header("Accept", "application/json") |> put_headers(headers) end end
35.806202
98
0.703399
9ee3a4e350aa32ed53eabdacca1564a91958db1d
243
ex
Elixir
lib/perspective/protocols/chars.ex
backmath/perspective
a0a577d0ffb06805b64e4dcb171a093e051884b0
[ "MIT" ]
2
2020-04-24T19:43:06.000Z
2020-04-24T19:52:27.000Z
lib/perspective/protocols/chars.ex
backmath/perspective
a0a577d0ffb06805b64e4dcb171a093e051884b0
[ "MIT" ]
null
null
null
lib/perspective/protocols/chars.ex
backmath/perspective
a0a577d0ffb06805b64e4dcb171a093e051884b0
[ "MIT" ]
null
null
null
defimpl String.Chars, for: Tuple do def to_string(tuple) do opts = struct(Inspect.Opts, []) doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(tuple, opts)) Inspect.Algebra.format(doc, 10000) |> Kernel.to_string() end end
24.3
68
0.691358
9ee3c0c9e1dc05fc2f228fcacdf16203fb4a71b5
6,372
ex
Elixir
lib/typed_struct.ex
s3cur3/typed_struct
1185f83434088cf68d36c44cd2c3b4e19f0005eb
[ "MIT" ]
null
null
null
lib/typed_struct.ex
s3cur3/typed_struct
1185f83434088cf68d36c44cd2c3b4e19f0005eb
[ "MIT" ]
null
null
null
lib/typed_struct.ex
s3cur3/typed_struct
1185f83434088cf68d36c44cd2c3b4e19f0005eb
[ "MIT" ]
null
null
null
defmodule TypedStruct do @external_resource "README.md" @moduledoc "README.md" |> File.read!() |> String.split("<!-- MDOC !-->") |> Enum.fetch!(1) @doc false defmacro __using__(_) do quote do import TypedStruct, only: [typedstruct: 1, typedstruct: 2] end end @doc """ Defines a typed struct. Inside a `typedstruct` block, each field is defined through the `field/2` macro. ## Options * `enforce` - if set to true, sets `enforce: true` to all fields by default. This can be overridden by setting `enforce: false` or a default value on individual fields. * `opaque` - if set to true, creates an opaque type for the struct. * `module` - if set, creates the struct in a submodule named `module`. ## Examples defmodule MyStruct do use TypedStruct typedstruct do field :field_one, String.t() field :field_two, integer(), enforce: true field :field_three, boolean(), enforce: true field :field_four, atom(), default: :hey end end The following is an equivalent using the *enforce by default* behaviour: defmodule MyStruct do use TypedStruct typedstruct enforce: true do field :field_one, String.t(), enforce: false field :field_two, integer() field :field_three, boolean() field :field_four, atom(), default: :hey end end You can create the struct in a submodule instead: defmodule MyModule do use TypedStruct typedstruct, module: Struct do field :field_one, String.t() field :field_two, integer(), enforce: true field :field_three, boolean(), enforce: true field :field_four, atom(), default: :hey end end """ defmacro typedstruct(opts \\ [], do: block) do if is_nil(opts[:module]) do quote do Module.eval_quoted( __ENV__, TypedStruct.__typedstruct__( unquote(Macro.escape(block)), unquote(opts) ) ) end else quote do defmodule unquote(opts[:module]) do Module.eval_quoted( __ENV__, TypedStruct.__typedstruct__( unquote(Macro.escape(block)), unquote(opts) ) ) end end end end @doc false def __typedstruct__(block, opts) do quote do Module.register_attribute(__MODULE__, :ts_plugins, accumulate: true) Module.register_attribute(__MODULE__, :ts_fields, accumulate: true) Module.register_attribute(__MODULE__, :ts_types, accumulate: true) Module.register_attribute(__MODULE__, :ts_enforce_keys, accumulate: true) Module.put_attribute(__MODULE__, :ts_enforce?, unquote(!!opts[:enforce])) import TypedStruct unquote(block) @enforce_keys @ts_enforce_keys defstruct @ts_fields TypedStruct.__type__(@ts_types, unquote(opts)) Enum.each(@ts_plugins, fn {plugin, plugin_opts} -> if {:after_definition, 1} in plugin.__info__(:functions) do Module.eval_quoted(__MODULE__, plugin.after_definition(plugin_opts)) end end) Module.delete_attribute(__MODULE__, :ts_enforce?) Module.delete_attribute(__MODULE__, :ts_enforce_keys) Module.delete_attribute(__MODULE__, :ts_types) Module.delete_attribute(__MODULE__, :ts_plugins) end end @doc false defmacro __type__(types, opts) do if Keyword.get(opts, :opaque, false) do quote bind_quoted: [types: types] do @opaque t() :: %__MODULE__{unquote_splicing(types)} end else quote bind_quoted: [types: types] do @type t() :: %__MODULE__{unquote_splicing(types)} end end end @doc """ Registers a plugin for the currently defined struct. ## Example typedstruct do plugin MyPlugin field :a_field, String.t() end For more information on how to define your own plugins, please see `TypedStruct.Plugin`. To use a third-party plugin, please refer directly to its documentation. """ defmacro plugin(plugin, opts \\ []) do quote do Module.put_attribute( __MODULE__, :ts_plugins, {unquote(plugin), unquote(opts)} ) require unquote(plugin) unquote(plugin).init(unquote(opts)) end end @doc """ Defines a field in a typed struct. ## Example # A field named :example of type String.t() field :example, String.t() ## Options * `default` - sets the default value for the field * `enforce` - if set to true, enforces the field and makes its type non-nullable """ defmacro field(name, type, opts \\ []) do quote do TypedStruct.__field__( __MODULE__, unquote(name), unquote(Macro.escape(type)), unquote(opts) ) Enum.each(@ts_plugins, fn {plugin, plugin_opts} -> if {:field, 3} in plugin.__info__(:functions) do Module.eval_quoted( __MODULE__, plugin.field( unquote(name), unquote(Macro.escape(type)), unquote(opts) ++ plugin_opts ) ) end end) end end @doc false def __field__(mod, name, type, opts) when is_atom(name) do if mod |> Module.get_attribute(:ts_fields) |> Keyword.has_key?(name) do raise ArgumentError, "the field #{inspect(name)} is already set" end has_default? = Keyword.has_key?(opts, :default) enforce_by_default? = Module.get_attribute(mod, :ts_enforce?) enforce? = if is_nil(opts[:enforce]), do: enforce_by_default? && !has_default?, else: !!opts[:enforce] nullable? = !has_default? && !enforce? Module.put_attribute(mod, :ts_fields, {name, opts[:default]}) Module.put_attribute(mod, :ts_types, {name, type_for(type, nullable?)}) if enforce?, do: Module.put_attribute(mod, :ts_enforce_keys, name) end def __field__(_mod, name, _type, _opts) do raise ArgumentError, "a field name must be an atom, got #{inspect(name)}" end # Makes the type nullable if the key is not enforced. defp type_for(type, false), do: type defp type_for(type, _), do: quote(do: unquote(type) | nil) end
27.465517
80
0.618487
9ee4313c0497770311b02ee8c57126369f2ee0e1
4,345
exs
Elixir
test/iris/rpc_test.exs
zmoshansky/iris
8470e990e3fd742d95b0ca35efcc6393951f81ee
[ "Apache-2.0", "MIT" ]
null
null
null
test/iris/rpc_test.exs
zmoshansky/iris
8470e990e3fd742d95b0ca35efcc6393951f81ee
[ "Apache-2.0", "MIT" ]
null
null
null
test/iris/rpc_test.exs
zmoshansky/iris
8470e990e3fd742d95b0ca35efcc6393951f81ee
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule Iris.RPCTest do use Iris.Test.Helper @doc """ @assigns, @opts declared in Iris.Test.Helper """ @public_args ["TestModule", "test_public", ["bar"]] @public_parsed_args {:"Elixir.Iris.Test.TestModule", :test_public, ["bar"]} @private_args ["TestModule", "test_private", ["food"]] @private_parsed_args {:"Elixir.Iris.Test.TestModule", :test_private, ["food"]} test "process_call/2 succeeds" do res = Iris.RPC.process_call @public_args, :public assert {:ok, "foo bar", @public_parsed_args} == res res = Iris.RPC.process_call @private_args, :private assert {:ok, "bar food", @private_parsed_args} == res end test "process_call/2 succeeds without prefix" do res = Iris.RPC.process_call ["Elixir.Iris.Test.TestModule", "test_public", ["bar"]], :no_prefix assert {:ok, "foo bar", {Iris.Test.TestModule, :test_public, ["bar"]}} == res end test "process_call/2 fails" do refute_ok Iris.RPC.process_call nil, nil refute_ok Iris.RPC.process_call ["Enum", "test_public", ["bar"]], :public refute_ok Iris.RPC.process_call [nil, "test_public", ["bar"]], :public refute_ok Iris.RPC.process_call ["TestModule", nil, ["bar"]], :public refute_ok Iris.RPC.process_call ["TestModule", "test_public", nil], :public refute_ok Iris.RPC.process_call @public_args, :private refute_ok Iris.RPC.process_call @private_args, :public end test "process_call/3 succeeds" do res = Iris.RPC.process_call ["TestModule", "test_assigns", ["bar"]], :private, @assigns assert {:ok, "hellobar", {Iris.Test.TestModule, :test_assigns, [%{text: "hello"}, "bar"]}} == res end test "process_call/3 fails" do refute_ok Iris.RPC.process_call nil, nil, %{text: "hello"} refute_ok Iris.RPC.process_call ["Enum", "test_assigns", ["bar"]], :private, @assigns refute_ok Iris.RPC.process_call [nil, "test_assigns", ["bar"]], :private, @assigns refute_ok Iris.RPC.process_call ["TestModule", nil, ["bar"]], :private, @assigns refute_ok Iris.RPC.process_call ["TestModule", nil, "bar"], :private, @assigns refute_ok Iris.RPC.process_call ["TestModule", "test_assigns", nil], :private, @assigns end test "parse_input/2 suceeds" do result = Iris.RPC.parse_input @public_args, @opts assert_ok result {_, {module, _, _}} = result assert module == :"Elixir.Iris.Test.TestModule" # Here we show how @opts passed to parse_input affects the parsing of the module, in particular, a lack of :mod_prefix result = Iris.RPC.parse_input @public_args, nil assert_ok result {_, {module, _, _}} = result assert module == :"TestModule" end test "parse_input/2 fails" do refute_ok Iris.RPC.parse_input(["TestModule", "test_public"], @opts) refute_ok Iris.RPC.parse_input(["NotAModule", "test_public", ["bar"]], @opts) refute_ok Iris.RPC.parse_input("TestModule", @opts) end test "parse_input/2 without mod_prefix" do result = Iris.RPC.parse_input ["Elixir.Iris.Test.TestModule", "test_public", ["bar"]], @opts_no_prefix assert_ok result {_, {module, fun, args}} = result assert module == :"Elixir.Iris.Test.TestModule" assert fun == :test_public assert args == ["bar"] end test "dispatch/4 succeeds" do assert Iris.RPC.dispatch :"Elixir.Iris.Test.TestModule", :test_public, ["bar"], @opts end test "dispatch/4 errors" do assert_raise(Iris.PermissionError, fn -> Iris.RPC.dispatch(:"Elixir.Iris.Test.TestModule", :does_not_exist, ["bar"], @opts) end) end test "call_allowed?/3 returns true if MFA is allowed" do assert Iris.RPC.call_allowed? :"Elixir.Iris.Test.TestModule", :test_public, ["bar"], @opts end test "call_allowed?/3 returns false if MFA is disallowed" do refute Iris.RPC.call_allowed? :"Elixir.Iris.Test.TestModule", :test_public, ["bar", "food"], @opts refute Iris.RPC.call_allowed? :"Elixir.Iris.Test.TestModule", :test_private, ["food"], @opts refute Iris.RPC.call_allowed? :users, :test_public, ["bar"], @opts end test "call_allowed?/3 returns false if any args are nil" do refute Iris.RPC.call_allowed? nil, :test_public, ["bar"], @opts refute Iris.RPC.call_allowed? :"Elixir.Iris.Test.TestModule", nil, ["bar"], @opts refute Iris.RPC.call_allowed? :"Elixir.Iris.Test.TestModule", :test_public, nil, @opts end end
43.019802
132
0.688608
9ee4329a1455a1cdb824d13e38fd9fee19565582
1,612
exs
Elixir
combo/phxexibee/mix.exs
exineris/shp_challenge2021
2a5447af681259d0ea699b670cf079bd31315cd8
[ "Apache-2.0" ]
null
null
null
combo/phxexibee/mix.exs
exineris/shp_challenge2021
2a5447af681259d0ea699b670cf079bd31315cd8
[ "Apache-2.0" ]
null
null
null
combo/phxexibee/mix.exs
exineris/shp_challenge2021
2a5447af681259d0ea699b670cf079bd31315cd8
[ "Apache-2.0" ]
null
null
null
defmodule Phxexibee.MixProject do use Mix.Project def project do [ app: :phxexibee, version: "0.1.0", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Phxexibee.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.5.8"}, {:phoenix_live_view, "~> 0.15.1"}, {:floki, ">= 0.27.0", only: :test}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:phoenix_live_dashboard, "~> 0.4"}, {:telemetry_metrics, "~> 0.4"}, {:telemetry_poller, "~> 0.4"}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to install project dependencies and perform other setup tasks, run: # # $ mix setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ setup: ["deps.get", "cmd npm install --prefix assets"] ] end end
26
84
0.586849
9ee445e538343be9982de32251316e654525a896
1,218
exs
Elixir
test/io/osabie_test.exs
Tux9001/05AB1E
8b28b648961c19217cc8e481714e33a4a16f41c2
[ "MIT" ]
null
null
null
test/io/osabie_test.exs
Tux9001/05AB1E
8b28b648961c19217cc8e481714e33a4a16f41c2
[ "MIT" ]
null
null
null
test/io/osabie_test.exs
Tux9001/05AB1E
8b28b648961c19217cc8e481714e33a4a16f41c2
[ "MIT" ]
null
null
null
defmodule OsabieTest do use ExUnit.Case alias Osabie.CLI import ExUnit.CaptureIO import TestHelper def run_osabie(code, args \\ []) do String.trim_trailing(capture_io(fn -> file_test(fn file -> File.write!(file, code); Osabie.CLI.main([file | args]) end) end), "\n") |> String.split("\n") end test "run normal program" do assert run_osabie("5L") == ["[1, 2, 3, 4, 5]"] end test "run with debug" do assert run_osabie("5L", ["--debug"]) == [ "----------------------------------", "", "Current Command: {:number, \"5\"}", "----------------------------------", "", "Current Command: {:unary_op, \"L\"}", "[1, 2, 3, 4, 5]" ] end test "run with already printed" do assert run_osabie("1,2") == ["1"] end test "run with canvas" do assert run_osabie("5 'a 3Λ") == [ "a ", " a ", " a ", " a ", " a" ] end test "run with canvas on stack" do assert run_osabie("5 'a 3.Λ 11£") == [ "a ", " a " ] end end
25.375
161
0.416256
9ee4550931adb28275d3c2f986210bd56e0bcea0
2,246
exs
Elixir
config/config.exs
char0n/qencode
22751a652e0af229b89e9b70498a0d36761c30e5
[ "BSD-3-Clause" ]
2
2019-07-03T11:51:39.000Z
2019-08-06T15:34:34.000Z
config/config.exs
char0n/qencode
22751a652e0af229b89e9b70498a0d36761c30e5
[ "BSD-3-Clause" ]
5
2019-07-19T17:34:09.000Z
2019-11-04T10:59:11.000Z
config/config.exs
char0n/qencode
22751a652e0af229b89e9b70498a0d36761c30e5
[ "BSD-3-Clause" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.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 :qencode, key: :value # # and access this configuration in your application as: # # Application.get_env(:qencode, :key) # # You can also configure a third-party app: # # config :logger, level: :info # config :qencode, json_library: Jason, api_key: System.get_env("QENCODE_API_KEY"), profiles: System.get_env("QENCODE_PROFILES") config :git_ops, mix_project: Qencode.MixProject, changelog_file: "CHANGELOG.md", repository_url: "https://github.com/char0n/qencode", types: [ # Makes an allowed commit type called `tidbit` that is not # shown in the changelog tidbit: [ hidden?: true ], # Makes an allowed commit type called `important` that gets # a section in the changelog with the header "Important Changes" important: [ header: "Important Changes" ] ], # Instructs the tool to manage your mix version in your `mix.exs` file # See below for more information manage_mix_version?: true, # Instructs the tool to manage the version in your README.md # Pass in `true` to use `"README.md"` or a string to customize manage_readme_version: "README.md" config :logger, backends: [:console], compile_time_purge_matching: [ [level_lower_than: :info] ] config :junit_formatter, report_file: "test-junit-report.xml", print_report_file: true # 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). # # import_config "#{Mix.env()}.exs"
32.550725
73
0.729297
9ee45952ae7535b51117514185834a3f99397da7
1,570
ex
Elixir
lib/token_manager.ex
omnifroodle/astraex
873d5ca985c8387f236c086ffb76780092823e01
[ "Apache-2.0" ]
3
2021-02-16T20:30:52.000Z
2021-08-16T15:02:59.000Z
lib/token_manager.ex
omnifroodle/astraex
873d5ca985c8387f236c086ffb76780092823e01
[ "Apache-2.0" ]
null
null
null
lib/token_manager.ex
omnifroodle/astraex
873d5ca985c8387f236c086ffb76780092823e01
[ "Apache-2.0" ]
null
null
null
defmodule Astra.TokenManager do @moduledoc false use GenServer require Logger @update_interval 1_700_000 def start_link(_opts) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end @doc """ Get Token fetches a security token from Astra for use with other requests. """ def get_token() do GenServer.call(__MODULE__, {:get}) end @impl true def init(:ok) do config = Application.get_all_env(:astra) {:ok, get_current_token(config[:username], config[:password], config[:application_token])} end @impl true def handle_call({:get}, _, token) do {:reply, token, token} end @impl true def handle_cast({:set, new_token}, _token) do {:noreply, new_token} end @impl true def handle_info(:tick, _) do config = Application.get_all_env(:astra) token = get_current_token(config[:username], config[:password], nil) Process.send_after(self(), :tick, @update_interval) {:noreply, token} end #fetch a token from the server and schedule a regular update of the security token def get_current_token(username, password, nil) do Process.send_after(self(), :tick, @update_interval) case Astra.Auth.authorize_user(username, password) do {:ok, %{authToken: token}} -> {:ok, token} other -> Logger.warn("Failed to get Astra token, response was: #{inspect(other)}") {:error, "something went wrong!"} end end #use a static app token, used when app token is provided in the config def get_current_token(_,_,token), do: {:ok, token} end
28.035714
94
0.682166