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 list | 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 list | 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 list | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03b91660a71aaae44f855edafdf063578304a61c | 46,229 | exs | Elixir | lib/iex/test/iex/helpers_test.exs | ChezCrawford/elixir | 2701169b1e5d60da1a4cd71b41866cb29fc36d21 | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/helpers_test.exs | ChezCrawford/elixir | 2701169b1e5d60da1a4cd71b41866cb29fc36d21 | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/helpers_test.exs | ChezCrawford/elixir | 2701169b1e5d60da1a4cd71b41866cb29fc36d21 | [
"Apache-2.0"
] | null | null | null | Code.require_file("../test_helper.exs", __DIR__)
defmodule IEx.HelpersTest do
use IEx.Case
import IEx.Helpers
@compile {:no_warn_undefined, [:sample, Sample, Sample2]}
describe "whereami" do
test "is disabled by default" do
assert capture_iex("whereami()") =~ "Pry session is not currently enabled"
end
test "shows current location for custom envs" do
whereami = capture_iex("whereami()", [], env: %{__ENV__ | line: 3})
assert whereami =~ "test/iex/helpers_test.exs:3"
assert whereami =~ "3: defmodule IEx.HelpersTest do"
end
test "prints message when location is not available" do
whereami = capture_iex("whereami()", [], env: %{__ENV__ | line: 30000})
assert whereami =~ "test/iex/helpers_test.exs:30000"
assert whereami =~ "Could not extract source snippet. Location is not available."
whereami = capture_iex("whereami()", [], env: %{__ENV__ | file: "nofile", line: 1})
assert whereami =~ "nofile:1"
assert whereami =~ "Could not extract source snippet. Location is not available."
end
end
describe "breakpoints" do
setup do
on_exit(fn -> IEx.Pry.remove_breaks() end)
end
test "sets up a breakpoint with capture syntax" do
assert break!(URI.decode_query() / 2) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "sets up a breakpoint with call syntax" do
assert break!(URI.decode_query(_, %{})) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "sets up a breakpoint with guards syntax" do
assert break!(URI.decode_query(_, map) when is_map(map)) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "sets up a breakpoint on the given module" do
assert break!(URI, :decode_query, 2) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "resets breaks on the given ID" do
assert break!(URI, :decode_query, 2) == 1
assert reset_break(1) == :ok
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 0}]
end
test "resets breaks on the given module" do
assert break!(URI, :decode_query, 2) == 1
assert reset_break(URI, :decode_query, 2) == :ok
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 0}]
end
test "removes breaks in the given module" do
assert break!(URI.decode_query() / 2) == 1
assert remove_breaks(URI) == :ok
assert IEx.Pry.breaks() == []
end
test "removes breaks on all modules" do
assert break!(URI.decode_query() / 2) == 1
assert remove_breaks() == :ok
assert IEx.Pry.breaks() == []
end
test "errors when setting up a breakpoint with invalid guard" do
assert_raise CompileError, ~r"cannot find or invoke local is_whatever/1", fn ->
break!(URI.decode_query(_, map) when is_whatever(map))
end
end
test "errors when setting up a break with no beam" do
assert_raise RuntimeError,
"could not set breakpoint, could not find .beam file for IEx.HelpersTest",
fn -> break!(__MODULE__, :setup, 1) end
end
test "errors when setting up a break for unknown function" do
assert_raise RuntimeError,
"could not set breakpoint, unknown function/macro URI.unknown/2",
fn -> break!(URI, :unknown, 2) end
end
test "errors for non-Elixir modules" do
assert_raise RuntimeError,
"could not set breakpoint, module :elixir was not written in Elixir",
fn -> break!(:elixir, :unknown, 2) end
end
test "prints table with breaks" do
break!(URI, :decode_query, 2)
assert capture_io(fn -> breaks() end) == """
ID Module.function/arity Pending stops
---- ----------------------- ---------------
1 URI.decode_query/2 1
"""
assert capture_io(fn -> URI.decode_query("foo=bar", %{}) end) != ""
assert capture_io(fn -> breaks() end) == """
ID Module.function/arity Pending stops
---- ----------------------- ---------------
1 URI.decode_query/2 0
"""
assert capture_io(fn -> URI.decode_query("foo=bar", %{}) end) == ""
assert capture_io(fn -> breaks() end) == """
ID Module.function/arity Pending stops
---- ----------------------- ---------------
1 URI.decode_query/2 0
"""
end
test "does not print table when there are no breaks" do
assert capture_io(fn -> breaks() end) == "No breakpoints set\n"
end
end
describe "open" do
@iex_helpers "iex/lib/iex/helpers.ex"
@elixir_erl "elixir/src/elixir.erl"
@lists_erl "#{:code.lib_dir(:stdlib, :src)}/lists.erl"
@httpc_erl "src/http_client/httpc.erl"
@editor System.get_env("ELIXIR_EDITOR")
test "opens __FILE__ and __LINE__" do
System.put_env("ELIXIR_EDITOR", "echo __LINE__:__FILE__")
assert capture_iex("open({#{inspect(__ENV__.file)}, 3})") |> maybe_trim_quotes() ==
"3:#{__ENV__.file}"
after
System.put_env("ELIXIR_EDITOR", @editor)
end
test "opens Elixir module" do
assert capture_iex("open(IEx.Helpers)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:1$/
end
test "opens function" do
assert capture_iex("open(h)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
end
test "opens function/arity" do
assert capture_iex("open(b/1)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
assert capture_iex("open(h/0)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
end
test "opens module.function" do
assert capture_iex("open(IEx.Helpers.b)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
assert capture_iex("open(IEx.Helpers.h)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
end
test "opens module.function/arity" do
assert capture_iex("open(IEx.Helpers.b/1)") |> maybe_trim_quotes() =~
~r/#{@iex_helpers}:\d+$/
assert capture_iex("open(IEx.Helpers.h/0)") |> maybe_trim_quotes() =~
~r/#{@iex_helpers}:\d+$/
end
test "opens Erlang module" do
assert capture_iex("open(:elixir)") |> maybe_trim_quotes() =~ ~r/#{@elixir_erl}:\d+$/
end
test "opens Erlang module.function" do
assert capture_iex("open(:elixir.start)") |> maybe_trim_quotes() =~ ~r/#{@elixir_erl}:\d+$/
end
test "opens Erlang module.function/arity" do
assert capture_iex("open(:elixir.start/2)") |> maybe_trim_quotes() =~
~r/#{@elixir_erl}:\d+$/
end
# Some installations remove the source file once Erlang is compiled. See #7348.
if File.regular?(@lists_erl) do
test "opens OTP lists module" do
assert capture_iex("open(:lists)") |> maybe_trim_quotes() =~ ~r/#{@lists_erl}:\d+$/
end
test "opens OTP lists module.function" do
assert capture_iex("open(:lists.reverse)") |> maybe_trim_quotes() =~
~r/#{@lists_erl}:\d+$/
end
test "opens OTP lists module.function/arity" do
assert capture_iex("open(:lists.reverse/1)") |> maybe_trim_quotes() =~
~r/#{@lists_erl}:\d+$/
end
end
# Some installations remove the source file once Erlang is compiled. See #7348.
if File.regular?(@httpc_erl) do
test "opens OTP httpc module" do
assert capture_iex("open(:httpc)") |> maybe_trim_quotes() =~ ~r/#{@httpc_erl}:\d+$/
end
test "opens OTP httpc module.function" do
assert capture_iex("open(:httpc.request)") |> maybe_trim_quotes() =~
~r/#{@httpc_erl}:\d+$/
end
test "opens OTP httpc module.function/arity" do
assert capture_iex("open(:httpc.request/1)") |> maybe_trim_quotes() =~
~r/#{@httpc_erl}:\d+$/
end
end
test "errors OTP preloaded module" do
assert capture_iex("open(:init)") =~ ~r"(Could not open)|(Invalid arguments)"
end
test "errors if module is not available" do
assert capture_iex("open(:unknown)") == "Could not open: :unknown. Module is not available."
end
test "errors if module.function is not available" do
assert capture_iex("open(:unknown.unknown)") ==
"Could not open: :unknown.unknown. Module is not available."
assert capture_iex("open(:elixir.unknown)") ==
"Could not open: :elixir.unknown. Function/macro is not available."
assert capture_iex("open(:lists.unknown)") ==
"Could not open: :lists.unknown. Function/macro is not available."
assert capture_iex("open(:httpc.unknown)") ==
"Could not open: :httpc.unknown. Function/macro is not available."
end
test "errors if module.function/arity is not available" do
assert capture_iex("open(:unknown.start/10)") ==
"Could not open: :unknown.start/10. Module is not available."
assert capture_iex("open(:elixir.start/10)") ==
"Could not open: :elixir.start/10. Function/macro is not available."
assert capture_iex("open(:lists.reverse/10)") ==
"Could not open: :lists.reverse/10. Function/macro is not available."
assert capture_iex("open(:httpc.request/10)") ==
"Could not open: :httpc.request/10. Function/macro is not available."
end
test "errors if module is in-memory" do
assert capture_iex("defmodule Foo, do: nil ; open(Foo)") =~
~r"Invalid arguments for open helper:"
after
cleanup_modules([Foo])
end
test "opens the current pry location" do
assert capture_iex("open()", [], env: %{__ENV__ | line: 3}) |> maybe_trim_quotes() ==
"#{__ENV__.file}:3"
end
test "errors if prying is not available" do
assert capture_iex("open()") == "Pry session is not currently enabled"
end
test "opens given {file, line}" do
assert capture_iex("open({#{inspect(__ENV__.file)}, 3})") |> maybe_trim_quotes() ==
"#{__ENV__.file}:3"
end
test "errors when given {file, line} is not available" do
assert capture_iex("open({~s[foo], 3})") ==
"Could not open: \"foo\". File is not available."
end
defp maybe_trim_quotes(string) do
case :os.type() do
{:win32, _} -> String.replace(string, "\"", "")
_ -> string
end
end
end
describe "clear" do
test "clear the screen with ansi" do
Application.put_env(:elixir, :ansi_enabled, true)
assert capture_iex("clear()") == "\e[H\e[2J"
Application.put_env(:elixir, :ansi_enabled, false)
assert capture_iex("clear()") =~
"Cannot clear the screen because ANSI escape codes are not enabled on this shell"
after
Application.delete_env(:elixir, :ansi_enabled)
end
end
describe "runtime_info" do
test "shows VM information" do
assert "\n## System and architecture" <> _ = capture_io(fn -> runtime_info() end)
end
end
describe "h" do
test "shows help" do
help = capture_iex("h()")
assert help =~ "IEx.Helpers"
assert help =~ "Welcome to Interactive Elixir"
end
test "prints non-Elixir module specs" do
assert capture_io(fn -> h(:timer.nonexistent_function()) end) ==
":timer was not compiled with docs\n"
assert capture_io(fn -> h(:timer.nonexistent_function() / 1) end) ==
":timer was not compiled with docs\n"
assert capture_io(fn -> h(:erlang.trace_pattern()) end) ==
":erlang was not compiled with docs\n"
assert capture_io(fn -> h(:erlang.trace_pattern() / 2) end) ==
":erlang was not compiled with docs\n"
assert capture_io(fn -> h(:timer.sleep() / 1) end) == """
:timer.sleep/1
@spec sleep(time) :: :ok when time: timeout()
Module was compiled without docs. Showing only specs.
"""
end
test "prints module documentation" do
assert "\n IEx.Helpers\n\nWelcome to Interactive Elixir" <>
_ = capture_io(fn -> h(IEx.Helpers) end)
assert capture_io(fn -> h(:whatever) end) ==
"Could not load module :whatever, got: nofile\n"
assert capture_io(fn -> h(:lists) end) ==
":lists was not compiled with docs\n"
end
test "prints function/macro documentation" do
pwd_h = """
def pwd()
Prints the current working directory.
"""
c_h = """
def c(files, path \\\\ :in_memory)
Compiles the given files.
"""
eq_h = """
def left == right
@spec term() == term() :: boolean()
guard: true
Returns `true` if the two terms are equal.
"""
def_h = """
defmacro def(call, expr \\\\ nil)
Defines a public function with the given name and body.
"""
assert capture_io(fn -> h(IEx.Helpers.pwd() / 0) end) =~ pwd_h
assert capture_io(fn -> h(IEx.Helpers.c() / 2) end) =~ c_h
assert capture_io(fn -> h(== / 2) end) =~ eq_h
assert capture_io(fn -> h(def / 2) end) =~ def_h
assert capture_io(fn -> h(IEx.Helpers.c() / 1) end) =~ c_h
assert capture_io(fn -> h(pwd) end) =~ pwd_h
assert capture_io(fn -> h(def) end) =~ def_h
end
test "prints __info__ documentation" do
h_output_module = capture_io(fn -> h(Module.__info__()) end)
assert capture_io(fn -> h(Module.UnlikelyTo.Exist.__info__()) end) == h_output_module
assert capture_io(fn -> h(Module.UnlikelyTo.Exist.__info__() / 1) end) == h_output_module
assert capture_io(fn -> h(__info__) end) ==
"No documentation for Kernel.__info__ was found\n"
end
test "prints documentation metadata" do
content = """
defmodule Sample do
@moduledoc "Sample module"
@moduledoc deprecated: "Use OtherSample", since: "1.2.3", authors: ["Alice", "Bob"]
@doc "With metadata"
@doc since: "1.2.3", author: "Alice"
@deprecated "Use OtherSample.with_metadata/0"
def with_metadata(), do: 0
@doc "Without metadata"
def without_metadata(), do: 1
end
"""
filename = "sample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [Sample]
assert capture_io(fn -> h(Sample) end) == """
Sample
deprecated: Use OtherSample
since: 1.2.3
Sample module
"""
assert capture_io(fn -> h(Sample.with_metadata()) end) == """
def with_metadata()
deprecated: Use OtherSample.with_metadata/0
since: 1.2.3
With metadata
"""
assert capture_io(fn -> h(Sample.without_metadata()) end) == """
def without_metadata()
Without metadata
"""
end)
after
cleanup_modules([Sample])
end
test "considers underscored functions without docs by default" do
content = """
defmodule Sample do
def __foo__(), do: 0
@doc "Bar doc"
def __bar__(), do: 1
end
"""
filename = "sample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [Sample]
assert capture_io(fn -> h(Sample.__foo__()) end) ==
"No documentation for Sample.__foo__ was found\n"
assert capture_io(fn -> h(Sample.__bar__()) end) == """
def __bar__()
Bar doc
"""
assert capture_io(fn -> h(Sample.__foo__() / 0) end) ==
"No documentation for Sample.__foo__/0 was found\n"
assert capture_io(fn -> h(Sample.__bar__() / 0) end) == """
def __bar__()
Bar doc
"""
end)
after
cleanup_modules([Sample])
end
test "prints callback documentation when function docs are not available" do
behaviour = """
defmodule MyBehaviour do
@doc "Docs for MyBehaviour.first"
@callback first(integer) :: integer
@callback second(integer) :: integer
@callback second(integer, integer) :: integer
end
"""
impl = """
defmodule Impl do
@behaviour MyBehaviour
def first(0), do: 0
@doc "Docs for Impl.second/1"
def second(0), do: 0
@doc "Docs for Impl.second/2"
def second(0, 0), do: 0
end
"""
files = ["my_behaviour.ex", "impl.ex"]
with_file(files, [behaviour, impl], fn ->
assert c(files, ".") |> Enum.sort() == [Impl, MyBehaviour]
assert capture_io(fn -> h(Impl.first() / 1) end) == """
@callback first(integer()) :: integer()
Docs for MyBehaviour.first
"""
assert capture_io(fn -> h(Impl.second() / 1) end) == """
def second(int)
Docs for Impl.second/1
"""
assert capture_io(fn -> h(Impl.second() / 2) end) == """
def second(int1, int2)
Docs for Impl.second/2
"""
assert capture_io(fn -> h(Impl.first()) end) == """
@callback first(integer()) :: integer()
Docs for MyBehaviour.first
"""
assert capture_io(fn -> h(Impl.second()) end) == """
def second(int)
Docs for Impl.second/1
def second(int1, int2)
Docs for Impl.second/2
"""
assert capture_io(fn -> h(MyBehaviour.first()) end) == """
No documentation for function MyBehaviour.first was found, but there is a callback with the same name.
You can view callback documentation with the b/1 helper.\n
"""
assert capture_io(fn -> h(MyBehaviour.second() / 2) end) == """
No documentation for function MyBehaviour.second/2 was found, but there is a callback with the same name.
You can view callback documentation with the b/1 helper.\n
"""
assert capture_io(fn -> h(MyBehaviour.second() / 3) end) ==
"No documentation for MyBehaviour.second/3 was found\n"
end)
after
cleanup_modules([Impl, MyBehaviour])
end
test "prints protocol function docs" do
output = capture_io(fn -> h(Enumerable.reduce()) end)
assert output =~ "@spec reduce(t(), acc(), reducer()) :: result()"
assert output =~ "Reduces the `enumerable`"
end
test "prints documentation for delegates" do
filename = "delegate.ex"
content = """
defmodule Delegator do
defdelegate func1, to: Delegated
@doc "Delegator func2 doc"
defdelegate func2, to: Delegated
end
defmodule Delegated do
def func1, do: 1
def func2, do: 2
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") |> Enum.sort() == [Delegated, Delegator]
assert capture_io(fn -> h(Delegator.func1()) end) == """
def func1()
delegate_to: Delegated.func1/0
"""
assert capture_io(fn -> h(Delegator.func2()) end) == """
def func2()
delegate_to: Delegated.func2/0
Delegator func2 doc
"""
end)
after
cleanup_modules([Delegated, Delegator])
end
test "prints type documentation when function docs are not available" do
content = """
defmodule MyTypes do
@type first() :: any()
@type second(a, b) :: {a, b}
end
"""
filename = "my_types.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [MyTypes]
assert capture_io(fn -> h(MyTypes.first()) end) == """
No documentation for function MyTypes.first was found, but there is a type with the same name.
You can view type documentation with the t/1 helper.\n
"""
assert capture_io(fn -> h(MyTypes.second() / 2) end) == """
No documentation for function MyTypes.second/2 was found, but there is a type with the same name.
You can view type documentation with the t/1 helper.\n
"""
end)
after
cleanup_modules([MyTypes])
end
test "prints modules compiled without docs" do
Code.compiler_options(docs: false)
content = """
defmodule Sample do
@spec foo(any()) :: any()
def foo(arg), do: arg
end
"""
filename = "sample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [Sample]
assert capture_io(fn -> h(Sample.foo() / 1) end) == """
Sample.foo/1
@spec foo(any()) :: any()
Module was compiled without docs. Showing only specs.
"""
end)
after
Code.compiler_options(docs: true)
cleanup_modules([Sample])
end
test "does not print docs for @doc false functions" do
# Here we assert that @doc false works and that we are not leaking
# IEx.Pry internal functions.
assert capture_io(fn -> h(IEx.Pry.child_spec()) end) ==
"No documentation for IEx.Pry.child_spec was found\n"
end
end
describe "b" do
test "lists all callbacks for an Elixir module" do
assert capture_io(fn -> b(Mix) end) == "No callbacks for Mix were found\n"
assert capture_io(fn -> b(NoMix) end) == "Could not load module NoMix, got: nofile\n"
assert capture_io(fn -> b(Mix.SCM) end) =~ """
@callback accepts_options(app :: atom(), opts()) :: opts() | nil
@callback checked_out?(opts()) :: boolean()
"""
end
test "lists all callbacks for an Erlang module" do
output = capture_io(fn -> b(:gen_server) end)
assert output =~ "@callback handle_cast(request :: term(), state :: term()) ::"
assert output =~ "@callback handle_info(info :: :timeout | term(), state :: term()) ::"
assert output =~ "@callback init(args :: term()) ::"
end
test "lists all macrocallbacks for a module" do
filename = "macrocallbacks.ex"
content = """
defmodule Macrocallbacks do
@macrocallback test(:foo) :: integer
@macrocallback test(:bar) :: var when var: integer
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") == [Macrocallbacks]
callbacks = capture_io(fn -> b(Macrocallbacks) end)
assert callbacks =~ "@macrocallback test(:foo) :: integer()\n"
assert callbacks =~ "@macrocallback test(:bar) :: var when var: integer()\n"
end)
after
cleanup_modules([Macrocallbacks])
end
test "lists all callbacks for a protocol" do
assert capture_io(fn -> b(Enumerable) end) =~ """
@callback count(t()) :: {:ok, non_neg_integer()} | {:error, module()}
@callback member?(t(), term()) :: {:ok, boolean()} | {:error, module()}
@callback reduce(t(), acc(), reducer()) :: result()
"""
end
test "prints protocol function docs" do
output = capture_io(fn -> b(Enumerable.reduce()) end)
assert output =~ "@callback reduce(t(), acc(), reducer()) :: result()"
assert output =~ "Reduces the `enumerable`"
end
test "lists callback with multiple clauses" do
filename = "multiple_clauses_callback.ex"
content = """
defmodule MultipleClauseCallback do
@doc "callback"
@callback test(:foo) :: integer
@callback test(:bar) :: [integer]
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") == [MultipleClauseCallback]
assert capture_io(fn -> b(MultipleClauseCallback) end) =~ """
@callback test(:foo) :: integer()
@callback test(:bar) :: [integer()]
"""
assert capture_io(fn -> b(MultipleClauseCallback.test()) end) =~ """
@callback test(:foo) :: integer()
@callback test(:bar) :: [integer()]
callback
"""
end)
after
cleanup_modules([MultipleClauseCallback])
end
test "prints callback documentation" do
assert capture_io(fn -> b(Mix.Task.stop()) end) ==
"No documentation for Mix.Task.stop was found\n"
assert capture_io(fn -> b(Mix.Task.run()) end) =~
"@callback run(command_line_args :: [binary()]) :: any()\n\nA task needs to implement `run`"
assert capture_io(fn -> b(NoMix.run()) end) == "Could not load module NoMix, got: nofile\n"
assert capture_io(fn -> b(Exception.message() / 1) end) ==
"@callback message(t()) :: String.t()\n\n"
assert capture_io(fn -> b(:gen_server.handle_cast() / 2) end) =~
"@callback handle_cast(request :: term(), state :: term()) ::"
end
test "prints callback documentation metadata" do
filename = "callback_with_metadata.ex"
content = """
defmodule CallbackWithMetadata do
@doc "callback"
@doc since: "1.2.3", deprecated: "Use handle_test/1", purpose: :test
@callback test(:foo) :: integer
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") == [CallbackWithMetadata]
assert capture_io(fn -> b(CallbackWithMetadata.test()) end) == """
@callback test(:foo) :: integer()
deprecated: Use handle_test/1
since: 1.2.3
callback
"""
end)
after
cleanup_modules([CallbackWithMetadata])
end
test "prints optional callback" do
filename = "optional_callbacks.ex"
content = """
defmodule OptionalCallbacks do
@doc "callback"
@callback optional_callback(:foo) :: integer
@macrocallback optional_macrocallback(:bar) :: atom
@optional_callbacks optional_callback: 1, optional_macrocallback: 1
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") == [OptionalCallbacks]
assert capture_io(fn -> b(OptionalCallbacks) end) =~ """
@callback optional_callback(:foo) :: integer()
@macrocallback optional_macrocallback(:bar) :: atom()
@optional_callbacks [optional_callback: 1, optional_macrocallback: 1]
"""
end)
after
cleanup_modules([OptionalCallbacks])
end
test "does not print docs for @doc false callbacks" do
filename = "hidden_callbacks.ex"
content = """
defmodule HiddenCallbacks do
@doc false
@callback hidden_callback() :: integer
@doc false
@macrocallback hidden_macrocallback() :: integer
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") == [HiddenCallbacks]
assert capture_io(fn -> b(HiddenCallbacks) end) =~
"No callbacks for HiddenCallbacks were found\n"
end)
after
cleanup_modules([HiddenCallbacks])
end
end
describe "t" do
test "prints when there is no type information or the type is private" do
assert capture_io(fn -> t(IEx) end) == "No type information for IEx was found\n"
assert capture_io(fn -> t(Enum.doesnt_exist()) end) ==
"No type information for Enum.doesnt_exist was found or " <>
"Enum.doesnt_exist is private\n"
contents = """
defmodule TypeSample do
@type public_so_t_doesnt_warn() :: t()
@typep t() :: term()
end
"""
filename = "typesample.ex"
with_file(filename, contents, fn ->
assert c(filename, ".") == [TypeSample]
assert capture_io(fn -> t(TypeSample.t() / 0) end) ==
"No type information for TypeSample.t was found or TypeSample.t is private\n"
end)
after
cleanup_modules([TypeSample])
end
test "prints all types in module" do
# Test that it shows at least two types
assert Enum.count(capture_io(fn -> t(Enum) end) |> String.split("\n"), fn line ->
String.starts_with?(line, "@type")
end) >= 2
end
test "prints private types" do
assert capture_io(fn -> t(Date.Range) end) =~ "@typep iso_days"
end
test "prints type information" do
assert "@type t() ::" <> _ = capture_io(fn -> t(Enum.t()) end)
assert capture_io(fn -> t(Enum.t()) end) == capture_io(fn -> t(Enum.t() / 0) end)
assert "@type child_spec() ::" <> _ = capture_io(fn -> t(:supervisor.child_spec()) end)
assert capture_io(fn -> t(URI.t()) end) == capture_io(fn -> t(URI.t() / 0) end)
end
test "sorts types alphabetically" do
unsorted =
capture_io(fn -> t(Enum) end)
|> String.split("\n")
|> Enum.reject(&(&1 == ""))
|> Enum.map(&String.replace(&1, ~r/@(type|opaque) /, ""))
assert unsorted == Enum.sort(unsorted)
end
test "prints type documentation" do
content = """
defmodule TypeSample do
@typedoc "An ID with description."
@type id_with_desc :: {number, String.t}
end
"""
filename = "typesample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [TypeSample]
assert capture_io(fn -> t(TypeSample.id_with_desc() / 0) end) == """
@type id_with_desc() :: {number(), String.t()}
An ID with description.
"""
assert capture_io(fn -> t(TypeSample.id_with_desc()) end) == """
@type id_with_desc() :: {number(), String.t()}
An ID with description.
"""
end)
after
cleanup_modules([TypeSample])
end
test "prints type documentation metadata" do
content = """
defmodule TypeSample do
@typedoc "An ID with description."
@typedoc since: "1.2.3", deprecated: "Use t/0", purpose: :test
@type id_with_desc :: {number, String.t}
end
"""
filename = "typesample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [TypeSample]
assert capture_io(fn -> t(TypeSample.id_with_desc()) end) == """
@type id_with_desc() :: {number(), String.t()}
deprecated: Use t/0
since: 1.2.3
An ID with description.
"""
end)
after
cleanup_modules([TypeSample])
end
end
describe "v" do
test "returns history" do
assert "** (RuntimeError) v(0) is out of bounds" <> _ = capture_iex("v(0)")
assert "** (RuntimeError) v(1) is out of bounds" <> _ = capture_iex("v(1)")
assert "** (RuntimeError) v(-1) is out of bounds" <> _ = capture_iex("v(-1)")
assert capture_iex("1\n2\nv(2)") == "1\n2\n2"
assert capture_iex("1\n2\nv(2)") == capture_iex("1\n2\nv(-1)")
assert capture_iex("1\n2\nv(2)") == capture_iex("1\n2\nv()")
end
end
describe "flush" do
test "flushes messages" do
assert capture_io(fn ->
send(self(), :hello)
flush()
end) == ":hello\n"
end
end
describe "pwd" do
test "prints the working directory" do
File.cd!(iex_path(), fn ->
assert capture_io(fn -> pwd() end) =~ ~r"lib[\\/]iex\n$"
end)
end
end
describe "ls" do
test "lists the current directory" do
File.cd!(iex_path(), fn ->
paths =
capture_io(fn -> ls() end)
|> String.split()
|> Enum.map(&String.trim/1)
assert "ebin" in paths
assert "mix.exs" in paths
end)
end
test "lists the given directory" do
assert capture_io(fn -> ls("~") end) == capture_io(fn -> ls(System.user_home()) end)
end
end
describe "exports" do
test "prints module exports" do
exports = capture_io(fn -> exports(IEx.Autocomplete) end)
assert exports == "expand/1 expand/2 exports/1 remsh/1 \n"
end
end
describe "import_file" do
test "imports a file" do
with_file("dot-iex", "variable = :hello\nimport IO", fn ->
capture_io(:stderr, fn ->
assert "** (CompileError) iex:1: undefined function variable/0" <> _ =
capture_iex("variable")
end)
assert "** (CompileError) iex:1: undefined function puts/1" <> _ =
capture_iex("puts \"hi\"")
assert capture_iex("import_file \"dot-iex\"\nvariable\nputs \"hi\"") ==
"IO\n:hello\nhi\n:ok"
end)
end
test "imports a file that imports another file" do
dot = "parent = true\nimport_file \"dot-iex-1\""
dot_1 = "variable = :hello\nimport IO"
with_file(["dot-iex", "dot-iex-1"], [dot, dot_1], fn ->
capture_io(:stderr, fn ->
assert "** (CompileError) iex:1: undefined function parent/0" <> _ =
capture_iex("parent")
end)
assert "** (CompileError) iex:1: undefined function puts/1" <> _ =
capture_iex("puts \"hi\"")
assert capture_iex("import_file \"dot-iex\"\nvariable\nputs \"hi\"\nparent") ==
"IO\n:hello\nhi\n:ok\ntrue"
end)
end
test "raises if file is missing" do
failing = capture_iex("import_file \"nonexistent\"")
assert "** (File.Error) could not read file" <> _ = failing
assert failing =~ "no such file or directory"
end
test "does not raise if file is missing and using import_file_if_available" do
assert "nil" == capture_iex("import_file_if_available \"nonexistent\"")
end
test "circular imports" do
dot_1 = "import_file \"dot-iex-2\""
dot_2 = "import_file \"dot-iex-1\""
with_file(["dot-iex-1", "dot-iex-2"], [dot_1, dot_2], fn ->
assert capture_io(:stderr, fn ->
assert capture_iex(":ok", [], dot_iex_path: "dot-iex-1") == ":ok"
end) =~ "dot-iex-2 was already imported, skipping circular file imports"
end)
end
end
describe "import_if_available" do
test "imports a module only if available" do
assert "nil" == capture_iex("import_if_available NoSuchModule")
assert "[1, 2, 3]" == capture_iex("import_if_available Integer; digits 123")
assert "[1, 2, 3]" ==
capture_iex("import_if_available Integer, only: [digits: 1]; digits 123")
end
end
describe "use_if_available" do
test "uses a module only if available" do
assert "nil" == capture_iex("use_if_available NoSuchModule")
assert "1" == capture_iex("use_if_available Bitwise; 1 &&& 1")
assert "1" == capture_iex("use_if_available Bitwise, only_operators: true; 1 &&& 1")
end
end
describe "c" do
test "compiles a file" do
assert_raise UndefinedFunctionError, ~r"function Sample\.run/0 is undefined", fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert c(Path.expand(filename)) == [Sample]
refute File.exists?("Elixir.Sample.beam")
assert Sample.run() == :run
end)
after
cleanup_modules([Sample])
end
test "handles errors" do
ExUnit.CaptureIO.capture_io(fn ->
with_file("sample.ex", "raise \"oops\"", fn ->
assert_raise CompileError, fn -> c("sample.ex") end
end)
end)
end
test "compiles a file with multiple modules " do
assert_raise UndefinedFunctionError, ~r"function Sample.run/0 is undefined", fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code() <> "\n" <> another_test_module(), fn ->
assert c(filename) |> Enum.sort() == [Sample, Sample2]
assert Sample.run() == :run
assert Sample2.hello() == :world
end)
after
cleanup_modules([Sample, Sample2])
end
test "compiles multiple modules" do
assert_raise UndefinedFunctionError, ~r"function Sample.run/0 is undefined", fn ->
Sample.run()
end
filenames = ["sample1.ex", "sample2.ex"]
with_file(filenames, [test_module_code(), another_test_module()], fn ->
assert c(filenames) |> Enum.sort() == [Sample, Sample2]
assert Sample.run() == :run
assert Sample2.hello() == :world
end)
after
cleanup_modules([Sample, Sample2])
end
test "compiles Erlang modules" do
assert_raise UndefinedFunctionError, ~r"function :sample.hello/0 is undefined", fn ->
:sample.hello()
end
filename = "sample.erl"
with_file(filename, erlang_module_code(), fn ->
assert c(filename) == [:sample]
assert :sample.hello() == :world
refute File.exists?("sample.beam")
end)
after
cleanup_modules([:sample])
end
test "skips unknown files" do
assert_raise UndefinedFunctionError, ~r"function :sample.hello/0 is undefined", fn ->
:sample.hello()
end
filenames = ["sample.erl", "not_found.ex", "sample2.ex"]
with_file(filenames, [erlang_module_code(), "", another_test_module()], fn ->
assert c(filenames) |> Enum.sort() == [Sample2, :sample]
assert :sample.hello() == :world
assert Sample2.hello() == :world
end)
after
cleanup_modules([:sample, Sample2])
end
test "compiles file in path" do
assert_raise UndefinedFunctionError, ~r"function Sample\.run/0 is undefined", fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert c(filename, ".") == [Sample]
assert File.exists?("Elixir.Sample.beam")
assert Sample.run() == :run
end)
after
cleanup_modules([Sample])
end
end
describe "l" do
test "returns error tuple for nonexistent modules" do
assert l(:nonexistent_module) == {:error, :nofile}
end
test "loads a given module" do
assert_raise UndefinedFunctionError,
~r"function Sample.run/0 is undefined",
fn -> Sample.run() end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert c(filename, ".") == [Sample]
assert Sample.run() == :run
File.write!(filename, "defmodule Sample do end")
elixirc(["sample.ex"])
assert l(Sample) == {:module, Sample}
assert_raise UndefinedFunctionError,
~r"function Sample.run/0 is undefined",
fn -> Sample.run() end
end)
after
# Clean up the old version left over after l()
cleanup_modules([Sample])
end
end
describe "nl" do
@tag :capture_log
test "loads a given module on the given nodes" do
assert nl([node()], :lists) == {:ok, [{:nonode@nohost, :error, :sticky_directory}]}
assert nl(:nonexistent_module) == {:error, :nofile}
assert nl([:nosuchnode@badhost], Enum) == {:ok, [{:nosuchnode@badhost, :badrpc, :nodedown}]}
assert nl([node()], Enum) == {:ok, [{:nonode@nohost, :loaded, Enum}]}
end
end
describe "r" do
test "raises when reloading a nonexistent module" do
assert_raise ArgumentError, "could not load nor find module: :nonexistent_module", fn ->
r(:nonexistent_module)
end
end
test "reloads Elixir modules" do
message = ~r"function Sample.run/0 is undefined \(module Sample is not available\)"
assert_raise UndefinedFunctionError, message, fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert capture_io(:stderr, fn ->
assert c(filename, ".") == [Sample]
assert Sample.run() == :run
File.write!(filename, "defmodule Sample do end")
assert {:reloaded, Sample, [Sample]} = r(Sample)
message = "function Sample.run/0 is undefined or private"
assert_raise UndefinedFunctionError, message, fn ->
Sample.run()
end
end) =~
"redefining module Sample (current version loaded from ./Elixir.Sample.beam)"
end)
after
# Clean up old version produced by the r helper
cleanup_modules([Sample])
end
test "reloads Erlang modules" do
assert_raise UndefinedFunctionError, ~r"function :sample.hello/0 is undefined", fn ->
:sample.hello()
end
filename = "sample.erl"
with_file(filename, erlang_module_code(), fn ->
assert c(filename, ".") == [:sample]
assert :sample.hello() == :world
File.write!(filename, other_erlang_module_code())
assert {:reloaded, :sample, [:sample]} = r(:sample)
assert :sample.hello() == :bye
end)
after
cleanup_modules([:sample])
end
end
describe "pid/1,3" do
test "builds a PID from string" do
assert inspect(pid("0.32767.3276")) == "#PID<0.32767.3276>"
assert inspect(pid("0.5.6")) == "#PID<0.5.6>"
assert_raise ArgumentError, fn ->
pid("0.6.-6")
end
end
test "builds a PID from integers" do
assert inspect(pid(0, 32767, 3276)) == "#PID<0.32767.3276>"
assert inspect(pid(0, 5, 6)) == "#PID<0.5.6>"
assert_raise FunctionClauseError, fn ->
pid(0, 6, -6)
end
end
end
describe "port" do
test "builds a port from string" do
assert inspect(port("0.8080")) == "#Port<0.8080>"
assert inspect(port("0.0")) == "#Port<0.0>"
assert_raise ArgumentError, fn ->
port("0.-6")
end
end
test "builds a port from integers" do
assert inspect(port(0, 8080)) == "#Port<0.8080>"
assert inspect(port(0, 0)) == "#Port<0.0>"
assert_raise FunctionClauseError, fn ->
port(-1, -6)
end
end
end
describe "ref" do
test "builds a ref from string" do
ref = make_ref()
[_, inner, _] = String.split(inspect(ref), ["<", ">"])
assert ref(inner) == ref
assert_raise ArgumentError, fn ->
ref("0.6.6.-6")
end
end
test "builds a ref from integers" do
ref = make_ref()
[_, inner, _] = String.split(inspect(ref), ["<", ">"])
[p1, p2, p3, p4] = inner |> String.split(".") |> Enum.map(&String.to_integer/1)
assert ref(p1, p2, p3, p4) == ref
assert_raise FunctionClauseError, fn ->
ref(0, 6, 6, -6)
end
end
end
describe "i" do
test "prints information about the data type" do
assert capture_io(fn -> i(:ok) end) =~ """
Term
:ok
Data type
Atom
Reference modules
Atom\
"""
end
test "handles functions that don't display result" do
assert capture_io(fn -> i(IEx.dont_display_result()) end) =~ """
Term
:"do not show this result in output"
Data type
Atom
Description
This atom is returned by IEx when a function that should not print its
return value on screen is executed.\
"""
end
defmodule MyIExInfoModule do
defstruct []
defimpl IEx.Info do
def info(_), do: [{"A", "it's A"}, {:b, "it's :b"}, {'c', "it's 'c'"}]
end
end
test "uses the IEx.Info protocol" do
assert capture_io(fn -> i(%MyIExInfoModule{}) end) =~ """
Term
%IEx.HelpersTest.MyIExInfoModule{}
A
it's A
b
it's :b
c
it's 'c'
"""
after
cleanup_modules([MyIExInfoModule])
end
end
defp test_module_code do
"""
defmodule Sample do
def run do
:run
end
end
"""
end
defp another_test_module do
"""
defmodule Sample2 do
def hello do
:world
end
end
"""
end
defp erlang_module_code do
"""
-module(sample).
-export([hello/0]).
hello() -> world.
"""
end
defp other_erlang_module_code do
"""
-module(sample).
-export([hello/0]).
hello() -> bye.
"""
end
defp cleanup_modules(mods) do
Enum.each(mods, fn mod ->
File.rm("#{mod}.beam")
:code.purge(mod)
true = :code.delete(mod)
end)
end
defp with_file(names, codes, fun) when is_list(names) and is_list(codes) do
Enum.each(Enum.zip(names, codes), fn {name, code} ->
File.write!(name, code)
end)
try do
fun.()
after
Enum.each(names, &File.rm/1)
end
end
defp with_file(name, code, fun) do
with_file(List.wrap(name), List.wrap(code), fun)
end
defp elixirc(args) do
executable = Path.expand("../../../../bin/elixirc", __DIR__)
System.cmd("#{executable}#{executable_extension()}", args, stderr_to_stdout: true)
end
defp iex_path do
Path.expand("../..", __DIR__)
end
if match?({:win32, _}, :os.type()) do
defp executable_extension, do: ".bat"
else
defp executable_extension, do: ""
end
end
| 30.433838 | 120 | 0.561833 |
03b91adec2083409ef866b4d73579d05db5216ea | 10,115 | ex | Elixir | clients/android_publisher/lib/google_api/android_publisher/v3/model/subscription_purchase.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v3/model/subscription_purchase.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v3/model/subscription_purchase.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.AndroidPublisher.V3.Model.SubscriptionPurchase do
@moduledoc """
A SubscriptionPurchase resource indicates the status of a user's subscription purchase.
## Attributes
* `acknowledgementState` (*type:* `integer()`, *default:* `nil`) - The acknowledgement state of the subscription product. Possible values are:
- Yet to be acknowledged
- Acknowledged
* `autoRenewing` (*type:* `boolean()`, *default:* `nil`) - Whether the subscription will automatically be renewed when it reaches its current expiry time.
* `autoResumeTimeMillis` (*type:* `String.t`, *default:* `nil`) - Time at which the subscription will be automatically resumed, in milliseconds since the Epoch. Only present if the user has requested to pause the subscription.
* `cancelReason` (*type:* `integer()`, *default:* `nil`) - The reason why a subscription was canceled or is not auto-renewing. Possible values are:
- User canceled the subscription
- Subscription was canceled by the system, for example because of a billing problem
- Subscription was replaced with a new subscription
- Subscription was canceled by the developer
* `cancelSurveyResult` (*type:* `GoogleApi.AndroidPublisher.V3.Model.SubscriptionCancelSurveyResult.t`, *default:* `nil`) - Information provided by the user when they complete the subscription cancellation flow (cancellation reason survey).
* `countryCode` (*type:* `String.t`, *default:* `nil`) - ISO 3166-1 alpha-2 billing country/region code of the user at the time the subscription was granted.
* `developerPayload` (*type:* `String.t`, *default:* `nil`) - A developer-specified string that contains supplemental information about an order.
* `emailAddress` (*type:* `String.t`, *default:* `nil`) - The email address of the user when the subscription was purchased. Only present for purchases made with 'Subscribe with Google'.
* `expiryTimeMillis` (*type:* `String.t`, *default:* `nil`) - Time at which the subscription will expire, in milliseconds since the Epoch.
* `externalAccountId` (*type:* `String.t`, *default:* `nil`) - User account identifier in the third-party service. Only present if account linking happened as part of the subscription purchase flow.
* `familyName` (*type:* `String.t`, *default:* `nil`) - The family name of the user when the subscription was purchased. Only present for purchases made with 'Subscribe with Google'.
* `givenName` (*type:* `String.t`, *default:* `nil`) - The given name of the user when the subscription was purchased. Only present for purchases made with 'Subscribe with Google'.
* `introductoryPriceInfo` (*type:* `GoogleApi.AndroidPublisher.V3.Model.IntroductoryPriceInfo.t`, *default:* `nil`) - Introductory price information of the subscription. This is only present when the subscription was purchased with an introductory price.
This field does not indicate the subscription is currently in introductory price period.
* `kind` (*type:* `String.t`, *default:* `androidpublisher#subscriptionPurchase`) - This kind represents a subscriptionPurchase object in the androidpublisher service.
* `linkedPurchaseToken` (*type:* `String.t`, *default:* `nil`) - The purchase token of the originating purchase if this subscription is one of the following:
- Re-signup of a canceled but non-lapsed subscription
- Upgrade/downgrade from a previous subscription For example, suppose a user originally signs up and you receive purchase token X, then the user cancels and goes through the resignup flow (before their subscription lapses) and you receive purchase token Y, and finally the user upgrades their subscription and you receive purchase token Z. If you call this API with purchase token Z, this field will be set to Y. If you call this API with purchase token Y, this field will be set to X. If you call this API with purchase token X, this field will not be set.
* `orderId` (*type:* `String.t`, *default:* `nil`) - The order id of the latest recurring order associated with the purchase of the subscription.
* `paymentState` (*type:* `integer()`, *default:* `nil`) - The payment state of the subscription. Possible values are:
- Payment pending
- Payment received
- Free trial
- Pending deferred upgrade/downgrade
* `priceAmountMicros` (*type:* `String.t`, *default:* `nil`) - Price of the subscription, not including tax. Price is expressed in micro-units, where 1,000,000 micro-units represents one unit of the currency. For example, if the subscription price is €1.99, price_amount_micros is 1990000.
* `priceChange` (*type:* `GoogleApi.AndroidPublisher.V3.Model.SubscriptionPriceChange.t`, *default:* `nil`) - The latest price change information available. This is present only when there is an upcoming price change for the subscription yet to be applied.
Once the subscription renews with the new price or the subscription is canceled, no price change information will be returned.
* `priceCurrencyCode` (*type:* `String.t`, *default:* `nil`) - ISO 4217 currency code for the subscription price. For example, if the price is specified in British pounds sterling, price_currency_code is "GBP".
* `profileId` (*type:* `String.t`, *default:* `nil`) - The Google profile id of the user when the subscription was purchased. Only present for purchases made with 'Subscribe with Google'.
* `profileName` (*type:* `String.t`, *default:* `nil`) - The profile name of the user when the subscription was purchased. Only present for purchases made with 'Subscribe with Google'.
* `promotionCode` (*type:* `String.t`, *default:* `nil`) - The promotion code applied on this purchase. This field is only set if a vanity code promotion is applied when the subscription was purchased.
* `promotionType` (*type:* `integer()`, *default:* `nil`) - The type of promotion applied on this purchase. This field is only set if a promotion is applied when the subscription was purchased. Possible values are:
- One time code
- Vanity code
* `purchaseType` (*type:* `integer()`, *default:* `nil`) - The type of purchase of the subscription. This field is only set if this purchase was not made using the standard in-app billing flow. Possible values are:
- Test (i.e. purchased from a license testing account)
- Promo (i.e. purchased using a promo code)
* `startTimeMillis` (*type:* `String.t`, *default:* `nil`) - Time at which the subscription was granted, in milliseconds since the Epoch.
* `userCancellationTimeMillis` (*type:* `String.t`, *default:* `nil`) - The time at which the subscription was canceled by the user, in milliseconds since the epoch. Only present if cancelReason is 0.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:acknowledgementState => integer(),
:autoRenewing => boolean(),
:autoResumeTimeMillis => String.t(),
:cancelReason => integer(),
:cancelSurveyResult =>
GoogleApi.AndroidPublisher.V3.Model.SubscriptionCancelSurveyResult.t(),
:countryCode => String.t(),
:developerPayload => String.t(),
:emailAddress => String.t(),
:expiryTimeMillis => String.t(),
:externalAccountId => String.t(),
:familyName => String.t(),
:givenName => String.t(),
:introductoryPriceInfo => GoogleApi.AndroidPublisher.V3.Model.IntroductoryPriceInfo.t(),
:kind => String.t(),
:linkedPurchaseToken => String.t(),
:orderId => String.t(),
:paymentState => integer(),
:priceAmountMicros => String.t(),
:priceChange => GoogleApi.AndroidPublisher.V3.Model.SubscriptionPriceChange.t(),
:priceCurrencyCode => String.t(),
:profileId => String.t(),
:profileName => String.t(),
:promotionCode => String.t(),
:promotionType => integer(),
:purchaseType => integer(),
:startTimeMillis => String.t(),
:userCancellationTimeMillis => String.t()
}
field(:acknowledgementState)
field(:autoRenewing)
field(:autoResumeTimeMillis)
field(:cancelReason)
field(:cancelSurveyResult,
as: GoogleApi.AndroidPublisher.V3.Model.SubscriptionCancelSurveyResult
)
field(:countryCode)
field(:developerPayload)
field(:emailAddress)
field(:expiryTimeMillis)
field(:externalAccountId)
field(:familyName)
field(:givenName)
field(:introductoryPriceInfo, as: GoogleApi.AndroidPublisher.V3.Model.IntroductoryPriceInfo)
field(:kind)
field(:linkedPurchaseToken)
field(:orderId)
field(:paymentState)
field(:priceAmountMicros)
field(:priceChange, as: GoogleApi.AndroidPublisher.V3.Model.SubscriptionPriceChange)
field(:priceCurrencyCode)
field(:profileId)
field(:profileName)
field(:promotionCode)
field(:promotionType)
field(:purchaseType)
field(:startTimeMillis)
field(:userCancellationTimeMillis)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidPublisher.V3.Model.SubscriptionPurchase do
def decode(value, options) do
GoogleApi.AndroidPublisher.V3.Model.SubscriptionPurchase.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidPublisher.V3.Model.SubscriptionPurchase do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 67.433333 | 564 | 0.718735 |
03b92c7f415cc5c47124f1edce534ca6617e16ed | 3,022 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/api/marketplaceprivateauction.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/api/marketplaceprivateauction.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/api/marketplaceprivateauction.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"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 "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 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.AdExchangeBuyer.V14.Api.Marketplaceprivateauction do
@moduledoc """
API calls for all endpoints tagged `Marketplaceprivateauction`.
"""
alias GoogleApi.AdExchangeBuyer.V14.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Update a given private auction proposal
## Parameters
- connection (GoogleApi.AdExchangeBuyer.V14.Connection): Connection to server
- private_auction_id (String.t): The private auction id to be updated.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (UpdatePrivateAuctionProposalRequest):
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec adexchangebuyer_marketplaceprivateauction_updateproposal(
Tesla.Env.client(),
String.t(),
keyword()
) :: {:ok, nil} | {:error, Tesla.Env.t()}
def adexchangebuyer_marketplaceprivateauction_updateproposal(
connection,
private_auction_id,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/privateauction/{privateAuctionId}/updateproposal", %{
"privateAuctionId" => URI.encode_www_form(private_auction_id)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(decode: false)
end
end
| 36.409639 | 170 | 0.694904 |
03b942f27507585d2bd6a2fbfc02946ddbb20f3f | 88 | exs | Elixir | test/web/views/page_view_test.exs | danjac/podcatcher | 748cf7419aebfff9216e7ff9353a5bdb46d3d7b1 | [
"MIT"
] | null | null | null | test/web/views/page_view_test.exs | danjac/podcatcher | 748cf7419aebfff9216e7ff9353a5bdb46d3d7b1 | [
"MIT"
] | null | null | null | test/web/views/page_view_test.exs | danjac/podcatcher | 748cf7419aebfff9216e7ff9353a5bdb46d3d7b1 | [
"MIT"
] | null | null | null | defmodule Podcatcher.Web.PageViewTest do
use Podcatcher.Web.ConnCase, async: true
end
| 22 | 42 | 0.818182 |
03b94ab12306c0f357421f01d05984e327157409 | 329 | ex | Elixir | lib/ex_trello/board_channel/supervisor.ex | KazuCocoa/ex_torello | 187d814094f79a3d99bca2746683804333d40dfe | [
"MIT"
] | null | null | null | lib/ex_trello/board_channel/supervisor.ex | KazuCocoa/ex_torello | 187d814094f79a3d99bca2746683804333d40dfe | [
"MIT"
] | null | null | null | lib/ex_trello/board_channel/supervisor.ex | KazuCocoa/ex_torello | 187d814094f79a3d99bca2746683804333d40dfe | [
"MIT"
] | null | null | null | defmodule ExTrello.BoardChannel.Supervisor do
use Supervisor
def start_link do
Supervisor.start_link(__MODULE__, :ok, name: __MODULE__)
end
def init(:ok) do
children = [
worker(ExTrello.BoardChannel.Monitor, [], restart: :temporary)
]
supervise(children, strategy: :simple_one_for_one)
end
end
| 20.5625 | 68 | 0.714286 |
03b94e17b42efe8bbaf5bfac433d36ff94bd9ee4 | 135 | exs | Elixir | test/aba_cli_test.exs | jscheel42/aba_cli | c66c4921f970dbc8acea4f273d9802c978d2f123 | [
"MIT"
] | null | null | null | test/aba_cli_test.exs | jscheel42/aba_cli | c66c4921f970dbc8acea4f273d9802c978d2f123 | [
"MIT"
] | null | null | null | test/aba_cli_test.exs | jscheel42/aba_cli | c66c4921f970dbc8acea4f273d9802c978d2f123 | [
"MIT"
] | null | null | null | defmodule AbaCLITest do
use ExUnit.Case
doctest AbaCLI
test "greets the world" do
assert AbaCLI.hello() == :world
end
end
| 15 | 35 | 0.703704 |
03b95f76fce304e7e6ae6f165b993439255a805e | 457 | ex | Elixir | web/views/auth_view.ex | andreihod/cryptofolio-api | 063bfcf39a0b334204e6b6ef01990622a1f316af | [
"MIT"
] | 2 | 2017-07-19T17:03:41.000Z | 2017-09-18T12:58:42.000Z | web/views/auth_view.ex | mateusfs/cryptofolio-api | 063bfcf39a0b334204e6b6ef01990622a1f316af | [
"MIT"
] | 7 | 2017-07-18T23:32:45.000Z | 2017-08-18T01:09:11.000Z | web/views/auth_view.ex | mateusfs/cryptofolio-api | 063bfcf39a0b334204e6b6ef01990622a1f316af | [
"MIT"
] | 2 | 2017-08-03T19:55:21.000Z | 2018-07-01T19:54:22.000Z | defmodule Cryptofolio.AuthView do
use Cryptofolio.Web, :view
def render("show.json", %{user: user}) do
%{user: render_one(user, Cryptofolio.UserView, "user.json")}
end
def render("login.json", %{user: user, jwt: jwt, exp: exp}) do
%{
user: render_one(user, Cryptofolio.UserView, "user.json"),
jwt: jwt,
exp: exp
}
end
def render("message.json", %{message: message}) do
%{message: message}
end
end
| 21.761905 | 66 | 0.617068 |
03b96b25909252b69651c399f14fba2f28b4c519 | 17,516 | ex | Elixir | lib/chain.ex | diodechain/diode_server | 1692788bd92cc17654965878abd059d13b5e236c | [
"Apache-2.0"
] | 8 | 2021-03-12T15:35:09.000Z | 2022-03-06T06:37:49.000Z | lib/chain.ex | diodechain/diode_server | 1692788bd92cc17654965878abd059d13b5e236c | [
"Apache-2.0"
] | 2 | 2021-03-12T15:34:40.000Z | 2022-02-03T10:05:01.000Z | lib/chain.ex | diodechain/diode_server | 1692788bd92cc17654965878abd059d13b5e236c | [
"Apache-2.0"
] | 5 | 2021-10-01T12:52:28.000Z | 2022-02-02T19:29:56.000Z | # Diode Server
# Copyright 2021 Diode
# Licensed under the Diode License, Version 1.1
defmodule Chain do
alias Chain.BlockCache, as: Block
alias Chain.Transaction
alias Model.ChainSql
use GenServer
defstruct peak: nil, by_hash: %{}, states: %{}
@type t :: %Chain{
peak: Chain.Block.t(),
by_hash: %{binary() => Chain.Block.t()} | nil,
states: Map.t()
}
@spec start_link(any()) :: :ignore | {:error, any()} | {:ok, pid()}
def start_link(ets_extra) do
case GenServer.start_link(__MODULE__, ets_extra, name: __MODULE__, hibernate_after: 5_000) do
{:ok, pid} ->
Chain.BlockCache.warmup()
Diode.puts("====== Chain ======")
peak = peak_block()
Diode.puts("Peak Block: #{Block.printable(peak)}")
Diode.puts("Final Block: #{Block.printable(Block.last_final(peak))}")
Diode.puts("")
{:ok, pid}
error ->
error
end
end
@spec init(any()) :: {:ok, Chain.t()}
def init(ets_extra) do
ProcessLru.new(:blocks, 10)
EtsLru.new(Chain.Lru, 1000)
_create(ets_extra)
state = load_blocks()
{:ok, state}
end
def window_size() do
100
end
def genesis_hash() do
Block.hash(block(0))
end
def sync() do
call(fn state, _from -> {:reply, :ok, state} end)
end
@doc "Function for unit tests, replaces the current state"
def set_state(state) do
call(fn _state, _from ->
{:reply, :ok, seed(state)}
end)
Chain.Worker.update_sync()
:ok
end
@doc "Function for unit tests, resets state to genesis state"
def reset_state() do
set_state(genesis_state())
Chain.BlockCache.reset()
end
def state() do
state = call(fn state, _from -> {:reply, state, state} end)
by_hash =
Enum.map(blocks(Block.hash(state.peak)), fn block ->
{Block.hash(block), Block.with_state(block)}
end)
|> Map.new()
%{state | by_hash: by_hash}
end
defp call(fun, timeout \\ 25000) do
GenServer.call(__MODULE__, {:call, fun}, timeout)
end
@doc "Gaslimit for block validation and estimation"
def gas_limit() do
20_000_000
end
@doc "GasPrice for block validation and estimation"
def gas_price() do
0
end
@spec average_transaction_gas() :: 200_000
def average_transaction_gas() do
200_000
end
def blocktime_goal() do
15
end
@spec peak() :: integer()
def peak() do
Block.number(peak_block())
end
def set_peak(%Chain.Block{} = block) do
call(
fn state, _from ->
ChainSql.put_peak(block)
ets_prefetch()
{:reply, :ok, %{state | peak: block}}
end,
:infinity
)
end
def epoch() do
case :persistent_term.get(:epoch, nil) do
nil -> Block.epoch(peak_block())
num -> num
end
end
def epoch_length() do
if Diode.dev_mode?() do
4
else
40320
end
end
@spec final_block() :: Chain.Block.t()
def final_block() do
call(fn state, _from -> {:reply, Block.last_final(state.peak), state} end)
end
@spec peak_block() :: Chain.Block.t()
def peak_block() do
call(fn state, _from -> {:reply, state.peak, state} end)
end
@spec peak_state() :: Chain.State.t()
def peak_state() do
Block.state(peak_block())
end
@spec block(number()) :: Chain.Block.t() | nil
def block(n) do
ets_lookup_idx(n, fn -> ChainSql.block(n) end)
end
@spec blockhash(number()) :: binary() | nil
def blockhash(n) do
ets_lookup_hash(n)
end
@doc """
Checks for existance of the given block. This is faster
than using block_by_hash() as it can be fullfilled with
a single ets lookoup and no need to ever fetch the full
block.
"""
@spec block_by_hash?(any()) :: boolean()
def block_by_hash?(nil) do
false
end
def block_by_hash?(hash) do
case ets_lookup(hash, fn -> true end) do
nil -> false
true -> true
%Chain.Block{} -> true
end
end
@spec block_by_hash(any()) :: Chain.Block.t() | nil
def block_by_hash(nil) do
nil
end
def block_by_hash(hash) do
# :erlang.system_flag(:backtrace_depth, 3)
# {:current_stacktrace, what} = :erlang.process_info(self(), :current_stacktrace)
# :io.format("block_by_hash: ~p~n", [what])
Stats.tc(:block_by_hash, fn ->
do_block_by_hash(hash)
end)
end
defp do_block_by_hash(hash) do
ProcessLru.fetch(:blocks, hash, fn ->
ets_lookup(hash, fn ->
Stats.tc(:sql_block_by_hash, fn ->
EtsLru.fetch(Chain.Lru, hash, fn ->
ChainSql.block_by_hash(hash)
end)
end)
end)
end)
end
def block_by_txhash(txhash) do
ChainSql.block_by_txhash(txhash)
end
def transaction(txhash) do
ChainSql.transaction(txhash)
end
# returns all blocks from the current peak
@spec blocks() :: Enumerable.t()
def blocks() do
blocks(Block.hash(peak_block()))
end
# returns all blocks from the given hash
@spec blocks(Chain.Block.t() | binary()) :: Enumerable.t()
def blocks(block_or_hash) do
Stream.unfold([block_or_hash], fn
[] ->
nil
[hash] when is_binary(hash) ->
case ChainSql.blocks_by_hash(hash, 100) do
[] -> nil
[block | rest] -> {block, rest}
end
[block] ->
case ChainSql.blocks_by_hash(Block.hash(block), 100) do
[] -> nil
[block | rest] -> {block, rest}
end
[block | rest] ->
{block, rest}
end)
end
@spec load_blocks() :: Chain.t()
defp load_blocks() do
case ChainSql.peak_block() do
nil ->
genesis_state() |> seed()
block ->
ets_prefetch()
%Chain{peak: block, by_hash: nil}
end
end
defp seed(state) do
ChainSql.truncate_blocks()
Map.values(state.by_hash)
|> Enum.each(fn block ->
ChainSql.put_block(block)
end)
ets_prefetch()
peak = ChainSql.peak_block()
:persistent_term.put(:epoch, Block.epoch(peak))
%Chain{peak: peak, by_hash: nil}
end
defp genesis_state() do
{gen, parent} = genesis()
hash = Block.hash(gen)
phash = Block.hash(parent)
%Chain{
peak: gen,
by_hash: %{hash => gen, phash => parent},
states: %{}
}
end
@spec add_block(any()) :: :added | :stored
def add_block(block, relay \\ true, async \\ false) do
block_hash = Block.hash(block)
true = Block.has_state?(block)
cond do
block_by_hash?(block_hash) ->
IO.puts("Chain.add_block: Skipping existing block (2)")
:added
Block.number(block) < 1 ->
IO.puts("Chain.add_block: Rejected invalid genesis block")
:rejected
true ->
parent_hash = Block.parent_hash(block)
if async == false do
ret = GenServer.call(__MODULE__, {:add_block, block, parent_hash, relay})
if ret == :added do
Chain.Worker.update()
end
ret
else
GenServer.cast(__MODULE__, {:add_block, block, parent_hash, relay})
:unknown
end
end
end
def handle_cast({:add_block, block, parent_hash, relay}, state) do
{:reply, _reply, state} = handle_call({:add_block, block, parent_hash, relay}, nil, state)
{:noreply, state}
end
def handle_call({:add_block, block, parent_hash, relay}, _from, state) do
Stats.tc(:addblock, fn ->
peak = state.peak
peak_hash = Block.hash(peak)
info = Block.printable(block)
cond do
block_by_hash?(Block.hash(block)) ->
IO.puts("Chain.add_block: Skipping existing block (3)")
{:reply, :added, state}
peak_hash != parent_hash and Block.total_difficulty(block) <= Block.total_difficulty(peak) ->
ChainSql.put_new_block(block)
ets_add_alt(block)
IO.puts("Chain.add_block: Extended alt #{info} | (@#{Block.printable(peak)}")
{:reply, :stored, state}
true ->
# Update the state
if peak_hash == parent_hash do
IO.puts("Chain.add_block: Extending main #{info}")
Stats.incr(:block_cnt)
ChainSql.put_block(block)
ets_add(block)
else
IO.puts("Chain.add_block: Replacing main #{info}")
# Recursively makes a new branch normative
ChainSql.put_peak(block)
ets_refetch(block)
end
state = %{state | peak: block}
:persistent_term.put(:epoch, Block.epoch(block))
# Printing some debug output per transaction
if Diode.dev_mode?() do
print_transactions(block)
end
# Remove all transactions that have been processed in this block
# from the outstanding local transaction pool
Chain.Pool.remove_transactions(block)
# Let the ticketstore know the new block
PubSub.publish(:rpc, {:rpc, :block, block})
Debouncer.immediate(TicketStore, fn ->
TicketStore.newblock(block)
end)
if relay do
if Wallet.equal?(Block.miner(block), Diode.miner()) do
Kademlia.broadcast(Block.export(block))
else
Kademlia.relay(Block.export(block))
end
end
{:reply, :added, state}
end
end)
end
def handle_call({:call, fun}, from, state) when is_function(fun) do
fun.(state, from)
end
def export_blocks(filename \\ "block_export.sq3", blocks \\ Chain.blocks()) do
Sqlitex.with_db(filename, fn db ->
Sqlitex.query!(db, """
CREATE TABLE IF NOT EXISTS block_export (
number INTEGER PRIMARY KEY,
data BLOB
) WITHOUT ROWID;
""")
start =
case Sqlitex.query!(db, "SELECT MAX(number) as max FROM block_export") do
[[max: nil]] -> 0
[[max: max]] -> max
end
IO.puts("start: #{start}")
Stream.take_while(blocks, fn block -> Block.number(block) > start end)
|> Stream.chunk_every(100)
|> Task.async_stream(fn blocks ->
IO.puts("Writing block #{Block.number(hd(blocks))}")
Enum.map(blocks, fn block ->
data =
Block.export(block)
|> BertInt.encode!()
[Block.number(block), data]
end)
end)
|> Stream.each(fn {:ok, blocks} ->
:ok = Sqlitex.exec(db, "BEGIN")
Enum.each(blocks, fn [num, data] ->
Sqlitex.query!(
db,
"INSERT INTO block_export (number, data) VALUES(?1, CAST(?2 AS BLOB))",
bind: [num, data]
)
end)
:ok = Sqlitex.exec(db, "COMMIT")
end)
|> Stream.run()
end)
end
defp decode_blocks("") do
[]
end
defp decode_blocks(<<size::unsigned-size(32), block::binary-size(size), rest::binary>>) do
[BertInt.decode!(block)] ++ decode_blocks(rest)
end
def import_blocks(filename) when is_binary(filename) do
File.read!(filename)
|> decode_blocks()
|> import_blocks()
end
def import_blocks(blocks) do
Stream.drop_while(blocks, fn block ->
block_by_hash?(Block.hash(block))
end)
|> do_import_blocks()
end
defp do_import_blocks(blocks) do
ProcessLru.new(:blocks, 10)
prev = Enum.at(blocks, 0) |> Block.parent()
# replay block backup list
lastblock =
Enum.reduce_while(blocks, prev, fn nextblock, prevblock ->
if prevblock != nil do
ProcessLru.put(:blocks, Block.hash(prevblock), prevblock)
end
block_hash = Block.hash(nextblock)
case block_by_hash(block_hash) do
%Chain.Block{} = existing ->
{:cont, existing}
nil ->
ret =
Stats.tc(:vldt, fn ->
Block.validate(nextblock, prevblock)
end)
case ret do
%Chain.Block{} = block ->
add_block(block, false, false)
{:cont, block}
nonblock ->
:io.format("Chain.import_blocks(2): Failed with ~p on: ~p~n", [
nonblock,
Block.printable(nextblock)
])
{:halt, nonblock}
end
end
end)
finish_sync()
lastblock
end
def is_active_sync(register \\ false) do
me = self()
case Process.whereis(:active_sync) do
nil ->
if register do
Process.register(self(), :active_sync)
PubSub.publish(:rpc, {:rpc, :syncing, true})
end
true
^me ->
true
_other ->
false
end
end
def throttle_sync(register \\ false, msg \\ "Syncing") do
# For better resource usage we only let one process sync at full
# throttle
if is_active_sync(register) do
:io.format("#{msg} ...~n")
else
:io.format("#{msg} (background worker) ...~n")
Process.sleep(30_000)
end
end
defp finish_sync() do
Process.unregister(:active_sync)
PubSub.publish(:rpc, {:rpc, :syncing, false})
spawn(fn ->
Model.SyncSql.clean_before(Chain.peak())
Model.SyncSql.free_space()
end)
end
def print_transactions(block) do
for {tx, rcpt} <- Enum.zip([Block.transactions(block), Block.receipts(block)]) do
status =
case rcpt.msg do
:evmc_revert -> ABI.decode_revert(rcpt.evmout)
_ -> {rcpt.msg, rcpt.evmout}
end
Transaction.print(tx)
IO.puts("\tStatus: #{inspect(status)}")
end
IO.puts("")
end
@spec state(number()) :: Chain.State.t()
def state(n) do
Block.state(block(n))
end
def store_file(filename, term, overwrite \\ false) do
if overwrite or not File.exists?(filename) do
content = BertInt.encode!(term)
with :ok <- File.mkdir_p(Path.dirname(filename)) do
tmp = "#{filename}.#{:erlang.phash2(self())}"
File.write!(tmp, content)
File.rename!(tmp, filename)
end
end
term
end
def load_file(filename, default \\ nil) do
case File.read(filename) do
{:ok, content} ->
BertInt.decode_unsafe!(content)
{:error, _} ->
case default do
fun when is_function(fun) -> fun.()
_ -> default
end
end
end
defp genesis() do
{Chain.GenesisFactory.testnet(), Chain.GenesisFactory.testnet_parent()}
end
#######################
# ETS CACHE FUNCTIONS
#######################
@ets_size 500
defp ets_prefetch() do
:persistent_term.put(:placeholder_complete, false)
_clear()
Diode.start_subwork("clearing alt blocks", fn ->
ChainSql.clear_alt_blocks()
# for block <- ChainSql.alt_blocks(), do: ets_add_alt(block)
end)
Diode.start_subwork("preloading hashes", fn ->
for [hash: hash, number: number] <- ChainSql.all_block_hashes() do
ets_add_placeholder(hash, number)
end
:persistent_term.put(:placeholder_complete, true)
end)
Diode.start_subwork("preloading top blocks", fn ->
for block <- ChainSql.top_blocks(@ets_size), do: ets_add(block)
end)
end
# Just fetching blocks of a newly adopted chain branch
defp ets_refetch(nil) do
:ok
end
defp ets_refetch(block) do
block_hash = Block.hash(block)
idx = Block.number(block)
case do_ets_lookup(idx) do
[{^idx, ^block_hash}] ->
:ok
_other ->
ets_add(block)
Block.parent_hash(block)
|> ChainSql.block_by_hash()
|> ets_refetch()
end
end
defp ets_add_alt(block) do
# block = Block.strip_state(block)
_insert(Block.hash(block), true)
end
defp ets_add_placeholder(hash, number) do
_insert(hash, true)
_insert(number, hash)
end
defp placeholder_complete() do
:persistent_term.get(:placeholder_complete, false)
end
defp ets_add(block) do
_insert(Block.hash(block), block)
_insert(Block.number(block), Block.hash(block))
ets_remove_idx(Block.number(block) - @ets_size)
end
defp ets_remove_idx(idx) when idx <= 0 do
:ok
end
defp ets_remove_idx(idx) do
case do_ets_lookup(idx) do
[{^idx, block_hash}] ->
_insert(block_hash, true)
_ ->
nil
end
end
defp ets_lookup_idx(idx, default) when is_integer(idx) do
case do_ets_lookup(idx) do
[] -> default.()
[{^idx, block_hash}] -> block_by_hash(block_hash)
end
end
defp ets_lookup_hash(idx) when is_integer(idx) do
case do_ets_lookup(idx) do
[] -> nil
[{^idx, block_hash}] -> block_hash
end
end
defp ets_lookup(hash, default) when is_binary(hash) do
case do_ets_lookup(hash) do
[] -> if placeholder_complete(), do: nil, else: default.()
[{^hash, true}] -> default.()
[{^hash, block}] -> block
end
end
defp do_ets_lookup(idx) do
_lookup(idx)
# Regularly getting output like this from the code below:
# Slow ets lookup 16896
# Slow ets lookup 10506
# {time, ret} = :timer.tc(fn -> _lookup(idx) end)
# if time > 10000 do
# :io.format("Slow ets lookup ~p~n", [time])
# end
# ret
end
defp _create(ets_extra) do
__MODULE__ =
:ets.new(__MODULE__, [:named_table, :public, {:read_concurrency, true}] ++ ets_extra)
end
defp _lookup(idx), do: :ets.lookup(__MODULE__, idx)
defp _insert(key, value), do: :ets.insert(__MODULE__, {key, value})
defp _clear(), do: :ets.delete_all_objects(__MODULE__)
end
| 24.16 | 101 | 0.589632 |
03b97d3550addb51c1a0dd1f93478addca0e26d7 | 4,267 | exs | Elixir | test/batcher/message_test.exs | ansonlc/bors-ng | 524ae21a471e25c11bf02c87c9ad3f6cf997ac7d | [
"Apache-2.0"
] | null | null | null | test/batcher/message_test.exs | ansonlc/bors-ng | 524ae21a471e25c11bf02c87c9ad3f6cf997ac7d | [
"Apache-2.0"
] | null | null | null | test/batcher/message_test.exs | ansonlc/bors-ng | 524ae21a471e25c11bf02c87c9ad3f6cf997ac7d | [
"Apache-2.0"
] | null | null | null | defmodule BorsNG.Worker.BatcherMessageTest do
use ExUnit.Case, async: true
alias BorsNG.Worker.Batcher.Message
test "generate configuration problem message" do
expected_message = "# Configuration problem\nExample problem"
actual_message = Message.generate_message({:config, "Example problem"})
assert expected_message == actual_message
end
test "generate retry message" do
expected_message = "# Build failed (retrying...)\n * stat"
example_statuses = [%{url: nil, identifier: "stat"}]
actual_message = Message.generate_message({:retrying, example_statuses})
assert expected_message == actual_message
end
test "generate retry message w/ url" do
expected_message = "# Build failed (retrying...)\n * [stat](x)"
example_statuses = [%{url: "x", identifier: "stat"}]
actual_message = Message.generate_message({:retrying, example_statuses})
assert expected_message == actual_message
end
test "generate failure message" do
expected_message = "# Build failed\n * stat"
example_statuses = [%{url: nil, identifier: "stat"}]
actual_message = Message.generate_message({:failed, example_statuses})
assert expected_message == actual_message
end
test "generate success message" do
expected_message = "# Build succeeded\n * stat"
example_statuses = [%{url: nil, identifier: "stat"}]
actual_message = Message.generate_message({:succeeded, example_statuses})
assert expected_message == actual_message
end
test "generate conflict message" do
expected_message = "# Merge conflict"
actual_message = Message.generate_message({:conflict, :failed})
assert expected_message == actual_message
end
test "generate conflict/retry message" do
expected_message = "# Merge conflict (retrying...)"
actual_message = Message.generate_message({:conflict, :retrying})
assert expected_message == actual_message
end
test "generate merged into master message" do
expected_message = "# Pull request successfully merged into master."
actual_message = Message.generate_message({:merged, :squashed, "master"})
assert expected_message == actual_message
end
test "generate commit message" do
expected_message = """
Merge #1 #2
1: Alpha r=r a=lag
a
2: Beta r=s a=leg
b
Co-authored-by: foo
Co-authored-by: bar
"""
patches = [
%{
patch: %{
pr_xref: 1,
title: "Alpha",
body: "a",
author: %{login: "lag"}},
reviewer: "r"},
%{
patch: %{
pr_xref: 2,
title: "Beta",
body: "b",
author: %{login: "leg"}},
reviewer: "s"}]
co_authors = ["foo", "bar"]
actual_message = Message.generate_commit_message(patches, nil, co_authors)
assert expected_message == actual_message
end
test "cut body" do
assert "a" == Message.cut_body("abc", "b")
end
test "cut body with multiple matches" do
assert "aa" == Message.cut_body("aabcbd", "b")
end
test "cut body with no match" do
assert "ac" == Message.cut_body("ac", "b")
end
test "cut body with nil text" do
assert "" == Message.cut_body(nil, "b")
end
test "cut commit message bodies" do
expected_message = """
Merge #1
1: Synchronize background and foreground processing r=bill a=pea
Fixes that annoying bug.
Co-authored-by: foo
"""
title = "Synchronize background and foreground processing"
body = """
Fixes that annoying bug.
<!-- boilerplate follows -->
Thank you for contributing to my awesome OSS project!
To make sure your PR is accepted ASAP, make sure all of this
stuff is done:
- [ ] Run the linter
- [ ] Run any new or changed tests
- [ ] This PR fixes #___ (fill in if it exists)
- [ ] Make sure your commit messages make sense
"""
patches = [
%{
patch: %{
pr_xref: 1,
title: title,
body: body,
author: %{login: "pea"}},
reviewer: "bill"} ]
co_authors = ["foo"]
actual_message = Message.generate_commit_message(
patches,
"\n\n<!-- boilerplate follows -->",
co_authors)
assert expected_message == actual_message
end
end
| 28.446667 | 78 | 0.646356 |
03b9894028b7c2f5c081206c7d8b7f18f4af3f28 | 340 | exs | Elixir | config/test.exs | drewkerrigan/ecto_riak | 5e5e07864adc475d89d46c2469c23ad81201fa1d | [
"Apache-2.0"
] | 3 | 2016-07-28T14:26:38.000Z | 2017-10-24T14:14:37.000Z | config/test.exs | drewkerrigan/ecto_riak | 5e5e07864adc475d89d46c2469c23ad81201fa1d | [
"Apache-2.0"
] | null | null | null | config/test.exs | drewkerrigan/ecto_riak | 5e5e07864adc475d89d46c2469c23ad81201fa1d | [
"Apache-2.0"
] | null | null | null | use Mix.Config
config :ecto, EctoRiak.RiakTSRepo,
adapter: Ecto.Adapters.RiakTS,
pool: [
[host: '127.0.0.1', port: 8087]
]
config :ecto, EctoRiak.RiakKVRepo,
adapter: Ecto.Adapters.RiakKV,
host: "localhost",
port: 8087
config :ecto, EctoRiak.RiakDTRepo,
adapter: Ecto.Adapters.RiakDT,
host: "localhost",
port: 8087
| 18.888889 | 35 | 0.691176 |
03b9b65965cc1a6d27f4d4732fb852ac20833cd6 | 617 | ex | Elixir | lib/utils/map.ex | coletiv/speakeasy | c7a0fe7d88ede6f26eaf0b6d30b8a562dd0a0636 | [
"MIT"
] | null | null | null | lib/utils/map.ex | coletiv/speakeasy | c7a0fe7d88ede6f26eaf0b6d30b8a562dd0a0636 | [
"MIT"
] | null | null | null | lib/utils/map.ex | coletiv/speakeasy | c7a0fe7d88ede6f26eaf0b6d30b8a562dd0a0636 | [
"MIT"
] | null | null | null | defmodule Speakeasy.Utils.Map do
@moduledoc """
Module for help with Map
"""
@doc """
Merge two maps deep
"""
def deep_merge(left, right) do
Map.merge(left, right, &deep_resolve/3)
end
# Key exists in both maps, and both values are maps as well.
# These can be merged recursively.
defp deep_resolve(_key, left = %{}, right = %{}) do
deep_merge(left, right)
end
# Key exists in both maps, but at least one of the values is
# NOT a map. We fall back to standard merge behavior, preferring
# the value on the right.
defp deep_resolve(_key, _left, right) do
right
end
end
| 23.730769 | 66 | 0.670989 |
03b9bea8af440aef7e917200133f104b762e0a98 | 8,302 | ex | Elixir | lib/terrasol/document.ex | mwmiller/terrasol | ea503c008c5b6a80c2fac24acc206ed1d17096a8 | [
"MIT"
] | 4 | 2021-06-27T17:27:33.000Z | 2021-07-25T03:42:07.000Z | lib/terrasol/document.ex | mwmiller/terrasol | ea503c008c5b6a80c2fac24acc206ed1d17096a8 | [
"MIT"
] | null | null | null | lib/terrasol/document.ex | mwmiller/terrasol | ea503c008c5b6a80c2fac24acc206ed1d17096a8 | [
"MIT"
] | null | null | null | defmodule Terrasol.Document do
@nul32 <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0>>
@moduledoc """
Handling of the Earthstar document format and the resulting
`Terrasol.Document.t` structures
"""
@enforce_keys [
:author,
:content,
:contentHash,
:deleteAfter,
:format,
:path,
:signature,
:timestamp,
:workspace
]
@derive Jason.Encoder
defstruct author: "",
content: "",
contentHash: "",
deleteAfter: nil,
format: "es.4",
path: "",
signature: "",
timestamp: 1,
workspace: ""
@typedoc "An Earthstar document"
@type t() :: %__MODULE__{
author: Terrasol.Author.t(),
content: String.t(),
contentHash: String.t(),
deleteAfter: nil | pos_integer(),
format: String.t(),
path: Terrasol.Path.t(),
signature: String.t(),
timestamp: pos_integer(),
workspace: Terrasol.Workspace.t()
}
defp compute_hash(doc) do
Terrasol.bencode(
:crypto.hash(
:sha256,
gather_fields(
doc,
[:author, :contentHash, :deleteAfter, :format, :path, :timestamp, :workspace],
""
)
)
)
end
defp content_hash(doc), do: :crypto.hash(:sha256, doc.content)
@doc """
Build a `Terrasol.Document` from a map containing all or some of the required keys.
This is resolved internally in a deterministic way which is implementation-specific
and should not be depended upon to remain the same between versions.
A `:ttl` key may be used. It will be parsed into a `:deleteAfter` using
the document timestamp and adding `Terrasol.duration_us(ttl)`
The final value is passed through `parse/1` returning as that function does.
"""
def build(map) do
build(map, [
:timestamp,
:ttl,
:deleteAfter,
:format,
:workspace,
:path,
:author,
:content,
:contentHash,
:signature
])
end
defp build(map, []), do: parse(map)
defp build(map, [key | rest]), do: build(val_or_gen(map, key), rest)
defp val_or_gen(map, :ttl) do
case Map.fetch(map, :ttl) do
:error ->
map
{:ok, val} ->
map
|> Map.delete(:ttl)
|> Map.put(:deleteAfter, map.timestamp + Terrasol.duration_us(val))
end
end
defp val_or_gen(map, key) do
case Map.fetch(map, key) do
:error -> Map.put(map, key, default(key, map))
_ -> map
end
end
defp default(:timestamp, _), do: :erlang.system_time(:microsecond)
defp default(:format, _), do: "es.4"
defp default(:workspace, _), do: "+terrasol.scratch"
defp default(:path, map) do
case(Map.fetch(map, :deleteAfter)) do
:error -> "/terrasol/scratch/default.txt"
{:ok, nil} -> "/terrasol/scratch/default.txt"
_ -> "/terrasol/scratch/!default.txt"
end
end
defp default(:author, _), do: Terrasol.Author.build(%{})
defp default(:content, _), do: "Auto-text from Terrasol."
defp default(:contentHash, map), do: map |> content_hash |> Terrasol.bencode()
defp default(:deleteAfter, _), do: nil
defp default(:signature, map) do
{priv, pub} =
case Terrasol.Author.parse(map.author) do
:error -> {@nul32, @nul32}
%Terrasol.Author{privatekey: nil, publickey: pk} -> {@nul32, pk}
%Terrasol.Author{privatekey: sk, publickey: pk} -> {sk, pk}
end
map |> compute_hash |> Ed25519.signature(priv, pub) |> Terrasol.bencode()
end
defp gather_fields(_, [], str), do: str
defp gather_fields(doc, [f | rest], str) do
case Map.fetch!(doc, f) do
nil -> gather_fields(doc, rest, str)
val -> gather_fields(doc, rest, str <> "#{f}\t#{val}\n")
end
end
@doc """
Parse and return a `Terrasol.Document` from a map.
Returns `{:invalid, [error_field]}` on an invalid document
A string document is presumed to be JSON
"""
def parse(document)
def parse(doc) when is_binary(doc) do
try do
doc
|> Jason.decode!(keys: :atoms!)
|> parse()
rescue
_ -> {:error, [:badjson]}
end
end
def parse(%__MODULE__{} = doc) do
parse_fields(
doc,
[
:author,
:content,
:contentHash,
:path,
:deleteAfter,
:format,
:signature,
:timestamp,
:workspace
],
[]
)
end
def parse(%{} = doc) do
struct(__MODULE__, doc) |> parse
end
def parse(_), do: {:error, [:badformat]}
defp parse_fields(doc, [], []), do: doc
defp parse_fields(_, [], errs), do: {:invalid, Enum.sort(errs)}
defp parse_fields(doc, [f | rest], errs) when f == :author do
author = Terrasol.Author.parse(doc.author)
errlist =
case author do
%Terrasol.Author{} -> errs
:error -> [f | errs]
end
parse_fields(%{doc | author: author}, rest, errlist)
end
defp parse_fields(doc, [f | rest], errs) when f == :workspace do
ws = Terrasol.Workspace.parse(doc.workspace)
errlist =
case ws do
%Terrasol.Workspace{} -> errs
:error -> [f | errs]
end
parse_fields(%{doc | workspace: ws}, rest, errlist)
end
defp parse_fields(doc, [f | rest], errs) when f == :path do
path = Terrasol.Path.parse(doc.path)
errlist =
case path do
%Terrasol.Path{} -> errs
:error -> [f | errs]
end
parse_fields(%{doc | path: path}, rest, errlist)
end
defp parse_fields(doc, [f | rest], errs) when f == :format do
errlist =
case doc.format do
"es.4" -> errs
_ -> [f | errs]
end
parse_fields(doc, rest, errlist)
end
@min_ts 10_000_000_000_000
@max_ts 9_007_199_254_740_990
defp parse_fields(doc, [f | rest], errs) when f == :deleteAfter do
# Spec min int or after now from our perspective
min_allowed = Enum.max([@min_ts, :erlang.system_time(:microsecond)])
val = doc.deleteAfter
ephem =
case doc.path do
%Terrasol.Path{ephemeral: val} -> val
_ -> false
end
errlist =
case {is_nil(val), ephem, not is_integer(val) or (val >= min_allowed and val <= @max_ts)} do
{true, true, _} -> [:ephem_delete_mismatch | errs]
{false, false, _} -> [:ephem_delete_mismatch | errs]
{_, _, false} -> [f | errs]
{_, _, true} -> errs
end
parse_fields(doc, rest, errlist)
end
defp parse_fields(doc, [f | rest], errs) when f == :timestamp do
# Spec max int or 10 minutes into the future
max_allowed = Enum.min([@max_ts, :erlang.system_time(:microsecond) + 600_000_000])
val = doc.timestamp
errlist =
case is_integer(val) and val >= @min_ts and val <= max_allowed do
true -> errs
false -> [f | errs]
end
parse_fields(doc, rest, errlist)
end
@max_doc_bytes 4_000_000
defp parse_fields(doc, [f | rest], errs) when f == :content do
val = doc.content
errlist =
case byte_size(val) < @max_doc_bytes and String.valid?(val) do
true -> errs
false -> [f | errs]
end
parse_fields(doc, rest, errlist)
end
defp parse_fields(doc, [f | rest], errs) when f == :contentHash do
computed_hash = content_hash(doc)
published_hash =
case Terrasol.bdecode(doc.contentHash) do
:error -> @nul32
val -> val
end
errlist =
case Equivalex.equal?(computed_hash, published_hash) do
true -> errs
false -> [f | errs]
end
parse_fields(doc, rest, errlist)
end
defp parse_fields(doc, [f | rest], errs) when f == :signature do
sig =
case Terrasol.bdecode(doc.signature) do
:error -> @nul32
val -> val
end
author_pub_key =
case Terrasol.Author.parse(doc.author) do
:error -> @nul32
%Terrasol.Author{publickey: pk} -> pk
end
errlist =
case Ed25519.valid_signature?(sig, compute_hash(doc), author_pub_key) do
true -> errs
false -> [f | errs]
end
parse_fields(doc, rest, errlist)
end
# Skip unimplemented checks
defp parse_fields(doc, [_f | rest], errs), do: parse_fields(doc, rest, errs)
end
| 25.006024 | 98 | 0.581667 |
03b9dacc0328d85917708f2f6c91b9c4d574274c | 2,619 | ex | Elixir | clients/monitoring/lib/google_api/monitoring/v3/model/monitored_resource.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/monitoring/lib/google_api/monitoring/v3/model/monitored_resource.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/monitoring/lib/google_api/monitoring/v3/model/monitored_resource.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.Monitoring.V3.Model.MonitoredResource do
@moduledoc """
An object representing a resource that can be used for monitoring, logging, billing, or other purposes. Examples include virtual machine instances, databases, and storage devices such as disks. The type field identifies a MonitoredResourceDescriptor object that describes the resource's schema. Information in the labels field identifies the actual resource and its attributes according to the schema. For example, a particular Compute Engine VM instance could be represented by the following object, because the MonitoredResourceDescriptor for "gce_instance" has labels "instance_id" and "zone":
{ "type": "gce_instance",
"labels": { "instance_id": "12345678901234",
"zone": "us-central1-a" }}
## Attributes
* `labels` (*type:* `map()`, *default:* `nil`) - Required. Values for all of the labels listed in the associated monitored resource descriptor. For example, Compute Engine VM instances use the labels "project_id", "instance_id", and "zone".
* `type` (*type:* `String.t`, *default:* `nil`) - Required. The monitored resource type. This field must match the type field of a MonitoredResourceDescriptor object. For example, the type of a Compute Engine VM instance is gce_instance. For a list of types, see Monitoring resource types and Logging resource types.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:labels => map(),
:type => String.t()
}
field(:labels, type: :map)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.MonitoredResource do
def decode(value, options) do
GoogleApi.Monitoring.V3.Model.MonitoredResource.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.MonitoredResource do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 48.5 | 598 | 0.74685 |
03ba24bcd8f9d2d8ab0079f3d7cc2c2628d5996e | 1,978 | ex | Elixir | test/support/job_test_helper.ex | carguero/carguero_task_bunny | e6f4346904433a5ffe3b3b256a97f348839ab514 | [
"MIT"
] | 2 | 2020-12-03T18:09:00.000Z | 2021-01-17T22:44:50.000Z | test/support/job_test_helper.ex | carguero/carguero_task_bunny | e6f4346904433a5ffe3b3b256a97f348839ab514 | [
"MIT"
] | null | null | null | test/support/job_test_helper.ex | carguero/carguero_task_bunny | e6f4346904433a5ffe3b3b256a97f348839ab514 | [
"MIT"
] | null | null | null | defmodule CargueroTaskBunny.JobTestHelper do
defmodule Tracer do
def performed(_), do: nil
end
defmodule RetryInterval do
def interval, do: 60_000
end
defmodule TestJob do
use CargueroTaskBunny.Job
def perform(payload) do
Tracer.performed(payload)
if payload["sleep"], do: :timer.sleep(payload["sleep"])
cond do
payload["reject"] -> :reject
payload["fail"] -> :error
true -> :ok
end
end
def retry_interval(_), do: RetryInterval.interval()
def on_reject(body) do
ppid =
body
|> Jason.decode!()
|> get_in(["payload", "ppid"])
ppid &&
ppid |> Base.decode64!() |> :erlang.binary_to_term() |> send(:on_reject_callback_called)
:ok
end
end
def wait_for_perform(number \\ 1) do
performed =
Enum.find_value(
1..100,
fn _ ->
history = :meck.history(Tracer)
if length(history) >= number do
true
else
:timer.sleep(10)
false
end
end || false
)
# wait for the last message handled
:timer.sleep(20)
performed
end
def performed_payloads do
:meck.history(Tracer)
|> Enum.map(fn {_, {_, _, args}, _} -> List.first(args) end)
end
def performed_count do
length(:meck.history(Tracer))
end
def setup do
:meck.new(Tracer)
:meck.expect(Tracer, :performed, fn _ -> nil end)
end
def teardown do
:meck.unload()
end
def wait_for_connection(host) do
Enum.find_value(
1..100,
fn _ ->
case CargueroTaskBunny.Connection.subscribe_connection(host, self()) do
:ok ->
true
_ ->
:timer.sleep(10)
false
end
end || raise("connection process is not up")
)
receive do
{:connected, conn} -> conn
after
1_000 -> raise "failed to connect to #{host}"
end
end
end
| 19.584158 | 96 | 0.561678 |
03ba2afb7644ab2810a9c216f8fec7f046ca82c6 | 1,480 | ex | Elixir | clients/connectors/lib/google_api/connectors/v1/model/secret.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/connectors/lib/google_api/connectors/v1/model/secret.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/connectors/lib/google_api/connectors/v1/model/secret.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.Connectors.V1.Model.Secret do
@moduledoc """
Secret provides a reference to entries in Secret Manager.
## Attributes
* `secretVersion` (*type:* `String.t`, *default:* `nil`) - The resource name of the secret version in the format, format as: `projects/*/secrets/*/versions/*`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:secretVersion => String.t() | nil
}
field(:secretVersion)
end
defimpl Poison.Decoder, for: GoogleApi.Connectors.V1.Model.Secret do
def decode(value, options) do
GoogleApi.Connectors.V1.Model.Secret.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Connectors.V1.Model.Secret do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.489362 | 163 | 0.732432 |
03ba4aa1e419196921849e0f921fd58126d25515 | 1,908 | ex | Elixir | lib/hexpm/accounts/email.ex | hubertpompecki/hexpm | 5cd4208b07a70bf2e1490930bf5d577978793b50 | [
"Apache-2.0"
] | null | null | null | lib/hexpm/accounts/email.ex | hubertpompecki/hexpm | 5cd4208b07a70bf2e1490930bf5d577978793b50 | [
"Apache-2.0"
] | null | null | null | lib/hexpm/accounts/email.ex | hubertpompecki/hexpm | 5cd4208b07a70bf2e1490930bf5d577978793b50 | [
"Apache-2.0"
] | null | null | null | defmodule Hexpm.Accounts.Email do
use Hexpm.Web, :schema
@derive Hexpm.Web.Stale
@email_regex ~r"^.+@.+\..+$"
schema "emails" do
field :email, :string
field :verified, :boolean, default: false
field :primary, :boolean, default: false
field :public, :boolean, default: false
field :gravatar, :boolean, default: false
field :verification_key, :string
belongs_to :user, User
timestamps()
end
def changeset(email, type, params, verified? \\ not Application.get_env(:hexpm, :user_confirm))
def changeset(email, :first, params, verified?) do
changeset(email, :create, params, verified?)
|> put_change(:primary, true)
|> put_change(:public, true)
end
def changeset(email, :create, params, verified?) do
cast(email, params, ~w(email)a)
|> validate_required(~w(email)a)
|> update_change(:email, &String.downcase/1)
|> validate_format(:email, @email_regex)
|> validate_confirmation(:email, message: "does not match email")
|> validate_verified_email_exists(:email, message: "already in use")
|> unique_constraint(:email, name: "emails_email_key")
|> unique_constraint(:email, name: "emails_email_user_key")
|> put_change(:verified, verified?)
|> put_change(:verification_key, Auth.gen_key())
end
def verify?(nil, _key), do: false
def verify?(%Email{verification_key: verification_key}, key), do: verify?(verification_key, key)
def verify?(verification_key, key), do: Hexpm.Utils.secure_check(verification_key, key)
def verify(email) do
change(email, %{verified: true, verification_key: nil})
|> unique_constraint(:email, name: "emails_email_key", message: "already in use")
end
def toggle_flag(email, flag, value) do
change(email, %{flag => value})
end
def order_emails(emails) do
Enum.sort_by(emails, &[not &1.primary, not &1.public, not &1.verified, -&1.id])
end
end
| 32.896552 | 98 | 0.688679 |
03ba6677191ad6a043bb6ab4f92031ed691a5cd8 | 1,992 | ex | Elixir | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/external_protection_level_options.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/external_protection_level_options.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/external_protection_level_options.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"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.CloudKMS.V1.Model.ExternalProtectionLevelOptions do
@moduledoc """
ExternalProtectionLevelOptions stores a group of additional fields for configuring a CryptoKeyVersion that are specific to the EXTERNAL protection level and EXTERNAL_VPC protection levels.
## Attributes
* `ekmConnectionKeyPath` (*type:* `String.t`, *default:* `nil`) - The path to the external key material on the EKM when using EkmConnection e.g., "v0/my/key". Set this field instead of external_key_uri when using an EkmConnection.
* `externalKeyUri` (*type:* `String.t`, *default:* `nil`) - The URI for an external resource that this CryptoKeyVersion represents.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:ekmConnectionKeyPath => String.t() | nil,
:externalKeyUri => String.t() | nil
}
field(:ekmConnectionKeyPath)
field(:externalKeyUri)
end
defimpl Poison.Decoder, for: GoogleApi.CloudKMS.V1.Model.ExternalProtectionLevelOptions do
def decode(value, options) do
GoogleApi.CloudKMS.V1.Model.ExternalProtectionLevelOptions.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudKMS.V1.Model.ExternalProtectionLevelOptions do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.84 | 234 | 0.755522 |
03baac93d3bc9495338c17b07fb6e0ef9a5c4ce1 | 2,196 | exs | Elixir | test/ecto/query/builder/distinct_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | test/ecto/query/builder/distinct_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | test/ecto/query/builder/distinct_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Query.Builder.DistinctTest do
use ExUnit.Case, async: true
import Ecto.Query.Builder.Distinct
doctest Ecto.Query.Builder.Distinct
import Ecto.Query
describe "escape" do
test "handles expressions and params" do
assert {true, %{}} ==
escape(true, [x: 0], __ENV__)
assert {Macro.escape(quote do [asc: &0.y] end), %{}} ==
escape(quote do x.y end, [x: 0], __ENV__)
assert {Macro.escape(quote do [asc: &0.x, asc: &1.y] end), %{}} ==
escape(quote do [x.x, y.y] end, [x: 0, y: 1], __ENV__)
assert {Macro.escape(quote do [asc: &0.x, desc: &1.y] end), %{}} ==
escape(quote do [x.x, desc: y.y] end, [x: 0, y: 1], __ENV__)
import Kernel, except: [>: 2]
assert {Macro.escape(quote do [asc: 1 > 2] end), %{}} ==
escape(quote do 1 > 2 end, [], __ENV__)
end
test "raises on unbound variables" do
assert_raise Ecto.Query.CompileError, ~r"unbound variable `x` in query", fn ->
escape(quote do x.y end, [], __ENV__)
end
end
end
describe "at runtime" do
test "accepts fields" do
key = :title
assert distinct("q", [q], ^key).distinct == distinct("q", [q], [q.title]).distinct
assert distinct("q", [q], [^key]).distinct == distinct("q", [q], [q.title]).distinct
end
test "accepts keyword lists" do
kw = [desc: :title]
assert distinct("q", [q], ^kw).distinct == distinct("q", [q], [desc: q.title]).distinct
end
test "accepts the boolean true" do
bool = true
assert distinct("q", [q], ^bool).distinct == distinct("q", [q], true).distinct
end
test "raises on non-atoms" do
message = "expected a field as an atom, a list or keyword list in `distinct`, got: `\"temp\"`"
assert_raise ArgumentError, message, fn ->
temp = "temp"
distinct("posts", [p], [^temp])
end
end
test "raises non-lists" do
message = "expected a field as an atom, a list or keyword list in `distinct`, got: `\"temp\"`"
assert_raise ArgumentError, message, fn ->
temp = "temp"
distinct("posts", [p], ^temp)
end
end
end
end
| 31.826087 | 100 | 0.572404 |
03babe4d61fbf1ca6cc4be16b2a2770fe82cd7aa | 485 | exs | Elixir | ch01/list_filter/test/list_filter_test.exs | arilsonsouza/rocketseat-ignite-elixir | 93e32d52d589336dfd2d81e755d6dd7f05ee40b8 | [
"MIT"
] | null | null | null | ch01/list_filter/test/list_filter_test.exs | arilsonsouza/rocketseat-ignite-elixir | 93e32d52d589336dfd2d81e755d6dd7f05ee40b8 | [
"MIT"
] | null | null | null | ch01/list_filter/test/list_filter_test.exs | arilsonsouza/rocketseat-ignite-elixir | 93e32d52d589336dfd2d81e755d6dd7f05ee40b8 | [
"MIT"
] | null | null | null | defmodule ListFilterTest do
use ExUnit.Case
describe "call/1" do
test "count the number of odd number for a given list" do
list1 = ["1", "3", "6", "43", "banana", "6", "abc"]
list2 = ["1", "6", "43"]
list3 = ["1"]
assert ListFilter.call(list1) == 3
assert ListFilter.call(list2) == 2
assert ListFilter.call(list3) == 1
end
test "passing an empty list" do
list = []
assert ListFilter.call(list) == 0
end
end
end
| 22.045455 | 61 | 0.56701 |
03bac931587b8a419ad27af768ddfb5fe64baf6e | 433 | exs | Elixir | examples/github/mix.exs | scrogson/revolver | 174f1049ba8beae65e53672b19d526bbba761a6d | [
"Apache-2.0"
] | 9 | 2015-07-26T13:27:16.000Z | 2017-04-02T11:18:46.000Z | examples/github/mix.exs | scrogson/revolver | 174f1049ba8beae65e53672b19d526bbba761a6d | [
"Apache-2.0"
] | 1 | 2016-08-16T02:48:37.000Z | 2016-08-16T03:44:19.000Z | examples/github/mix.exs | scrogson/revolver | 174f1049ba8beae65e53672b19d526bbba761a6d | [
"Apache-2.0"
] | null | null | null | defmodule GitHub.Mixfile do
use Mix.Project
def project do
[app: :github,
version: "0.1.0",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end
def application do
[applications: [:logger, :revolver, :hackney, :poison]]
end
defp deps do
[{:revolver, path: "../.."},
{:hackney, "~> 1.6"},
{:poison, "~> 2.2"}]
end
end
| 18.826087 | 59 | 0.551963 |
03bad3ca62f37522589d99698136ce2b9fa32ab0 | 2,081 | ex | Elixir | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_versioning_v1main_workload_cjis_settings.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_versioning_v1main_workload_cjis_settings.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_versioning_v1main_workload_cjis_settings.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.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadCJISSettings do
@moduledoc """
Settings specific to resources needed for CJIS.
## Attributes
* `kmsSettings` (*type:* `GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadKMSSettings.t`, *default:* `nil`) - Required. Input only. Immutable. Settings used to create a CMEK crypto key.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kmsSettings =>
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadKMSSettings.t()
| nil
}
field(:kmsSettings,
as:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadKMSSettings
)
end
defimpl Poison.Decoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadCJISSettings do
def decode(value, options) do
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadCJISSettings.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsVersioningV1mainWorkloadCJISSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.271186 | 233 | 0.775589 |
03bad544a2ead3dc2d6e9a02be1daa4b4e825403 | 2,182 | exs | Elixir | config/prod.exs | cjonesy/helmsman | c839ce6a961baab7c789879ff52d5fb09d005254 | [
"MIT"
] | 2 | 2017-10-25T14:21:36.000Z | 2018-08-24T17:49:51.000Z | config/prod.exs | cjonesy/helmsman | c839ce6a961baab7c789879ff52d5fb09d005254 | [
"MIT"
] | 4 | 2017-10-18T01:36:16.000Z | 2018-03-20T20:07:41.000Z | config/prod.exs | cjonesy/helmsman | c839ce6a961baab7c789879ff52d5fb09d005254 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we often load configuration from external
# sources, such as your system environment. For this reason,
# you won't find the :http configuration below, but set inside
# HelmsmanWeb.Endpoint.init/2 when load_from_system_env is
# true. Any dynamic configuration should be done there.
#
# Don't forget to configure the url host to something meaningful,
# Phoenix uses this information when generating URLs.
#
# Finally, we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the mix phx.digest task
# which you typically run after static files are built.
config :helmsman, HelmsmanWeb.Endpoint,
load_from_system_env: true,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :helmsman, HelmsmanWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [:inet6,
# port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :helmsman, HelmsmanWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :helmsman, HelmsmanWeb.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
import_config "prod.secret.exs"
| 33.569231 | 67 | 0.722731 |
03bb1ff3036ac48f43f888bea97372b4752a37fc | 2,140 | ex | Elixir | clients/big_query_connection/lib/google_api/big_query_connection/v1beta1/model/set_iam_policy_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/big_query_connection/lib/google_api/big_query_connection/v1beta1/model/set_iam_policy_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/big_query_connection/lib/google_api/big_query_connection/v1beta1/model/set_iam_policy_request.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.BigQueryConnection.V1beta1.Model.SetIamPolicyRequest do
@moduledoc """
Request message for `SetIamPolicy` method.
## Attributes
* `policy` (*type:* `GoogleApi.BigQueryConnection.V1beta1.Model.Policy.t`, *default:* `nil`) - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them.
* `updateMask` (*type:* `String.t`, *default:* `nil`) - OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"`
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:policy => GoogleApi.BigQueryConnection.V1beta1.Model.Policy.t() | nil,
:updateMask => String.t() | nil
}
field(:policy, as: GoogleApi.BigQueryConnection.V1beta1.Model.Policy)
field(:updateMask)
end
defimpl Poison.Decoder, for: GoogleApi.BigQueryConnection.V1beta1.Model.SetIamPolicyRequest do
def decode(value, options) do
GoogleApi.BigQueryConnection.V1beta1.Model.SetIamPolicyRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQueryConnection.V1beta1.Model.SetIamPolicyRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.8 | 323 | 0.749533 |
03bb33bb94d5ce04d320fa08784659d4ef07ff31 | 1,341 | exs | Elixir | mix.exs | gorkemduman/goth | ba0b436eec1f4eb70428c60c273da367c66f675e | [
"MIT"
] | null | null | null | mix.exs | gorkemduman/goth | ba0b436eec1f4eb70428c60c273da367c66f675e | [
"MIT"
] | null | null | null | mix.exs | gorkemduman/goth | ba0b436eec1f4eb70428c60c273da367c66f675e | [
"MIT"
] | null | null | null | defmodule Goth.Mixfile do
use Mix.Project
@version "1.3.0-rc.2"
@source_url "https://github.com/peburrows/goth"
def project do
[
app: :goth,
version: @version,
package: package(),
elixirc_paths: elixirc_paths(Mix.env()),
elixir: "~> 1.10",
source_url: @source_url,
name: "Goth",
description: description(),
docs: [source_ref: "v#{@version}", main: "readme", extras: ["README.md"]],
deps: deps()
]
end
def application do
[
mod: {Goth.Application, []},
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:jose, "~> 1.10"},
{:jason, "~> 1.1"},
{:hackney, "~> 1.0", optional: true},
{:bypass, "~> 2.1", only: :test},
{:mix_test_watch, "~> 0.2", only: :dev},
{:ex_doc, "~> 0.19", only: :dev},
{:credo, "~> 0.8", only: [:test, :dev]},
{:dialyxir, "~> 0.5", only: [:dev], runtime: false}
]
end
defp description do
"""
A simple library to generate and retrieve Oauth2 tokens for use with Google Cloud Service accounts.
"""
end
defp package do
[
maintainers: ["Phil Burrows"],
licenses: ["MIT"],
links: %{"GitHub" => @source_url}
]
end
end
| 22.728814 | 103 | 0.542133 |
03bb452c38a5c58405321e2db6709ccc8f4812c5 | 60,519 | ex | Elixir | clients/cloud_identity/lib/google_api/cloud_identity/v1/api/groups.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/cloud_identity/lib/google_api/cloud_identity/v1/api/groups.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/cloud_identity/lib/google_api/cloud_identity/v1/api/groups.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.CloudIdentity.V1.Api.Groups do
@moduledoc """
API calls for all endpoints tagged `Groups`.
"""
alias GoogleApi.CloudIdentity.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Creates a Group.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:initialGroupConfig` (*type:* `String.t`) - Optional. The initial configuration option for the `Group`.
* `:body` (*type:* `GoogleApi.CloudIdentity.V1.Model.Group.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_create(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_create(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:initialGroupConfig => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/groups", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Operation{}])
end
@doc """
Deletes a `Group`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The [resource name](https://cloud.google.com/apis/design/resource_names) of the `Group` to retrieve. Must be of the form `groups/{group}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_delete(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Operation{}])
end
@doc """
Retrieves a `Group`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The [resource name](https://cloud.google.com/apis/design/resource_names) of the `Group` to retrieve. Must be of the form `groups/{group}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Group{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Group.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Group{}])
end
@doc """
Lists the `Group` resources under a customer or namespace.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The maximum number of results to return. Note that the number of results returned may be less than this value even if there are more available results. To fetch all results, clients must continue calling this method repeatedly until the response no longer contains a `next_page_token`. If unspecified, defaults to 200 for `View.BASIC` and to 50 for `View.FULL`. Must not be greater than 1000 for `View.BASIC` or 500 for `View.FULL`.
* `:pageToken` (*type:* `String.t`) - The `next_page_token` value returned from a previous list request, if any.
* `:parent` (*type:* `String.t`) - Required. The parent resource under which to list all `Group` resources. Must be of the form `identitysources/{identity_source}` for external- identity-mapped groups or `customers/{customer}` for Google Groups. The `customer` must begin with "C" (for example, 'C046psxkn').
* `:view` (*type:* `String.t`) - The level of detail to be returned. If unspecified, defaults to `View.BASIC`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.ListGroupsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.ListGroupsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query,
:parent => :query,
:view => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/groups", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.ListGroupsResponse{}])
end
@doc """
Looks up the [resource name](https://cloud.google.com/apis/design/resource_names) of a `Group` by its `EntityKey`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"groupKey.id"` (*type:* `String.t`) - The ID of the entity. For Google-managed entities, the `id` should be the email address of an existing group or user. For external-identity-mapped entities, the `id` must be a string conforming to the Identity Source's requirements. Must be unique within a `namespace`.
* `:"groupKey.namespace"` (*type:* `String.t`) - The namespace in which the entity exists. If not specified, the `EntityKey` represents a Google-managed entity such as a Google user or a Google Group. If specified, the `EntityKey` represents an external-identity-mapped group. The namespace must correspond to an identity source created in Admin Console and must be in the form of `identitysources/{identity_source}`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.LookupGroupNameResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_lookup(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.LookupGroupNameResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_lookup(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"groupKey.id" => :query,
:"groupKey.namespace" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/groups:lookup", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.LookupGroupNameResponse{}]
)
end
@doc """
Updates a `Group`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Output only. The [resource name](https://cloud.google.com/apis/design/resource_names) of the `Group`. Shall be of the form `groups/{group}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. The names of fields to update. May only contain the following field names: `display_name`, `description`, `labels`.
* `:body` (*type:* `GoogleApi.CloudIdentity.V1.Model.Group.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_patch(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Operation{}])
end
@doc """
Searches for `Group` resources matching a specified query.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The maximum number of results to return. Note that the number of results returned may be less than this value even if there are more available results. To fetch all results, clients must continue calling this method repeatedly until the response no longer contains a `next_page_token`. If unspecified, defaults to 200 for `GroupView.BASIC` and 50 for `GroupView.FULL`. Must not be greater than 1000 for `GroupView.BASIC` or 500 for `GroupView.FULL`.
* `:pageToken` (*type:* `String.t`) - The `next_page_token` value returned from a previous search request, if any.
* `:query` (*type:* `String.t`) - Required. The search query. Must be specified in [Common Expression Language](https://opensource.google/projects/cel). May only contain equality operators on the parent and inclusion operators on labels (e.g., `parent == 'customers/{customer}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels`). The `customer` must begin with "C" (for example, 'C046psxkn').
* `:view` (*type:* `String.t`) - The level of detail to be returned. If unspecified, defaults to `View.BASIC`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.SearchGroupsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_search(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.SearchGroupsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_search(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query,
:query => :query,
:view => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/groups:search", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.SearchGroupsResponse{}])
end
@doc """
Check a potential member for membership in a group. **Note:** This feature is only available to Google Workspace Enterprise Standard, Enterprise Plus, and Enterprise for Education; and Cloud Identity Premium accounts. If the account of the member is not one of these, a 403 (PERMISSION_DENIED) HTTP status code will be returned. A member has membership to a group as long as there is a single viewable transitive membership between the group and the member. The actor must have view permissions to at least one transitive membership between the member and group.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - [Resource name](https://cloud.google.com/apis/design/resource_names) of the group to check the transitive membership in. Format: `groups/{group}`, where `group` is the unique id assigned to the Group to which the Membership belongs to.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:query` (*type:* `String.t`) - Required. A CEL expression that MUST include member specification. This is a `required` field. Certain groups are uniquely identified by both a 'member_key_id' and a 'member_key_namespace', which requires an additional query input: 'member_key_namespace'. Example query: `member_key_id == 'member_key_id_value'`
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.CheckTransitiveMembershipResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_check_transitive_membership(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.CheckTransitiveMembershipResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_check_transitive_membership(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:query => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships:checkTransitiveMembership", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.CheckTransitiveMembershipResponse{}]
)
end
@doc """
Creates a `Membership`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent `Group` resource under which to create the `Membership`. Must be of the form `groups/{group}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.CloudIdentity.V1.Model.Membership.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/memberships", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Operation{}])
end
@doc """
Deletes a `Membership`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The [resource name](https://cloud.google.com/apis/design/resource_names) of the `Membership` to delete. Must be of the form `groups/{group}/memberships/{membership}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_delete(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Operation{}])
end
@doc """
Retrieves a `Membership`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The [resource name](https://cloud.google.com/apis/design/resource_names) of the `Membership` to retrieve. Must be of the form `groups/{group}/memberships/{membership}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Membership{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Membership.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Membership{}])
end
@doc """
Get a membership graph of just a member or both a member and a group. **Note:** This feature is only available to Google Workspace Enterprise Standard, Enterprise Plus, and Enterprise for Education; and Cloud Identity Premium accounts. If the account of the member is not one of these, a 403 (PERMISSION_DENIED) HTTP status code will be returned. Given a member, the response will contain all membership paths from the member. Given both a group and a member, the response will contain all membership paths between the group and the member.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the group to search transitive memberships in. Format: `groups/{group}`, where `group` is the unique ID assigned to the Group to which the Membership belongs to. group can be a wildcard collection id "-". When a group is specified, the membership graph will be constrained to paths between the member (defined in the query) and the parent. If a wildcard collection is provided, all membership paths connected to the member will be returned.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:query` (*type:* `String.t`) - Required. A CEL expression that MUST include member specification AND label(s). Certain groups are uniquely identified by both a 'member_key_id' and a 'member_key_namespace', which requires an additional query input: 'member_key_namespace'. Example query: `member_key_id == 'member_key_id_value' && in labels`
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_get_membership_graph(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_get_membership_graph(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:query => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships:getMembershipGraph", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.Operation{}])
end
@doc """
Lists the `Membership`s within a `Group`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent `Group` resource under which to lookup the `Membership` name. Must be of the form `groups/{group}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The maximum number of results to return. Note that the number of results returned may be less than this value even if there are more available results. To fetch all results, clients must continue calling this method repeatedly until the response no longer contains a `next_page_token`. If unspecified, defaults to 200 for `GroupView.BASIC` and to 50 for `GroupView.FULL`. Must not be greater than 1000 for `GroupView.BASIC` or 500 for `GroupView.FULL`.
* `:pageToken` (*type:* `String.t`) - The `next_page_token` value returned from a previous search request, if any.
* `:view` (*type:* `String.t`) - The level of detail to be returned. If unspecified, defaults to `View.BASIC`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.ListMembershipsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.ListMembershipsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_list(connection, parent, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query,
:view => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.ListMembershipsResponse{}]
)
end
@doc """
Looks up the [resource name](https://cloud.google.com/apis/design/resource_names) of a `Membership` by its `EntityKey`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent `Group` resource under which to lookup the `Membership` name. Must be of the form `groups/{group}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"memberKey.id"` (*type:* `String.t`) - The ID of the entity. For Google-managed entities, the `id` should be the email address of an existing group or user. For external-identity-mapped entities, the `id` must be a string conforming to the Identity Source's requirements. Must be unique within a `namespace`.
* `:"memberKey.namespace"` (*type:* `String.t`) - The namespace in which the entity exists. If not specified, the `EntityKey` represents a Google-managed entity such as a Google user or a Google Group. If specified, the `EntityKey` represents an external-identity-mapped group. The namespace must correspond to an identity source created in Admin Console and must be in the form of `identitysources/{identity_source}`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.LookupMembershipNameResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_lookup(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.LookupMembershipNameResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_lookup(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"memberKey.id" => :query,
:"memberKey.namespace" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships:lookup", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.LookupMembershipNameResponse{}]
)
end
@doc """
Modifies the `MembershipRole`s of a `Membership`.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The [resource name](https://cloud.google.com/apis/design/resource_names) of the `Membership` whose roles are to be modified. Must be of the form `groups/{group}/memberships/{membership}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.CloudIdentity.V1.Model.ModifyMembershipRolesRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.ModifyMembershipRolesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_modify_membership_roles(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.ModifyMembershipRolesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_modify_membership_roles(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:modifyMembershipRoles", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.ModifyMembershipRolesResponse{}]
)
end
@doc """
Search transitive groups of a member. **Note:** This feature is only available to Google Workspace Enterprise Standard, Enterprise Plus, and Enterprise for Education; and Cloud Identity Premium accounts. If the account of the member is not one of these, a 403 (PERMISSION_DENIED) HTTP status code will be returned. A transitive group is any group that has a direct or indirect membership to the member. Actor must have view permissions all transitive groups.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - [Resource name](https://cloud.google.com/apis/design/resource_names) of the group to search transitive memberships in. Format: `groups/{group}`, where `group` is always '-' as this API will search across all groups for a given member.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The default page size is 200 (max 1000).
* `:pageToken` (*type:* `String.t`) - The next_page_token value returned from a previous list request, if any.
* `:query` (*type:* `String.t`) - Required. A CEL expression that MUST include member specification AND label(s). This is a `required` field. Users can search on label attributes of groups. CONTAINS match ('in') is supported on labels. Identity-mapped groups are uniquely identified by both a `member_key_id` and a `member_key_namespace`, which requires an additional query input: `member_key_namespace`. Example query: `member_key_id == 'member_key_id_value' && in labels`
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.SearchTransitiveGroupsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_search_transitive_groups(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.SearchTransitiveGroupsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_search_transitive_groups(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query,
:query => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships:searchTransitiveGroups", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.SearchTransitiveGroupsResponse{}]
)
end
@doc """
Search transitive memberships of a group. **Note:** This feature is only available to Google Workspace Enterprise Standard, Enterprise Plus, and Enterprise for Education; and Cloud Identity Premium accounts. If the account of the group is not one of these, a 403 (PERMISSION_DENIED) HTTP status code will be returned. A transitive membership is any direct or indirect membership of a group. Actor must have view permissions to all transitive memberships.
## Parameters
* `connection` (*type:* `GoogleApi.CloudIdentity.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - [Resource name](https://cloud.google.com/apis/design/resource_names) of the group to search transitive memberships in. Format: `groups/{group}`, where `group` is the unique ID assigned to the Group.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - The default page size is 200 (max 1000).
* `:pageToken` (*type:* `String.t`) - The next_page_token value returned from a previous list request, if any.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudIdentity.V1.Model.SearchTransitiveMembershipsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudidentity_groups_memberships_search_transitive_memberships(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudIdentity.V1.Model.SearchTransitiveMembershipsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def cloudidentity_groups_memberships_search_transitive_memberships(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/memberships:searchTransitiveMemberships", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudIdentity.V1.Model.SearchTransitiveMembershipsResponse{}]
)
end
end
| 51.027825 | 564 | 0.630942 |
03bb59bba23c0110e73711f3f9ac8dd4de9ad790 | 1,381 | exs | Elixir | mix.exs | Errol-Hassall-OVO/microsoft-graph-api | 087a5ce6e7b79712c79383d2dd75c7817779d750 | [
"MIT"
] | 2 | 2020-01-28T14:19:38.000Z | 2021-07-03T00:33:11.000Z | mix.exs | Errol-Hassall-OVO/microsoft-graph-api | 087a5ce6e7b79712c79383d2dd75c7817779d750 | [
"MIT"
] | null | null | null | mix.exs | Errol-Hassall-OVO/microsoft-graph-api | 087a5ce6e7b79712c79383d2dd75c7817779d750 | [
"MIT"
] | 2 | 2019-07-25T06:43:05.000Z | 2020-01-28T14:19:41.000Z | defmodule MicrosoftGraphApi.Mixfile do
use Mix.Project
def project do
[
app: :microsoft_graph_api,
version: "0.0.1",
elixir: "~> 1.7",
test_coverage: [tool: ExCoveralls],
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {MicrosoftGraphApi.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.3.4"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:plug_cowboy, "~> 1.0"},
{:cowboy, "~> 1.0"},
{:httpoison, "~> 1.4"},
{:poison, "~> 3.1"},
{:retry, "~> 0.11"},
{:bypass, "~> 0.8", only: :test},
{:credo, "~> 0.10.0", only: [:dev, :test], runtime: false},
{:excoveralls, "~> 0.10", only: :test}
]
end
end
| 26.557692 | 65 | 0.559739 |
03bb611b1930d1c3c18fa42bd1a0222e8a2e4a59 | 1,001 | exs | Elixir | astreu/deps/uuid/mix.exs | wesleimp/Astreu | 4d430733e7ecc8b3eba8e27811a152aa2c6d79c1 | [
"Apache-2.0"
] | null | null | null | astreu/deps/uuid/mix.exs | wesleimp/Astreu | 4d430733e7ecc8b3eba8e27811a152aa2c6d79c1 | [
"Apache-2.0"
] | null | null | null | astreu/deps/uuid/mix.exs | wesleimp/Astreu | 4d430733e7ecc8b3eba8e27811a152aa2c6d79c1 | [
"Apache-2.0"
] | null | null | null | defmodule UUID.Mixfile do
use Mix.Project
@version "1.1.8"
def project do
[app: :uuid,
name: "UUID",
version: @version,
elixir: "~> 1.0",
docs: [extras: ["README.md", "CHANGELOG.md"],
main: "readme",
source_ref: "v#{@version}"],
source_url: "https://github.com/zyro/elixir-uuid",
description: description(),
package: package(),
deps: deps()]
end
# Application configuration.
def application do
[]
end
# List of dependencies.
defp deps do
[{:ex_doc, "~> 0.16", only: :dev},
{:earmark, "~> 1.2", only: :dev},
{:benchfella, "~> 0.3", only: :dev}]
end
# Description.
defp description do
"""
UUID generator and utilities for Elixir.
"""
end
# Package info.
defp package do
[files: ["lib", "mix.exs", "README.md", "LICENSE"],
maintainers: ["Andrei Mihu"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/zyro/elixir-uuid"}]
end
end
| 20.854167 | 65 | 0.56044 |
03bb7ed098c59d6d666b7ecd349195d6f85f263b | 13,160 | exs | Elixir | test/cizen/saga_test.exs | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | test/cizen/saga_test.exs | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | test/cizen/saga_test.exs | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | defmodule Cizen.SagaTest do
use Cizen.SagaCase
doctest Cizen.Saga
alias Cizen.TestHelper
alias Cizen.TestSaga
import Cizen.TestHelper,
only: [
launch_test_saga: 0,
launch_test_saga: 1,
assert_condition: 2
]
alias Cizen.Dispatcher
alias Cizen.Saga
alias Cizen.SagaID
defmodule(TestEvent, do: defstruct([:value]))
describe "Saga" do
test "dispatches Launched event on launch" do
Dispatcher.listen_event_type(Saga.Started)
id = launch_test_saga()
assert_receive %Saga.Started{saga_id: ^id}
end
test "finishes on Finish event" do
Dispatcher.listen_event_type(Saga.Started)
id = launch_test_saga()
Dispatcher.dispatch(%Saga.Finish{saga_id: id})
assert_condition(100, :error == Saga.get_pid(id))
end
test "does not finish on Finish event for other saga" do
pid = self()
Dispatcher.listen_event_type(Saga.Started)
id =
launch_test_saga(
handle_event: fn event, state ->
send(pid, event)
state
end
)
finish = %Saga.Finish{saga_id: SagaID.new()}
Saga.send_to(id, finish)
assert_receive ^finish
assert {:ok, _} = Saga.get_pid(id)
end
test "dispatches Finished event on finish" do
Dispatcher.listen_event_type(Saga.Finished)
id = launch_test_saga()
Dispatcher.dispatch(%Saga.Finish{saga_id: id})
assert_receive %Saga.Finished{saga_id: ^id}
end
defmodule(CrashTestEvent1, do: defstruct([]))
test "terminated on crash" do
TestHelper.surpress_crash_log()
id =
launch_test_saga(
on_start: fn _state ->
Dispatcher.listen_event_type(CrashTestEvent1)
end,
handle_event: fn body, state ->
case body do
%CrashTestEvent1{} ->
raise "Crash!!!"
_ ->
state
end
end
)
Dispatcher.dispatch(%CrashTestEvent1{})
assert_condition(100, :error == Saga.get_pid(id))
end
defmodule(CrashTestEvent2, do: defstruct([]))
test "dispatches Crashed event on crash" do
TestHelper.surpress_crash_log()
Dispatcher.listen_event_type(Saga.Crashed)
id =
launch_test_saga(
on_start: fn _state ->
Dispatcher.listen_event_type(CrashTestEvent2)
end,
handle_event: fn body, state ->
case body do
%CrashTestEvent2{} ->
raise "Crash!!!"
_ ->
state
end
end
)
Dispatcher.dispatch(%CrashTestEvent2{})
assert_receive %Saga.Crashed{
saga_id: ^id,
reason: %RuntimeError{},
stacktrace: [{__MODULE__, _, _, _} | _]
}
end
defmodule(TestEventReply, do: defstruct([:value]))
test "handles events" do
Dispatcher.listen_event_type(TestEventReply)
id =
launch_test_saga(
on_start: fn _state ->
Dispatcher.listen_event_type(TestEvent)
end,
handle_event: fn body, state ->
case body do
%TestEvent{value: value} ->
Dispatcher.dispatch(%TestEventReply{value: value})
state
_ ->
state
end
end
)
Dispatcher.dispatch(%TestEvent{value: id})
assert_receive %TestEventReply{value: ^id}
end
test "finishes immediately" do
Dispatcher.listen_event_type(Saga.Finished)
id =
launch_test_saga(
on_start: fn state ->
id = Saga.self()
Dispatcher.dispatch(%Saga.Finish{saga_id: id})
state
end
)
assert_receive %Saga.Finished{saga_id: ^id}
assert_condition(100, :error == Saga.get_pid(id))
end
defmodule LazyLaunchSaga do
use Cizen.Saga
defstruct []
@impl true
def on_start(_) do
Dispatcher.listen_event_type(TestEvent)
{Saga.lazy_init(), :ok}
end
@impl true
def handle_event(%TestEvent{}, :ok) do
id = Saga.self()
Dispatcher.dispatch(%Saga.Started{saga_id: id})
:ok
end
end
test "does not dispatch Launched event on lazy launch" do
Dispatcher.listen_event_type(Saga.Started)
{:ok, id} = Saga.start(%LazyLaunchSaga{}, return: :saga_id)
refute_receive %Saga.Started{saga_id: ^id}
Dispatcher.dispatch(%TestEvent{})
assert_receive %Saga.Started{saga_id: ^id}
end
end
describe "Saga.module/1" do
test "returns the saga module" do
assert Saga.module(%TestSaga{}) == TestSaga
end
end
describe "Saga.start/2" do
test "starts a saga" do
Dispatcher.listen_event_type(Saga.Started)
{:ok, pid} = Saga.start(%TestSaga{extra: :some_value})
assert_receive %Saga.Started{saga_id: id}
assert {:ok, ^pid} = Saga.get_pid(id)
end
test "raises an error when called with unknown option" do
assert_raise ArgumentError, "invalid argument(s): [:unknown_key]", fn ->
Saga.start(%TestSaga{extra: :some_value}, unknown_key: :exists)
end
end
test "resumes a saga" do
Dispatcher.listen_event_type(Saga.Resumed)
{:ok, pid} = Saga.start(%TestSaga{extra: :some_value}, resume: :resumed_state)
assert_receive %Saga.Resumed{saga_id: id}
assert {:ok, ^pid} = Saga.get_pid(id)
assert :resumed_state == :sys.get_state(pid).state
end
test "starts a saga with a specific saga ID" do
Dispatcher.listen_event_type(Saga.Started)
saga_id = SagaID.new()
{:ok, pid} = Saga.start(%TestSaga{extra: :some_value}, saga_id: saga_id)
assert_receive %Saga.Started{saga_id: ^saga_id}
assert {:ok, ^pid} = Saga.get_pid(saga_id)
end
test "returns a saga ID" do
Dispatcher.listen_event_type(Saga.Started)
{:ok, saga_id} = Saga.start(%TestSaga{extra: :some_value}, return: :saga_id)
assert_receive %Saga.Started{saga_id: ^saga_id}
end
test "finishes when the given lifetime process exits" do
lifetime =
spawn(fn ->
receive do
:finish -> :ok
end
end)
{:ok, saga_id} =
Saga.start(%TestSaga{extra: :some_value}, lifetime: lifetime, return: :saga_id)
assert {:ok, _} = Saga.get_pid(saga_id)
send(lifetime, :finish)
assert_condition(100, :error == Saga.get_pid(saga_id))
end
test "finishes when the given lifetime saga exits" do
lifetime = TestHelper.launch_test_saga()
{:ok, saga_id} =
Saga.start(%TestSaga{extra: :some_value}, lifetime: lifetime, return: :saga_id)
assert {:ok, _} = Saga.get_pid(saga_id)
Saga.stop(lifetime)
assert_condition(100, :error == Saga.get_pid(saga_id))
end
test "finishes immediately when the given lifetime saga already ended" do
# No pid
lifetime = SagaID.new()
{:ok, saga_id} =
Saga.start(%TestSaga{extra: :some_value}, lifetime: lifetime, return: :saga_id)
assert_condition(10, :error == Saga.get_pid(saga_id))
end
end
describe "Saga.start_link/2" do
test "starts a saga linked to the current process" do
{:ok, pid} = Saga.start_link(%TestSaga{extra: :some_value})
links = self() |> Process.info() |> Keyword.fetch!(:links)
assert pid in links
Process.unlink(pid)
end
end
describe "Saga.get_pid/1" do
test "launched saga is registered" do
id = launch_test_saga()
assert {:ok, _pid} = Saga.get_pid(id)
end
test "killed saga is unregistered" do
id = launch_test_saga()
assert {:ok, pid} = Saga.get_pid(id)
true = Process.exit(pid, :kill)
assert_condition(100, :error == Saga.get_pid(id))
end
end
defmodule TestSagaState do
use Cizen.Saga
defstruct [:value]
@impl true
def on_start(%__MODULE__{}) do
:ok
end
@impl true
def handle_event(_event, :ok) do
:ok
end
end
describe "Saga.get_saga/1" do
test "returns a saga struct" do
{:ok, id} = Saga.start(%TestSagaState{value: :some_value}, return: :saga_id)
assert {:ok, %TestSagaState{value: :some_value}} = Saga.get_saga(id)
end
test "returns error for unregistered saga" do
assert :error == Saga.get_saga(SagaID.new())
end
end
describe "Saga.send_to/2" do
test "sends an event to a saga" do
pid = self()
id =
launch_test_saga(
handle_event: fn event, _state ->
id = Saga.self()
send(pid, {id, event})
end
)
Saga.send_to(id, %TestEvent{value: 10})
assert_receive {^id, %TestEvent{value: 10}}
end
end
describe "Saga.resume/3" do
test "starts a saga" do
saga_id = SagaID.new()
{:ok, pid} = Saga.resume(saga_id, %TestSaga{}, nil)
assert {:ok, ^pid} = Saga.get_pid(saga_id)
end
test "does not invoke init callback" do
pid = self()
saga_id = SagaID.new()
{:ok, _pid} =
Saga.resume(
saga_id,
%TestSaga{
on_start: fn _saga ->
send(pid, :called_init)
end
},
nil
)
refute_receive :called_init
end
test "invokes resume callback with arguments" do
pid = self()
saga_id = SagaID.new()
{:ok, _pid} =
Saga.resume(
saga_id,
%TestSaga{
on_resume: fn saga, state ->
send(pid, {Saga.self(), saga, state})
end,
extra: 42
},
:state
)
assert_receive {^saga_id, %TestSaga{extra: 42}, :state}
end
test "uses a resume callback's result as the next state" do
pid = self()
saga_id = SagaID.new()
{:ok, _pid} =
Saga.resume(
saga_id,
%TestSaga{
on_resume: fn _saga, _state ->
:next_state
end,
handle_event: fn _event, state ->
send(pid, state)
end
},
nil
)
Saga.send_to(saga_id, %TestEvent{})
assert_receive :next_state
end
test "dispatches Resumed event" do
Dispatcher.listen_event_type(Saga.Resumed)
saga_id = SagaID.new()
{:ok, _pid} =
Saga.resume(
saga_id,
%TestSaga{},
nil
)
assert_receive %Saga.Resumed{saga_id: ^saga_id}
end
defmodule TestSagaNoResume do
use Saga
defstruct [:value]
@impl true
def on_start(saga) do
Dispatcher.dispatch(%TestEvent{value: {:called_init, saga}})
:state
end
@impl true
def handle_event(event, state) do
Dispatcher.dispatch(%TestEvent{value: {:called_handle_event, event, state}})
:next_state
end
end
test "invokes init instead of resume when resume is not defined" do
saga_id = SagaID.new()
saga = %TestSagaNoResume{value: :some_value}
Dispatcher.listen_event_type(TestEvent)
{:ok, _pid} =
Saga.resume(
saga_id,
saga,
nil
)
assert_receive %TestEvent{value: {:called_init, ^saga}}
end
test "use the given state as next state" do
saga_id = SagaID.new()
Dispatcher.listen_event_type(TestEvent)
{:ok, _pid} =
Saga.resume(
saga_id,
%TestSagaNoResume{},
:resumed_state
)
receive do
%TestEvent{value: {:called_init, _}} -> :ok
end
event = %TestEvent{value: :some_value}
Saga.send_to(saga_id, event)
assert_receive %TestEvent{value: {:called_handle_event, ^event, :resumed_state}}
end
end
describe "Saga.self/0" do
defmodule TestSagaSelf do
use Saga
defstruct [:pid]
@impl true
def on_start(saga) do
send(saga.pid, Saga.self())
saga
end
@impl true
def handle_event(_event, saga) do
saga
end
end
test "invokes init instead of resume when resume is not defined" do
{:ok, saga_id} = Saga.start(%TestSagaSelf{pid: self()}, return: :saga_id)
assert_receive ^saga_id
end
end
defmodule TestSagaGenServer do
use Saga
defstruct []
@impl true
def on_start(_saga) do
[]
end
@impl true
def handle_event(_event, saga) do
saga
end
@impl true
def handle_call(:pop, from, [head | tail]) do
Saga.reply(from, head)
tail
end
@impl true
def handle_cast({:push, item}, state) do
[item | state]
end
end
describe "handle_call/3 and handle_cast/3" do
test "works with Saga.call/2 and Saga.cast/2" do
saga_id = SagaID.new()
{:ok, pid} = Saga.start(%TestSagaGenServer{}, saga_id: saga_id)
Saga.cast(saga_id, {:push, :a})
assert :sys.get_state(pid) == [:a]
assert Saga.call(saga_id, :pop) == :a
assert :sys.get_state(pid) == []
end
end
end
| 24.146789 | 87 | 0.585106 |
03bb9b4273709ae344d7e2320818462f96735f78 | 200 | ex | Elixir | backend/lib/aptamer_web/views/job_view.ex | ui-icts/aptamer-web | a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06 | [
"MIT"
] | null | null | null | backend/lib/aptamer_web/views/job_view.ex | ui-icts/aptamer-web | a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06 | [
"MIT"
] | 7 | 2019-02-08T18:28:49.000Z | 2022-02-12T06:44:59.000Z | backend/lib/aptamer_web/views/job_view.ex | ui-icts/aptamer-web | a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06 | [
"MIT"
] | null | null | null | defmodule AptamerWeb.JobView do
use AptamerWeb, :view
use JaSerializer.PhoenixView
attributes([:status, :output, :inserted_at])
has_one(:file,
field: :file_id,
type: "files"
)
end
| 16.666667 | 46 | 0.695 |
03bbca71d5081ac44321ba21f7c3ae8ca0354ade | 2,521 | ex | Elixir | lib/estated/property.ex | jdav-dev/estated | a8476b803eff425b5b73517e7ea180bb7f8cc30b | [
"Apache-2.0"
] | null | null | null | lib/estated/property.ex | jdav-dev/estated | a8476b803eff425b5b73517e7ea180bb7f8cc30b | [
"Apache-2.0"
] | null | null | null | lib/estated/property.ex | jdav-dev/estated | a8476b803eff425b5b73517e7ea180bb7f8cc30b | [
"Apache-2.0"
] | null | null | null | defmodule Estated.Property do
@moduledoc "A property record."
@moduledoc since: "0.1.0"
alias Estated.Property.Address
alias Estated.Property.Assessment
alias Estated.Property.Deed
alias Estated.Property.MarketAssessment
alias Estated.Property.Metadata
alias Estated.Property.Owner
alias Estated.Property.Parcel
alias Estated.Property.Structure
alias Estated.Property.Tax
alias Estated.Property.Valuation
defstruct [
:metadata,
:address,
:parcel,
:structure,
:taxes,
:assessments,
:market_assessments,
:valuation,
:owner,
:deeds
]
@typedoc "A property record."
@typedoc since: "0.1.0"
@type t :: %__MODULE__{
metadata: Metadata.t() | nil,
address: Address.t() | nil,
parcel: Parcel.t() | nil,
structure: Structure.t() | nil,
taxes: [Tax.t()],
assessments: [Assessment.t()],
market_assessments: [MarketAssessment.t()],
valuation: Valuation.t() | nil,
owner: Owner.t() | nil,
deeds: Deed.deeds()
}
@doc false
@doc since: "0.1.0"
@spec cast(map()) :: t()
def cast(%{} = property) do
Enum.reduce(property, %__MODULE__{}, &cast_field/2)
end
@spec cast(nil) :: nil
def cast(nil) do
nil
end
defp cast_field({"metadata", metadata}, acc) do
%__MODULE__{acc | metadata: Metadata.cast(metadata)}
end
defp cast_field({"address", address}, acc) do
%__MODULE__{acc | address: Address.cast(address)}
end
defp cast_field({"parcel", parcel}, acc) do
%__MODULE__{acc | parcel: Parcel.cast(parcel)}
end
defp cast_field({"structure", structure}, acc) do
%__MODULE__{acc | structure: Structure.cast(structure)}
end
defp cast_field({"taxes", taxes}, acc) do
%__MODULE__{acc | taxes: Tax.cast_list(taxes)}
end
defp cast_field({"assessments", assessments}, acc) do
%__MODULE__{acc | assessments: Assessment.cast_list(assessments)}
end
defp cast_field({"market_assessments", market_assessments}, acc) do
%__MODULE__{acc | market_assessments: MarketAssessment.cast_list(market_assessments)}
end
defp cast_field({"valuation", valuation}, acc) do
%__MODULE__{acc | valuation: Valuation.cast(valuation)}
end
defp cast_field({"owner", owner}, acc) do
%__MODULE__{acc | owner: Owner.cast(owner)}
end
defp cast_field({"deeds", deeds}, acc) do
%__MODULE__{acc | deeds: Deed.cast_list(deeds)}
end
defp cast_field(_map_entry, acc) do
acc
end
end
| 25.21 | 89 | 0.658072 |
03bbd6e919228cce790d871d0158dafa42882cb4 | 2,462 | exs | Elixir | mix.exs | manusajith/nebulex_redis_adapter | 0a29e6eaa5563ec2237e38ad9b88a476aaa8a26b | [
"MIT"
] | null | null | null | mix.exs | manusajith/nebulex_redis_adapter | 0a29e6eaa5563ec2237e38ad9b88a476aaa8a26b | [
"MIT"
] | null | null | null | mix.exs | manusajith/nebulex_redis_adapter | 0a29e6eaa5563ec2237e38ad9b88a476aaa8a26b | [
"MIT"
] | null | null | null | defmodule NebulexRedisAdapter.MixProject do
use Mix.Project
@version "1.1.1"
def project do
[
app: :nebulex_redis_adapter,
version: @version,
elixir: "~> 1.8",
deps: deps(),
# Docs
name: "NebulexRedisAdapter",
docs: docs(),
# Testing
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
# Dialyzer
dialyzer: dialyzer(),
# Hex
package: package(),
description: "Nebulex adapter for Redis"
]
end
def application do
[]
end
defp deps do
[
{:redix, "~> 0.11"},
# This is because the adapter tests need some support modules and shared
# tests from nebulex dependency, and the hex dependency doesn't include
# the test folder. Hence, to run the tests it is necessary to fetch
# nebulex dependency directly from GH.
{:nebulex, nebulex_dep()},
{:nebulex_cluster, "~> 0.1"},
{:jchash, "~> 0.1.1"},
{:crc, "~> 0.9"},
# Test
{:excoveralls, "~> 0.11", only: :test},
{:benchee, "~> 1.0", optional: true, only: :dev},
{:benchee_html, "~> 1.0", optional: true, only: :dev},
# Code Analysis
{:dialyxir, "~> 0.5", optional: true, only: [:dev, :test], runtime: false},
{:credo, "~> 1.0", optional: true, only: [:dev, :test]},
# Docs
{:ex_doc, "~> 0.20", only: :dev, runtime: false},
{:inch_ex, "~> 2.0", only: :docs}
]
end
defp nebulex_dep do
if System.get_env("NBX_TEST") do
[github: "cabol/nebulex", tag: "v1.1.1", override: true]
else
"~> 1.1"
end
end
defp package do
[
name: :nebulex_redis_adapter,
maintainers: ["Carlos Bolanos"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/cabol/nebulex_redis_adapter"}
]
end
defp docs do
[
main: "NebulexRedisAdapter",
source_ref: "v#{@version}",
canonical: "http://hexdocs.pm/nebulex_redis_adapter",
source_url: "https://github.com/cabol/nebulex_redis_adapter"
]
end
defp dialyzer do
[
plt_add_apps: [:mix, :eex, :nebulex, :shards, :jchash],
flags: [
:unmatched_returns,
:error_handling,
:race_conditions,
:no_opaque,
:unknown,
:no_return
]
]
end
end
| 23.009346 | 81 | 0.555646 |
03bbe8c6b1f6158dbc333899c204e97456d0156d | 1,373 | exs | Elixir | test/load_page_test.exs | losvedir/ephemeral2-logs | 05dadbd514493f8509457bcb411bbdd9b92f4f3a | [
"MIT"
] | 2 | 2015-08-04T17:35:50.000Z | 2015-08-12T18:37:48.000Z | test/load_page_test.exs | losvedir/ephemeral2-logs | 05dadbd514493f8509457bcb411bbdd9b92f4f3a | [
"MIT"
] | null | null | null | test/load_page_test.exs | losvedir/ephemeral2-logs | 05dadbd514493f8509457bcb411bbdd9b92f4f3a | [
"MIT"
] | null | null | null | defmodule LoadPageTest do
use ExUnit.Case
test "header/0" do
"timestamp,connect,service,status"
end
test "parse_line/1" do
l1 = ~s(342 <158>1 2015-05-12T13:19:53.089058+00:00 heroku router - - at=info method=GET path="/2bbbf21959178ef2f935e90fc60e5b6e368d27514fe305ca7dcecc32c0134838" host=ephemeralp2p.durazo.us request_id=e4a2ff6c-27c4-45c1-a97b-bc75204af065 fwd="93.34.60.136" dyno=web.1 connect=1ms service=11ms status=200 bytes=1450)
l2 = ~s(396 <158>1 2015-05-12T18:27:15.834333+00:00 heroku router - - at=error code=H13 desc="Connection closed without response" method=GET path="/2bbbf21959178ef2f935e90fc60e5b6e368d27514fe305ca7dcecc32c0134838" host=ephemeralp2p.durazo.us request_id=a84a62c8-7b79-463c-9db3-29ba69dd4758 fwd="128.119.40.196" dyno=web.1 connect=1ms service=10512ms status=503 bytes=0)
l3 = ~s(341 <158>1 2015-05-12T18:33:11.201252+00:00 heroku router - - at=info method=GET path="/2bbbf21959178ef2f935e90fc60e5b6e368d27514fe305ca7dcecc32c0134838" host=ephemeralp2p.durazo.us request_id=abdeec8f-6b6f-4185-baad-d08d2dc56027 fwd="46.236.26.102" dyno=web.1 connect=7ms service=8ms status=406 bytes=226)
assert ParseLogs.LoadPage.parse_line(l1) == "1431436793,1,11,200"
assert ParseLogs.LoadPage.parse_line(l2) == "1431455235,1,10512,503"
assert ParseLogs.LoadPage.parse_line(l3) == "1431455591,7,8,406"
end
end
| 76.277778 | 373 | 0.777859 |
03bc1245f871651724c4baabf0a5afa74ff6d41e | 2,445 | exs | Elixir | config/dev.exs | thelastinuit/akkad | 08df3f51daeada737c53d07663c166a5e6cc297e | [
"MIT"
] | 1 | 2022-03-05T00:05:26.000Z | 2022-03-05T00:05:26.000Z | config/dev.exs | thelastinuit/akkad | 08df3f51daeada737c53d07663c166a5e6cc297e | [
"MIT"
] | null | null | null | config/dev.exs | thelastinuit/akkad | 08df3f51daeada737c53d07663c166a5e6cc297e | [
"MIT"
] | null | null | null | import Config
# Configure your database
config :akkad, Akkad.Repo,
username: "postgres",
password: "postgres",
hostname: "localhost",
database: "akkad_dev",
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 esbuild to bundle .js and .css sources.
config :akkad, AkkadWeb.Endpoint,
# Binding to loopback ipv4 address prevents access from other machines.
# Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
http: [ip: {127, 0, 0, 1}, port: 4000],
check_origin: false,
code_reloader: true,
debug_errors: true,
secret_key_base:
"gjWK5Sl1nb7NqyCJeIjU62ZnCqjAc+JZtsHOfLW6Bt9h8nN/xnwx524w2zdWA6/B",
watchers: [
# Start the esbuild watcher by calling Esbuild.install_and_run(:default, args)
esbuild:
{Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]},
tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]}
]
# ## 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 :akkad, AkkadWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/akkad_web/(live|views)/.*(ex)$",
~r"lib/akkad_web/templates/.*(eex)$"
]
]
# 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
| 31.346154 | 82 | 0.703885 |
03bc1cdfb40b898b038ab0f07a8a8e38a238a504 | 45 | exs | Elixir | learning/programming_elixir/stack/test/stack_test.exs | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | 2 | 2020-01-20T20:15:20.000Z | 2020-02-27T11:08:42.000Z | learning/programming_elixir/stack/test/stack_test.exs | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | learning/programming_elixir/stack/test/stack_test.exs | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | defmodule StackTest do
use ExUnit.Case
end
| 11.25 | 22 | 0.8 |
03bc5c30c249767f62bbcf8f6e20d396a3da9179 | 289 | ex | Elixir | lib/xgps/gps_data.ex | mholtman/xgps | b660df067800d38658e13faa87dc60027425cf66 | [
"MIT"
] | 20 | 2016-12-05T18:34:36.000Z | 2021-12-21T13:32:44.000Z | lib/xgps/gps_data.ex | mholtman/xgps | b660df067800d38658e13faa87dc60027425cf66 | [
"MIT"
] | 1 | 2016-10-16T07:09:02.000Z | 2016-10-16T07:09:02.000Z | lib/xgps/gps_data.ex | mholtman/xgps | b660df067800d38658e13faa87dc60027425cf66 | [
"MIT"
] | 5 | 2017-03-04T00:18:50.000Z | 2021-01-15T12:26:54.000Z | defmodule XGPS.GpsData do
defstruct [
has_fix: false,
time: nil,
date: nil,
latitude: nil,
longitude: nil,
geoidheight: nil,
altitude: nil,
speed: nil,
angle: nil,
magvariation: nil,
hdop: nil,
fix_quality: nil,
satelites: nil
]
end
| 16.055556 | 25 | 0.595156 |
03bc6edfe53d94b952ae0fed34c2ef0a090f5db1 | 599 | exs | Elixir | elixir/animals/mix.exs | rusucosmin/til | 1687b89454b22e14c5c720f41199a5d2badf7db2 | [
"MIT"
] | 14 | 2016-02-19T22:14:31.000Z | 2022-02-06T21:59:46.000Z | elixir/animals/mix.exs | rusucosmin/til | 1687b89454b22e14c5c720f41199a5d2badf7db2 | [
"MIT"
] | null | null | null | elixir/animals/mix.exs | rusucosmin/til | 1687b89454b22e14c5c720f41199a5d2badf7db2 | [
"MIT"
] | 2 | 2020-01-07T11:27:26.000Z | 2022-02-06T21:59:54.000Z | defmodule Animals.MixProject do
use Mix.Project
def project do
[
app: :animals,
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
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ex_doc, "~> 0.12"}
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
| 19.966667 | 88 | 0.564274 |
03bc829b0dced703bbca5ecf47fe47af4f09c5cb | 142 | exs | Elixir | test/harald/hci/event/inquiry_complete_test.exs | smartrent/harald | 158a69bc2b70b3f51d67bd935d223a42a3633d68 | [
"MIT"
] | 3 | 2020-08-07T02:09:09.000Z | 2020-08-28T12:25:48.000Z | test/harald/hci/event/inquiry_complete_test.exs | smartrent/harald | 158a69bc2b70b3f51d67bd935d223a42a3633d68 | [
"MIT"
] | null | null | null | test/harald/hci/event/inquiry_complete_test.exs | smartrent/harald | 158a69bc2b70b3f51d67bd935d223a42a3633d68 | [
"MIT"
] | null | null | null | defmodule Harald.HCI.Event.InquiryCompleteTest do
use ExUnit.Case, async: true
doctest Harald.HCI.Event.InquiryComplete, import: true
end
| 28.4 | 56 | 0.809859 |
03bc8451b52377955f4d454b5bc6df2c7c31cdea | 6,438 | ex | Elixir | wasmcloud_host/lib/wasmcloud_host_web/live/components/start_actor_component.ex | adobe-platform/wasmcloud-otp | bcfcdf9814bc529e67c954eacabdc9a05c772cfa | [
"Apache-2.0"
] | null | null | null | wasmcloud_host/lib/wasmcloud_host_web/live/components/start_actor_component.ex | adobe-platform/wasmcloud-otp | bcfcdf9814bc529e67c954eacabdc9a05c772cfa | [
"Apache-2.0"
] | null | null | null | wasmcloud_host/lib/wasmcloud_host_web/live/components/start_actor_component.ex | adobe-platform/wasmcloud-otp | bcfcdf9814bc529e67c954eacabdc9a05c772cfa | [
"Apache-2.0"
] | null | null | null | defmodule StartActorComponent do
use Phoenix.LiveComponent
@max_actor_size 16_000_000
def mount(socket) do
{:ok,
socket
|> assign(:uploads, %{})
|> assign(:error_msg, nil)
|> allow_upload(:actor, accept: ~w(.wasm), max_entries: 1, max_file_size: @max_actor_size)}
end
def handle_event("validate", _params, socket) do
case socket.assigns
|> Map.get(:uploads, %{})
|> Map.get(:actor, %{})
|> Map.get(:entries, [])
|> List.first(nil) do
nil ->
{:noreply, socket}
item when item.client_size > @max_actor_size ->
{:noreply,
assign(socket,
error_msg: "Uploaded actor was too large, must be under #{@max_actor_size} bytes"
)}
_ ->
{:noreply, socket}
end
end
def handle_event(
"start_actor_file",
%{"replicas" => replicas},
socket
) do
error_msg =
Phoenix.LiveView.consume_uploaded_entries(socket, :actor, fn %{path: path}, _entry ->
replicas = 1..String.to_integer(replicas)
case File.read(path) do
{:ok, bytes} ->
replicas
|> Enum.reduce_while("", fn _, _ ->
case HostCore.Actors.ActorSupervisor.start_actor(bytes) do
{:stop, err} ->
{:halt, "Error: #{err}"}
_any ->
{:cont, ""}
end
end)
{:error, reason} ->
"Error #{reason}"
end
end)
|> List.first()
case error_msg do
nil ->
{:noreply, assign(socket, error_msg: "Please select a file")}
"" ->
Phoenix.PubSub.broadcast(WasmcloudHost.PubSub, "frontend", :hide_modal)
{:noreply, assign(socket, error_msg: nil)}
msg ->
{:noreply, assign(socket, error_msg: msg)}
end
end
def handle_event(
"start_actor_ociref",
%{"replicas" => replicas, "actor_ociref" => actor_ociref, "host_id" => host_id},
socket
) do
case host_id do
"" ->
case WasmcloudHost.Lattice.ControlInterface.auction_actor(actor_ociref, %{}) do
{:ok, auction_host_id} ->
start_actor(actor_ociref, replicas, auction_host_id, socket)
{:error, error} ->
{:noreply, assign(socket, error_msg: error)}
end
host_id ->
start_actor(actor_ociref, replicas, host_id, socket)
end
end
defp start_actor(actor_ociref, replicas, host_id, socket) do
actor_id =
WasmcloudHost.Lattice.StateMonitor.get_ocirefs()
|> Enum.find({actor_ociref, ""}, fn {oci, _id} -> oci == actor_ociref end)
|> elem(1)
case WasmcloudHost.Lattice.ControlInterface.scale_actor(
actor_id,
actor_ociref,
replicas,
host_id
) do
:ok ->
Phoenix.PubSub.broadcast(WasmcloudHost.PubSub, "frontend", :hide_modal)
{:noreply, assign(socket, error_msg: nil)}
{:error, error} ->
{:noreply, assign(socket, error_msg: error)}
end
end
def render(assigns) do
modal_id =
if assigns.id == :start_actor_file_modal do
"start_actor_file"
else
"start_actor_ociref"
end
~L"""
<form class="form-horizontal" phx-submit="<%= modal_id %>" phx-change="validate" phx-target="<%= @myself %>">
<input name="_csrf_token" type="hidden" value="<%= Phoenix.Controller.get_csrf_token() %>">
<%= if assigns.id == :start_actor_file_modal do %>
<div class="form-group row" phx-drop-target="<%= @uploads.actor.ref %>">
<label class="col-md-3 col-form-label" for="file-input">File</label>
<div class="col-md-9">
<%= live_file_input @uploads.actor %>
</div>
</div>
<% else %>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="text-input">Desired Host</label>
<div class="col-md-9">
<%# On select, populate the linkname and contract_id options with the matching data %>
<select class="form-control select2-single id-monospace" id="host-id-select" name="host_id">
<%= if @selected_host != nil do %>
<option value> -- First available -- </option>
<%= for {host_id, _host_map} <- @hosts do %>
<%= if host_id == @selected_host do %>
<option selected value="<%= host_id %>" data-host-id="<%= host_id %>">
<%= String.slice(host_id, 0..4) %>...
</option>
<% else %>
<option value="<%= host_id %>" data-host-id="<%= host_id %>">
<%= String.slice(host_id, 0..4) %>...
</option>
<% end %>
<% end %>
<% else %>
<option selected value> -- First available -- </option>
<%= for {host_id, _host_map} <- @hosts do %>
<option value="<%= host_id %>" data-host-id="<%= host_id %>">
<%= String.slice(host_id, 0..4) %>...
</option>
<% end %>
<% end %>
</select>
<span class="help-block"><strong>First available</strong> will hold an auction for an appropriate host</span>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="file-input">OCI reference</label>
<div class="col-md-9">
<input class="form-control" id="text-input" type="text" name="actor_ociref"
placeholder="wasmcloud.azurecr.io/echo:0.3.2" value="" required>
<span class="help-block">Enter an OCI reference</span>
</div>
</div>
<% end %>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="text-input">Replicas</label>
<div class="col-md-9">
<input class="form-control" id="number-input" type="number" name="replicas" placeholder="1" value="1" min="1">
<span class="help-block">Enter how many instances of this actor you want</span>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" phx-click="hide_modal">Close</button>
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
<%= if @error_msg != nil do %>
<div class="alert alert-danger">
<%= @error_msg %>
</div>
<% end %>
"""
end
end
| 33.185567 | 120 | 0.54722 |
03bd0c394bae1ebd54521c5c60f612f94b7f4e4a | 1,631 | ex | Elixir | lib/web/controllers/admin/race_controller.ex | stevegrossi/ex_venture | e02d5a63fdb882d92cfb4af3e15f7b48ad7054aa | [
"MIT"
] | 2 | 2019-05-14T11:36:44.000Z | 2020-07-01T08:54:04.000Z | lib/web/controllers/admin/race_controller.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | null | null | null | lib/web/controllers/admin/race_controller.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | 1 | 2021-01-29T14:12:40.000Z | 2021-01-29T14:12:40.000Z | defmodule Web.Admin.RaceController do
use Web.AdminController
alias Web.Race
def index(conn, _params) do
races = Race.all()
conn
|> assign(:races, races)
|> render("index.html")
end
def show(conn, %{"id" => id}) do
race = Race.get(id)
conn
|> assign(:race, race)
|> render("show.html")
end
def new(conn, _params) do
changeset = Race.new()
conn
|> assign(:changeset, changeset)
|> render("new.html")
end
def create(conn, %{"race" => params}) do
case Race.create(params) do
{:ok, race} ->
conn
|> put_flash(:info, "#{race.name} created!")
|> redirect(to: race_path(conn, :show, race.id))
{:error, changeset} ->
conn
|> put_flash(:error, "There was a problem creating the race. Please try again.")
|> assign(:changeset, changeset)
|> render("new.html")
end
end
def edit(conn, %{"id" => id}) do
race = Race.get(id)
changeset = Race.edit(race)
conn
|> assign(:race, race)
|> assign(:changeset, changeset)
|> render("edit.html")
end
def update(conn, %{"id" => id, "race" => params}) do
case Race.update(id, params) do
{:ok, race} ->
conn
|> put_flash(:info, "#{race.name} updated!")
|> redirect(to: race_path(conn, :show, race.id))
{:error, changeset} ->
race = Race.get(id)
conn
|> put_flash(:error, "There was an issue updating #{race.name}. Please try again.")
|> assign(:race, race)
|> assign(:changeset, changeset)
|> render("edit.html")
end
end
end
| 22.342466 | 91 | 0.554261 |
03bd1d861575e05f5ad58af6efc65fd20389fe2d | 24,298 | ex | Elixir | apps/language_server/lib/language_server/providers/completion.ex | princemaple/elixir-ls | d2e6788cc32ede3f9f2ef080c051a061ae4f4d63 | [
"Apache-2.0"
] | null | null | null | apps/language_server/lib/language_server/providers/completion.ex | princemaple/elixir-ls | d2e6788cc32ede3f9f2ef080c051a061ae4f4d63 | [
"Apache-2.0"
] | null | null | null | apps/language_server/lib/language_server/providers/completion.ex | princemaple/elixir-ls | d2e6788cc32ede3f9f2ef080c051a061ae4f4d63 | [
"Apache-2.0"
] | null | null | null | defmodule ElixirLS.LanguageServer.Providers.Completion do
@moduledoc """
Auto-complete provider utilizing Elixir Sense
We use Elixir Sense to retrieve auto-complete suggestions based on the source file text and cursor
position, and then perform some additional processing on those suggestions to make them compatible
with the Language Server Protocol. We also attempt to determine the context based on the line
text before the cursor so we can filter out suggestions that are not relevant.
"""
alias ElixirLS.LanguageServer.SourceFile
@enforce_keys [:label, :kind, :insert_text, :priority, :tags]
defstruct [
:label,
:kind,
:detail,
:documentation,
:insert_text,
:filter_text,
# Lower priority is shown higher in the result list
:priority,
:tags,
:command
]
@func_snippets %{
{"Kernel.SpecialForms", "case"} => "case $1 do\n\t$2 ->\n\t\t$0\nend",
{"Kernel.SpecialForms", "with"} => "with $2 <- $1 do\n\t$0\nend",
{"Kernel.SpecialForms", "cond"} => "cond do\n\t$1 ->\n\t\t$0\nend",
{"Kernel.SpecialForms", "receive"} =>
"receive do\n\t${1:{${2::message_type}, ${3:value}\\}} ->\n\t\t${0:# code}\nend\n",
{"Kernel.SpecialForms", "fn"} => "fn $1 -> $0 end",
{"Kernel.SpecialForms", "for"} => "for $1 <- $2 do\n\t$3\nend",
{"Kernel.SpecialForms", "super"} => "super($1)",
{"Kernel.SpecialForms", "quote"} => "quote do\n\t$0\nend",
{"Kernel.SpecialForms", "try"} => "try do\n\t$0\nend",
{"Kernel", "if"} => "if $1 do\n\t$0\nend",
{"Kernel", "unless"} => "unless $1 do\n\t$0\nend",
{"Kernel", "def"} => "def $1 do\n\t$0\nend",
{"Kernel", "defp"} => "defp $1 do\n\t$0\nend",
{"Kernel", "defcallback"} => "defcallback $1 :: $0",
{"Kernel", "defdelegate"} => "defdelegate $1, to: $0",
{"Kernel", "defexception"} => "defexception [${1::message}]",
{"Kernel", "defguard"} => "defguard ${1:guard_name}($2) when $3",
{"Kernel", "defguardp"} => "defguardp ${1:guard_name}($2) when $3",
{"Kernel", "defimpl"} => "defimpl $1, for: $2 do\n\t$0\nend",
{"Kernel", "defmacro"} => "defmacro $1 do\n\t$0\nend",
{"Kernel", "defmacrocallback"} => "defmacrocallback $1 :: $0",
{"Kernel", "defmacrop"} => "defmacrop $1 do\n\t$0\nend",
{"Kernel", "defmodule"} => "defmodule $1 do\n\t$0\nend",
{"Kernel", "defprotocol"} => "defprotocol $1 do\n\t$0\nend",
{"Kernel", "defstruct"} => "defstruct $1: $2",
{"ExUnit.Callbacks", "setup"} => "setup ${1:%{$2\\}} do\n\t$3\nend",
{"ExUnit.Callbacks", "setup_all"} => "setup_all ${1:%{$2\\}} do\n\t$3\nend",
{"ExUnit.Case", "test"} => "test $1 do\n\t$0\nend",
{"ExUnit.Case", "describe"} => "describe \"$1\" do\n\t$0\nend"
}
@use_name_only MapSet.new([
{"Kernel", "not"},
{"Kernel", "use"},
{"Kernel", "or"},
{"Kernel", "and"},
{"Kernel", "raise"},
{"Kernel", "reraise"},
{"Kernel", "in"},
{"Kernel.SpecialForms", "alias"},
{"Kernel.SpecialForms", "import"},
{"Kernel.SpecialForms", "require"},
"ExUnit.Assertions"
])
def trigger_characters do
# VS Code's 24x7 autocompletion triggers automatically on alphanumeric characters. We add these
# for "SomeModule." calls, @module_attrs, function capture, variable pinning, erlang module calls
[".", "@", "&", "%", "^", ":", "!"]
end
def completion(text, line, character, options) do
line_text =
text
|> SourceFile.lines()
|> Enum.at(line)
text_before_cursor = String.slice(line_text, 0, character)
text_after_cursor = String.slice(line_text, character..-1)
prefix = get_prefix(text_before_cursor)
# TODO: Don't call into here directly
# Can we use ElixirSense.Providers.Suggestion? ElixirSense.suggestions/3
env =
ElixirSense.Core.Parser.parse_string(text, true, true, line + 1)
|> ElixirSense.Core.Metadata.get_env(line + 1)
scope =
case env.scope do
scope when scope in [Elixir, nil] -> :file
module when is_atom(module) -> :module
{_, _} -> :function
end
def_before =
cond do
Regex.match?(Regex.recompile!(~r/(defdelegate|defp?)\s*#{prefix}$/), text_before_cursor) ->
:def
Regex.match?(
Regex.recompile!(~r/(defguardp?|defmacrop?)\s*#{prefix}$/),
text_before_cursor
) ->
:defmacro
true ->
nil
end
context = %{
text_before_cursor: text_before_cursor,
text_after_cursor: text_after_cursor,
prefix: prefix,
def_before: def_before,
pipe_before?: Regex.match?(Regex.recompile!(~r/\|>\s*#{prefix}$/), text_before_cursor),
capture_before?: Regex.match?(Regex.recompile!(~r/&#{prefix}$/), text_before_cursor),
scope: scope,
module: env.module
}
items =
ElixirSense.suggestions(text, line + 1, character + 1)
|> maybe_reject_derived_functions(context, options)
|> Enum.map(&from_completion_item(&1, context, options))
items_json =
items
|> Enum.reject(&is_nil/1)
|> Enum.uniq_by(&{&1.detail, &1.documentation, &1.insert_text})
|> sort_items()
|> items_to_json(options)
{:ok, %{"isIncomplete" => is_incomplete(items_json), "items" => items_json}}
end
## Helpers
defp is_incomplete(items) do
if Enum.empty?(items) do
false
else
# By returning isIncomplete = true we tell the client that it should
# always fetch more results, this lets us control the ordering of
# completions accurately
true
end
end
defp maybe_reject_derived_functions(suggestions, context, options) do
locals_without_parens = Keyword.get(options, :locals_without_parens)
signature_help_supported = Keyword.get(options, :signature_help_supported, false)
capture_before? = context.capture_before?
Enum.reject(suggestions, fn s ->
s.type in [:function, :macro] and
!capture_before? and
s.arity < s.def_arity and
signature_help_supported and
function_name_with_parens?(s.name, s.arity, locals_without_parens) ==
function_name_with_parens?(s.name, s.def_arity, locals_without_parens)
end)
end
defp from_completion_item(
%{type: :attribute, name: name},
%{
prefix: prefix,
def_before: nil,
capture_before?: false,
pipe_before?: false
},
_options
) do
name_only = String.trim_leading(name, "@")
insert_text = if String.starts_with?(prefix, "@"), do: name_only, else: name
if name == prefix do
nil
else
%__MODULE__{
label: name,
kind: :variable,
detail: "module attribute",
insert_text: insert_text,
filter_text: name_only,
priority: 14,
tags: []
}
end
end
defp from_completion_item(
%{type: :variable, name: name},
%{
def_before: nil,
pipe_before?: false,
capture_before?: false
},
_options
) do
%__MODULE__{
label: to_string(name),
kind: :variable,
detail: "variable",
insert_text: name,
priority: 13,
tags: []
}
end
defp from_completion_item(
%{type: :return, description: description, spec: spec, snippet: snippet},
%{def_before: nil, capture_before?: false, pipe_before?: false},
_options
) do
snippet = Regex.replace(Regex.recompile!(~r/"\$\{(.*)\}\$"/U), snippet, "${\\1}")
%__MODULE__{
label: description,
kind: :value,
detail: "return value",
documentation: spec,
insert_text: snippet,
priority: 15,
tags: []
}
end
defp from_completion_item(
%{type: :module, name: name, summary: summary, subtype: subtype, metadata: metadata},
%{def_before: nil},
_options
) do
detail =
if subtype do
Atom.to_string(subtype)
else
"module"
end
kind =
case subtype do
:behaviour -> :interface
:protocol -> :interface
:exception -> :struct
:struct -> :struct
_ -> :module
end
label =
if subtype do
"#{name} (#{subtype})"
else
name
end
insert_text =
case name do
":" <> rest -> rest
other -> other
end
%__MODULE__{
label: label,
kind: kind,
detail: detail,
documentation: summary,
insert_text: insert_text,
filter_text: name,
priority: 14,
tags: metadata_to_tags(metadata)
}
end
defp from_completion_item(
%{
type: :callback,
subtype: subtype,
args_list: args_list,
name: name,
summary: summary,
arity: arity,
origin: origin,
metadata: metadata
},
context,
options
) do
if (context[:def_before] == :def && subtype == :macrocallback) ||
(context[:def_before] == :defmacro && subtype == :callback) do
nil
else
def_str =
if context[:def_before] == nil do
if subtype == :macrocallback do
"defmacro "
else
"def "
end
end
opts = Keyword.put(options, :with_parens?, true)
insert_text = def_snippet(def_str, name, args_list, arity, opts)
label = "#{def_str}#{name}/#{arity}"
filter_text =
if def_str do
"#{def_str}#{name}"
else
name
end
%__MODULE__{
label: label,
kind: :interface,
detail: "#{origin} #{subtype}",
documentation: summary,
insert_text: insert_text,
priority: 12,
filter_text: filter_text,
tags: metadata_to_tags(metadata)
}
end
end
defp from_completion_item(
%{
type: :protocol_function,
args_list: args_list,
spec: _spec,
name: name,
summary: summary,
arity: arity,
origin: origin,
metadata: metadata
},
context,
options
) do
unless context[:def_before] == :defmacro do
def_str = if(context[:def_before] == nil, do: "def ")
opts = Keyword.put(options, :with_parens?, true)
insert_text = def_snippet(def_str, name, args_list, arity, opts)
label = "#{def_str}#{name}/#{arity}"
%__MODULE__{
label: label,
kind: :interface,
detail: "#{origin} protocol function",
documentation: summary,
insert_text: insert_text,
priority: 12,
filter_text: name,
tags: metadata_to_tags(metadata)
}
end
end
defp from_completion_item(
%{type: :field, subtype: subtype, name: name, origin: origin, call?: call?},
_context,
_options
) do
detail =
case {subtype, origin} do
{:map_key, _} -> "map key"
{:struct_field, nil} -> "struct field"
{:struct_field, module_name} -> "#{module_name} struct field"
end
%__MODULE__{
label: to_string(name),
detail: detail,
insert_text: if(call?, do: name, else: "#{name}: "),
priority: 10,
kind: :field,
tags: []
}
end
defp from_completion_item(%{type: :param_option} = suggestion, _context, _options) do
%{name: name, origin: _origin, doc: doc, type_spec: type_spec, expanded_spec: expanded_spec} =
suggestion
formatted_spec =
if expanded_spec != "" do
"\n\n```\n#{expanded_spec}\n```\n"
else
""
end
%__MODULE__{
label: to_string(name),
detail: "#{type_spec}",
documentation: "#{doc}#{formatted_spec}",
insert_text: "#{name}: ",
priority: 10,
kind: :field,
tags: []
}
end
defp from_completion_item(
%{type: :type_spec, metadata: metadata} = suggestion,
_context,
_options
) do
%{name: name, arity: arity, origin: _origin, doc: doc, signature: signature, spec: spec} =
suggestion
formatted_spec =
if spec != "" do
"\n\n```\n#{spec}\n```\n"
else
""
end
snippet =
if arity > 0 do
"#{name}($0)"
else
"#{name}()"
end
%__MODULE__{
label: signature,
detail: "typespec #{signature}",
documentation: "#{doc}#{formatted_spec}",
insert_text: snippet,
priority: 10,
kind: :class,
tags: metadata_to_tags(metadata)
}
end
defp from_completion_item(%{type: :generic, kind: kind, label: label} = suggestion, _ctx, opts) do
insert_text =
cond do
suggestion[:snippet] && Keyword.get(opts, :snippets_supported, false) ->
suggestion[:snippet]
insert_text = suggestion[:insert_text] ->
insert_text
true ->
label
end
%__MODULE__{
label: label,
detail: suggestion[:detail] || "",
documentation: suggestion[:documentation] || "",
insert_text: insert_text,
filter_text: suggestion[:filter_text],
priority: suggestion[:priority] || 0,
kind: kind,
command: suggestion[:command],
tags: []
}
end
defp from_completion_item(
%{
arity: 0
},
%{
pipe_before?: true
},
_options
),
do: nil
defp from_completion_item(
%{name: name, origin: origin} = item,
%{def_before: nil} = context,
options
) do
completion = function_completion(item, context, options)
completion =
if origin == "Kernel" || origin == "Kernel.SpecialForms" do
%{completion | kind: :keyword, priority: 18}
else
completion
end
if snippet = Map.get(@func_snippets, {origin, name}) do
%{completion | insert_text: snippet, kind: :snippet, label: name}
else
completion
end
end
defp from_completion_item(_suggestion, _context, _options) do
nil
end
defp def_snippet(def_str, name, args, arity, opts) do
if Keyword.get(opts, :snippets_supported, false) do
"#{def_str}#{function_snippet(name, args, arity, opts)} do\n\t$0\nend"
else
"#{def_str}#{name}"
end
end
def function_snippet(name, args, arity, opts) do
snippets_supported? = Keyword.get(opts, :snippets_supported, false)
trigger_signature? = Keyword.get(opts, :trigger_signature?, false)
capture_before? = Keyword.get(opts, :capture_before?, false)
pipe_before? = Keyword.get(opts, :pipe_before?, false)
with_parens? = Keyword.get(opts, :with_parens?, false)
snippet = Keyword.get(opts, :snippet)
cond do
snippet && snippets_supported? && !pipe_before? && !capture_before? ->
snippet
capture_before? ->
function_snippet_with_capture_before(name, arity, snippets_supported?)
trigger_signature? ->
text_after_cursor = Keyword.get(opts, :text_after_cursor, "")
function_snippet_with_signature(
name,
text_after_cursor,
snippets_supported?,
with_parens?
)
has_text_after_cursor?(opts) ->
name
snippets_supported? ->
function_snippet_with_args(name, arity, args, pipe_before?, with_parens?)
true ->
name
end
end
defp function_snippet_with_args(name, arity, args_list, pipe_before?, with_parens?) do
args_list =
args_list
|> Enum.map(&format_arg_for_snippet/1)
|> remove_unused_default_args(arity)
args_list =
if pipe_before? do
tl(args_list)
else
args_list
end
tabstops =
args_list
|> Enum.with_index()
|> Enum.map(fn {arg, i} -> "${#{i + 1}:#{arg}}" end)
{before_args, after_args} =
if with_parens? do
{"(", ")"}
else
{" ", ""}
end
Enum.join([name, before_args, Enum.join(tabstops, ", "), after_args])
end
defp function_snippet_with_signature(name, text_after_cursor, snippets_supported?, with_parens?) do
cond do
!with_parens? ->
if String.starts_with?(text_after_cursor, " "), do: name, else: "#{name} "
# Don't add the closing parenthesis to the snippet if the cursor is
# immediately before a valid argument. This usually happens when we
# want to wrap an existing variable or literal, e.g. using IO.inspect/2.
!snippets_supported? || Regex.match?(~r/^[a-zA-Z0-9_:"'%<@\[\{]/, text_after_cursor) ->
"#{name}("
true ->
"#{name}($1)$0"
end
end
defp function_snippet_with_capture_before(name, 0, _snippets_supported?) do
"#{name}/0"
end
defp function_snippet_with_capture_before(name, arity, snippets_supported?) do
if snippets_supported? do
"#{name}${1:/#{arity}}$0"
else
"#{name}/#{arity}"
end
end
defp has_text_after_cursor?(opts) do
text =
opts
|> Keyword.get(:text_after_cursor, "")
|> String.trim()
text != ""
end
# LSP CompletionItemKind enumeration
defp completion_kind(kind) do
case kind do
:text -> 1
:method -> 2
:function -> 3
:constructor -> 4
:field -> 5
:variable -> 6
:class -> 7
:interface -> 8
:module -> 9
:property -> 10
:unit -> 11
:value -> 12
:enum -> 13
:keyword -> 14
:snippet -> 15
:color -> 16
:file -> 17
:reference -> 18
:folder -> 19
:enum_member -> 20
:constant -> 21
:struct -> 22
:event -> 23
:operator -> 24
:type_parameter -> 25
end
end
defp insert_text_format(type) do
case type do
:plain_text -> 1
:snippet -> 2
end
end
defp get_prefix(text_before_cursor) do
regex = Regex.recompile!(~r/[\w0-9\._!\?\:@\->]+$/)
case Regex.run(regex, text_before_cursor) do
[prefix] -> prefix
_ -> ""
end
end
defp format_arg_for_snippet(arg) do
arg
|> String.replace("\\", "\\\\")
|> String.replace("$", "\\$")
|> String.replace("}", "\\}")
end
defp remove_unused_default_args(args, arity) do
reversed_args = Enum.reverse(args)
acc = {[], length(args) - arity}
{result, _} =
Enum.reduce(reversed_args, acc, fn arg, {result, remove_count} ->
parts = String.split(arg, "\\\\\\\\")
var = Enum.at(parts, 0) |> String.trim()
default_value = Enum.at(parts, 1)
if remove_count > 0 && default_value do
{result, remove_count - 1}
else
{[var | result], remove_count}
end
end)
result
end
defp function_completion(info, context, options) do
%{
type: type,
args: args,
args_list: args_list,
name: name,
summary: summary,
arity: arity,
spec: spec,
origin: origin,
metadata: metadata
} = info
# ElixirSense now returns types as an atom
type = to_string(type)
%{
pipe_before?: pipe_before?,
capture_before?: capture_before?,
text_after_cursor: text_after_cursor,
module: module
} = context
locals_without_parens = Keyword.get(options, :locals_without_parens)
signature_help_supported? = Keyword.get(options, :signature_help_supported, false)
signature_after_complete? = Keyword.get(options, :signature_after_complete, true)
with_parens? = function_name_with_parens?(name, arity, locals_without_parens)
trigger_signature? = signature_help_supported? && ((arity == 1 && !pipe_before?) || arity > 1)
{label, insert_text} =
cond do
match?("sigil_" <> _, name) ->
"sigil_" <> sigil_name = name
text = "~#{sigil_name}"
{text, text}
use_name_only?(origin, name) or String.starts_with?(text_after_cursor, "(") ->
{name, name}
true ->
label = "#{name}/#{arity}"
insert_text =
function_snippet(
name,
args_list,
arity,
Keyword.merge(
options,
pipe_before?: pipe_before?,
capture_before?: capture_before?,
trigger_signature?: trigger_signature?,
locals_without_parens: locals_without_parens,
text_after_cursor: text_after_cursor,
with_parens?: with_parens?,
snippet: info[:snippet]
)
)
{label, insert_text}
end
detail_prefix =
if inspect(module) == origin do
"(#{type}) "
else
"(#{type}) #{origin}."
end
detail = Enum.join([detail_prefix, name, "(", args, ")"])
footer = SourceFile.format_spec(spec, line_length: 30)
command =
if trigger_signature? && signature_after_complete? && !capture_before? do
%{
"title" => "Trigger Parameter Hint",
"command" => "editor.action.triggerParameterHints"
}
end
%__MODULE__{
label: label,
kind: :function,
detail: detail,
documentation: summary <> footer,
insert_text: insert_text,
priority: 17,
tags: metadata_to_tags(metadata),
command: command
}
end
defp use_name_only?(module_name, function_name) do
module_name in @use_name_only or {module_name, function_name} in @use_name_only or
String.starts_with?(function_name, "__") or
function_name =~ Regex.recompile!(~r/^[^a-zA-Z0-9]+$/)
end
defp sort_items(items) do
Enum.sort_by(items, fn %__MODULE__{priority: priority, label: label} ->
{priority, label =~ Regex.recompile!(~r/^[^a-zA-Z0-9]/), label}
end)
end
defp items_to_json(items, options) do
snippets_supported = Keyword.get(options, :snippets_supported, false)
items =
Enum.reject(items, fn item ->
not snippets_supported and snippet?(item)
end)
for {item, idx} <- Enum.with_index(items) do
item_to_json(item, idx, options)
end
end
defp item_to_json(item, idx, options) do
json = %{
"label" => item.label,
"kind" => completion_kind(item.kind),
"detail" => item.detail,
"documentation" => %{"value" => item.documentation || "", kind: "markdown"},
"filterText" => item.filter_text,
"sortText" => String.pad_leading(to_string(idx), 8, "0"),
"insertText" => item.insert_text,
"command" => item.command,
"insertTextFormat" =>
if Keyword.get(options, :snippets_supported, false) do
insert_text_format(:snippet)
else
insert_text_format(:plain_text)
end
}
# deprecated as of Language Server Protocol Specification - 3.15
json =
if Keyword.get(options, :deprecated_supported, false) do
Map.merge(json, %{
"deprecated" => item.tags |> Enum.any?(&(&1 == :deprecated))
})
else
json
end
tags_supported = options |> Keyword.get(:tags_supported, [])
json =
if tags_supported != [] do
Map.merge(json, %{
"tags" => item.tags |> Enum.map(&tag_to_code/1) |> Enum.filter(&(&1 in tags_supported))
})
else
json
end
for {k, v} <- json, not is_nil(v), into: %{}, do: {k, v}
end
defp snippet?(item) do
item.kind == :snippet || String.match?(item.insert_text, ~r/\${?\d/)
end
# As defined by CompletionItemTag in https://microsoft.github.io/language-server-protocol/specifications/specification-current/
defp tag_to_code(:deprecated), do: 1
defp metadata_to_tags(metadata) do
# As of Language Server Protocol Specification - 3.15 only one tag is supported
case metadata[:deprecated] do
nil -> []
_ -> [:deprecated]
end
end
defp function_name_with_parens?(name, arity, locals_without_parens) do
(locals_without_parens || MapSet.new())
|> MapSet.member?({String.to_atom(name), arity})
|> Kernel.not()
end
end
| 27.864679 | 129 | 0.575438 |
03bd4b707d34825a334b6fc337513ee182a693fa | 1,618 | ex | Elixir | clients/qpx_express/lib/google_api/qpx_express/v1/model/aircraft_data.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/qpx_express/lib/google_api/qpx_express/v1/model/aircraft_data.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/qpx_express/lib/google_api/qpx_express/v1/model/aircraft_data.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"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 "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 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.QPXExpress.V1.Model.AircraftData do
@moduledoc """
The make, model, and type of an aircraft.
## Attributes
- code (String): The aircraft code. For example, for a Boeing 777 the code would be 777. Defaults to: `null`.
- kind (String): Identifies this as an aircraftData object. Value: the fixed string qpxexpress#aircraftData Defaults to: `null`.
- name (String): The name of an aircraft, for example Boeing 777. Defaults to: `null`.
"""
defstruct [
:"code",
:"kind",
:"name"
]
end
defimpl Poison.Decoder, for: GoogleApi.QPXExpress.V1.Model.AircraftData do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.QPXExpress.V1.Model.AircraftData do
def encode(value, options) do
GoogleApi.QPXExpress.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 32.36 | 130 | 0.739802 |
03bd77417b8ff32cdbb2a3882e909e9944d8b57f | 1,663 | ex | Elixir | clients/prediction/lib/google_api/prediction/v16/model/analyze_data_description_numeric.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/prediction/lib/google_api/prediction/v16/model/analyze_data_description_numeric.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/prediction/lib/google_api/prediction/v16/model/analyze_data_description_numeric.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"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 "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 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.Prediction.V16.Model.AnalyzeDataDescriptionNumeric do
@moduledoc """
Description of the numeric values of this feature.
## Attributes
- count (String): Number of numeric values for this feature in the data set. Defaults to: `null`.
- mean (String): Mean of the numeric values of this feature in the data set. Defaults to: `null`.
- variance (String): Variance of the numeric values of this feature in the data set. Defaults to: `null`.
"""
defstruct [
:"count",
:"mean",
:"variance"
]
end
defimpl Poison.Decoder, for: GoogleApi.Prediction.V16.Model.AnalyzeDataDescriptionNumeric do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Prediction.V16.Model.AnalyzeDataDescriptionNumeric do
def encode(value, options) do
GoogleApi.Prediction.V16.Deserializer.serialize_non_nil(value, options)
end
end
| 33.26 | 107 | 0.750451 |
03bdc8dbb4cfa1b4204d083c81e8bc80293d9e0a | 351 | ex | Elixir | test/support/agent_of_change.ex | geometerio/euclid | 9a9e059ec77d87858ae7878df8d4d75dc01c57f8 | [
"MIT-0"
] | 4 | 2021-06-14T13:54:05.000Z | 2021-10-22T02:55:16.000Z | test/support/agent_of_change.ex | geometerio/euclid | 9a9e059ec77d87858ae7878df8d4d75dc01c57f8 | [
"MIT-0"
] | 3 | 2021-06-15T21:45:51.000Z | 2022-01-14T20:08:32.000Z | test/support/agent_of_change.ex | geometerio/euclid | 9a9e059ec77d87858ae7878df8d4d75dc01c57f8 | [
"MIT-0"
] | null | null | null | defmodule AgentOfChange do
use Agent
def start_link(_) do
Agent.start_link(fn -> 0 end, name: __MODULE__)
end
def get(), do: Agent.get(__MODULE__, fn state -> state end)
def add() do
value =
Agent.get_and_update(__MODULE__, fn value ->
value = value + 1
{value, value}
end)
{:ok, value}
end
end
| 17.55 | 61 | 0.606838 |
03bddda45bc98eea9753a8f723894f20fdba7398 | 389 | ex | Elixir | test/support/factory.ex | jeyemwey/radiator-spark | 2fba0a84eb43ab1d58e8ec58c6a07f64adf9cb9d | [
"MIT"
] | null | null | null | test/support/factory.ex | jeyemwey/radiator-spark | 2fba0a84eb43ab1d58e8ec58c6a07f64adf9cb9d | [
"MIT"
] | null | null | null | test/support/factory.ex | jeyemwey/radiator-spark | 2fba0a84eb43ab1d58e8ec58c6a07f64adf9cb9d | [
"MIT"
] | null | null | null | defmodule Radiator.Factory do
use ExMachina.Ecto, repo: Radiator.Repo
def podcast_factory do
title = sequence(:title, &"My Podcast ##{&1}")
%Radiator.Directory.Podcast{
title: title
}
end
def episode_factory do
title = sequence(:title, &"Episode ##{&1}")
%Radiator.Directory.Episode{
podcast: build(:podcast),
title: title
}
end
end
| 18.52381 | 50 | 0.637532 |
03bdec2b15dbe566733671977cd2da62cc2a2302 | 4,063 | ex | Elixir | lib/teslamate_web/live/car_live/summary.ex | gundalow/teslamate | 69b7c96284f2287393a5700d8a7afd797feb914a | [
"MIT"
] | 1 | 2019-10-14T20:49:45.000Z | 2019-10-14T20:49:45.000Z | lib/teslamate_web/live/car_live/summary.ex | gundalow/teslamate | 69b7c96284f2287393a5700d8a7afd797feb914a | [
"MIT"
] | null | null | null | lib/teslamate_web/live/car_live/summary.ex | gundalow/teslamate | 69b7c96284f2287393a5700d8a7afd797feb914a | [
"MIT"
] | 1 | 2019-12-03T20:40:02.000Z | 2019-12-03T20:40:02.000Z | defmodule TeslaMateWeb.CarLive.Summary do
use Phoenix.LiveView
import TeslaMateWeb.Gettext
alias TeslaMateWeb.CarView
alias TeslaMate.Vehicles.Vehicle.Summary
alias TeslaMate.Vehicles
@impl true
def mount(%{summary: %Summary{car: car} = summary, settings: settings}, socket) do
if connected?(socket) do
send(self(), :update_duration)
Vehicles.subscribe(car.id)
end
assigns = %{
car: car,
summary: summary,
settings: settings,
translate_state: &translate_state/1,
duration: duration_str(summary.since),
error: nil,
error_timeout: nil,
loading: false
}
{:ok, assign(socket, assigns)}
end
@impl true
def render(assigns) do
CarView.render("summary.html", assigns)
end
@impl true
def handle_event("suspend_logging", _val, socket) do
cancel_timer(socket.assigns.error_timeout)
send(self(), :suspend_logging)
{:noreply, assign(socket, loading: true)}
end
def handle_event("resume_logging", _val, socket) do
send(self(), :resume_logging)
{:noreply, assign(socket, loading: true)}
end
@impl true
def handle_info(:update_duration, socket) do
Process.send_after(self(), :update_duration, :timer.seconds(1))
{:noreply, assign(socket, duration: duration_str(socket.assigns.summary.since))}
end
def handle_info(:resume_logging, socket) do
:ok = Vehicles.resume_logging(socket.assigns.car.id)
{:noreply, socket}
end
def handle_info(:suspend_logging, socket) do
assigns =
case Vehicles.suspend_logging(socket.assigns.car.id) do
:ok ->
%{error: nil, error_timeout: nil, loading: false}
{:error, reason} ->
%{
error: translate_error(reason),
error_timeout: Process.send_after(self(), :hide_error, 5_000),
loading: false
}
end
{:noreply, assign(socket, assigns)}
end
def handle_info(:hide_error, socket) do
{:noreply, assign(socket, error: nil, error_timeout: nil)}
end
def handle_info(summary, socket) do
{:noreply,
assign(socket, summary: summary, duration: duration_str(summary.since), loading: false)}
end
defp translate_state(:start), do: nil
defp translate_state(:driving), do: gettext("driving")
defp translate_state(:charging), do: gettext("charging")
defp translate_state(:updating), do: gettext("updating")
defp translate_state(:suspended), do: gettext("falling asleep")
defp translate_state(:online), do: gettext("online")
defp translate_state(:offline), do: gettext("offline")
defp translate_state(:asleep), do: gettext("asleep")
defp translate_state(:unavailable), do: gettext("unavailable")
defp translate_error(:unlocked), do: gettext("Car is unlocked")
defp translate_error(:sentry_mode), do: gettext("Sentry mode is enabled")
defp translate_error(:shift_state), do: gettext("Shift state present")
defp translate_error(:temp_reading), do: gettext("Temperature readings")
defp translate_error(:preconditioning), do: gettext("Preconditioning")
defp translate_error(:user_present), do: gettext("User present")
defp translate_error(:update_in_progress), do: gettext("Update in progress")
defp translate_error(:sleep_mode_disabled_at_location),
do: gettext("Sleep Mode is disabled at current location")
defp cancel_timer(nil), do: :ok
defp cancel_timer(ref) when is_reference(ref), do: Process.cancel_timer(ref)
defp duration_str(nil), do: nil
defp duration_str(date), do: DateTime.utc_now() |> DateTime.diff(date, :second) |> sec_to_str()
@minute 60
@hour @minute * 60
@day @hour * 24
@week @day * 7
@divisor [@week, @day, @hour, @minute, 1]
def sec_to_str(sec) when sec < 5, do: nil
def sec_to_str(sec) do
{_, [s, m, h, d, w]} =
Enum.reduce(@divisor, {sec, []}, fn divisor, {n, acc} ->
{rem(n, divisor), [div(n, divisor) | acc]}
end)
["#{w} wk", "#{d} d", "#{h} h", "#{m} min", "#{s} s"]
|> Enum.reject(&String.starts_with?(&1, "0"))
|> Enum.take(2)
end
end
| 31.015267 | 97 | 0.675117 |
03be09f3ce848158483d3db69eafc2e887ae231b | 403 | ex | Elixir | ex/loqui/lib/loqui/types.ex | NorthIsUp/loqui | 8d394a7951fd3a82d109becc1aebbd9e7ccc894a | [
"MIT"
] | 147 | 2017-10-02T18:16:52.000Z | 2020-03-16T03:26:40.000Z | ex/loqui/lib/loqui/types.ex | NorthIsUp/loqui | 8d394a7951fd3a82d109becc1aebbd9e7ccc894a | [
"MIT"
] | 14 | 2017-09-19T16:13:32.000Z | 2019-06-25T21:18:47.000Z | ex/loqui/lib/loqui/types.ex | NorthIsUp/loqui | 8d394a7951fd3a82d109becc1aebbd9e7ccc894a | [
"MIT"
] | 25 | 2017-10-01T20:10:31.000Z | 2020-03-19T14:00:20.000Z | defmodule Loqui.Types do
@moduledoc false
defmacro __using__(_) do
quote do
@doc false
defmacro uint8 do
quote do: unsigned - integer - size(8)
end
@doc false
defmacro uint16 do
quote do: unsigned - integer - size(16)
end
@doc false
defmacro uint32 do
quote do: unsigned - integer - size(32)
end
end
end
end
| 17.521739 | 47 | 0.580645 |
03be0a314c5fe56f974c291a688004febe51067a | 736 | ex | Elixir | ros/ros_lib/lib/enum/ros_order_source_enum.ex | kujua/elixir-handbook | 4185ad8da7f652fdb59c799dc58bcb33fda10475 | [
"Apache-2.0"
] | 1 | 2019-07-01T18:47:28.000Z | 2019-07-01T18:47:28.000Z | ros/ros_lib/lib/enum/ros_order_source_enum.ex | kujua/elixir-handbook | 4185ad8da7f652fdb59c799dc58bcb33fda10475 | [
"Apache-2.0"
] | 4 | 2020-07-17T16:57:18.000Z | 2021-05-09T23:50:52.000Z | ros/ros_lib/lib/enum/ros_order_source_enum.ex | kujua/elixir-handbook | 4185ad8da7f652fdb59c799dc58bcb33fda10475 | [
"Apache-2.0"
] | null | null | null | defmodule Ros.Lib.Enum.OrderSource do
@moduledoc false
@type t :: %__MODULE__{
service: Ros.Lib.Enum.Base.t,
telephone: Ros.Lib.Enum.Base.t,
online_takeaway: Ros.Lib.Enum.Base.t,
telephone_takeaway: Ros.Lib.Enum.Base.t
}
@derive Jason.Encoder
defstruct service: %Ros.Lib.Enum.Base{key: :service, value: "Service"},
telephone: %Ros.Lib.Enum.Base{key: :telephone, value: "Telephone"},
online_takeaway: %Ros.Lib.Enum.Base{key: :online_takeaway, value: "Online Takeaway"},
telephone_takeaway: %Ros.Lib.Enum.Base{key: :telephone_takeaway, value: "Telephone Takeaway"}
end | 43.294118 | 105 | 0.588315 |
03be16ab6f30c3f251aaa0c0579e2ed9d6aa2c43 | 8,353 | ex | Elixir | lib/ex_docker_build.ex | filipevarjao/ex_docker_build | a263de4dda38cc849de9496e1c2f47781024996f | [
"MIT"
] | null | null | null | lib/ex_docker_build.ex | filipevarjao/ex_docker_build | a263de4dda38cc849de9496e1c2f47781024996f | [
"MIT"
] | null | null | null | lib/ex_docker_build.ex | filipevarjao/ex_docker_build | a263de4dda38cc849de9496e1c2f47781024996f | [
"MIT"
] | null | null | null | defmodule ExDockerBuild do
require Logger
alias ExDockerBuild.Tar
alias ExDockerBuild.API.{Docker, DockerRemoteAPI}
@spec create_layer(map(), keyword()) :: {:ok, Docker.image_id()} | {:error, any()}
def create_layer(payload, opts \\ []) do
wait = Keyword.get(opts, :wait, false)
with {:ok, container_id} <- create_container(payload),
{:ok, ^container_id} <- start_container(container_id),
{:ok, ^container_id} <- maybe_wait_container(container_id, wait),
{:ok, ^container_id} <- stop_container(container_id),
{:ok, new_image_id} <- commit(container_id, %{}),
:ok <- remove_container(container_id) do
{:ok, new_image_id}
else
{:error, _} = error -> error
end
end
@spec commit(Docker.container_id(), map()) :: {:ok, Docker.image_id()} | {:error, any()}
def commit(container_id, payload) do
case DockerRemoteAPI.commit(container_id, payload) do
{:ok, %{body: body, status_code: 201}} ->
%{"Id" => image_id} = Poison.decode!(body)
# ImageId comes in the form of sha256:IMGAGE_ID and the only part that we are
# interested in is in the IMAGE_ID
image_id = String.slice(image_id, 7..-1)
Logger.info("image created #{image_id}")
{:ok, image_id}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec create_container(map(), map()) :: {:ok, Docker.container_id()} | {:error, any()}
def create_container(payload, params \\ %{}) do
case DockerRemoteAPI.create_container(payload, params) do
{:ok, %{body: body, status_code: 201}} ->
%{"Id" => container_id} = Poison.decode!(body)
Logger.info("container created #{container_id}")
{:ok, container_id}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec remove_container(Docker.container_id(), map()) :: :ok | {:error, any()}
def remove_container(container_id, params \\ %{}) do
case DockerRemoteAPI.remove_container(container_id, params) do
{:ok, %{status_code: 204}} ->
:ok
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec start_container(Docker.container_id()) :: {:ok, Docker.container_id()} | {:error, any()}
def start_container(container_id) do
case DockerRemoteAPI.start_container(container_id) do
{:ok, %{status_code: code}} when code in [204, 304] ->
{:ok, container_id}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec stop_container(Docker.container_id()) :: {:ok, Docker.container_id()} | {:error, any()}
def stop_container(container_id) do
case DockerRemoteAPI.stop_container(container_id) do
{:ok, %{status_code: status}} when status in [204, 304] ->
{:ok, container_id}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec maybe_wait_container(Docker.container_id(), timeout) ::
{:ok, Docker.container_id()} | {:error, any()}
when timeout: boolean() | pos_integer()
def maybe_wait_container(container_id, timeout) when is_integer(timeout) do
# wait some time for a container to be up and running
# there's no way to know if a container is blocked running a CMD, ENTRYPOINT
# instruction, or is running a long task
# TODO: maybe use container inspect to see its current state or docker events
case wait_container(container_id, timeout) do
{:ok, _} = result ->
result
{:error, _} = error ->
error
end
end
def maybe_wait_container(container_id, true), do: wait_container(container_id)
def maybe_wait_container(container_id, false), do: {:ok, container_id}
@spec wait_container(Docker.container_id(), timeout) ::
{:ok, Docker.container_id()} | {:error, any()}
when timeout: pos_integer() | :infinity
def wait_container(container_id, timeout \\ :infinity) do
case DockerRemoteAPI.wait_container(container_id, timeout) do
{:ok, %{status_code: 200}} ->
{:ok, container_id}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec containers_logs(Docker.container_id(), map()) :: {:error, any()} | {:ok, [String.t()]}
def containers_logs(container_id, params \\ %{}) do
DockerRemoteAPI.containers_logs(container_id, params, stream_to: self())
end
@spec upload_file(Docker.container_id(), Path.t(), Path.t()) ::
{:ok, Docker.container_id()} | {:error, any()} | no_return()
def upload_file(container_id, input_path, output_path) do
case Tar.tar(input_path, File.cwd!()) do
{:ok, final_path} ->
archive_payload = File.read!(final_path)
try do
case DockerRemoteAPI.upload_file(container_id, archive_payload, output_path) do
{:ok, %{status_code: 200}} ->
{:ok, container_id}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
after
File.rm!(final_path)
end
{:error, _} = error ->
error
end
end
@spec pull(Docker.image_id()) :: :ok | {:error, any()}
def pull(image) do
Logger.info("pulling image #{image}")
case DockerRemoteAPI.pull(image) do
{:ok, %{status_code: 200}} ->
:ok
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec create_volume(map()) :: :ok | {:error, any()}
def create_volume(payload) do
case DockerRemoteAPI.create_volume(payload) do
{:ok, %{status_code: 201}} ->
:ok
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec delete_image(Docker.image_id()) :: :ok | {:error, any()}
def delete_image(image) do
delete_image(image, false)
end
@spec delete_image(Docker.image_id(), boolean()) :: :ok | {:error, any()}
def delete_image(image, force) do
Logger.info("deleting image by image id #{image}")
case DockerRemoteAPI.delete_image(image, force) do
{:ok, %{status_code: 200}} ->
:ok
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec push_image(Docker.image_id(), Docker.tag_name(), Docker.docker_credentials()) ::
:ok | {:error, any()}
def push_image(image, tag_name, credentials) do
Logger.info("pushing image id #{image} to docker registry")
case DockerRemoteAPI.push_image(image, tag_name, credentials) do
{:ok, %{status_code: 200}} ->
:ok
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec tag_image(
Docker.image_id(),
Docker.repository_name(),
Docker.tag_name(),
Docker.docker_credentials()
) :: :ok | {:error, any()}
def tag_image(image, repo_name, tag_name, credentials) do
case DockerRemoteAPI.tag_image(image, repo_name, tag_name, credentials) do
{:ok, %{status_code: 201}} ->
:ok
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
@spec container_inspect(Docker.container_id(), boolean()) :: {:ok, any()} | {:error, any()}
def container_inspect(container_id, size) do
Logger.info("inspecting container by container id #{container_id}")
case DockerRemoteAPI.container_inspect(container_id, size) do
{:ok, %{status_code: 200, body: body}} ->
{:ok, Poison.decode!(body)}
{:ok, %{body: body, status_code: _}} ->
{:error, body}
{:error, %{reason: reason}} ->
{:error, reason}
end
end
end
| 30.822878 | 96 | 0.593918 |
03be16e49e66a375235cec54b47c0a49e161c2e2 | 34 | ex | Elixir | lib/ueberauth_shopify.ex | ringofhealth/ueberauth_shopify | b7aebf005e2c9bb22a3476cb6f2f3ab523fb4ae4 | [
"MIT"
] | 3 | 2016-11-07T19:04:50.000Z | 2017-02-04T01:38:45.000Z | lib/ueberauth_shopify.ex | ringofhealth/ueberauth_shopify | b7aebf005e2c9bb22a3476cb6f2f3ab523fb4ae4 | [
"MIT"
] | 2 | 2017-04-03T18:43:55.000Z | 2020-01-16T16:53:58.000Z | lib/ueberauth_shopify.ex | ringofhealth/ueberauth_shopify | b7aebf005e2c9bb22a3476cb6f2f3ab523fb4ae4 | [
"MIT"
] | 8 | 2017-09-19T10:38:27.000Z | 2022-01-27T01:35:26.000Z | defmodule UeberauthShopify do
end
| 11.333333 | 29 | 0.882353 |
03be192078040a9210f434131aa32b08edef4c14 | 695 | ex | Elixir | lib/bandit/http2/frame/unknown.ex | moogle19/bandit | 610aebaac2ddf76d53faac109b07e519727affb6 | [
"MIT"
] | 226 | 2020-05-18T09:36:32.000Z | 2022-03-30T00:25:51.000Z | lib/bandit/http2/frame/unknown.ex | moogle19/bandit | 610aebaac2ddf76d53faac109b07e519727affb6 | [
"MIT"
] | 11 | 2021-10-11T13:48:24.000Z | 2022-03-05T20:18:11.000Z | lib/bandit/http2/frame/unknown.ex | moogle19/bandit | 610aebaac2ddf76d53faac109b07e519727affb6 | [
"MIT"
] | 7 | 2020-05-18T09:36:35.000Z | 2022-02-08T11:12:16.000Z | defmodule Bandit.HTTP2.Frame.Unknown do
@moduledoc false
alias Bandit.HTTP2.{Frame, Stream}
defstruct type: nil,
flags: nil,
stream_id: nil,
payload: nil
@typedoc "An HTTP/2 frame of unknown type"
@type t :: %__MODULE__{
type: Frame.frame_type(),
flags: Frame.flags(),
stream_id: Stream.stream_id(),
payload: iodata()
}
# Note this is arity 4
@spec deserialize(Frame.frame_type(), Frame.flags(), Stream.stream_id(), iodata()) :: {:ok, t()}
def deserialize(type, flags, stream_id, payload) do
{:ok, %__MODULE__{type: type, flags: flags, stream_id: stream_id, payload: payload}}
end
end
| 27.8 | 98 | 0.615827 |
03be259b92108d4393807d9a40717c8671250bbc | 743 | exs | Elixir | test/brando_pages/pages/utils_test.exs | twined/brando_pages | cc9905bf9ab47fdcaef9588a056f19dc18f036a9 | [
"MIT"
] | null | null | null | test/brando_pages/pages/utils_test.exs | twined/brando_pages | cc9905bf9ab47fdcaef9588a056f19dc18f036a9 | [
"MIT"
] | null | null | null | test/brando_pages/pages/utils_test.exs | twined/brando_pages | cc9905bf9ab47fdcaef9588a056f19dc18f036a9 | [
"MIT"
] | null | null | null | defmodule Brando.Pages.UtilsTest do
use ExUnit.Case
use BrandoPages.ConnCase
use Plug.Test
use RouterHelper
alias BrandoPages.Factory
alias Brando.Pages.Utils
test "render_fragment invalid" do
{:safe, return} = Utils.render_fragment("invalid/key")
assert return =~ "Missing page fragment"
assert return =~ "invalid/key"
assert return =~ Brando.config(:default_language)
end
test "render_fragment valid" do
user = Factory.insert(:user)
Factory.insert(:page_fragment, creator: user)
{:safe, return} = Utils.render_fragment("key/path")
assert return =~ "Missing page fragment"
{:safe, return} = Utils.render_fragment("key/path", "en")
assert return =~ "<p>Text in p.</p>"
end
end
| 25.62069 | 61 | 0.697174 |
03be3cc0aff94697add33e5ba4e0ccce6d6df8e2 | 1,274 | ex | Elixir | lib/brando_admin/components/form/input.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | lib/brando_admin/components/form/input.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | lib/brando_admin/components/form/input.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | defmodule BrandoAdmin.Components.Form.Input do
use Surface.LiveComponent
use Phoenix.HTML
prop current_user, :any
prop form, :any
prop input, :any
prop blueprint, :any
prop uploads, :any
data component_module, :any
data component_opts, :any
data component_id, :string
def mount(socket) do
{:ok, socket}
end
def update(assigns, socket) do
component_module =
case assigns.input.type do
{:component, module} ->
module
type ->
input_type = type |> to_string |> Recase.to_pascal()
Module.concat([__MODULE__, input_type])
end
component_id =
Enum.join(
[assigns.form.id, assigns.input.name],
"-"
)
{:ok,
socket
|> assign(assigns)
|> assign(:component_id, component_id)
|> assign(:component_module, component_module)
|> assign(:component_opts, assigns.input.opts)}
end
def render(assigns) do
~F"""
<div class="brando-input">
{live_component(@socket, @component_module,
id: @component_id,
form: @form,
input: @input,
blueprint: @blueprint,
uploads: @uploads,
opts: @component_opts,
current_user: @current_user
)}
</div>
"""
end
end
| 21.233333 | 62 | 0.603611 |
03be43cec55ba0618e30cf195c3de4996506ae2d | 795 | exs | Elixir | config/test.exs | corybuecker/simple-budget | d86241ff712552267da87052120468b01d2b8f41 | [
"MIT"
] | 2 | 2019-04-02T01:06:40.000Z | 2019-05-13T01:12:24.000Z | config/test.exs | corybuecker/simple-budget | d86241ff712552267da87052120468b01d2b8f41 | [
"MIT"
] | 7 | 2018-12-27T12:33:38.000Z | 2021-03-08T22:31:14.000Z | config/test.exs | corybuecker/simple-budget | d86241ff712552267da87052120468b01d2b8f41 | [
"MIT"
] | null | null | null | use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :simple_budget, SimpleBudgetWeb.Endpoint,
http: [port: 4001],
server: false,
secret_key_base:
"SECRET_KEY_BASESECRET_KEY_BASESECRET_KEY_BASESECRET_KEY_BASESECRET_KEY_BASESECRET_KEY_BASE"
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :simple_budget, SimpleBudget.Repo,
url: System.get_env("TEST_DATABASE_URL"),
pool: Ecto.Adapters.SQL.Sandbox
config :argon2_elixir, t_cost: 2, m_cost: 8
config :simple_budget,
token_key: "development-use-only",
google_client_id: "test"
config :simple_budget,
cookie_signing_salt: "COOKIE_SIGNING_SALT",
cookie_encryption_salt: "COOKIE_ENCRYPTION_SALT"
| 28.392857 | 96 | 0.788679 |
03be7fef9351c389ad83d4305c8c1c54c38defb0 | 9,885 | ex | Elixir | lib/ex_saga/retry.ex | naramore/ex_saga | 66c6b64867f28a1bbfb8ec2b6a786469b5f84e47 | [
"MIT"
] | null | null | null | lib/ex_saga/retry.ex | naramore/ex_saga | 66c6b64867f28a1bbfb8ec2b6a786469b5f84e47 | [
"MIT"
] | 17 | 2019-02-06T03:51:03.000Z | 2019-10-22T10:15:48.000Z | lib/ex_saga/retry.ex | naramore/ex_saga | 66c6b64867f28a1bbfb8ec2b6a786469b5f84e47 | [
"MIT"
] | null | null | null | defmodule ExSaga.Retry do
@moduledoc """
"""
alias ExSaga.{DryRun, Event, Hook, Stage, Step, Stepable}
@typedoc """
"""
@type accumulator :: %{
:on_retry => module,
:hooks_left => [Hook.t()],
:retry_updates_left => [{Stage.full_name(), module}],
:update => retry_result | nil,
:effects_so_far => Stage.effects(),
:abort? => boolean,
optional(term) => term
}
@typedoc """
"""
@type retry_opts :: Keyword.t()
@typedoc """
"""
@type retry_state :: term
@typedoc """
"""
@type wait :: {non_neg_integer, System.time_unit()}
@typedoc """
"""
@type retry_result ::
{:retry, wait, retry_state}
| {:noretry, retry_state}
@typedoc """
"""
@type update_result :: :ok | {:ok, retry_state}
@doc """
"""
@callback init(retry_opts) :: {:ok, retry_state, retry_opts}
@doc """
"""
@callback handle_retry(retry_state, retry_opts) :: retry_result
@doc """
"""
@callback update(retry_state, origin_full_name :: Stage.full_name(), retry_result) :: update_result
defmacro __using__(opts) do
shared_state? = Keyword.get(opts, :shared_state?, true)
quote do
@behaviour ExSaga.Retry
@shared_state? unquote(shared_state?)
alias ExSaga.Retry
@doc false
@spec shared_state?() :: boolean
def shared_state?(), do: @shared_state?
@impl Retry
def update(_retry_state, _stage_name, _retry_opts) do
:ok
end
defoverridable update: 3
end
end
@doc """
"""
@spec start_retry(accumulator, Event.t(), retry_opts) :: Event.t() | nil
def start_retry(%{abort?: true}, _event, _retry_opts),
do: nil
def start_retry(acc, event, retry_opts) do
%{effects_so_far: effects_so_far} = acc
retry_state = get_retry_state(effects_so_far, acc.on_retry, event.stage_name)
if is_nil(retry_state) do
Event.update(event,
name: [:starting, :retry, :init],
context: retry_opts
)
else
Event.update(event,
name: [:starting, :retry, :handler],
context: {retry_state, retry_opts}
)
end
end
@doc false
@spec get_retry_state(Stage.effects(), module, Stage.full_name()) :: retry_state
defp get_retry_state(effects_so_far, mod, name) do
get_in(effects_so_far, get_retry_state_path(mod, name))
end
@doc false
@spec update_retry_state(Stage.effects(), module, Stage.full_name(), retry_state) :: Stage.effects()
defp update_retry_state(%{__retry__: retry_states} = effects_so_far, mod, name, retry_state)
when is_map(retry_states) do
put_in(effects_so_far, get_retry_state_path(mod, name), retry_state)
end
defp update_retry_state(effects_so_far, mod, name, retry_state) do
[_, key] = get_retry_state_path(mod, name)
Map.merge(effects_so_far, %{__retry__: %{key => retry_state}})
end
@doc false
@spec get_retry_state_path(module, Stage.full_name()) :: retry_state
defp get_retry_state_path(mod, name) do
if mod.shared_state?() do
[:__retry__, mod]
else
[:__retry__, name]
end
end
@doc """
"""
@spec step(accumulator, Event.t(), Step.opts()) :: {:retry | :noretry | :continue, Event.t(), accumulator}
def step(acc, event, opts \\ [])
def step(%{retry_updates_left: []} = acc, %Event{name: [:starting, :retry, :init]} = event, opts) do
event = execute_retry_init(acc, event, opts)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
def step(%{retry_updates_left: []} = acc, %Event{name: [:completed, :retry, :init]} = event, opts) do
case event.context do
{:ok, retry_state, retry_opts} ->
event =
Event.update(event,
name: [:starting, :retry, :handler],
context: {retry_state, retry_opts}
)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
{:error, reason} ->
%{effects_so_far: effects_so_far} = acc
event =
Event.update(event,
name: [:starting, :error_handler],
context: {reason, event, effects_so_far}
)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
end
def step(%{retry_updates_left: []} = acc, %Event{name: [:starting, :retry, :handler]} = event, opts) do
event = execute_retry_handler(acc, event, opts)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
def step(%{retry_updates_left: [], update: nil} = acc, %Event{name: [:completed, :retry, :handler]} = event, opts) do
%{effects_so_far: effects_so_far} = acc
case event.context do
{:retry, _wait, retry_state} ->
# TODO: implement the actual wait...
%{
acc
| effects_so_far: update_retry_state(effects_so_far, acc.on_retry, event.stage_name, retry_state),
hooks_left: Hook.merge_hooks(acc, opts),
retry_updates_left: Keyword.get(opts, :retry_updates, []),
update: event.context
}
|> step(event, opts)
{:noretry, retry_state} ->
%{
acc
| effects_so_far: update_retry_state(effects_so_far, acc.on_retry, event.stage_name, retry_state),
hooks_left: Hook.merge_hooks(acc, opts),
retry_updates_left: Keyword.get(opts, :retry_updates, []),
update: event.context
}
|> step(event, opts)
{:error, reason} ->
event =
Event.update(event,
name: [:starting, :error_handler],
context: {reason, event, effects_so_far}
)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
end
def step(%{retry_updates_left: []} = acc, %Event{name: [:completed, :retry, n]} = event, _opts)
when n in [:handler, :update] do
case Map.get(acc, :update, {:noretry, nil}) do
{:retry, _wait, _retry_state} -> {:retry, event, %{acc | update: nil}}
{:noretry, _retry_state} -> {:noretry, event, %{acc | update: nil}}
end
end
def step(
%{retry_updates_left: [{path, retry} | us]} = acc,
%Event{name: [:completed, :retry, :handler]} = event,
opts
) do
%{update: update} = acc
event =
Event.update(event,
name: [:starting, :retry, :update],
context: {path, retry, update}
)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts), retry_updates_left: us}}
end
def step(%{retry_updates_left: [_ | _]} = acc, %Event{name: [:completed, :retry, :update]} = event, opts) do
%{effects_so_far: effects_so_far} = acc
case event.context do
:ok ->
step(acc, %{event | name: [:completed, :retry, :handler]}, opts)
{:ok, retry_state} ->
%{acc | effects_so_far: update_retry_state(effects_so_far, acc.on_retry, event.stage_name, retry_state)}
|> step(%{event | name: [:completed, :retry, :handler]}, opts)
{:error, reason} ->
event =
Event.update(event,
name: [:starting, :error_handler],
context: {reason, event, effects_so_far}
)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
end
def step(acc, %Event{name: [:starting, :retry, :update]} = event, opts) do
event = execute_retry_update(acc, event, opts)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
def step(acc, event, opts) do
reason = {:unknown_event, event}
%{effects_so_far: effects_so_far} = acc
event =
Event.update(event,
name: [:starting, :error_handler],
context: {reason, event, effects_so_far}
)
{:continue, event, %{acc | hooks_left: Hook.merge_hooks(acc, opts)}}
end
@doc false
@spec execute_retry_init(accumulator, Event.t(), Stepable.opts()) :: Event.t()
defp execute_retry_init(acc, event, opts) do
retry_handler = Map.get(acc, :on_retry)
opts = DryRun.from_stepable(event, opts, {:ok, nil})
result =
case DryRun.maybe_execute(&retry_handler.init/1, [event.context], opts) do
{:ok, retry_state, retry_opts} -> {:ok, retry_state, retry_opts}
otherwise -> {:error, {:unsupported_retry_init_result_form, otherwise}}
end
Event.update(event,
name: [:completed, :retry, :init],
context: result
)
end
@doc false
@spec execute_retry_handler(accumulator, Event.t(), Stepable.opts()) :: Event.t()
defp execute_retry_handler(acc, event, opts) do
{retry_state, retry_opts} = event.context
retry_handler = Map.get(acc, :on_retry)
opts = DryRun.from_stepable(event, opts, {:ok, nil})
result =
case DryRun.maybe_execute(&retry_handler.handle_retry/2, [retry_state, retry_opts], opts) do
{:retry, wait, retry_state} -> {:retry, wait, retry_state}
{:noretry, retry_state} -> {:noretry, retry_state}
otherwise -> {:error, {:unsupported_retry_handler_result_form, otherwise}}
end
Event.update(event,
name: [:completed, :retry, :handler],
context: result
)
end
@doc false
@spec execute_retry_update(accumulator, Event.t(), Stepable.opts()) :: Event.t()
defp execute_retry_update(acc, event, opts) do
{path, retry, retry_result} = event.context
%{effects_so_far: effects_so_far} = acc
retry_state = get_retry_state(effects_so_far, retry, path)
opts = DryRun.from_stepable(event, opts, {:ok, nil})
result =
case DryRun.maybe_execute(&retry.update/3, [retry_state, path, retry_result], opts) do
:ok -> :ok
{:ok, retry_state} -> {:ok, retry_state}
otherwise -> {:error, {:unsupported_retry_handler_result_form, otherwise}}
end
Event.update(event,
name: [:completed, :retry, :update],
context: result
)
end
end
| 30.603715 | 119 | 0.616388 |
03be858b40522e90b0c36de70267d7608b7396c4 | 1,719 | ex | Elixir | lib/decompilerl.ex | aerosol/decompilerl | aa4b3e8e9fc3542ce6baf058dd2cfdb413b4bb81 | [
"WTFPL"
] | 27 | 2016-05-07T21:29:25.000Z | 2022-02-03T08:38:39.000Z | lib/decompilerl.ex | aerosol/decompilerl | aa4b3e8e9fc3542ce6baf058dd2cfdb413b4bb81 | [
"WTFPL"
] | 2 | 2017-05-18T23:17:02.000Z | 2018-01-24T22:55:00.000Z | lib/decompilerl.ex | aerosol/decompilerl | aa4b3e8e9fc3542ce6baf058dd2cfdb413b4bb81 | [
"WTFPL"
] | 4 | 2017-05-18T22:05:59.000Z | 2021-03-23T18:57:29.000Z | defmodule Decompilerl do
def decompile(module_or_path, opts \\ []) do
device = Keyword.get(opts, :device, :stdio)
skip_info? = Keyword.get(opts, :skip_info, false)
module_or_path
|> get_beam()
|> Enum.map(&do_decompile(&1, skip_info?))
|> write_to(device)
end
defp get_beam(module) when is_atom(module) do
{^module, bytecode, _file} = :code.get_object_code(module)
[bytecode]
end
defp get_beam(path) when is_binary(path) do
case Path.extname(path) do
".beam" ->
[String.to_charlist(path)]
".ex" ->
code = File.read!(path)
for {_module, beam} <- Code.compile_string(code) do
beam
end
end
end
defp do_decompile(bytecode_or_path, skip_info?) do
{:ok, {_, [abstract_code: {_, ac}]}} = :beam_lib.chunks(bytecode_or_path, [:abstract_code])
ac = if skip_info?, do: skip_info(ac), else: ac
:erl_prettypr.format(:erl_syntax.form_list(ac))
end
defp skip_info(ac) do
ac
|> Enum.reduce([], fn item, acc ->
case item do
{:attribute, _, :export, exports} ->
exports = exports -- [__info__: 1]
item = put_elem(item, 3, exports)
[item | acc]
{:attribute, _, :spec, {{:__info__, 1}, _}} ->
acc
{:function, _, :__info__, 1, _} ->
acc
_ ->
[item | acc]
end
end)
|> Enum.reverse()
end
defp write_to(code, device) when is_atom(device) or is_pid(device) do
IO.puts(device, code)
end
defp write_to(code, filename) when is_binary(filename) do
{:ok, result} =
File.open(filename, [:write], fn file ->
IO.binwrite(file, code)
end)
result
end
end
| 23.875 | 95 | 0.582897 |
03be8e74b7339237fb28eaa89b93c81e65180a82 | 2,118 | exs | Elixir | test/grizzly/command_class/sensor_multilevel/supported_get_sensor_test.exs | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | test/grizzly/command_class/sensor_multilevel/supported_get_sensor_test.exs | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | test/grizzly/command_class/sensor_multilevel/supported_get_sensor_test.exs | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | defmodule Grizzly.CommandClass.SensorMultilevel.SupportedGetSensor.Test do
use ExUnit.Case, async: true
alias Grizzly.Packet
alias Grizzly.CommandClass.SensorMultilevel.SupportedGetSensor
describe "implements the Grizzly.Command behaviour" do
test "initializes command" do
assert {:ok, %SupportedGetSensor{}} = SupportedGetSensor.init(seq_number: 0x09)
end
test "encodes correctly" do
{:ok, command} = SupportedGetSensor.init(seq_number: 0x08)
binary = <<35, 2, 128, 208, 8, 0, 0, 3, 2, 0, 0x31, 0x01>>
assert {:ok, binary} == SupportedGetSensor.encode(command)
end
test "handles ack response" do
{:ok, command} = SupportedGetSensor.init(seq_number: 0x10)
packet = Packet.new(seq_number: 0x10, types: [:ack_response])
assert {:continue, ^command} = SupportedGetSensor.handle_response(command, packet)
end
test "handles nack response" do
{:ok, command} = SupportedGetSensor.init(seq_number: 0x10, retries: 0)
packet = Packet.new(seq_number: 0x10, types: [:nack_response])
assert {:done, {:error, :nack_response}} ==
SupportedGetSensor.handle_response(command, packet)
end
test "handles retries" do
{:ok, command} = SupportedGetSensor.init(seq_number: 0x10)
packet = Packet.new(seq_number: 0x10, types: [:nack_response])
assert {:retry, %SupportedGetSensor{retries: 1}} =
SupportedGetSensor.handle_response(command, packet)
end
test "handles sensor multilevel report" do
report = %{
command_class: :sensor_multilevel,
command: :supported_sensor_report,
value: [:illuminance, :power]
}
{:ok, command} = SupportedGetSensor.init([])
packet = Packet.new(body: report)
assert {:done, {:ok, [:illuminance, :power]}} ==
SupportedGetSensor.handle_response(command, packet)
end
test "handles other responses" do
{:ok, command} = SupportedGetSensor.init([])
assert {:continue, ^command} = SupportedGetSensor.handle_response(command, %{value: 100})
end
end
end
| 33.619048 | 95 | 0.670916 |
03bea7ea473696fea4d2b41e82e45fa4b49f73bb | 6,818 | exs | Elixir | test/zoneinfo/time_zone_database_test.exs | wojtekmach/zoneinfo | 640de834203ef8288df6ad6b4ca2e95a0cf20710 | [
"Apache-2.0"
] | null | null | null | test/zoneinfo/time_zone_database_test.exs | wojtekmach/zoneinfo | 640de834203ef8288df6ad6b4ca2e95a0cf20710 | [
"Apache-2.0"
] | null | null | null | test/zoneinfo/time_zone_database_test.exs | wojtekmach/zoneinfo | 640de834203ef8288df6ad6b4ca2e95a0cf20710 | [
"Apache-2.0"
] | null | null | null | defmodule Zoneinfo.TimeZoneDatabaseTest do
use ExUnit.Case, async: true
import Zoneinfo.Utils
@truth Tz
# Set these to the range of times that are important
# Make sure that the Makefile generates tzif files that include range.
@earliest_time ~N[1940-01-02 00:00:00]
@latest_time ~N[2038-01-01 00:00:00]
# This is a list of known utc_offset discrepancies with Tz
#
# The total time zone offset (utc_offset + std_offset) is correct so time
# zone conversions will return the right answer. However, the utc_offset and
# std_offset differ from Tz.
@std_offset_discrepancies %{
# Europe/Monaco and Europe/Paris
#
# Zoneinfo returned {:ok, %{std_offset: 3600, utc_offset: 3600, zone_abbr: "WEMT"}}
# Tz returned {:ok, %{std_offset: 7200, utc_offset: 0, zone_abbr: "WEMT"}}
#
# Tz is right. The UTC offset heuristic messes up since the right answer is
# a 2 hour DST offset. There's a nearby standard time offset that would be
# 1 hour in both cases and the heuristic rules prioritize matching that
# one. You can tell by comparing zone abbreviations that the real one is
# the 2 hour offset.
"Europe/Monaco" => [1945],
"Europe/Paris" => 1944..1945,
# Africa/Casablanca and Africa/El_Aaiun
#
# Zoneinfo returned {:ok, %{std_offset: 3600, utc_offset: -3600, zone_abbr: "+00"}}
# Tz returned {:ok, %{std_offset: -3600, utc_offset: 3600, zone_abbr: "+00"}}
#
# Casablanca and El Aaiun are on DST (+01) most of the year and then drops
# back to standard time (+00) for Ramadan. I think that both Zoneinfo and
# Tz are wrong. Since it's a standard time, it seems like std_offset should
# be 0. Unfortunately, the TZif file marks the time zone records as "dst"
# which I think is an artifact of the IANA rules database hardcoding the
# start and end dates.
"Africa/Casablanca" => 2019..2037,
"Africa/El_Aaiun" => 2019..2037
}
test "quick zoneinfo consistency check for utc iso days" do
check_time_zone(
"America/New_York",
@earliest_time,
@latest_time,
step_size("quick1")
)
end
test "quick zoneinfo consistency check for wall clock inputs" do
check_wall_clock(
"Europe/London",
@earliest_time,
@latest_time,
step_size("quick2")
)
end
# Run through all of the time zone in "slow" mode
for time_zone <- Zoneinfo.time_zones() do
@tag :slow
test "zoneinfo consistent for #{time_zone} for utc iso days" do
check_time_zone(
unquote(time_zone),
@earliest_time,
@latest_time,
step_size(unquote(time_zone))
)
end
end
for time_zone <- Zoneinfo.time_zones() do
@tag :slow
test "zoneinfo consistent for #{time_zone} for wall clock inputs" do
check_wall_clock(
unquote(time_zone),
@earliest_time,
@latest_time,
step_size(unquote(time_zone))
)
end
end
defp step_size(time_zone) do
# Vary the step size deterministically per time zone to try to cover a few
# more boundary conditions
nominal_step_size = 7 * 60 * 60 * 24
nominal_step_size + :erlang.phash2(time_zone, div(nominal_step_size, 4)) -
div(nominal_step_size, 8)
end
defp check_time_zone(time_zone, time, end_time, step_size) do
iso_days =
Calendar.ISO.naive_datetime_to_iso_days(
time.year,
time.month,
time.day,
time.hour,
time.minute,
time.second,
{0, 6}
)
next_time = NaiveDateTime.add(time, step_size)
zoneinfo_result =
Zoneinfo.TimeZoneDatabase.time_zone_period_from_utc_iso_days(iso_days, time_zone)
expected_result =
@truth.TimeZoneDatabase.time_zone_period_from_utc_iso_days(iso_days, time_zone)
context = {time_zone, time.year}
assert same_results?(context, zoneinfo_result, expected_result), """
Assertion failed for #{time_zone} @ #{inspect(time)}
iso_days=#{inspect(iso_days)}
gregorian_seconds=#{inspect(iso_days_to_gregorian_seconds(iso_days))}
Zoneinfo returned #{inspect(zoneinfo_result)}
#{@truth |> to_string() |> String.trim_leading("Elixir.")} returned #{
inspect(expected_result)
}
Add #{inspect(context)} to known discrepancy if this needs to be ignored
"""
if NaiveDateTime.compare(next_time, end_time) == :lt do
check_time_zone(time_zone, next_time, end_time, step_size)
end
end
defp same_period?(
_context,
%{std_offset: s, utc_offset: u, zone_abbr: z},
%{std_offset: s, utc_offset: u, zone_abbr: z}
),
do: true
defp same_period?(
context,
%{std_offset: tzf1, utc_offset: tzf2, zone_abbr: z},
%{std_offset: tz1, utc_offset: tz2, zone_abbr: z}
)
when tzf1 + tzf2 == tz1 + tz2 do
# Time zone calculations will work since the sum of the two gets the right
# answer. Elixir's calendar computations currently always sum the two.
#
# However, if a user's program needs to know the utc offset or the offset
# from standard time, it will get the wrong answer.
#
# If we know about the discrepancy, return that the answer is good.
{time_zone, year} = context
case @std_offset_discrepancies[time_zone] do
nil -> false
years -> year in years
end
end
defp same_period?(_context, _a, _b), do: false
defp same_results?(context, {:ok, p1}, {:ok, p2}) do
same_period?(context, p1, p2)
end
defp same_results?(context, {:gap, {ap1, t1}, {ap2, t2}}, {:gap, {bp1, t1}, {bp2, t2}}) do
same_period?(context, ap1, bp1) and same_period?(context, ap2, bp2)
end
defp same_results?(context, {:ambiguous, ap1, ap2}, {:ambiguous, bp1, bp2}) do
same_period?(context, ap1, bp1) and same_period?(context, ap2, bp2)
end
defp same_results?(_context, a, b), do: a == b
defp check_wall_clock(time_zone, time, end_time, step_size) do
next_time = NaiveDateTime.add(time, step_size)
zoneinfo_result =
Zoneinfo.TimeZoneDatabase.time_zone_periods_from_wall_datetime(time, time_zone)
expected_result =
@truth.TimeZoneDatabase.time_zone_periods_from_wall_datetime(time, time_zone)
context = {time_zone, time.year}
assert same_results?(context, zoneinfo_result, expected_result), """
Assertion failed for #{time_zone} @ #{inspect(time)}
Zoneinfo returned #{inspect(zoneinfo_result)}
#{@truth |> to_string() |> String.trim_leading("Elixir.")} returned #{
inspect(expected_result)
}
Add #{inspect(context)} to known discrepancy if this needs to be ignored
"""
if NaiveDateTime.compare(next_time, end_time) == :lt do
check_wall_clock(time_zone, next_time, end_time, step_size)
end
end
end
| 32.312796 | 92 | 0.669698 |
03beb7dc38958749600c8a29afddac339a805e0a | 2,182 | exs | Elixir | Phoenix_Sockets/example1/config/prod.exs | shubhamagiwal/DOSFall2017 | 3c1522c4163f57402f147b50614d4051b05a080f | [
"MIT"
] | 3 | 2019-10-28T21:02:55.000Z | 2020-10-01T02:29:37.000Z | Phoenix_Sockets/example1/config/prod.exs | shubhamagiwal/DOSFall2017 | 3c1522c4163f57402f147b50614d4051b05a080f | [
"MIT"
] | null | null | null | Phoenix_Sockets/example1/config/prod.exs | shubhamagiwal/DOSFall2017 | 3c1522c4163f57402f147b50614d4051b05a080f | [
"MIT"
] | 4 | 2019-10-12T19:41:58.000Z | 2021-09-24T20:24:47.000Z | use Mix.Config
# For production, we often load configuration from external
# sources, such as your system environment. For this reason,
# you won't find the :http configuration below, but set inside
# Example1Web.Endpoint.init/2 when load_from_system_env is
# true. Any dynamic configuration should be done there.
#
# Don't forget to configure the url host to something meaningful,
# Phoenix uses this information when generating URLs.
#
# Finally, we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the mix phx.digest task
# which you typically run after static files are built.
config :example1, Example1Web.Endpoint,
load_from_system_env: true,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :example1, Example1Web.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [:inet6,
# port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :example1, Example1Web.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :example1, Example1Web.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
import_config "prod.secret.exs"
| 33.569231 | 67 | 0.722731 |
03bede9e89f09905dfc542cc6dd2172074428672 | 1,860 | ex | Elixir | clients/playable_locations/lib/google_api/playable_locations/v3/model/google_type_lat_lng.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/playable_locations/lib/google_api/playable_locations/v3/model/google_type_lat_lng.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/playable_locations/lib/google_api/playable_locations/v3/model/google_type_lat_lng.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.PlayableLocations.V3.Model.GoogleTypeLatLng do
@moduledoc """
An object representing a latitude/longitude pair. This is expressed as a pair of doubles representing degrees latitude and degrees longitude. Unless specified otherwise, this must conform to the WGS84 standard. Values must be within normalized ranges.
## Attributes
* `latitude` (*type:* `float()`, *default:* `nil`) - The latitude in degrees. It must be in the range [-90.0, +90.0].
* `longitude` (*type:* `float()`, *default:* `nil`) - The longitude in degrees. It must be in the range [-180.0, +180.0].
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:latitude => float(),
:longitude => float()
}
field(:latitude)
field(:longitude)
end
defimpl Poison.Decoder, for: GoogleApi.PlayableLocations.V3.Model.GoogleTypeLatLng do
def decode(value, options) do
GoogleApi.PlayableLocations.V3.Model.GoogleTypeLatLng.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.PlayableLocations.V3.Model.GoogleTypeLatLng do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.2 | 253 | 0.733333 |
03beefc66d759b8f72baf480728dabb82c612f6a | 3,422 | ex | Elixir | learning/programming_elixir/issues/lib/issues/table_formatter.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | 2 | 2020-01-20T20:15:20.000Z | 2020-02-27T11:08:42.000Z | learning/programming_elixir/issues/lib/issues/table_formatter.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | learning/programming_elixir/issues/lib/issues/table_formatter.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | defmodule Issues.TableFormatter do
import Enum, only: [ each: 2, map: 2, map_join: 3, max: 1 ]
@doc """
Takes a list of row data, where each row is a Map, and a list of
headers. Prints a table to STDOUT of the data from each row
identified by each header. That is, each header identifies a column,
and those columns are extracted and printed from the rows.
We calculate the width of each column to fit the longest element
in that column.
"""
def print_table_for_columns(rows, headers) do
with data_by_columns = split_into_columns(rows, headers),
column_widths = widths_of(data_by_columns),
format = format_for(column_widths)
do
puts_one_line_in_columns(headers, format)
IO.puts(separator(column_widths))
puts_in_columns(data_by_columns, format)
end
end
@doc """
Given a list of rows, where each row contains a keyed list
of columns, return a list containing lists of the data in
each column. The `headers` parameter contains the
list of columns to extract
## Example
iex> list = [Enum.into([{"a", "1"},{"b", "2"},{"c", "3"}], %{}),
...> Enum.into([{"a", "4"},{"b", "5"},{"c", "6"}], %{})]
iex> Issues.TableFormatter.split_into_columns(list, [ "a", "b", "c" ])
[ ["1", "4"], ["2", "5"], ["3", "6"] ]
"""
def split_into_columns(rows, headers) do
for header <- headers do
for row <- rows, do: printable(row[header])
end
end
@doc """
Return a binary (string) version of our parameter.
## Examples
iex> Issues.TableFormatter.printable("a")
"a"
iex> Issues.TableFormatter.printable(99)
"99"
"""
def printable(str) when is_binary(str), do: str
def printable(str), do: to_string(str)
@doc """
Given a list containing sublists, where each sublist contains the data for
a column, return a list containing the maximum width of each column
## Example
iex> data = [ [ "cat", "wombat", "elk"], ["mongoose", "ant", "gnu"]]
iex> Issues.TableFormatter.widths_of(data)
[ 6, 8 ]
"""
def widths_of(columns) do
for column <- columns, do: column |> map(&String.length/1) |> max
end
@doc """
Return a format string that hard codes the widths of a set of columns.
We put `" | "` between each column.
## Example
iex> widths = [5,6,99]
iex> Issues.TableFormatter.format_for(widths)
"~-5s | ~-6s | ~-99s~n"
"""
def format_for(column_widths) do
map_join(column_widths, " | ", fn width -> "~-#{width}s" end) <> "~n"
end
@doc """
Generate the line that goes below the column headings. It is a string of
hyphens, with + signs where the vertical bar between the columns goes.
## Example
iex> widths = [5,6,9]
iex> Issues.TableFormatter.separator(widths)
"------+--------+----------"
"""
def separator(column_widths) do
map_join(column_widths, "-+-", fn width -> List.duplicate("-", width) end)
end
@doc """
Given a list containing rows of data, a list containing the header selectors,
and a format string, write the extracted data under control of the format string.
"""
def puts_in_columns(data_by_columns, format) do
data_by_columns
|> List.zip
|> map(&Tuple.to_list/1)
|> each(&puts_one_line_in_columns(&1, format))
end
def puts_one_line_in_columns(fields, format) do
:io.format(format, fields)
end
end
| 30.828829 | 83 | 0.634717 |
03bf6077023eb0dcac09b5b198bdfa2013bed791 | 1,992 | exs | Elixir | apps/omg_watcher_info/mix.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 177 | 2018-08-24T03:51:02.000Z | 2020-05-30T13:29:25.000Z | apps/omg_watcher_info/mix.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 1,042 | 2018-08-25T00:52:39.000Z | 2020-06-01T05:15:17.000Z | apps/omg_watcher_info/mix.exs | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 47 | 2018-08-24T12:06:33.000Z | 2020-04-28T11:49:25.000Z | defmodule OMG.WatcherInfo.MixProject do
use Mix.Project
def project() do
[
app: :omg_watcher_info,
version: version(),
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.8",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
deps: deps(),
test_coverage: [tool: ExCoveralls]
]
end
def application() do
[
mod: {OMG.WatcherInfo.Application, []},
start_phases: [{:attach_telemetry, []}],
extra_applications: [:logger, :runtime_tools, :telemetry, :omg_watcher]
]
end
defp version() do
"git"
|> System.cmd(["describe", "--tags", "--abbrev=0"])
|> elem(0)
|> String.replace("v", "")
|> String.replace("\n", "")
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:prod), do: ["lib"]
defp elixirc_paths(:dev), do: ["lib"]
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp deps() do
[
{:postgrex, "~> 0.15"},
{:ecto_sql, "~> 3.4"},
{:telemetry, "~> 0.4.1"},
{:spandex_ecto, "~> 0.6.0"},
# there's no apparent reason why libsecp256k1, spandex need to be included as dependencies
# to this umbrella application apart from mix ecto.gen.migration not working, so here they are, copied from
# the parent (main) mix.exs
{:spandex, "~> 3.0.2"},
{:jason, "~> 1.0"},
# UMBRELLA
{:omg_status, in_umbrella: true},
{:omg_utils, in_umbrella: true},
# TEST ONLY
# here only to leverage common test helpers and code
{:fake_server, "~> 2.1", only: [:dev, :test], runtime: false},
{:briefly, "~> 0.3.0", only: [:dev, :test]},
{:phoenix, "~> 1.5", runtime: false},
{:poison, "~> 4.0"},
{:ex_machina, "~> 2.3", only: [:test], runtime: false}
]
end
end
| 28.869565 | 113 | 0.563253 |
03bf623e25ebda9e16947d4781a257f16f31e189 | 1,690 | ex | Elixir | clients/content/lib/google_api/content/v21/model/orders_cancel_line_item_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/orders_cancel_line_item_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/content/lib/google_api/content/v21/model/orders_cancel_line_item_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"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.Content.V21.Model.OrdersCancelLineItemResponse do
@moduledoc """
## Attributes
* `executionStatus` (*type:* `String.t`, *default:* `nil`) - The status of the execution. Acceptable values are: - "`duplicate`" - "`executed`"
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "content#ordersCancelLineItemResponse".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:executionStatus => String.t(),
:kind => String.t()
}
field(:executionStatus)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.OrdersCancelLineItemResponse do
def decode(value, options) do
GoogleApi.Content.V21.Model.OrdersCancelLineItemResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.OrdersCancelLineItemResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.8 | 159 | 0.731361 |
03bfc774a2929a5aeb89ebb563433054e053ea67 | 2,311 | ex | Elixir | lib/algae/free.ex | Naillik1/algae | cd47031ea151ab7880135f729bc0690cab579a20 | [
"MIT"
] | null | null | null | lib/algae/free.ex | Naillik1/algae | cd47031ea151ab7880135f729bc0690cab579a20 | [
"MIT"
] | 1 | 2019-03-09T17:15:56.000Z | 2019-03-09T17:15:56.000Z | lib/algae/free.ex | toraritte/algae | cd47031ea151ab7880135f729bc0690cab579a20 | [
"MIT"
] | null | null | null | defmodule Algae.Free do
@moduledoc """
A "free" structure that converts functors into monads by embedding them in
a special structure with all of the monadic heavy lifting done for you.
Similar to trees and lists, but with the ability to add a struct "tag",
at each level. Often used for DSLs, interpreters, or building structured data.
For a simple introduction to the "free monad + interpreter" pattern, we recommend
[Why free monads matter](http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html).
## Anatomy
### Pure
`Pure` simply holds a plain value.
%Free.Pure{pure: 42}
### Roll
`Roll` resursively containment of more `Free` structures embedded in
a another ADT. For example, with `Id`:
%Free.Roll{
roll: %Id{
id: %Pure{
pure: 42
}
}
}
"""
alias Alage.Free.{Pure, Roll}
import Algae
use Witchcraft
defsum do
defdata Roll :: any() # Witchcraft.Functor.t()
defdata Pure :: any() \\ %Witchcraft.Unit{}
end
@doc """
Create an `Algae.Free.Pure` wrapping a single, simple value
## Examples
iex> new(42)
%Algae.Free.Pure{pure: 42}
"""
@spec new(any()) :: t()
def new(value), do: %Pure{pure: value}
@doc """
Add another layer to a free structure
## Examples
iex> 13
...> |> new()
...> |> layer(%Algae.Id{})
%Algae.Free.Roll{
roll: %Algae.Id{
id: %Algae.Free.Pure{
pure: 13
}
}
}
"""
@spec layer(t(), any()) :: t()
def layer(free, mutual), do: %Roll{roll: of(mutual, free)}
@doc """
Wrap a functor in a free structure.
## Examples
iex> wrap(%Algae.Id{id: 42})
%Algae.Free.Roll{
roll: %Algae.Id{
id: 42
}
}
"""
@spec wrap(Witchcraft.Functor.t()) :: Roll.t()
def wrap(functor), do: %Roll{roll: functor}
@doc """
Lift a plain functor up into a free monad.
## Examples
iex> free(%Algae.Id{id: 42})
%Algae.Free.Roll{
roll: %Algae.Id{
id: %Algae.Free.Pure{
pure: 42
}
}
}
"""
@spec free(Witchcraft.Functor.t()) :: t()
def free(functor) do
functor
|> map(&of(%Roll{}, &1))
|> wrap()
end
end
| 20.27193 | 106 | 0.562527 |
03bfdc7eb1fd1f750e34d929b4f2edda69219c9e | 728 | ex | Elixir | lib/git_bisect_app_web/gettext.ex | bdubaut/git-bisect-talk | 5b8691935a4e73307d3099d8b1b3af7dddbc2904 | [
"MIT"
] | null | null | null | lib/git_bisect_app_web/gettext.ex | bdubaut/git-bisect-talk | 5b8691935a4e73307d3099d8b1b3af7dddbc2904 | [
"MIT"
] | null | null | null | lib/git_bisect_app_web/gettext.ex | bdubaut/git-bisect-talk | 5b8691935a4e73307d3099d8b1b3af7dddbc2904 | [
"MIT"
] | null | null | null | defmodule GitBisectAppWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import GitBisectAppWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :git_bisect_app
end
| 29.12 | 72 | 0.68544 |
03bfe8ccf549a49c07ed45c194adce00cb64bb9d | 2,180 | exs | Elixir | test/validations/acceptance_test.exs | Apelsinka223/vex | dfd399724f7950d91fe6d894bb5a02e3d27bfa24 | [
"MIT"
] | null | null | null | test/validations/acceptance_test.exs | Apelsinka223/vex | dfd399724f7950d91fe6d894bb5a02e3d27bfa24 | [
"MIT"
] | null | null | null | test/validations/acceptance_test.exs | Apelsinka223/vex | dfd399724f7950d91fe6d894bb5a02e3d27bfa24 | [
"MIT"
] | null | null | null | defmodule AcceptanceTestRecord do
defstruct accepts_terms: false
use Vex.Struct
validates :accepts_terms, acceptance: true
end
defmodule CustomAcceptanceTestRecord do
defstruct accepts_terms: false
use Vex.Struct
validates :accepts_terms, acceptance: [as: "yes"]
end
defmodule AcceptanceTest do
use ExUnit.Case
test "keyword list, provided basic acceptance validation" do
assert Vex.valid?([accepts_terms: true], accepts_terms: [acceptance: true])
assert Vex.valid?([accepts_terms: "anything"], accepts_terms: [acceptance: true])
assert !Vex.valid?([accepts_terms: nil], accepts_terms: [acceptance: true])
end
test "keyword list, included presence validation" do
assert Vex.valid?([accepts_terms: true, _vex: [accepts_terms: [acceptance: true]]])
assert Vex.valid?([accepts_terms: "anything", _vex: [accepts_terms: [acceptance: true]]])
assert !Vex.valid?([accepts_terms: false, _vex: [accepts_terms: [acceptance: true]]])
end
test "keyword list, provided custom acceptance validation" do
assert Vex.valid?([accepts_terms: "yes"], accepts_terms: [acceptance: [as: "yes"]])
assert !Vex.valid?([accepts_terms: false], accepts_terms: [acceptance: [as: "yes"]])
assert !Vex.valid?([accepts_terms: true], accepts_terms: [acceptance: [as: "yes"]])
end
test "keyword list, included custom validation" do
assert Vex.valid?([accepts_terms: "yes", _vex: [accepts_terms: [acceptance: [as: "yes"]]]])
assert !Vex.valid?([accepts_terms: false, _vex: [accepts_terms: [acceptance: [as: "yes"]]]])
assert !Vex.valid?([accepts_terms: true, _vex: [accepts_terms: [acceptance: [as: "yes"]]]])
end
test "record, included basic presence validation" do
assert Vex.valid?(%AcceptanceTestRecord{accepts_terms: "yes"})
assert Vex.valid?(%AcceptanceTestRecord{accepts_terms: true})
end
test "record, included custom presence validation" do
assert Vex.valid?(%CustomAcceptanceTestRecord{accepts_terms: "yes"})
assert !Vex.valid?(%CustomAcceptanceTestRecord{accepts_terms: true})
assert !Vex.valid?(%CustomAcceptanceTestRecord{accepts_terms: false})
end
end
| 40.37037 | 96 | 0.716514 |
03bfeac0f1998bc0e495dc08f3fd0b0832b390fe | 42 | ex | Elixir | imaas/lib/imaas.ex | Elonsoft/imaas | ba5eca1559d042822ba66786e8db53d2f988fb2f | [
"WTFPL"
] | 1 | 2020-07-27T15:50:30.000Z | 2020-07-27T15:50:30.000Z | imaas/lib/imaas.ex | Elonsoft/imaas | ba5eca1559d042822ba66786e8db53d2f988fb2f | [
"WTFPL"
] | null | null | null | imaas/lib/imaas.ex | Elonsoft/imaas | ba5eca1559d042822ba66786e8db53d2f988fb2f | [
"WTFPL"
] | null | null | null | defmodule Imaas do
@moduledoc false
end
| 10.5 | 18 | 0.785714 |
03bff2b90fe1147d326f54318e337969b3593a4c | 489 | ex | Elixir | lib/figgis_web/views/error_view.ex | jherdman/figgis | 4eae5d0fc48d550c3585c088ff5ac74d97efa7d4 | [
"MIT"
] | null | null | null | lib/figgis_web/views/error_view.ex | jherdman/figgis | 4eae5d0fc48d550c3585c088ff5ac74d97efa7d4 | [
"MIT"
] | null | null | null | lib/figgis_web/views/error_view.ex | jherdman/figgis | 4eae5d0fc48d550c3585c088ff5ac74d97efa7d4 | [
"MIT"
] | null | null | null | defmodule FiggisWeb.ErrorView do
use FiggisWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 28.764706 | 61 | 0.734151 |
03bff40c49e31f7824ab294d530df60173be6a2a | 1,271 | exs | Elixir | mix.exs | samhamilton/pinglix | ca78ffc5f23dfd7c7e2b12a86b7278178aa1b2b0 | [
"MIT"
] | 8 | 2015-11-11T08:40:46.000Z | 2020-01-13T22:24:45.000Z | mix.exs | samhamilton/pinglix | ca78ffc5f23dfd7c7e2b12a86b7278178aa1b2b0 | [
"MIT"
] | 10 | 2017-04-28T23:02:03.000Z | 2021-08-18T01:04:39.000Z | mix.exs | samhamilton/pinglix | ca78ffc5f23dfd7c7e2b12a86b7278178aa1b2b0 | [
"MIT"
] | 9 | 2017-04-27T16:20:50.000Z | 2021-09-03T02:59:50.000Z | defmodule Pinglix.Mixfile do
use Mix.Project
@source_url "https://github.com/pvdvreede/pinglix"
@version "1.1.4"
def project do
[
app: :pinglix,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
package: package(),
deps: deps(),
docs: docs()
]
end
def application do
[extra_applications: [:logger]]
end
defp package do
[
description:
"Plug compatible health check system in Elixir based " <>
"on https://github.com/jbarnette/pinglish.",
contributors: ["Paul Van de Vreede"],
maintainers: ["Paul Van de Vreede"],
licenses: ["MIT License"],
files: ["lib", "mix.exs", "README.md", "LICENSE"],
links: %{"GitHub" => @source_url}
]
end
defp deps do
[
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:dialyxir, "~> 0.5", only: :dev},
{:timex, "~> 3.0"},
{:poison, "~> 3.1.0"},
{:plug, "~> 1.0"}
]
end
defp docs do
[
extras: [
"LICENSE.md": [title: "License"],
"README.md": [title: "Overview"]
],
main: "readme",
source_url: @source_url,
formatters: ["html"]
]
end
end
| 21.542373 | 65 | 0.527144 |
03c04de8eeae1e99fd249a075f5901f519fd27a2 | 34,348 | ex | Elixir | lib/phoenix_live_view/helpers.ex | nTraum/phoenix_live_view | 62050eb995d13fb46976d2ff18c7a1dfa40eadfe | [
"MIT"
] | null | null | null | lib/phoenix_live_view/helpers.ex | nTraum/phoenix_live_view | 62050eb995d13fb46976d2ff18c7a1dfa40eadfe | [
"MIT"
] | null | null | null | lib/phoenix_live_view/helpers.ex | nTraum/phoenix_live_view | 62050eb995d13fb46976d2ff18c7a1dfa40eadfe | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveView.Helpers do
@moduledoc """
A collection of helpers to be imported into your views.
"""
# TODO: Convert all functions with the `live_` prefix to function components?
alias Phoenix.LiveView
alias Phoenix.LiveView.{Component, Socket, Static}
@doc """
Provides `~L` sigil with HTML safe Live EEx syntax inside source files.
iex> ~L"\""
...> Hello <%= "world" %>
...> "\""
{:safe, ["Hello ", "world", "\\n"]}
"""
@doc deprecated: "Use ~H instead"
defmacro sigil_L({:<<>>, meta, [expr]}, []) do
options = [
engine: Phoenix.LiveView.Engine,
file: __CALLER__.file,
line: __CALLER__.line + 1,
indentation: meta[:indentation] || 0
]
EEx.compile_string(expr, options)
end
@doc ~S'''
Provides `~H` sigil with HTML-safe and HTML-aware syntax inside source files.
> Note: `HEEx` requires Elixir >= `1.12.0` in order to provide accurate
> file:line:column information in error messages. Earlier Elixir versions will
> work but will show inaccurate error messages.
`HEEx` is a HTML-aware and component-friendly extension of `EEx` that provides:
* Built-in handling of HTML attributes
* An HTML-like notation for injecting function components
* Compile-time validation of the structure of the template
* The ability to minimize the amount of data sent over the wire
## Example
~H"""
<div title="My div" class={@class}>
<p>Hello <%= @name %></p>
<MyApp.Weather.city name="Kraków"/>
</div>
"""
## Syntax
`HEEx` is built on top of Embedded Elixir (`EEx`), a templating syntax that uses
`<%= ... %>` for interpolating results. In this section, we are going to cover the
basic constructs in `HEEx` templates as well as its syntax extensions.
### Interpolation
Both `HEEx` and `EEx` templates use `<%= ... %>` for interpolating code inside the body
of HTML tags:
<p>Hello, <%= @name %></p>
Similarly, conditionals and other block Elixir constructs are supported:
<%= if @show_greeting? do %>
<p>Hello, <%= @name %></p>
<% end %>
Note we don't include the equal sign `=` in the closing `<% end %>` tag
(because the closing tag does not output anything).
There is one important difference between `HEEx` and Elixir's builtin `EEx`.
`HEEx` uses a specific annotation for interpolating HTML tags and attributes.
Let's check it out.
### HEEx extension: Defining attributes
Since `HEEx` must parse and validate the HTML structure, code interpolation using
`<%= ... %>` and `<% ... %>` are restricted to the body (inner content) of the
HTML/component nodes and it cannot be applied within tags.
For instance, the following syntax is invalid:
<div class="<%= @class %>">
...
</div>
Instead do:
<div class={@class}>
...
</div>
You can put any Elixir expression between `{ ... }`. For example, if you want
to set classes, where some are static and others are dynamic, you can using
string interpolation:
<div class={"btn btn-#{@type}"}>
...
</div>
The following attribute values have special meaning:
* `true` - if a value is `true`, the attribute is rendered with no value at all.
For example, `<input required={true}>` is the same as `<input required>`;
* `false` or `nil` - if a value is `false` or `nil`, the attribute is not rendered;
* `list` (only for the `class` attribute) - each element of the list is processed
as a different class. `nil` and `false` elements are discarded.
For multiple dynamic attributes, you can use the same notation but without
assigning the expression to any specific attribute.
<div {@dynamic_attrs}>
...
</div>
The expression inside `{...}` must be either a keyword list or a map containing
the key-value pairs representing the dynamic attributes.
### HEEx extension: Defining function components
Function components are stateless components implemented as pure functions
with the help of the `Phoenix.Component` module. They can be either local
(same module) or remote (external module).
`HEEx` allows invoking these function components directly in the template
using an HTML-like notation. For example, a remote function:
<MyApp.Weather.city name="Kraków"/>
A local function can be invoked with a leading dot:
<.city name="Kraków"/>
where the component could be defined as follows:
defmodule MyApp.Weather do
use Phoenix.Component
def city(assigns) do
~H"""
The chosen city is: <%= @name %>.
"""
end
def country(assigns) do
~H"""
The chosen country is: <%= @name %>.
"""
end
end
It is typically best to group related functions into a single module, as
opposed to having many modules with a single `render/1` function. Function
components support other important features, such as slots. You can learn
more about components in `Phoenix.Component`.
'''
defmacro sigil_H({:<<>>, meta, [expr]}, []) do
unless Macro.Env.has_var?(__CALLER__, {:assigns, nil}) do
raise "~H requires a variable named \"assigns\" to exist and be set to a map"
end
options = [
engine: Phoenix.LiveView.HTMLEngine,
file: __CALLER__.file,
line: __CALLER__.line + 1,
module: __CALLER__.module,
indentation: meta[:indentation] || 0
]
EEx.compile_string(expr, options)
end
@doc ~S'''
Filters the assigns as a list of keywords for use in dynamic tag attributes.
Useful for transforming caller assigns into dynamic attributes while
stripping reserved keys from the result.
## Examples
Imagine the following `my_link` component which allows a caller
to pass a `new_window` assign, along with any other attributes they
would like to add to the element, such as class, data attributes, etc:
<.my_link href="/" id={@id} new_window={true} class="my-class">Home</.my_link>
We could support the dynamic attributes with the following component:
def my_link(assigns) do
target = if assigns[:new_window], do: "_blank", else: false
extra = assigns_to_attributes(assigns, [:new_window])
assigns =
assigns
|> Phoenix.LiveView.assign(:target, target)
|> Phoenix.LiveView.assign(:extra, extra)
~H"""
<a href={@href} target={@target} {@extra}>
<%= render_slot(@inner_block) %>
</a>
"""
end
The optional second argument to `assigns_to_attributes` takes a list of keys to exclude
which will typically be the keys reserved by the component itself which either
do not belong in the markup, or are already handled explicitly by the component.
'''
def assigns_to_attributes(assigns, exclude \\ []) do
excluded_keys = [:__changed__, :__slot__, :inner_block, :myself, :flash, :socket] ++ exclude
for {key, val} <- assigns, key not in excluded_keys, into: [], do: {key, val}
end
@doc false
def live_patch(opts) when is_list(opts) do
live_link("patch", Keyword.fetch!(opts, :do), Keyword.delete(opts, :do))
end
@doc """
Generates a link that will patch the current LiveView.
When navigating to the current LiveView,
`c:Phoenix.LiveView.handle_params/3` is
immediately invoked to handle the change of params and URL state.
Then the new state is pushed to the client, without reloading the
whole page while also maintaining the current scroll position.
For live redirects to another LiveView, use `live_redirect/2`.
## Options
* `:to` - the required path to link to.
* `:replace` - the flag to replace the current history or push a new state.
Defaults `false`.
All other options are forwarded to the anchor tag.
## Examples
<%= live_patch "home", to: Routes.page_path(@socket, :index) %>
<%= live_patch "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
<%= live_patch to: Routes.live_path(@socket, MyLive, dir: :asc), replace: false do %>
Sort By Price
<% end %>
"""
def live_patch(text, opts)
def live_patch(%Socket{}, _) do
raise """
you are invoking live_patch/2 with a socket but a socket is not expected.
If you want to live_patch/2 inside a LiveView, use push_patch/2 instead.
If you are inside a template, make the sure the first argument is a string.
"""
end
def live_patch(opts, do: block) when is_list(opts) do
live_link("patch", block, opts)
end
def live_patch(text, opts) when is_list(opts) do
live_link("patch", text, opts)
end
@doc false
def live_redirect(opts) when is_list(opts) do
live_link("redirect", Keyword.fetch!(opts, :do), Keyword.delete(opts, :do))
end
@doc """
Generates a link that will redirect to a new LiveView of the same live session.
The current LiveView will be shut down and a new one will be mounted
in its place, without reloading the whole page. This can
also be used to remount the same LiveView, in case you want to start
fresh. If you want to navigate to the same LiveView without remounting
it, use `live_patch/2` instead.
*Note*: The live redirects are only supported between two LiveViews defined
under the same live session. See `Phoenix.LiveView.Router.live_session/3` for
more details.
## Options
* `:to` - the required path to link to.
* `:replace` - the flag to replace the current history or push a new state.
Defaults `false`.
All other options are forwarded to the anchor tag.
## Examples
<%= live_redirect "home", to: Routes.page_path(@socket, :index) %>
<%= live_redirect "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
<%= live_redirect to: Routes.live_path(@socket, MyLive, dir: :asc), replace: false do %>
Sort By Price
<% end %>
"""
def live_redirect(text, opts)
def live_redirect(%Socket{}, _) do
raise """
you are invoking live_redirect/2 with a socket but a socket is not expected.
If you want to live_redirect/2 inside a LiveView, use push_redirect/2 instead.
If you are inside a template, make the sure the first argument is a string.
"""
end
def live_redirect(opts, do: block) when is_list(opts) do
live_link("redirect", block, opts)
end
def live_redirect(text, opts) when is_list(opts) do
live_link("redirect", text, opts)
end
defp live_link(type, block_or_text, opts) do
uri = Keyword.fetch!(opts, :to)
replace = Keyword.get(opts, :replace, false)
kind = if replace, do: "replace", else: "push"
data = [phx_link: type, phx_link_state: kind]
opts =
opts
|> Keyword.update(:data, data, &Keyword.merge(&1, data))
|> Keyword.put(:href, uri)
Phoenix.HTML.Tag.content_tag(:a, Keyword.delete(opts, :to), do: block_or_text)
end
@doc """
Renders a LiveView within a template.
This is useful in two situations:
* When rendering a child LiveView inside a LiveView
* When rendering a LiveView inside a regular (non-live) controller/view
## Options
* `:session` - a map of binary keys with extra session data to be
serialized and sent to the client. All session data currently in
the connection is automatically available in LiveViews. You can
use this option to provide extra data. Remember all session data
is serialized and sent to the client, so you should always
keep the data in the session to a minimum. For example, instead
of storing a User struct, you should store the "user_id" and load
the User when the LiveView mounts.
* `:container` - an optional tuple for the HTML tag and DOM
attributes to be used for the LiveView container. For example:
`{:li, style: "color: blue;"}`. By default it uses the module
definition container. See the "Containers" section below for more
information.
* `:id` - both the DOM ID and the ID to uniquely identify a LiveView.
An `:id` is automatically generated when rendering root LiveViews
but it is a required option when rendering a child LiveView.
* `:sticky` - an optional flag to maintain the LiveView across
live redirects, even if it is nested within another LiveView.
## Examples
When rendering from a controller/view, you can call:
<%= live_render(@conn, MyApp.ThermostatLive) %>
Or:
<%= live_render(@conn, MyApp.ThermostatLive, session: %{"home_id" => @home.id}) %>
Within another LiveView, you must pass the `:id` option:
<%= live_render(@socket, MyApp.ThermostatLive, id: "thermostat") %>
## Containers
When a `LiveView` is rendered, its contents are wrapped in a container.
By default, the container is a `div` tag with a handful of `LiveView`
specific attributes.
The container can be customized in different ways:
* You can change the default `container` on `use Phoenix.LiveView`:
use Phoenix.LiveView, container: {:tr, id: "foo-bar"}
* You can override the container tag and pass extra attributes when
calling `live_render` (as well as on your `live` call in your router):
live_render socket, MyLiveView, container: {:tr, class: "highlight"}
"""
def live_render(conn_or_socket, view, opts \\ [])
def live_render(%Plug.Conn{} = conn, view, opts) do
case Static.render(conn, view, opts) do
{:ok, content, _assigns} ->
content
{:stop, _} ->
raise RuntimeError, "cannot redirect from a child LiveView"
end
end
def live_render(%Socket{} = parent, view, opts) do
Static.nested_render(parent, view, opts)
end
@doc """
A function component for rendering `Phoenix.LiveComponent`
within a parent LiveView.
While `LiveView`s can be nested, each LiveView starts its
own process. A `LiveComponent` provides similar functionality
to `LiveView`, except they run in the same process as the
`LiveView`, with its own encapsulated state. That's why they
are called stateful components.
See `Phoenix.LiveComponent` for more information.
## Examples
`.live_component` requires the component `:module` and its
`:id` to be given:
<.live_component module={MyApp.WeatherComponent} id="thermostat" city="Kraków" />
The `:id` is used to identify this `LiveComponent` throughout the
LiveView lifecycle. Note the `:id` won't necessarily be used as the
DOM ID. That's up to the component.
"""
def live_component(assigns) when is_map(assigns) do
id = assigns[:id]
{module, assigns} =
assigns
|> Map.delete(:__changed__)
|> Map.pop(:module)
if module == nil or not is_atom(module) do
raise ArgumentError,
".live_component expects module={...} to be given and to be an atom, " <>
"got: #{inspect(module)}"
end
if id == nil do
raise ArgumentError, ".live_component expects id={...} to be given, got: nil"
end
case module.__live__() do
%{kind: :component} ->
%Component{id: id, assigns: assigns, component: module}
%{kind: kind} ->
raise ArgumentError, "expected #{inspect(module)} to be a component, but it is a #{kind}"
end
end
def live_component(component) when is_atom(component) do
IO.warn(
"<%= live_component Component %> is deprecated, " <>
"please use <.live_component module={Component} id=\"hello\" /> inside HEEx templates instead"
)
Phoenix.LiveView.Helpers.__live_component__(component.__live__(), %{}, nil)
end
@doc """
Deprecated API for rendering `LiveComponent`.
## Upgrading
In order to migrate from `<%= live_component ... %>` to `<.live_component>`,
you must first:
1. Migrate from `~L` sigil and `.leex` templates to
`~H` sigil and `.heex` templates
2. Then instead of:
```
<%= live_component MyModule, id: "hello" do %>
...
<% end %>
```
You should do:
```
<.live_component module={MyModule} id="hello">
...
</.live_component>
```
3. If your component is using `render_block/2`, replace
it by `render_slot/2`
"""
@doc deprecated: "Use .live_component (live_component/1) instead"
defmacro live_component(component, assigns, do_block \\ []) do
if is_assign?(:socket, component) do
IO.warn(
"passing the @socket to live_component is no longer necessary, " <>
"please remove the socket argument",
Macro.Env.stacktrace(__CALLER__)
)
end
{inner_block, do_block, assigns} =
case {do_block, assigns} do
{[do: do_block], _} -> {rewrite_do!(do_block, :inner_block, __CALLER__), [], assigns}
{_, [do: do_block]} -> {rewrite_do!(do_block, :inner_block, __CALLER__), [], []}
{_, _} -> {nil, do_block, assigns}
end
if match?({:__aliases__, _, _}, component) or is_atom(component) or is_list(assigns) or
is_map(assigns) do
quote do
Phoenix.LiveView.Helpers.__live_component__(
unquote(component).__live__(),
unquote(assigns),
unquote(inner_block)
)
end
else
quote do
case unquote(component) do
%Phoenix.LiveView.Socket{} ->
Phoenix.LiveView.Helpers.__live_component__(
unquote(assigns).__live__(),
unquote(do_block),
unquote(inner_block)
)
component ->
Phoenix.LiveView.Helpers.__live_component__(
component.__live__(),
unquote(assigns),
unquote(inner_block)
)
end
end
end
end
@doc false
def __live_component__(%{kind: :component, module: component}, assigns, inner)
when is_list(assigns) or is_map(assigns) do
assigns = assigns |> Map.new() |> Map.put_new(:id, nil)
assigns = if inner, do: Map.put(assigns, :inner_block, inner), else: assigns
id = assigns[:id]
# TODO: Remove logic from Diff once stateless components are removed.
# TODO: Remove live_component arity checks from Engine
if is_nil(id) and
(function_exported?(component, :handle_event, 3) or
function_exported?(component, :preload, 1)) do
raise "a component #{inspect(component)} that has implemented handle_event/3 or preload/1 " <>
"requires an :id assign to be given"
end
%Component{id: id, assigns: assigns, component: component}
end
def __live_component__(%{kind: kind, module: module}, assigns, _inner)
when is_list(assigns) or is_map(assigns) do
raise "expected #{inspect(module)} to be a component, but it is a #{kind}"
end
defp rewrite_do!(do_block, key, caller) do
if Macro.Env.has_var?(caller, {:assigns, nil}) do
rewrite_do(do_block, key)
else
raise ArgumentError,
"cannot use live_component because the assigns var is unbound/unset"
end
end
@doc """
Renders a component defined by the given function.
This function is rarely invoked directly by users. Instead, it is used by `~H`
to render `Phoenix.Component`s. For example, the following:
<MyApp.Weather.city name="Kraków" />
Is the same as:
<%= component(&MyApp.Weather.city/1, name: "Kraków") %>
"""
def component(func, assigns \\ [])
when (is_function(func, 1) and is_list(assigns)) or is_map(assigns) do
assigns =
case assigns do
%{__changed__: _} -> assigns
_ -> assigns |> Map.new() |> Map.put_new(:__changed__, nil)
end
case func.(assigns) do
%Phoenix.LiveView.Rendered{} = rendered ->
rendered
%Phoenix.LiveView.Component{} = component ->
component
other ->
raise RuntimeError, """
expected #{inspect(func)} to return a %Phoenix.LiveView.Rendered{} struct
Ensure your render function uses ~H to define its template.
Got:
#{inspect(other)}
"""
end
end
@doc """
Renders the `@inner_block` assign of a component with the given `argument`.
<%= render_block(@inner_block, value: @value)
This function is deprecated for function components. Use `render_slot/2`
instead.
"""
@doc deprecated: "Use render_slot/2 instead"
defmacro render_block(inner_block, argument \\ []) do
quote do
unquote(__MODULE__).__render_block__(unquote(inner_block)).(
var!(changed, Phoenix.LiveView.Engine),
unquote(argument)
)
end
end
@doc false
def __render_block__([%{inner_block: fun}]), do: fun
def __render_block__(fun), do: fun
@doc ~S'''
Renders a slot entry with the given optional `argument`.
<%= render_slot(@inner_block, @form) %>
If multiple slot entries are defined for the same slot,
`render_slot/2` will automatically render all entries,
merging their contents. In case you want to use the entries'
attributes, you need to iterate over the list to access each
slot individually.
For example, imagine a table component:
<.table rows={@users}>
<:col let={user} label="Name">
<%= user.name %>
</:col>
<:col let={user} label="Address">
<%= user.address %>
</:col>
</.table>
At the top level, we pass the rows as an assign and we define
a `:col` slot for each column we want in the table. Each
column also has a `label`, which we are going to use in the
table header.
Inside the component, you can render the table with headers,
rows, and columns:
def table(assigns) do
~H"""
<table>
<tr>
<%= for col <- @col do %>
<th><%= col.label %></th>
<% end %>
</tr>
<%= for row <- @rows do %>
<tr>
<%= for col <- @col do %>
<td><%= render_slot(col, row) %></td>
<% end %>
</tr>
<% end %>
</table>
"""
end
'''
defmacro render_slot(slot, argument \\ nil) do
quote do
unquote(__MODULE__).__render_slot__(
var!(changed, Phoenix.LiveView.Engine),
unquote(slot),
unquote(argument)
)
end
end
@doc false
def __render_slot__(_, [], _), do: ""
def __render_slot__(changed, [entry], argument) do
call_inner_block!(entry, changed, argument)
end
def __render_slot__(changed, entries, argument) when is_list(entries) do
assigns = %{}
~H"""
<%= for entry <- entries do %><%= call_inner_block!(entry, changed, argument) %><% end %>
"""
end
def __render_slot__(changed, entry, argument) when is_map(entry) do
entry.inner_block.(changed, argument)
end
defp call_inner_block!(entry, changed, argument) do
if !entry.inner_block do
message = "attempted to render slot <:#{entry.__slot__}> but the slot has no inner content"
raise RuntimeError, message
end
entry.inner_block.(changed, argument)
end
@doc """
Define a inner block, generally used by slots.
This macro is mostly used by HTML engines that provides
a `slot` implementation and rarely called directly. The
`name` must be the assign name the slot/block will be stored
under.
If you're using HEEx templates, you should use its higher
level `<:slot>` notation instead. See `Phoenix.Component`
for more information.
"""
defmacro inner_block(name, do: do_block) do
rewrite_do(do_block, name)
end
defp rewrite_do([{:->, meta, _} | _] = do_block, key) do
inner_fun = {:fn, meta, do_block}
quote do
fn parent_changed, arg ->
var!(assigns) =
unquote(__MODULE__).__assigns__(var!(assigns), unquote(key), parent_changed)
_ = var!(assigns)
unquote(inner_fun).(arg)
end
end
end
defp rewrite_do(do_block, key) do
quote do
fn parent_changed, arg ->
var!(assigns) =
unquote(__MODULE__).__assigns__(var!(assigns), unquote(key), parent_changed)
_ = var!(assigns)
unquote(do_block)
end
end
end
@doc false
def __assigns__(assigns, key, parent_changed) do
# If the component is in its initial render (parent_changed == nil)
# or the slot/block key is in parent_changed, then we render the
# function with the assigns as is.
#
# Otherwise, we will set changed to an empty list, which is the same
# as marking everything as not changed. This is correct because
# parent_changed will always be marked as changed whenever any of the
# assigns it references inside is changed. It will also be marked as
# changed if it has any variable (such as the ones coming from let).
if is_nil(parent_changed) or Map.has_key?(parent_changed, key) do
assigns
else
Map.put(assigns, :__changed__, %{})
end
end
@doc """
Returns the flash message from the LiveView flash assign.
## Examples
<p class="alert alert-info"><%= live_flash(@flash, :info) %></p>
<p class="alert alert-danger"><%= live_flash(@flash, :error) %></p>
"""
def live_flash(%_struct{} = other, _key) do
raise ArgumentError, "live_flash/2 expects a @flash assign, got: #{inspect(other)}"
end
def live_flash(%{} = flash, key), do: Map.get(flash, to_string(key))
@doc """
Returns the entry errors for an upload.
The following error may be returned:
* `:too_many_files` - The number of selected files exceeds the `:max_entries` constraint
## Examples
def error_to_string(:too_many_files), do: "You have selected too many files"
<%= for err <- upload_errors(@uploads.avatar) do %>
<div class="alert alert-danger">
<%= error_to_string(err) %>
</div>
<% end %>
"""
def upload_errors(%Phoenix.LiveView.UploadConfig{} = conf) do
for {ref, error} <- conf.errors, ref == conf.ref, do: error
end
@doc """
Returns the entry errors for an upload.
The following errors may be returned:
* `:too_large` - The entry exceeds the `:max_file_size` constraint
* `:not_accepted` - The entry does not match the `:accept` MIME types
## Examples
def error_to_string(:too_large), do: "Too large"
def error_to_string(:not_accepted), do: "You have selected an unacceptable file type"
<%= for entry <- @uploads.avatar.entries do %>
<%= for err <- upload_errors(@uploads.avatar, entry) do %>
<div class="alert alert-danger">
<%= error_to_string(err) %>
</div>
<% end %>
<% end %>
"""
def upload_errors(
%Phoenix.LiveView.UploadConfig{} = conf,
%Phoenix.LiveView.UploadEntry{} = entry
) do
for {ref, error} <- conf.errors, ref == entry.ref, do: error
end
@doc """
Generates an image preview on the client for a selected file.
## Examples
<%= for entry <- @uploads.avatar.entries do %>
<%= live_img_preview entry, width: 75 %>
<% end %>
"""
def live_img_preview(%Phoenix.LiveView.UploadEntry{ref: ref} = entry, opts \\ []) do
attrs =
Keyword.merge(opts,
id: "phx-preview-#{ref}",
data_phx_upload_ref: entry.upload_ref,
data_phx_entry_ref: ref,
data_phx_hook: "Phoenix.LiveImgPreview",
data_phx_update: "ignore"
)
assigns = LiveView.assign(%{__changed__: nil}, attrs: attrs)
~H"<img {@attrs}/>"
end
@doc """
Builds a file input tag for a LiveView upload.
Options may be passed through to the tag builder for custom attributes.
## Drag and Drop
Drag and drop is supported by annotating the droppable container with a `phx-drop-target`
attribute pointing to the DOM ID of the file input. By default, the file input ID is the
upload `ref`, so the following markup is all that is required for drag and drop support:
<div class="container" phx-drop-target={@uploads.avatar.ref}>
...
<%= live_file_input @uploads.avatar %>
</div>
## Examples
<%= live_file_input @uploads.avatar %>
"""
def live_file_input(%Phoenix.LiveView.UploadConfig{} = conf, opts \\ []) do
if opts[:id], do: raise(ArgumentError, "the :id cannot be overridden on a live_file_input")
opts =
if conf.max_entries > 1 do
Keyword.put(opts, :multiple, true)
else
opts
end
preflighted_entries = for entry <- conf.entries, entry.preflighted?, do: entry
done_entries = for entry <- conf.entries, entry.done?, do: entry
valid? = Enum.any?(conf.entries) && Enum.empty?(conf.errors)
Phoenix.HTML.Tag.content_tag(
:input,
"",
Keyword.merge(opts,
type: "file",
id: conf.ref,
name: conf.name,
accept: if(conf.accept != :any, do: conf.accept),
phx_hook: "Phoenix.LiveFileUpload",
data_phx_update: "ignore",
data_phx_upload_ref: conf.ref,
data_phx_active_refs: Enum.map_join(conf.entries, ",", & &1.ref),
data_phx_done_refs: Enum.map_join(done_entries, ",", & &1.ref),
data_phx_preflighted_refs: Enum.map_join(preflighted_entries, ",", & &1.ref),
data_phx_auto_upload: valid? && conf.auto_upload?
)
)
end
@doc """
Renders a title tag with automatic prefix/suffix on `@page_title` updates.
## Examples
<%= live_title_tag assigns[:page_title] || "Welcome", prefix: "MyApp – " %>
<%= live_title_tag assigns[:page_title] || "Welcome", suffix: " – MyApp" %>
"""
def live_title_tag(title, opts \\ []) do
title_tag(title, opts[:prefix], opts[:suffix], opts)
end
defp title_tag(title, nil = _prefix, "" <> suffix, _opts) do
Phoenix.HTML.Tag.content_tag(:title, title <> suffix, data: [suffix: suffix])
end
defp title_tag(title, "" <> prefix, nil = _suffix, _opts) do
Phoenix.HTML.Tag.content_tag(:title, prefix <> title, data: [prefix: prefix])
end
defp title_tag(title, "" <> pre, "" <> post, _opts) do
Phoenix.HTML.Tag.content_tag(:title, pre <> title <> post, data: [prefix: pre, suffix: post])
end
defp title_tag(title, _prefix = nil, _postfix = nil, []) do
Phoenix.HTML.Tag.content_tag(:title, title)
end
defp title_tag(_title, _prefix = nil, _suffix = nil, opts) do
raise ArgumentError,
"live_title_tag/2 expects a :prefix and/or :suffix option, got: #{inspect(opts)}"
end
@doc """
Renders a form function component.
This function is built on top of `Phoenix.HTML.Form.form_for/4`. For
more information about options and how to build inputs, see
`Phoenix.HTML.Form`.
## Options
The `:for` assign is the form's source data and the optional `:action`
assign can be provided for the form's action. Additionally accepts
the same options as `Phoenix.HTML.Form.form_for/4` as optional assigns:
* `:as` - the server side parameter in which all params for this
form will be collected (i.e. `as: :user_params` would mean all fields
for this form will be accessed as `conn.params.user_params` server
side). Automatically inflected when a changeset is given.
* `:method` - the HTTP method. If the method is not "get" nor "post",
an input tag with name `_method` is generated along-side the form tag.
Defaults to "post".
* `:multipart` - when true, sets enctype to "multipart/form-data".
Required when uploading files
* `:csrf_token` - for "post" requests, the form tag will automatically
include an input tag with name `_csrf_token`. When set to false, this
is disabled
* `:errors` - use this to manually pass a keyword list of errors to the form
(for example from `conn.assigns[:errors]`). This option is only used when a
connection is used as the form source and it will make the errors available
under `f.errors`
* `:id` - the ID of the form attribute. If an ID is given, all form inputs
will also be prefixed by the given ID
All further assigns will be passed to the form tag.
## Examples
<.form let={f} for={@changeset}>
<%= text_input f, :name %>
</.form>
<.form let={user_form} for={@changeset} as="user" multipart {@extra}>
<%= text_input user_form, :name %>
</.form>
"""
def form(assigns) do
# Extract options and then to the same call as form_for
action = assigns[:action] || "#"
form_for = assigns[:for] || raise ArgumentError, "missing :for assign to form"
form_options = assigns_to_attributes(assigns, [:action, :for])
# Since FormData may add options, read the actual options from form
%{options: opts} =
form = %Phoenix.HTML.Form{
Phoenix.HTML.FormData.to_form(form_for, form_options)
| action: action
}
# And then process method, csrf_token, and multipart as in form_tag
{method, opts} = Keyword.pop(opts, :method, "post")
{method, hidden_method} = form_method(method)
{csrf_token, opts} =
Keyword.pop_lazy(opts, :csrf_token, fn ->
if method == "post", do: Plug.CSRFProtection.get_csrf_token_for(action)
end)
opts =
case Keyword.pop(opts, :multipart, false) do
{false, opts} -> opts
{true, opts} -> Keyword.put(opts, :enctype, "multipart/form-data")
end
# Finally we can render the form
assigns =
LiveView.assign(assigns,
form: form,
csrf_token: csrf_token,
hidden_method: hidden_method,
attrs: [action: action, method: method] ++ opts
)
~H"""
<form {@attrs}>
<%= if @hidden_method && @hidden_method not in ~w(get post) do %>
<input name="_method" type="hidden" value={@hidden_method}>
<% end %>
<%= if @csrf_token do %>
<input name="_csrf_token" type="hidden" value={@csrf_token}>
<% end %>
<%= render_slot(@inner_block, @form) %>
</form>
"""
end
defp form_method(method) when method in ~w(get post), do: {method, nil}
defp form_method(method) when is_binary(method), do: {"post", method}
defp is_assign?(assign_name, expression) do
match?({:@, _, [{^assign_name, _, _}]}, expression) or
match?({^assign_name, _, _}, expression) or
match?({{:., _, [{:assigns, _, nil}, ^assign_name]}, _, []}, expression)
end
end
| 31.569853 | 102 | 0.643793 |
03c07db6b194cc9cd310751fc81da5674685b73b | 873 | exs | Elixir | test/cog/models/group_test.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 1,003 | 2016-02-23T17:21:12.000Z | 2022-02-20T14:39:35.000Z | test/cog/models/group_test.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 906 | 2016-02-22T22:54:19.000Z | 2022-03-11T15:19:43.000Z | test/cog/models/group_test.exs | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 95 | 2016-02-23T13:42:31.000Z | 2021-11-30T14:39:55.000Z | defmodule Cog.Models.Group.Test do
use Cog.ModelCase
alias Cog.Models.Group
test "names are required" do
changeset = Group.changeset(%Group{}, %{})
assert {:name, {"can't be blank", []}} in changeset.errors
end
test "names are unique" do
{:ok, _group} = Repo.insert Group.changeset(%Group{}, %{"name" => "admin"})
{:error, changeset} = Repo.insert Group.changeset(%Group{}, %{"name" => "admin"})
assert {:name, {"has already been taken", []}} in changeset.errors
end
test "admin group cannot be renamed" do
Cog.Bootstrap.bootstrap
group = Group |> Repo.get_by(name: Cog.Util.Misc.admin_group)
assert group.name == Cog.Util.Misc.admin_group
{:error, changeset} = Repo.update(Group.changeset(group, %{"name" => "not-cog-admin"}))
assert {:name, {"admin group may not be modified", []}} in changeset.errors
end
end
| 33.576923 | 91 | 0.656357 |
03c09d7ac9b05e34d99ea35b92d5ed341fd70385 | 219 | ex | Elixir | lib/pun_discord_bot.ex | sizumita/pun-discord-bot | 80c0c5231669ce1f691116756a46f6af6e0f07a7 | [
"MIT"
] | null | null | null | lib/pun_discord_bot.ex | sizumita/pun-discord-bot | 80c0c5231669ce1f691116756a46f6af6e0f07a7 | [
"MIT"
] | 6 | 2020-09-06T05:33:02.000Z | 2020-09-09T01:57:42.000Z | lib/pun_discord_bot.ex | sizumita/pun-discord-bot | 80c0c5231669ce1f691116756a46f6af6e0f07a7 | [
"MIT"
] | null | null | null | defmodule PunDiscordBot do
@moduledoc """
Documentation for `PunDiscordBot`.
"""
@doc """
Hello world.
## Examples
iex> PunDiscordBot.hello()
:world
"""
def hello do
:world
end
end
| 11.526316 | 36 | 0.593607 |
03c0aaddc956a528b84d389d1b7e9234358527a5 | 650 | exs | Elixir | phoenix/priv/repo/migrations/20171018091459_create_categories.exs | komlanvi/www.mehr-schulferien.de | fe74772f2cc8ce430e04adf6e66023971456ce57 | [
"MIT"
] | null | null | null | phoenix/priv/repo/migrations/20171018091459_create_categories.exs | komlanvi/www.mehr-schulferien.de | fe74772f2cc8ce430e04adf6e66023971456ce57 | [
"MIT"
] | null | null | null | phoenix/priv/repo/migrations/20171018091459_create_categories.exs | komlanvi/www.mehr-schulferien.de | fe74772f2cc8ce430e04adf6e66023971456ce57 | [
"MIT"
] | null | null | null | defmodule MehrSchulferien.Repo.Migrations.CreateCategories do
use Ecto.Migration
def change do
create table(:categories) do
add :name, :string
add :name_plural, :string
add :slug, :string
add :needs_exeat, :boolean, default: false, null: false
add :for_students, :boolean, default: false, null: false
add :for_anybody, :boolean, default: false, null: false
add :is_a_religion, :boolean, default: false, null: false
timestamps()
end
create unique_index(:categories, [:name])
create unique_index(:categories, [:name_plural])
create unique_index(:categories, [:slug])
end
end
| 29.545455 | 63 | 0.684615 |
03c0bd6772663e73e9157123aaf5b2f756900586 | 4,402 | exs | Elixir | test/schemas/server/update_build_info_params_test.exs | Kintull/elidactyl | 9a051ed511ed92fa7578038784baa73288f1312b | [
"MIT"
] | 6 | 2020-04-28T21:38:40.000Z | 2022-02-13T01:04:10.000Z | test/schemas/server/update_build_info_params_test.exs | Kintull/elidactyl | 9a051ed511ed92fa7578038784baa73288f1312b | [
"MIT"
] | 1 | 2021-03-16T10:39:32.000Z | 2021-03-16T10:39:32.000Z | test/schemas/server/update_build_info_params_test.exs | Kintull/elidactyl | 9a051ed511ed92fa7578038784baa73288f1312b | [
"MIT"
] | null | null | null | defmodule Elidactyl.Schemas.Server.UpdateBuildInfoParamsTest do
use ExUnit.Case
use Elidactyl.ChangesetCase
alias Elidactyl.Schemas.Server.UpdateBuildInfoParams
import UpdateBuildInfoParams
@valid %{
allocation: 1,
memory: 512,
swap: 0,
disk: 200,
io: 500,
cpu: 0,
threads: nil,
feature_limits: %{databases: 5, allocations: 5, backups: 2},
}
def build_changeset(params \\ %{}) do
changeset(%UpdateBuildInfoParams{}, Map.merge(@valid, params))
end
describe "changeset/2" do
test "allows valid params" do
build_changeset() |> assert_valid()
end
test "validates that mandatory fields are present" do
changeset = changeset(%UpdateBuildInfoParams{}, %{})
assert_invalid(changeset, :allocation, error_message == "can't be blank")
assert_invalid(changeset, :memory, error_message == "can't be blank")
assert_invalid(changeset, :swap, error_message == "can't be blank")
assert_invalid(changeset, :io, error_message == "can't be blank")
assert_invalid(changeset, :cpu, error_message == "can't be blank")
assert_invalid(changeset, :disk, error_message == "can't be blank")
assert_invalid(changeset, :feature_limits, error_message == "can't be blank")
end
test "allows optional fields to not present" do
%UpdateBuildInfoParams{}
|> changeset(Map.drop(@valid, ~w[threads]a))
|> assert_valid()
end
test "validates fields types" do
%{allocation: "a"} |> build_changeset() |> assert_invalid(:allocation)
%{memory: "a"} |> build_changeset() |> assert_invalid(:memory)
%{swap: "a"} |> build_changeset() |> assert_invalid(:swap)
%{disk: "a"} |> build_changeset() |> assert_invalid(:disk)
%{io: "a"} |> build_changeset() |> assert_invalid(:io)
%{cpu: "a"} |> build_changeset() |> assert_invalid(:cpu)
%{threads: true} |> build_changeset() |> assert_invalid(:threads)
%{feature_limits: "a"} |> build_changeset() |> assert_invalid(:feature_limits)
end
test "allows nil, integer, string, list and range threads" do
%{threads: nil} |> build_changeset() |> assert_valid(:threads)
%{threads: 1} |> build_changeset() |> assert_valid(:threads)
%{threads: ""} |> build_changeset() |> assert_valid(:threads)
%{threads: "1"} |> build_changeset() |> assert_valid(:threads)
%{threads: "1,2,3"} |> build_changeset() |> assert_valid(:threads)
%{threads: "1-3,5"} |> build_changeset() |> assert_valid(:threads)
end
test "refutes invalid threads values" do
%{threads: "5-3"} |> build_changeset() |> assert_invalid(:threads)
%{threads: "1, 2"} |> build_changeset() |> assert_invalid(:threads)
%{threads: false} |> build_changeset() |> assert_invalid(:threads)
%{threads: ["1", "2"]} |> build_changeset() |> assert_invalid(:threads)
%{threads: [1, 2]} |> build_changeset() |> assert_invalid(:threads)
end
test "refutes zero and negative allocation values" do
%{allocation: 0} |> build_changeset() |> assert_invalid(:allocation)
%{allocation: -1} |> build_changeset() |> assert_invalid(:allocation)
%{allocation: 1} |> build_changeset() |> assert_valid(:allocation)
end
test "refutes negative memory values" do
%{memory: -1} |> build_changeset() |> assert_invalid(:memory)
%{memory: 0} |> build_changeset() |> assert_valid(:memory)
end
test "refutes swap values that < -1" do
%{swap: -2} |> build_changeset() |> assert_invalid(:swap)
%{swap: -1} |> build_changeset() |> assert_valid(:swap)
%{swap: 0} |> build_changeset() |> assert_valid(:swap)
end
test "refutes negative io values" do
%{io: -1} |> build_changeset() |> assert_invalid(:io)
%{io: 0} |> build_changeset() |> assert_valid(:io)
end
test "accepts cpu values only from 0 to 100" do
%{cpu: -1} |> build_changeset() |> assert_invalid(:cpu)
%{cpu: 0} |> build_changeset() |> assert_valid(:cpu)
%{cpu: 50} |> build_changeset() |> assert_valid(:cpu)
%{cpu: 100} |> build_changeset() |> assert_valid(:cpu)
%{cpu: 101} |> build_changeset() |> assert_invalid(:cpu)
end
test "refutes negative disk values" do
%{disk: -1} |> build_changeset() |> assert_invalid(:disk)
%{disk: 0} |> build_changeset() |> assert_valid(:disk)
end
end
end
| 40.385321 | 84 | 0.638573 |
03c0d96743955bc91e01647e91ea9980e5204c0e | 1,092 | ex | Elixir | lib/membrane_element_tee/master.ex | membraneframework/membrane_element_tee | 580a4aa9b8b8b517e66c322bc0ff9d23757aaffb | [
"Apache-2.0"
] | null | null | null | lib/membrane_element_tee/master.ex | membraneframework/membrane_element_tee | 580a4aa9b8b8b517e66c322bc0ff9d23757aaffb | [
"Apache-2.0"
] | 3 | 2021-12-29T09:57:27.000Z | 2021-12-30T16:21:43.000Z | lib/membrane_element_tee/master.ex | membraneframework/membrane_element_tee | 580a4aa9b8b8b517e66c322bc0ff9d23757aaffb | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.Element.Tee.Master do
use Membrane.Filter
@moduledoc """
Element for forwarding buffers to at least one output pad
It has one input pad `:input` and 2 output pads:
* `:master` - is a static pad which is always available and works in pull mode
* `:copy` - is a dynamic pad that can be linked to any number of elements (including 0) and works in push mode
The `:master` pad dictates the speed of processing data and any element (or elements) connected to `:copy` pad
will receive the same data as `:master`
"""
def_input_pad :input,
availability: :always,
mode: :pull,
demand_unit: :buffers,
caps: :any
def_output_pad :master,
availability: :always,
mode: :pull,
caps: :any
def_output_pad :copy,
availability: :on_request,
mode: :push,
caps: :any
@impl true
def handle_process(:input, %Membrane.Buffer{} = buffer, _ctx, state) do
{{:ok, forward: buffer}, state}
end
@impl true
def handle_demand(:master, size, :buffers, _ctx, state) do
{{:ok, demand: {:input, size}}, state}
end
end
| 26.634146 | 112 | 0.67674 |
03c0fa9fca4832786292efdc2964317b983c69e1 | 2,517 | ex | Elixir | clients/calendar/lib/google_api/calendar/v3/model/colors.ex | jechol/elixir-google-api | 0290b683dfc6491ca2ef755a80bc329378738d03 | [
"Apache-2.0"
] | null | null | null | clients/calendar/lib/google_api/calendar/v3/model/colors.ex | jechol/elixir-google-api | 0290b683dfc6491ca2ef755a80bc329378738d03 | [
"Apache-2.0"
] | null | null | null | clients/calendar/lib/google_api/calendar/v3/model/colors.ex | jechol/elixir-google-api | 0290b683dfc6491ca2ef755a80bc329378738d03 | [
"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.Calendar.V3.Model.Colors do
@moduledoc """
## Attributes
* `calendar` (*type:* `%{optional(String.t) => GoogleApi.Calendar.V3.Model.ColorDefinition.t}`, *default:* `nil`) - A global palette of calendar colors, mapping from the color ID to its definition. A calendarListEntry resource refers to one of these color IDs in its color field. Read-only.
* `event` (*type:* `%{optional(String.t) => GoogleApi.Calendar.V3.Model.ColorDefinition.t}`, *default:* `nil`) - A global palette of event colors, mapping from the color ID to its definition. An event resource may refer to one of these color IDs in its color field. Read-only.
* `kind` (*type:* `String.t`, *default:* `calendar#colors`) - Type of the resource ("calendar#colors").
* `updated` (*type:* `DateTime.t`, *default:* `nil`) - Last modification time of the color palette (as a RFC3339 timestamp). Read-only.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:calendar =>
%{optional(String.t()) => GoogleApi.Calendar.V3.Model.ColorDefinition.t()} | nil,
:event =>
%{optional(String.t()) => GoogleApi.Calendar.V3.Model.ColorDefinition.t()} | nil,
:kind => String.t() | nil,
:updated => DateTime.t() | nil
}
field(:calendar, as: GoogleApi.Calendar.V3.Model.ColorDefinition, type: :map)
field(:event, as: GoogleApi.Calendar.V3.Model.ColorDefinition, type: :map)
field(:kind)
field(:updated, as: DateTime)
end
defimpl Poison.Decoder, for: GoogleApi.Calendar.V3.Model.Colors do
def decode(value, options) do
GoogleApi.Calendar.V3.Model.Colors.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Calendar.V3.Model.Colors do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.396552 | 294 | 0.704013 |
03c106da6199e02fadfbee7b2fbd9163d15b53b9 | 289 | exs | Elixir | priv/repo/migrations/20190527022506_create_users.exs | joshddunn/loudspeaker-elixir | 9d2aba711c698e456f497cbfa10c18b0042c1831 | [
"MIT"
] | null | null | null | priv/repo/migrations/20190527022506_create_users.exs | joshddunn/loudspeaker-elixir | 9d2aba711c698e456f497cbfa10c18b0042c1831 | [
"MIT"
] | null | null | null | priv/repo/migrations/20190527022506_create_users.exs | joshddunn/loudspeaker-elixir | 9d2aba711c698e456f497cbfa10c18b0042c1831 | [
"MIT"
] | null | null | null | defmodule Myapp.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string
add :account_id, :string
add :jti, :string
add :token, :string
add :token_exp, :integer
timestamps()
end
end
end
| 17 | 46 | 0.629758 |
03c1208102687564e9e7666633a9ae86fe3ecd44 | 1,404 | exs | Elixir | mix.exs | vemperor/ecto_searcher | 4e9f368df6dd68623fd63d591abc2544e8a23d19 | [
"MIT"
] | 4 | 2019-08-06T19:31:53.000Z | 2020-11-18T23:49:49.000Z | mix.exs | ivalentinee/ecto_searcher | 4e9f368df6dd68623fd63d591abc2544e8a23d19 | [
"MIT"
] | null | null | null | mix.exs | ivalentinee/ecto_searcher | 4e9f368df6dd68623fd63d591abc2544e8a23d19 | [
"MIT"
] | null | null | null | defmodule EctoSearcher.MixProject do
use Mix.Project
def project do
[
app: :ecto_searcher,
version: "0.2.1",
elixir: "~> 1.6",
elixirc_paths: elixirc_paths(Mix.env()),
description: "Totally not an attempt to build Ransack-like search",
package: package(),
docs: docs(),
deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
end
def package do
[
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/ivalentinee/ecto_searcher"}
]
end
defp docs do
[
main: "EctoSearcher",
source_url: "https://github.com/ivalentinee/ecto_searcher"
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp extra_applications(:test), do: [:logger, :postgrex, :ecto_sql]
defp extra_applications(_), do: []
def application do
[extra_applications: extra_applications(Mix.env())]
end
defp deps do
[
{:ecto, "~> 3.2"},
{:ex_doc, "~> 0.21", only: :dev, runtime: false},
{:ecto_sql, "~> 3.2", only: :test, optional: true},
{:postgrex, ">= 0.0.0", only: :test, optional: true},
{:excoveralls, "~> 0.10", only: :test, optional: true}
]
end
end
| 24.206897 | 74 | 0.580484 |
03c1472fa07adb040127dfca5d6456a466bde7c7 | 6,642 | exs | Elixir | test/plug/session_test.exs | tomciopp/plug | af7fba19e8bce208129d858b924c7a49b93beef1 | [
"Apache-2.0"
] | null | null | null | test/plug/session_test.exs | tomciopp/plug | af7fba19e8bce208129d858b924c7a49b93beef1 | [
"Apache-2.0"
] | null | null | null | test/plug/session_test.exs | tomciopp/plug | af7fba19e8bce208129d858b924c7a49b93beef1 | [
"Apache-2.0"
] | null | null | null | defmodule Plug.SessionTest do
use ExUnit.Case, async: true
use Plug.Test
alias Plug.ProcessStore
test "puts session cookie" do
conn = fetch_cookies(conn(:get, "/"))
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = send_resp(conn, 200, "")
assert conn.resp_cookies == %{}
conn = fetch_cookies(conn(:get, "/"))
opts =
Plug.Session.init(
store: ProcessStore,
key: "foobar",
secure: true,
path: "some/path",
extra: "extra"
)
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = put_session(conn, "foo", "bar")
conn = send_resp(conn, 200, "")
assert %{"foobar" => %{value: _, secure: true, path: "some/path", extra: "extra"}} =
conn.resp_cookies
refute Map.has_key?(conn.resp_cookies["foobar"], :http_only)
conn = fetch_cookies(conn(:get, "/"))
opts =
Plug.Session.init(
store: ProcessStore,
key: "unsafe_foobar",
http_only: false,
path: "some/path"
)
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = put_session(conn, "foo", "bar")
conn = send_resp(conn, 200, "")
assert %{"unsafe_foobar" => %{value: _, http_only: false, path: "some/path"}} =
conn.resp_cookies
end
test "put session" do
conn = fetch_cookies(conn(:get, "/"))
conn = %{conn | cookies: %{"foobar" => "sid"}}
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = put_session(conn, "foo", "bar")
send_resp(conn, 200, "")
assert Process.get({:session, "sid"}) == %{"foo" => "bar"}
end
test "get session" do
Process.put({:session, "sid"}, %{"foo" => "bar"})
conn = fetch_cookies(conn(:get, "/"))
conn = %{conn | cookies: %{"foobar" => "sid"}}
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
assert get_session(conn, "foo") == "bar"
end
test "drop session" do
Process.put({:session, "sid"}, %{"foo" => "bar"})
conn = fetch_cookies(conn(:get, "/"))
conn = %{conn | cookies: %{"foobar" => "sid"}}
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = put_session(conn, "foo", "bar")
conn = configure_session(conn, drop: true)
conn = send_resp(conn, 200, "")
assert conn.resp_cookies ==
%{"foobar" => %{max_age: 0, universal_time: {{1970, 1, 1}, {0, 0, 0}}}}
end
test "drop session without cookie when there is no sid" do
conn = fetch_cookies(conn(:get, "/"))
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = put_session(conn, "foo", "bar")
conn = configure_session(conn, drop: true)
conn = send_resp(conn, 200, "")
assert conn.resp_cookies == %{}
end
test "renew session" do
Process.put({:session, "sid"}, %{"foo" => "bar"})
conn = fetch_cookies(conn(:get, "/"))
conn = %{conn | cookies: %{"foobar" => "sid"}}
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = configure_session(conn, renew: true)
conn = send_resp(conn, 200, "")
assert match?(%{"foobar" => %{value: _}}, conn.resp_cookies)
refute match?(%{"foobar" => %{value: "sid"}}, conn.resp_cookies)
end
test "ignore changes to session" do
conn = fetch_cookies(conn(:get, "/"))
opts = Plug.Session.init(store: ProcessStore, key: "foobar", secure: true, path: "some/path")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = configure_session(conn, ignore: true)
conn = put_session(conn, "foo", "bar")
conn = send_resp(conn, 200, "")
assert conn.resp_cookies == %{}
end
test "reuses sid and as such does not generate new cookie" do
Process.put({:session, "sid"}, %{"foo" => "bar"})
conn = fetch_cookies(conn(:get, "/"))
conn = %{conn | cookies: %{"foobar" => "sid"}}
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = send_resp(conn, 200, "")
assert conn.resp_cookies == %{}
end
test "generates sid" do
conn = fetch_cookies(conn(:get, "/"))
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = put_session(conn, "foo", "bar")
conn = send_resp(conn, 200, "")
assert %{value: sid} = conn.resp_cookies["foobar"]
assert Process.get({:session, sid}) == %{"foo" => "bar"}
end
test "converts store reference" do
opts = Plug.Session.init(store: :ets, key: "foobar", table: :some_table)
assert opts.store == Plug.Session.ETS
end
test "init_test_session/2" do
conn = init_test_session(conn(:get, "/"), foo: "bar")
assert get_session(conn, :foo) == "bar"
conn = fetch_session(conn)
assert get_session(conn, :foo) == "bar"
conn = put_session(conn, :bar, "foo")
assert get_session(conn, :bar) == "foo"
conn = delete_session(conn, :bar)
refute get_session(conn, :bar)
conn = clear_session(conn)
refute get_session(conn, :foo)
end
test "init_test_session/2 merges values when called after Plug.Session" do
conn = fetch_cookies(conn(:get, "/"))
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = conn |> put_session(:foo, "bar") |> put_session(:bar, "foo")
conn = init_test_session(conn, bar: "bar", other: "other")
assert get_session(conn, :foo) == "bar"
assert get_session(conn, :other) == "other"
assert get_session(conn, :bar) == "bar"
end
test "init_test_session/2 merges values when called before Plug.Session" do
opts = Plug.Session.init(store: ProcessStore, key: "foobar")
conn = fetch_cookies(conn(:get, "/"))
conn = conn |> Plug.Session.call(opts) |> fetch_session()
conn = conn |> put_session(:foo, "bar") |> put_session(:bar, "foo")
conn = send_resp(conn, 200, "")
conn = recycle_cookies(conn(:get, "/"), conn)
conn = init_test_session(conn, bar: "bar", other: "other")
conn = conn |> Plug.Session.call(opts) |> fetch_session()
assert get_session(conn, :foo) == "bar"
assert get_session(conn, :other) == "other"
assert get_session(conn, :bar) == "bar"
end
end
| 33.21 | 97 | 0.610961 |
03c1611208850ad5e1b743f1c76988dd75beaa91 | 190 | exs | Elixir | test/mimicron_test.exs | jcoder39/mimicron | 10a4de1ce26e8014445f060d3208e4d8ad2e24c9 | [
"MIT"
] | 1 | 2019-07-30T11:06:48.000Z | 2019-07-30T11:06:48.000Z | test/mimicron_test.exs | jcoder39/mimicron | 10a4de1ce26e8014445f060d3208e4d8ad2e24c9 | [
"MIT"
] | null | null | null | test/mimicron_test.exs | jcoder39/mimicron | 10a4de1ce26e8014445f060d3208e4d8ad2e24c9 | [
"MIT"
] | null | null | null | defmodule Usage do
use Mimicron
def sample, do: 1
end
defmodule MimicronTest do
use ExUnit.Case
doctest Mimicron
test "usage sample" do
assert Usage.sample() == 1
end
end
| 12.666667 | 30 | 0.705263 |
03c16aa08cd77791bc50b124275278a59c4dc82e | 73 | exs | Elixir | test/open_banking_test.exs | robmckinnon/open_banking_ex | d8a8cb7810c0748be886ee8c47b012fd1883a7b3 | [
"MIT"
] | null | null | null | test/open_banking_test.exs | robmckinnon/open_banking_ex | d8a8cb7810c0748be886ee8c47b012fd1883a7b3 | [
"MIT"
] | null | null | null | test/open_banking_test.exs | robmckinnon/open_banking_ex | d8a8cb7810c0748be886ee8c47b012fd1883a7b3 | [
"MIT"
] | null | null | null | defmodule OpenBankingTest do
use ExUnit.Case
doctest OpenBanking
end
| 14.6 | 28 | 0.821918 |
03c17a83626a1838390995be4659ca025903d508 | 2,480 | ex | Elixir | lib/logger/lib/logger/watcher.ex | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | 1 | 2019-10-11T01:36:26.000Z | 2019-10-11T01:36:26.000Z | lib/logger/lib/logger/watcher.ex | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | 1 | 2019-04-25T12:52:49.000Z | 2019-04-25T13:27:31.000Z | lib/logger/lib/logger/watcher.ex | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | null | null | null | defmodule Logger.Watcher do
@moduledoc false
require Logger
use GenServer
# TODO: Once we remove :error_logger in Erlang/OTP 21+, there is no reason
# to pass the `mod` argument in, as we will only ever watch Logger handlers
@doc """
Starts a watcher server.
This is useful when there is a need to start a handler
outside of the handler supervision tree.
"""
def start_link(triplet) do
GenServer.start_link(__MODULE__, triplet)
end
## Callbacks
@doc false
def init({mod, handler, args}) do
Process.flag(:trap_exit, true)
case :gen_event.delete_handler(mod, handler, :ok) do
{:error, :module_not_found} ->
case :gen_event.add_sup_handler(mod, handler, args) do
:ok ->
{:ok, {mod, handler}}
{:error, :ignore} ->
# Can't return :ignore as a transient child under a one_for_one.
# Instead return ok and then immediately exit normally - using a fake
# message.
send(self(), {:gen_event_EXIT, handler, :normal})
{:ok, {mod, handler}}
{:error, reason} ->
{:stop, reason}
{:EXIT, _} = exit ->
{:stop, exit}
end
_ ->
init({mod, handler, args})
end
end
@doc false
def handle_info({:gen_event_EXIT, handler, reason}, {_, handler} = state)
when reason in [:normal, :shutdown] do
{:stop, reason, state}
end
def handle_info({:gen_event_EXIT, handler, reason}, {mod, handler} = state) do
message = [
":gen_event handler ",
inspect(handler),
" installed in ",
inspect(mod),
" terminating",
?\n,
"** (exit) ",
format_exit(reason)
]
cond do
mod == :error_logger -> Logger.error(message)
logger_has_backends?() -> :ok
true -> IO.puts(:stderr, message)
end
{:stop, reason, state}
end
def handle_info(_msg, state) do
{:noreply, state}
end
defp logger_has_backends?() do
try do
:gen_event.which_handlers(Logger) != [Logger.Config]
catch
_, _ -> false
end
end
def terminate(_reason, {mod, handler}) do
# On terminate we remove the handler, this makes the
# process sync, allowing existing messages to be flushed
:gen_event.delete_handler(mod, handler, :ok)
:ok
end
defp format_exit({:EXIT, reason}), do: Exception.format_exit(reason)
defp format_exit(reason), do: Exception.format_exit(reason)
end
| 24.8 | 81 | 0.608871 |
03c181ce638e7fe332fea64b7f6354dd0657bb3c | 7,289 | ex | Elixir | apps/admin_api/lib/admin_api/v1/controllers/user_controller.ex | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/admin_api/lib/admin_api/v1/controllers/user_controller.ex | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/admin_api/lib/admin_api/v1/controllers/user_controller.ex | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 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 AdminAPI.V1.UserController do
use AdminAPI, :controller
import AdminAPI.V1.ErrorHandler
alias AdminAPI.V1.AccountHelper
alias Ecto.Changeset
alias EWallet.{UserPolicy, UserFetcher}
alias EWallet.Web.{Originator, Orchestrator, Paginator, V1.UserOverlay}
alias EWalletDB.{Account, AccountUser, User, UserQuery, AuthToken}
@doc """
Retrieves a list of users.
"""
@spec all(Plug.Conn.t(), map()) :: Plug.Conn.t()
def all(conn, attrs) do
with :ok <- permit(:all, conn.assigns, nil) do
# Get all users since everyone can access them
User
|> UserQuery.where_end_user()
|> do_all(attrs, conn)
else
error -> respond_single(error, conn)
end
end
@spec all_for_account(Plug.Conn.t(), map()) :: Plug.Conn.t()
def all_for_account(conn, %{"id" => account_id, "owned" => true} = attrs) do
with %Account{} = account <- Account.get(account_id) || {:error, :unauthorized},
:ok <- permit(:all, conn.assigns, account) do
User
|> UserQuery.where_end_user()
|> Account.query_all_users([account.uuid])
|> do_all(attrs, conn)
else
error -> respond_single(error, conn)
end
end
def all_for_account(conn, %{"id" => account_id} = attrs) do
with %Account{} = account <- Account.get(account_id) || {:error, :unauthorized},
:ok <- permit(:all, conn.assigns, account),
descendant_uuids <- Account.get_all_descendants_uuids(account) do
User
|> UserQuery.where_end_user()
|> Account.query_all_users(descendant_uuids)
|> do_all(attrs, conn)
else
error -> respond_single(error, conn)
end
end
def all_for_account(conn, _), do: handle_error(conn, :invalid_parameter)
@spec do_all(Ecto.Queryable.t(), map(), Plug.Conn.t()) :: Plug.Conn.t()
defp do_all(query, attrs, conn) do
query
|> Orchestrator.query(UserOverlay, attrs)
|> respond_multiple(conn)
end
@doc """
Retrieves a specific user by its id.
"""
@spec get(Plug.Conn.t(), map()) :: Plug.Conn.t()
def get(conn, %{"id" => id}) do
with %User{} = user <- User.get(id) || {:error, :unauthorized},
:ok <- permit(:get, conn.assigns, user) do
respond_single(user, conn)
else
error -> respond_single(error, conn)
end
end
def get(conn, %{"provider_user_id" => id})
when is_binary(id) and byte_size(id) > 0 do
with %User{} = user <- User.get_by_provider_user_id(id) || {:error, :unauthorized},
:ok <- permit(:get, conn.assigns, user) do
respond_single(user, conn)
else
error -> respond_single(error, conn)
end
end
def get(conn, _params) do
handle_error(conn, :invalid_parameter)
end
# When creating a new user, we need to link it with the current account
# defined in the key or in the auth token so that the user can access it
# even if that user hasn't had any transaction with the account yet (since
# that's how users and accounts are linked together).
@spec create(Plug.Conn.t(), map()) :: Plug.Conn.t()
def create(conn, attrs) do
with :ok <- permit(:create, conn.assigns, nil),
originator <- Originator.extract(conn.assigns),
attrs <- Map.put(attrs, "originator", originator),
{:ok, user} <- User.insert(attrs),
%Account{} = account <- AccountHelper.get_current_account(conn),
{:ok, _account_user} <- AccountUser.link(account.uuid, user.uuid, originator) do
respond_single(user, conn)
else
error -> respond_single(error, conn)
end
end
@doc """
Updates the user if all required parameters are provided.
"""
# Pattern matching for required params because changeset will treat
# missing param as not need to update.
@spec update(Plug.Conn.t(), map()) :: Plug.Conn.t()
def update(
conn,
%{
"id" => id,
"username" => _
} = attrs
)
when is_binary(id) and byte_size(id) > 0 do
with %User{} = user <- User.get(id) || {:error, :unauthorized},
:ok <- permit(:update, conn.assigns, user),
attrs <- Originator.set_in_attrs(attrs, conn.assigns) do
user
|> User.update(attrs)
|> respond_single(conn)
else
error -> respond_single(error, conn)
end
end
def update(
conn,
%{
"provider_user_id" => id,
"username" => _
} = attrs
)
when is_binary(id) and byte_size(id) > 0 do
with %User{} = user <- User.get_by_provider_user_id(id) || {:error, :unauthorized},
:ok <- permit(:update, conn.assigns, user),
attrs <- Originator.set_in_attrs(attrs, conn.assigns) do
user
|> User.update(attrs)
|> respond_single(conn)
else
error -> respond_single(error, conn)
end
end
def update(conn, _attrs), do: handle_error(conn, :invalid_parameter)
@doc """
Enable or disable a user.
"""
@spec enable_or_disable(Plug.Conn.t(), map()) :: Plug.Conn.t()
def enable_or_disable(conn, attrs) do
with {:ok, %User{} = user} <- UserFetcher.fetch(attrs),
:ok <- permit(:enable_or_disable, conn.assigns, user),
attrs <- Originator.set_in_attrs(attrs, conn.assigns),
{:ok, updated} <- User.enable_or_disable(user, attrs),
:ok <- AuthToken.expire_for_user(updated) do
respond_single(updated, conn)
else
{:error, :invalid_parameter = error} ->
handle_error(
conn,
error,
"Invalid parameter provided. `id` or `provider_user_id` is required."
)
{:error, error} ->
handle_error(conn, error)
end
end
# Respond with a list of users
defp respond_multiple(%Paginator{} = paged_users, conn) do
render(conn, :users, %{users: paged_users})
end
defp respond_multiple({:error, code, description}, conn) do
handle_error(conn, code, description)
end
# Respond with a single user
defp respond_single(%User{} = user, conn), do: render(conn, :user, %{user: user})
# Responds when the user is not found
defp respond_single(nil, conn), do: handle_error(conn, :user_id_not_found)
# Responds when user is saved successfully
defp respond_single({:ok, user}, conn) do
respond_single(user, conn)
end
defp respond_single({:error, %Changeset{} = changeset}, conn) do
handle_error(conn, :invalid_parameter, changeset)
end
defp respond_single({:error, code}, conn) do
handle_error(conn, code)
end
@spec permit(:all | :create | :get | :update, map(), %Account{} | %User{} | nil) ::
:ok | {:error, any()} | no_return()
defp permit(action, params, user) do
Bodyguard.permit(UserPolicy, action, params, user)
end
end
| 32.686099 | 89 | 0.640966 |
03c1a2517ad56a6adcaad64361df07efb7f63df8 | 17,593 | ex | Elixir | clients/drive/lib/google_api/drive/v3/api/drives.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/drive/lib/google_api/drive/v3/api/drives.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/drive/lib/google_api/drive/v3/api/drives.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.Drive.V3.Api.Drives do
@moduledoc """
API calls for all endpoints tagged `Drives`.
"""
alias GoogleApi.Drive.V3.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Creates a new shared drive.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `request_id` (*type:* `String.t`) - An ID, such as a random UUID, which uniquely identifies this user's request for idempotent creation of a shared drive. A repeated request by the same user and with the same request ID will avoid creating duplicates by attempting to create the same shared drive. If the shared drive already exists a 409 error will be returned.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Drive.V3.Model.Drive.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Drive.V3.Model.Drive{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_create(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Drive.V3.Model.Drive.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_create(connection, request_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/drive/v3/drives", %{})
|> Request.add_param(:query, :requestId, request_id)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.Drive{}])
end
@doc """
Permanently deletes a shared drive for which the user is an organizer. The shared drive cannot contain any untrashed items.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `drive_id` (*type:* `String.t`) - The ID of the shared drive.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_delete(connection, drive_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/drive/v3/drives/{driveId}", %{
"driveId" => URI.encode(drive_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Gets a shared drive's metadata by ID.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `drive_id` (*type:* `String.t`) - The ID of the shared drive.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:useDomainAdminAccess` (*type:* `boolean()`) - Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the shared drive belongs.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Drive.V3.Model.Drive{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Drive.V3.Model.Drive.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_get(connection, drive_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:useDomainAdminAccess => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/drive/v3/drives/{driveId}", %{
"driveId" => URI.encode(drive_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.Drive{}])
end
@doc """
Hides a shared drive from the default view.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `drive_id` (*type:* `String.t`) - The ID of the shared drive.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Drive.V3.Model.Drive{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_hide(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Drive.V3.Model.Drive.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_hide(connection, drive_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/drive/v3/drives/{driveId}/hide", %{
"driveId" => URI.encode(drive_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.Drive{}])
end
@doc """
Lists the user's shared drives.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:pageSize` (*type:* `integer()`) - Maximum number of shared drives to return.
* `:pageToken` (*type:* `String.t`) - Page token for shared drives.
* `:q` (*type:* `String.t`) - Query string for searching shared drives.
* `:useDomainAdminAccess` (*type:* `boolean()`) - Issue the request as a domain administrator; if set to true, then all shared drives of the domain in which the requester is an administrator are returned.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Drive.V3.Model.DriveList{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Drive.V3.Model.DriveList.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:pageSize => :query,
:pageToken => :query,
:q => :query,
:useDomainAdminAccess => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/drive/v3/drives", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.DriveList{}])
end
@doc """
Restores a shared drive to the default view.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `drive_id` (*type:* `String.t`) - The ID of the shared drive.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Drive.V3.Model.Drive{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_unhide(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Drive.V3.Model.Drive.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_unhide(connection, drive_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/drive/v3/drives/{driveId}/unhide", %{
"driveId" => URI.encode(drive_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.Drive{}])
end
@doc """
Updates the metadate for a shared drive.
## Parameters
* `connection` (*type:* `GoogleApi.Drive.V3.Connection.t`) - Connection to server
* `drive_id` (*type:* `String.t`) - The ID of the shared drive.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:useDomainAdminAccess` (*type:* `boolean()`) - Issue the request as a domain administrator; if set to true, then the requester will be granted access if they are an administrator of the domain to which the shared drive belongs.
* `:body` (*type:* `GoogleApi.Drive.V3.Model.Drive.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Drive.V3.Model.Drive{}}` on success
* `{:error, info}` on failure
"""
@spec drive_drives_update(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Drive.V3.Model.Drive.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def drive_drives_update(connection, drive_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:useDomainAdminAccess => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/drive/v3/drives/{driveId}", %{
"driveId" => URI.encode(drive_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Drive.V3.Model.Drive{}])
end
end
| 45.934726 | 368 | 0.632524 |
03c1e039157ab901e4224276c58c05ae1ea95e08 | 1,712 | ex | Elixir | clients/display_video/lib/google_api/display_video/v1/model/inventory_source_filter.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/display_video/lib/google_api/display_video/v1/model/inventory_source_filter.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/display_video/lib/google_api/display_video/v1/model/inventory_source_filter.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.DisplayVideo.V1.Model.InventorySourceFilter do
@moduledoc """
A filtering option for filtering on Inventory Source entities.
## Attributes
* `inventorySourceIds` (*type:* `list(String.t)`, *default:* `nil`) - Inventory Sources to download by ID. All IDs must belong to the same Advertiser or Partner specified in CreateSdfDownloadTaskRequest. Leave empty to download all Inventory Sources for the selected Advertiser or Partner.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:inventorySourceIds => list(String.t()) | nil
}
field(:inventorySourceIds, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.InventorySourceFilter do
def decode(value, options) do
GoogleApi.DisplayVideo.V1.Model.InventorySourceFilter.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.InventorySourceFilter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.425532 | 293 | 0.758178 |
03c2140fd8bf185d41d25183e83848a5fd77ce8c | 468 | ex | Elixir | web/router.ex | lsimoneau/panda-ci | 24804b310eda9800a721e71e97bcb0304554517d | [
"MIT"
] | null | null | null | web/router.ex | lsimoneau/panda-ci | 24804b310eda9800a721e71e97bcb0304554517d | [
"MIT"
] | null | null | null | web/router.ex | lsimoneau/panda-ci | 24804b310eda9800a721e71e97bcb0304554517d | [
"MIT"
] | null | null | null | defmodule Panda.Router do
use Panda.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", Panda do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
end
# Other scopes may use custom stacks.
# scope "/api", Panda do
# pipe_through :api
# end
end
| 18 | 57 | 0.655983 |
03c21c9b4f4271e16da8624fa0bbe09a8b18a340 | 739 | ex | Elixir | lib/chatter/post.ex | lucasmelin/Chatter | 023595dab54bc86d94062a61628c344fa5d7f56d | [
"MIT"
] | null | null | null | lib/chatter/post.ex | lucasmelin/Chatter | 023595dab54bc86d94062a61628c344fa5d7f56d | [
"MIT"
] | 1 | 2020-07-16T23:18:36.000Z | 2020-07-16T23:18:36.000Z | lib/chatter/post.ex | lucasmelin/Chatter | 023595dab54bc86d94062a61628c344fa5d7f56d | [
"MIT"
] | null | null | null | defmodule Chatter.Post do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query
alias Chatter.{User, Comment, Repo}
schema "posts" do
field :body, :string
belongs_to :user, User
has_many :comments, Comment
timestamps()
end
def all do
Repo.all(
from p in __MODULE__,
order_by: [desc: p.id]
)
end
def find(id) do
Repo.get(__MODULE__, id)
end
def create(attrs) do
attrs
|> changeset()
|> Repo.insert()
end
def changeset(attrs) do
%__MODULE__{}
|> changeset(attrs)
end
def changeset(post, attrs) do
post
|> cast(attrs, [:body, :user_id])
|> validate_required([:body, :user_id])
|> foreign_key_constraint(:user_id)
end
end
| 16.065217 | 43 | 0.622463 |
03c266f00c096fb4098750090cde2b9437c9df38 | 3,365 | ex | Elixir | lib/absinthe/type/enum.ex | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 2 | 2021-04-22T23:45:04.000Z | 2021-05-07T01:01:15.000Z | lib/absinthe/type/enum.ex | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 1 | 2020-04-07T23:46:38.000Z | 2020-04-07T23:46:38.000Z | lib/absinthe/type/enum.ex | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | null | null | null | defmodule Absinthe.Type.Enum do
@moduledoc """
Used to define an enum type, a special scalar that can only have a defined set
of values.
See the `t` type below for details and examples.
## Examples
Given a type defined as the following (see `Absinthe.Schema.Notation`):
```
@desc "The selected color channel"
enum :color_channel do
value :red, as: :r, description: "Color Red"
value :green, as: :g, description: "Color Green"
value :blue, as: :b, description: "Color Blue"
value :alpha, as: :a, deprecate: "We no longer support opacity settings", description: "Alpha Channel"
end
```
The "ColorChannel" type (referred inside Absinthe as `:color_channel`) is an
Enum type, with values with names "red", "green", "blue", and "alpha" that map
to internal, raw values `:r`, `:g`, `:b`, and `:a`. The alpha color channel
is deprecated, just as fields and arguments can be.
You can omit the raw `value` if you'd like it to be the same as the
identifier. For instance, in this example the `value` is automatically set to
`:red`:
```
enum :color_channel do
description "The selected color channel"
value :red, description: "Color Red"
value :green, description: "Color Green"
value :blue, description: "Color Blue"
value :alpha, deprecate: "We no longer support opacity settings", description: "Alpha Channel"
end
```
If you really want to use a shorthand, skipping support for descriptions,
custom raw values, and deprecation, you can just provide a list of atoms:
```
enum :color_channel, values: [:red, :green, :blue, :alpha]
```
Keep in mind that writing a terse definition that skips descriptions and
deprecations today may hamper tooling that relies on introspection tomorrow.
"""
use Absinthe.Introspection.Kind
alias Absinthe.{Blueprint, Type}
@typedoc """
A defined enum type.
Should be defined using `Absinthe.Schema.Notation.enum/2`.
* `:name` - The name of the enum type. Should be a TitleCased `binary`. Set automatically.
* `:description` - A nice description for introspection.
* `:values` - The enum values, usually provided using the `Absinthe.Schema.Notation.values/1` or `Absinthe.Schema.Notation.value/1` macro.
The `__private__` and `:__reference__` fields are for internal use.
"""
@type t :: %__MODULE__{
name: binary,
description: binary,
values: %{binary => Type.Enum.Value.t()},
identifier: atom,
__private__: Keyword.t(),
definition: module,
__reference__: Type.Reference.t()
}
defstruct name: nil,
description: nil,
identifier: nil,
values: %{},
values_by_internal_value: %{},
values_by_name: %{},
__private__: [],
definition: nil,
__reference__: nil
# Get the internal representation of an enum value
@doc false
@spec parse(t, any) :: any
def parse(enum, %Blueprint.Input.Enum{value: external_value}) do
Map.fetch(enum.values_by_name, external_value)
end
def parse(_, _) do
:error
end
# Get the external representation of an enum value
@doc false
@spec serialize(t, any) :: binary
def serialize(enum, internal_value) do
Map.fetch!(enum.values_by_internal_value, internal_value).name
end
end
| 31.157407 | 140 | 0.668945 |
03c276a3e2632be7c7238cf0e69e5e1962a7e727 | 2,126 | ex | Elixir | lib/swoosh/adapters/logger.ex | craigp/swoosh | 83364b3e9029988e585d4cc0c4d5ec1ccfb4930a | [
"MIT"
] | 1,214 | 2016-03-21T16:56:42.000Z | 2022-03-31T19:10:11.000Z | lib/swoosh/adapters/logger.ex | craigp/swoosh | 83364b3e9029988e585d4cc0c4d5ec1ccfb4930a | [
"MIT"
] | 399 | 2016-03-21T23:11:32.000Z | 2022-03-04T10:52:28.000Z | lib/swoosh/adapters/logger.ex | nash-io/swoosh | 05c8676890da07403225c302f9a069fc7d221330 | [
"MIT"
] | 208 | 2016-03-21T21:12:11.000Z | 2022-03-04T06:35:33.000Z | defmodule Swoosh.Adapters.Logger do
@moduledoc ~S"""
An adapter that only logs email using Logger.
It can be useful in environment where you do not necessarily want to send real
emails (eg. staging environments) or in development.
By default it only prints the recipient of the email but you can print the full
email by using `log_full_email: true` in the adapter configuration.
## Example
# config/config.exs
config :sample, Sample.Mailer,
adapter: Swoosh.Adapters.Logger,
level: :debug
# lib/sample/mailer.ex
defmodule Sample.Mailer do
use Swoosh.Mailer, otp_app: :sample
end
"""
use Swoosh.Adapter
require Logger
import Swoosh.Email.Render
@impl true
def deliver(%Swoosh.Email{} = email, config) do
rendered_email = render(config[:log_full_email] || false, email)
Logger.log(config[:level] || :info, rendered_email)
{:ok, %{}}
end
defp render(false, email) do
"New email delivered to #{render_recipient(email.to)}"
end
defp render(true, email) do
recipients = render_recipients(email)
subject = render_subject(email)
headers = render_headers(email)
bodies = render_bodies(email)
message =
[recipients, subject, headers, bodies]
|> Enum.filter(fn text -> text != "" end)
|> Enum.join("\n")
"New email delivered\n#{message}"
end
defp render_subject(email), do: "Subject: #{email.subject}"
defp render_recipients(email) do
[:from, :reply_to, :to, :cc, :bcc]
|> Enum.map(fn key -> {to_string(key), Map.get(email, key)} end)
|> Enum.filter(fn
{_key, value} when is_list(value) -> !Enum.empty?(value)
{_key, value} -> value
end)
|> Enum.map_join("\n", fn {key, value} ->
String.capitalize(key) <> ": " <> render_recipient(value)
end)
end
defp render_headers(email) do
Enum.map_join(
email.headers,
"\n",
fn {key, value} -> "#{key}: #{value}" end
)
end
defp render_bodies(email) do
"""
Text body:
#{email.text_body}
HTML body:
#{email.html_body}
"""
end
end
| 24.436782 | 81 | 0.636877 |
03c2a657ccd1fada2ff2e450458f243b837c2a67 | 336 | exs | Elixir | inverse_captcha/mix.exs | ChrisWilding/Advent-of-Code-2017 | 62284eec7a0e924230d82765d9ae17e52bc52ca8 | [
"Apache-2.0"
] | 1 | 2019-05-14T05:10:34.000Z | 2019-05-14T05:10:34.000Z | inverse_captcha/mix.exs | ChrisWilding/Advent-of-Code-2017 | 62284eec7a0e924230d82765d9ae17e52bc52ca8 | [
"Apache-2.0"
] | null | null | null | inverse_captcha/mix.exs | ChrisWilding/Advent-of-Code-2017 | 62284eec7a0e924230d82765d9ae17e52bc52ca8 | [
"Apache-2.0"
] | null | null | null | defmodule InverseCaptcha.Mixfile do
use Mix.Project
def project do
[
app: :inverse_captcha,
version: "0.1.0",
elixir: "~> 1.5",
start_permanent: Mix.env == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[]
end
end
| 14 | 40 | 0.559524 |
03c2abaca38f2fc0a2e1b1497a550b75f096bfd4 | 5,122 | ex | Elixir | lib/documenter/api.ex | IanLuites/api_doc | b93ac8d82888c96bde7c55a08ec5716926976097 | [
"MIT"
] | 1 | 2020-01-12T03:41:03.000Z | 2020-01-12T03:41:03.000Z | lib/documenter/api.ex | IanLuites/api_doc | b93ac8d82888c96bde7c55a08ec5716926976097 | [
"MIT"
] | 1 | 2019-04-17T15:32:15.000Z | 2019-04-17T15:32:15.000Z | lib/documenter/api.ex | IanLuites/api_doc | b93ac8d82888c96bde7c55a08ec5716926976097 | [
"MIT"
] | null | null | null | defmodule APIDoc.APIDocumenter do
@moduledoc ~S"""
API Documenter.
Documents the main entry of the API.
The following annotations can be set:
- `@api` (string) name of the API.
- `@vsn` (string) version of the API.
- `@moduledoc` (string) API description. Supports markdown.
- `@contact` (string) contact info.
The following macros can be used for documenting:
- `schema/2`, `schema/3`: Adds data schemas to the documentation.
- `server/1`, `server/2`: Add possible servers to the documentation.
"""
require Logger
alias APIDoc.Doc.Contact
alias APIDoc.Doc.Schema
alias APIDoc.Doc.Security
alias APIDoc.Doc.Server
alias Mix.Project
@doc @moduledoc
defmacro __using__(opts \\ []) do
quote do
Module.register_attribute(__MODULE__, :api, accumulate: false, persist: false)
Module.register_attribute(__MODULE__, :contact, accumulate: false, persist: false)
Module.register_attribute(__MODULE__, :security, accumulate: true, persist: false)
Module.register_attribute(__MODULE__, :server, accumulate: true, persist: false)
Module.register_attribute(__MODULE__, :schema, accumulate: true, persist: false)
require APIDoc.APIDocumenter
import APIDoc.APIDocumenter,
only: [server: 1, server: 2, schema: 2, schema: 3, security: 4, security: 5]
@before_compile APIDoc.APIDocumenter
@router unquote(opts[:router])
end
end
@doc false
defmacro __before_compile__(env) do
name = Module.get_attribute(env.module, :api) || "API Documentation"
version = Module.get_attribute(env.module, :vsn) || Project.config()[:version]
servers = Module.get_attribute(env.module, :server) || []
schemas = Module.get_attribute(env.module, :schema) || []
security = Module.get_attribute(env.module, :security) || []
contact =
with %{"email" => email, "name" => name} <-
Regex.named_captures(
~r/^(?'name'.*?)\ ?<(?'email'.*)>$/,
Module.get_attribute(env.module, :contact) || ""
) do
%Contact{email: email, name: name}
else
_ -> nil
end
# Perform validations
schemas |> Enum.each(&Schema.validate!/1)
quote do
@doc ~S"""
Format the document with a given formatter.
Uses `APIDoc.Format.OpenAPI3` by default.
"""
@spec format(atom) :: String.t()
def format(formatter \\ APIDoc.Format.OpenAPI3), do: formatter.format(__document__())
@doc false
@spec __document__ :: map
def __document__ do
%APIDoc.Doc.Document{
info: %APIDoc.Doc.Info{
name: unquote(name),
version: unquote(version),
description: @moduledoc,
contact: unquote(Macro.escape(contact))
},
servers: unquote(Macro.escape(servers)),
schemas: unquote(Macro.escape(schemas)),
security: unquote(Macro.escape(Enum.into(security, %{}))),
endpoints: @router.__api_doc__()
}
end
end
end
@doc ~S"""
Add server to documentation.
## Examples
Only url:
```
server "https://prod.example.com"
server "https://stage.example.com"
```
Url and description:
```
server "https://prod.example.com", "Production example server"
server "https://stage.example.com", "Staging example server"
```
"""
@spec server(String.t(), String.t() | nil) :: term
defmacro server(url, description \\ nil) do
quote do
@server %Server{
url: unquote(url),
description: unquote(description)
}
end
end
@doc ~S"""
Add security scheme to documentation.
```
"""
@spec security(atom, String.t(), Security.type(), Security.location(), String.t() | nil) :: term
defmacro security(id, name, type, location, description \\ nil) do
quote do
@security {unquote(id),
%Security{
name: unquote(Macro.expand(name, __CALLER__)),
type: unquote(type),
in: unquote(location),
description: unquote(description)
}}
end
end
@doc ~S"""
Add schema to documentation.
The `name` and `type` are always required.
For additional optional fields see: `APIDoc.Doc.Schema`.
## Examples
Just name and type:
```
schema Name, :string
schema Age, :integer
```
Additional options:
```
schema Name, :string,
example: "Bob"
schema Age, :integer,
format: :int32,
example: 34,
minimum: 1,
maximum: 150
```
"""
@spec schema(atom, Schema.type(), Keyword.t()) :: term
defmacro schema(name, type, opts \\ []) do
quote do
@schema %Schema{
name: unquote(Macro.expand(name, __CALLER__)),
type: unquote(type),
format: unquote(opts[:format]),
required: unquote(opts[:required]),
properties: unquote(opts[:properties]),
example: unquote(opts[:example]),
minimum: unquote(opts[:minimum]),
maximum: unquote(opts[:maximum]),
items: unquote(opts[:items])
}
end
end
end
| 28.142857 | 98 | 0.612847 |
03c2b3403108edde732cab913b3f339f5c86cc57 | 711 | exs | Elixir | test/exception_test.exs | ktec/decorator | 2ceda1adc8beea7eb6d712034f9ae8d12ff3e46f | [
"MIT"
] | null | null | null | test/exception_test.exs | ktec/decorator | 2ceda1adc8beea7eb6d712034f9ae8d12ff3e46f | [
"MIT"
] | null | null | null | test/exception_test.exs | ktec/decorator | 2ceda1adc8beea7eb6d712034f9ae8d12ff3e46f | [
"MIT"
] | null | null | null | # two arguments
defmodule DecoratorTest.Fixture.ExceptionDecorator do
use Decorator.Define, test: 0
def test(body, _context) do
{:ok, body}
end
end
defmodule DecoratorTest.Fixture.ExceptionTestModule do
use DecoratorTest.Fixture.ExceptionDecorator
@decorate test()
def result(a) do
if a == :throw do
raise RuntimeError, "text"
end
a
rescue
_ in RuntimeError ->
:error
end
end
defmodule DecoratorTest.Exception do
use ExUnit.Case
alias DecoratorTest.Fixture.ExceptionTestModule
test "Functions which have a 'rescue' clause" do
assert {:ok, 3} = ExceptionTestModule.result(3)
assert {:ok, :error} = ExceptionTestModule.result(:throw)
end
end
| 19.75 | 61 | 0.7173 |
03c30473c36cb2365c493eb18592410365859541 | 1,095 | exs | Elixir | test/todotin/router_user_test.exs | matin-nayob/todotin | 8f356118a7197ef9276ce3fa8437de1d03c356f9 | [
"Unlicense"
] | null | null | null | test/todotin/router_user_test.exs | matin-nayob/todotin | 8f356118a7197ef9276ce3fa8437de1d03c356f9 | [
"Unlicense"
] | null | null | null | test/todotin/router_user_test.exs | matin-nayob/todotin | 8f356118a7197ef9276ce3fa8437de1d03c356f9 | [
"Unlicense"
] | null | null | null | defmodule Todotin.Routers.UserTest do
use ExUnit.Case
use Plug.Test
alias Todotin.Router.Main
@opt Main.init([])
setup do
user = Todotin.Model.User.new("user.router@test.com", "User Router Test")
{:ok, user: user, user_id: user.user_id}
end
test "create user fail", context do
resp =
:put
|> conn("/user/new", %{:wrong => "value"})
|> Main.call(@opts)
assert resp.state == :sent
assert resp.status == 422
end
test "create user success", context do
resp =
:put
|> conn("/user/new", %{:user_id => context[:user_id], :name => context.user.name})
|> Main.call(@opts)
assert resp.state == :sent
assert resp.status == 201
end
test "get user home", context do
resp =
:get
|> conn("/user/", "")
|> Main.call(@opts)
assert resp.state == :sent
assert resp.status == 200
end
test "get user", context do
resp =
:get
|> conn("/user/#{context[:user_id]}", "")
|> Main.call(@opts)
assert resp.state == :sent
assert resp.status == 200
end
end
| 19.909091 | 88 | 0.573516 |
03c32f79dcf44a923acabd9c444be29b9b9de31e | 191 | exs | Elixir | priv/repo/migrations/20170520194853_add_hidden_to_categories.exs | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 184 | 2015-11-23T20:51:50.000Z | 2022-03-30T01:01:39.000Z | priv/repo/migrations/20170520194853_add_hidden_to_categories.exs | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 15 | 2015-11-26T16:00:20.000Z | 2018-05-25T20:13:39.000Z | priv/repo/migrations/20170520194853_add_hidden_to_categories.exs | van-mronov/ex_money | 39010f02fd822657e3b5694e08b872bd2ab72c26 | [
"0BSD"
] | 21 | 2015-11-26T21:34:40.000Z | 2022-03-26T02:56:42.000Z | defmodule ExMoney.Repo.Migrations.AddHiddenToCategories do
use Ecto.Migration
def change do
alter table(:categories) do
add :hidden, :boolean, default: false
end
end
end
| 19.1 | 58 | 0.727749 |
03c33403fa01e1d50459678a896f3f88302d338f | 1,180 | exs | Elixir | test/test_helper.exs | Jcambass/phoenix_ecto | d0bed6522ef286feb14bd00019c406acf5670002 | [
"MIT"
] | 359 | 2015-03-06T17:03:53.000Z | 2022-03-24T19:24:44.000Z | test/test_helper.exs | Jcambass/phoenix_ecto | d0bed6522ef286feb14bd00019c406acf5670002 | [
"MIT"
] | 134 | 2015-03-14T01:19:51.000Z | 2022-03-31T11:44:51.000Z | test/test_helper.exs | Jcambass/phoenix_ecto | d0bed6522ef286feb14bd00019c406acf5670002 | [
"MIT"
] | 128 | 2015-03-12T00:05:54.000Z | 2022-03-31T11:11:50.000Z | defmodule Permalink do
use Ecto.Schema
embedded_schema do
field :url
end
def changeset(permalink, params) do
import Ecto.Changeset
permalink
|> cast(params, ~w(url)a)
|> validate_required(:url)
|> validate_length(:url, min: 3)
end
end
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :body
end
def changeset(comment, params) do
import Ecto.Changeset
comment
|> cast(params, ~w(body)a)
|> validate_required(:body)
|> validate_length(:body, min: 3)
end
def custom_changeset(comment, params, required_length) do
import Ecto.Changeset
comment
|> cast(params, ~w(body)a)
|> validate_length(:body, min: required_length)
end
end
defmodule User do
use Ecto.Schema
schema "users" do
field :name
field :title
field :age, :integer
field :score, :decimal
embeds_one :permalink, Permalink, on_replace: :delete
embeds_many :permalinks, Permalink, on_replace: :delete
has_one :comment, Comment, on_replace: :delete
has_many :comments, Comment, on_replace: :delete
end
end
defmodule SchemalessUser do
defstruct name: nil
end
ExUnit.start()
| 18.730159 | 59 | 0.685593 |
03c340c906b54121dbe98ae9dbaeae92cafa1124 | 599 | ex | Elixir | web/views/talk_view.ex | pbrudnick/pyconar-talks | f0b2fdff9cae7bd7558cb4fdc5e0048403bbde7e | [
"MIT"
] | null | null | null | web/views/talk_view.ex | pbrudnick/pyconar-talks | f0b2fdff9cae7bd7558cb4fdc5e0048403bbde7e | [
"MIT"
] | null | null | null | web/views/talk_view.ex | pbrudnick/pyconar-talks | f0b2fdff9cae7bd7558cb4fdc5e0048403bbde7e | [
"MIT"
] | null | null | null | defmodule PyconarTalks.TalkView do
use PyconarTalks.Web, :view
def render("index.json", %{talks: talks}) do
%{talks: render_many(talks, PyconarTalks.TalkView, "talk.json")}
end
def render("show.json", %{talk: talk}) do
%{talk: render_one(talk, PyconarTalks.TalkView, "talk.json")}
end
def render("talk.json", %{talk: talk}) do
%{id: talk.id,
name: talk.name,
description: talk.description,
tags: talk.tags,
conf_key: talk.conf_key,
room: talk.room,
author: talk.author,
start: talk.start,
disabled: talk.disabled}
end
end
| 24.958333 | 68 | 0.641068 |
03c3b43a9a71f77cec704be73ec493c81a42a207 | 5,095 | ex | Elixir | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1_workload.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1_workload.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1_workload.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"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.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1Workload do
@moduledoc """
An Workload object for managing highly regulated workloads of cloud customers.
## Attributes
* `billingAccount` (*type:* `String.t`, *default:* `nil`) - Required. Input only. The billing account used for the resources which are direct children of workload. This billing account is initially associated with the resources created as part of Workload creation. After the initial creation of these resources, the customer can change the assigned billing account. The resource name has the form `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF`.
* `complianceRegime` (*type:* `String.t`, *default:* `nil`) - Required. Immutable. Compliance Regime associated with this workload.
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Immutable. The Workload creation timestamp.
* `displayName` (*type:* `String.t`, *default:* `nil`) - Required. The user-assigned display name of the Workload. When present it must be between 4 to 30 characters. Allowed characters are: lowercase and uppercase letters, numbers, hyphen, and spaces. Example: My Workload
* `etag` (*type:* `String.t`, *default:* `nil`) - Optional. ETag of the workload, it is calculated on the basis of the Workload contents. It will be used in Update & Delete operations.
* `kmsSettings` (*type:* `GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadKMSSettings.t`, *default:* `nil`) - Input only. Settings used to create a CMEK crypto key. When set a project with a KMS CMEK key is provisioned. This field is mandatory for a subset of Compliance Regimes.
* `labels` (*type:* `map()`, *default:* `nil`) - Optional. Labels applied to the workload.
* `name` (*type:* `String.t`, *default:* `nil`) - Optional. The resource name of the workload. Format: organizations/{organization}/locations/{location}/workloads/{workload} Read-only.
* `provisionedResourcesParent` (*type:* `String.t`, *default:* `nil`) - Input only. The parent resource for the resources managed by this Assured Workload. May be either an organization or a folder. Must be the same or a child of the Workload parent. If not specified all resources are created under the Workload parent. Formats: folders/{folder_id} organizations/{organization_id}
* `resources` (*type:* `list(GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadResourceInfo.t)`, *default:* `nil`) - Output only. The resources associated with this workload. These resources will be created when creating the workload. If any of the projects already exist, the workload creation will fail. Always read only.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:billingAccount => String.t(),
:complianceRegime => String.t(),
:createTime => DateTime.t(),
:displayName => String.t(),
:etag => String.t(),
:kmsSettings =>
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadKMSSettings.t(),
:labels => map(),
:name => String.t(),
:provisionedResourcesParent => String.t(),
:resources =>
list(
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadResourceInfo.t()
)
}
field(:billingAccount)
field(:complianceRegime)
field(:createTime, as: DateTime)
field(:displayName)
field(:etag)
field(:kmsSettings,
as: GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadKMSSettings
)
field(:labels, type: :map)
field(:name)
field(:provisionedResourcesParent)
field(:resources,
as:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1WorkloadResourceInfo,
type: :list
)
end
defimpl Poison.Decoder,
for: GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1Workload do
def decode(value, options) do
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1Workload.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1Workload do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 55.380435 | 494 | 0.735623 |
03c3bc2cbc36cc6e19bb7178a5c7e01f7b73cab6 | 295 | ex | Elixir | lib/still.ex | tomasz-tomczyk/still | 3f2fdb64c72244b789e14b31d514199f8adeb796 | [
"ISC"
] | 202 | 2021-01-13T15:45:17.000Z | 2022-03-22T01:26:27.000Z | lib/still.ex | tomasz-tomczyk/still | 3f2fdb64c72244b789e14b31d514199f8adeb796 | [
"ISC"
] | 55 | 2021-01-26T14:11:34.000Z | 2022-03-22T22:34:37.000Z | lib/still.ex | tomasz-tomczyk/still | 3f2fdb64c72244b789e14b31d514199f8adeb796 | [
"ISC"
] | 10 | 2021-02-04T21:14:41.000Z | 2022-03-20T10:12:59.000Z | defmodule Still do
@moduledoc false
@doc """
Registers a callback to be called synchronously after the compilation.
"""
defdelegate after_compile(fun), to: Still.Compiler.Compile
@doc """
Compiles the site.
"""
defdelegate compile(), to: Still.Compiler.Compile, as: :run
end
| 21.071429 | 72 | 0.705085 |
03c3d7bbaf6ae254a12b7bfd3be05ade65977b91 | 57,003 | ex | Elixir | lib/db_connection.ex | kianmeng/db_connection | 9752b8194f945c6a877e07c0eb8b7dbc41177f0d | [
"Apache-2.0"
] | 1 | 2021-02-24T13:06:18.000Z | 2021-02-24T13:06:18.000Z | lib/db_connection.ex | kianmeng/db_connection | 9752b8194f945c6a877e07c0eb8b7dbc41177f0d | [
"Apache-2.0"
] | null | null | null | lib/db_connection.ex | kianmeng/db_connection | 9752b8194f945c6a877e07c0eb8b7dbc41177f0d | [
"Apache-2.0"
] | null | null | null | defmodule DBConnection.Stream do
defstruct [:conn, :query, :params, :opts]
@type t :: %__MODULE__{conn: DBConnection.conn,
query: any,
params: any,
opts: Keyword.t}
end
defimpl Enumerable, for: DBConnection.Stream do
def count(_), do: {:error, __MODULE__}
def member?(_, _), do: {:error, __MODULE__}
def slice(_), do: {:error, __MODULE__}
def reduce(stream, acc, fun), do: DBConnection.reduce(stream, acc, fun)
end
defmodule DBConnection.PrepareStream do
defstruct [:conn, :query, :params, :opts]
@type t :: %__MODULE__{conn: DBConnection.conn,
query: any,
params: any,
opts: Keyword.t}
end
defimpl Enumerable, for: DBConnection.PrepareStream do
def count(_), do: {:error, __MODULE__}
def member?(_, _), do: {:error, __MODULE__}
def slice(_), do: {:error, __MODULE__}
def reduce(stream, acc, fun), do: DBConnection.reduce(stream, acc, fun)
end
defmodule DBConnection do
@moduledoc """
A behaviour module for implementing efficient database connection
client processes, pools and transactions.
`DBConnection` handles callbacks differently to most behaviours. Some
callbacks will be called in the calling process, with the state
copied to and from the calling process. This is useful when the data
for a request is large and means that a calling process can interact
with a socket directly.
A side effect of this is that query handling can be written in a
simple blocking fashion, while the connection process itself will
remain responsive to OTP messages and can enqueue and cancel queued
requests.
If a request or series of requests takes too long to handle in the
client process a timeout will trigger and the socket can be cleanly
disconnected by the connection process.
If a calling process waits too long to start its request it will
timeout and its request will be cancelled. This prevents requests
building up when the database can not keep up.
If no requests are received for an idle interval, the pool will
ping all stale connections which can then ping the database to keep
the connection alive.
Should the connection be lost, attempts will be made to reconnect with
(configurable) exponential random backoff to reconnect. All state is
lost when a connection disconnects but the process is reused.
The `DBConnection.Query` protocol provide utility functions so that
queries can be encoded and decoded without blocking the connection or pool.
"""
require Logger
alias DBConnection.Holder
defstruct [:pool_ref, :conn_ref, :conn_mode]
defmodule EncodeError do
defexception [:message]
end
defmodule TransactionError do
defexception [:status, :message]
def exception(:idle),
do: %__MODULE__{status: :idle, message: "transaction is not started"}
def exception(:transaction),
do: %__MODULE__{status: :transaction, message: "transaction is already started"}
def exception(:error),
do: %__MODULE__{status: :error, message: "transaction is aborted"}
end
@typedoc """
Run or transaction connection reference.
"""
@type t :: %__MODULE__{pool_ref: any, conn_ref: reference}
@type conn :: GenServer.server | t
@type query :: DBConnection.Query.t
@type params :: any
@type result :: any
@type cursor :: any
@type status :: :idle | :transaction | :error
@type start_option ::
{:after_connect, (t -> any) | {module, atom, [any]} | nil}
| {:after_connect_timeout, timeout}
| {:connection_listeners, list(Process.dest()) | nil}
| {:backoff_max, non_neg_integer}
| {:backoff_min, non_neg_integer}
| {:backoff_type, :stop | :exp | :rand | :rand_exp}
| {:configure, (keyword -> keyword) | {module, atom, [any]} | nil}
| {:idle_interval, non_neg_integer}
| {:max_restarts, non_neg_integer}
| {:max_seconds, pos_integer}
| {:name, GenServer.name()}
| {:pool, module}
| {:pool_size, pos_integer}
| {:queue_interval, non_neg_integer}
| {:queue_target, non_neg_integer}
| {:show_sensitive_data_on_connection_error, boolean}
@type option ::
{:log, (DBConnection.LogEntry.t -> any) | {module, atom, [any]} | nil}
| {:queue, boolean}
| {:timeout, timeout}
| {:deadline, integer | nil}
@doc """
Connect to the database. Return `{:ok, state}` on success or
`{:error, exception}` on failure.
If an error is returned it will be logged and another
connection attempt will be made after a backoff interval.
This callback is called in the connection process.
"""
@callback connect(opts :: Keyword.t) ::
{:ok, state :: any} | {:error, Exception.t}
@doc """
Checkouts the state from the connection process. Return `{:ok, state}`
to allow the checkout or `{:disconnect, exception, state}` to disconnect.
This callback is called when the control of the state is passed to
another process. `c:checkin/1` is called with the new state when control
is returned to the connection process.
This callback is called in the connection process.
"""
@callback checkout(state :: any) ::
{:ok, new_state :: any} | {:disconnect, Exception.t, new_state :: any}
@doc """
Checks in the state to the connection process. Return `{:ok, state}`
to allow the checkin or `{:disconnect, exception, state}` to disconnect.
This callback is called when the control of the state is passed back
to the connection process. It should reverse any changes to the
connection state made in `c:checkout/1`.
This callback is called in the connection process.
"""
@callback checkin(state :: any) ::
{:ok, new_state :: any} | {:disconnect, Exception.t, new_state :: any}
@doc """
Called when the connection has been idle for a period of time. Return
`{:ok, state}` to continue or `{:disconnect, exception, state}` to
disconnect.
This callback is called if no callbacks have been called after the
idle timeout and a client process is not using the state. The idle
timeout can be configured by the `:idle_interval` option. This function
can be called whether the connection is checked in or checked out.
This callback is called in the connection process.
"""
@callback ping(state :: any) ::
{:ok, new_state :: any} | {:disconnect, Exception.t, new_state :: any}
@doc """
Handle the beginning of a transaction.
Return `{:ok, result, state}` to continue, `{status, state}` to notify caller
that the transaction can not begin due to the transaction status `status`,
`{:error, exception, state}` (deprecated) to error without beginning the
transaction, or `{:disconnect, exception, state}` to error and disconnect.
A callback implementation should only return `status` if it
can determine the database's transaction status without side effect.
This callback is called in the client process.
"""
@callback handle_begin(opts :: Keyword.t, state :: any) ::
{:ok, result, new_state :: any} |
{status, new_state :: any} |
{:disconnect, Exception.t, new_state :: any}
@doc """
Handle committing a transaction. Return `{:ok, result, state}` on successfully
committing transaction, `{status, state}` to notify caller that the
transaction can not commit due to the transaction status `status`,
`{:error, exception, state}` (deprecated) to error and no longer be inside
transaction, or `{:disconnect, exception, state}` to error and disconnect.
A callback implementation should only return `status` if it
can determine the database's transaction status without side effect.
This callback is called in the client process.
"""
@callback handle_commit(opts :: Keyword.t, state :: any) ::
{:ok, result, new_state :: any} |
{status, new_state :: any} |
{:disconnect, Exception.t, new_state :: any}
@doc """
Handle rolling back a transaction. Return `{:ok, result, state}` on successfully
rolling back transaction, `{status, state}` to notify caller that the
transaction can not rollback due to the transaction status `status`,
`{:error, exception, state}` (deprecated) to
error and no longer be inside transaction, or
`{:disconnect, exception, state}` to error and disconnect.
A callback implementation should only return `status` if it
can determine the database' transaction status without side effect.
This callback is called in the client and connection process.
"""
@callback handle_rollback(opts :: Keyword.t, state :: any) ::
{:ok, result, new_state :: any} |
{status, new_state :: any} |
{:disconnect, Exception.t, new_state :: any}
@doc """
Handle getting the transaction status. Return `{:idle, state}` if outside a
transaction, `{:transaction, state}` if inside a transaction,
`{:error, state}` if inside an aborted transaction, or
`{:disconnect, exception, state}` to error and disconnect.
If the callback returns a `:disconnect` tuples then `status/2` will return
`:error`.
"""
@callback handle_status(opts :: Keyword.t, state :: any) ::
{status, new_state :: any} |
{:disconnect, Exception.t, new_state :: any}
@doc """
Prepare a query with the database. Return `{:ok, query, state}` where
`query` is a query to pass to `execute/4` or `close/3`,
`{:error, exception, state}` to return an error and continue or
`{:disconnect, exception, state}` to return an error and disconnect.
This callback is intended for cases where the state of a connection is
needed to prepare a query and/or the query can be saved in the
database to call later.
This callback is called in the client process.
"""
@callback handle_prepare(query, opts :: Keyword.t, state :: any) ::
{:ok, query, new_state :: any} |
{:error | :disconnect, Exception.t, new_state :: any}
@doc """
Execute a query prepared by `c:handle_prepare/3`. Return
`{:ok, query, result, state}` to return altered query `query` and result
`result` and continue, `{:error, exception, state}` to return an error and
continue or `{:disconnect, exception, state}` to return an error and
disconnect.
This callback is called in the client process.
"""
@callback handle_execute(query, params, opts :: Keyword.t, state :: any) ::
{:ok, query, result, new_state :: any} |
{:error | :disconnect, Exception.t, new_state :: any}
@doc """
Close a query prepared by `c:handle_prepare/3` with the database. Return
`{:ok, result, state}` on success and to continue,
`{:error, exception, state}` to return an error and continue, or
`{:disconnect, exception, state}` to return an error and disconnect.
This callback is called in the client process.
"""
@callback handle_close(query, opts :: Keyword.t, state :: any) ::
{:ok, result, new_state :: any} |
{:error | :disconnect, Exception.t, new_state :: any}
@doc """
Declare a cursor using a query prepared by `c:handle_prepare/3`. Return
`{:ok, query, cursor, state}` to return altered query `query` and cursor
`cursor` for a stream and continue, `{:error, exception, state}` to return an
error and continue or `{:disconnect, exception, state}` to return an error
and disconnect.
This callback is called in the client process.
"""
@callback handle_declare(query, params, opts :: Keyword.t, state :: any) ::
{:ok, query, cursor, new_state :: any} |
{:error | :disconnect, Exception.t, new_state :: any}
@doc """
Fetch the next result from a cursor declared by `c:handle_declare/4`. Return
`{:cont, result, state}` to return the result `result` and continue using
cursor, `{:halt, result, state}` to return the result `result` and close the
cursor, `{:error, exception, state}` to return an error and close the
cursor, `{:disconnect, exception, state}` to return an error and disconnect.
This callback is called in the client process.
"""
@callback handle_fetch(query, cursor, opts :: Keyword.t, state :: any) ::
{:cont | :halt, result, new_state :: any} |
{:error | :disconnect, Exception.t, new_state :: any}
@doc """
Deallocate a cursor declared by `c:handle_declare/4` with the database. Return
`{:ok, result, state}` on success and to continue,
`{:error, exception, state}` to return an error and continue, or
`{:disconnect, exception, state}` to return an error and disconnect.
This callback is called in the client process.
"""
@callback handle_deallocate(query, cursor, opts :: Keyword.t, state :: any) ::
{:ok, result, new_state :: any} |
{:error | :disconnect, Exception.t, new_state :: any}
@doc """
Disconnect from the database. Return `:ok`.
The exception as first argument is the exception from a `:disconnect`
3-tuple returned by a previous callback.
If the state is controlled by a client and it exits or takes too long
to process a request the state will be last known state. In these
cases the exception will be a `DBConnection.ConnectionError`.
This callback is called in the connection process.
"""
@callback disconnect(err :: Exception.t, state :: any) :: :ok
@doc """
Use `DBConnection` to set the behaviour.
"""
defmacro __using__(_) do
quote location: :keep do
@behaviour DBConnection
end
end
@doc """
Starts and links to a database connection process.
By default the `DBConnection` starts a pool with a single connection.
The size of the pool can be increased with `:pool_size`. A separate
pool can be given with the `:pool` option.
### Options
* `:backoff_min` - The minimum backoff interval (default: `1_000`)
* `:backoff_max` - The maximum backoff interval (default: `30_000`)
* `:backoff_type` - The backoff strategy, `:stop` for no backoff and
to stop, `:exp` for exponential, `:rand` for random and `:rand_exp` for
random exponential (default: `:rand_exp`)
* `:configure` - A function to run before every connect attempt to
dynamically configure the options, either a 1-arity fun,
`{module, function, args}` with options prepended to `args` or `nil` where
only returned options are passed to connect callback (default: `nil`)
* `:after_connect` - A function to run on connect using `run/3`, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.t/0` prepended
to `args` or `nil` (default: `nil`)
* `:after_connect_timeout` - The maximum time allowed to perform
function specified by `:after_connect` option (default: `15_000`)
* `:connection_listeners` - A list of process destinations to send
notification messages whenever a connection is connected or disconnected.
See "Connection listeners" below
* `:name` - A name to register the started process (see the `:name` option
in `GenServer.start_link/3`)
* `:pool` - Chooses the pool to be started
* `:pool_size` - Chooses the size of the pool
* `:idle_interval` - Controls the frequency we ping the database when the
connection is idle. Defaults to 1000ms.
* `:queue_target` and `:queue_interval` - See "Queue config" below
* `:max_restarts` and `:max_seconds` - Configures the `:max_restarts` and
`:max_seconds` for the connection pool supervisor (see the `Supervisor` docs)
* `:show_sensitive_data_on_connection_error` - By default, `DBConnection`
hides all information during connection errors to avoid leaking credentials
or other sensitive information. You can set this option if you wish to
see complete errors and stacktraces during connection errors
### Example
{:ok, conn} = DBConnection.start_link(mod, [idle_interval: 5_000])
## Queue config
Handling requests is done through a queue. When DBConnection is
started, there are two relevant options to control the queue:
* `:queue_target` in milliseconds, defaults to 50ms
* `:queue_interval` in milliseconds, defaults to 1000ms
Our goal is to wait at most `:queue_target` for a connection.
If all connections checked out during a `:queue_interval` takes
more than `:queue_target`, then we double the `:queue_target`.
If checking out connections take longer than the new target,
then we start dropping messages.
For example, by default our target is 50ms. If all connections
checkouts take longer than 50ms for a whole second, we double
the target to 100ms and we start dropping messages if the
time to checkout goes above the new limit.
This allows us to better plan for overloads as we can refuse
requests before they are sent to the database, which would
otherwise increase the burden on the database, making the
overload worse.
## Connection listeners
The `:connection_listeners` option allows one or more processes to be notified
whenever a connection is connected or disconnected. A listener may be a remote
or local PID, a locally registered name, or a tuple in the form of
`{registered_name, node}` for a registered name at another node.
Each listener process may receive the following messages where `pid`
identifies the connection process:
* `{:connected, pid}`
* `{:disconnected, pid}`
"""
@spec start_link(module, opts :: Keyword.t) :: GenServer.on_start
def start_link(conn_mod, opts) do
case child_spec(conn_mod, opts) do
{_, {m, f, args}, _, _, _, _} -> apply(m, f, args)
%{start: {m, f, args}} -> apply(m, f, args)
end
end
@doc """
Creates a supervisor child specification for a pool of connections.
See `start_link/2` for options.
"""
@spec child_spec(module, opts :: Keyword.t) :: :supervisor.child_spec()
def child_spec(conn_mod, opts) do
pool = Keyword.get(opts, :pool, DBConnection.ConnectionPool)
pool.child_spec({conn_mod, opts})
end
@doc """
Prepare a query with a database connection for later execution.
It returns `{:ok, query}` on success or `{:error, exception}` if there was
an error.
The returned `query` can then be passed to `execute/4` and/or `close/3`
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.LogEntry.t/0`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
The pool and connection module may support other options. All options
are passed to `c:handle_prepare/3`.
### Example
DBConnection.transaction(pool, fn conn ->
query = %Query{statement: "SELECT * FROM table"}
query = DBConnection.prepare!(conn, query)
try do
DBConnection.execute!(conn, query, [])
after
DBConnection.close(conn, query)
end
end)
"""
@spec prepare(conn, query, opts :: Keyword.t) ::
{:ok, query} | {:error, Exception.t}
def prepare(conn, query, opts \\ []) do
meter = meter(opts)
result =
with {:ok, query, meter} <- parse(query, meter, opts) do
run(conn, &run_prepare/4, query, meter, opts)
end
log(result, :prepare, query, nil)
end
@doc """
Prepare a query with a database connection and return the prepared
query. An exception is raised on error.
See `prepare/3`.
"""
@spec prepare!(conn, query, opts :: Keyword.t) :: query
def prepare!(conn, query, opts \\ []) do
case prepare(conn, query, opts) do
{:ok, result} -> result
{:error, err} -> raise err
end
end
@doc """
Prepare a query and execute it with a database connection and return both the
prepared query and the result, `{:ok, query, result}` on success or
`{:error, exception}` if there was an error.
The returned `query` can be passed to `execute/4` and `close/3`.
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.LogEntry.t/0`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
### Example
query = %Query{statement: "SELECT id FROM table WHERE id=$1"}
{:ok, query, result} = DBConnection.prepare_execute(conn, query, [1])
{:ok, result2} = DBConnection.execute(conn, query, [2])
:ok = DBConnection.close(conn, query)
"""
@spec prepare_execute(conn, query, params, Keyword.t) ::
{:ok, query, result} |
{:error, Exception.t}
def prepare_execute(conn, query, params, opts \\ []) do
result =
with {:ok, query, meter} <- parse(query, meter(opts), opts) do
parsed_prepare_execute(conn, query, params, meter, opts)
end
log(result, :prepare_execute, query, params)
end
defp parsed_prepare_execute(conn, query, params, meter, opts) do
with {:ok, query, result, meter} <- run(conn, &run_prepare_execute/5, query, params, meter, opts),
{:ok, result, meter} <- decode(query, result, meter, opts) do
{:ok, query, result, meter}
end
end
@doc """
Prepare a query and execute it with a database connection and return both the
prepared query and result. An exception is raised on error.
See `prepare_execute/4`.
"""
@spec prepare_execute!(conn, query, Keyword.t) :: {query, result}
def prepare_execute!(conn, query, params, opts \\ []) do
case prepare_execute(conn, query, params, opts) do
{:ok, query, result} -> {query, result}
{:error, err} -> raise err
end
end
@doc """
Execute a prepared query with a database connection and return
`{:ok, query, result}` on success or `{:error, exception}` if there was an error.
If the query is not prepared on the connection an attempt may be made to
prepare it and then execute again.
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.LogEntry.t/0`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
The pool and connection module may support other options. All options
are passed to `handle_execute/4`.
See `prepare/3`.
"""
@spec execute(conn, query, params, opts :: Keyword.t) ::
{:ok, query, result} | {:error, Exception.t}
def execute(conn, query, params, opts \\ []) do
result =
case maybe_encode(query, params, meter(opts), opts) do
{:prepare, meter} ->
parsed_prepare_execute(conn, query, params, meter, opts)
{:ok, params, meter} ->
with {:ok, query, result, meter} <- run(conn, &run_execute/5, query, params, meter, opts),
{:ok, result, meter} <- decode(query, result, meter, opts) do
{:ok, query, result, meter}
end
{_, _, _, _} = error ->
error
end
log(result, :execute, query, params)
end
@doc """
Execute a prepared query with a database connection and return the
result. Raises an exception on error.
See `execute/4`
"""
@spec execute!(conn, query, params, opts :: Keyword.t) :: result
def execute!(conn, query, params, opts \\ []) do
case execute(conn, query, params, opts) do
{:ok, _query, result} -> result
{:error, err} -> raise err
end
end
@doc """
Close a prepared query on a database connection and return `{:ok, result}` on
success or `{:error, exception}` on error.
This function should be used to free resources held by the connection
process and/or the database server.
## Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.LogEntry.t/0`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
The pool and connection module may support other options. All options
are passed to `c:handle_close/3`.
See `prepare/3`.
"""
@spec close(conn, query, opts :: Keyword.t) ::
{:ok, result} | {:error, Exception.t}
def close(conn, query, opts \\ []) do
conn
|> run_cleanup(&run_close/4, [query], meter(opts), opts)
|> log(:close, query, nil)
end
@doc """
Close a prepared query on a database connection and return the result. Raises
an exception on error.
See `close/3`.
"""
@spec close!(conn, query, opts :: Keyword.t) :: result
def close!(conn, query, opts \\ []) do
case close(conn, query, opts) do
{:ok, result} -> result
{:error, err} -> raise err
end
end
@doc """
Acquire a lock on a connection and run a series of requests on it.
The return value of this function is the return value of `fun`.
To use the locked connection call the request with the connection
reference passed as the single argument to the `fun`. If the
connection disconnects all future calls using that connection
reference will fail.
`run/3` and `transaction/3` can be nested multiple times but a
`transaction/3` call inside another `transaction/3` will be treated
the same as `run/3`.
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
The pool may support other options.
### Example
{:ok, res} = DBConnection.run(conn, fn conn ->
DBConnection.execute!(conn, query, [])
end)
"""
@spec run(conn, (t -> result), opts :: Keyword.t) :: result when result: var
def run(conn, fun, opts \\ [])
def run(%DBConnection{} = conn, fun, _) do
fun.(conn)
end
def run(pool, fun, opts) do
case checkout(pool, nil, opts) do
{:ok, conn, _} ->
old_status = status(conn, opts)
try do
result = fun.(conn)
{result, run(conn, &run_status/3, nil, opts)}
catch
kind, error ->
checkin(conn)
:erlang.raise(kind, error, __STACKTRACE__)
else
{result, {:error, _, _}} ->
checkin(conn)
result
{result, {^old_status, _meter}} ->
checkin(conn)
result
{_result, {new_status, _meter}} ->
err = DBConnection.ConnectionError.exception(
"connection was checked out with status #{inspect(old_status)} " <>
"but it was checked in with status #{inspect(new_status)}"
)
disconnect(conn, err)
raise err
{_result, {kind, reason, stack, _meter}} ->
:erlang.raise(kind, reason, stack)
end
{:error, err, _} ->
raise err
{kind, reason, stack, _} ->
:erlang.raise(kind, reason, stack)
end
end
@doc """
Acquire a lock on a connection and run a series of requests inside a
transaction. The result of the transaction fun is return inside an `:ok`
tuple: `{:ok, result}`.
To use the locked connection call the request with the connection
reference passed as the single argument to the `fun`. If the
connection disconnects all future calls using that connection
reference will fail.
`run/3` and `transaction/3` can be nested multiple times. If a transaction is
rolled back or a nested transaction `fun` raises the transaction is marked as
failed. All calls except `run/3`, `transaction/3`, `rollback/2`, `close/3` and
`close!/3` will raise an exception inside a failed transaction until the outer
transaction call returns. All `transaction/3` calls will return
`{:error, :rollback}` if the transaction failed or connection closed and
`rollback/2` is not called for that `transaction/3`.
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about begin, commit and rollback
calls made as part of the transaction, either a 1-arity fun,
`{module, function, args}` with `t:DBConnection.LogEntry.t/0` prepended to
`args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
The pool and connection module may support other options. All options
are passed to `c:handle_begin/2`, `c:handle_commit/2` and
`c:handle_rollback/2`.
### Example
{:ok, res} = DBConnection.transaction(conn, fn conn ->
DBConnection.execute!(conn, query, [])
end)
"""
@spec transaction(conn, (t -> result), opts :: Keyword.t) ::
{:ok, result} | {:error, reason :: any} when result: var
def transaction(conn, fun, opts \\ [])
def transaction(%DBConnection{conn_mode: :transaction} = conn, fun, _opts) do
%DBConnection{conn_ref: conn_ref} = conn
try do
result = fun.(conn)
conclude(conn, result)
catch
:throw, {__MODULE__, ^conn_ref, reason} ->
fail(conn)
{:error, reason}
kind, reason ->
stack = __STACKTRACE__
fail(conn)
:erlang.raise(kind, reason, stack)
else
result ->
{:ok, result}
end
end
def transaction(%DBConnection{} = conn, fun, opts) do
case begin(conn, &run/4, opts) do
{:ok, _} ->
run_transaction(conn, fun, &run/4, opts)
{:error, %DBConnection.TransactionError{}} ->
{:error, :rollback}
{:error, err} ->
raise err
end
end
def transaction(pool, fun, opts) do
case begin(pool, &checkout/4, opts) do
{:ok, conn, _} ->
run_transaction(conn, fun, &checkin/4, opts)
{:error, %DBConnection.TransactionError{}} ->
{:error, :rollback}
{:error, err} ->
raise err
end
end
@doc """
Rollback a database transaction and release lock on connection.
When inside of a `transaction/3` call does a non-local return, using a
`throw/1` to cause the transaction to enter a failed state and the
`transaction/3` call returns `{:error, reason}`. If `transaction/3` calls are
nested the connection is marked as failed until the outermost transaction call
does the database rollback.
### Example
{:error, :oops} = DBConnection.transaction(pool, fun(conn) ->
DBConnection.rollback(conn, :oops)
end)
"""
@spec rollback(t, reason :: any) :: no_return
def rollback(conn, reason)
def rollback(%DBConnection{conn_mode: :transaction} = conn, reason) do
%DBConnection{conn_ref: conn_ref} = conn
throw({__MODULE__, conn_ref, reason})
end
def rollback(%DBConnection{} = _conn, _reason) do
raise "not inside transaction"
end
@doc """
Return the transaction status of a connection.
The callback implementation should return the transaction status according to
the database, and not make assumptions based on client-side state.
This function will raise a `DBConnection.ConnectionError` when called inside a
deprecated `transaction/3`.
### Options
See module documentation. The pool and connection module may support other
options. All options are passed to `c:handle_status/2`.
### Example
# outside of the transaction, the status is `:idle`
DBConnection.status(conn) #=> :idle
DBConnection.transaction(conn, fn conn ->
DBConnection.status(conn) #=> :transaction
# run a query that will cause the transaction to rollback, e.g.
# uniqueness constraint violation
DBConnection.execute(conn, bad_query, [])
DBConnection.status(conn) #=> :error
end)
DBConnection.status(conn) #=> :idle
"""
@spec status(conn, opts :: Keyword.t) :: status
def status(conn, opts \\ []) do
case run(conn, &run_status/3, nil, opts) do
{status, _meter} ->
status
{:error, _err, _meter} ->
:error
{kind, reason, stack, _meter} ->
:erlang.raise(kind, reason, stack)
end
end
@doc """
Create a stream that will prepare a query, execute it and stream results
using a cursor.
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.LogEntry.t/0`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
The pool and connection module may support other options. All options
are passed to `c:handle_prepare/3`, `c:handle_close/3`, `c:handle_declare/4`,
and `c:handle_deallocate/4`.
### Example
{:ok, results} = DBConnection.transaction(conn, fn conn ->
query = %Query{statement: "SELECT id FROM table"}
stream = DBConnection.prepare_stream(conn, query, [])
Enum.to_list(stream)
end)
"""
@spec prepare_stream(t, query, params, opts :: Keyword.t) ::
DBConnection.PrepareStream.t
def prepare_stream(%DBConnection{} = conn, query, params, opts \\ []) do
%DBConnection.PrepareStream{conn: conn, query: query, params: params,
opts: opts}
end
@doc """
Create a stream that will execute a prepared query and stream results using a
cursor.
### Options
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`). See "Queue config" in
`start_link/2` docs
* `:timeout` - The maximum time that the caller is allowed to perform
this operation (default: `15_000`)
* `:deadline` - If set, overrides `:timeout` option and specifies absolute
monotonic time in milliseconds by which caller must perform operation.
See `System` module documentation for more information on monotonic time
(default: `nil`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `t:DBConnection.LogEntry.t/0`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
The pool and connection module may support other options. All options
are passed to `c:handle_declare/4` and `c:handle_deallocate/4`.
### Example
DBConnection.transaction(pool, fn conn ->
query = %Query{statement: "SELECT id FROM table"}
query = DBConnection.prepare!(conn, query)
try do
stream = DBConnection.stream(conn, query, [])
Enum.to_list(stream)
after
# Make sure query is closed!
DBConnection.close(conn, query)
end
end)
"""
@spec stream(t, query, params, opts :: Keyword.t) :: DBConnection.Stream.t
def stream(%DBConnection{} = conn, query, params, opts \\ []) do
%DBConnection.Stream{conn: conn, query: query, params: params, opts: opts}
end
@doc """
Reduces a previously built stream or prepared stream.
"""
def reduce(%DBConnection.PrepareStream{} = stream, acc, fun) do
%DBConnection.PrepareStream{conn: conn, query: query, params: params,
opts: opts} = stream
declare =
fn(conn, opts) ->
{query, cursor} = prepare_declare!(conn, query, params, opts)
{:cont, query, cursor}
end
enum = resource(conn, declare, &stream_fetch/3, &stream_deallocate/3, opts)
enum.(acc, fun)
end
def reduce(%DBConnection.Stream{} = stream, acc, fun) do
%DBConnection.Stream{conn: conn, query: query, params: params,
opts: opts} = stream
declare =
fn(conn, opts) ->
case declare(conn, query, params, opts) do
{:ok, query, cursor} ->
{:cont, query, cursor}
{:ok, cursor} ->
{:cont, query, cursor}
{:error, err} ->
raise err
end
end
enum = resource(conn, declare, &stream_fetch/3, &stream_deallocate/3, opts)
enum.(acc, fun)
end
## Helpers
defp checkout(pool, meter, opts) do
checkout = System.monotonic_time()
# The holder is only used internally by DBConnection.Task
holder = Keyword.get(opts, :holder, DBConnection.Holder)
try do
holder.checkout(pool, opts)
catch
kind, reason ->
stack = __STACKTRACE__
{kind, reason, stack, past_event(meter, :checkout, checkout)}
else
{:ok, pool_ref, _conn_mod, checkin, _conn_state} ->
conn = %DBConnection{pool_ref: pool_ref, conn_ref: make_ref()}
meter = meter |> past_event(:checkin, checkin) |> past_event(:checkout, checkout)
{:ok, conn, meter}
{:error, err} ->
{:error, err, past_event(meter, :checkout, checkout)}
end
end
defp checkout(%DBConnection{} = conn, fun, meter, opts) do
with {:ok, result, meter} <- fun.(conn, meter, opts) do
{:ok, conn, result, meter}
end
end
defp checkout(pool, fun, meter, opts) do
with {:ok, conn, meter} <- checkout(pool, meter, opts) do
case fun.(conn, meter, opts) do
{:ok, result, meter} ->
{:ok, conn, result, meter}
error ->
checkin(conn)
error
end
end
end
defp checkin(%DBConnection{pool_ref: pool_ref}) do
Holder.checkin(pool_ref)
end
defp checkin(%DBConnection{} = conn, fun, meter, opts) do
return = fun.(conn, meter, opts)
checkin(conn)
return
end
defp checkin(pool, fun, meter, opts) do
run(pool, fun, meter, opts)
end
defp disconnect(%DBConnection{pool_ref: pool_ref}, err) do
_ = Holder.disconnect(pool_ref, err)
:ok
end
defp stop(%DBConnection{pool_ref: pool_ref}, kind, reason, stack) do
msg = "client #{inspect self()} stopped: " <> Exception.format(kind, reason, stack)
exception = DBConnection.ConnectionError.exception(msg)
_ = Holder.stop(pool_ref, exception)
:ok
end
defp handle_common_result(return, conn, meter) do
case return do
{:ok, result, _conn_state} ->
{:ok, result, meter}
{:error, err, _conn_state} ->
{:error, err, meter}
{:disconnect, err, _conn_state} ->
disconnect(conn, err)
{:error, err, meter}
{:catch, kind, reason, stack} ->
stop(conn, kind, reason, stack)
{kind, reason, stack, meter}
other ->
bad_return!(other, conn, meter)
end
end
@compile {:inline, bad_return!: 3}
defp bad_return!(other, conn, meter) do
try do
raise DBConnection.ConnectionError, "bad return value: #{inspect other}"
catch
:error, reason ->
stack = __STACKTRACE__
stop(conn, :error, reason, stack)
{:error, reason, stack, meter}
end
end
defp parse(query, meter, opts) do
try do
DBConnection.Query.parse(query, opts)
catch
kind, reason ->
stack = __STACKTRACE__
{kind, reason, stack, meter}
else
query ->
{:ok, query, meter}
end
end
defp describe(conn, query, meter, opts) do
try do
DBConnection.Query.describe(query, opts)
catch
kind, reason ->
stack = __STACKTRACE__
raised_close(conn, query, meter, opts, kind, reason, stack)
else
query ->
{:ok, query, meter}
end
end
defp encode(conn, query, params, meter, opts) do
try do
DBConnection.Query.encode(query, params, opts)
catch
kind, reason ->
stack = __STACKTRACE__
raised_close(conn, query, meter, opts, kind, reason, stack)
else
params ->
{:ok, params, meter}
end
end
defp maybe_encode(query, params, meter, opts) do
try do
DBConnection.Query.encode(query, params, opts)
rescue
DBConnection.EncodeError -> {:prepare, meter}
catch
kind, reason ->
stack = __STACKTRACE__
{kind, reason, stack, meter}
else
params ->
{:ok, params, meter}
end
end
defp decode(query, result, meter, opts) do
meter = event(meter, :decode)
try do
DBConnection.Query.decode(query, result, opts)
catch
kind, reason ->
stack = __STACKTRACE__
{kind, reason, stack, meter}
else
result ->
{:ok, result, meter}
end
end
defp prepare_declare(conn, query, params, opts) do
result =
with {:ok, query, meter} <- parse(query, meter(opts), opts) do
parsed_prepare_declare(conn, query, params, meter, opts)
end
log(result, :prepare_declare, query, params)
end
defp parsed_prepare_declare(conn, query, params, meter, opts) do
run(conn, &run_prepare_declare/5, query, params, meter, opts)
end
defp prepare_declare!(conn, query, params, opts) do
case prepare_declare(conn, query, params, opts) do
{:ok, query, cursor} ->
{query, cursor}
{:error, err} ->
raise err
end
end
defp declare(conn, query, params, opts) do
result =
case maybe_encode(query, params, meter(opts), opts) do
{:prepare, meter} ->
parsed_prepare_declare(conn, query, params, meter, opts)
{:ok, params, meter} ->
run(conn, &run_declare/5, query, params, meter, opts)
{_, _, _, _} = error ->
error
end
log(result, :declare, query, params)
end
defp deallocate(conn, query, cursor, opts) do
conn
|> run_cleanup(&run_deallocate/4, [query, cursor], meter(opts), opts)
|> log(:deallocate, query, cursor)
end
defp run_prepare(conn, query, meter, opts) do
with {:ok, query, meter} <- prepare(conn, query, meter, opts) do
describe(conn, query, meter, opts)
end
end
defp prepare(%DBConnection{pool_ref: pool_ref} = conn, query, meter, opts) do
pool_ref
|> Holder.handle(:handle_prepare, [query], opts)
|> handle_common_result(conn, event(meter, :prepare))
end
defp run_prepare_execute(conn, query, params, meter, opts) do
with {:ok, query, meter} <- run_prepare(conn, query, meter, opts),
{:ok, params, meter} <- encode(conn, query, params, meter, opts) do
run_execute(conn, query, params, meter, opts)
end
end
defp run_execute(conn, query, params, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
meter = event(meter, :execute)
case Holder.handle(pool_ref, :handle_execute, [query, params], opts) do
{:ok, query, result, _conn_state} ->
{:ok, query, result, meter}
{:ok, _, _} = other ->
bad_return!(other, conn, meter)
other ->
handle_common_result(other, conn, meter)
end
end
defp raised_close(conn, query, meter, opts, kind, reason, stack) do
with {:ok, _, meter} <- run_close(conn, [query], meter, opts) do
{kind, reason, stack, meter}
end
end
defp run_close(conn, args, meter, opts) do
meter = event(meter, :close)
cleanup(conn, :handle_close, args, meter, opts)
end
defp run_cleanup(%DBConnection{} = conn, fun, args, meter, opts) do
fun.(conn, args, meter, opts)
end
defp run_cleanup(pool, fun, args, meter, opts) do
with {:ok, conn, meter} <- checkout(pool, meter, opts) do
try do
fun.(conn, args, meter, opts)
after
checkin(conn)
end
end
end
defp cleanup(conn, fun, args, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
case Holder.cleanup(pool_ref, fun, args, opts) do
{:ok, result, _conn_state} ->
{:ok, result, meter}
{:error, err, _conn_state} ->
{:error, err, meter}
{:disconnect, err, _conn_state} ->
disconnect(conn, err)
{:error, err, meter}
{:catch, kind, reason, stack} ->
stop(conn, kind, reason, stack)
{kind, reason, stack, meter}
other ->
bad_return!(other, conn, meter)
end
end
defp run(%DBConnection{} = conn, fun, meter, opts) do
fun.(conn, meter, opts)
end
defp run(pool, fun, meter, opts) do
with {:ok, conn, meter} <- checkout(pool, meter, opts) do
try do
fun.(conn, meter, opts)
after
checkin(conn)
end
end
end
defp run(%DBConnection{} = conn, fun, arg, meter, opts) do
fun.(conn, arg, meter, opts)
end
defp run(pool, fun, arg, meter, opts) do
with {:ok, conn, meter} <- checkout(pool, meter, opts) do
try do
fun.(conn, arg, meter, opts)
after
checkin(conn)
end
end
end
defp run(%DBConnection{} = conn, fun, arg1, arg2, meter, opts) do
fun.(conn, arg1, arg2, meter, opts)
end
defp run(pool, fun, arg1, arg2, meter, opts) do
with {:ok, conn, meter} <- checkout(pool, meter, opts) do
try do
fun.(conn, arg1, arg2, meter, opts)
after
checkin(conn)
end
end
end
defp meter(opts) do
case Keyword.get(opts, :log) do
nil -> nil
log -> {log, []}
end
end
defp event(nil, _),
do: nil
defp event({log, events}, event),
do: {log, [{event, System.monotonic_time()} | events]}
defp past_event(nil, _, _),
do: nil
defp past_event(log_events, _, nil),
do: log_events
defp past_event({log, events}, event, time),
do: {log, [{event, time} | events]}
defp log({:ok, res, meter}, call, query, params),
do: log(meter, call, query, params, {:ok, res})
defp log({:ok, res1, res2, meter}, call, query, params),
do: log(meter, call, query, params, {:ok, res1, res2})
defp log({ok, res, meter}, call, query, cursor) when ok in [:cont, :halt],
do: log(meter, call, query, cursor, {ok, res})
defp log({:error, err, meter}, call, query, params),
do: log(meter, call, query, params, {:error, err})
defp log({kind, reason, stack, meter}, call, query, params),
do: log(meter, call, query, params, {kind, reason, stack})
defp log(nil, _, _, _, result),
do: log_result(result)
defp log({log, times}, call, query, params, result) do
entry = DBConnection.LogEntry.new(call, query, params, times, entry_result(result))
try do
log(log, entry)
catch
kind, reason ->
stack = __STACKTRACE__
log_raised(entry, kind, reason, stack)
end
log_result(result)
end
defp entry_result({kind, reason, stack})
when kind in [:error, :exit, :throw] do
msg = "an exception was raised: " <> Exception.format(kind, reason, stack)
{:error, %DBConnection.ConnectionError{message: msg}}
end
defp entry_result({ok, res}) when ok in [:cont, :halt],
do: {:ok, res}
defp entry_result(other), do: other
defp log({mod, fun, args}, entry), do: apply(mod, fun, [entry | args])
defp log(fun, entry), do: fun.(entry)
defp log_result({kind, reason, stack}) when kind in [:error, :exit, :throw] do
:erlang.raise(kind, reason, stack)
end
defp log_result(other), do: other
defp log_raised(entry, kind, reason, stack) do
reason = Exception.normalize(kind, reason, stack)
Logger.error(fn() ->
"an exception was raised logging #{inspect entry}: " <> Exception.format(kind, reason, stack)
end, crash_reason: {crash_reason(kind, reason), stack})
catch
_, _ ->
:ok
end
defp crash_reason(:throw, value), do: {:nocatch, value}
defp crash_reason(_, value), do: value
defp run_transaction(conn, fun, run, opts) do
%DBConnection{conn_ref: conn_ref} = conn
try do
result = fun.(%{conn | conn_mode: :transaction})
conclude(conn, result)
catch
:throw, {__MODULE__, ^conn_ref, reason} ->
reset(conn)
case rollback(conn, run, opts) do
{:ok, _} ->
{:error, reason}
{:error, %DBConnection.TransactionError{}} ->
{:error, reason}
{:error, %DBConnection.ConnectionError{}} ->
{:error, reason}
{:error, err} ->
raise err
end
kind, reason ->
stack = __STACKTRACE__
reset(conn)
_ = rollback(conn, run, opts)
:erlang.raise(kind, reason, stack)
else
result ->
case commit(conn, run, opts) do
{:ok, _} ->
{:ok, result}
{:error, %DBConnection.TransactionError{}} ->
{:error, :rollback}
{:error, err} ->
raise err
end
after
reset(conn)
end
end
defp fail(%DBConnection{pool_ref: pool_ref}) do
case Holder.status?(pool_ref, :ok) do
true -> Holder.put_status(pool_ref, :aborted)
false -> :ok
end
end
defp conclude(%DBConnection{pool_ref: pool_ref, conn_ref: conn_ref}, result) do
case Holder.status?(pool_ref, :ok) do
true -> result
false -> throw({__MODULE__, conn_ref, :rollback})
end
end
defp reset(%DBConnection{pool_ref: pool_ref}) do
case Holder.status?(pool_ref, :aborted) do
true -> Holder.put_status(pool_ref, :ok)
false -> :ok
end
end
defp begin(conn, run, opts) do
conn
|> run.(&run_begin/3, meter(opts), opts)
|> log(:begin, :begin, nil)
end
defp run_begin(conn, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
meter = event(meter, :begin)
case Holder.handle(pool_ref, :handle_begin, [], opts) do
{status, _conn_state} when status in [:idle, :transaction, :error] ->
status_disconnect(conn, status, meter)
other ->
handle_common_result(other, conn, meter)
end
end
defp rollback(conn, run, opts) do
conn
|> run.(&run_rollback/3, meter(opts), opts)
|> log(:rollback, :rollback, nil)
end
defp run_rollback(conn, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
meter = event(meter, :rollback)
case Holder.handle(pool_ref, :handle_rollback, [], opts) do
{status, _conn_state} when status in [:idle, :transaction, :error] ->
status_disconnect(conn, status, meter)
other ->
handle_common_result(other, conn, meter)
end
end
defp commit(conn, run, opts) do
case run.(conn, &run_commit/3, meter(opts), opts) do
{:rollback, {:ok, result, meter}} ->
log(meter, :commit, :rollback, nil, {:ok, result})
err = DBConnection.TransactionError.exception(:error)
{:error, err}
{query, other} ->
log(other, :commit, query, nil)
{:error, err, meter} ->
log(meter, :commit, :commit, nil, {:error, err})
{kind, reason, stack, meter} ->
log(meter, :commit, :commit, nil, {kind, reason, stack})
end
end
defp run_commit(conn, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
meter = event(meter, :commit)
case Holder.handle(pool_ref, :handle_commit, [], opts) do
{:error, _conn_state} ->
{:rollback, run_rollback(conn, meter, opts)}
{status, _conn_state} when status in [:idle, :transaction] ->
{:commit, status_disconnect(conn, status, meter)}
other ->
{:commit, handle_common_result(other, conn, meter)}
end
end
defp status_disconnect(conn, status, meter) do
err = DBConnection.TransactionError.exception(status)
disconnect(conn, err)
{:error, err, meter}
end
defp run_status(conn, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
case Holder.handle(pool_ref, :handle_status, [], opts) do
{status, _conn_state} when status in [:idle, :transaction, :error] ->
{status, meter}
{:disconnect, err, _conn_state} ->
disconnect(conn, err)
{:error, err, meter}
{:catch, kind, reason, stack} ->
stop(conn, kind, reason, stack)
{kind, reason, stack, meter}
other ->
bad_return!(other, conn, meter)
end
end
defp run_prepare_declare(conn, query, params, meter, opts) do
with {:ok, query, meter} <- prepare(conn, query, meter, opts),
{:ok, query, meter} <- describe(conn, query, meter, opts),
{:ok, params, meter} <- encode(conn, query, params, meter, opts),
{:ok, query, cursor, meter} <- run_declare(conn, query, params, meter, opts) do
{:ok, query, cursor, meter}
end
end
defp run_declare(conn, query, params, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
meter = event(meter, :declare)
case Holder.handle(pool_ref, :handle_declare, [query, params], opts) do
{:ok, query, result, _conn_state} ->
{:ok, query, result, meter}
{:ok, _, _} = other ->
bad_return!(other, conn, meter)
other ->
handle_common_result(other, conn, meter)
end
end
defp stream_fetch(conn, {:cont, query, cursor}, opts) do
conn
|> run(&run_stream_fetch/4, [query, cursor], meter(opts), opts)
|> log(:fetch, query, cursor)
|> case do
{ok, result} when ok in [:cont, :halt] ->
{[result], {ok, query, cursor}}
{:error, err} ->
raise err
end
end
defp stream_fetch(_, {:halt, _, _} = state, _) do
{:halt, state}
end
defp run_stream_fetch(conn, args, meter, opts) do
[query, _] = args
with {ok, result, meter} when ok in [:cont, :halt] <- run_fetch(conn, args, meter, opts),
{:ok, result, meter} <- decode(query, result, meter, opts) do
{ok, result, meter}
end
end
defp run_fetch(conn, args, meter, opts) do
%DBConnection{pool_ref: pool_ref} = conn
meter = event(meter, :fetch)
case Holder.handle(pool_ref, :handle_fetch, args, opts) do
{:cont, result, _conn_state} ->
{:cont, result, meter}
{:halt, result, _conn_state} ->
{:halt, result, meter}
other ->
handle_common_result(other, conn, meter)
end
end
defp stream_deallocate(conn, {_status, query, cursor}, opts),
do: deallocate(conn, query, cursor, opts)
defp run_deallocate(conn, args, meter, opts) do
meter = event(meter, :deallocate)
cleanup(conn, :handle_deallocate, args, meter, opts)
end
defp resource(%DBConnection{} = conn, start, next, stop, opts) do
start = fn -> start.(conn, opts) end
next = fn state -> next.(conn, state, opts) end
stop = fn state -> stop.(conn, state, opts) end
Stream.resource(start, next, stop)
end
end
| 34.072325 | 102 | 0.647422 |
03c3dcb9017eef06027baf3471071a6a70670b20 | 2,614 | exs | Elixir | test/debug_test.exs | aruki-delivery/quaff | 3538bec660642398537488377d57f5212b44414a | [
"Apache-2.0"
] | null | null | null | test/debug_test.exs | aruki-delivery/quaff | 3538bec660642398537488377d57f5212b44414a | [
"Apache-2.0"
] | null | null | null | test/debug_test.exs | aruki-delivery/quaff | 3538bec660642398537488377d57f5212b44414a | [
"Apache-2.0"
] | 1 | 2019-12-03T15:46:32.000Z | 2019-12-03T15:46:32.000Z | defmodule Quaff.Debug.Test do
use ExUnit.Case
require Quaff.Debug
require Quaff
alias Quaff.Debug, as: Dbg
setup context do
if context[:debugger] do
:meck.new(:debugger)
:meck.expect(:debugger, :start, fn -> {:ok, self()} end)
end
if context[:int] do
:meck.new(:int)
:meck.expect(:int, :i, fn _ -> :ok end)
:meck.expect(:int, :ni, fn _ -> :ok end)
end
on_exit(context, fn ->
:meck.unload()
end)
:ok
end
@tag :debugger
test "debug start" do
Dbg.start()
assert :meck.called(:debugger, :start, [])
assert :meck.validate(:debugger)
end
@tag :int
test "interpret file" do
Dbg.load("test/dummy.ex")
assert dummy_was_loaded(:i)
assert :meck.validate(:int)
end
@tag :int
test "interpret file ni" do
Dbg.nload("test/dummy.ex")
assert dummy_was_loaded(:ni)
assert :meck.validate(:int)
end
@tag :int
test "interpret module" do
Dbg.load(Quaff.Constants)
ex_pat = Regex.compile!("constants\.ex$")
beam_pat = Regex.compile!("Elixir\.Quaff\.Constants\.beam$")
assert called_pattern(:int, :i, fn
[{Quaff.Constants, src, beam, bb}]
when is_binary(bb) ->
Regex.match?(ex_pat, List.to_string(src)) and
Regex.match?(beam_pat, List.to_string(beam))
_ ->
false
end)
assert :meck.validate(:int)
end
def dummy_was_loaded(f) do
called_pattern(:int, f, fn
[{Dummy1, 'test/dummy.ex', 'Elixir.Dummy1.beam', bb}]
when is_binary(bb) ->
true
_ ->
false
end)
called_pattern(:int, f, fn
[{Dummy2, 'test/dummy.ex', 'Elixir.Dummy2.beam', bb}]
when is_binary(bb) ->
true
_ ->
false
end)
true
end
def called_pattern(mod, f, scanner) do
hist = :meck.history(mod)
case Enum.reduce(hist, {[], false}, fn
_, {_, true} ->
{nil, true}
{_pid, {mod1, f1, args}, _res}, {checked, false} when mod1 == mod and f1 == f ->
case scanner.(args) do
true -> {nil, true}
_ -> {[args | checked], false}
end
_, acc ->
acc
end) do
{nil, true} ->
true
{calls, false} ->
prn_calls =
Enum.map(calls, fn
[{a, b, c, x}] when byte_size(x) > 20 ->
[{a, b, c, :"[binary]"}]
x ->
x
end)
:io.format("No matching call:~n~p~n", [prn_calls])
false
end
end
end
| 21.252033 | 91 | 0.519128 |
03c3e125c8c4e6c1520b9176c81f9422df0deaf2 | 2,222 | ex | Elixir | lib/freegiving/fundraisers/gift_card.ex | jfcloutier/freegiving | 2ab3821595996fc295c5b55515d6f60cbce05181 | [
"Unlicense"
] | null | null | null | lib/freegiving/fundraisers/gift_card.ex | jfcloutier/freegiving | 2ab3821595996fc295c5b55515d6f60cbce05181 | [
"Unlicense"
] | null | null | null | lib/freegiving/fundraisers/gift_card.ex | jfcloutier/freegiving | 2ab3821595996fc295c5b55515d6f60cbce05181 | [
"Unlicense"
] | null | null | null | defmodule Freegiving.Fundraisers.GiftCard do
use Ecto.Schema
import Ecto.Query
import Ecto.Changeset, warn: false
alias Freegiving.Fundraisers.{Fundraiser, Participant, CardRefill}
alias Freegiving.Repo
alias __MODULE__
# A gift card always belongs to a fundraiser and my also belong to a participant in that fundraiser
# A gift card that does not bleong to a particpant is in the "gift cards reserve" of the fundraiser
# Gift cards are allocated to participants of a fundraiser from its card reserve
schema "gift_cards" do
field :card_number, :string
field :active, :boolean, default: false
field :name, :string, default: "My card"
belongs_to :participant, Participant
belongs_to :fundraiser, Fundraiser
has_many :card_refills, CardRefill
timestamps()
end
def changeset(gift_card, attrs) do
gift_card
|> cast(attrs, [:card_number, :active, :name])
|> validate_required([:card_number])
|> unique_constraint(:card_number)
|> validate_assigned_participant()
|> validate_name_unique_to_participant()
end
defp validate_assigned_participant(changeset) do
validate_change(changeset, :participant_id, fn _field, participant_id ->
if participant_id != nil do
participant = Repo.get_by(Participant, :participant_id)
fundraiser_id = Ecto.Changeset.get_field(changeset, :fundraiser_id)
if participant.fundraiser_id != fundraiser_id do
[
{:participant_id,
"must reference a participant in the gift card's fundraiser (#{fundraiser_id})"}
]
else
[]
end
else
[]
end
end)
end
defp validate_name_unique_to_participant(changeset) do
validate_change(changeset, :name, fn _field, name ->
participant_id = Ecto.Changeset.get_field(changeset, :participant_id)
if participant_id != nil do
count =
from(GiftCard, where: [participant_id: ^participant_id, name: ^name])
|> Repo.all()
|> Enum.count()
if count > 0 do
[{:name, "the name \"#{name}\" is already taken"}]
else
[]
end
else
[]
end
end)
end
end
| 30.861111 | 101 | 0.663366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.