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
0850e517ef0fe4e073d5d2b78f5d5410b3de6e17
24,711
exs
Elixir
lib/ex_unit/test/ex_unit/assertions_test.exs
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
19,291
2015-01-01T02:42:49.000Z
2022-03-31T21:01:40.000Z
lib/ex_unit/test/ex_unit/assertions_test.exs
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
8,082
2015-01-01T04:16:23.000Z
2022-03-31T22:08:02.000Z
lib/ex_unit/test/ex_unit/assertions_test.exs
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
3,472
2015-01-03T04:11:56.000Z
2022-03-29T02:07:30.000Z
Code.require_file("../test_helper.exs", __DIR__) defmodule ExUnit.AssertionsTest.Value do def tuple, do: {2, 1} def falsy, do: nil def truthy, do: :truthy def binary, do: <<5, "Frank the Walrus">> end defmodule ExUnit.AssertionsTest.BrokenError do defexception [:message] @impl true def message(_) do raise "error" end end alias ExUnit.AssertionsTest.{BrokenError, Value} defmodule ExUnit.AssertionsTest do use ExUnit.Case, async: true defmacro sigil_l({:<<>>, _, [string]}, _), do: Code.string_to_quoted!(string, []) defmacro argless_macro(), do: raise("should not be invoked") defmacrop assert_ok(arg) do quote do assert {:ok, val} = ok(unquote(arg)) end end defmacrop assert_ok_with_pin_from_quoted_var(arg) do quote do kind = :ok assert {^kind, value} = unquote(arg) end end require Record Record.defrecordp(:vec, x: 0, y: 0, z: 0) defguardp is_zero(zero) when zero == 0 test "assert inside macro" do assert_ok(42) end test "assert inside macro with pins" do try do assert_ok_with_pin_from_quoted_var({:error, :oops}) rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message end end test "assert with truthy value" do :truthy = assert Value.truthy() end test "assert with message when value is falsy" do try do "This should never be tested" = assert Value.falsy(), "This should be truthy" rescue error in [ExUnit.AssertionError] -> "This should be truthy" = error.message end end test "assert when value evaluates to falsy" do try do "This should never be tested" = assert Value.falsy() rescue error in [ExUnit.AssertionError] -> "assert Value.falsy()" = error.expr |> Macro.to_string() "Expected truthy, got nil" = error.message end end test "assert arguments in special form" do true = assert (case :ok do :ok -> true end) end test "assert arguments semantics on function call" do x = 1 true = assert not_equal(x = 2, x) 2 = x end test "assert arguments are not kept for operators" do try do "This should never be tested" = assert !Value.truthy() rescue error in [ExUnit.AssertionError] -> false = is_list(error.args) end end test "assert with equality" do try do "This should never be tested" = assert 1 + 1 == 1 rescue error in [ExUnit.AssertionError] -> 1 = error.right 2 = error.left "assert 1 + 1 == 1" = error.expr |> Macro.to_string() end end test "assert with equality in reverse" do try do "This should never be tested" = assert 1 == 1 + 1 rescue error in [ExUnit.AssertionError] -> 1 = error.left 2 = error.right "assert 1 == 1 + 1" = error.expr |> Macro.to_string() end end test "assert exposes nested macro variables in matches" do assert ~l(a) = 1 assert a == 1 assert {~l(b), ~l(c)} = {2, 3} assert b == 2 assert c == 3 end test "assert does not expand variables" do assert argless_macro = 1 assert argless_macro == 1 end test "refute when value is falsy" do false = refute false nil = refute Value.falsy() end test "refute when value evaluates to truthy" do try do refute Value.truthy() raise "refute was supposed to fail" rescue error in [ExUnit.AssertionError] -> "refute Value.truthy()" = Macro.to_string(error.expr) "Expected false or nil, got :truthy" = error.message end end test "assert match when equal" do {2, 1} = assert {2, 1} = Value.tuple() # With dup vars assert {tuple, tuple} = {Value.tuple(), Value.tuple()} assert <<name_size::size(8), _::binary-size(name_size), " the ", _::binary>> = Value.binary() end test "assert match with unused var" do assert ExUnit.CaptureIO.capture_io(:stderr, fn -> Code.eval_string(""" defmodule ExSample do import ExUnit.Assertions def run do {2, 1} = assert {2, var} = ExUnit.AssertionsTest.Value.tuple() end end """) end) =~ "variable \"var\" is unused" after :code.delete(ExSample) :code.purge(ExSample) end test "assert match expands argument in match context" do {x, y, z} = {1, 2, 3} assert vec(x: ^x, y: ^y) = vec(x: x, y: y, z: z) end @test_mod_attribute %{key: :value} test "assert match with module attribute" do try do assert {@test_mod_attribute, 1} = Value.tuple() rescue error in [ExUnit.AssertionError] -> assert "{%{key: :value}, 1}" == Macro.to_string(error.left) end end test "assert match with pinned variable" do a = 1 {2, 1} = assert {2, ^a} = Value.tuple() try do assert {^a, 1} = Value.tuple() rescue error in [ExUnit.AssertionError] -> "match (=) failed\n" <> "The following variables were pinned:\n" <> " a = 1" = error.message "assert {^a, 1} = Value.tuple()" = Macro.to_string(error.expr) end end test "assert match with pinned variable from another context" do var!(a, Elixir) = 1 {2, 1} = assert {2, ^var!(a, Elixir)} = Value.tuple() try do assert {^var!(a, Elixir), 1} = Value.tuple() rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message "assert {^var!(a, Elixir), 1} = Value.tuple()" = Macro.to_string(error.expr) end end test "assert match?" do true = assert match?({2, 1}, Value.tuple()) try do "This should never be tested" = assert match?({:ok, _}, error(true)) rescue error in [ExUnit.AssertionError] -> "match (match?) failed" = error.message "assert match?({:ok, _}, error(true))" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "assert match? with guards" do true = assert match?(tuple when is_tuple(tuple), Value.tuple()) try do "This should never be tested" = assert match?(tuple when not is_tuple(tuple), error(true)) rescue error in [ExUnit.AssertionError] -> "match (match?) failed" = error.message "assert match?(tuple when not is_tuple(tuple), error(true))" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "refute match?" do false = refute match?({1, 1}, Value.tuple()) try do "This should never be tested" = refute match?({:error, _}, error(true)) rescue error in [ExUnit.AssertionError] -> "match (match?) succeeded, but should have failed" = error.message "refute match?({:error, _}, error(true))" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "assert match? with pinned variable" do a = 1 try do "This should never be tested" = assert(match?({^a, 1}, Value.tuple())) rescue error in [ExUnit.AssertionError] -> "match (match?) failed\nThe following variables were pinned:\n a = 1" = error.message "assert match?({^a, 1}, Value.tuple())" = Macro.to_string(error.expr) end end test "refute match? with pinned variable" do a = 2 try do "This should never be tested" = refute(match?({^a, 1}, Value.tuple())) rescue error in [ExUnit.AssertionError] -> """ match (match?) succeeded, but should have failed The following variables were pinned: a = 2\ """ = error.message "refute match?({^a, 1}, Value.tuple())" = Macro.to_string(error.expr) end end test "assert receive waits" do parent = self() spawn(fn -> send(parent, :hello) end) :hello = assert_receive :hello end @string "hello" test "assert receive with interpolated compile-time string" do parent = self() spawn(fn -> send(parent, "string: hello") end) "string: #{@string}" = assert_receive "string: #{@string}" end test "assert receive accepts custom failure message" do send(self(), :hello) assert_receive message, 0, "failure message" :hello = message end test "assert receive with message in mailbox after timeout, but before reading mailbox tells user to increase timeout" do parent = self() # This is testing a race condition, so it's not # guaranteed this works under all loads of the system timeout = 100 spawn(fn -> Process.send_after(parent, :hello, timeout) end) try do assert_receive :hello, timeout rescue error in [ExUnit.AssertionError] -> true = error.message =~ "Found message matching :hello after 100ms" or error.message =~ "no matching message after 100ms" end end test "assert_receive exposes nested macro variables" do send(self(), {:hello}) assert_receive {~l(a)}, 0, "failure message" assert a == :hello end test "assert_receive raises on invalid timeout" do timeout = ok(1) try do assert_receive {~l(_a)}, timeout rescue error in [ArgumentError] -> "timeout must be a non-negative integer, got: {:ok, 1}" = error.message end end test "assert_receive expands argument in match context" do {x, y, z} = {1, 2, 3} send(self(), vec(x: x, y: y, z: z)) assert_receive vec(x: ^x, y: ^y) end test "assert_receive expands argument in guard context" do send(self(), {:ok, 0, :other}) assert_receive {:ok, val, atom} when is_zero(val) and is_atom(atom) end test "assert received does not wait" do send(self(), :hello) :hello = assert_received :hello end @received :hello test "assert received with module attribute" do send(self(), :hello) :hello = assert_received @received end test "assert received with pinned variable" do status = :valid send(self(), {:status, :invalid}) try do "This should never be tested" = assert_received {:status, ^status} rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms The following variables were pinned: status = :valid Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received {:status, ^status}" = Macro.to_string(error.expr) "{:status, ^status}" = Macro.to_string(error.left) end end test "assert received with multiple identical pinned variables" do status = :valid send(self(), {:status, :invalid, :invalid}) try do "This should never be tested" = assert_received {:status, ^status, ^status} rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms The following variables were pinned: status = :valid Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received {:status, ^status, ^status}" = Macro.to_string(error.expr) "{:status, ^status, ^status}" = Macro.to_string(error.left) "\n\nAssertion failed" <> _ = Exception.message(error) end end test "assert received with multiple unique pinned variables" do status = :valid other_status = :invalid send(self(), {:status, :invalid, :invalid}) try do "This should never be tested" = assert_received {:status, ^status, ^other_status} rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms The following variables were pinned: status = :valid other_status = :invalid Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received {:status, ^status, ^other_status}" = Macro.to_string(error.expr) "{:status, ^status, ^other_status}" = Macro.to_string(error.left) end end test "assert received when empty mailbox" do try do "This should never be tested" = assert_received :hello rescue error in [ExUnit.AssertionError] -> "Assertion failed, no matching message after 0ms\nThe process mailbox is empty." = error.message "assert_received :hello" = Macro.to_string(error.expr) end end test "assert received when different message" do send(self(), {:message, :not_expected, :at_all}) try do "This should never be tested" = assert_received :hello rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms Showing 1 of 1 message in the mailbox\ """ = error.message "assert_received :hello" = Macro.to_string(error.expr) ":hello" = Macro.to_string(error.left) end end test "assert received when different message having more than 10 on mailbox" do for i <- 1..11, do: send(self(), {:message, i}) try do "This should never be tested" = assert_received x when x == :hello rescue error in [ExUnit.AssertionError] -> """ Assertion failed, no matching message after 0ms Showing 10 of 11 messages in the mailbox\ """ = error.message "assert_received x when x == :hello" = Macro.to_string(error.expr) "x when x == :hello" = Macro.to_string(error.left) end end test "assert received binds variables" do send(self(), {:hello, :world}) assert_received {:hello, world} :world = world end test "assert received does not leak external variables used in guards" do send(self(), {:hello, :world}) guard_world = :world assert_received {:hello, world} when world == guard_world :world = world end test "refute received does not wait" do false = refute_received :hello end test "refute receive waits" do false = refute_receive :hello end test "refute received when equal" do send(self(), :hello) try do "This should never be tested" = refute_received :hello rescue error in [ExUnit.AssertionError] -> "Unexpectedly received message :hello (which matched :hello)" = error.message end end test "assert in when member" do true = assert 'foo' in ['foo', 'bar'] end test "assert in when is not member" do try do "This should never be tested" = assert 'foo' in 'bar' rescue error in [ExUnit.AssertionError] -> 'foo' = error.left 'bar' = error.right "assert 'foo' in 'bar'" = Macro.to_string(error.expr) end end test "refute in when is not member" do false = refute 'baz' in ['foo', 'bar'] end test "refute in when is member" do try do "This should never be tested" = refute 'foo' in ['foo', 'bar'] rescue error in [ExUnit.AssertionError] -> 'foo' = error.left ['foo', 'bar'] = error.right "refute 'foo' in ['foo', 'bar']" = Macro.to_string(error.expr) end end test "assert match" do {:ok, true} = assert {:ok, _} = ok(true) end test "assert match with bitstrings" do "foobar" = assert "foo" <> bar = "foobar" "bar" = bar end test "assert match when no match" do try do assert {:ok, _} = error(true) rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message "assert {:ok, _} = error(true)" = Macro.to_string(error.expr) "{:error, true}" = Macro.to_string(error.right) end end test "assert match when falsy but not match" do try do assert {:ok, _x} = nil rescue error in [ExUnit.AssertionError] -> "match (=) failed" = error.message "assert {:ok, _x} = nil" = Macro.to_string(error.expr) "nil" = Macro.to_string(error.right) end end test "assert match when falsy" do try do assert _x = nil rescue error in [ExUnit.AssertionError] -> "Expected truthy, got nil" = error.message "assert _x = nil" = Macro.to_string(error.expr) end end test "refute match when no match" do try do "This should never be tested" = refute _ = ok(true) rescue error in [ExUnit.AssertionError] -> "refute _ = ok(true)" = Macro.to_string(error.expr) "Expected false or nil, got {:ok, true}" = error.message end end test "assert regex match" do true = assert "foo" =~ ~r/o/ end test "assert regex match when no match" do try do "This should never be tested" = assert "foo" =~ ~r/a/ rescue error in [ExUnit.AssertionError] -> "foo" = error.left ~r{a} = error.right end end test "refute regex match" do false = refute "foo" =~ ~r/a/ end test "refute regex match when match" do try do "This should never be tested" = refute "foo" =~ ~r/o/ rescue error in [ExUnit.AssertionError] -> "foo" = error.left ~r"o" = error.right end end test "assert raise with no error" do "This should never be tested" = assert_raise ArgumentError, fn -> nil end rescue error in [ExUnit.AssertionError] -> "Expected exception ArgumentError but nothing was raised" = error.message end test "assert raise with error" do error = assert_raise ArgumentError, fn -> raise ArgumentError, "test error" end "test error" = error.message end @compile {:no_warn_undefined, Not.Defined} test "assert raise with some other error" do "This should never be tested" = assert_raise ArgumentError, fn -> Not.Defined.function(1, 2, 3) end rescue error in [ExUnit.AssertionError] -> "Expected exception ArgumentError but got UndefinedFunctionError " <> "(function Not.Defined.function/3 is undefined (module Not.Defined is not available))" = error.message end test "assert raise with some other error includes stacktrace from original error" do "This should never be tested" = assert_raise ArgumentError, fn -> Not.Defined.function(1, 2, 3) end rescue ExUnit.AssertionError -> [{Not.Defined, :function, [1, 2, 3], _} | _] = __STACKTRACE__ end test "assert raise with Erlang error" do assert_raise SyntaxError, fn -> List.flatten(1) end rescue error in [ExUnit.AssertionError] -> "Expected exception SyntaxError but got FunctionClauseError (no function clause matching in :lists.flatten/1)" = error.message end test "assert raise comparing messages (for equality)" do assert_raise RuntimeError, "foo", fn -> raise RuntimeError, "bar" end rescue error in [ExUnit.AssertionError] -> """ Wrong message for RuntimeError expected: "foo" actual: "bar"\ """ = error.message end test "assert raise comparing messages (with a regex)" do assert_raise RuntimeError, ~r/ba[zk]/, fn -> raise RuntimeError, "bar" end rescue error in [ExUnit.AssertionError] -> """ Wrong message for RuntimeError expected: ~r/ba[zk]/ actual: "bar"\ """ = error.message end test "assert raise with an exception with bad message/1 implementation" do assert_raise BrokenError, fn -> raise BrokenError end rescue error in [ExUnit.AssertionError] -> """ Got exception ExUnit.AssertionsTest.BrokenError but it failed to produce a message with: ** (RuntimeError) error """ <> _ = error.message end test "assert greater-than operator" do true = assert 2 > 1 end test "assert greater-than operator error" do "This should never be tested" = assert 1 > 2 rescue error in [ExUnit.AssertionError] -> 1 = error.left 2 = error.right "assert 1 > 2" = Macro.to_string(error.expr) end test "assert less or equal than operator" do true = assert 1 <= 2 end test "assert less or equal than operator error" do "This should never be tested" = assert 2 <= 1 rescue error in [ExUnit.AssertionError] -> "assert 2 <= 1" = Macro.to_string(error.expr) 2 = error.left 1 = error.right end test "assert operator with expressions" do greater = 5 true = assert 1 + 2 < greater end test "assert operator with custom message" do "This should never be tested" = assert 1 > 2, "assertion" rescue error in [ExUnit.AssertionError] -> "assertion" = error.message end test "assert lack of equality" do try do "This should never be tested" = assert "one" != "one" rescue error in [ExUnit.AssertionError] -> "Assertion with != failed, both sides are exactly equal" = error.message "one" = error.left end try do "This should never be tested" = assert 2 != 2.0 rescue error in [ExUnit.AssertionError] -> "Assertion with != failed" = error.message 2 = error.left 2.0 = error.right end end test "refute equality" do try do "This should never be tested" = refute "one" == "one" rescue error in [ExUnit.AssertionError] -> "Refute with == failed, both sides are exactly equal" = error.message "one" = error.left end try do "This should never be tested" = refute 2 == 2.0 rescue error in [ExUnit.AssertionError] -> "Refute with == failed" = error.message 2 = error.left 2.0 = error.right end end test "assert in delta" do true = assert_in_delta(1.1, 1.2, 0.2) end test "assert in delta raises when passing a negative delta" do assert_raise ArgumentError, fn -> assert_in_delta(1.1, 1.2, -0.2) end end test "assert in delta works with equal values and a delta of zero" do assert_in_delta(10, 10, 0) end test "assert in delta error" do "This should never be tested" = assert_in_delta(10, 12, 1) rescue error in [ExUnit.AssertionError] -> "Expected the difference between 10 and 12 (2) to be less than or equal to 1" = error.message end test "assert in delta with message" do "This should never be tested" = assert_in_delta(10, 12, 1, "test message") rescue error in [ExUnit.AssertionError] -> "test message" = error.message end test "refute in delta" do false = refute_in_delta(1.1, 1.5, 0.2) end test "refute in delta error" do "This should never be tested" = refute_in_delta(10, 11, 2) rescue error in [ExUnit.AssertionError] -> "Expected the difference between 10 and 11 (1) to be more than 2" = error.message end test "refute in delta with message" do "This should never be tested" = refute_in_delta(10, 11, 2, "test message") rescue error in [ExUnit.AssertionError] -> "test message (difference between 10 and 11 is less than 2)" = error.message end test "catch_throw with no throw" do catch_throw(1) rescue error in [ExUnit.AssertionError] -> "Expected to catch throw, got nothing" = error.message end test "catch_error with no error" do catch_error(1) rescue error in [ExUnit.AssertionError] -> "Expected to catch error, got nothing" = error.message end test "catch_exit with no exit" do catch_exit(1) rescue error in [ExUnit.AssertionError] -> "Expected to catch exit, got nothing" = error.message end test "catch_throw with throw" do 1 = catch_throw(throw(1)) end test "catch_exit with exit" do 1 = catch_exit(exit(1)) end test "catch_error with error" do :function_clause = catch_error(List.flatten(1)) end test "flunk" do "This should never be tested" = flunk() rescue error in [ExUnit.AssertionError] -> "Flunked!" = error.message end test "flunk with message" do "This should never be tested" = flunk("This should raise an error") rescue error in [ExUnit.AssertionError] -> "This should raise an error" = error.message end test "flunk with wrong argument type" do "This should never be tested" = flunk(["flunk takes a binary, not a list"]) rescue error -> "no function clause matching in ExUnit.Assertions.flunk/1" = FunctionClauseError.message(error) end test "AssertionError.message/1 is nicely formatted" do assert :a = :b rescue error in [ExUnit.AssertionError] -> """ match (=) failed code: assert :a = :b left: :a right: :b """ = Exception.message(error) end defp ok(val), do: {:ok, val} defp error(val), do: {:error, val} defp not_equal(left, right), do: left != right end
27.365449
123
0.623123
085119e6ed7bae2424eecd651cbfa4f644acb63f
4,736
ex
Elixir
lib/machinery/transition.ex
joaomdmoura/machinery
f434c90e952cbefd7ec657ec1255d941fe57dc76
[ "Apache-2.0" ]
433
2017-10-12T17:59:33.000Z
2022-03-29T17:32:54.000Z
lib/machinery/transition.ex
joaomdmoura/machinery
f434c90e952cbefd7ec657ec1255d941fe57dc76
[ "Apache-2.0" ]
74
2017-12-11T04:42:39.000Z
2022-01-24T05:44:43.000Z
lib/machinery/transition.ex
joaomdmoura/machinery
f434c90e952cbefd7ec657ec1255d941fe57dc76
[ "Apache-2.0" ]
46
2017-12-04T12:54:00.000Z
2022-03-28T10:13:56.000Z
defmodule Machinery.Transition do @moduledoc """ Machinery module responsible for control transitions, guard functions and callbacks (before and after). This is meant to be for internal use only. """ @doc """ Function responsible for checking if the transition from a state to another was specifically declared. This is meant to be for internal use only. """ @spec declared_transition?(list, atom, atom) :: boolean def declared_transition?(transitions, current_state, next_state) do if matches_wildcard?(transitions, next_state) do true else matches_transition?(transitions, current_state, next_state) end end @doc """ Default guard transition fallback to make sure all transitions are permitted unless another existing guard condition exists. This is meant to be for internal use only. """ @spec guarded_transition?(module, struct, atom) :: boolean def guarded_transition?(module, struct, state) do case run_or_fallback( &module.guard_transition/2, &guard_transition_fallback/4, struct, state, module._field() ) do {:error, cause} -> {:error, cause} _ -> false end end @doc """ Function responsible to run all before_transitions callbacks or fallback to a boilerplate behaviour. This is meant to be for internal use only. """ @spec before_callbacks(struct, atom, module) :: struct def before_callbacks(struct, state, module) do run_or_fallback( &module.before_transition/2, &callbacks_fallback/4, struct, state, module._field() ) end @doc """ Function responsible to run all after_transitions callbacks or fallback to a boilerplate behaviour. This is meant to be for internal use only. """ @spec after_callbacks(struct, atom, module) :: struct def after_callbacks(struct, state, module) do run_or_fallback( &module.after_transition/2, &callbacks_fallback/4, struct, state, module._field() ) end @doc """ This function will try to trigger persistence, if declared, to the struct changing state. This is meant to be for internal use only. """ @spec persist_struct(struct, atom, module) :: struct def persist_struct(struct, state, module) do run_or_fallback(&module.persist/2, &persist_fallback/4, struct, state, module._field()) end @doc """ Function responsible for triggering transitions persistence. This is meant to be for internal use only. """ @spec log_transition(struct, atom, module) :: struct def log_transition(struct, state, module) do run_or_fallback( &module.log_transition/2, &log_transition_fallback/4, struct, state, module._field() ) end defp matches_wildcard?(transitions, next_state) do matches_transition?(transitions, "*", next_state) end defp matches_transition?(transitions, current_state, next_state) do case Map.fetch(transitions, current_state) do {:ok, [_ | _] = declared_states} -> Enum.member?(declared_states, next_state) {:ok, declared_state} -> declared_state == next_state :error -> false end end # Private function that receives a function, a callback, # a struct and the related state. It tries to execute the function, # rescue for a couple of specific Exceptions and passes it forward # to the callback, that will re-raise it if not related to # guard_transition nor before | after call backs defp run_or_fallback(func, callback, struct, state, field) do func.(struct, state) rescue error in UndefinedFunctionError -> callback.(struct, state, error, field) error in FunctionClauseError -> callback.(struct, state, error, field) end defp persist_fallback(struct, state, error, field) do if error.function == :persist && error.arity == 2 do Map.put(struct, field, state) else raise error end end defp log_transition_fallback(struct, _state, error, _field) do if error.function == :log_transition && error.arity == 2 do struct else raise error end end defp callbacks_fallback(struct, _state, error, _field) do if error.function in [:after_transition, :before_transition] && error.arity == 2 do struct else raise error end end # If the exception passed is related to a specific signature of # guard_transition/2 it will fallback returning true and # allowing the transition, otherwise it will raise the exception. defp guard_transition_fallback(_struct, _state, error, _field) do if error.function == :guard_transition && error.arity == 2 do true else raise error end end end
30.165605
91
0.693623
085126ce5f7bee3be45cf34cbd3b65d6d07a5377
356
ex
Elixir
lib/phat/accounts.ex
tajchumber/live-view-chat
d98d445b145a197eadc4381e264f3d1918f0b90f
[ "Apache-2.0" ]
50
2019-05-23T11:59:30.000Z
2022-03-11T04:12:36.000Z
lib/phat/accounts.ex
tajchumber/live-view-chat
d98d445b145a197eadc4381e264f3d1918f0b90f
[ "Apache-2.0" ]
6
2019-05-18T09:53:46.000Z
2021-01-27T11:26:15.000Z
lib/phat/accounts.ex
tajchumber/live-view-chat
d98d445b145a197eadc4381e264f3d1918f0b90f
[ "Apache-2.0" ]
18
2019-05-18T08:13:51.000Z
2021-11-23T13:57:33.000Z
defmodule Phat.Accounts do alias Phat.Repo alias Phat.Accounts.User def change_user(changeset) do User.changeset(changeset) end def list_users do Repo.all(User) end def create_user(user_params) do User.changeset(%User{}, user_params) |> Repo.insert() end def get_user(user_id) do Repo.get(User, user_id) end end
16.181818
40
0.696629
08512fa1842206c3f2cbe1a354db923fb5655c13
2,146
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/update_private_auction_proposal_request.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/update_private_auction_proposal_request.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/update_private_auction_proposal_request.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 &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdExchangeBuyer.V14.Model.UpdatePrivateAuctionProposalRequest do @moduledoc """ ## Attributes - externalDealId (String.t): The externalDealId of the deal to be updated. Defaults to: `null`. - note (MarketplaceNote): Optional note to be added. Defaults to: `null`. - proposalRevisionNumber (String.t): The current revision number of the proposal to be updated. Defaults to: `null`. - updateAction (String.t): The proposed action on the private auction proposal. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :externalDealId => any(), :note => GoogleApi.AdExchangeBuyer.V14.Model.MarketplaceNote.t(), :proposalRevisionNumber => any(), :updateAction => any() } field(:externalDealId) field(:note, as: GoogleApi.AdExchangeBuyer.V14.Model.MarketplaceNote) field(:proposalRevisionNumber) field(:updateAction) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V14.Model.UpdatePrivateAuctionProposalRequest do def decode(value, options) do GoogleApi.AdExchangeBuyer.V14.Model.UpdatePrivateAuctionProposalRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V14.Model.UpdatePrivateAuctionProposalRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.372881
118
0.749767
08514568b9f25b7a66013a7a10422e46c4fafd32
1,947
exs
Elixir
config/dev.exs
first-tree/yggdrasil
dfe1417822a04c8d8da24912d0b4a8271c24e7c9
[ "MIT" ]
null
null
null
config/dev.exs
first-tree/yggdrasil
dfe1417822a04c8d8da24912d0b4a8271c24e7c9
[ "MIT" ]
1
2018-05-31T02:43:11.000Z
2018-05-31T02:43:11.000Z
config/dev.exs
first-tree/yggdrasil
dfe1417822a04c8d8da24912d0b4a8271c24e7c9
[ "MIT" ]
null
null
null
use Mix.Config # 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 brunch.io to recompile .js and .css sources. config :yggdrasil, YggdrasilWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../assets", __DIR__)]] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.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 :yggdrasil, YggdrasilWeb.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/yggdrasil_web/views/.*(ex)$}, ~r{lib/yggdrasil_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 # Configure your database config :yggdrasil, Yggdrasil.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "yggdrasil_dev", hostname: "localhost", pool_size: 10
33
170
0.705701
08516c04049b5b2ed8a3f0b1e5bfd185212c8e3e
948
exs
Elixir
elixir-lang__org__getting-started/alias_require_import.exs
jim80net/elixir_tutorial_projects
db19901a9305b297faa90642bebcc08455621b52
[ "Unlicense" ]
null
null
null
elixir-lang__org__getting-started/alias_require_import.exs
jim80net/elixir_tutorial_projects
db19901a9305b297faa90642bebcc08455621b52
[ "Unlicense" ]
null
null
null
elixir-lang__org__getting-started/alias_require_import.exs
jim80net/elixir_tutorial_projects
db19901a9305b297faa90642bebcc08455621b52
[ "Unlicense" ]
null
null
null
require Jim Jim.i alias Jim, as: J J.i 123 import Jim i :asdf defmodule Stats do alias Math.List, as: List end defmodule Math do def plus(a, b) do alias Math.List end def minus(a, b) do end end require Integer i Integer.is_odd(3) import List, only: [duplicate: 2] i duplicate :ok, 3 i ExUnit.start() defmodule AssertionTest do use ExUnit.Case, async: true test "always pass" do assert true end end #defmodule Example do # use Feature, option: :value #end # is compiled into #defmodule Example do # require Feature # Feature.__using__(option: :value) #end i is_atom(String) i to_string(String) i :"Elixir.String" == String i :"Elixir.String" === String i :lists.flatten([1, [2], 3]) i alias String, as: Str i to_string(Str) # defmodule Foo do # defmodule Bar do # end # end # is compiled into # defmodule Elixir.Foo do # defmodule Elixir.Foo.Bar do # end # alias Elixir.Foo.Bar, as: Bar # end
13.352113
36
0.684599
08517afa6462a607a99ebd2cc0636cb60e2539e4
7,198
ex
Elixir
lib/algae.ex
doma-engineering/algae
da85c5a9e78591c707859f07f9d485ed68019349
[ "MIT" ]
191
2016-08-22T17:34:45.000Z
2019-05-28T19:02:39.000Z
lib/algae.ex
doma-engineering/algae
da85c5a9e78591c707859f07f9d485ed68019349
[ "MIT" ]
35
2016-08-30T20:56:22.000Z
2019-05-02T17:32:31.000Z
lib/algae.ex
doma-engineering/algae
da85c5a9e78591c707859f07f9d485ed68019349
[ "MIT" ]
10
2016-08-30T18:41:54.000Z
2019-02-14T14:14:55.000Z
defmodule Algae do @moduledoc """ Builder DSL to handle common ADT definition use cases """ import Algae.Internal @type ast() :: {atom(), any(), any()} @doc ~S""" Build a product type Includes: * Struct * Type definition * Constructor function (for piping and defaults) * Implicit defaults for simple values ## Definition For convenveniece, several variants of the DSL are available. ### Standard defmodule Player do # =============== # # Data Definition # # =============== # defdata do name :: String.t() hit_points :: non_neg_integer() experience :: non_neg_integer() end # =================== # # Rest of Module # # (business as usual) # # =================== # @spec attack(t(), t()) :: {t(), t()} def attack(%{experience: xp} = player, %{hit_points: hp} = target) do { %{player | experience: xp + 50}, %{target | hit_points: hp - 10} } end end #=> %Player{name: "Sir Bob", hit_points: 10, experience: 500} ### Single Field Shorthand Without any fields specified, Algae will default to a single field with the same name as the module (essentially a "wrapper type"). You must still provide the type for this field, however. Embedded in another module: defmodule Id do defdata any() end %Id{} #=> %Id{id: nil} Standalone: defdata Wrapper :: any() %Wrapper{} #=> %Wrapper{wrapper: nil} ## Constructor A helper function, especially useful for piping. The order of arguments is the same as the order that they are defined in. defmodule Person do defdata do name :: String.t() age :: non_neg_integer() end end Person.new("Rachel Weintraub") #=> %Person{ # name: "Rachel Weintraub", # age: 0 # } ### Constructor Defaults Fields will automatically default to a sensible value (a typical "zero" for that datatype). For example, `non_neg_integer()` will default to `0`, and `String.t()` will default to `""`. You may also overwrite these defaults with the `\\\\` syntax. defmodule Pet do defdata do name :: String.t() leg_count :: non_neg_integer() \\\\ 4 end end Pet.new("Crookshanks") #=> %Pet{ # name: "Crookshanks", # leg_count: 4 # } Pet.new("Paul the Psychic Octopus", 8) #=> %Pet{ # name: "Paul the Psychic Octopus", # leg_count: 8 # } This overwriting syntax is _required_ for complex types: defdata Grocery do item :: {String.t(), integer(), boolean()} \\\\ {"Apple", 4, false} end Grocery.new() #=> %Grocery{ # item: {"Apple", 4, false} # } ### Overwrite Constructor The `new` constructor function may be overwritten. iex> defmodule Constant do ...> defdata fun() ...> ...> def new(value), do: %Constant{constant: fn _ -> value end} ...> end ...> ...> fourty_two = Constant.new(42) ...> fourty_two.constant.(33) 42 ## Empty Tag An empty type (with no fields) is definable using the `none`() type defmodule Nothing do defdata none() end Nothing.new() #=> %Nothing{} """ defmacro defdata(ast) do caller_module = __CALLER__.module case ast do {:none, _, _} = type -> embedded_data_ast() {:\\, _, [{:::, _, [module_ctx, type]}, default]} -> caller_module |> modules(module_ctx) |> data_ast(default, type) {:\\, _, [type, default]} -> caller_module |> List.wrap() |> embedded_data_ast(default, type) {:::, _, [module_ctx, {:none, _, _} = type]} -> caller_module |> modules(module_ctx) |> data_ast(type) {:::, _, [module_ctx, type]} -> caller_module |> modules(module_ctx) |> data_ast(default_value(type), type) {_, _, _} = type -> data_ast(caller_module, type) [do: {:__block__, _, lines}] -> data_ast(lines, __CALLER__) [do: line] -> data_ast([line], __CALLER__) end end defmacro defdata(module_ctx, do: body) do module_name = __CALLER__.module |> modules(module_ctx) |> Module.concat() inner = body |> case do {:__block__, _, lines} -> lines line -> List.wrap(line) end |> data_ast(__CALLER__) quote do defmodule unquote(module_name) do unquote(inner) end end end @doc """ Build a sum (coproduct) type from product types defmodule Light do # ============== # # Sum Definition # # ============== # defsum do defdata Red :: none() defdata Yellow :: none() defdata Green :: none() end # =================== # # Rest of Module # # (business as usual) # # =================== # def from_number(1), do: %Light.Red{} def from_number(2), do: %Light.Yellow{} def from_number(3), do: %Light.Green{} end Light.new() #=> %Light.Red{} ## Embedded Products Data with multiple fileds can be defined directly as part of a sum defmodule Pet do defsum do defdata Cat do name :: String.t() claw_sharpness :: String.t() end defdata Dog do name :: String.t() bark_loudness :: non_neg_integer() end end end ## Default Constructor The first `defdata`'s constructor will be the default constructor for the sum defmodule Maybe do defsum do defdata Nothing :: none() defdata Just :: any() end end Maybe.new() #=> %Maybe.Nothing{} ## Tagged Unions Sums join existing types with tags: new types to help distibguish the context that they are in (the sum type) defdata Book :: String.t() \\\\ "War and Peace" defdata Video :: String.t() \\\\ "2001: A Space Odyssey" defmodule Media do defsum do defdata Paper :: Book.t() defdata Film :: Video.t() \\\\ Video.new("A Clockwork Orange") end end media = Media.new() #=> %Paper{ # paper: %Book{ # book: "War and Peace" # } # } """ @spec defsum([do: {:__block__, [any()], ast()}]) :: ast() defmacro defsum(do: {:__block__, _, [first | _] = parts} = block) do module_ctx = __CALLER__.module types = or_types(parts, module_ctx) default_module = module_ctx |> List.wrap() |> Kernel.++(submodule_name(first)) |> Module.concat() quote do @type t :: unquote(types) unquote(block) @spec new() :: t() def new, do: unquote(default_module).new() defoverridable [new: 0] end end end
22.49375
79
0.522506
085195cd1f64656534b0d7323491faef76a8c090
3,575
ex
Elixir
lib/akd/destination.ex
corroded/akd
ed15b8929b6d110552a19522f8a17edf75452e87
[ "MIT" ]
null
null
null
lib/akd/destination.ex
corroded/akd
ed15b8929b6d110552a19522f8a17edf75452e87
[ "MIT" ]
null
null
null
lib/akd/destination.ex
corroded/akd
ed15b8929b6d110552a19522f8a17edf75452e87
[ "MIT" ]
null
null
null
defmodule Akd.Destination do @moduledoc """ This module represents a `Destination` struct which contains metadata about a destination/location/host. The meta data involves: * `user` - Represents the user who will be accessing a host/server. Expects a string, defaults to `:current`. * `host` - Represents the host/server being accessed. Expects a string, defaults to `:local`. * `path` - Represents the path on the server being accessed. Expects a string, defaults to `.` (current directory). Example: - Accessing `root@x.x.x.x:/path/to/dir"` would have: * `user`: `"root"` * `host`: `"x.x.x.x"` * `path`: `"/path/to/dir/"` This struct is mainly used by native hooks in `Akd`, but it can be leveraged to produce custom hooks. """ defstruct [user: :current, host: :local, path: "."] @typedoc ~s(A `Akd.Destination.user` can be either a string or `:current`) @type user :: String.t | :current @typedoc ~s(A `Akd.Destination.host` can be either a string or `:local`) @type host :: String.t | :local @typedoc ~s(Generic type for Akd.Destination) @type t :: %__MODULE__{ user: user, host: host, path: String.t } @doc """ Takes an `Akd.Destination.t` struct, `dest` and parses it into a readable string. ## Examples When `dest` is a local destination: iex> params = %{user: :current, host: :local, path: "/path/to/dir"} iex> local_destination = struct!(Akd.Destination, params) iex> Akd.Destination.to_string(local_destination) "/path/to/dir" When `dest` remote destination: iex> params = %{user: "dragonborn", host: "skyrim", path: "whiterun"} iex> local_destination = struct!(Akd.Destination, params) iex> Akd.Destination.to_string(local_destination) "dragonborn@skyrim:whiterun" """ @spec to_string(__MODULE__.t) :: String.t def to_string(dest) def to_string(%__MODULE__{user: :current, host: :local, path: path}), do: path def to_string(%__MODULE__{user: user, host: ip, path: path}) do "#{user}@#{ip}:#{path}" end @doc """ Takes a readable string and converts it to an `Akd.Destination.t` struct. Expects the string to be in the following format: `<user>@<host>:<path>` and parses it to: `%Akd.Destination{user: <user>, host: <host>, path: <path>}` Raises a `MatchError` if the string isn't in the correct format. ## Examples When a string with the correct format is given: iex> Akd.Destination.parse("dragonborn@skyrim:whiterun") %Akd.Destination{user: "dragonborn", host: "skyrim", path: "whiterun"} When a wrongly formatted string is given: iex> Akd.Destination.parse("arrowtotheknee") ** (MatchError) no match of right hand side value: ["arrowtotheknee"] """ @spec parse(String.t) :: __MODULE__.t def parse(string) do [user, host, path] = Regex.split(~r{@|:}, string) %__MODULE__{user: user, host: host, path: path} end @doc """ Takes a string path and returns a local `Akd.Destination.t` struct which corresponds to locahost with the given `path`. __Alternatively one can initialize an `Akd.Destination.t` struct with just a path, which will return a local Destination struct by default__ ## Examples When a path is given: iex> Akd.Destination.local("/fus/ro/dah") %Akd.Destination{host: :local, path: "/fus/ro/dah", user: :current} """ @spec local(String.t) :: __MODULE__.t def local(path \\ ".") do %__MODULE__{user: :current, host: :local, path: path} end end
31.359649
83
0.658741
0851a3d86d2ebc495f488cdab0a3ce0b26986d4a
807
ex
Elixir
lib/openflow/multipart/port_stats/request.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
5
2019-05-25T02:25:13.000Z
2020-10-06T17:00:03.000Z
lib/openflow/multipart/port_stats/request.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
5
2018-03-29T14:42:10.000Z
2019-11-19T07:03:09.000Z
lib/openflow/multipart/port_stats/request.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
1
2019-03-30T20:48:27.000Z
2019-03-30T20:48:27.000Z
defmodule Openflow.Multipart.Port.Request do defstruct( version: 4, xid: 0, # virtual field datapath_id: nil, flags: [], port_number: :any ) alias __MODULE__ def ofp_type, do: 18 def new(options \\ []) do %Request{ xid: options[:xid] || 0, port_number: options[:port_no] || :any } end def read(<<port_no_int::32, _::size(4)-unit(8)>>) do port_no = Openflow.Utils.get_enum(port_no_int, :openflow13_port_no) %Request{port_number: port_no} end def to_binary(%Request{port_number: port_no} = msg) do port_no_int = Openflow.Utils.get_enum(port_no, :openflow13_port_no) body_bin = <<port_no_int::32, 0::size(4)-unit(8)>> header_bin = Openflow.Multipart.Request.header(msg) <<header_bin::bytes, body_bin::bytes>> end end
23.735294
71
0.654275
0851aad1c90518d9e634766c28b3d0269a3f1d51
67
ex
Elixir
lib/miles_to_go_web/views/layout_view.ex
code-shoily/miles_to_go
cf5758d3113244326651320bd19c1887677bcf51
[ "MIT" ]
6
2020-12-18T08:36:32.000Z
2021-06-13T03:02:16.000Z
lib/miles_to_go_web/views/layout_view.ex
code-shoily/miles_to_go
cf5758d3113244326651320bd19c1887677bcf51
[ "MIT" ]
null
null
null
lib/miles_to_go_web/views/layout_view.ex
code-shoily/miles_to_go
cf5758d3113244326651320bd19c1887677bcf51
[ "MIT" ]
null
null
null
defmodule MilesToGoWeb.LayoutView do use MilesToGoWeb, :view end
16.75
36
0.820896
0851ca3b3bf78b1bae464ba6ef4d2c6594b62837
153
exs
Elixir
test/shutdown_flag_test.exs
cogini/shutdown_flag
1045223cc764ff5b0efc2b7b89445299ddc4ef90
[ "Apache-2.0" ]
5
2018-05-20T01:49:48.000Z
2020-01-13T23:22:09.000Z
test/shutdown_flag_test.exs
cogini/shutdown_flag
1045223cc764ff5b0efc2b7b89445299ddc4ef90
[ "Apache-2.0" ]
null
null
null
test/shutdown_flag_test.exs
cogini/shutdown_flag
1045223cc764ff5b0efc2b7b89445299ddc4ef90
[ "Apache-2.0" ]
null
null
null
defmodule ShutdownFlagTest do use ExUnit.Case doctest ShutdownFlag test "greets the world" do assert ShutdownFlag.hello() == :world end end
17
41
0.738562
0851d98e2d564f51440642d0c16f8ad7dfa341c9
675
ex
Elixir
lib/mix/tasks/test_integration.ex
SmartColumbusOS/divo
9fccc400dcc64142698061b3da2a67e7828829e3
[ "Apache-2.0" ]
21
2019-05-07T14:08:31.000Z
2020-08-05T02:04:07.000Z
lib/mix/tasks/test_integration.ex
UrbanOS-Public/divo
9fccc400dcc64142698061b3da2a67e7828829e3
[ "Apache-2.0" ]
11
2019-05-08T18:08:09.000Z
2020-05-19T17:26:55.000Z
lib/mix/tasks/test_integration.ex
UrbanOS-Public/divo
9fccc400dcc64142698061b3da2a67e7828829e3
[ "Apache-2.0" ]
6
2019-05-07T19:26:55.000Z
2020-01-28T17:11:09.000Z
defmodule Mix.Tasks.Test.Integration do @moduledoc """ Runs integration tests. This task will only work if your project has been configured according to the configuration steps provided in `Divo`. """ use Mix.Task require Logger @impl Mix.Task def run(args) do env = :integration {_, res} = System.cmd("mix", ["test", "--no-start", color() | args], into: IO.binstream(:stdio, :line), env: [{"MIX_ENV", to_string(env)}] ) if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end defp color() do if IO.ANSI.enabled?() do "--color" else "--no-color" end end end
20.454545
69
0.592593
0851de8def284220bd7d2effffbf09c2d4a68918
2,394
ex
Elixir
lib/cadet/jobs/autograder/result_store_worker.ex
source-academy/cadet
c447552453f78799755de73f66999e4c9d20383c
[ "Apache-2.0" ]
27
2018-01-20T05:56:24.000Z
2021-05-24T03:21:55.000Z
lib/cadet/jobs/autograder/result_store_worker.ex
source-academy/cadet
c447552453f78799755de73f66999e4c9d20383c
[ "Apache-2.0" ]
731
2018-04-16T13:25:49.000Z
2021-06-22T07:16:12.000Z
lib/cadet/jobs/autograder/result_store_worker.ex
source-academy/cadet
c447552453f78799755de73f66999e4c9d20383c
[ "Apache-2.0" ]
43
2018-01-20T06:35:46.000Z
2021-05-05T03:22:35.000Z
defmodule Cadet.Autograder.ResultStoreWorker do # Suppress no_match from macro @dialyzer {:no_match, __after_compile__: 2} @moduledoc """ This module writes results from the autograder to db. Separate worker is created with lower concurrency on the assumption that autograding time >> db IO time so as to reduce db load. """ use Que.Worker, concurrency: 5 require Logger import Cadet.SharedHelper import Ecto.Query alias Ecto.Multi alias Cadet.Repo alias Cadet.Assessments.Answer def perform(params = %{answer_id: answer_id, result: result}) when is_ecto_id(answer_id) do Multi.new() |> Multi.run(:fetch, fn _repo, _ -> fetch_answer(answer_id) end) |> Multi.run(:update, fn _repo, %{fetch: answer} -> update_answer(answer, result, params[:overwrite] || false) end) |> Repo.transaction() |> case do {:ok, _} -> nil {:error, failed_operation, failed_value, _} -> error_message = "Failed to store autograder result. " <> "answer_id: #{answer_id}, #{failed_operation}, #{inspect(failed_value, pretty: true)}" Logger.error(error_message) Sentry.capture_message(error_message) end end defp fetch_answer(answer_id) when is_ecto_id(answer_id) do answer = Answer |> join(:inner, [a], q in assoc(a, :question)) |> preload([_, q], question: q) |> Repo.get(answer_id) if answer do {:ok, answer} else {:error, "Answer not found"} end end defp update_answer(answer = %Answer{}, result = %{status: status}, overwrite) do xp = cond do result.max_score == 0 and length(result.result) > 0 -> testcase_results = result.result num_passed = testcase_results |> Enum.filter(fn r -> r["resultType"] == "pass" end) |> length() Integer.floor_div(answer.question.max_xp * num_passed, length(testcase_results)) result.max_score == 0 -> 0 true -> Integer.floor_div(answer.question.max_xp * result.score, result.max_score) end changes = %{ xp: xp, autograding_status: status, autograding_results: result.result } changes = if(overwrite, do: Map.put(changes, :xp_adjustment, 0), else: changes) answer |> Answer.autograding_changeset(changes) |> Repo.update() end end
27.517241
98
0.635338
0851df68f978d7fef4854fa720de219604e33dca
16,664
ex
Elixir
lib/fake_server.ex
fcapovilla/fake_server
68ee414ed421127f5aaca19c104b7ba01c12d716
[ "Apache-2.0" ]
null
null
null
lib/fake_server.ex
fcapovilla/fake_server
68ee414ed421127f5aaca19c104b7ba01c12d716
[ "Apache-2.0" ]
null
null
null
lib/fake_server.ex
fcapovilla/fake_server
68ee414ed421127f5aaca19c104b7ba01c12d716
[ "Apache-2.0" ]
null
null
null
defmodule FakeServer do @moduledoc """ Manage HTTP servers on your tests """ @doc """ Starts an HTTP server. Returns the tuple `{:ok, pid}` if the server started and `{:error, reason}` if any error happens. ## Parameters: - `name`: An identifier to the server. It must be an atom. - `port` (optional): The port the server will listen. It must be an integer between 55000 and 65000. ## Examples ``` iex> FakeServer.start(:myserver) {:ok, #PID<0.203.0>} iex> FakeServer.start(:myserver2, 55_000) {:ok, #PID<0.219.0>} iex> FakeServer.start(:myserver3, 54_999) {:error, {54999, "port is not in allowed range: 55000..65000"}} ``` """ def start(name, port \\ nil) do %{server_name: name, port: port} |> FakeServer.Instance.run() end @doc """ Starts an HTTP server. Unlike `start/1`, it will not return a tuple, but the server pid only. It will raise `FakeServer.Error` if any error happens. ## Parameters: - `name`: An identifier to the server. It must be an atom. - `port` (optional): The port the server will listen. It must be an integer between 55000 and 65000. ## Examples ``` iex> FakeServer.start!(:myserver1) #PID<0.203.0> iex> FakeServer.start!(:myserver2, 55_000) #PID<0.219.0> iex> FakeServer.start!(:myserver3, 54_999) ** (FakeServer.Error) 54999: port is not in allowed range: 55000..65000 ``` """ def start!(name, port \\ nil) do case start(name, port) do {:ok, pid} -> pid {:error, reason} -> raise FakeServer.Error, reason end end @doc """ Stops a given `server`. """ def stop(server), do: FakeServer.Instance.stop(server) @doc """ Returns the server port. ## Parameters - `server`: Can be a server `name` or `PID`. Make sure the server is running, using `FakeServer.start/2`. Returns the tuple `{:ok, port}` if the `server` is running and `{:error, reason}` if any error happens. ## Example ``` iex> {:ok, pid} = FakeServer.start(:myserver) {:ok, #PID<0.203.0>} iex> FakeServer.port(:myserver) {:ok, 62767} iex> FakeServer.port(pid) {:ok, 62767} iex> FakeServer.port(:otherserver) {:error, {:otherserver, "this server is not running"}} ``` """ def port(server) do try do {:ok, FakeServer.Instance.port(server)} catch :exit, _ -> {:error, {server, "this server is not running"}} end end @doc """ Returns the server port. ## Parameters - `server`: It can be a server name or PID Unlike `port/1`, it will not return a tuple, but the port number only. It will raise `FakeServer.Error` if any error happens. ## Example ``` iex> {:ok, pid} = FakeServer.start(:myserver) {:ok, #PID<0.194.0>} iex> FakeServer.port!(:myserver) 57198 iex> FakeServer.port!(pid) 57198 iex> FakeServer.port!(:otherserver) ** (FakeServer.Error) :otherserver: this server is not running ``` """ def port!(server) do case port(server) do {:ok, port_value} -> port_value {:error, reason} -> raise FakeServer.Error, reason end end @doc """ Adds a route to a `server`. Returns `:ok` if the route is added and `{:error, reason}` if any error happens. It will override an existing route if you add another route with the same path. Adding a route with this function is similar to `FakeServer.route/2` macro. ## Parameters - `server`: It can be a server name or PID. - `path`: A string representing the route path. See `FakeServer.route/2` for more information. - `response`: The response server will give use when this path is requested. See `FakeServer.route/2` for more information. ## Examples ``` iex> FakeServer.start(:myserver) {:ok, #PID<0.204.0>} iex> FakeServer.put_route(:myserver, "/healthcheck", FakeServer.Response.ok("WORKING")) :ok iex> FakeServer.put_route(:myserver, "/timeout", fn(_) -> :timer.sleep(10_000) end) :ok ``` """ def put_route(server, path, response) do try do FakeServer.Instance.add_route(server, path, response) catch :exit, _ -> {:error, {server, "this server is not running"}} end end @doc """ Adds a route to a `server`. Returns `:ok` if the route is added and raise `FakeServer.Error` if any error happens. It will override an existing route if you add another route with the same path. Adding a route with this function is similar to `FakeServer.route/2` macro. ## Parameters - `server`: It can be a server name or PID. - `path`: A string representing the route path. See `FakeServer.route/2` for more information. - `response`: The response server will give use when this path is requested. See `FakeServer.route/2` for more information. ## Examples ``` iex> FakeServer.start(:myserver) {:ok, #PID<0.204.0>} iex> FakeServer.put_route(:myserver, "/healthcheck", FakeServer.Response.ok("WORKING")) :ok iex> FakeServer.put_route(:myserver, "/timeout", fn(_) -> :timer.sleep(10_000) end) :ok ``` """ def put_route!(server, path, response) do case put_route(server, path, response) do :ok -> :ok {:error, reason} -> raise FakeServer.Error, reason end end @doc section: :macro defmacro test_with_server(test_description, opts \\ [], test_block) @doc """ Runs a test with an HTTP server. If you need an HTTP server on your test, just write it using `test_with_server/3` instead of `ExUnit.Case.test/3`. Their arguments are similar: A description (the `test_description` argument), the implementation of the test case itself (the `list` argument) and an optional list of parameters (the `opts` argument). The server will start just before your test block and will stop just before the test exits. Each `test_with_server/3` has its own server. By default, all servers will start in a random unused port, which allows you to run your tests with `ExUnit.Case async: true` option enabled. ## Server options You can set some options to the server before it starts using the `opts` params. The following options are accepted: - `:routes`: A list of routes to add to the server. If you set a route here, you don't need to configure a route using `route/2`. - `:port`: The port that the server will listen. The port value must be between 55_000 and 65_000 ## Usage: ```elixir defmodule SomeTest do use ExUnit.Case import FakeServer alias FakeServer.Response alias FakeServer.Route test_with_server "supports inline port configuration", [port: 63_543] do assert FakeServer.port() == 63_543 end test_with_server "supports inline route configuration", [routes: [Route.create!(path: "/test", response: Response.accepted!())]] do response = HTTPoison.get!(FakeServer.address <> "/test") assert response.status_code == 202 end end ``` """ defmacro test_with_server(test_description, opts, do: test_block) do quote do test unquote(test_description) do case FakeServer.Instance.run(unquote(opts)) do {:ok, server} -> var!(current_server, FakeServer) = server unquote(test_block) FakeServer.Instance.stop(server) {:error, reason} -> raise FakeServer.Error, reason end end end end @doc section: :macro defmacro route(path, response_block) @doc """ Adds a route to a server and sets its response. If you run a `test_with_server/3` with no route configured, the server will always reply `404`. ## Route path The route path must be a string starting with "/". Route binding and optional segments are accepted: ```elixir test_with_server "supports route binding" do route "/test/:param", fn(%Request{path: path}) -> if path == "/test/hello", do: Response.ok!(), else: Response.not_found!() end response = HTTPoison.get!(FakeServer.address <> "/test/hello") assert response.status_code == 200 response = HTTPoison.get!(FakeServer.address <> "/test/world") assert response.status_code == 404 end test_with_server "supports optional segments" do route "/test[/not[/mandatory]]", Response.accepted!() response = HTTPoison.get!(FakeServer.address <> "/test") assert response.status_code == 202 response = HTTPoison.get!(FakeServer.address <> "/test/not") assert response.status_code == 202 response = HTTPoison.get!(FakeServer.address <> "/test/not/mandatory") assert response.status_code == 202 end test_with_server "supports fully optional segments" do route "/test/[...]", Response.accepted!() response = HTTPoison.get!(FakeServer.address <> "/test") assert response.status_code == 202 response = HTTPoison.get!(FakeServer.address <> "/test/not") assert response.status_code == 202 response = HTTPoison.get!(FakeServer.address <> "/test/not/mandatory") assert response.status_code == 202 end test_with_server "paths ending in slash are no different than those ending without slash" do route "/test", Response.accepted!() response = HTTPoison.get!(FakeServer.address <> "/test") assert response.status_code == 202 response = HTTPoison.get!(FakeServer.address <> "/test/") assert response.status_code == 202 end ``` ## Adding routes Besides the path, you need to tell the server what to reply when that path is requested. FakeServer accepts three types of response: - a single `FakeServer.Response` structure - a list of `FakeServer.Response` structures - a function with arity 1 ### Routes with a single FakeServer.Response structure When a route is expected to be called once or to always reply the same thing, simply configure it with a `FakeServer.Response` structure as response. Every request to this path will always receive the same response. ```elixir test_with_server "Updating a user always returns 204" do route "/user/:id", Response.no_content!() response = HTTPoison.put!(FakeServer.address <> "/user/1234") assert response.status_code == 204 response = HTTPoison.put!(FakeServer.address <> "/user/5678") assert response.status_code == 204 end ``` ### Routes with a list of FakeServer.Response structure When the route is configured with a `FakeServer.Response` structure list, the server will reply every request with the first element in the list and then remove it. If the list is empty, the server will reply `FakeServer.Response.default/0`. ```elixir test_with_server "the server will always reply the first element and then remove it" do route "/", [Response.ok, Response.not_found, Response.bad_request] assert FakeServer.hits == 0 response = HTTPoison.get! FakeServer.address <> "/" assert response.status_code == 200 assert FakeServer.hits == 1 response = HTTPoison.get! FakeServer.address <> "/" assert response.status_code == 404 assert FakeServer.hits == 2 response = HTTPoison.get! FakeServer.address <> "/" assert response.status_code == 400 assert FakeServer.hits == 3 end ``` ### Configuring a route with a function You can configure a route to execute a function every time a request arrives. This function must accept a single argument, which is an `FakeServer.Request` object. The `FakeServer.Request` structure holds several information about the request, such as method, headers and query strings. Configure a route with a function is useful when you need to simulate timeouts, validate the presence of headers or some mandatory parameters. It also can be useful when used together with route path binding. The function will be called every time the route is requested. If the return value of the function is a `FakeServer.Response`, this response will be replied. However, if the function return value is not a `FakeServer.Response`, it will reply `FakeServer.Response.default/0`. ```elixir test_with_server "the server will return the default response if the function return is not a Response struct" do route "/", fn(_) -> :ok end response = HTTPoison.get! FakeServer.address <> "/" assert response.status_code == 200 assert response.body == ~s<{"message": "This is a default response from FakeServer"}> end test_with_server "you can evaluate the request object to choose what to reply" do route "/", fn(%{query: query} = _req) -> case Map.get(query, "access_token") do "1234" -> Response.ok("Welcome!") nil -> Response.bad_request("You must provide and access_token!") _ -> Response.forbidden("Invalid access token!") end end response = HTTPoison.get! FakeServer.address <> "/" assert response.status_code == 400 assert response.body == "You must provide and access_token!" response = HTTPoison.get! FakeServer.address <> "/?access_token=4321" assert response.status_code == 403 assert response.body == "Invalid access token!" response = HTTPoison.get! FakeServer.address <> "/?access_token=1234" assert response.status_code == 200 assert response.body == "Welcome!" end ``` """ defmacro route(path, response_block) do quote do server = var!(current_server, FakeServer) case FakeServer.Instance.add_route(server, unquote(path), unquote(response_block)) do :ok -> :ok {:error, reason} -> raise FakeServer.Error, reason end end end @doc section: :macro defmacro address() @doc """ Returns the current server address. You can only call `FakeServer.address/0` inside `test_with_server/3`. ## Usage ```elixir test_with_server "Getting the server address", [port: 55001] do assert FakeServer.address == "127.0.0.1:55001" end ``` """ defmacro address do quote do server = var!(current_server, FakeServer) "127.0.0.1:#{FakeServer.Instance.port(server)}" end end @doc section: :macro defmacro http_address() @doc """ Returns the current server HTTP address. You can only call `FakeServer.http_address/0` inside `test_with_server/3`. ## Usage ```elixir test_with_server "Getting the server address", [port: 55001] do assert FakeServer.address == "http://127.0.0.1:55001" end ``` """ defmacro http_address do quote do server = var!(current_server, FakeServer) "http://127.0.0.1:#{FakeServer.Instance.port(server)}" end end @doc section: :macro defmacro port() @doc """ Returns the current server TCP port. You can only call `FakeServer.port/0` inside `test_with_server/3`. ## Usage ```elixir test_with_server "Getting the server port", [port: 55001] do assert FakeServer.port == 55001 end ``` """ defmacro port do quote do server = var!(current_server, FakeServer) FakeServer.Instance.port(server) end end @doc section: :macro defmacro hits() @doc """ Returns the number of requests made to the server. You can only call `FakeServer.hits/0` inside `test_with_server/3`. ## Usage ```elixir test_with_server "counting server hits" do route "/", do: Response.ok assert FakeServer.hits == 0 HTTPoison.get! FakeServer.address <> "/" assert FakeServer.hits == 1 HTTPoison.get! FakeServer.address <> "/" assert FakeServer.hits == 2 end ``` """ defmacro hits do quote do server = var!(current_server, FakeServer) case FakeServer.Instance.access_list(server) do {:ok, access_list} -> length(access_list) {:error, reason} -> raise FakeServer.Error, reason end end end @doc section: :macro defmacro hits(path) @doc """ Returns the number of requests made to a route in the server. You can only call `FakeServer.hits/1` inside `test_with_server/3`. ## Usage ```elixir test_with_server "count route hits" do route "/no/cache", FakeServer.Response.ok route "/cache", FakeServer.Response.ok assert (FakeServer.hits "/no/cache") == 0 assert (FakeServer.hits "/cache") == 0 HTTPoison.get! FakeServer.address <> "/no/cache" assert (FakeServer.hits "/no/cache") == 1 HTTPoison.get! FakeServer.address <> "/cache" assert (FakeServer.hits "/cache") == 1 assert FakeServer.hits == 2 end ``` """ defmacro hits(path) do quote do server = var!(current_server, FakeServer) case FakeServer.Instance.access_list(server) do {:ok, access_list} -> access_list_path = access_list |> Enum.filter(&(&1 == unquote(path))) length(access_list_path) {:error, reason} -> raise FakeServer.Error, reason end end end end
31.560606
317
0.676248
0852243421b684ea470caeaf5c0c1dcb6c677201
7,252
ex
Elixir
lib/floki/html_tree.ex
danhuynhdev/floki
6700c14f842765eb5d1661af18fd686e87d1ddd7
[ "MIT" ]
null
null
null
lib/floki/html_tree.ex
danhuynhdev/floki
6700c14f842765eb5d1661af18fd686e87d1ddd7
[ "MIT" ]
null
null
null
lib/floki/html_tree.ex
danhuynhdev/floki
6700c14f842765eb5d1661af18fd686e87d1ddd7
[ "MIT" ]
null
null
null
defmodule Floki.HTMLTree do @moduledoc false # Builds a `Map` representing a HTML tree based on tuples or list of tuples. # # It is useful because keeps references for each node, and the possibility to # update the tree. defstruct nodes: %{}, root_nodes_ids: [], node_ids: [] alias Floki.HTMLTree alias Floki.HTMLTree.{HTMLNode, Text, Comment, IDSeeder} def build({:comment, comment}) do %HTMLTree{ root_nodes_ids: [1], node_ids: [1], nodes: %{ 1 => %Comment{content: comment, node_id: 1} } } end def build({tag, attrs, children}) do root_id = IDSeeder.seed([]) root_node = %HTMLNode{type: tag, attributes: attrs, node_id: root_id} build_tree( %HTMLTree{root_nodes_ids: [root_id], node_ids: [root_id], nodes: %{root_id => root_node}}, children, root_id, [] ) end def build(html_tuples) when is_list(html_tuples) do reducer = fn {:pi, _}, tree -> tree {:pi, _, _}, tree -> tree {tag, attrs, children}, tree -> root_id = IDSeeder.seed(tree.node_ids) root_node = %HTMLNode{type: tag, attributes: attrs, node_id: root_id} build_tree( %{ tree | nodes: Map.put(tree.nodes, root_id, root_node), node_ids: [root_id | tree.node_ids], root_nodes_ids: [root_id | tree.root_nodes_ids] }, children, root_id, [] ) text, tree when is_binary(text) -> root_id = IDSeeder.seed(tree.node_ids) root_node = %Text{content: text, node_id: root_id} build_tree( %{ tree | nodes: Map.put(tree.nodes, root_id, root_node), node_ids: [root_id | tree.node_ids], root_nodes_ids: [root_id | tree.root_nodes_ids] }, [], root_id, [] ) {:comment, comment}, tree -> root_id = IDSeeder.seed(tree.node_ids) root_node = %Comment{content: comment, node_id: root_id} build_tree( %{ tree | nodes: Map.put(tree.nodes, root_id, root_node), node_ids: [root_id | tree.node_ids], root_nodes_ids: [root_id | tree.root_nodes_ids] }, [], root_id, [] ) _, tree -> tree end Enum.reduce(html_tuples, %HTMLTree{}, reducer) end def build(_), do: %HTMLTree{} def delete_node(tree, html_node) do do_delete(tree, [html_node], []) end def to_tuple(_tree, %Text{content: text}), do: text def to_tuple(_tree, %Comment{content: comment}), do: {:comment, comment} def to_tuple(tree, html_node) do children = html_node.children_nodes_ids |> Enum.reverse() |> Enum.map(fn id -> to_tuple(tree, Map.get(tree.nodes, id)) end) {html_node.type, html_node.attributes, children} end defp do_delete(tree, [], []), do: tree defp do_delete(tree, [html_node | t], stack_ids) do new_tree_nodes = delete_node_from_nodes(tree.nodes, html_node) ids_for_stack = get_ids_for_delete_stack(html_node) do_delete( %{ tree | nodes: new_tree_nodes, node_ids: List.delete(tree.node_ids, html_node.node_id), root_nodes_ids: List.delete(tree.root_nodes_ids, html_node.node_id) }, t, ids_for_stack ++ stack_ids ) end defp do_delete(tree, [], stack_ids) do html_nodes = tree.nodes |> Map.take(stack_ids) |> Map.values() do_delete(tree, html_nodes, []) end defp delete_node_from_nodes(nodes, html_node) do tree_nodes = Map.delete(nodes, html_node.node_id) parent_node = Map.get(nodes, html_node.parent_node_id) if parent_node do children_ids = List.delete(parent_node.children_nodes_ids, html_node.node_id) new_parent = %{parent_node | children_nodes_ids: children_ids} %{tree_nodes | new_parent.node_id => new_parent} else tree_nodes end end defp get_ids_for_delete_stack(%HTMLNode{children_nodes_ids: ids}), do: ids defp get_ids_for_delete_stack(_), do: [] defp build_tree(tree, [], _, []), do: tree defp build_tree(tree, [{:pi, _, _} | children], parent_id, stack), do: build_tree(tree, children, parent_id, stack) defp build_tree(tree, [{tag, attrs, child_children} | children], parent_id, stack) do new_id = IDSeeder.seed(tree.node_ids) new_node = %HTMLNode{type: tag, attributes: attrs, node_id: new_id, parent_node_id: parent_id} nodes = put_new_node(tree.nodes, new_node) build_tree( %{tree | nodes: nodes, node_ids: [new_id | tree.node_ids]}, child_children, new_id, [{parent_id, children} | stack] ) end defp build_tree(tree, [{:comment, comment} | children], parent_id, stack) do new_id = IDSeeder.seed(tree.node_ids) new_node = %Comment{content: comment, node_id: new_id, parent_node_id: parent_id} nodes = put_new_node(tree.nodes, new_node) build_tree( %{tree | nodes: nodes, node_ids: [new_id | tree.node_ids]}, children, parent_id, stack ) end defp build_tree(tree, [text | children], parent_id, stack) when is_binary(text) do new_id = IDSeeder.seed(tree.node_ids) new_node = %Text{content: text, node_id: new_id, parent_node_id: parent_id} nodes = put_new_node(tree.nodes, new_node) build_tree( %{tree | nodes: nodes, node_ids: [new_id | tree.node_ids]}, children, parent_id, stack ) end defp build_tree(tree, [_other | children], parent_id, stack) do build_tree(tree, children, parent_id, stack) end defp build_tree(tree, [], _, [{parent_node_id, children} | stack]) do build_tree(tree, children, parent_node_id, stack) end defp put_new_node(nodes, new_node) do parent_node = Map.get(nodes, new_node.parent_node_id) children_ids = parent_node.children_nodes_ids updated_parent = %{parent_node | children_nodes_ids: [new_node.node_id | children_ids]} nodes |> Map.put(new_node.node_id, new_node) |> Map.put(new_node.parent_node_id, updated_parent) end # Enables using functions from `Enum` and `Stream` modules defimpl Enumerable do def count(html_tree) do {:ok, length(html_tree.node_ids)} end def member?(html_tree, html_node = %{node_id: node_id}) do a_node = Map.get(html_tree.nodes, node_id) {:ok, a_node === html_node} end def member?(_, _) do {:ok, false} end def slice(_) do {:error, __MODULE__} end def reduce(html_tree, state, fun) do do_reduce(%{html_tree | node_ids: Enum.reverse(html_tree.node_ids)}, state, fun) end defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc} defp do_reduce(tree, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(tree, &1, fun)} defp do_reduce(%HTMLTree{node_ids: []}, {:cont, acc}, _fun), do: {:done, acc} defp do_reduce(html_tree = %HTMLTree{node_ids: [h | t]}, {:cont, acc}, fun) do tree = %{html_tree | node_ids: t} head_node = Map.get(html_tree.nodes, h) do_reduce(tree, fun.(head_node, acc), fun) end end end
27.366038
98
0.622173
08522757a9ad3c7f38d8ae541e070a98365fc9bd
477
ex
Elixir
lib/tds/versions.ex
kianmeng/tds
36f228275c2bfde2baa45fe70d29d1eb1d44379b
[ "Apache-2.0" ]
null
null
null
lib/tds/versions.ex
kianmeng/tds
36f228275c2bfde2baa45fe70d29d1eb1d44379b
[ "Apache-2.0" ]
null
null
null
lib/tds/versions.ex
kianmeng/tds
36f228275c2bfde2baa45fe70d29d1eb1d44379b
[ "Apache-2.0" ]
1
2021-09-07T15:25:40.000Z
2021-09-07T15:25:40.000Z
defmodule Tds.Version do import Tds.Protocol.Grammar defstruct version: 0x74000004, str_version: "7.4" @versions [ {0x71000001, "7.1"}, {0x72090002, "7.2"}, {0x730A0003, "7.3.A"}, {0x730B0003, "7.3.B"}, {0x74000004, "7.4"} ] def decode(<<key::little-dword>>) do @versions |> List.keyfind(key, 0, "7.4") end def encode(ver) do val = @versions |> List.keyfind(ver, 1, 0x74000004) <<val::little-dword>> end end
17.666667
51
0.580713
0852290b936e3704bbd15e5610ca556c1846e618
1,448
ex
Elixir
test/support/data_case.ex
jackjoe/mailgun_logger
7d5a1989afdeb215bcd3753671c61bc25ed4e522
[ "MIT" ]
64
2020-02-10T20:42:46.000Z
2021-11-16T10:47:50.000Z
test/support/data_case.ex
jackjoe/mailgun_logger
7d5a1989afdeb215bcd3753671c61bc25ed4e522
[ "MIT" ]
16
2020-02-10T20:45:57.000Z
2022-03-04T12:53:34.000Z
test/support/data_case.ex
jackjoe/mailgun_logger
7d5a1989afdeb215bcd3753671c61bc25ed4e522
[ "MIT" ]
4
2020-04-03T17:13:19.000Z
2020-07-17T12:56:31.000Z
defmodule MailgunLogger.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias MailgunLogger.Repo import Ecto import Ecto.Changeset import Ecto.Query import MailgunLogger.Factory import MailgunLogger.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(MailgunLogger.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(MailgunLogger.Repo, {:shared, self()}) end :ok end @doc """ A helper that transform changeset errors to a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
26.327273
77
0.687845
08524058427251f68305a21b7e1e842ffbf3ab14
731
exs
Elixir
test/jaya_currency_converter/core/exchange_test.exs
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
test/jaya_currency_converter/core/exchange_test.exs
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
test/jaya_currency_converter/core/exchange_test.exs
franknfjr/jaya_currency_converter
56dfcf40b2ed2c9307fa39d7a5d1121cf4a1a37e
[ "MIT" ]
null
null
null
defmodule JayaCurrencyConverter.ExchangeTest do use JayaCurrencyConverter.DataCase alias JayaCurrencyConverter.Core.Exchange describe "exchange" do test "fetch_rates_from_currency/1 return value of a currency when currency is valid" do rates_brl = "BRL" |> Exchange.fetch_rates_from_currency() assert Exchange.fetch_rates_from_currency("BRL") == rates_brl end test "fetch_rates_from_currency/1 return value of a currency when invalid currency" do assert Exchange.fetch_rates_from_currency("FOM") == {:error, "error"} end test "calculate_amount/3 return a conversion of currency" do assert Exchange.calculate_amount("BRL", "USD", 1) == 0.1762 end end end
30.458333
91
0.729138
085287a0fa8132a28fb40ad157f0ddfabd058ecb
1,085
ex
Elixir
example/lib/calculator/generated/vector_product_type.ex
dnlserrano/elixir-thrift
568de9f7bdfa43279c819cb50e16c33b4dc09146
[ "Apache-2.0" ]
1
2020-06-11T03:52:25.000Z
2020-06-11T03:52:25.000Z
example/lib/calculator/generated/vector_product_type.ex
dnlserrano/elixir-thrift
568de9f7bdfa43279c819cb50e16c33b4dc09146
[ "Apache-2.0" ]
77
2018-08-29T00:36:42.000Z
2021-08-02T13:14:35.000Z
example/lib/calculator/generated/vector_product_type.ex
thecodeboss/elixir-thrift
621a2039bcbcec62d1cedc85b01421813e0910e8
[ "Apache-2.0" ]
1
2021-02-04T15:58:30.000Z
2021-02-04T15:58:30.000Z
defmodule(Calculator.Generated.VectorProductType) do @moduledoc false defmacro(unquote(:dot_product)()) do 1 end defmacro(unquote(:cross_product)()) do 2 end def(value_to_name(1)) do {:ok, :dot_product} end def(value_to_name(2)) do {:ok, :cross_product} end def(value_to_name(v)) do {:error, {:invalid_enum_value, v}} end def(name_to_value(:dot_product)) do {:ok, 1} end def(name_to_value(:cross_product)) do {:ok, 2} end def(name_to_value(k)) do {:error, {:invalid_enum_name, k}} end def(value_to_name!(value)) do {:ok, name} = value_to_name(value) name end def(name_to_value!(name)) do {:ok, value} = name_to_value(name) value end def(meta(:names)) do [:dot_product, :cross_product] end def(meta(:values)) do [1, 2] end def(member?(1)) do true end def(member?(2)) do true end def(member?(_)) do false end def(name?(:dot_product)) do true end def(name?(:cross_product)) do true end def(name?(_)) do false end end
14.090909
52
0.613825
0852b56212b5f6040324b9b73e49302fc4967ae9
7,926
exs
Elixir
test/erflow/model_test.exs
roi-levoso/erflow
e8683fd93720703ea706af8f2317376dba3b401f
[ "MIT" ]
null
null
null
test/erflow/model_test.exs
roi-levoso/erflow
e8683fd93720703ea706af8f2317376dba3b401f
[ "MIT" ]
null
null
null
test/erflow/model_test.exs
roi-levoso/erflow
e8683fd93720703ea706af8f2317376dba3b401f
[ "MIT" ]
null
null
null
# defmodule Erflow.ModelTest do # use Erflow.DataCase # alias Erflow.Modle # describe "dags" do # alias Erflow.Model.Dag # @valid_attrs %{dag_id: "some dag_id", enabled: "some enabled", end_time: "some end_time", scheduled_time: "some scheduled_time", start_time: "some start_time", status: "some status"} # @update_attrs %{dag_id: "some updated dag_id", enabled: "some updated enabled", end_time: "some updated end_time", scheduled_time: "some updated scheduled_time", start_time: "some updated start_time", status: "some updated status"} # @invalid_attrs %{dag_id: nil, enabled: nil, end_time: nil, scheduled_time: nil, start_time: nil, status: nil} # def dag_fixture(attrs \\ %{}) do # {:ok, dag} = # attrs # |> Enum.into(@valid_attrs) # |> Model.create_dag() # dag # end # test "list_dags/0 returns all dags" do # dag = dag_fixture() # assert Model.list_dags() == [dag] # end # test "get_dag!/1 returns the dag with given id" do # dag = dag_fixture() # assert Model.get_dag!(dag.id) == dag # end # test "create_dag/1 with valid data creates a dag" do # assert {:ok, %Dag{} = dag} = Model.create_dag(@valid_attrs) # assert dag.dag_id == "some dag_id" # assert dag.enabled == "some enabled" # assert dag.end_time == "some end_time" # assert dag.scheduled_time == "some scheduled_time" # assert dag.start_time == "some start_time" # assert dag.status == "some status" # end # test "create_dag/1 with invalid data returns error changeset" do # assert {:error, %Ecto.Changeset{}} = Model.create_dag(@invalid_attrs) # end # test "update_dag/2 with valid data updates the dag" do # dag = dag_fixture() # assert {:ok, %Dag{} = dag} = Model.update_dag(dag, @update_attrs) # assert dag.dag_id == "some updated dag_id" # assert dag.enabled == "some updated enabled" # assert dag.end_time == "some updated end_time" # assert dag.scheduled_time == "some updated scheduled_time" # assert dag.start_time == "some updated start_time" # assert dag.status == "some updated status" # end # test "update_dag/2 with invalid data returns error changeset" do # dag = dag_fixture() # assert {:error, %Ecto.Changeset{}} = Model.update_dag(dag, @invalid_attrs) # assert dag == Model.get_dag!(dag.id) # end # test "delete_dag/1 deletes the dag" do # dag = dag_fixture() # assert {:ok, %Dag{}} = Model.delete_dag(dag) # assert_raise Ecto.NoResultsError, fn -> Model.get_dag!(dag.id) end # end # test "change_dag/1 returns a dag changeset" do # dag = dag_fixture() # assert %Ecto.Changeset{} = Model.change_dag(dag) # end # end # describe "tasks" do # alias Erflow.Model.Task # @valid_attrs %{dag_id: "some dag_id", end_time: "some end_time", name: "some name", scheduled_time: "some scheduled_time", start_time: "some start_time", status: "some status", task_id: "some task_id"} # @update_attrs %{dag_id: "some updated dag_id", end_time: "some updated end_time", name: "some updated name", scheduled_time: "some updated scheduled_time", start_time: "some updated start_time", status: "some updated status", task_id: "some updated task_id"} # @invalid_attrs %{dag_id: nil, end_time: nil, name: nil, scheduled_time: nil, start_time: nil, status: nil, task_id: nil} # def task_fixture(attrs \\ %{}) do # {:ok, task} = # attrs # |> Enum.into(@valid_attrs) # |> Model.create_task() # task # end # test "list_tasks/0 returns all tasks" do # task = task_fixture() # assert Model.list_tasks() == [task] # end # test "get_task!/1 returns the task with given id" do # task = task_fixture() # assert Model.get_task!(task.id) == task # end # test "create_task/1 with valid data creates a task" do # assert {:ok, %Task{} = task} = Model.create_task(@valid_attrs) # assert task.dag_id == "some dag_id" # assert task.end_time == "some end_time" # assert task.name == "some name" # assert task.scheduled_time == "some scheduled_time" # assert task.start_time == "some start_time" # assert task.status == "some status" # assert task.task_id == "some task_id" # end # test "create_task/1 with invalid data returns error changeset" do # assert {:error, %Ecto.Changeset{}} = Model.create_task(@invalid_attrs) # end # test "update_task/2 with valid data updates the task" do # task = task_fixture() # assert {:ok, %Task{} = task} = Model.update_task(task, @update_attrs) # assert task.dag_id == "some updated dag_id" # assert task.end_time == "some updated end_time" # assert task.name == "some updated name" # assert task.scheduled_time == "some updated scheduled_time" # assert task.start_time == "some updated start_time" # assert task.status == "some updated status" # assert task.task_id == "some updated task_id" # end # test "update_task/2 with invalid data returns error changeset" do # task = task_fixture() # assert {:error, %Ecto.Changeset{}} = Model.update_task(task, @invalid_attrs) # assert task == Model.get_task!(task.id) # end # test "delete_task/1 deletes the task" do # task = task_fixture() # assert {:ok, %Task{}} = Model.delete_task(task) # assert_raise Ecto.NoResultsError, fn -> Model.get_task!(task.id) end # end # test "change_task/1 returns a task changeset" do # task = task_fixture() # assert %Ecto.Changeset{} = Model.change_task(task) # end # end # describe "relationships" do # alias Erflow.Model.Relationship # @valid_attrs %{} # @update_attrs %{} # @invalid_attrs %{} # def relationship_fixture(attrs \\ %{}) do # {:ok, relationship} = # attrs # |> Enum.into(@valid_attrs) # |> Model.create_relationship() # relationship # end # test "list_relationships/0 returns all relationships" do # relationship = relationship_fixture() # assert Model.list_relationships() == [relationship] # end # test "get_relationship!/1 returns the relationship with given id" do # relationship = relationship_fixture() # assert Model.get_relationship!(relationship.id) == relationship # end # test "create_relationship/1 with valid data creates a relationship" do # assert {:ok, %Relationship{} = relationship} = Model.create_relationship(@valid_attrs) # end # test "create_relationship/1 with invalid data returns error changeset" do # assert {:error, %Ecto.Changeset{}} = Model.create_relationship(@invalid_attrs) # end # test "update_relationship/2 with valid data updates the relationship" do # relationship = relationship_fixture() # assert {:ok, %Relationship{} = relationship} = Model.update_relationship(relationship, @update_attrs) # end # test "update_relationship/2 with invalid data returns error changeset" do # relationship = relationship_fixture() # assert {:error, %Ecto.Changeset{}} = Model.update_relationship(relationship, @invalid_attrs) # assert relationship == Model.get_relationship!(relationship.id) # end # test "delete_relationship/1 deletes the relationship" do # relationship = relationship_fixture() # assert {:ok, %Relationship{}} = Model.delete_relationship(relationship) # assert_raise Ecto.NoResultsError, fn -> Model.get_relationship!(relationship.id) end # end # test "change_relationship/1 returns a relationship changeset" do # relationship = relationship_fixture() # assert %Ecto.Changeset{} = Model.change_relationship(relationship) # end # end # end
39.044335
264
0.648877
0852f63fa517a543b716a0b8a9b7ed2e5569e770
52
ex
Elixir
lib/dig/good.ex
codedge-llc/dig
cdbe21dcb3291497b024c6cdc6e9fba0ca3a07da
[ "MIT" ]
null
null
null
lib/dig/good.ex
codedge-llc/dig
cdbe21dcb3291497b024c6cdc6e9fba0ca3a07da
[ "MIT" ]
null
null
null
lib/dig/good.ex
codedge-llc/dig
cdbe21dcb3291497b024c6cdc6e9fba0ca3a07da
[ "MIT" ]
null
null
null
defmodule Dig.Good do def yo, do: Dig.Derp.uh end
13
25
0.711538
0852f85bb076843a34e220a9be09992bd34295f7
239
ex
Elixir
lib/facebook/graph_video_api.ex
mojidabckuu/facebook.ex
c15c3acc4aa5c5e74140bbeb681fbccf762e3609
[ "MIT" ]
null
null
null
lib/facebook/graph_video_api.ex
mojidabckuu/facebook.ex
c15c3acc4aa5c5e74140bbeb681fbccf762e3609
[ "MIT" ]
null
null
null
lib/facebook/graph_video_api.ex
mojidabckuu/facebook.ex
c15c3acc4aa5c5e74140bbeb681fbccf762e3609
[ "MIT" ]
1
2018-09-10T15:35:53.000Z
2018-09-10T15:35:53.000Z
defmodule Facebook.GraphVideoAPI do @moduledoc false use HTTPoison.Base alias Facebook.Config def process_url(url), do: Config.graph_video_url <> url def process_response_body(body) do body |> JSON.decode end end
15.933333
57
0.728033
0852f9e7f67ab10e7e62f786508d822e0bf43c7b
664
ex
Elixir
lib/assertions/use_view_module.ex
facto/bamboo_espec
5899c1b5109ff9cb62ba7487482e31cc2af01b22
[ "MIT" ]
4
2017-01-16T08:58:00.000Z
2018-11-21T09:59:32.000Z
lib/assertions/use_view_module.ex
facto/bamboo_espec
5899c1b5109ff9cb62ba7487482e31cc2af01b22
[ "MIT" ]
null
null
null
lib/assertions/use_view_module.ex
facto/bamboo_espec
5899c1b5109ff9cb62ba7487482e31cc2af01b22
[ "MIT" ]
1
2018-11-21T09:59:41.000Z
2018-11-21T09:59:41.000Z
defmodule Bamboo.ESpec.Assertions.UseViewModule do use ESpec.Assertions.Interface defp match(%Bamboo.Email{} = email, value) do result = email.private.view_module == value {result, value} end defp success_message(email, value, _result, positive) do has = if positive, do: "has", else: "does not have" "`#{inspect email}` #{has} view module `#{inspect value}`." end defp error_message(email, value, _result, positive) do have = if positive, do: "have", else: "not to have" but = if positive, do: "it does not", else: "it does" "Expected `#{inspect email}` to #{have} view module `#{inspect value}`, but #{but}." end end
33.2
88
0.665663
08530050a4adeea4626613a7c3268e5f388cf374
2,196
exs
Elixir
apps/algolia/test/analytics_test.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
42
2019-05-29T16:05:30.000Z
2021-08-09T16:03:37.000Z
apps/algolia/test/analytics_test.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
872
2019-05-29T17:55:50.000Z
2022-03-30T09:28:43.000Z
apps/algolia/test/analytics_test.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
12
2019-07-01T18:33:21.000Z
2022-03-10T02:13:57.000Z
defmodule Algolia.AnalyticsTest do use ExUnit.Case, async: true @params %{ "objectID" => "objectID", "position" => "1", "queryID" => "queryID" } describe "when click tracking is disabled" do test "does not send request" do old_url = Application.get_env(:algolia, :click_analytics_url) Application.put_env(:algolia, :click_analytics_url, "return_error_if_called") on_exit(fn -> Application.put_env(:algolia, :click_analytics_url, old_url) end) assert Application.get_env(:algolia, :track_clicks?) == false assert Algolia.Analytics.click(@params) == :ok end end describe "when click tracking is enabled" do setup do bypass = Bypass.open() old_url = Application.get_env(:algolia, :click_analytics_url) Application.put_env(:algolia, :track_clicks?, true) Application.put_env(:algolia, :click_analytics_url, "http://localhost:#{bypass.port}") on_exit(fn -> Application.put_env(:algolia, :track_clicks?, false) Application.put_env(:algolia, :click_analytics_url, old_url) end) {:ok, bypass: bypass} end test "returns :ok when click is successfully logged", %{bypass: bypass} do Bypass.expect(bypass, fn conn -> Plug.Conn.send_resp(conn, 200, "success") end) assert Algolia.Analytics.click(@params) == :ok end test "returns {:error, %HTTPoison.Response{}} and logs a warning when response code is not 200", %{bypass: bypass} do Bypass.expect(bypass, fn conn -> Plug.Conn.send_resp(conn, 401, "Feature not available") end) log = ExUnit.CaptureLog.capture_log(fn -> assert {:error, %HTTPoison.Response{status_code: 401}} = Algolia.Analytics.click(@params) end) assert log =~ "Bad response" end test "returns {:error, %HTTPoison.Error{}} and logs a warning when unable to connect to Algolia", %{bypass: bypass} do Bypass.down(bypass) log = ExUnit.CaptureLog.capture_log(fn -> assert {:error, %HTTPoison.Error{}} = Algolia.Analytics.click(@params) end) assert log =~ "Error" end end end
30.929577
101
0.644809
0853986315b8a228212355666135a15c02aef06a
1,002
ex
Elixir
lib/ex_oauth2_provider/oauth2/authorization/utils.ex
gozego/ex_oauth2_provider
d3a7658d28233dda2dfdef7ed397b5b440a2f737
[ "Unlicense", "MIT" ]
2
2021-04-25T20:59:53.000Z
2021-07-13T22:49:20.000Z
lib/ex_oauth2_provider/oauth2/authorization/utils.ex
gozego/ex_oauth2_provider
d3a7658d28233dda2dfdef7ed397b5b440a2f737
[ "Unlicense", "MIT" ]
null
null
null
lib/ex_oauth2_provider/oauth2/authorization/utils.ex
gozego/ex_oauth2_provider
d3a7658d28233dda2dfdef7ed397b5b440a2f737
[ "Unlicense", "MIT" ]
null
null
null
defmodule ExOauth2Provider.Authorization.Utils do @moduledoc false alias ExOauth2Provider.OauthApplications alias ExOauth2Provider.Utils.Error @doc false def prehandle_request(resource_owner, request) do %{resource_owner: resource_owner, request: request} |> load_client |> set_defaults end defp load_client(%{request: %{"client_id" => client_id}} = params) do case OauthApplications.get_application(client_id) do nil -> Error.add_error(params, Error.invalid_client()) client -> Map.merge(params, %{client: client}) end end defp load_client(params), do: Error.add_error(params, Error.invalid_request()) defp set_defaults(%{error: _} = params), do: params defp set_defaults(%{request: request, client: client} = params) do redirect_uri = client.redirect_uri |> String.split |> Kernel.hd request = %{"redirect_uri" => redirect_uri, "scope" => nil} |> Map.merge(request) params |> Map.merge(%{request: request}) end end
30.363636
80
0.706587
08539c169d684f71737341611bc6d178ad85586d
734
ex
Elixir
spec/support/factory.ex
participateapp/participate-api
35dab43fc456f7e8b8c8479195562baad881aa44
[ "MIT" ]
3
2015-01-29T19:11:05.000Z
2015-10-19T02:12:02.000Z
spec/support/factory.ex
participateapp/participate-api
35dab43fc456f7e8b8c8479195562baad881aa44
[ "MIT" ]
43
2015-05-31T00:28:45.000Z
2017-02-06T20:06:19.000Z
spec/support/factory.ex
participateapp/participate-api
35dab43fc456f7e8b8c8479195562baad881aa44
[ "MIT" ]
2
2015-07-11T14:48:04.000Z
2015-07-13T06:51:37.000Z
defmodule ParticipateApi.Factory do use ExMachina.Ecto, repo: ParticipateApi.Repo def account_factory do %ParticipateApi.Account{ email: sequence(:email, &"email-#{&1}@example.com"), facebook_uid: sequence("facebookuid"), participant: build(:participant) } end def participant_factory do %ParticipateApi.Participant{ name: sequence("Participant name") } end def proposal_factory do %ParticipateApi.Proposal{ title: sequence("Proposal title"), body: sequence("Proposal body"), author: build(:participant) } end def support_factory do %ParticipateApi.Support{ author: build(:participant), proposal: build(:proposal) } end end
22.242424
58
0.671662
08539ce46e7680c9670e427dc390dd71d26686cf
1,139
exs
Elixir
config/config.exs
mbramson/ecto_sanitizer
ee56132a481b8ad610ccf0a0f58cf2c503a8a9ab
[ "MIT" ]
1
2019-06-28T17:51:47.000Z
2019-06-28T17:51:47.000Z
config/config.exs
mbramson/ecto_sanitizer
ee56132a481b8ad610ccf0a0f58cf2c503a8a9ab
[ "MIT" ]
1
2018-11-27T02:34:50.000Z
2018-11-27T02:34:50.000Z
config/config.exs
mbramson/ecto_sanitizer
ee56132a481b8ad610ccf0a0f58cf2c503a8a9ab
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :ecto_sanitizer, key: :value # # and access this configuration in your application as: # # Application.get_env(:ecto_sanitizer, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.741935
73
0.753292
08539f1f94dff5c0b17f54506a7a31f96466d1d0
2,668
ex
Elixir
webrtc/videoroom/lib/videoroom/room.ex
geometerio/membrane_demo
9a3255199af66353716e935b1efd0ba04dec242f
[ "Apache-2.0" ]
null
null
null
webrtc/videoroom/lib/videoroom/room.ex
geometerio/membrane_demo
9a3255199af66353716e935b1efd0ba04dec242f
[ "Apache-2.0" ]
null
null
null
webrtc/videoroom/lib/videoroom/room.ex
geometerio/membrane_demo
9a3255199af66353716e935b1efd0ba04dec242f
[ "Apache-2.0" ]
null
null
null
defmodule Videoroom.Room do @moduledoc false use GenServer require Membrane.Logger def start(opts) do GenServer.start(__MODULE__, [], opts) end def start_link(opts) do GenServer.start_link(__MODULE__, [], opts) end def add_peer_channel(room, peer_channel_pid, peer_id) do GenServer.call(room, {:add_peer_channel, peer_channel_pid, peer_id}) end @impl true def init(opts) do Membrane.Logger.info("Spawning room process: #{inspect(self())}") sfu_options = [ id: opts[:room_id], network_options: [ stun_servers: [ %{server_addr: "stun.l.google.com", server_port: 19_302} ], turn_servers: [], dtls_pkey: Application.get_env(:membrane_videoroom_demo, :dtls_pkey), dtls_cert: Application.get_env(:membrane_videoroom_demo, :dtls_cert) ], payload_and_depayload_tracks?: false ] {:ok, pid} = Membrane.RTC.Engine.start(sfu_options, []) send(pid, {:register, self()}) {:ok, %{sfu_engine: pid, peer_channels: %{}}} end @impl true def handle_call({:add_peer_channel, peer_channel_pid, peer_id}, _from, state) do state = put_in(state, [:peer_channels, peer_id], peer_channel_pid) Process.monitor(peer_channel_pid) {:reply, :ok, state} end @impl true def handle_info({_sfu_engine, {:sfu_media_event, :broadcast, event}}, state) do for {_peer_id, pid} <- state.peer_channels, do: send(pid, {:media_event, event}) {:noreply, state} end @impl true def handle_info({_sfu_engine, {:sfu_media_event, to, event}}, state) do if state.peer_channels[to] != nil do send(state.peer_channels[to], {:media_event, event}) end {:noreply, state} end @impl true def handle_info({sfu_engine, {:new_peer, peer_id, _metadata}}, state) do # get node the peer with peer_id is running on peer_channel_pid = Map.get(state.peer_channels, peer_id) peer_node = node(peer_channel_pid) send(sfu_engine, {:accept_new_peer, peer_id, peer_node}) {:noreply, state} end @impl true def handle_info({_sfu_engine, {:peer_left, _peer_id}}, state) do {:noreply, state} end @impl true def handle_info({:media_event, _from, _event} = msg, state) do send(state.sfu_engine, msg) {:noreply, state} end @impl true def handle_info({:DOWN, _ref, :process, pid, _reason}, state) do {peer_id, _peer_channel_id} = state.peer_channels |> Enum.find(fn {_peer_id, peer_channel_pid} -> peer_channel_pid == pid end) send(state.sfu_engine, {:remove_peer, peer_id}) {_elem, state} = pop_in(state, [:peer_channels, peer_id]) {:noreply, state} end end
28.084211
84
0.672414
0853a9a5a79c7d973e550beda754d0bac2dcdd3a
1,287
ex
Elixir
clients/os_config/lib/google_api/os_config/v1/model/cancel_operation_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/os_config/lib/google_api/os_config/v1/model/cancel_operation_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/os_config/lib/google_api/os_config/v1/model/cancel_operation_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.OSConfig.V1.Model.CancelOperationRequest do @moduledoc """ The request message for Operations.CancelOperation. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.OSConfig.V1.Model.CancelOperationRequest do def decode(value, options) do GoogleApi.OSConfig.V1.Model.CancelOperationRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.OSConfig.V1.Model.CancelOperationRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.642857
82
0.7669
0853b08f126984cff92a3d170582b4220381eaa6
5,719
ex
Elixir
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_entity.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_entity.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_entity.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "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.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity do @moduledoc """ An entity that could be a phrase in the text or a property that belongs to the document. It is a known entity type, such as a person, an organization, or location. ## Attributes * `confidence` (*type:* `number()`, *default:* `nil`) - Optional. Confidence of detected Schema entity. Range [0, 1]. * `id` (*type:* `String.t`, *default:* `nil`) - Optional. Canonical id. This will be a unique value in the entity list for this document. * `mentionId` (*type:* `String.t`, *default:* `nil`) - Optional. Deprecated. Use `id` field instead. * `mentionText` (*type:* `String.t`, *default:* `nil`) - Optional. Text value in the document e.g. `1600 Amphitheatre Pkwy`. If the entity is not present in the document, this field will be empty. * `nonPresent` (*type:* `boolean()`, *default:* `nil`) - Optional. This attribute indicates that the processing didn't actually identify this entity, but a confidence score was assigned that represent the potential that this could be a false negative. A non-present entity should have an empty mention_text and text_anchor. * `normalizedValue` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntityNormalizedValue.t`, *default:* `nil`) - Optional. Normalized entity value. Absent if the extracted value could not be converted or the type (e.g. address) is not supported for certain parsers. This field is also only populated for certain supported document types. * `pageAnchor` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchor.t`, *default:* `nil`) - Optional. Represents the provenance of this entity wrt. the location on the page where it was found. * `properties` (*type:* `list(GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity.t)`, *default:* `nil`) - Optional. Entities can be nested to form a hierarchical data structure representing the content in the document. * `provenance` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentProvenance.t`, *default:* `nil`) - Optional. The history of this annotation. * `redacted` (*type:* `boolean()`, *default:* `nil`) - Optional. Whether the entity will be redacted for de-identification purposes. * `textAnchor` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentTextAnchor.t`, *default:* `nil`) - Optional. Provenance of the entity. Text anchor indexing into the Document.text. * `type` (*type:* `String.t`, *default:* `nil`) - Required. Entity type from a schema e.g. `Address`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :confidence => number() | nil, :id => String.t() | nil, :mentionId => String.t() | nil, :mentionText => String.t() | nil, :nonPresent => boolean() | nil, :normalizedValue => GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntityNormalizedValue.t() | nil, :pageAnchor => GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchor.t() | nil, :properties => list( GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity.t() ) | nil, :provenance => GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentProvenance.t() | nil, :redacted => boolean() | nil, :textAnchor => GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentTextAnchor.t() | nil, :type => String.t() | nil } field(:confidence) field(:id) field(:mentionId) field(:mentionText) field(:nonPresent) field(:normalizedValue, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntityNormalizedValue ) field(:pageAnchor, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchor ) field(:properties, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity, type: :list ) field(:provenance, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentProvenance ) field(:redacted) field(:textAnchor, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentTextAnchor ) field(:type) end defimpl Poison.Decoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity do def decode(value, options) do GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentEntity do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
49.301724
375
0.720231
0853d86d7b9c4a44e5fd582408b3d3d34e63ece4
1,813
ex
Elixir
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/list_liens_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/list_liens_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/list_liens_response.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.CloudResourceManager.V1.Model.ListLiensResponse do @moduledoc """ The response message for Liens.ListLiens. ## Attributes * `liens` (*type:* `list(GoogleApi.CloudResourceManager.V1.Model.Lien.t)`, *default:* `nil`) - A list of Liens. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Token to retrieve the next page of results, or empty if there are no more results in the list. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :liens => list(GoogleApi.CloudResourceManager.V1.Model.Lien.t()), :nextPageToken => String.t() } field(:liens, as: GoogleApi.CloudResourceManager.V1.Model.Lien, type: :list) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.CloudResourceManager.V1.Model.ListLiensResponse do def decode(value, options) do GoogleApi.CloudResourceManager.V1.Model.ListLiensResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudResourceManager.V1.Model.ListLiensResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.54902
136
0.737452
08540a068d3c74c5fa76de2cc50d4fe909623e96
1,155
exs
Elixir
clients/firebase_dynamic_links/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/firebase_dynamic_links/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/firebase_dynamic_links/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :firebase_dynamic_links_api, key: :value # # And access this configuration in your application as: # # Application.get_env(:firebase_dynamic_links_api, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
37.258065
73
0.759307
08541400f11eb3effd29191240b9d6a75aefc75b
253
ex
Elixir
apps/local_hex/lib/local_hex.ex
FrancisMurillo/local_hex_mirror
005ddaeeb1a004bc44fde92c8ede64e8a399f2c5
[ "MIT" ]
5
2021-11-13T13:58:06.000Z
2022-03-26T03:47:57.000Z
apps/local_hex/lib/local_hex.ex
FrancisMurillo/local_hex_mirror
005ddaeeb1a004bc44fde92c8ede64e8a399f2c5
[ "MIT" ]
3
2021-11-16T18:45:45.000Z
2021-12-05T13:58:25.000Z
lib/local_hex.ex
imsoulfly/local_hex_repo
18fca51c44b3dd01d27684877b3c7bc13471f548
[ "Apache-2.0" ]
null
null
null
defmodule LocalHex do @moduledoc """ LocalHex keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
25.3
66
0.754941
085455f6900e2f7cd9dfa0ec89836507327bda1c
854
exs
Elixir
apps/financial_system_web/config/config.exs
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
null
null
null
apps/financial_system_web/config/config.exs
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
2
2021-03-10T03:19:32.000Z
2021-09-02T04:33:17.000Z
apps/financial_system_web/config/config.exs
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
null
null
null
# Since configuration is shared in umbrella projects, this file # should only configure the :financial_system_web application itself # and only for organization purposes. All other config goes to # the umbrella root. use Mix.Config # General application configuration config :financial_system_web, generators: [context_app: false] # Configures the endpoint config :financial_system_web, FinancialSystemWeb.Endpoint, url: [host: "localhost"], secret_key_base: "a4UHrEPL8SxBywYK8B9v/m6o32IRkvlRwyQaINg58iq1ffsm4LK8eWGZNicFs39O", render_errors: [view: FinancialSystemWeb.ErrorView, accepts: ~w(html json)], pubsub: [name: FinancialSystemWeb.PubSub, adapter: Phoenix.PubSub.PG2] # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
40.666667
86
0.800937
08545d25733fb56956c62f32ba43bb5179d1de0a
336
exs
Elixir
priv/repo/migrations/20210322015639_add_oban_jobs_table.exs
byhbt/kwtool
8958a160066e3e4c61806202af2563541f2261e3
[ "MIT" ]
5
2021-12-14T08:18:24.000Z
2022-03-29T10:02:48.000Z
priv/repo/migrations/20210322015639_add_oban_jobs_table.exs
byhbt/kwtool
8958a160066e3e4c61806202af2563541f2261e3
[ "MIT" ]
32
2021-03-21T16:32:18.000Z
2022-03-23T08:00:37.000Z
priv/repo/migrations/20210322015639_add_oban_jobs_table.exs
byhbt/kwtool
8958a160066e3e4c61806202af2563541f2261e3
[ "MIT" ]
1
2021-06-03T17:22:16.000Z
2021-06-03T17:22:16.000Z
defmodule Kwtool.Repo.Migrations.AddObanJobsTable do use Ecto.Migration def up do Oban.Migrations.up() end # We specify `version: 1` in `down`, ensuring that we'll roll all the way back down if # necessary, regardless of which version we've migrated `up` to. def down do Oban.Migrations.down(version: 1) end end
24
88
0.717262
0854bfaf88dd15dcf919149a6639036278484fa1
9,402
ex
Elixir
clients/data_labeling/lib/google_api/data_labeling/v1beta1/model/google_cloud_datalabeling_v1alpha1_label_operation_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/data_labeling/lib/google_api/data_labeling/v1beta1/model/google_cloud_datalabeling_v1alpha1_label_operation_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/data_labeling/lib/google_api/data_labeling/v1beta1/model/google_cloud_datalabeling_v1alpha1_label_operation_metadata.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.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelOperationMetadata do @moduledoc """ Metadata of a labeling operation, such as LabelImage or LabelVideo. Next tag: 23 ## Attributes * `annotatedDataset` (*type:* `String.t`, *default:* `nil`) - Output only. The name of annotated dataset in format "projects/*/datasets/*/annotatedDatasets/*". * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Timestamp when labeling request was created. * `dataset` (*type:* `String.t`, *default:* `nil`) - Output only. The name of dataset to be labeled. "projects/*/datasets/*" * `imageBoundingBoxDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageBoundingBoxOperationMetadata.t`, *default:* `nil`) - Details of label image bounding box operation. * `imageBoundingPolyDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageBoundingPolyOperationMetadata.t`, *default:* `nil`) - Details of label image bounding poly operation. * `imageClassificationDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageClassificationOperationMetadata.t`, *default:* `nil`) - Details of label image classification operation. * `imageOrientedBoundingBoxDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageOrientedBoundingBoxOperationMetadata.t`, *default:* `nil`) - Details of label image oriented bounding box operation. * `imagePolylineDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImagePolylineOperationMetadata.t`, *default:* `nil`) - Details of label image polyline operation. * `imageSegmentationDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageSegmentationOperationMetadata.t`, *default:* `nil`) - Details of label image segmentation operation. * `partialFailures` (*type:* `list(GoogleApi.DataLabeling.V1beta1.Model.GoogleRpcStatus.t)`, *default:* `nil`) - Output only. Partial failures encountered. E.g. single files that couldn't be read. Status details field will contain standard GCP error details. * `progressPercent` (*type:* `integer()`, *default:* `nil`) - Output only. Progress of label operation. Range: [0, 100]. * `textClassificationDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelTextClassificationOperationMetadata.t`, *default:* `nil`) - Details of label text classification operation. * `textEntityExtractionDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelTextEntityExtractionOperationMetadata.t`, *default:* `nil`) - Details of label text entity extraction operation. * `videoClassificationDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoClassificationOperationMetadata.t`, *default:* `nil`) - Details of label video classification operation. * `videoEventDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoEventOperationMetadata.t`, *default:* `nil`) - Details of label video event operation. * `videoObjectDetectionDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoObjectDetectionOperationMetadata.t`, *default:* `nil`) - Details of label video object detection operation. * `videoObjectTrackingDetails` (*type:* `GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoObjectTrackingOperationMetadata.t`, *default:* `nil`) - Details of label video object tracking operation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :annotatedDataset => String.t(), :createTime => DateTime.t(), :dataset => String.t(), :imageBoundingBoxDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageBoundingBoxOperationMetadata.t(), :imageBoundingPolyDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageBoundingPolyOperationMetadata.t(), :imageClassificationDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageClassificationOperationMetadata.t(), :imageOrientedBoundingBoxDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageOrientedBoundingBoxOperationMetadata.t(), :imagePolylineDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImagePolylineOperationMetadata.t(), :imageSegmentationDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageSegmentationOperationMetadata.t(), :partialFailures => list(GoogleApi.DataLabeling.V1beta1.Model.GoogleRpcStatus.t()), :progressPercent => integer(), :textClassificationDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelTextClassificationOperationMetadata.t(), :textEntityExtractionDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelTextEntityExtractionOperationMetadata.t(), :videoClassificationDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoClassificationOperationMetadata.t(), :videoEventDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoEventOperationMetadata.t(), :videoObjectDetectionDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoObjectDetectionOperationMetadata.t(), :videoObjectTrackingDetails => GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoObjectTrackingOperationMetadata.t() } field(:annotatedDataset) field(:createTime, as: DateTime) field(:dataset) field(:imageBoundingBoxDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageBoundingBoxOperationMetadata ) field(:imageBoundingPolyDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageBoundingPolyOperationMetadata ) field(:imageClassificationDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageClassificationOperationMetadata ) field(:imageOrientedBoundingBoxDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageOrientedBoundingBoxOperationMetadata ) field(:imagePolylineDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImagePolylineOperationMetadata ) field(:imageSegmentationDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelImageSegmentationOperationMetadata ) field(:partialFailures, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleRpcStatus, type: :list) field(:progressPercent) field(:textClassificationDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelTextClassificationOperationMetadata ) field(:textEntityExtractionDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelTextEntityExtractionOperationMetadata ) field(:videoClassificationDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoClassificationOperationMetadata ) field(:videoEventDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoEventOperationMetadata ) field(:videoObjectDetectionDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoObjectDetectionOperationMetadata ) field(:videoObjectTrackingDetails, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelVideoObjectTrackingOperationMetadata ) end defimpl Poison.Decoder, for: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelOperationMetadata do def decode(value, options) do GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelOperationMetadata.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1alpha1LabelOperationMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
58.397516
262
0.787811
0854c5fe3f5a2af99cc272936df6d6df6365740a
320
ex
Elixir
lib/adaptable_costs_evaluator_web/views/role_view.ex
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
null
null
null
lib/adaptable_costs_evaluator_web/views/role_view.ex
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
4
2021-12-07T12:26:50.000Z
2021-12-30T14:17:25.000Z
lib/adaptable_costs_evaluator_web/views/role_view.ex
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
null
null
null
defmodule AdaptableCostsEvaluatorWeb.RoleView do use AdaptableCostsEvaluatorWeb, :view alias AdaptableCostsEvaluatorWeb.RoleView def render("index.json", %{roles: roles}) do %{data: render_many(roles, RoleView, "role.json")} end def render("role.json", %{role: role}) do %{type: role.type} end end
24.615385
54
0.721875
0854c7158411d74555d96f46c1ff36c47a773636
46,128
ex
Elixir
clients/cloud_asset/lib/google_api/cloud_asset/v1/api/v1.ex
corp-momenti/elixir-google-api
fe1580e305789ab2ca0741791b8ffe924bd3240c
[ "Apache-2.0" ]
null
null
null
clients/cloud_asset/lib/google_api/cloud_asset/v1/api/v1.ex
corp-momenti/elixir-google-api
fe1580e305789ab2ca0741791b8ffe924bd3240c
[ "Apache-2.0" ]
null
null
null
clients/cloud_asset/lib/google_api/cloud_asset/v1/api/v1.ex
corp-momenti/elixir-google-api
fe1580e305789ab2ca0741791b8ffe924bd3240c
[ "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.CloudAsset.V1.Api.V1 do @moduledoc """ API calls for all endpoints tagged `V1`. """ alias GoogleApi.CloudAsset.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Analyzes IAM policies to answer which identities have what accesses on which resources. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `analysisQuery.scope`. Required. The relative name of the root asset. Only resources and IAM policies within the scope will be analyzed. This can only be an organization number (such as "organizations/123"), a folder number (such as "folders/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"). To know how to get organization id, visit [here ](https://cloud.google.com/resource-manager/docs/creating-managing-organization#retrieving_your_organization_id). To know how to get folder or project id, visit [here ](https://cloud.google.com/resource-manager/docs/creating-managing-folders#viewing_or_listing_folders_and_projects). * `v1_id1` (*type:* `String.t`) - Part of `analysisQuery.scope`. See documentation of `v1Id`. * `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"). * `:"analysisQuery.accessSelector.permissions"` (*type:* `list(String.t)`) - Optional. The permissions to appear in result. * `:"analysisQuery.accessSelector.roles"` (*type:* `list(String.t)`) - Optional. The roles to appear in result. * `:"analysisQuery.conditionContext.accessTime"` (*type:* `DateTime.t`) - The hypothetical access timestamp to evaluate IAM conditions. Note that this value must not be earlier than the current time; otherwise, an INVALID_ARGUMENT error will be returned. * `:"analysisQuery.identitySelector.identity"` (*type:* `String.t`) - Required. The identity appear in the form of principals in [IAM policy binding](https://cloud.google.com/iam/reference/rest/v1/Binding). The examples of supported forms are: "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com". Notice that wildcard characters (such as * and ?) are not supported. You must give a specific identity. * `:"analysisQuery.options.analyzeServiceAccountImpersonation"` (*type:* `boolean()`) - Optional. If true, the response will include access analysis from identities to resources via service account impersonation. This is a very expensive operation, because many derived queries will be executed. We highly recommend you use AssetService.AnalyzeIamPolicyLongrunning rpc instead. For example, if the request analyzes for which resources user A has permission P, and there's an IAM policy states user A has iam.serviceAccounts.getAccessToken permission to a service account SA, and there's another IAM policy states service account SA has permission P to a GCP folder F, then user A potentially has access to the GCP folder F. And those advanced analysis results will be included in AnalyzeIamPolicyResponse.service_account_impersonation_analysis. Another example, if the request analyzes for who has permission P to a GCP folder F, and there's an IAM policy states user A has iam.serviceAccounts.actAs permission to a service account SA, and there's another IAM policy states service account SA has permission P to the GCP folder F, then user A potentially has access to the GCP folder F. And those advanced analysis results will be included in AnalyzeIamPolicyResponse.service_account_impersonation_analysis. Default is false. * `:"analysisQuery.options.expandGroups"` (*type:* `boolean()`) - Optional. If true, the identities section of the result will expand any Google groups appearing in an IAM policy binding. If IamPolicyAnalysisQuery.identity_selector is specified, the identity in the result will be determined by the selector, and this flag is not allowed to set. Default is false. * `:"analysisQuery.options.expandResources"` (*type:* `boolean()`) - Optional. If true and IamPolicyAnalysisQuery.resource_selector is not specified, the resource section of the result will expand any resource attached to an IAM policy to include resources lower in the resource hierarchy. For example, if the request analyzes for which resources user A has permission P, and the results include an IAM policy with P on a GCP folder, the results will also include resources in that folder with permission P. If true and IamPolicyAnalysisQuery.resource_selector is specified, the resource section of the result will expand the specified resource to include resources lower in the resource hierarchy. Only project or lower resources are supported. Folder and organization resource cannot be used together with this option. For example, if the request analyzes for which users have permission P on a GCP project with this option enabled, the results will include all users who have permission P on that project or any lower resource. Default is false. * `:"analysisQuery.options.expandRoles"` (*type:* `boolean()`) - Optional. If true, the access section of result will expand any roles appearing in IAM policy bindings to include their permissions. If IamPolicyAnalysisQuery.access_selector is specified, the access section of the result will be determined by the selector, and this flag is not allowed to set. Default is false. * `:"analysisQuery.options.outputGroupEdges"` (*type:* `boolean()`) - Optional. If true, the result will output the relevant membership relationships between groups and other groups, and between groups and principals. Default is false. * `:"analysisQuery.options.outputResourceEdges"` (*type:* `boolean()`) - Optional. If true, the result will output the relevant parent/child relationships between resources. Default is false. * `:"analysisQuery.resourceSelector.fullResourceName"` (*type:* `String.t`) - Required. The [full resource name] (https://cloud.google.com/asset-inventory/docs/resource-name-format) of a resource of [supported resource types](https://cloud.google.com/asset-inventory/docs/supported-asset-types#analyzable_asset_types). * `:executionTimeout` (*type:* `String.t`) - Optional. Amount of time executable has to complete. See JSON representation of [Duration](https://developers.google.com/protocol-buffers/docs/proto3#json). If this field is set with a value less than the RPC deadline, and the execution of your query hasn't finished in the specified execution timeout, you will get a response with partial result. Otherwise, your query's execution will continue until the RPC deadline. If it's not finished until then, you will get a DEADLINE_EXCEEDED error. Default is empty. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.AnalyzeIamPolicyResponse{}}` on success * `{:error, info}` on failure """ @spec cloudasset_analyze_iam_policy( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.CloudAsset.V1.Model.AnalyzeIamPolicyResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_analyze_iam_policy(connection, v1_id, v1_id1, 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, :"analysisQuery.accessSelector.permissions" => :query, :"analysisQuery.accessSelector.roles" => :query, :"analysisQuery.conditionContext.accessTime" => :query, :"analysisQuery.identitySelector.identity" => :query, :"analysisQuery.options.analyzeServiceAccountImpersonation" => :query, :"analysisQuery.options.expandGroups" => :query, :"analysisQuery.options.expandResources" => :query, :"analysisQuery.options.expandRoles" => :query, :"analysisQuery.options.outputGroupEdges" => :query, :"analysisQuery.options.outputResourceEdges" => :query, :"analysisQuery.resourceSelector.fullResourceName" => :query, :executionTimeout => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{v1Id}/{v1Id1}:analyzeIamPolicy", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.AnalyzeIamPolicyResponse{}] ) end @doc """ Analyzes IAM policies asynchronously to answer which identities have what accesses on which resources, and writes the analysis results to a Google Cloud Storage or a BigQuery destination. For Cloud Storage destination, the output format is the JSON format that represents a AnalyzeIamPolicyResponse. This method implements the google.longrunning.Operation, which allows you to track the operation status. We recommend intervals of at least 2 seconds with exponential backoff retry to poll the operation result. The metadata contains the metadata for the long-running operation. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `analysisQuery.scope`. Required. The relative name of the root asset. Only resources and IAM policies within the scope will be analyzed. This can only be an organization number (such as "organizations/123"), a folder number (such as "folders/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"). To know how to get organization id, visit [here ](https://cloud.google.com/resource-manager/docs/creating-managing-organization#retrieving_your_organization_id). To know how to get folder or project id, visit [here ](https://cloud.google.com/resource-manager/docs/creating-managing-folders#viewing_or_listing_folders_and_projects). * `v1_id1` (*type:* `String.t`) - Part of `analysisQuery.scope`. See documentation of `v1Id`. * `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.CloudAsset.V1.Model.AnalyzeIamPolicyLongrunningRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec cloudasset_analyze_iam_policy_longrunning( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.CloudAsset.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_analyze_iam_policy_longrunning( connection, v1_id, v1_id1, 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/{v1Id}/{v1Id1}:analyzeIamPolicyLongrunning", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.Operation{}]) end @doc """ Analyze moving a resource to a specified destination without kicking off the actual move. The analysis is best effort depending on the user's permissions of viewing different hierarchical policies and configurations. The policies and configuration are subject to change before the actual resource migration takes place. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `resource`. Required. Name of the resource to perform the analysis against. Only GCP Project are supported as of today. Hence, this can only be Project ID (such as "projects/my-project-id") or a Project Number (such as "projects/12345"). * `v1_id1` (*type:* `String.t`) - Part of `resource`. See documentation of `v1Id`. * `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"). * `:destinationParent` (*type:* `String.t`) - Required. Name of the GCP Folder or Organization to reparent the target resource. The analysis will be performed against hypothetically moving the resource to this specified desitination parent. This can only be a Folder number (such as "folders/123") or an Organization number (such as "organizations/123"). * `:view` (*type:* `String.t`) - Analysis view indicating what information should be included in the analysis response. If unspecified, the default view is FULL. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.AnalyzeMoveResponse{}}` on success * `{:error, info}` on failure """ @spec cloudasset_analyze_move(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.CloudAsset.V1.Model.AnalyzeMoveResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_analyze_move(connection, v1_id, v1_id1, 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, :destinationParent => :query, :view => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{v1Id}/{v1Id1}:analyzeMove", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.AnalyzeMoveResponse{}]) end @doc """ Batch gets the update history of assets that overlap a time window. For IAM_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. Otherwise, this API outputs history with asset in both non-delete or deleted status. If a specified asset does not exist, this API returns an INVALID_ARGUMENT error. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `parent`. Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345"). * `v1_id1` (*type:* `String.t`) - Part of `parent`. See documentation of `v1Id`. * `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"). * `:assetNames` (*type:* `list(String.t)`) - A list of the full names of the assets. See: https://cloud.google.com/asset-inventory/docs/resource-name-format Example: `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request. * `:contentType` (*type:* `String.t`) - Optional. The content type. * `:"readTimeWindow.endTime"` (*type:* `DateTime.t`) - End time of the time window (inclusive). If not specified, the current timestamp is used instead. * `:"readTimeWindow.startTime"` (*type:* `DateTime.t`) - Start time of the time window (exclusive). * `:relationshipTypes` (*type:* `list(String.t)`) - Optional. A list of relationship types to output, for example: `INSTANCE_TO_INSTANCEGROUP`. This field should only be specified if content_type=RELATIONSHIP. * If specified: it outputs specified relationships' history on the [asset_names]. It returns an error if any of the [relationship_types] doesn't belong to the supported relationship types of the [asset_names] or if any of the [asset_names]'s types doesn't belong to the source types of the [relationship_types]. * Otherwise: it outputs the supported relationships' history on the [asset_names] or returns an error if any of the [asset_names]'s types has no relationship support. See [Introduction to Cloud Asset Inventory](https://cloud.google.com/asset-inventory/docs/overview) for all supported asset types and relationship types. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.BatchGetAssetsHistoryResponse{}}` on success * `{:error, info}` on failure """ @spec cloudasset_batch_get_assets_history( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.CloudAsset.V1.Model.BatchGetAssetsHistoryResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_batch_get_assets_history( connection, v1_id, v1_id1, 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, :assetNames => :query, :contentType => :query, :"readTimeWindow.endTime" => :query, :"readTimeWindow.startTime" => :query, :relationshipTypes => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{v1Id}/{v1Id1}:batchGetAssetsHistory", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.BatchGetAssetsHistoryResponse{}] ) end @doc """ Exports assets with time and resource types to a given Cloud Storage location/BigQuery table. For Cloud Storage location destinations, the output format is newline-delimited JSON. Each line represents a google.cloud.asset.v1.Asset in the JSON format; for BigQuery table destinations, the output table stores the fields in asset Protobuf as columns. This API implements the google.longrunning.Operation API, which allows you to keep track of the export. We recommend intervals of at least 2 seconds with exponential retry to poll the export operation result. For regular-size resource parent, the export operation usually finishes within 5 minutes. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `parent`. Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123"). * `v1_id1` (*type:* `String.t`) - Part of `parent`. See documentation of `v1Id`. * `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.CloudAsset.V1.Model.ExportAssetsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec cloudasset_export_assets(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.CloudAsset.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_export_assets(connection, v1_id, v1_id1, 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/{v1Id}/{v1Id1}:exportAssets", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.Operation{}]) end @doc """ Searches all IAM policies within the specified scope, such as a project, folder, or organization. The caller must be granted the `cloudasset.assets.searchAllIamPolicies` permission on the desired scope, otherwise the request will be rejected. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `scope`. Required. A scope can be a project, a folder, or an organization. The search is limited to the IAM policies within the `scope`. The caller must be granted the [`cloudasset.assets.searchAllIamPolicies`](https://cloud.google.com/asset-inventory/docs/access-control#required_permissions) permission on the desired scope. The allowed values are: * projects/{PROJECT_ID} (e.g., "projects/foo-bar") * projects/{PROJECT_NUMBER} (e.g., "projects/12345678") * folders/{FOLDER_NUMBER} (e.g., "folders/1234567") * organizations/{ORGANIZATION_NUMBER} (e.g., "organizations/123456") * `v1_id1` (*type:* `String.t`) - Part of `scope`. See documentation of `v1Id`. * `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"). * `:assetTypes` (*type:* `list(String.t)`) - Optional. A list of asset types that the IAM policies are attached to. If empty, it will search the IAM policies that are attached to all the [searchable asset types](https://cloud.google.com/asset-inventory/docs/supported-asset-types#searchable_asset_types). Regular expressions are also supported. For example: * "compute.googleapis.com.*" snapshots IAM policies attached to asset type starts with "compute.googleapis.com". * ".*Instance" snapshots IAM policies attached to asset type ends with "Instance". * ".*Instance.*" snapshots IAM policies attached to asset type contains "Instance". See [RE2](https://github.com/google/re2/wiki/Syntax) for all supported regular expression syntax. If the regular expression does not match any supported asset type, an INVALID_ARGUMENT error will be returned. * `:orderBy` (*type:* `String.t`) - Optional. A comma-separated list of fields specifying the sorting order of the results. The default order is ascending. Add " DESC" after the field name to indicate descending order. Redundant space characters are ignored. Example: "assetType DESC, resource". Only singular primitive fields in the response are sortable: * resource * assetType * project All the other fields such as repeated fields (e.g., `folders`) and non-primitive fields (e.g., `policy`) are not supported. * `:pageSize` (*type:* `integer()`) - Optional. The page size for search result pagination. Page size is capped at 500 even if a larger value is given. If set to zero, server will pick an appropriate default. Returned results may be fewer than requested. When this happens, there could be more results as long as `next_page_token` is returned. * `:pageToken` (*type:* `String.t`) - Optional. If present, retrieve the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of all other method parameters must be identical to those in the previous call. * `:query` (*type:* `String.t`) - Optional. The query statement. See [how to construct a query](https://cloud.google.com/asset-inventory/docs/searching-iam-policies#how_to_construct_a_query) for more information. If not specified or empty, it will search all the IAM policies within the specified `scope`. Note that the query string is compared against each Cloud IAM policy binding, including its principals, roles, and Cloud IAM conditions. The returned Cloud IAM policies will only contain the bindings that match your query. To learn more about the IAM policy structure, see [IAM policy doc](https://cloud.google.com/iam/docs/policies#structure). Examples: * `policy:amy@gmail.com` to find IAM policy bindings that specify user "amy@gmail.com". * `policy:roles/compute.admin` to find IAM policy bindings that specify the Compute Admin role. * `policy:comp*` to find IAM policy bindings that contain "comp" as a prefix of any word in the binding. * `policy.role.permissions:storage.buckets.update` to find IAM policy bindings that specify a role containing "storage.buckets.update" permission. Note that if callers don't have `iam.roles.get` access to a role's included permissions, policy bindings that specify this role will be dropped from the search results. * `policy.role.permissions:upd*` to find IAM policy bindings that specify a role containing "upd" as a prefix of any word in the role permission. Note that if callers don't have `iam.roles.get` access to a role's included permissions, policy bindings that specify this role will be dropped from the search results. * `resource:organizations/123456` to find IAM policy bindings that are set on "organizations/123456". * `resource=//cloudresourcemanager.googleapis.com/projects/myproject` to find IAM policy bindings that are set on the project named "myproject". * `Important` to find IAM policy bindings that contain "Important" as a word in any of the searchable fields (except for the included permissions). * `resource:(instance1 OR instance2) policy:amy` to find IAM policy bindings that are set on resources "instance1" or "instance2" and also specify user "amy". * `roles:roles/compute.admin` to find IAM policy bindings that specify the Compute Admin role. * `memberTypes:user` to find IAM policy bindings that contain the principal type "user". * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.SearchAllIamPoliciesResponse{}}` on success * `{:error, info}` on failure """ @spec cloudasset_search_all_iam_policies( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.CloudAsset.V1.Model.SearchAllIamPoliciesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_search_all_iam_policies( connection, v1_id, v1_id1, 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, :assetTypes => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query, :query => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{v1Id}/{v1Id1}:searchAllIamPolicies", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.SearchAllIamPoliciesResponse{}] ) end @doc """ Searches all Cloud resources within the specified scope, such as a project, folder, or organization. The caller must be granted the `cloudasset.assets.searchAllResources` permission on the desired scope, otherwise the request will be rejected. ## Parameters * `connection` (*type:* `GoogleApi.CloudAsset.V1.Connection.t`) - Connection to server * `v1_id` (*type:* `String.t`) - Part of `scope`. Required. A scope can be a project, a folder, or an organization. The search is limited to the resources within the `scope`. The caller must be granted the [`cloudasset.assets.searchAllResources`](https://cloud.google.com/asset-inventory/docs/access-control#required_permissions) permission on the desired scope. The allowed values are: * projects/{PROJECT_ID} (e.g., "projects/foo-bar") * projects/{PROJECT_NUMBER} (e.g., "projects/12345678") * folders/{FOLDER_NUMBER} (e.g., "folders/1234567") * organizations/{ORGANIZATION_NUMBER} (e.g., "organizations/123456") * `v1_id1` (*type:* `String.t`) - Part of `scope`. See documentation of `v1Id`. * `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"). * `:assetTypes` (*type:* `list(String.t)`) - Optional. A list of asset types that this request searches for. If empty, it will search all the [searchable asset types](https://cloud.google.com/asset-inventory/docs/supported-asset-types#searchable_asset_types). Regular expressions are also supported. For example: * "compute.googleapis.com.*" snapshots resources whose asset type starts with "compute.googleapis.com". * ".*Instance" snapshots resources whose asset type ends with "Instance". * ".*Instance.*" snapshots resources whose asset type contains "Instance". See [RE2](https://github.com/google/re2/wiki/Syntax) for all supported regular expression syntax. If the regular expression does not match any supported asset type, an INVALID_ARGUMENT error will be returned. * `:orderBy` (*type:* `String.t`) - Optional. A comma-separated list of fields specifying the sorting order of the results. The default order is ascending. Add " DESC" after the field name to indicate descending order. Redundant space characters are ignored. Example: "location DESC, name". Only singular primitive fields in the response are sortable: * name * assetType * project * displayName * description * location * kmsKey * createTime * updateTime * state * parentFullResourceName * parentAssetType All the other fields such as repeated fields (e.g., `networkTags`), map fields (e.g., `labels`) and struct fields (e.g., `additionalAttributes`) are not supported. * `:pageSize` (*type:* `integer()`) - Optional. The page size for search result pagination. Page size is capped at 500 even if a larger value is given. If set to zero, server will pick an appropriate default. Returned results may be fewer than requested. When this happens, there could be more results as long as `next_page_token` is returned. * `:pageToken` (*type:* `String.t`) - Optional. If present, then retrieve the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of all other method parameters, must be identical to those in the previous call. * `:query` (*type:* `String.t`) - Optional. The query statement. See [how to construct a query](https://cloud.google.com/asset-inventory/docs/searching-resources#how_to_construct_a_query) for more information. If not specified or empty, it will search all the resources within the specified `scope`. Examples: * `name:Important` to find Cloud resources whose name contains "Important" as a word. * `name=Important` to find the Cloud resource whose name is exactly "Important". * `displayName:Impor*` to find Cloud resources whose display name contains "Impor" as a prefix of any word in the field. * `location:us-west*` to find Cloud resources whose location contains both "us" and "west" as prefixes. * `labels:prod` to find Cloud resources whose labels contain "prod" as a key or value. * `labels.env:prod` to find Cloud resources that have a label "env" and its value is "prod". * `labels.env:*` to find Cloud resources that have a label "env". * `kmsKey:key` to find Cloud resources encrypted with a customer-managed encryption key whose name contains the word "key". * `state:ACTIVE` to find Cloud resources whose state contains "ACTIVE" as a word. * `NOT state:ACTIVE` to find Cloud resources whose state doesn't contain "ACTIVE" as a word. * `createTime<1609459200` to find Cloud resources that were created before "2021-01-01 00:00:00 UTC". 1609459200 is the epoch timestamp of "2021-01-01 00:00:00 UTC" in seconds. * `updateTime>1609459200` to find Cloud resources that were updated after "2021-01-01 00:00:00 UTC". 1609459200 is the epoch timestamp of "2021-01-01 00:00:00 UTC" in seconds. * `Important` to find Cloud resources that contain "Important" as a word in any of the searchable fields. * `Impor*` to find Cloud resources that contain "Impor" as a prefix of any word in any of the searchable fields. * `Important location:(us-west1 OR global)` to find Cloud resources that contain "Important" as a word in any of the searchable fields and are also located in the "us-west1" region or the "global" location. * `:readMask` (*type:* `String.t`) - Optional. A comma-separated list of fields specifying which fields to be returned in ResourceSearchResult. Only '*' or combination of top level fields can be specified. Field names of both snake_case and camelCase are supported. Examples: `"*"`, `"name,location"`, `"name,versionedResources"`. The read_mask paths must be valid field paths listed but not limited to (both snake_case and camelCase are supported): * name * assetType * project * displayName * description * location * labels * networkTags * kmsKey * createTime * updateTime * state * additionalAttributes * versionedResources If read_mask is not specified, all fields except versionedResources will be returned. If only '*' is specified, all fields including versionedResources will be returned. Any invalid field path will trigger INVALID_ARGUMENT error. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.CloudAsset.V1.Model.SearchAllResourcesResponse{}}` on success * `{:error, info}` on failure """ @spec cloudasset_search_all_resources( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.CloudAsset.V1.Model.SearchAllResourcesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def cloudasset_search_all_resources( connection, v1_id, v1_id1, 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, :assetTypes => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query, :query => :query, :readMask => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{v1Id}/{v1Id1}:searchAllResources", %{ "v1Id" => URI.encode(v1_id, &URI.char_unreserved?/1), "v1Id1" => URI.encode(v1_id1, &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.CloudAsset.V1.Model.SearchAllResourcesResponse{}] ) end end
78.44898
2,326
0.688064
085506258eb51d68257c33a4afd43d773d8c4995
2,674
exs
Elixir
exercism/elixir/all-your-base/test/all_your_base_test.exs
Tyyagoo/studies
f8fcc3a539cfb6d04a149174c88bf2208e220b96
[ "Unlicense" ]
null
null
null
exercism/elixir/all-your-base/test/all_your_base_test.exs
Tyyagoo/studies
f8fcc3a539cfb6d04a149174c88bf2208e220b96
[ "Unlicense" ]
null
null
null
exercism/elixir/all-your-base/test/all_your_base_test.exs
Tyyagoo/studies
f8fcc3a539cfb6d04a149174c88bf2208e220b96
[ "Unlicense" ]
null
null
null
defmodule AllYourBaseTest do use ExUnit.Case test "convert single bit one to decimal" do assert AllYourBase.convert([1], 2, 10) == {:ok, [1]} end test "convert binary to single decimal" do assert AllYourBase.convert([1, 0, 1], 2, 10) == {:ok, [5]} end test "convert single decimal to binary" do assert AllYourBase.convert([5], 10, 2) == {:ok, [1, 0, 1]} end test "convert binary to multiple decimal" do assert AllYourBase.convert([1, 0, 1, 0, 1, 0], 2, 10) == {:ok, [4, 2]} end test "convert decimal to binary" do assert AllYourBase.convert([4, 2], 10, 2) == {:ok, [1, 0, 1, 0, 1, 0]} end test "convert trinary to hexadecimal" do assert AllYourBase.convert([1, 1, 2, 0], 3, 16) == {:ok, [2, 10]} end test "convert hexadecimal to trinary" do assert AllYourBase.convert([2, 10], 16, 3) == {:ok, [1, 1, 2, 0]} end test "convert 15-bit integer" do assert AllYourBase.convert([3, 46, 60], 97, 73) == {:ok, [6, 10, 45]} end test "convert empty list" do assert AllYourBase.convert([], 2, 10) == {:ok, [0]} end test "convert single zero" do assert AllYourBase.convert([0], 10, 2) == {:ok, [0]} end test "convert multiple zeros" do assert AllYourBase.convert([0, 0, 0], 10, 2) == {:ok, [0]} end test "convert leading zeros" do assert AllYourBase.convert([0, 6, 0], 7, 10) == {:ok, [4, 2]} end test "convert first base is one" do assert AllYourBase.convert([0], 1, 10) == {:error, "input base must be >= 2"} end test "convert first base is zero" do assert AllYourBase.convert([], 0, 10) == {:error, "input base must be >= 2"} end test "convert first base is negative" do assert AllYourBase.convert([1], -2, 10) == {:error, "input base must be >= 2"} end test "convert negative digit" do assert AllYourBase.convert([1, -1, 1, 0, 1, 0], 2, 10) == {:error, "all digits must be >= 0 and < input base"} end test "convert invalid positive digit" do assert AllYourBase.convert([1, 2, 1, 0, 1, 0], 2, 10) == {:error, "all digits must be >= 0 and < input base"} end test "convert second base is one" do assert AllYourBase.convert([1, 0, 1, 0, 1, 0], 2, 1) == {:error, "output base must be >= 2"} end test "convert second base is zero" do assert AllYourBase.convert([7], 10, 0) == {:error, "output base must be >= 2"} end test "convert second base is negative" do assert AllYourBase.convert([1], 2, -7) == {:error, "output base must be >= 2"} end test "convert both bases are negative" do assert AllYourBase.convert([1], -2, -7) == {:error, "output base must be >= 2"} end end
29.711111
96
0.605086
0855204112732cf6908bdc4b9d177dc208decf85
334
ex
Elixir
lib/automata/core/automaton/types/graphical_models/behavior_tree/config/bt_config.ex
venomnert/automata
26b9bf3cb57fa8bc152fac8992ddcfe07c6e07a9
[ "Apache-2.0" ]
null
null
null
lib/automata/core/automaton/types/graphical_models/behavior_tree/config/bt_config.ex
venomnert/automata
26b9bf3cb57fa8bc152fac8992ddcfe07c6e07a9
[ "Apache-2.0" ]
null
null
null
lib/automata/core/automaton/types/graphical_models/behavior_tree/config/bt_config.ex
venomnert/automata
26b9bf3cb57fa8bc152fac8992ddcfe07c6e07a9
[ "Apache-2.0" ]
null
null
null
defmodule Automaton.Types.BT.Config do alias Automaton.Types.BT.CompositeServer alias Automaton.Types.BT.ComponentServer defstruct node_type: nil, c_types: CompositeServer.types(), cn_types: ComponentServer.types(), allowed_node_types: CompositeServer.types() ++ ComponentServer.types() end
33.4
82
0.724551
085528915af74f2fb901c20365b7308ff356444e
1,129
exs
Elixir
apps/ping_http/config/config.exs
insprac/ping
26943f171b2df6f009a0c3241449a988d4636c96
[ "MIT" ]
null
null
null
apps/ping_http/config/config.exs
insprac/ping
26943f171b2df6f009a0c3241449a988d4636c96
[ "MIT" ]
null
null
null
apps/ping_http/config/config.exs
insprac/ping
26943f171b2df6f009a0c3241449a988d4636c96
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :ping_http, key: :value # # and access this configuration in your application as: # # Application.get_env(:ping_http, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.419355
73
0.751107
085539ed3fc33203b62e4d21279245d055b5dced
2,133
ex
Elixir
clients/vault/lib/google_api/vault/v1/model/cloud_storage_file.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/cloud_storage_file.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/cloud_storage_file.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.Vault.V1.Model.CloudStorageFile do @moduledoc """ An export file on cloud storage ## Attributes * `bucketName` (*type:* `String.t`, *default:* `nil`) - The cloud storage bucket name of this export file. Can be used in cloud storage JSON/XML API, but not to list the bucket contents. Instead, you can <a href="https://cloud.google.com/storage/docs/json_api/v1/objects/get"> get individual export files</a> by object name. * `md5Hash` (*type:* `String.t`, *default:* `nil`) - The md5 hash of the file. * `objectName` (*type:* `String.t`, *default:* `nil`) - The cloud storage object name of this export file. Can be used in cloud storage JSON/XML API. * `size` (*type:* `String.t`, *default:* `nil`) - The size of the export file. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :bucketName => String.t(), :md5Hash => String.t(), :objectName => String.t(), :size => String.t() } field(:bucketName) field(:md5Hash) field(:objectName) field(:size) end defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.CloudStorageFile do def decode(value, options) do GoogleApi.Vault.V1.Model.CloudStorageFile.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.CloudStorageFile do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.967213
110
0.693858
085554fd050f161cf99d594697810ffd091eabf1
15,238
exs
Elixir
lib/elixir/test/elixir/code_formatter/integration_test.exs
lanodan/elixir
10ae66cda989f324bf76c402473fd5661a459100
[ "Apache-2.0" ]
1
2020-12-18T19:20:37.000Z
2020-12-18T19:20:37.000Z
lib/elixir/test/elixir/code_formatter/integration_test.exs
lanodan/elixir
10ae66cda989f324bf76c402473fd5661a459100
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/code_formatter/integration_test.exs
lanodan/elixir
10ae66cda989f324bf76c402473fd5661a459100
[ "Apache-2.0" ]
null
null
null
Code.require_file("../test_helper.exs", __DIR__) defmodule Code.Formatter.IntegrationTest do use ExUnit.Case, async: true import CodeFormatterHelpers test "empty documents" do assert_format " ", "" assert_format "\n", "" assert_format ";", "" end test "function with multiple calls and case" do assert_same """ def equivalent(string1, string2) when is_binary(string1) and is_binary(string2) do quoted1 = Code.string_to_quoted!(string1) quoted2 = Code.string_to_quoted!(string2) case not_equivalent(quoted1, quoted2) do {left, right} -> {:error, left, right} nil -> :ok end end """ end test "function with long pipeline" do assert_same ~S""" def to_algebra!(string, opts \\ []) when is_binary(string) and is_list(opts) do string |> Code.string_to_quoted!(wrap_literals_in_blocks: true, unescape: false) |> block_to_algebra(state(opts)) |> elem(0) end """ end test "case with multiple multi-line arrows" do assert_same ~S""" case meta[:format] do :list_heredoc -> string = list |> List.to_string() |> escape_string(:heredoc) {@single_heredoc |> line(string) |> concat(@single_heredoc) |> force_unfit(), state} :charlist -> string = list |> List.to_string() |> escape_string(@single_quote) {@single_quote |> concat(string) |> concat(@single_quote), state} _other -> list_to_algebra(list, state) end """ end test "function with long guards" do assert_same """ defp module_attribute_read?({:@, _, [{var, _, var_context}]}) when is_atom(var) and is_atom(var_context) do Code.Identifier.classify(var) == :callable_local end """ end test "anonymous function with single clause and blocks" do assert_same """ {args_doc, state} = Enum.reduce(args, {[], state}, fn quoted, {acc, state} -> {doc, state} = quoted_to_algebra(quoted, :block, state) doc = doc |> concat(nest(break(""), :reset)) |> group() {[doc | acc], state} end) """ end test "anonymous function with long single clause and blocks" do assert_same """ {function_count, call_count, total_time} = Enum.reduce(call_results, {0, 0, 0}, fn {_, {count, time}}, {function_count, call_count, total_time} -> {function_count + 1, call_count + count, total_time + time} end) """ end test "cond with long clause args" do assert_same """ cond do parent_prec == prec and parent_assoc == side -> binary_op_to_algebra(op, op_string, left, right, context, state, op_info, nesting) parent_op in @required_parens_on_binary_operands or parent_prec > prec or (parent_prec == prec and parent_assoc != side) -> {operand, state} = binary_op_to_algebra(op, op_string, left, right, context, state, op_info, 2) {concat(concat("(", nest(operand, 1)), ")"), state} true -> binary_op_to_algebra(op, op_string, left, right, context, state, op_info, 2) end """ end test "type with multiple |" do assert_same """ @type t :: binary | :doc_nil | :doc_line | doc_string | doc_cons | doc_nest | doc_break | doc_group | doc_color | doc_force | doc_cancel """ end test "spec with when keywords and |" do assert_same """ @spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend when dest: pid | port | atom | {atom, node}, msg: any, option: :noconnect | :nosuspend """ assert_same """ @spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend when dest: pid | port | atom | {atom, node} | and_a_really_long_type_to_force_a_line_break | followed_by_another_really_long_type """ assert_same """ @callback get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data} when get_value: var, data: container """ end test "spec with multiple keys on type" do assert_same """ @spec foo(%{(String.t() | atom) => any}) :: any """ end test "multiple whens with new lines" do assert_same """ def sleep(timeout) when is_integer(timeout) and timeout >= 0 when timeout == :infinity do receive after: (timeout -> :ok) end """ end test "function with operator and pipeline" do assert_same """ defp apply_next_break_fits?({fun, meta, args}) when is_atom(fun) and is_list(args) do meta[:terminator] in [@double_heredoc, @single_heredoc] and fun |> Atom.to_string() |> String.starts_with?("sigil_") end """ end test "mixed parens and no parens calls with anonymous function" do assert_same ~S""" node interface do resolve_type(fn %{__struct__: str}, _ -> str |> Model.Node.model_to_node_type() value, _ -> Logger.warn("Could not extract node type from value: #{inspect(value)}") nil end) end """ end test "long defstruct definition" do assert_same """ defstruct name: nil, module: nil, schema: nil, alias: nil, base_module: nil, web_module: nil, basename: nil, file: nil, test_file: nil """ end test "mix of operators and arguments" do assert_same """ def count(%{path: path, line_or_bytes: bytes}) do case File.stat(path) do {:ok, %{size: 0}} -> {:error, __MODULE__} {:ok, %{size: size}} -> {:ok, div(size, bytes) + if(rem(size, bytes) == 0, do: 0, else: 1)} {:error, reason} -> raise File.Error, reason: reason, action: "stream", path: path end end """ end test "mix of left and right operands" do assert_same """ defp server_get_modules(handlers) do for(handler(module: module) <- handlers, do: module) |> :ordsets.from_list() |> :ordsets.to_list() end """ assert_same """ neighbours = for({_, _} = t <- neighbours, do: t) |> :sets.from_list() """ end test "long expression with single line anonymous function" do assert_same """ for_many(uniq_list_of(integer(1..10000)), fn list -> assert Enum.uniq(list) == list end) """ end test "long comprehension" do assert_same """ for %{app: app, opts: opts, top_level: true} <- Mix.Dep.cached(), Keyword.get(opts, :app, true), Keyword.get(opts, :runtime, true), not Keyword.get(opts, :optional, false), app not in included_applications, app not in included_applications, do: app """ end test "short comprehensions" do assert_same """ for {protocol, :protocol, _beam} <- removed_metadata, remove_consolidated(protocol, output), do: {protocol, true}, into: %{} """ end test "comprehensions with when" do assert_same """ for {key, value} when is_atom(key) <- Map.to_list(map), key = Atom.to_string(key), String.starts_with?(key, hint) do %{kind: :map_key, name: key, value_is_map: is_map(value)} end """ assert_same """ with {_, doc} when unquote(doc_attr?) <- Module.get_attribute(__MODULE__, unquote(name), unquote(escaped)), do: doc """ end test "next break fits followed by inline tuple" do assert_same """ assert ExUnit.Filters.eval([line: "1"], [:line], %{line: 3, describe_line: 2}, tests) == {:error, "due to line filter"} """ end test "try/catch with clause comment" do assert_same """ def format_error(reason) do try do do_format_error(reason) catch # A user could create an error that looks like a built-in one # causing an error. :error, _ -> inspect(reason) end end """ end test "case with when and clause comment" do assert_same """ case decomposition do # Decomposition <<h, _::binary>> when h != ?< -> decomposition = decomposition |> :binary.split(" ", [:global]) |> Enum.map(&String.to_integer(&1, 16)) Map.put(dacc, String.to_integer(codepoint, 16), decomposition) _ -> dacc end """ end test "anonymous function with parens around integer argument" do bad = """ fn (1) -> "hello" end """ assert_format bad, """ fn 1 -> "hello" end """ end test "no parens keywords at the end of the line" do bad = """ defmodule Mod do def token_list_downcase(<<char, rest::binary>>, acc) when is_whitespace(char) or is_comma(char), do: token_list_downcase(rest, acc) def token_list_downcase(some_really_long_arg11, some_really_long_arg22, some_really_long_arg33), do: token_list_downcase(rest, acc) end """ assert_format bad, """ defmodule Mod do def token_list_downcase(<<char, rest::binary>>, acc) when is_whitespace(char) or is_comma(char), do: token_list_downcase(rest, acc) def token_list_downcase(some_really_long_arg11, some_really_long_arg22, some_really_long_arg33), do: token_list_downcase(rest, acc) end """ end test "do at the end of the line" do bad = """ foo bar, baz, quux do :ok end """ good = """ foo bar, baz, quux do :ok end """ assert_format bad, good, line_length: 18 end test "keyword lists in last line" do assert_same """ content = config(VeryLongModuleNameThatWillCauseBreak, "new.html", conn: conn, changeset: changeset, categories: categories ) """ assert_same """ content = config VeryLongModuleNameThatWillCauseBreak, "new.html", conn: conn, changeset: changeset, categories: categories """ end test "do at the end of the line with single argument" do bad = """ defmodule Location do def new(line, column) when is_integer(line) and line >= 0 and is_integer(column) and column >= 0 do %{column: column, line: line} end end """ assert_format bad, """ defmodule Location do def new(line, column) when is_integer(line) and line >= 0 and is_integer(column) and column >= 0 do %{column: column, line: line} end end """ end test "tuples as trees" do bad = """ @document Parser.parse( {"html", [], [ {"head", [], []}, {"body", [], [ {"div", [], [ {"p", [], ["1"]}, {"p", [], ["2"]}, {"div", [], [ {"p", [], ["3"]}, {"p", [], ["4"]}]}, {"p", [], ["5"]}]}]}]}) """ assert_format bad, """ @document Parser.parse( {"html", [], [ {"head", [], []}, {"body", [], [ {"div", [], [ {"p", [], ["1"]}, {"p", [], ["2"]}, {"div", [], [ {"p", [], ["3"]}, {"p", [], ["4"]} ]}, {"p", [], ["5"]} ]} ]} ]} ) """ end test "first argument in a call without parens with comments" do assert_same """ with bar :: :ok | :invalid # | :unknown | :other """ assert_same """ @spec bar :: :ok | :invalid # | :unknown | :other """ end test "when with keywords inside call" do assert_same """ quote((bar(foo(1)) when bat: foo(1)), []) """ assert_same """ quote(do: (bar(foo(1)) when bat: foo(1)), line: 1) """ assert_same """ typespec(quote(do: (bar(foo(1)) when bat: foo(1))), [foo: 1], []) """ end test "false positive sigil" do assert_same """ def sigil_d(<<year::2-bytes, "-", month::2-bytes, "-", day::2-bytes>>, calendar) do ymd(year, month, day, calendar) end """ end test "newline after stab" do assert_same """ capture_io(":erl. mof*,,l", fn -> assert :io.scan_erl_form('>') == {:ok, [{:":", 1}, {:atom, 1, :erl}, {:dot, 1}], 1} expected_tokens = [{:atom, 1, :mof}, {:*, 1}, {:",", 1}, {:",", 1}, {:atom, 1, :l}] assert :io.scan_erl_form('>') == {:ok, expected_tokens, 1} assert :io.scan_erl_form('>') == {:eof, 1} end) """ end test "capture with operators" do assert_same """ "this works" |> (&String.upcase/1) |> (&String.downcase/1) """ assert_same """ "this works" || (&String.upcase/1) || (&String.downcase/1) """ assert_same """ "this works" == (&String.upcase/1) == (&String.downcase/1) """ bad = """ "this works" = (&String.upcase/1) = (&String.downcase/1) """ assert_format bad, """ "this works" = (&String.upcase/1) = &String.downcase/1 """ bad = """ "this works" ++ (&String.upcase/1) ++ (&String.downcase/1) """ assert_format bad, """ "this works" ++ (&String.upcase/1) ++ &String.downcase/1 """ bad = """ "this works" +++ (&String.upcase/1) +++ (&String.downcase/1) """ assert_format bad, """ "this works" +++ (&String.upcase/1) +++ &String.downcase/1 """ bad = """ "this works" | (&String.upcase/1) | (&String.downcase/1) """ assert_format bad, """ "this works" | (&String.upcase/1) | &String.downcase/1 """ bad = ~S""" "this works" \\ (&String.upcase/1) \\ (&String.downcase/1) """ assert_format bad, ~S""" "this works" \\ &String.upcase/1 \\ &String.downcase/1 """ end test "comment inside operator with when" do bad = """ raise function(x) :: # Comment any """ assert_format bad, """ # Comment raise function(x) :: any """ bad = """ raise function(x) :: # Comment any when x: any """ assert_format bad, """ raise function(x) :: any # Comment when x: any """ bad = """ @spec function(x) :: # Comment any when x: any """ assert_format bad, """ @spec function(x) :: any # Comment when x: any """ bad = """ @spec function(x) :: # Comment any when x when y """ assert_format bad, """ @spec function(x) :: any # Comment when x when y """ end end
25.354409
137
0.524413
0855aa2105ff13937e3040131889ea71af1bc532
49
exs
Elixir
test/full_stackory_slack/plan_cache_test.exs
full-stackory/full_stackory_slack
a58f73248a91248554548187ab184e7e0b3f3b23
[ "Apache-2.0" ]
null
null
null
test/full_stackory_slack/plan_cache_test.exs
full-stackory/full_stackory_slack
a58f73248a91248554548187ab184e7e0b3f3b23
[ "Apache-2.0" ]
2
2021-03-10T06:19:38.000Z
2021-05-11T02:11:14.000Z
test/full_stackory_slack/plan_cache_test.exs
full-stackory/full_stackory_slack
a58f73248a91248554548187ab184e7e0b3f3b23
[ "Apache-2.0" ]
null
null
null
defmodule FullStackorySlack.PlanCacheTest do end
16.333333
44
0.897959
0855d715d39a43f919fdcfb904ee8ddf03fbdfc9
154
exs
Elixir
sources/Chapter7/sum2.exs
Geroshabu/ProgrammingElixir
979a835fc728f750af50a3ae771ebbac2ab4000f
[ "MIT" ]
null
null
null
sources/Chapter7/sum2.exs
Geroshabu/ProgrammingElixir
979a835fc728f750af50a3ae771ebbac2ab4000f
[ "MIT" ]
null
null
null
sources/Chapter7/sum2.exs
Geroshabu/ProgrammingElixir
979a835fc728f750af50a3ae771ebbac2ab4000f
[ "MIT" ]
null
null
null
defmodule MyList do def sum(list), do: _sum(list, 0) defp _sum([], total), do: total defp _sum([head|tail], total), do: _sum(tail, head+total) end
22
59
0.655844
0855f2fea180fd03be31ed292d4c47a777ba097a
1,229
ex
Elixir
lib/discovery_web/router.ex
spawnphile/discovery
0ea32c4915f0b0350d2878c7317f5530ea2474a8
[ "MIT" ]
3
2022-01-07T10:51:48.000Z
2022-03-15T04:39:09.000Z
lib/discovery_web/router.ex
gamezop/discovery
0ea32c4915f0b0350d2878c7317f5530ea2474a8
[ "MIT" ]
null
null
null
lib/discovery_web/router.ex
gamezop/discovery
0ea32c4915f0b0350d2878c7317f5530ea2474a8
[ "MIT" ]
null
null
null
defmodule DiscoveryWeb.Router do use DiscoveryWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :put_root_layout, {DiscoveryWeb.LayoutView, :root} plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug CORSPlug, origin: "*" plug :accepts, ["json"] end scope "/", DiscoveryWeb do pipe_through :browser live "/", PageLive, :index end # Other scopes may use custom stacks. scope "/api", DiscoveryWeb do pipe_through :api get "/get-endpoint", EndpointController, :get_endpoint end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through :browser live_dashboard "/dashboard", metrics: DiscoveryWeb.Telemetry end end end
26.717391
70
0.706265
0855f8f654e5da55993d426cc2fc4f23d399852a
3,966
exs
Elixir
test/adoptoposs_web/live/settings_live_test.exs
floriank/adoptoposs
02d1a8d87dbb36ee7364ae737241d6b129d0bf2d
[ "MIT" ]
null
null
null
test/adoptoposs_web/live/settings_live_test.exs
floriank/adoptoposs
02d1a8d87dbb36ee7364ae737241d6b129d0bf2d
[ "MIT" ]
1
2021-05-11T20:15:21.000Z
2021-05-11T20:15:21.000Z
test/adoptoposs_web/live/settings_live_test.exs
floriank/adoptoposs
02d1a8d87dbb36ee7364ae737241d6b129d0bf2d
[ "MIT" ]
null
null
null
defmodule AdoptopossWeb.SettingsLiveTest do use AdoptopossWeb.LiveCase alias AdoptopossWeb.SettingsLive alias Adoptoposs.Accounts.Settings test "disconnected mount of /settings when logged out", %{conn: conn} do conn = get(conn, Routes.live_path(conn, SettingsLive)) assert html_response(conn, 302) assert conn.halted end test "connected mount of /settings when logged out", %{conn: conn} do {:error, %{redirect: %{to: "/"}}} = live(conn, Routes.live_path(conn, SettingsLive)) end @tag login_as: "user123" test "disconnected mount of /settings when logged in", %{conn: conn} do conn = get(conn, Routes.live_path(conn, SettingsLive)) assert html_response(conn, 200) =~ "Settings" end @tag login_as: "user123" test "connected mount of /settings when logged in", %{conn: conn} do {:ok, _view, html} = live(conn, Routes.live_path(conn, SettingsLive)) assert html =~ "Settings" end describe "tag subscriptions" do @tag login_as: "user123" test "following a tag", %{conn: conn} do tag = insert(:tag, type: "language") {:ok, view, _html} = live(conn, Routes.live_path(conn, SettingsLive)) html = render_change(view, :search_tags, %{q: tag.name}) assert html =~ "Follow #{tag.name}" refute html =~ "Unfollow #{tag.name}" html = render_click(view, :follow_tag, %{tag_id: tag.id}) assert html =~ "Unfollow #{tag.name}" end @tag login_as: "user123" test "following a tag when already following", %{conn: conn, user: user} do tag = insert(:tag, type: "language") insert(:tag_subscription, user: user, tag: tag) {:ok, view, html} = live(conn, Routes.live_path(conn, SettingsLive)) assert html =~ "Unfollow #{tag.name}" html = render_change(view, :search_tags, %{q: tag.name}) refute html =~ "Follow #{tag.name}" html = render_click(view, :follow_tag, %{tag_id: tag.id}) assert html =~ "Unfollow #{tag.name}" end @tag login_as: "user123" test "unfollowing a tag", %{conn: conn, user: user} do tag_subscription = insert(:tag_subscription, user: user) {:ok, view, html} = live(conn, Routes.live_path(conn, SettingsLive)) assert html =~ "Unfollow #{tag_subscription.tag.name}" html = render_click(view, :unfollow_tag, %{tag_subscription_id: tag_subscription.id}) refute html =~ tag_subscription.tag.name end end describe "notifications" do @tag login_as: "user123" test "changing email_when_contacted", %{conn: conn} do {:ok, view, html} = live(conn, Routes.live_path(conn, SettingsLive)) valid_values = Settings.email_when_contacted_values() assert html =~ "value=\"#{List.first(valid_values)}\" checked" for value <- valid_values do settings = %{email_when_contacted: value} html = render_change(view, :update_settings, %{user: %{settings: settings}}) assert html =~ "value=\"#{value}\" checked" settings = %{email_when_contacted: "not-valid"} html = render_change(view, :update_settings, %{user: %{settings: settings}}) assert html =~ "value=\"#{value}\" checked" end end @tag login_as: "user123" test "changing email_project_recommendations", %{conn: conn} do {:ok, view, html} = live(conn, Routes.live_path(conn, SettingsLive)) valid_values = Settings.email_project_recommendations_values() assert html =~ "value=\"#{List.first(valid_values)}\" checked" for value <- valid_values do settings = %{email_project_recommendations: value} html = render_change(view, :update_settings, %{user: %{settings: settings}}) assert html =~ "value=\"#{value}\" checked" settings = %{email_project_recommendations: "not-valid"} html = render_change(view, :update_settings, %{user: %{settings: settings}}) assert html =~ "value=\"#{value}\" checked" end end end end
35.410714
91
0.653555
085610f840bb3cb125953081bc0749c3547fbab1
204
ex
Elixir
lib/sanbase_web/admin/insights/post_comment.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
lib/sanbase_web/admin/insights/post_comment.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
1
2021-07-24T16:26:03.000Z
2021-07-24T16:26:03.000Z
lib/sanbase_web/admin/insights/post_comment.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
defmodule SanbaseWeb.ExAdmin.Insight.PostComment do use ExAdmin.Register register_resource Sanbase.Insight.PostComment do show post_comment do attributes_table(all: true) end end end
20.4
51
0.77451
08561eb20c7808e2b49317b58498820a329a2a9a
184
exs
Elixir
priv/repo/migrations/20210512224557_change_default_flags.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
28
2021-10-11T01:53:53.000Z
2022-03-24T17:45:55.000Z
priv/repo/migrations/20210512224557_change_default_flags.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
20
2021-10-21T08:12:31.000Z
2022-03-31T13:35:53.000Z
priv/repo/migrations/20210512224557_change_default_flags.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
null
null
null
defmodule BikeBrigade.Repo.Migrations.ChangeDefaultFlags do use Ecto.Migration def change do alter table(:riders) do modify :flags, :map, default: %{} end end end
18.4
59
0.701087
08562ac5f0cab48d524ab7a62c71de220c560d99
1,771
ex
Elixir
clients/gke_hub/lib/google_api/gke_hub/v1/model/config_management_hierarchy_controller_deployment_state.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/gke_hub/lib/google_api/gke_hub/v1/model/config_management_hierarchy_controller_deployment_state.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/gke_hub/lib/google_api/gke_hub/v1/model/config_management_hierarchy_controller_deployment_state.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.GKEHub.V1.Model.ConfigManagementHierarchyControllerDeploymentState do @moduledoc """ Deployment state for Hierarchy Controller ## Attributes * `extension` (*type:* `String.t`, *default:* `nil`) - The deployment state for Hierarchy Controller extension (e.g. v0.7.0-hc.1) * `hnc` (*type:* `String.t`, *default:* `nil`) - The deployment state for open source HNC (e.g. v0.7.0-hc.0) """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :extension => String.t() | nil, :hnc => String.t() | nil } field(:extension) field(:hnc) end defimpl Poison.Decoder, for: GoogleApi.GKEHub.V1.Model.ConfigManagementHierarchyControllerDeploymentState do def decode(value, options) do GoogleApi.GKEHub.V1.Model.ConfigManagementHierarchyControllerDeploymentState.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.GKEHub.V1.Model.ConfigManagementHierarchyControllerDeploymentState do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.2
133
0.729531
085637594024facb141b3cdd10f1cc5a8237af89
1,875
ex
Elixir
clients/artifact_registry/lib/google_api/artifact_registry/v1beta1/model/tag.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/artifact_registry/lib/google_api/artifact_registry/v1beta1/model/tag.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/artifact_registry/lib/google_api/artifact_registry/v1beta1/model/tag.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "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.ArtifactRegistry.V1beta1.Model.Tag do @moduledoc """ Tags point to a version and represent an alternative name that can be used to access the version. ## Attributes * `name` (*type:* `String.t`, *default:* `nil`) - The name of the tag, for example: "projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/tags/tag1". If the package or tag ID parts contain slashes, the slashes are escaped. * `version` (*type:* `String.t`, *default:* `nil`) - The name of the version the tag refers to, for example: "projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/sha256:5243811" """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :name => String.t() | nil, :version => String.t() | nil } field(:name) field(:version) end defimpl Poison.Decoder, for: GoogleApi.ArtifactRegistry.V1beta1.Model.Tag do def decode(value, options) do GoogleApi.ArtifactRegistry.V1beta1.Model.Tag.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ArtifactRegistry.V1beta1.Model.Tag do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.5
240
0.732267
08563b4ebfa77025f962a74fa1cdf78c22742448
276
ex
Elixir
test/support/commands/conditional_increment.ex
toniqsystems/event_store
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
[ "Apache-2.0" ]
103
2018-02-09T23:13:21.000Z
2021-08-18T04:22:41.000Z
test/support/commands/conditional_increment.ex
tonic-sys/event_store
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
[ "Apache-2.0" ]
20
2018-04-05T16:10:53.000Z
2021-07-01T08:21:50.000Z
test/support/commands/conditional_increment.ex
tonic-sys/event_store
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
[ "Apache-2.0" ]
3
2018-09-13T06:03:10.000Z
2019-07-11T15:22:53.000Z
defmodule Maestro.SampleAggregate.Commands.ConditionalIncrement do @moduledoc false @behaviour Maestro.Aggregate.CommandHandler alias Maestro.InvalidCommandError def eval(_aggregate, _com) do raise InvalidCommandError, "command incorrectly specified" end end
23
66
0.815217
08563fe2e921f987e4595b0a77c91a4e1f178b7b
164
exs
Elixir
priv/repo/migrations/20201129175748_add_email_to_users.exs
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
priv/repo/migrations/20201129175748_add_email_to_users.exs
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
priv/repo/migrations/20201129175748_add_email_to_users.exs
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
defmodule Squadster.Repo.Migrations.AddEmailToUsers do use Ecto.Migration def change do alter table(:users) do add :email, :string end end end
16.4
54
0.707317
0856404e8667d3f62e7ad399fe85acc1354b7774
627
ex
Elixir
lib/oli/delivery/sections/enrollment.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli/delivery/sections/enrollment.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli/delivery/sections/enrollment.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule Oli.Delivery.Sections.Enrollment do use Ecto.Schema import Ecto.Changeset schema "enrollments" do belongs_to :user, Oli.Accounts.User belongs_to :section, Oli.Delivery.Sections.Section field :state, :map, default: %{} many_to_many :context_roles, Lti_1p3.DataProviders.EctoProvider.ContextRole, join_through: "enrollments_context_roles", on_replace: :delete timestamps(type: :utc_datetime) end @doc false def changeset(enrollment, attrs) do enrollment |> cast(attrs, [:user_id, :section_id, :state]) |> validate_required([:user_id, :section_id]) end end
25.08
80
0.719298
0856417985c1791cf12046648b8b982d4f41b4a7
2,335
exs
Elixir
config/dev.exs
seb3s/live_deck
316c8a414f81ba6bbd00d232852457d715a729bd
[ "MIT" ]
1
2020-06-15T00:43:17.000Z
2020-06-15T00:43:17.000Z
config/dev.exs
seb3s/live_deck
316c8a414f81ba6bbd00d232852457d715a729bd
[ "MIT" ]
null
null
null
config/dev.exs
seb3s/live_deck
316c8a414f81ba6bbd00d232852457d715a729bd
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database config :live_deck, LiveDeck.Repo, username: "postgres", password: "postgres", database: "live_deck_dev", hostname: "localhost", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :live_deck, LiveDeckWeb.Endpoint, http: [port: 4000], debug_errors: true, secret_key_base: "B6l0Z1Jb1CYfqVed1oJNRlxWknzsNj4Cuqqr+iAVsPm7+ISaUzSzvOz6dSfSqmWt", live_view: [signing_salt: "B6l0Z1Jb1CYfqVed1oJNRlxWknzsNj4Cuqqr+iAVsPm7+ISaUzSzvOz6dSfSqmWt"], code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :live_deck, LiveDeckWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/live_deck_web/{live,views}/.*(ex)$", ~r"lib/live_deck_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
29.556962
96
0.706638
08566895c7d06c2811954df7c23336cf7e7643df
1,638
exs
Elixir
test/bootstrap_form_test.exs
amandasposito/bootstrap_form
498cd0e3b3c29afd655303a757beeafa76cff307
[ "MIT" ]
null
null
null
test/bootstrap_form_test.exs
amandasposito/bootstrap_form
498cd0e3b3c29afd655303a757beeafa76cff307
[ "MIT" ]
null
null
null
test/bootstrap_form_test.exs
amandasposito/bootstrap_form
498cd0e3b3c29afd655303a757beeafa76cff307
[ "MIT" ]
null
null
null
defmodule BootstrapFormTest do use ExUnit.Case doctest BootstrapForm import Phoenix.HTML, only: [safe_to_string: 1] import Phoenix.HTML.Form, only: [form_for: 4] describe "input/3" do test "generates an input with bootstrap markup" do expected = ~s(<div class="form-group">) <> ~s(<label class="control-label" for="user_name">Name</label>) <> ~s(<input class="form-control" id="user_name" name="user[name]" type="text">) <> ~s(</div>) form = form_for(conn(), "/", [as: :user], fn form -> BootstrapForm.input(form, :name) end) assert safe_to_string(form) =~ expected end test "generates an input given a type" do expected = ~s(<div class="form-check">) <> ~s(<input name="user[active]" type="hidden" value="false">) <> ~s(<input class="form-check-input" id="user_active" name="user[active]" type="checkbox" value="true">) <> ~s(<label class="form-check-label" for="user_active">Active?</label>) <> ~s(</div>) form = form_for(conn(), "/", [as: :user], fn form -> BootstrapForm.input(form, :active, type: :checkbox, label_text: "Active?") end) assert safe_to_string(form) =~ expected end test "raises an error if a unknow type is given" do assert_raise RuntimeError, "type: :unknow is not yet implemented", fn -> form_for(conn(), "/", [as: :user], fn form -> BootstrapForm.input(form, :name, type: :unknow) end) end end end defp conn do Plug.Test.conn(:get, "/foo", %{}) end end
30.333333
115
0.582418
085673b5edb333cb91d515157407ddb1a81bd3e1
504
ex
Elixir
lib/mp_api_web/views/changeset_view.ex
jsvelasquezv/mp_api
9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0
[ "MIT" ]
null
null
null
lib/mp_api_web/views/changeset_view.ex
jsvelasquezv/mp_api
9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0
[ "MIT" ]
null
null
null
lib/mp_api_web/views/changeset_view.ex
jsvelasquezv/mp_api
9a2262188b5b12c0e2ecd9284a8e7f445d2be4a0
[ "MIT" ]
null
null
null
defmodule MpApiWeb.ChangesetView do use MpApiWeb, :view @doc """ Traverses and translates changeset errors. See `Ecto.Changeset.traverse_errors/2` for more details. """ def translate_errors(changeset) do Ecto.Changeset.traverse_errors(changeset, &translate_error/1) end def render("error.json", %{changeset: changeset}) do # When encoded, the changeset returns its errors # as a JSON object. So we just pass it forward. %{errors: translate_errors(changeset)} end end
26.526316
65
0.728175
0856764a4d30624242d4e952f72439d8e398f027
243
ex
Elixir
lib/hub.ex
Poeticode/hub
39df28dd5f18fe61899b72f18935c1508dd166ee
[ "MIT" ]
null
null
null
lib/hub.ex
Poeticode/hub
39df28dd5f18fe61899b72f18935c1508dd166ee
[ "MIT" ]
5
2020-07-17T23:35:42.000Z
2021-05-10T07:00:10.000Z
lib/hub.ex
Poeticode/hub
39df28dd5f18fe61899b72f18935c1508dd166ee
[ "MIT" ]
null
null
null
defmodule Hub do @moduledoc """ Hub keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
24.3
66
0.744856
0856a95b5460db6c37360c5e969d0b689f8af5dd
2,072
ex
Elixir
lib/actors/account.ex
nosovk/wms
c887fce7d23e8fc7846c6f1afaee0795c3e30a87
[ "ISC" ]
8
2019-08-02T01:50:01.000Z
2021-12-20T07:33:27.000Z
lib/actors/account.ex
nosovk/wms
c887fce7d23e8fc7846c6f1afaee0795c3e30a87
[ "ISC" ]
12
2019-07-08T14:21:01.000Z
2019-07-22T12:58:09.000Z
lib/actors/account.ex
enterprizing/plm
5f03461f7f07586e26f3b370775539d94dac2188
[ "0BSD" ]
4
2019-07-23T12:28:47.000Z
2021-11-29T12:49:37.000Z
defmodule BPE.Account do @moduledoc """ `PLM.Account` is a process that handles user investments. """ require ERP require BPE require Record Record.defrecord(:close_account, []) Record.defrecord(:tx, []) def def() do BPE.process( name: :n2o.user(), flows: [ BPE.sequenceFlow(source: :Created, target: :Init), BPE.sequenceFlow(source: :Init, target: :Upload), BPE.sequenceFlow(source: :Upload, target: :Payment), BPE.sequenceFlow(source: :Payment, target: [:Signatory, :Process]), BPE.sequenceFlow(source: :Process, target: [:Process, :Final]), BPE.sequenceFlow(source: :Signatory, target: [:Process, :Final]) ], tasks: [ BPE.userTask(name: :Created, module: BPE.Account), BPE.userTask(name: :Init, module: BPE.Account), BPE.userTask(name: :Upload, module: BPE.Account), BPE.userTask(name: :Signatory, module: BPE.Account), BPE.serviceTask(name: :Payment, module: BPE.Account), BPE.serviceTask(name: :Process, module: BPE.Account), BPE.endEvent(name: :Final, module: BPE.Account) ], beginEvent: :Init, endEvent: :Final, events: [BPE.messageEvent(name: :PaymentReceived)] ) end def action({:request, :Created}, proc) do IO.inspect("First Step") {:reply, proc} end def action({:request, :Init}, proc) do IO.inspect("Second Step") {:reply, proc} end def action({:request, :Payment}, proc) do payment = :bpe.doc({:payment_notification}, proc) case payment do [] -> {:reply, :Process, BPE.process(proc, docs: [tx()])} _ -> {:reply, :Signatory, Proc} end end def action({:request, :Signatory}, proc) do {:reply, :Process, proc} end def action({:request, :Process}, proc) do case :bpe.doc(close_account(), proc) do close_account() -> {:reply, :Final, proc} _ -> {:reply, proc} end end def action({:request, :Upload}, proc), do: {:reply, proc} def action({:request, :Final}, proc), do: {:reply, proc} end
29.6
75
0.612452
0856c2d22d83be1b7102df91155a806758d01a44
25,338
ex
Elixir
lib/aws/generated/doc_db.ex
pecigonzalo/aws-elixir
b52181ebfb9e62349dc8e8067b7fbcd4f7a18c68
[ "Apache-2.0" ]
null
null
null
lib/aws/generated/doc_db.ex
pecigonzalo/aws-elixir
b52181ebfb9e62349dc8e8067b7fbcd4f7a18c68
[ "Apache-2.0" ]
null
null
null
lib/aws/generated/doc_db.ex
pecigonzalo/aws-elixir
b52181ebfb9e62349dc8e8067b7fbcd4f7a18c68
[ "Apache-2.0" ]
null
null
null
# WARNING: DO NOT EDIT, AUTO-GENERATED CODE! # See https://github.com/aws-beam/aws-codegen for more details. defmodule AWS.DocDB do @moduledoc """ Amazon DocumentDB API documentation """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: "Amazon DocDB", api_version: "2014-10-31", content_type: "application/x-www-form-urlencoded", credential_scope: nil, endpoint_prefix: "rds", global?: false, protocol: "query", service_id: "DocDB", signature_version: "v4", signing_name: "rds", target_prefix: nil } end @doc """ Adds a source identifier to an existing event notification subscription. """ def add_source_identifier_to_subscription(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "AddSourceIdentifierToSubscription", input, options) end @doc """ Adds metadata tags to an Amazon DocumentDB resource. You can use these tags with cost allocation reporting to track costs that are associated with Amazon DocumentDB resources or in a `Condition` statement in an Identity and Access Management (IAM) policy for Amazon DocumentDB. """ def add_tags_to_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "AddTagsToResource", input, options) end @doc """ Applies a pending maintenance action to a resource (for example, to an Amazon DocumentDB instance). """ def apply_pending_maintenance_action(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ApplyPendingMaintenanceAction", input, options) end @doc """ Copies the specified cluster parameter group. """ def copy_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CopyDBClusterParameterGroup", input, options) end @doc """ Copies a snapshot of a cluster. To copy a cluster snapshot from a shared manual cluster snapshot, `SourceDBClusterSnapshotIdentifier` must be the Amazon Resource Name (ARN) of the shared cluster snapshot. You can only copy a shared DB cluster snapshot, whether encrypted or not, in the same Amazon Web Services Region. To cancel the copy operation after it is in progress, delete the target cluster snapshot identified by `TargetDBClusterSnapshotIdentifier` while that cluster snapshot is in the *copying* status. """ def copy_db_cluster_snapshot(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CopyDBClusterSnapshot", input, options) end @doc """ Creates a new Amazon DocumentDB cluster. """ def create_db_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateDBCluster", input, options) end @doc """ Creates a new cluster parameter group. Parameters in a cluster parameter group apply to all of the instances in a cluster. A cluster parameter group is initially created with the default parameters for the database engine used by instances in the cluster. In Amazon DocumentDB, you cannot make modifications directly to the `default.docdb3.6` cluster parameter group. If your Amazon DocumentDB cluster is using the default cluster parameter group and you want to modify a value in it, you must first [ create a new parameter group](https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-create.html) or [ copy an existing parameter group](https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-copy.html), modify it, and then apply the modified parameter group to your cluster. For the new cluster parameter group and associated settings to take effect, you must then reboot the instances in the cluster without failover. For more information, see [ Modifying Amazon DocumentDB Cluster Parameter Groups](https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-modify.html). """ def create_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateDBClusterParameterGroup", input, options) end @doc """ Creates a snapshot of a cluster. """ def create_db_cluster_snapshot(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateDBClusterSnapshot", input, options) end @doc """ Creates a new instance. """ def create_db_instance(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateDBInstance", input, options) end @doc """ Creates a new subnet group. subnet groups must contain at least one subnet in at least two Availability Zones in the Amazon Web Services Region. """ def create_db_subnet_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateDBSubnetGroup", input, options) end @doc """ Creates an Amazon DocumentDB event notification subscription. This action requires a topic Amazon Resource Name (ARN) created by using the Amazon DocumentDB console, the Amazon SNS console, or the Amazon SNS API. To obtain an ARN with Amazon SNS, you must create a topic in Amazon SNS and subscribe to the topic. The ARN is displayed in the Amazon SNS console. You can specify the type of source (`SourceType`) that you want to be notified of. You can also provide a list of Amazon DocumentDB sources (`SourceIds`) that trigger the events, and you can provide a list of event categories (`EventCategories`) for events that you want to be notified of. For example, you can specify `SourceType = db-instance`, `SourceIds = mydbinstance1, mydbinstance2` and `EventCategories = Availability, Backup`. If you specify both the `SourceType` and `SourceIds` (such as `SourceType = db-instance` and `SourceIdentifier = myDBInstance1`), you are notified of all the `db-instance` events for the specified source. If you specify a `SourceType` but do not specify a `SourceIdentifier`, you receive notice of the events for that source type for all your Amazon DocumentDB sources. If you do not specify either the `SourceType` or the `SourceIdentifier`, you are notified of events generated from all Amazon DocumentDB sources belonging to your customer account. """ def create_event_subscription(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateEventSubscription", input, options) end @doc """ Creates an Amazon DocumentDB global cluster that can span multiple multiple Amazon Web Services Regions. The global cluster contains one primary cluster with read-write capability, and up-to give read-only secondary clusters. Global clusters uses storage-based fast replication across regions with latencies less than one second, using dedicated infrastructure with no impact to your workload’s performance. You can create a global cluster that is initially empty, and then add a primary and a secondary to it. Or you can specify an existing cluster during the create operation, and this cluster becomes the primary of the global cluster. This action only applies to Amazon DocumentDB clusters. """ def create_global_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateGlobalCluster", input, options) end @doc """ Deletes a previously provisioned cluster. When you delete a cluster, all automated backups for that cluster are deleted and can't be recovered. Manual DB cluster snapshots of the specified cluster are not deleted. """ def delete_db_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteDBCluster", input, options) end @doc """ Deletes a specified cluster parameter group. The cluster parameter group to be deleted can't be associated with any clusters. """ def delete_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteDBClusterParameterGroup", input, options) end @doc """ Deletes a cluster snapshot. If the snapshot is being copied, the copy operation is terminated. The cluster snapshot must be in the `available` state to be deleted. """ def delete_db_cluster_snapshot(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteDBClusterSnapshot", input, options) end @doc """ Deletes a previously provisioned instance. """ def delete_db_instance(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteDBInstance", input, options) end @doc """ Deletes a subnet group. The specified database subnet group must not be associated with any DB instances. """ def delete_db_subnet_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteDBSubnetGroup", input, options) end @doc """ Deletes an Amazon DocumentDB event notification subscription. """ def delete_event_subscription(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteEventSubscription", input, options) end @doc """ Deletes a global cluster. The primary and secondary clusters must already be detached or deleted before attempting to delete a global cluster. This action only applies to Amazon DocumentDB clusters. """ def delete_global_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteGlobalCluster", input, options) end @doc """ Returns a list of certificate authority (CA) certificates provided by Amazon DocumentDB for this Amazon Web Services account. """ def describe_certificates(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeCertificates", input, options) end @doc """ Returns a list of `DBClusterParameterGroup` descriptions. If a `DBClusterParameterGroupName` parameter is specified, the list contains only the description of the specified cluster parameter group. """ def describe_db_cluster_parameter_groups(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBClusterParameterGroups", input, options) end @doc """ Returns the detailed parameter list for a particular cluster parameter group. """ def describe_db_cluster_parameters(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBClusterParameters", input, options) end @doc """ Returns a list of cluster snapshot attribute names and values for a manual DB cluster snapshot. When you share snapshots with other Amazon Web Services accounts, `DescribeDBClusterSnapshotAttributes` returns the `restore` attribute and a list of IDs for the Amazon Web Services accounts that are authorized to copy or restore the manual cluster snapshot. If `all` is included in the list of values for the `restore` attribute, then the manual cluster snapshot is public and can be copied or restored by all Amazon Web Services accounts. """ def describe_db_cluster_snapshot_attributes(%Client{} = client, input, options \\ []) do Request.request_post( client, metadata(), "DescribeDBClusterSnapshotAttributes", input, options ) end @doc """ Returns information about cluster snapshots. This API operation supports pagination. """ def describe_db_cluster_snapshots(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBClusterSnapshots", input, options) end @doc """ Returns information about provisioned Amazon DocumentDB clusters. This API operation supports pagination. For certain management features such as cluster and instance lifecycle management, Amazon DocumentDB leverages operational technology that is shared with Amazon RDS and Amazon Neptune. Use the `filterName=engine,Values=docdb` filter parameter to return only Amazon DocumentDB clusters. """ def describe_db_clusters(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBClusters", input, options) end @doc """ Returns a list of the available engines. """ def describe_db_engine_versions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBEngineVersions", input, options) end @doc """ Returns information about provisioned Amazon DocumentDB instances. This API supports pagination. """ def describe_db_instances(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBInstances", input, options) end @doc """ Returns a list of `DBSubnetGroup` descriptions. If a `DBSubnetGroupName` is specified, the list will contain only the descriptions of the specified `DBSubnetGroup`. """ def describe_db_subnet_groups(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeDBSubnetGroups", input, options) end @doc """ Returns the default engine and system parameter information for the cluster database engine. """ def describe_engine_default_cluster_parameters(%Client{} = client, input, options \\ []) do Request.request_post( client, metadata(), "DescribeEngineDefaultClusterParameters", input, options ) end @doc """ Displays a list of categories for all event source types, or, if specified, for a specified source type. """ def describe_event_categories(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeEventCategories", input, options) end @doc """ Lists all the subscription descriptions for a customer account. The description for a subscription includes `SubscriptionName`, `SNSTopicARN`, `CustomerID`, `SourceType`, `SourceID`, `CreationTime`, and `Status`. If you specify a `SubscriptionName`, lists the description for that subscription. """ def describe_event_subscriptions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeEventSubscriptions", input, options) end @doc """ Returns events related to instances, security groups, snapshots, and DB parameter groups for the past 14 days. You can obtain events specific to a particular DB instance, security group, snapshot, or parameter group by providing the name as a parameter. By default, the events of the past hour are returned. """ def describe_events(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeEvents", input, options) end @doc """ Returns information about Amazon DocumentDB global clusters. This API supports pagination. This action only applies to Amazon DocumentDB clusters. """ def describe_global_clusters(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeGlobalClusters", input, options) end @doc """ Returns a list of orderable instance options for the specified engine. """ def describe_orderable_db_instance_options(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeOrderableDBInstanceOptions", input, options) end @doc """ Returns a list of resources (for example, instances) that have at least one pending maintenance action. """ def describe_pending_maintenance_actions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribePendingMaintenanceActions", input, options) end @doc """ Forces a failover for a cluster. A failover for a cluster promotes one of the Amazon DocumentDB replicas (read-only instances) in the cluster to be the primary instance (the cluster writer). If the primary instance fails, Amazon DocumentDB automatically fails over to an Amazon DocumentDB replica, if one exists. You can force a failover when you want to simulate a failure of a primary instance for testing. """ def failover_db_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "FailoverDBCluster", input, options) end @doc """ Lists all tags on an Amazon DocumentDB resource. """ def list_tags_for_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListTagsForResource", input, options) end @doc """ Modifies a setting for an Amazon DocumentDB cluster. You can change one or more database configuration parameters by specifying these parameters and the new values in the request. """ def modify_db_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyDBCluster", input, options) end @doc """ Modifies the parameters of a cluster parameter group. To modify more than one parameter, submit a list of the following: `ParameterName`, `ParameterValue`, and `ApplyMethod`. A maximum of 20 parameters can be modified in a single request. Changes to dynamic parameters are applied immediately. Changes to static parameters require a reboot or maintenance window before the change can take effect. After you create a cluster parameter group, you should wait at least 5 minutes before creating your first cluster that uses that cluster parameter group as the default parameter group. This allows Amazon DocumentDB to fully complete the create action before the parameter group is used as the default for a new cluster. This step is especially important for parameters that are critical when creating the default database for a cluster, such as the character set for the default database defined by the `character_set_database` parameter. """ def modify_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyDBClusterParameterGroup", input, options) end @doc """ Adds an attribute and values to, or removes an attribute and values from, a manual cluster snapshot. To share a manual cluster snapshot with other Amazon Web Services accounts, specify `restore` as the `AttributeName`, and use the `ValuesToAdd` parameter to add a list of IDs of the Amazon Web Services accounts that are authorized to restore the manual cluster snapshot. Use the value `all` to make the manual cluster snapshot public, which means that it can be copied or restored by all Amazon Web Services accounts. Do not add the `all` value for any manual cluster snapshots that contain private information that you don't want available to all Amazon Web Services accounts. If a manual cluster snapshot is encrypted, it can be shared, but only by specifying a list of authorized Amazon Web Services account IDs for the `ValuesToAdd` parameter. You can't use `all` as a value for that parameter in this case. """ def modify_db_cluster_snapshot_attribute(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyDBClusterSnapshotAttribute", input, options) end @doc """ Modifies settings for an instance. You can change one or more database configuration parameters by specifying these parameters and the new values in the request. """ def modify_db_instance(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyDBInstance", input, options) end @doc """ Modifies an existing subnet group. subnet groups must contain at least one subnet in at least two Availability Zones in the Amazon Web Services Region. """ def modify_db_subnet_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyDBSubnetGroup", input, options) end @doc """ Modifies an existing Amazon DocumentDB event notification subscription. """ def modify_event_subscription(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyEventSubscription", input, options) end @doc """ Modify a setting for an Amazon DocumentDB global cluster. You can change one or more configuration parameters (for example: deletion protection), or the global cluster identifier by specifying these parameters and the new values in the request. This action only applies to Amazon DocumentDB clusters. """ def modify_global_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ModifyGlobalCluster", input, options) end @doc """ You might need to reboot your instance, usually for maintenance reasons. For example, if you make certain changes, or if you change the cluster parameter group that is associated with the instance, you must reboot the instance for the changes to take effect. Rebooting an instance restarts the database engine service. Rebooting an instance results in a momentary outage, during which the instance status is set to *rebooting*. """ def reboot_db_instance(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RebootDBInstance", input, options) end @doc """ Detaches an Amazon DocumentDB secondary cluster from a global cluster. The cluster becomes a standalone cluster with read-write capability instead of being read-only and receiving data from a primary in a different region. This action only applies to Amazon DocumentDB clusters. """ def remove_from_global_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RemoveFromGlobalCluster", input, options) end @doc """ Removes a source identifier from an existing Amazon DocumentDB event notification subscription. """ def remove_source_identifier_from_subscription(%Client{} = client, input, options \\ []) do Request.request_post( client, metadata(), "RemoveSourceIdentifierFromSubscription", input, options ) end @doc """ Removes metadata tags from an Amazon DocumentDB resource. """ def remove_tags_from_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RemoveTagsFromResource", input, options) end @doc """ Modifies the parameters of a cluster parameter group to the default value. To reset specific parameters, submit a list of the following: `ParameterName` and `ApplyMethod`. To reset the entire cluster parameter group, specify the `DBClusterParameterGroupName` and `ResetAllParameters` parameters. When you reset the entire group, dynamic parameters are updated immediately and static parameters are set to `pending-reboot` to take effect on the next DB instance reboot. """ def reset_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ResetDBClusterParameterGroup", input, options) end @doc """ Creates a new cluster from a snapshot or cluster snapshot. If a snapshot is specified, the target cluster is created from the source DB snapshot with a default configuration and default security group. If a cluster snapshot is specified, the target cluster is created from the source cluster restore point with the same configuration as the original source DB cluster, except that the new cluster is created with the default security group. """ def restore_db_cluster_from_snapshot(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RestoreDBClusterFromSnapshot", input, options) end @doc """ Restores a cluster to an arbitrary point in time. Users can restore to any point in time before `LatestRestorableTime` for up to `BackupRetentionPeriod` days. The target cluster is created from the source cluster with the same configuration as the original cluster, except that the new cluster is created with the default security group. """ def restore_db_cluster_to_point_in_time(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RestoreDBClusterToPointInTime", input, options) end @doc """ Restarts the stopped cluster that is specified by `DBClusterIdentifier`. For more information, see [Stopping and Starting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html). """ def start_db_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "StartDBCluster", input, options) end @doc """ Stops the running cluster that is specified by `DBClusterIdentifier`. The cluster must be in the *available* state. For more information, see [Stopping and Starting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html). """ def stop_db_cluster(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "StopDBCluster", input, options) end end
39.9653
170
0.740429
0856cc5ba31ca1d0862a774685a6369d3816b396
618
ex
Elixir
test/support/acceptance_case.ex
abratashov/shortly
39dbf813f0cf643525b9038adb39764466e75d5e
[ "MIT" ]
null
null
null
test/support/acceptance_case.ex
abratashov/shortly
39dbf813f0cf643525b9038adb39764466e75d5e
[ "MIT" ]
null
null
null
test/support/acceptance_case.ex
abratashov/shortly
39dbf813f0cf643525b9038adb39764466e75d5e
[ "MIT" ]
null
null
null
defmodule Shortly.AcceptanceCase do use ExUnit.CaseTemplate using do quote do use Wallaby.DSL alias Shortly.Repo import Ecto import Ecto.Changeset import Ecto.Query import ShortlyWeb.Router.Helpers end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Shortly.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Shortly.Repo, {:shared, self()}) end metadata = Phoenix.Ecto.SQL.Sandbox.metadata_for(Shortly.Repo, self()) {:ok, session} = Wallaby.start_session(metadata: metadata) {:ok, session: session} end end
21.310345
74
0.677994
0856d90b40f3847e913ec069a2920a3c0f867b17
1,992
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/operations_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/operations_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/operations_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.SQLAdmin.V1beta4.Model.OperationsListResponse do @moduledoc """ Database instance list operations response. ## Attributes * `items` (*type:* `list(GoogleApi.SQLAdmin.V1beta4.Model.Operation.t)`, *default:* `nil`) - List of operation resources. * `kind` (*type:* `String.t`, *default:* `nil`) - This is always *sql#operationsList*. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :items => list(GoogleApi.SQLAdmin.V1beta4.Model.Operation.t()), :kind => String.t(), :nextPageToken => String.t() } field(:items, as: GoogleApi.SQLAdmin.V1beta4.Model.Operation, type: :list) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.OperationsListResponse do def decode(value, options) do GoogleApi.SQLAdmin.V1beta4.Model.OperationsListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.OperationsListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.584906
205
0.72992
0856e0ecdf2153a76bd32898756fcb9862291886
1,334
ex
Elixir
lib/auto_api/commands/rooftop_control_command.ex
nonninz/auto-api-elixir
53e11542043285e94bbb5a0a3b8ffff0b1b47167
[ "MIT" ]
null
null
null
lib/auto_api/commands/rooftop_control_command.ex
nonninz/auto-api-elixir
53e11542043285e94bbb5a0a3b8ffff0b1b47167
[ "MIT" ]
null
null
null
lib/auto_api/commands/rooftop_control_command.ex
nonninz/auto-api-elixir
53e11542043285e94bbb5a0a3b8ffff0b1b47167
[ "MIT" ]
null
null
null
# AutoAPI # The MIT License # # Copyright (c) 2018- High-Mobility GmbH (https://high-mobility.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. defmodule AutoApi.RooftopControlCommand do @moduledoc """ Handles Hood commands and apply binary commands on `%AutoApi.RooftopControlState{}` """ use AutoApi.Command end
46
85
0.774363
0856e875ed9ccbf60915ed3494a74d593f2e7e57
551
ex
Elixir
rocketpay/lib/rocketpay_web/controllers/welcome_controller.ex
Samuel-Ricardo/RocketPay
aeec9d00fd04de8b1541f5369dcdcb2cb5e03807
[ "MIT" ]
3
2021-02-24T02:55:37.000Z
2021-07-14T18:55:40.000Z
rocketpay/lib/rocketpay_web/controllers/welcome_controller.ex
Samuel-Ricardo/RocketPay
aeec9d00fd04de8b1541f5369dcdcb2cb5e03807
[ "MIT" ]
null
null
null
rocketpay/lib/rocketpay_web/controllers/welcome_controller.ex
Samuel-Ricardo/RocketPay
aeec9d00fd04de8b1541f5369dcdcb2cb5e03807
[ "MIT" ]
1
2021-03-13T01:32:40.000Z
2021-03-13T01:32:40.000Z
defmodule RocketpayWeb.WelcomeController do use RocketpayWeb, :controller alias Rocketpay.Numbers def index(connection, %{"filename" => filename}) do filename |>Numbers.sum_from_file() |>handle_response(connection) end defp handle_response({:ok, %{result: result}}, conn) do conn |> put_status(:ok) |> json(%{message: "Welcome to rocket API your number is: #{result}"}) end defp handle_response({:error, reason}, conn) do conn |> put_status(:bad_request) |> json(reason) end end
19.678571
76
0.653358
0856ef34d4f614182f9fa7f9f29e8c59279b0b1b
641
ex
Elixir
elixir/advent_of_code/lib/day3/part1.ex
childss/aoc-2016
8570cf4bcf42e1ea85cfdf5e3444baf71c5c5312
[ "MIT" ]
null
null
null
elixir/advent_of_code/lib/day3/part1.ex
childss/aoc-2016
8570cf4bcf42e1ea85cfdf5e3444baf71c5c5312
[ "MIT" ]
null
null
null
elixir/advent_of_code/lib/day3/part1.ex
childss/aoc-2016
8570cf4bcf42e1ea85cfdf5e3444baf71c5c5312
[ "MIT" ]
null
null
null
defmodule Day3.Part1 do def run(input) do input |> File.read! |> parse_input |> count_triangles end defp parse_input(input) do for line <- String.split(input, "\n", trim: true), sides = String.split(line, " ", trim: true), do: Enum.map(sides, &String.to_integer/1) end defp count_triangles(candidates) do Enum.count(candidates, &is_triangle?/1) end defp is_triangle?(candidate) do candidate |> permute |> Enum.all?(fn [a, b, c] -> a + b > c end) end defp permute([]), do: [[]] defp permute(list) do for x <- list, y <- permute(list -- [x]), do: [x|y] end end
21.366667
55
0.592824
0856f1e55ee2eebfab201fcff75351e9148a216f
2,318
ex
Elixir
clients/slides/lib/google_api/slides/v1/model/update_line_properties_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/slides/lib/google_api/slides/v1/model/update_line_properties_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/slides/lib/google_api/slides/v1/model/update_line_properties_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Slides.V1.Model.UpdateLinePropertiesRequest do @moduledoc """ Updates the properties of a Line. ## Attributes * `fields` (*type:* `String.t`, *default:* `nil`) - The fields that should be updated. At least one field must be specified. The root `lineProperties` is implied and should not be specified. A single `"*"` can be used as short-hand for listing every field. For example to update the line solid fill color, set `fields` to `"lineFill.solidFill.color"`. To reset a property to its default value, include its field name in the field mask but leave the field itself unset. * `lineProperties` (*type:* `GoogleApi.Slides.V1.Model.LineProperties.t`, *default:* `nil`) - The line properties to update. * `objectId` (*type:* `String.t`, *default:* `nil`) - The object ID of the line the update is applied to. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :fields => String.t(), :lineProperties => GoogleApi.Slides.V1.Model.LineProperties.t(), :objectId => String.t() } field(:fields) field(:lineProperties, as: GoogleApi.Slides.V1.Model.LineProperties) field(:objectId) end defimpl Poison.Decoder, for: GoogleApi.Slides.V1.Model.UpdateLinePropertiesRequest do def decode(value, options) do GoogleApi.Slides.V1.Model.UpdateLinePropertiesRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Slides.V1.Model.UpdateLinePropertiesRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.793651
128
0.719154
08570b91afbb1b48bb21ae57c2c32b2b5bd375d1
626
exs
Elixir
test/absinthe/federation/notation_test.exs
trbngr/absinthe_federation
7ebe9c26c16ea088e42914df9797acd04e9d9894
[ "MIT" ]
40
2021-06-26T08:43:50.000Z
2022-03-30T15:41:08.000Z
test/absinthe/federation/notation_test.exs
trbngr/absinthe_federation
7ebe9c26c16ea088e42914df9797acd04e9d9894
[ "MIT" ]
22
2021-07-14T20:01:08.000Z
2022-03-31T15:58:02.000Z
test/absinthe/federation/notation_test.exs
trbngr/absinthe_federation
7ebe9c26c16ea088e42914df9797acd04e9d9894
[ "MIT" ]
4
2021-08-23T14:38:41.000Z
2021-11-30T00:16:19.000Z
defmodule Absinthe.Federation.NotationTest do use Absinthe.Federation.Case, async: true describe "macro schema" do defmodule MacroSchema do use Absinthe.Schema use Absinthe.Federation.Schema query do field :me, :user end object :user do key_fields("id") extends() field :id, non_null(:id) do external() end end end test "can use federation macros" do sdl = Absinthe.Schema.to_sdl(MacroSchema) assert sdl =~ "type User @extends @key(fields: \"id\")" assert sdl =~ "id: ID! @external" end end end
20.866667
61
0.602236
085743db919a3af699d32409f96fbfa52b86e4ee
4,041
ex
Elixir
apps/artemis_web/lib/artemis_web/controllers/wiki_page_controller.ex
artemis-platform/artemis_dashboard
5ab3f5ac4c5255478bbebf76f0e43b44992e3cab
[ "MIT" ]
9
2019-08-19T19:56:34.000Z
2022-03-22T17:56:38.000Z
apps/artemis_web/lib/artemis_web/controllers/wiki_page_controller.ex
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
7
2019-07-12T21:41:01.000Z
2020-08-17T21:29:22.000Z
apps/artemis_web/lib/artemis_web/controllers/wiki_page_controller.ex
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
2
2019-04-10T13:34:15.000Z
2019-05-17T02:42:24.000Z
defmodule ArtemisWeb.WikiPageController do use ArtemisWeb, :controller use ArtemisWeb.Controller.CommentsShow, path: &Routes.wiki_page_path/3, permission: "wiki-pages:show", resource_getter: &Artemis.GetWikiPage.call!/2, resource_id_key: "wiki_page_id", resource_type: "WikiPage" alias Artemis.CreateWikiPage alias Artemis.DeleteWikiPage alias Artemis.GetWikiPage alias Artemis.ListWikiPages alias Artemis.UpdateWikiPage alias Artemis.WikiPage @default_section "General" @preload [] def index(conn, params) do authorize(conn, "wiki-pages:list", fn -> user = current_user(conn) params = Map.put(params, :paginate, true) tags = get_tags("wiki-pages", user) wiki_pages = ListWikiPages.call(params, user) render(conn, "index.html", tags: tags, wiki_pages: wiki_pages) end) end def new(conn, _params) do authorize(conn, "wiki-pages:create", fn -> wiki_page = %WikiPage{} changeset = WikiPage.changeset(wiki_page) user = current_user(conn) sections = get_sections(user) render(conn, "new.html", changeset: changeset, sections: sections, wiki_page: wiki_page) end) end def create(conn, %{"wiki_page" => params}) do authorize(conn, "wiki-pages:create", fn -> user = current_user(conn) params = Map.put(params, "user_id", user.id) case CreateWikiPage.call(params, user) do {:ok, wiki_page} -> conn |> put_flash(:info, "Page created successfully.") |> redirect(to: Routes.wiki_page_path(conn, :show, wiki_page)) {:error, %Ecto.Changeset{} = changeset} -> wiki_page = %WikiPage{} sections = get_sections(user) render(conn, "new.html", changeset: changeset, sections: sections, wiki_page: wiki_page) end end) end def show(conn, %{"id" => id}) do authorize(conn, "wiki-pages:show", fn -> user = current_user(conn) wiki_page = GetWikiPage.call!(id, user) tags = get_tags("wiki-pages", user) tags_changeset = WikiPage.changeset(wiki_page) render(conn, "show.html", tags: tags, tags_changeset: tags_changeset, wiki_page: wiki_page ) end) end def edit(conn, %{"id" => id}) do authorize(conn, "wiki-pages:update", fn -> wiki_page = GetWikiPage.call(id, current_user(conn), preload: @preload) changeset = WikiPage.changeset(wiki_page) user = current_user(conn) sections = get_sections(user) render(conn, "edit.html", changeset: changeset, sections: sections, wiki_page: wiki_page) end) end def update(conn, %{"id" => id, "wiki_page" => params}) do authorize(conn, "wiki-pages:update", fn -> user = current_user(conn) params = Map.put(params, "user_id", user.id) case UpdateWikiPage.call(id, params, user) do {:ok, wiki_page} -> conn |> put_flash(:info, "Page updated successfully.") |> redirect(to: Routes.wiki_page_path(conn, :show, wiki_page)) {:error, %Ecto.Changeset{} = changeset} -> wiki_page = GetWikiPage.call(id, current_user(conn), preload: @preload) sections = get_sections(user) render(conn, "edit.html", changeset: changeset, sections: sections, wiki_page: wiki_page) end end) end def delete(conn, %{"id" => id}) do authorize(conn, "wiki-pages:delete", fn -> {:ok, _wiki_page} = DeleteWikiPage.call(id, current_user(conn)) conn |> put_flash(:info, "Page deleted successfully.") |> redirect(to: Routes.wiki_page_path(conn, :index)) end) end # Helpers defp get_sections(user) do sections = %{distinct: :section} |> ListWikiPages.call(user) |> Enum.map(& &1.section) case Enum.member?(sections, @default_section) do true -> omitted = List.delete(sections, @default_section) [@default_section | omitted] false -> [@default_section | sections] end end end
29.282609
99
0.636229
085767269bb9b9311dab2e6c039d642ee1b99b63
302
exs
Elixir
adv_2020/test/day_19_test.exs
SamuelSarle/advent
31025f7b081826cb51b37a2d8b8d263413b71086
[ "Unlicense" ]
null
null
null
adv_2020/test/day_19_test.exs
SamuelSarle/advent
31025f7b081826cb51b37a2d8b8d263413b71086
[ "Unlicense" ]
null
null
null
adv_2020/test/day_19_test.exs
SamuelSarle/advent
31025f7b081826cb51b37a2d8b8d263413b71086
[ "Unlicense" ]
null
null
null
defmodule DayNineteenTest do use ExUnit.Case test "returns correct result" do input = """ 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb """ assert DayNineteen.solve(input) == 2 end end
13.130435
40
0.523179
085767e635e9fa5c47375aa7899cb13121738287
845
ex
Elixir
lib/automata/core/automaton/types/typology.ex
venomnert/automata
26b9bf3cb57fa8bc152fac8992ddcfe07c6e07a9
[ "Apache-2.0" ]
null
null
null
lib/automata/core/automaton/types/typology.ex
venomnert/automata
26b9bf3cb57fa8bc152fac8992ddcfe07c6e07a9
[ "Apache-2.0" ]
null
null
null
lib/automata/core/automaton/types/typology.ex
venomnert/automata
26b9bf3cb57fa8bc152fac8992ddcfe07c6e07a9
[ "Apache-2.0" ]
null
null
null
defmodule Automaton.Types.Typology do @moduledoc """ ## Types are builtin state space representations. Typology is for interpretation of what state space representation to use based on user configuration. Each type has a `config/` dir to handle user config parsing and interpretation specific to its domain. """ alias Automaton.Types.BT @types [:behavior_tree] def types, do: @types # @spec call(nonempty_list()) :: nonempty_list() def call(automaton_config) do type = automaton_config[:type] |> case do :behavior_tree -> quote do: use(BT, automaton_config: unquote(automaton_config)) # TODO: need this for children. # use parent type? raise error? nil -> quote do: use(BT, automaton_config: unquote(automaton_config)) end [type] end end
27.258065
80
0.674556
0857a6f60f38da27f1c4db9ab6dc83d18cf02799
1,224
ex
Elixir
api/lib/contracts/agreements/part/account.ex
abmBispo/Contracts
9e7fad225d6da26ba719f55943dc5a3de03fb02b
[ "MIT" ]
1
2020-08-17T21:31:04.000Z
2020-08-17T21:31:04.000Z
api/lib/contracts/agreements/part/account.ex
abmBispo/Contracts
9e7fad225d6da26ba719f55943dc5a3de03fb02b
[ "MIT" ]
null
null
null
api/lib/contracts/agreements/part/account.ex
abmBispo/Contracts
9e7fad225d6da26ba719f55943dc5a3de03fb02b
[ "MIT" ]
1
2021-03-21T16:17:29.000Z
2021-03-21T16:17:29.000Z
defmodule Contracts.Agreements.Part.Account do use Ecto.Schema import Ecto.Changeset alias Contracts.Agreements.{ Part.Profile, Relation } @fields [:email, :password] schema "accounts" do field :email, :string field :password, :string has_one :profile, Profile has_many :relations, Relation has_many :contracts, through: [:relations, :contract] timestamps() end def changeset(account, :create, attrs) do account |> cast(attrs, @fields) |> put_change(:password, "123456") |> put_password() |> validate_required(@fields) |> unique_constraint(:email) end def changeset(account, :update, attrs) do profile = Profile.changeset(account.profile, :update, %{ id: account.profile.id, name: attrs["name"], tax_id: attrs["tax_id"], telephone: attrs["telephone"] }) account |> cast(attrs, @fields) |> put_assoc(:profile, profile) |> validate_required(@fields) |> unique_constraint(:email) end defp put_password(%{valid?: true, changes: %{password: password}} = changeset) do change(changeset, password: Argon2.hash_pwd_salt(password)) end defp put_password(changeset), do: changeset end
23.538462
83
0.665033
0857c419edf6d26298aa1f41a834c85e1b8c7033
1,126
ex
Elixir
test/support/conn_case.ex
niklas/prometheus-phx
3183672a86f00433b58f76fcdf4e08c1955053fa
[ "Apache-2.0" ]
5
2020-09-19T22:29:41.000Z
2021-03-28T03:17:00.000Z
test/support/conn_case.ex
niklas/prometheus-phx
3183672a86f00433b58f76fcdf4e08c1955053fa
[ "Apache-2.0" ]
1
2021-04-15T19:03:45.000Z
2021-04-15T19:03:45.000Z
test/support/conn_case.ex
niklas/prometheus-phx
3183672a86f00433b58f76fcdf4e08c1955053fa
[ "Apache-2.0" ]
4
2020-10-29T15:28:08.000Z
2021-12-15T17:44:31.000Z
defmodule PrometheusPhxTestWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use PrometheusPhxTestWeb.ConnCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections import Plug.Conn import Phoenix.ConnTest import PrometheusPhxTestWeb.ConnCase alias PrometheusPhxTestWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint PrometheusPhxTestWeb.Endpoint end end setup _tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
29.631579
71
0.746004
0857cad4e617d1db3f9aeccc94e558c978698f5d
199
exs
Elixir
test/timetracker_web/controllers/work_block_controller_test.exs
LunarLogic/timetracker
5c2ffffc9023c7b099d7af8de7f21225352483ca
[ "MIT" ]
1
2019-06-26T06:53:01.000Z
2019-06-26T06:53:01.000Z
test/timetracker_web/controllers/work_block_controller_test.exs
LunarLogic/timetracker
5c2ffffc9023c7b099d7af8de7f21225352483ca
[ "MIT" ]
null
null
null
test/timetracker_web/controllers/work_block_controller_test.exs
LunarLogic/timetracker
5c2ffffc9023c7b099d7af8de7f21225352483ca
[ "MIT" ]
null
null
null
defmodule TimetrackerWeb.WorkBlockControllerTest do use TimetrackerWeb.ConnCase test "GET /", %{conn: conn} do conn = get(conn, "/") assert html_response(conn, 200) =~ "Start" end end
22.111111
51
0.693467
0857e42ea74b46b13b7adee124eada13cb54c456
12,647
ex
Elixir
lib/geometry/geometry_collection_z.ex
hrzndhrn/geometry
bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60
[ "MIT" ]
null
null
null
lib/geometry/geometry_collection_z.ex
hrzndhrn/geometry
bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60
[ "MIT" ]
2
2020-10-25T10:06:07.000Z
2020-10-26T18:15:20.000Z
lib/geometry/geometry_collection_z.ex
hrzndhrn/geometry
bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60
[ "MIT" ]
null
null
null
defmodule Geometry.GeometryCollectionZ do @moduledoc """ A collection set of 3D geometries. `GeometryCollectionZ` implements the protocols `Enumerable` and `Collectable`. ## Examples iex> Enum.map( ...> GeometryCollectionZ.new([ ...> PointZ.new(11, 12, 13), ...> LineStringZ.new([ ...> PointZ.new(21, 22, 23), ...> PointZ.new(31, 32, 33) ...> ]) ...> ]), ...> fn ...> %PointZ{} -> :point ...> %LineStringZ{} -> :line_string ...> end ...> ) |> Enum.sort() [:line_string, :point] iex> Enum.into([PointZ.new(1, 2, 3)], GeometryCollectionZ.new()) %GeometryCollectionZ{ geometries: MapSet.new([%PointZ{coordinate: [1, 2, 3]}]) } """ alias Geometry.{ GeoJson, GeometryCollectionZ, WKB, WKT } defstruct geometries: MapSet.new() @type t :: %GeometryCollectionZ{geometries: MapSet.t(Geometry.t())} @doc """ Creates an empty `GeometryCollectionZ`. ## Examples iex> GeometryCollectionZ.new() %GeometryCollectionZ{geometries: MapSet.new()} """ @spec new :: t() def new, do: %GeometryCollectionZ{} @doc """ Creates an empty `GeometryCollectionZ`. ## Examples iex> GeometryCollectionZ.new([ ...> PointZ.new(1, 2, 3), ...> LineStringZ.new([PointZ.new(1, 1, 1), PointZ.new(2, 2, 2)]) ...> ]) %GeometryCollectionZ{geometries: MapSet.new([ %PointZ{coordinate: [1, 2, 3]}, %LineStringZ{points: [[1, 1, 1], [2, 2, 2]]} ])} """ @spec new([Geometry.t()]) :: t() def new(geometries), do: %GeometryCollectionZ{geometries: MapSet.new(geometries)} @doc """ Returns `true` if the given `GeometryCollectionZ` is empty. ## Examples iex> GeometryCollectionZ.empty?(GeometryCollectionZ.new()) true iex> GeometryCollectionZ.empty?(GeometryCollectionZ.new([PointZ.new(1, 2, 3)])) false """ @spec empty?(t()) :: boolean def empty?(%GeometryCollectionZ{geometries: geometries}), do: Enum.empty?(geometries) @doc """ Returns the WKT representation for a `GeometryCollectionZ`. With option `:srid` an EWKT representation with the SRID is returned. ## Examples iex> GeometryCollectionZ.to_wkt(GeometryCollectionZ.new()) "GeometryCollection Z EMPTY" iex> GeometryCollectionZ.to_wkt( ...> GeometryCollectionZ.new([ ...> PointZ.new(1.1, 1.2, 1.3), ...> PointZ.new(2.1, 2.2, 2.3) ...> ]) ...> ) "GeometryCollection Z (Point Z (1.1 1.2 1.3), Point Z (2.1 2.2 2.3))" iex> GeometryCollectionZ.to_wkt( ...> GeometryCollectionZ.new([PointZ.new(1.1, 2.2, 3.3)]), ...> srid: 4711) "SRID=4711;GeometryCollection Z (Point Z (1.1 2.2 3.3))" """ @spec to_wkt(t(), opts) :: Geometry.wkt() when opts: [srid: Geometry.srid()] def to_wkt(%GeometryCollectionZ{geometries: geometries}, opts \\ []) do WKT.to_ewkt( << "GeometryCollection Z ", geometries |> MapSet.to_list() |> to_wkt_geometries()::binary() >>, opts ) end @doc """ Returns an `:ok` tuple with the `GeometryCollectionZ` from the given WKT string. Otherwise returns an `:error` tuple. If the geometry contains a SRID the id is added to the tuple. ## Examples iex> GeometryCollectionZ.from_wkt( ...> "GeometryCollection Z (Point Z (1.1 2.2 3.3))") { :ok, %GeometryCollectionZ{ geometries: MapSet.new([%PointZ{coordinate: [1.1, 2.2, 3.3]}]) } } iex> GeometryCollectionZ.from_wkt( ...> "SRID=123;GeometryCollection Z (Point Z (1.1 2.2 3.3))") {:ok, { %GeometryCollectionZ{ geometries: MapSet.new([%PointZ{coordinate: [1.1, 2.2, 3.3]}]) }, 123 }} iex> GeometryCollectionZ.from_wkt("GeometryCollection Z EMPTY") {:ok, %GeometryCollectionZ{}} """ @spec from_wkt(Geometry.wkt()) :: {:ok, t() | {t(), Geometry.srid()}} | Geometry.wkt_error() def from_wkt(wkt), do: WKT.to_geometry(wkt, GeometryCollectionZ) @doc """ The same as `from_wkt/1`, but raises a `Geometry.Error` exception if it fails. """ @spec from_wkt!(Geometry.wkt()) :: t() | {t(), Geometry.srid()} def from_wkt!(wkt) do case WKT.to_geometry(wkt, GeometryCollectionZ) do {:ok, geometry} -> geometry error -> raise Geometry.Error, error end end @doc """ Returns the GeoJSON term of a `GeometryCollectionZ`. ## Examples iex> GeometryCollectionZ.to_geo_json( ...> GeometryCollectionZ.new([PointZ.new(1.1, 2.2, 3.3)])) %{ "type" => "GeometryCollection", "geometries" => [ %{ "type" => "Point", "coordinates" => [1.1, 2.2, 3.3] } ] } """ @spec to_geo_json(t()) :: Geometry.geo_json_term() def to_geo_json(%GeometryCollectionZ{geometries: geometries}) do %{ "type" => "GeometryCollection", "geometries" => Enum.map(geometries, fn geometry -> Geometry.to_geo_json(geometry) end) } end @doc """ Returns an `:ok` tuple with the `GeometryCollectionZ` from the given GeoJSON term. Otherwise returns an `:error` tuple. ## Examples iex> ~s({ ...> "type": "GeometryCollection", ...> "geometries": [ ...> {"type": "Point", "coordinates": [1.1, 2.2, 3.3]} ...> ] ...> }) iex> |> Jason.decode!() iex> |> GeometryCollectionZ.from_geo_json() { :ok, %GeometryCollectionZ{ geometries: MapSet.new([%PointZ{coordinate: [1.1, 2.2, 3.3]}]) } } """ @spec from_geo_json(Geometry.geo_json_term()) :: {:ok, t()} | Geometry.geo_json_error() def from_geo_json(json) do GeoJson.to_geometry_collection(json, GeometryCollectionZ, type: :z) end @doc """ The same as `from_geo_json/1`, but raises a `Geometry.Error` exception if it fails. """ @spec from_geo_json!(Geometry.geo_json_term()) :: t() def from_geo_json!(json) do case GeoJson.to_geometry_collection(json, GeometryCollectionZ, type: :z) do {:ok, geometry} -> geometry error -> raise Geometry.Error, error end end @doc """ Returns the WKB representation for a `GeometryCollectionZ`. With option `:srid` an EWKB representation with the SRID is returned. The option `endian` indicates whether `:xdr` big endian or `:ndr` little endian is returned. The default is `:ndr`. The `:mode` determines whether a hex-string or binary is returned. The default is `:binary`. An example of a simpler geometry can be found in the description for the `Geometry.PointZ.to_wkb/1` function. """ @spec to_wkb(t(), opts) :: Geometry.wkb() when opts: [endian: Geometry.endian(), srid: Geometry.srid()] def to_wkb(%GeometryCollectionZ{geometries: geometries}, opts \\ []) do endian = Keyword.get(opts, :endian, Geometry.default_endian()) mode = Keyword.get(opts, :mode, Geometry.default_mode()) srid = Keyword.get(opts, :srid) << WKB.byte_order(endian, mode)::binary(), wkb_code(endian, not is_nil(srid), mode)::binary(), WKB.srid(srid, endian, mode)::binary(), to_wkb_geometries(geometries, endian, mode)::binary() >> end @doc """ Returns an `:ok` tuple with the `GeometryCollectionZ` from the given WKB string. Otherwise returns an `:error` tuple. If the geometry contains a SRID the id is added to the tuple. An example of a simpler geometry can be found in the description for the `Geometry.PointZ.from_wkb/2` function. """ @spec from_wkb(Geometry.wkb(), Geometry.mode()) :: {:ok, t() | {t(), Geometry.srid()}} | Geometry.wkb_error() def from_wkb(wkb, mode \\ :binary), do: WKB.to_geometry(wkb, mode, GeometryCollectionZ) @doc """ The same as `from_wkb/2`, but raises a `Geometry.Error` exception if it fails. """ @spec from_wkb!(Geometry.wkb(), Geometry.mode()) :: t() | {t(), Geometry.srid()} def from_wkb!(wkb, mode \\ :binary) do case WKB.to_geometry(wkb, mode, GeometryCollectionZ) do {:ok, geometry} -> geometry error -> raise Geometry.Error, error end end @doc """ Returns the number of elements in `GeometryCollectionZ`. ## Examples iex> GeometryCollectionZ.size( ...> GeometryCollectionZ.new([ ...> PointZ.new(11, 12, 13), ...> LineStringZ.new([ ...> PointZ.new(21, 22, 23), ...> PointZ.new(31, 32, 33) ...> ]) ...> ]) ...> ) 2 """ @spec size(t()) :: non_neg_integer() def size(%GeometryCollectionZ{geometries: geometries}), do: MapSet.size(geometries) @doc """ Checks if `GeometryCollectionZ` contains `geometry`. ## Examples iex> GeometryCollectionZ.member?( ...> GeometryCollectionZ.new([ ...> PointZ.new(11, 12, 13), ...> LineStringZ.new([ ...> PointZ.new(21, 22, 23), ...> PointZ.new(31, 32, 33) ...> ]) ...> ]), ...> PointZ.new(11, 12, 13) ...> ) true iex> GeometryCollectionZ.member?( ...> GeometryCollectionZ.new([ ...> PointZ.new(11, 12, 13), ...> LineStringZ.new([ ...> PointZ.new(21, 22, 23), ...> PointZ.new(31, 32, 33) ...> ]) ...> ]), ...> PointZ.new(1, 2, 3) ...> ) false """ @spec member?(t(), Geometry.t()) :: boolean() def member?(%GeometryCollectionZ{geometries: geometries}, geometry), do: MapSet.member?(geometries, geometry) @doc """ Converts `GeometryCollectionZ` to a list. ## Examples iex> GeometryCollectionZ.to_list( ...> GeometryCollectionZ.new([ ...> PointZ.new(11, 12, 13) ...> ]) ...> ) [%PointZ{coordinate: [11, 12, 13]}] """ @spec to_list(t()) :: [Geometry.t()] def to_list(%GeometryCollectionZ{geometries: geometries}), do: MapSet.to_list(geometries) @compile {:inline, to_wkt_geometries: 1} defp to_wkt_geometries([]), do: "EMPTY" defp to_wkt_geometries([geometry | geometries]) do <<"(", Enum.reduce(geometries, Geometry.to_wkt(geometry), fn %module{} = geometry, acc -> <<acc::binary(), ", ", module.to_wkt(geometry)::binary()>> end)::binary(), ")">> end @compile {:inline, to_wkb_geometries: 3} defp to_wkb_geometries(geometries, endian, mode) do Enum.reduce(geometries, WKB.length(geometries, endian, mode), fn %module{} = geometry, acc -> <<acc::binary(), module.to_wkb(geometry, endian: endian, mode: mode)::binary()>> end) end @compile {:inline, wkb_code: 3} defp wkb_code(endian, srid?, :hex) do case {endian, srid?} do {:xdr, false} -> "80000007" {:ndr, false} -> "07000080" {:xdr, true} -> "A0000007" {:ndr, true} -> "070000A0" end end defp wkb_code(endian, srid?, :binary) do case {endian, srid?} do {:xdr, false} -> <<0x80000007::big-integer-size(32)>> {:ndr, false} -> <<0x80000007::little-integer-size(32)>> {:xdr, true} -> <<0xA0000007::big-integer-size(32)>> {:ndr, true} -> <<0xA0000007::little-integer-size(32)>> end end defimpl Enumerable do # credo:disable-for-next-line Credo.Check.Readability.Specs def count(geometry_collection) do {:ok, GeometryCollectionZ.size(geometry_collection)} end # credo:disable-for-next-line Credo.Check.Readability.Specs def member?(geometry_collection, val) do {:ok, GeometryCollectionZ.member?(geometry_collection, val)} end # credo:disable-for-next-line Credo.Check.Readability.Specs def slice(geometry_collection) do size = GeometryCollectionZ.size(geometry_collection) {:ok, size, &Enumerable.List.slice(GeometryCollectionZ.to_list(geometry_collection), &1, &2, size)} end # credo:disable-for-next-line Credo.Check.Readability.Specs def reduce(geometry_collection, acc, fun) do Enumerable.List.reduce(GeometryCollectionZ.to_list(geometry_collection), acc, fun) end end defimpl Collectable do # credo:disable-for-next-line Credo.Check.Readability.Specs def into(%GeometryCollectionZ{geometries: geometries}) do fun = fn list, {:cont, x} -> [{x, []} | list] list, :done -> %GeometryCollectionZ{ geometries: %{geometries | map: Map.merge(geometries.map, Map.new(list))} } _list, :halt -> :ok end {[], fun} end end end
29.618267
97
0.593817
0857eb6d2e0cad37478a7a5b2c1e7def086c59d8
505
exs
Elixir
test/unit/hologram/compiler/transformers/unary_negative_operator_transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
40
2022-01-19T20:27:36.000Z
2022-03-31T18:17:41.000Z
test/unit/hologram/compiler/transformers/unary_negative_operator_transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
42
2022-02-03T22:52:43.000Z
2022-03-26T20:57:32.000Z
test/unit/hologram/compiler/transformers/unary_negative_operator_transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
3
2022-02-10T04:00:37.000Z
2022-03-08T22:07:45.000Z
defmodule Hologram.Compiler.UnaryNegativeOperatorTransformerTest do use Hologram.Test.UnitCase, async: true alias Hologram.Compiler.{Context, UnaryNegativeOperatorTransformer} alias Hologram.Compiler.IR.{IntegerType, UnaryNegativeOperator} test "transform/3" do code = "-2" ast = ast(code) result = UnaryNegativeOperatorTransformer.transform(ast, %Context{}) expected = %UnaryNegativeOperator{ value: %IntegerType{value: 2} } assert result == expected end end
25.25
72
0.742574
0857fa3fd13b7ec5f95fdf5035aa981bb6fe20e8
1,867
exs
Elixir
clients/testing/mix.exs
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/testing/mix.exs
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/testing/mix.exs
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "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.Testing.Mixfile do use Mix.Project @version "0.20.0" def project() do [ app: :google_api_testing, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/testing" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Testing API client library. Allows developers to run automated tests for their mobile applications on Google infrastructure. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/testing", "Homepage" => "https://developers.google.com/cloud-test-lab/" } ] end end
27.865672
134
0.658275
0857fcc54704ceaefb501b311bd2dce021e6a4d4
2,211
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p3beta1_product_search_results_object_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p3beta1_product_search_results_object_annotation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p3beta1_product_search_results_object_annotation.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.Vision.V1.Model.GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation do @moduledoc """ Prediction for what the object in the bounding box is. ## Attributes * `languageCode` (*type:* `String.t`, *default:* `nil`) - The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. * `mid` (*type:* `String.t`, *default:* `nil`) - Object ID that should align with EntityAnnotation mid. * `name` (*type:* `String.t`, *default:* `nil`) - Object name, expressed in its `language_code` language. * `score` (*type:* `number()`, *default:* `nil`) - Score of the result. Range [0, 1]. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :languageCode => String.t() | nil, :mid => String.t() | nil, :name => String.t() | nil, :score => number() | nil } field(:languageCode) field(:mid) field(:name) field(:score) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.245902
207
0.713704
085808ba87a119a025c150ef64bf07ba61ea2ee0
3,417
exs
Elixir
test/multipart_test.exs
kf8a/multipart
b1fbb0bdc5345045d516170fa0a572f56741e3ce
[ "MIT" ]
null
null
null
test/multipart_test.exs
kf8a/multipart
b1fbb0bdc5345045d516170fa0a572f56741e3ce
[ "MIT" ]
null
null
null
test/multipart_test.exs
kf8a/multipart
b1fbb0bdc5345045d516170fa0a572f56741e3ce
[ "MIT" ]
null
null
null
defmodule MultipartTest do use ExUnit.Case doctest Multipart @boundary "==testboundary==" alias Multipart.Part test "building a message of binary parts" do expected_output = File.read!(file_path("/outputs/binary_parts_message.txt")) multipart = Multipart.new(@boundary) |> Multipart.add_part(Part.binary_body("first body")) |> Multipart.add_part(Part.binary_body("second body\r\n", [{"content-type", "text/plain"}])) |> Multipart.add_part(Part.binary_body("third body")) output = Multipart.body_binary(multipart) assert output == expected_output content_length = Multipart.content_length(multipart) assert content_length == Multipart.octet_length(expected_output) end test "building a message of file parts" do expected_output = File.read!(file_path("outputs/file_parts_message.txt")) multipart = Multipart.new(@boundary) |> Multipart.add_part(Part.file_body(file_path("files/test.json"))) |> Multipart.add_part(Part.file_body(file_path("files/test.txt"))) output = Multipart.body_binary(multipart) assert output == expected_output content_length = Multipart.content_length(multipart) assert content_length == Multipart.octet_length(expected_output) end test "building a message of text form-data parts" do expected_output = File.read!(file_path("outputs/text_form_data_parts_message.txt")) multipart = Multipart.new(@boundary) |> Multipart.add_part(Part.text_field("abc", "field1")) |> Multipart.add_part(Part.text_field("def", "field2")) output = Multipart.body_binary(multipart) assert output == expected_output content_length = Multipart.content_length(multipart) assert content_length == Multipart.octet_length(expected_output) end test "building a message of file form-data parts" do expected_output = File.read!(file_path("outputs/file_form_data_parts_message.txt")) multipart = Multipart.new(@boundary) |> Multipart.add_part(Part.file_field(file_path("files/test.json"), "attachment")) |> Multipart.add_part( Part.file_field(file_path("files/test.txt"), "attachment_2", [], filename: "attachment.txt" ) ) |> Multipart.add_part( Part.file_field(file_path("files/test.txt"), "attachment_3", [], content_type: "application/octet-stream", filename: false ) ) output = Multipart.body_binary(multipart) assert output == expected_output content_length = Multipart.content_length(multipart) assert content_length == Multipart.octet_length(expected_output) end test "building a message preserves original line breaks" do multipart = Multipart.new(@boundary) |> Multipart.add_part(Part.file_field(file_path("files/test-crlf.txt"), "text")) output = Multipart.body_binary(multipart) header = "\r\n--#{@boundary}\r\ncontent-type: text/plain\r\ncontent-disposition: form-data; name=\"text\"; filename=\"test-crlf.txt\"\r\n\r\n" body = File.read!(file_path("files/test-crlf.txt")) footer = "\r\n--#{@boundary}--\r\n" expected_output = header <> body <> footer assert output == expected_output end test "counting octets correctly" do str = "abc\r\n" assert Multipart.octet_length(str) == 5 end defp file_path(path) do Path.join(__DIR__, path) end end
32.235849
139
0.695347
0858137eac13e299507c4203f89e04bf892e21a8
287
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_arrow_operation_parsing_test_case/MatchedTwoOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/matched_arrow_operation_parsing_test_case/MatchedTwoOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/matched_arrow_operation_parsing_test_case/MatchedTwoOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
one ++ two <~ three -- four one <> two |> three .. four one -- two ~> three <> four one .. two <<< three -- four one ++ two <<~ three <> four one ++ two <|> three .. four one ++ two <~> three -- four one ++ two >>> three -- four one ++ two ~>> three -- four one ++ two ^^^ three -- four
26.090909
28
0.522648
085828b3cb8ef662b25a8373f809011903842ecd
487
ex
Elixir
lib/teddy_web/views/error_view.ex
abotkit/teddy
72f1c7015a278d4fd1b2c90daeaeb49d0d8ef142
[ "MIT" ]
1
2022-02-03T19:41:52.000Z
2022-02-03T19:41:52.000Z
lib/teddy_web/views/error_view.ex
abotkit/teddy
72f1c7015a278d4fd1b2c90daeaeb49d0d8ef142
[ "MIT" ]
null
null
null
lib/teddy_web/views/error_view.ex
abotkit/teddy
72f1c7015a278d4fd1b2c90daeaeb49d0d8ef142
[ "MIT" ]
null
null
null
defmodule TeddyWeb.ErrorView do use TeddyWeb, :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.647059
61
0.73306
08582b634fa2051d83757c417bdf5be1436e3a12
531
ex
Elixir
lib/level/schemas/notification.ex
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
928
2018-04-03T16:18:11.000Z
2019-09-09T17:59:55.000Z
lib/level/schemas/notification.ex
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
74
2018-04-03T00:46:50.000Z
2019-03-10T18:57:27.000Z
lib/level/schemas/notification.ex
mindriot101/level
0a2cbae151869c2d9b79b3bfb388f5d00739ae12
[ "Apache-2.0" ]
89
2018-04-03T17:33:20.000Z
2019-08-19T03:40:20.000Z
defmodule Level.Schemas.Notification do @moduledoc """ The Notification schema. """ use Ecto.Schema alias Level.Schemas.Space alias Level.Schemas.SpaceUser @type t :: %__MODULE__{} @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id schema "notifications" do field :state, :string, read_after_writes: true field :topic, :string field :event, :string field :data, :map belongs_to :space, Space belongs_to :space_user, SpaceUser timestamps() end end
20.423077
52
0.698682
08583747b255a8910e6389a116fcc4fb0f47cdb7
1,099
exs
Elixir
test/controllers/username_controller_test.exs
zubairshokh/asciinema-server
b882f285a84054e94e70def8f9777cc2fc3551b1
[ "Apache-2.0" ]
null
null
null
test/controllers/username_controller_test.exs
zubairshokh/asciinema-server
b882f285a84054e94e70def8f9777cc2fc3551b1
[ "Apache-2.0" ]
null
null
null
test/controllers/username_controller_test.exs
zubairshokh/asciinema-server
b882f285a84054e94e70def8f9777cc2fc3551b1
[ "Apache-2.0" ]
null
null
null
defmodule Asciinema.UsernameControllerTest do use AsciinemaWeb.ConnCase import Asciinema.Factory describe "setting username" do test "requires logged in user", %{conn: conn} do conn = get(conn, "/username/new") assert redirected_to(conn, 302) == "/login/new" end test "displays form", %{conn: conn} do user = insert(:user) conn = log_in(conn, user) conn = get(conn, "/username/new") assert html_response(conn, 200) =~ ~r/your username/i end test "redirects to profile on success", %{conn: conn} do user = insert(:user) conn = log_in(conn, user) conn = post(conn, "/username", %{user: %{username: "ricksanchez"}}) assert response(conn, 302) location = List.first(get_resp_header(conn, "location")) assert location == "/~ricksanchez" end test "redisplays form on error", %{conn: conn} do user = insert(:user) conn = log_in(conn, user) conn = post(conn, "/username", %{user: %{username: "---"}}) assert html_response(conn, 422) =~ "only letters" end end end
28.179487
73
0.620564
08583da63f4c378d7485caa846d7dfce3b968774
383
ex
Elixir
apps/cucumber_expressions/lib/cucumber_expressions/utils/random/random.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
2
2021-05-18T18:20:05.000Z
2022-02-13T00:15:06.000Z
apps/cucumber_expressions/lib/cucumber_expressions/utils/random/random.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
2
2021-04-22T00:28:17.000Z
2021-05-19T21:04:20.000Z
apps/cucumber_expressions/lib/cucumber_expressions/utils/random/random.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
4
2021-04-14T03:07:45.000Z
2021-12-12T21:23:59.000Z
defmodule CucumberExpressions.Utils.Random do @moduledoc """ Generate random id with a risk of repeat as being about the same as that of you being hit by a meteorite. """ use Puid, total: 10.0e6, risk: 1.0e12 @type t() :: String.t() @spec id :: t() def id, do: generate() @spec id(:fixed) :: t() def id(:fixed), do: "000000000000000" def length, do: 15 end
21.277778
69
0.64752
085873da0475484e5264820ff5d303272b3f9f55
467
ex
Elixir
test/e2e/lib/hologram_e2e_web/pages/operators/subtraction_page.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
40
2022-01-19T20:27:36.000Z
2022-03-31T18:17:41.000Z
test/e2e/lib/hologram_e2e_web/pages/operators/subtraction_page.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
42
2022-02-03T22:52:43.000Z
2022-03-26T20:57:32.000Z
test/e2e/lib/hologram_e2e_web/pages/operators/subtraction_page.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
3
2022-02-10T04:00:37.000Z
2022-03-08T22:07:45.000Z
defmodule HologramE2E.Operators.SubtractionPage do use Hologram.Page route "/e2e/operators/subtraction" def init(_params, _conn) do %{ left: 10, right: 6, result: 0 } end def template do ~H""" <button id="button" on:click="calculate">Calculate</button> <div id="text">Result = {@result}</div> """ end def action(:calculate, _params, state) do Map.put(state, :result, state.left - state.right) end end
18.68
63
0.625268
08588bb7ec3ed789de03dd7d94bdf73420e26fe9
384
ex
Elixir
lib/hangman/letter_retrieval_strategy.ex
brpandey/elixir-hangman
458502af766b42e492ebb9ca543fc8b855687b09
[ "MIT" ]
1
2016-12-19T00:10:34.000Z
2016-12-19T00:10:34.000Z
lib/hangman/letter_retrieval_strategy.ex
brpandey/elixir-hangman
458502af766b42e492ebb9ca543fc8b855687b09
[ "MIT" ]
null
null
null
lib/hangman/letter_retrieval_strategy.ex
brpandey/elixir-hangman
458502af766b42e492ebb9ca543fc8b855687b09
[ "MIT" ]
null
null
null
defmodule Hangman.Letter.Retrieval.Strategy do alias Hangman.Letter.{Retrieval, Strategy} # Letter.Retrieval.Strategy serves as a behavior with one function to implement @callback optimal(Strategy.t()) :: String.t() | no_return # Only supports one letter retrieval type for the moment def select(%Strategy{} = strategy) do Retrieval.Common.optimal(strategy) end end
32
81
0.757813
0858987ce87675c29245919dd7fe9f0639021c78
487
ex
Elixir
lib/plate_slate_web/views/layout_view.ex
nontech/graphql_absinthe
c813fcb020c4d2e6eb9fcebdc05cc36d6fcf2dde
[ "MIT" ]
null
null
null
lib/plate_slate_web/views/layout_view.ex
nontech/graphql_absinthe
c813fcb020c4d2e6eb9fcebdc05cc36d6fcf2dde
[ "MIT" ]
null
null
null
lib/plate_slate_web/views/layout_view.ex
nontech/graphql_absinthe
c813fcb020c4d2e6eb9fcebdc05cc36d6fcf2dde
[ "MIT" ]
null
null
null
#--- # Excerpted from "Craft GraphQL APIs in Elixir with Absinthe", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/wwgraphql for more book information. #--- defmodule PlateSlateWeb.LayoutView do use PlateSlateWeb, :view end
40.583333
86
0.767967
0858abbf495cbe7476b881be09696c1588cefb96
383
ex
Elixir
lib/codes/codes_a94.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_a94.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_a94.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_A94 do alias IcdCode.ICDCode def _A94 do %ICDCode{full_code: "A94", category_code: "A94", short_code: "", full_name: "Unspecified arthropod-borne viral fever", short_name: "Unspecified arthropod-borne viral fever", category_name: "Unspecified arthropod-borne viral fever" } end end
23.9375
66
0.652742
0858df7b3c05ff0b47d3b3a483446f629a47a680
1,692
ex
Elixir
hello_elixir/lib/hello/hello_catch.ex
wangxingfred/hello
2358b6358a55e68a425887901685d6b066cd2b2e
[ "MIT" ]
null
null
null
hello_elixir/lib/hello/hello_catch.ex
wangxingfred/hello
2358b6358a55e68a425887901685d6b066cd2b2e
[ "MIT" ]
4
2021-10-06T22:07:13.000Z
2022-02-27T10:35:34.000Z
hello_elixir/lib/hello/hello_catch.ex
wangxingfred/hello
2358b6358a55e68a425887901685d6b066cd2b2e
[ "MIT" ]
null
null
null
defmodule HelloCatch do @moduledoc ~S""" Copyright <Woobest> 2020. All Rights Reserved. History: 2020-11-11 09:20, fred 'wangxingfred@gmail.com', create module TODO 编写模块描述 """ def try_catch_else1(term, kind \\ "throw") do try do if term !== nil and term !== :ok do _exception!(kind, term) end term catch e -> "Catch #{inspect e}" else :ok -> "else :ok" e -> "else e -> #{inspect e}~" end end def try_catch_else2(term, kind \\ "throw") do try do if term !== nil and term !== :ok do _exception!(kind, term) end term catch kind, reason -> "Catch #{inspect {kind, reason}}" else :ok -> "else :ok" e -> "else e -> #{inspect e}~" end end def try_after(message, kind) do try do if is_function(message), do: message.(), else: _exception!(kind, message) after IO.puts "after: message = #{inspect message}" end end def try_after!(message, kind) do try do if is_function(message), do: message.(), else: _exception!(kind, message) after _exception!(kind, "after!") end end def do_after(message) do raise "oops" after IO.puts "after: message = #{inspect message}" end defp _exception!("throw", message), do: throw message defp _exception!("raise", message), do: raise message defp _exception!("error", message), do: :erlang.error(message) end
26.030769
85
0.507092
0858f2d416f0cef58e52cdd404173eb84a85de7c
412
ex
Elixir
test/support/test_helper.ex
ucwaldo/expublish
d56a6d93401d0c0491f38437f0159111af11e3c4
[ "Apache-2.0" ]
21
2021-02-21T15:45:31.000Z
2022-03-25T10:47:42.000Z
test/support/test_helper.ex
ucwaldo/expublish
d56a6d93401d0c0491f38437f0159111af11e3c4
[ "Apache-2.0" ]
21
2021-02-22T09:31:36.000Z
2021-12-19T19:39:05.000Z
test/support/test_helper.ex
ucwaldo/expublish
d56a6d93401d0c0491f38437f0159111af11e3c4
[ "Apache-2.0" ]
null
null
null
defmodule Expublish.TestHelper do @moduledoc false def with_release_md(fun) do if File.exists?("RELEASE.md") do fun.() else File.write!("RELEASE.md", "generated by expublish test") fun.() File.rm!("RELEASE.md") end end def parts_to_iso(parts, separator \\ "-") do parts |> Enum.map(&String.pad_leading("#{&1}", 2, "0")) |> Enum.join(separator) end end
20.6
62
0.604369
0858f423e17d3f4ee677fb82bf41dc56fd22547a
2,788
ex
Elixir
lib/phoenix_live_view/test/structs.ex
sthagen/phoenixframework-phoenix_live_view
196ba2f8c9c367ee9e0ff8273f2a9c22a1c7027a
[ "MIT" ]
null
null
null
lib/phoenix_live_view/test/structs.ex
sthagen/phoenixframework-phoenix_live_view
196ba2f8c9c367ee9e0ff8273f2a9c22a1c7027a
[ "MIT" ]
null
null
null
lib/phoenix_live_view/test/structs.ex
sthagen/phoenixframework-phoenix_live_view
196ba2f8c9c367ee9e0ff8273f2a9c22a1c7027a
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveViewTest.View do @moduledoc """ The struct for testing LiveViews. The following public fields represent the LiveView: * `id` - The DOM id of the LiveView * `module` - The module of the running LiveView * `pid` - The Pid of the running LiveView * `endpoint` - The endpoint for the LiveView * `target` - The target to scope events to See the `Phoenix.LiveViewTest` documentation for usage. """ @derive {Inspect, only: [:id, :module, :pid, :endpoint]} defstruct id: nil, module: nil, pid: nil, proxy: nil, endpoint: nil, target: nil end defmodule Phoenix.LiveViewTest.Element do @moduledoc """ The struct returned by `Phoenix.LiveViewTest.element/3`. The following public fields represent the element: * `selector` - The query selector * `text_filter` - The text to further filter the element See the `Phoenix.LiveViewTest` documentation for usage. """ @derive {Inspect, only: [:selector, :text_filter]} defstruct proxy: nil, selector: nil, text_filter: nil, event: nil, form_data: nil, meta: %{} end defmodule Phoenix.LiveViewTest.Upload do @moduledoc """ The struct returned by `Phoenix.LiveViewTest.file_input/4`. The following public fields represent the element: * `selector` - The query selector * `entries` - The list of selected file entries See the `Phoenix.LiveViewTest` documentation for usage. """ alias Phoenix.LiveViewTest.{Upload, Element} @derive {Inspect, only: [:selector, :entries]} defstruct pid: nil, view: nil, element: nil, ref: nil, selector: nil, config: %{}, entries: [], cid: nil @doc false def new(pid, %Phoenix.LiveViewTest.View{} = view, form_selector, name, entries, cid) do populated_entries = Enum.map(entries, fn entry -> populate_entry(entry) end) selector = "#{form_selector} input[type=\"file\"][name=\"#{name}\"]" %Upload{ pid: pid, view: view, element: %Element{proxy: view.proxy, selector: selector}, entries: populated_entries, cid: cid } end defp populate_entry(%{} = entry) do name = Map.get(entry, :name) || raise ArgumentError, "a :name of the entry filename is required." content = Map.get(entry, :content) || raise ArgumentError, "the :content of the binary entry file data is required." %{ "name" => name, "content" => content, "ref" => to_string(System.unique_integer([:positive])), "size" => entry[:size] || byte_size(content), "type" => entry[:type] || MIME.from_path(name) } end end
27.333333
89
0.61693
085945ea8437114b0cb76c36a28b348f07dc0cd4
783
ex
Elixir
apps/reaper/lib/reaper/decoder/xml.ex
smartcitiesdata/smartcitiesdata
c926c25003a8ee2d09b933c521c49f674841c0b6
[ "Apache-2.0" ]
26
2019-09-20T23:54:45.000Z
2020-08-20T14:23:32.000Z
apps/reaper/lib/reaper/decoder/xml.ex
smartcitiesdata/smartcitiesdata
c926c25003a8ee2d09b933c521c49f674841c0b6
[ "Apache-2.0" ]
757
2019-08-15T18:15:07.000Z
2020-09-18T20:55:31.000Z
apps/reaper/lib/reaper/decoder/xml.ex
smartcitiesdata/smartcitiesdata
c926c25003a8ee2d09b933c521c49f674841c0b6
[ "Apache-2.0" ]
9
2019-11-12T16:43:46.000Z
2020-03-25T16:23:16.000Z
defmodule Reaper.Decoder.Xml do @moduledoc """ Reaper.Decoder implementation to decode a csv file into a stream of records """ alias Reaper.XmlSchemaMapper defmodule XmlError do defexception [:message] end @behaviour Reaper.Decoder @impl Reaper.Decoder def decode( {:file, filename}, %SmartCity.Ingestion{schema: schema, topLevelSelector: selector} = ingestion ) do try do stream = filename |> XMLStream.stream(selector) |> Stream.map(&XmlSchemaMapper.map(&1, schema)) {:ok, stream} rescue error -> {:error, "IngestionId: #{ingestion.id}", error} end end @impl Reaper.Decoder def handle?(source_format) do String.downcase(source_format) == "text/xml" end end
21.162162
84
0.644955
085948c233f6edfb66e24e4dc0710ec59e59407b
2,277
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/resource_id.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/resource_id.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/resource_id.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "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.YouTube.V3.Model.ResourceId do @moduledoc """ A resource id is a generic reference that points to another YouTube resource. ## Attributes * `channelId` (*type:* `String.t`, *default:* `nil`) - The ID that YouTube uses to uniquely identify the referred resource, if that resource is a channel. This property is only present if the resourceId.kind value is youtube#channel. * `kind` (*type:* `String.t`, *default:* `nil`) - The type of the API resource. * `playlistId` (*type:* `String.t`, *default:* `nil`) - The ID that YouTube uses to uniquely identify the referred resource, if that resource is a playlist. This property is only present if the resourceId.kind value is youtube#playlist. * `videoId` (*type:* `String.t`, *default:* `nil`) - The ID that YouTube uses to uniquely identify the referred resource, if that resource is a video. This property is only present if the resourceId.kind value is youtube#video. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :channelId => String.t(), :kind => String.t(), :playlistId => String.t(), :videoId => String.t() } field(:channelId) field(:kind) field(:playlistId) field(:videoId) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.ResourceId do def decode(value, options) do GoogleApi.YouTube.V3.Model.ResourceId.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.ResourceId do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.660714
240
0.71805
0859499e071c9d29e088bf0683f68c66a06112d5
1,375
ex
Elixir
lib/shopify_api/rest/inventory_level.ex
ProtoJazz/elixir-shopifyapi
759e20baff5afdff235386193bc42b2ecd343f5d
[ "Apache-2.0" ]
18
2019-06-07T13:36:39.000Z
2021-08-03T21:06:36.000Z
lib/shopify_api/rest/inventory_level.ex
ProtoJazz/elixir-shopifyapi
759e20baff5afdff235386193bc42b2ecd343f5d
[ "Apache-2.0" ]
158
2018-08-30T22:09:00.000Z
2021-09-22T01:18:59.000Z
lib/shopify_api/rest/inventory_level.ex
ProtoJazz/elixir-shopifyapi
759e20baff5afdff235386193bc42b2ecd343f5d
[ "Apache-2.0" ]
4
2020-09-05T00:48:46.000Z
2020-09-30T15:53:50.000Z
defmodule ShopifyAPI.REST.InventoryLevel do @moduledoc """ ShopifyAPI REST API InventoryLevel resource """ alias ShopifyAPI.AuthToken alias ShopifyAPI.REST @doc """ Return a list of inventory levels. ## Example iex> ShopifyAPI.REST.InventoryLevel.all(auth) {:ok, [%{}, ...] = inventory_level} """ def all(%AuthToken{} = auth, params \\ [], options \\ []), do: REST.get(auth, "inventory_levels.json", params, options) @doc """ Sets the inventory level for an inventory item at a location. ## Example iex> ShopifyAPI.REST.InventoryLevel.set(auth, %{ inventory_level: %{inventory_item_id: integer, location_id: integer, available: integer}}) {:ok, [] = inventory_level} """ def set( %AuthToken{} = auth, %{ inventory_level: %{inventory_item_id: _, location_id: _, available: _} = inventory_level } ) do REST.post(auth, "inventory_levels/set.json", inventory_level) end @doc """ Delete an inventory level of an inventory item at a location. ## Example iex> ShopifyAPI.REST.InventoryLevel.delete(auth, integer, integer) {:ok, 200 }} """ def delete(%AuthToken{} = auth, inventory_item_id, location_id) do REST.delete( auth, "inventory_levels.json?inventory_item_id=#{inventory_item_id}&location_id=#{location_id}" ) end end
26.960784
145
0.655273
08596186be4631b5c710604d8d196d15e070d3ef
861
ex
Elixir
apps/omg_rpc/lib/omg_rpc/web/views/transaction.ex
kendricktan/elixir-omg
834c103fd5c4b9e063c1d32b9b4e5728abb64009
[ "Apache-2.0" ]
null
null
null
apps/omg_rpc/lib/omg_rpc/web/views/transaction.ex
kendricktan/elixir-omg
834c103fd5c4b9e063c1d32b9b4e5728abb64009
[ "Apache-2.0" ]
null
null
null
apps/omg_rpc/lib/omg_rpc/web/views/transaction.ex
kendricktan/elixir-omg
834c103fd5c4b9e063c1d32b9b4e5728abb64009
[ "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 OMG.RPC.Web.View.Transaction do @moduledoc """ The Transaction submission view for rendering json """ alias OMG.Utils.HttpRPC.Response def render("submit.json", %{result: result}) do result |> Response.sanitize() |> Response.serialize() end end
30.75
74
0.738676
08596e8e15569dc3fe39dece40eb05284d2bddc8
6,127
ex
Elixir
lib/akin.ex
vanessaklee/akin
fc97befb871536b6c7ef0b35740fe6efc032c566
[ "Apache-2.0" ]
8
2021-10-31T21:24:37.000Z
2022-02-27T05:30:24.000Z
lib/akin.ex
vanessaklee/akin
fc97befb871536b6c7ef0b35740fe6efc032c566
[ "Apache-2.0" ]
1
2021-10-31T17:57:41.000Z
2021-11-09T22:54:50.000Z
lib/akin.ex
vanessaklee/akin
fc97befb871536b6c7ef0b35740fe6efc032c566
[ "Apache-2.0" ]
null
null
null
defmodule Akin do @moduledoc """ Akin ======= Functions for comparing two strings for similarity using a collection of string comparison algorithms for Elixir. Algorithms can be called independently or in total to return a map of metrics. ## Options Options accepted in a keyword list (i.e. [ngram_size: 3]). 1. `algorithms`: algorithms to use in comparision. Accepts the name or a keyword list. Default is algorithms/0. 1. `metric` - algorithm metric. Default is both - "string": uses string algorithms - "phonetic": uses phonetic algorithms 1. `unit` - algorithm unit. Default is both. - "whole": uses algorithms best suited for whole string comparison (distance) - "partial": uses algorithms best suited for partial string comparison (substring) 1. `level` - level for double phonetic matching. Default is "normal". - "strict": both encodings for each string must match - "strong": the primary encoding for each string must match - "normal": the primary encoding of one string must match either encoding of other string (default) - "weak": either primary or secondary encoding of one string must match one encoding of other string 1. `match_at`: an algorith score equal to or above this value is condsidered a match. Default is 0.9 1. `ngram_size`: number of contiguous letters to split strings into. Default is 2. 1. `short_length`: qualifies as "short" to recieve a shortness boost. Used by Name Metric. Default is 8. 1. `stem`: boolean representing whether to compare the stemmed version the strings; uses Stemmer. Default `false` """ import Akin.Util, only: [list_algorithms: 1, modulize: 1, compose: 1, opts: 2, r: 1, default_opts: 0] alias Akin.Corpus alias Akin.Names @spec compare(binary() | %Corpus{}, binary() | %Corpus{}, keyword()) :: float() @doc """ Compare two strings. Return map of algorithm metrics. Options accepted as a keyword list. If no options are given, default values will be used. """ def compare(left, right, opts \\ default_opts()) def compare(left, right, opts) when is_binary(left) and is_binary(right) do if opts(opts, :stem) do left = compose(left).stems |> Enum.join(" ") right = compose(right).stems |> Enum.join(" ") compare(compose(left), compose(right), opts) else compare(compose(left), compose(right), opts) end end def compare(%Corpus{} = left, %Corpus{} = right, opts) do Enum.reduce(list_algorithms(opts), %{}, fn algorithm, acc -> Map.put(acc, algorithm, apply(modulize(algorithm), :compare, [left, right, opts])) end) |> Enum.reduce([], fn {k, v}, acc -> if is_nil(v) do acc else [{String.replace(k, ".", ""), v} | acc] end end) |> Enum.map(fn {k, v} -> {String.to_atom(k), r(v)} end) |> Enum.into(%{}) end @spec match_names(binary() | %Corpus{}, binary() | %Corpus{} | list(), keyword()) :: float() @doc """ Compare a string against a list of strings. Matches are determined by algorithem metrics equal to or higher than the `match_at` option. Return a list of strings that are a likely match. """ def match_names(left, rights, opts \\ default_opts()) def match_names(_, [], _), do: [] def match_names(left, rights, opts) when is_binary(left) and is_list(rights) do rights = Enum.map(rights, fn right -> compose(right) end) match_names(compose(left), rights, opts) end def match_names(%Corpus{} = left, rights, opts) do Enum.reduce(rights, [], fn right, acc -> %{scores: scores} = Names.compare(left, right, opts) if Enum.any?(scores, fn {_algo, score} -> score > opts(opts, :match_at) end) do [right.original | acc] else acc end end) end @spec match_names_metrics(binary(), list(), keyword()) :: float() @doc """ Compare a string against a list of strings. Matches are determined by algorithem metrics equal to or higher than the `match_at` option. Return a list of strings that are a likely match and their algorithm metrics. """ def match_names_metrics(left, rights, opts \\ default_opts()) def match_names_metrics(left, rights, opts) when is_binary(left) and is_list(rights) do Enum.reduce(rights, [], fn right, acc -> %{left: left, right: right, metrics: scores, match: match} = match_name_metrics(left, right, opts) if match == 1 do [%{left: left, right: right, metrics: scores, match: 1} | acc] else [%{left: left, right: right, metrics: scores, match: 0} | acc] end end) end @spec match_name_metrics(binary(), binary(), Keyword.t()) :: %{ :left => binary(), :match => 0 | 1, :metrics => [any()], :right => binary() } @doc """ Compare a string to a string with logic specific to names. Matches are determined by algorithem metrics equal to or higher than the `match_at` option. Return a list of strings that are a likely match and their algorithm metrics. """ def match_name_metrics(left, rights, opts \\ default_opts()) def match_name_metrics(left, right, opts) when is_binary(left) and is_binary(right) do left = compose(left) right = compose(right) %{scores: scores} = Names.compare(left, right, opts) left = Enum.join(left.list, " ") right = Enum.join(right.list, " ") if Enum.any?(scores, fn {_algo, score} -> score > opts(opts, :match_at) end) do %{left: left, right: right, metrics: scores, match: 1} else %{left: left, right: right, metrics: scores, match: 0} end end @spec phonemes(binary() | %Corpus{}) :: list() @doc """ Returns list of unique phonetic encodings produces by the single and double metaphone algorithms. """ def phonemes(string) when is_binary(string) do phonemes(compose(string), string) end defp phonemes(%Corpus{string: string}, _original_string) do single = Akin.Metaphone.Single.compute(string) double = Akin.Metaphone.Double.parse(string) |> Tuple.to_list() [single | double] |> List.flatten() |> Enum.uniq() end end
38.534591
194
0.660845
08598779f8074c006e502f213e3918a87246030c
1,645
ex
Elixir
apps/astarte_trigger_engine/lib/astarte_trigger_engine_web/plug/health_plug.ex
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
191
2018-03-30T13:23:08.000Z
2022-03-02T12:05:32.000Z
apps/astarte_trigger_engine/lib/astarte_trigger_engine_web/plug/health_plug.ex
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
402
2018-03-30T13:37:00.000Z
2022-03-31T16:47:10.000Z
apps/astarte_trigger_engine/lib/astarte_trigger_engine_web/plug/health_plug.ex
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
24
2018-03-30T13:29:48.000Z
2022-02-28T11:10:26.000Z
# # This file is part of Astarte. # # Copyright 2020 Ispirata Srl # # 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 Astarte.TriggerEngineWeb.HealthPlug do import Plug.Conn alias Astarte.TriggerEngine.Health def init(_args), do: nil def call(%{request_path: "/health", method: "GET"} = conn, _opts) do try do case Health.get_health() do {:ok, %{status: status}} when status in [:ready, :degraded] -> :telemetry.execute( [:astarte, :trigger_engine, :service], %{health: 1}, %{status: status} ) conn |> send_resp(:ok, "") |> halt() _ -> :telemetry.execute( [:astarte, :trigger_engine, :service], %{health: 0} ) conn |> send_resp(:service_unavailable, "") |> halt() end rescue _ -> :telemetry.execute( [:astarte, :trigger_engine, :service], %{health: 0} ) conn |> send_resp(:internal_server_error, "") |> halt() end end def call(conn, _opts), do: conn end
25.703125
74
0.595745
0859b170f2677453a9caf8fce6328fa383f05137
1,952
ex
Elixir
lib/distillery_packager/debian/control.ex
denvera/distillery_packager
337e08ba87653a0e43c1fcbf06f8634e4c91f7a3
[ "MIT" ]
null
null
null
lib/distillery_packager/debian/control.ex
denvera/distillery_packager
337e08ba87653a0e43c1fcbf06f8634e4c91f7a3
[ "MIT" ]
null
null
null
lib/distillery_packager/debian/control.ex
denvera/distillery_packager
337e08ba87653a0e43c1fcbf06f8634e4c91f7a3
[ "MIT" ]
null
null
null
defmodule DistilleryPackager.Debian.Control do @moduledoc """ This module houses the logic required to build the control file and include custom control data such as pre/post install hooks. """ alias DistilleryPackager.Debian.Generators.Control alias DistilleryPackager.Utils.Compression import Mix.Releases.Shell, only: [debug: 1] # - Add ability to create pre-inst / post-inst hooks [WIP] def build(deb_root, config) do control_dir = Path.join([deb_root, "control"]) debug "Building debian control directory" :ok = File.mkdir_p(control_dir) Control.build(config, control_dir) add_custom_hooks(config, control_dir) add_conffiles_file(config, control_dir) System.cmd("chmod", ["-R", "og-w", control_dir]) Compression.compress( control_dir, Path.join([control_dir, "..", "control.tar.gz"]), owner: %{user: "root", group: "root"} ) DistilleryPackager.Utils.File.remove_tmp(control_dir) :ok end defp add_conffiles_file(config, control_dir) do debug "Marking config files" config_files = config |> Map.get(:config_files, []) |> Enum.map_join(&(&1 <> "\n")) :ok = [control_dir, "conffiles"] |> Path.join() |> File.write(config_files) end defp add_custom_hooks(config, control_dir) do debug "Adding in custom hooks" for {type, path} <- config.maintainer_scripts do script = [File.cwd!, path] |> Path.join true = File.exists?(script) filename = case type do :pre_install -> "preinst" :post_install -> "postinst" :pre_uninstall -> "prerm" :post_uninstall -> "postrm" _ -> Atom.to_string(type) end filename = [control_dir, filename] |> Path.join debug "Copying #{Atom.to_string(type)} file to #{filename}" File.cp(script, filename) end end end
27.885714
77
0.629098
0859d282088a7c3d1a1f1ba267083a8c10c0fa41
4,265
ex
Elixir
lib/paper/docs.ex
alexanderttalvarez/elixir_dropbox
a1ce6eb7ba6f9b0b082031fba9797db3f7848b05
[ "MIT" ]
null
null
null
lib/paper/docs.ex
alexanderttalvarez/elixir_dropbox
a1ce6eb7ba6f9b0b082031fba9797db3f7848b05
[ "MIT" ]
null
null
null
lib/paper/docs.ex
alexanderttalvarez/elixir_dropbox
a1ce6eb7ba6f9b0b082031fba9797db3f7848b05
[ "MIT" ]
null
null
null
defmodule ElixirDropbox.Paper.Docs do @moduledoc """ This namespace contains endpoints and data types for managing docs and folders in Dropbox Paper. """ import ElixirDropbox @doc """ Marks the given Paper doc as archived. ## Example ElixirDropbox.Paper.Docs.docs_archive client, "" More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-create """ def docs_archive(client, doc_id) do body = %{"doc_id" => doc_id} result = to_string(Poison.Encoder.encode(body, %{})) post(client, "/paper/docs/archive", result) end @doc """ Creates a new Paper doc with the provided content. ## Example ElixirDropbox.Paper.Docs.docs_create client, "", "", "" More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-create """ def docs_create(client, import_format, parent_folder_id, file) do dropbox_headers = %{ :import_format => import_format, :parent_folder_id => parent_folder_id } headers = %{ "Dropbox-API-Arg" => Poison.encode!(dropbox_headers), "Content-Type" => "application/octet-stream" } upload_request( client, Application.get_env(:elixir_dropbox, :base_url), "/paper/docs/create", file, headers ) end @doc """ Exports and downloads Paper doc either as HTML or markdown. ## Example ElixirDropbox.Paper.Docs.docs_download client, "", "" More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-download """ def docs_download(client, doc_id, export_format) do dropbox_headers = %{ :doc_id => doc_id, :export_format => export_format } headers = %{"Dropbox-API-Arg" => Poison.encode!(dropbox_headers)} download_request( client, Application.get_env(:elixir_dropbox, :base_url), "/paper/docs/download", [], headers ) end @doc """ Retrieves folder information for the given Paper doc. ## Example ElixirDropbox.Paper.Docs.get_folder_info client, "", "" More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-get_folder_info """ def get_folder_info(client, doc_id) do body = %{"doc_id" => doc_id} result = to_string(Poison.Encoder.encode(body, %{})) post(client, "/paper/docs/get_folder_info", result) end @doc """ Return the list of all Paper docs according to the argument specifications. ## Example ElixirDropbox.Paper.Docs.docs_list client More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-list """ def docs_list( client, filter_by \\ "docs_created", sort_by \\ "modified", sort_order \\ "descending", limit \\ 100 ) do body = %{ "filter_by" => filter_by, "sort_by" => sort_by, "sort_order" => sort_order, "limit" => limit } result = to_string(Poison.Encoder.encode(body, %{})) post(client, "/paper/docs/list", result) end @doc """ Permanently deletes the given Paper doc. ## Example ElixirDropbox.Paper.Docs.permanently_delete client More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-list """ def permanently_delete(client, doc_id) do body = %{"doc_id" => doc_id} result = to_string(Poison.Encoder.encode(body, %{})) post(client, "/paper/docs/permanently_delete", result) end @doc """ Updates an existing Paper doc with the provided content. ## Example ElixirDropbox.Paper.Docs.docs_update client, "", "", "", "", "" More info at: https://www.dropbox.com/developers/documentation/http/documentation#paper-docs-download """ def docs_update(client, doc_id, doc_update_policy, revision, import_format, file) do dropbox_headers = %{ :doc_id => doc_id, :doc_update_policy => doc_update_policy, :revision => revision, :import_format => import_format } headers = %{"Dropbox-API-Arg" => Poison.encode!(dropbox_headers)} upload_request( client, Application.get_env(:elixir_dropbox, :base_url), "/paper/docs/update", file, headers ) end end
26.165644
110
0.665885
085a4c1313e262a2201aa6f03441b3aa06349d2b
1,215
ex
Elixir
clients/elixir/generated/lib/swaggy_jenkins/model/extension_class_container_impl1map.ex
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/elixir/generated/lib/swaggy_jenkins/model/extension_class_container_impl1map.ex
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/elixir/generated/lib/swaggy_jenkins/model/extension_class_container_impl1map.ex
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule SwaggyJenkins.Model.ExtensionClassContainerImpl1map do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"io.jenkins.blueocean.service.embedded.rest.PipelineImpl", :"io.jenkins.blueocean.service.embedded.rest.MultiBranchPipelineImpl", :"_class" ] @type t :: %__MODULE__{ :"io.jenkins.blueocean.service.embedded.rest.PipelineImpl" => SwaggyJenkins.Model.ExtensionClassImpl.t | nil, :"io.jenkins.blueocean.service.embedded.rest.MultiBranchPipelineImpl" => SwaggyJenkins.Model.ExtensionClassImpl.t | nil, :"_class" => String.t | nil } end defimpl Poison.Decoder, for: SwaggyJenkins.Model.ExtensionClassContainerImpl1map do import SwaggyJenkins.Deserializer def decode(value, options) do value |> deserialize(:"io.jenkins.blueocean.service.embedded.rest.PipelineImpl", :struct, SwaggyJenkins.Model.ExtensionClassImpl, options) |> deserialize(:"io.jenkins.blueocean.service.embedded.rest.MultiBranchPipelineImpl", :struct, SwaggyJenkins.Model.ExtensionClassImpl, options) end end
36.818182
147
0.760494
085a59b028550a07f5af0f721395303145841dbe
11,363
ex
Elixir
lib/coherence/controllers/session_controller.ex
Sathras/coherence-react
c17f9143daceecade7ae724db2d51815f9d09c00
[ "MIT" ]
2
2018-01-19T06:12:16.000Z
2018-03-12T07:17:17.000Z
lib/coherence/controllers/session_controller.ex
Sathras/coherence-react
c17f9143daceecade7ae724db2d51815f9d09c00
[ "MIT" ]
null
null
null
lib/coherence/controllers/session_controller.ex
Sathras/coherence-react
c17f9143daceecade7ae724db2d51815f9d09c00
[ "MIT" ]
null
null
null
defmodule Coherence.SessionController do @moduledoc """ Handle the authentication actions. """ use CoherenceWeb, :controller use Timex use Coherence.Config import Ecto.Query import Coherence.{LockableService, RememberableService, TrackableService} import Coherence.Schemas, only: [schema: 1] import Coherence.Authentication.Utils, only: [create_user_token: 2] alias Coherence.{ConfirmableService, Messages} alias Coherence.Schemas require Logger @type schema :: Ecto.Schema.t @type conn :: Plug.Conn.t @type params :: Map.t @doc false @spec login_cookie() :: String.t def login_cookie, do: "coherence_login" @doc """ Retrieve the login cookie. """ @spec get_login_cookie(conn) :: String.t def get_login_cookie(conn) do conn.cookies[Config.login_cookie] end @doc """ Login the user. Find the user based on the login_field. Hash the given password and verify it matches the value stored in the database. Login proceeds only if the following other conditions are satisfied: * Confirmation is enabled and the user has been confirmed. * Lockable is enabled and the user is not locked. If the Trackable option is enabled, the trackable fields are update. If the provided password is not correct, and the lockable option is enabled check to see if the maximum login attempts threshold is exceeded. If so, lock the account. If the rememberable option is enabled, create a new series and rememberable token, create a new cookie and update the database. """ @spec create(conn, params) :: conn def create(conn, params) do if Coherence.logged_in?(conn) do conn |> put_status(409) |> json(%{flash: Messages.backend().already_logged_in() }) else user_schema = Config.user_schema() lockable? = user_schema.lockable?() login_field = Config.login_field() login = params[to_string(login_field)] remember = if user_schema.rememberable?(), do: params["remember"], else: false user = Schemas.get_by_user [{login_field, login}] if valid_user_login? user, params do if confirmed_access? user do do_lockable(conn, [user, user_schema, remember, lockable?], lockable? and user_schema.locked?(user)) else conn |> put_status(406) |> json( %{ flash: Messages.backend().you_must_confirm_your_account() }) end else conn |> track_failed_login(user, user_schema.trackable_table?()) |> failed_login(user, lockable?) |> put_status(401) |> json( %{ error: Messages.backend().invalid_email_or_password() }) end end end defp confirmed_access?(user) do ConfirmableService.confirmed?(user) || ConfirmableService.unconfirmed_access?(user) end defp valid_user_login?(nil, _params), do: false defp valid_user_login?(%{active: false}, _params), do: false defp valid_user_login?(user, %{"password" => password}) do user.__struct__.checkpw(password, Map.get(user, Config.password_hash())) end defp valid_user_login?(_user, _params), do: false defp do_lockable(conn, _, true) do conn |> put_status(423) |> json( %{ flash: Messages.backend().too_many_failed_login_attempts() }) end defp do_lockable(conn, opts, false) do [user, user_schema, remember, lockable?] = opts conn = if lockable? && user.locked_at() do unlock!(user) track_unlock conn, user, user_schema.trackable_table?() else conn end conn = Config.auth_module() |> apply(Config.create_login(), [conn, user, [id_key: Config.schema_key()]]) |> reset_failed_attempts(user, lockable?) |> track_login(user, user_schema.trackable?(), user_schema.trackable_table?()) |> save_rememberable(user, remember) |> create_user_token(user) |> put_status(201) json(conn, %{ userToken: conn.assigns[:user_token] }) end @doc """ Logout the user. Delete the user's session, track the logout and delete the rememberable cookie. """ @spec delete(conn, params) :: conn def delete(conn, _params) do user_schema = Config.user_schema() user = Coherence.current_user conn Config.auth_module() |> apply(Config.delete_login(), [conn, [id_key: Config.schema_key]]) |> track_logout(user, user_schema.trackable?, user_schema.trackable_table?) |> delete_rememberable(user) |> put_status(204) |> json(%{}) end defp log_lockable_update({:error, changeset}), do: lockable_failure changeset defp log_lockable_update(_), do: :ok @spec reset_failed_attempts(conn, Ecto.Schema.t, boolean) :: conn def reset_failed_attempts(conn, %{failed_attempts: attempts} = user, true) when attempts > 0 do :session |> Controller.changeset(user.__struct__, user, %{failed_attempts: 0}) |> Schemas.update |> log_lockable_update conn end def reset_failed_attempts(conn, _user, _), do: conn defp failed_login(conn, %{} = user, true) do attempts = user.failed_attempts + 1 {conn, params} = cond do not user_active?(user) -> {put_flash_inactive_user(conn), %{}} attempts >= Config.max_failed_login_attempts() -> new_conn = conn |> assign(:locked, true) |> track_lock(user, user.__struct__.trackable_table?()) {put_flash(new_conn, :error, Messages.backend().maximum_login_attempts_exceeded()), %{locked_at: NaiveDateTime.utc_now()}} true -> {put_flash(conn, :error, Messages.backend().incorrect_login_or_password(login_field: Config.login_field())), %{}} end :session |> Controller.changeset(user.__struct__, user, Map.put(params, :failed_attempts, attempts)) |> Schemas.update |> log_lockable_update conn end defp failed_login(conn, _user, _) do put_flash(conn, :error, Messages.backend().incorrect_login_or_password( login_field: Config.login_field())) end def put_flash_inactive_user(conn) do put_flash conn, :error, Messages.backend().account_is_inactive() end @doc """ Callback for the authenticate plug. Validate the rememberable cookie. If valid, generate a new token, keep the same series number. Update the rememberable database with the new token. Save the new cookie. """ @spec rememberable_callback(conn, integer, String.t, String.t, Keyword.t) :: conn def rememberable_callback(conn, id, series, token, opts) do Coherence.RememberableServer.callback fn -> do_rememberable_callback(conn, id, series, token, opts) end end @doc false def do_rememberable_callback(conn, id, series, token, opts) do case validate_login(id, series, token) do {:ok, rememberable} -> # Logger.debug "Valid login :ok" Config.user_schema() id |> Schemas.get_user |> do_valid_login(conn, [id, rememberable, series, token], opts) {:error, :not_found} -> Logger.debug "No valid login found" {conn, nil} {:error, :invalid_token} -> # this is a case of potential fraud Logger.warn "Invalid token. Potential Fraud." conn |> delete_req_header(opts[:login_key]) |> put_flash(:error, Messages.backend().you_are_using_an_invalid_security_token()) |> redirect(to: logged_out_url()) |> halt end end defp do_valid_login(nil, _conn, _parms, _opts), do: {:error, :not_found} defp do_valid_login(user, conn, params, opts) do [id, rememberable, series, token] = params cred_store = Coherence.Authentication.Utils.get_credential_store() if Config.async_rememberable?() and Enum.any?(conn.req_headers, fn {k,v} -> k == "x-requested-with" and v == "XMLHttpRequest" end) do # for ajax requests, we don't update the sequence number, ensuring that # multiple concurrent ajax requests don't fail on the seq_no {assign(conn, :remembered, true), user} else id |> gen_cookie(series, token) |> cred_store.delete_credentials {changeset, new_token} = schema(Rememberable).update_login(rememberable) cred_store.put_credentials({gen_cookie(id, series, new_token), Config.user_schema(), Config.schema_key()}) Config.repo.update! changeset conn = conn |> save_login_cookie(id, series, new_token, opts) |> assign(:remembered, true) {conn, user} end end @doc """ Save the login cookie. """ @spec save_login_cookie(conn, Integer.t, String.t, String.t, Keyword.t) :: conn def save_login_cookie(conn, id, series, token, opts \\ []) do key = opts[:login_key] || "coherence_login" expire = opts[:cookie_expire] || (2 * 24 * 60 * 60) put_resp_cookie conn, key, gen_cookie(id, series, token), max_age: expire end defp save_rememberable(conn, _user, none) when none in [nil, false], do: conn defp save_rememberable(conn, user, _) do {changeset, series, token} = schema(Rememberable).create_login(user) Config.repo().insert! changeset opts = [ login_key: Config.login_cookie(), cookie_expire: Config.rememberable_cookie_expire_hours() * 60 * 60 ] save_login_cookie conn, user.id, series, token, opts end @doc """ Fetch a rememberable database record. """ @spec get_rememberables(integer) :: [schema] def get_rememberables(id) do Schemas.get_by_rememberable user_id: id Rememberable |> where([u], u.user_id == ^id) |> Config.repo.all end @doc """ Validate the login cookie. Check the following conditions: * a record exists for the user, the series, but a different token * assume a fraud case * remove the rememberable cookie and delete the session * a record exists for the user, the series, and the token * a valid remembered user * otherwise, this is an unknown user. """ @spec validate_login(integer, String.t, String.t) :: {:ok, schema} | {:error, atom} def validate_login(user_id, series, token) do hash_series = hash series hash_token = hash token repo = Config.repo() # TODO: move this to the RememberableServer. But first, we need to change the # logic below to ignore expired tokens delete_expired_tokens!(repo) with :ok <- get_invalid_login!(repo, user_id, hash_series, hash_token), {:ok, rememberable} <- get_valid_login!(repo, user_id, hash_series, hash_token), do: {:ok, rememberable} end defp get_invalid_login!(repo, user_id, series, token) do case repo.one schema(Rememberable).get_invalid_login(user_id, series, token) do 0 -> :ok _ -> repo.delete_all schema(Rememberable).delete_all(user_id) {:error, :invalid_token} end end defp get_valid_login!(repo, user_id, series, token) do case repo.one schema(Rememberable).get_valid_login(user_id, series, token) do nil -> {:error, :not_found} item -> {:ok, item} end end defp delete_expired_tokens!(repo) do repo.delete_all schema(Rememberable).delete_expired_tokens() end defp hash(value) do schema(Rememberable).hash value end defp gen_cookie(user_id, series, token) do schema(Rememberable).gen_cookie user_id, series, token end defp user_active?(user) do Map.get(user, :active, true) end end
32.936232
112
0.675438