hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
03065e373c7ea09cf3dc5fc959690fa4b9276145
195
exs
Elixir
test/web/controllers/page_controller_test.exs
ShaneKilkelly/teal
494de9b9a3848ab57a5c3731c9d462bad335a3c0
[ "MIT" ]
null
null
null
test/web/controllers/page_controller_test.exs
ShaneKilkelly/teal
494de9b9a3848ab57a5c3731c9d462bad335a3c0
[ "MIT" ]
null
null
null
test/web/controllers/page_controller_test.exs
ShaneKilkelly/teal
494de9b9a3848ab57a5c3731c9d462bad335a3c0
[ "MIT" ]
null
null
null
defmodule Teal.Web.PageControllerTest do use Teal.Web.ConnCase test "GET /", %{conn: conn} do conn = get conn, "/" assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
21.666667
60
0.666667
03066caee841d849bcd75bb44cc5e084c2f05543
494
exs
Elixir
test/credo/check/readability/semicolons_test.exs
rodrigues/credo
b4e08477a2141d5537d8fc9c5cc08ebf93a5ee23
[ "MIT" ]
null
null
null
test/credo/check/readability/semicolons_test.exs
rodrigues/credo
b4e08477a2141d5537d8fc9c5cc08ebf93a5ee23
[ "MIT" ]
null
null
null
test/credo/check/readability/semicolons_test.exs
rodrigues/credo
b4e08477a2141d5537d8fc9c5cc08ebf93a5ee23
[ "MIT" ]
null
null
null
defmodule Credo.Check.Readability.SemicolonsTest do use Credo.TestHelper @described_check Credo.Check.Readability.Semicolons @moduletag :to_be_implemented test "it should NOT report expected code" do """ def fun_name do statement1 statement2 end """ |> to_source_file |> refute_issues(@described_check) end test "it should report a violation" do """ def fun_name() do statement1; statement2 end """ |> to_source_file |> assert_issue(@described_check) end end
16.466667
53
0.738866
0306b042525c9353cfc989d3ce03e32304ac63c8
56
ex
Elixir
test/support/payment.ex
TORIFUKUKaiou/ex-r_enum
5fd99b61dae3c7fe8fc3838158af342ff308dff1
[ "Apache-2.0" ]
24
2022-01-13T23:13:11.000Z
2022-03-27T18:02:39.000Z
test/support/payment.ex
TORIFUKUKaiou/ex-r_enum
5fd99b61dae3c7fe8fc3838158af342ff308dff1
[ "Apache-2.0" ]
16
2022-01-16T09:18:17.000Z
2022-02-08T01:10:09.000Z
test/support/payment.ex
TORIFUKUKaiou/ex-r_enum
5fd99b61dae3c7fe8fc3838158af342ff308dff1
[ "Apache-2.0" ]
6
2022-01-16T04:40:42.000Z
2022-02-07T14:56:26.000Z
defmodule Payment do defstruct [:dollars, :cents] end
14
30
0.75
0306bbc67fe2d486979364e1ccf1bb4107865a68
160
ex
Elixir
lib/quasar/web/views/api/v1/user_view.ex
okbreathe/quasar
58449a190aefde36aa83e5b1f3116f458ced7c09
[ "Apache-2.0" ]
11
2017-07-10T10:13:42.000Z
2021-12-19T16:46:20.000Z
lib/quasar/web/views/api/v1/user_view.ex
okbreathe/quasar
58449a190aefde36aa83e5b1f3116f458ced7c09
[ "Apache-2.0" ]
null
null
null
lib/quasar/web/views/api/v1/user_view.ex
okbreathe/quasar
58449a190aefde36aa83e5b1f3116f458ced7c09
[ "Apache-2.0" ]
3
2017-07-18T20:03:34.000Z
2019-07-28T13:32:49.000Z
defmodule Quasar.Web.Api.V1.UserView do use Quasar.Web, :view attributes [ :email, :name, :settings, :inserted_at, :updated_at ] end
13.333333
39
0.625
0306c6a18d6c8113286f2cdf449211257d567416
35,150
ex
Elixir
lib/ecto/query/builder.ex
Qqwy/ecto
c25ab093adcee031a36484ed86e576a4c28b2c6f
[ "Apache-2.0" ]
1
2019-05-03T08:51:16.000Z
2019-05-03T08:51:16.000Z
lib/ecto/query/builder.ex
Qqwy/ecto
c25ab093adcee031a36484ed86e576a4c28b2c6f
[ "Apache-2.0" ]
null
null
null
lib/ecto/query/builder.ex
Qqwy/ecto
c25ab093adcee031a36484ed86e576a4c28b2c6f
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Query.Builder do @moduledoc false alias Ecto.Query @comparisons [ is_nil: 1, ==: 2, !=: 2, <: 2, >: 2, <=: 2, >=: 2 ] @dynamic_aggregates [ max: 1, min: 1, first_value: 1, last_value: 1, nth_value: 2, lag: 3, lead: 3, lag: 2, lead: 2, lag: 1, lead: 1 ] @static_aggregates [ count: {0, :integer}, count: {1, :integer}, count: {2, :integer}, avg: {1, :any}, sum: {1, :any}, row_number: {0, :integer}, rank: {0, :integer}, dense_rank: {0, :integer}, percent_rank: {0, :any}, cume_dist: {0, :any}, ntile: {1, :integer} ] @typedoc """ Quoted types store primitive types and types in the format {source, quoted}. The latter are handled directly in the planner, never forwarded to Ecto.Type. The Ecto.Type module concerns itself only with runtime types, which include all primitive types and custom user types. Also note custom user types do not show up during compilation time. """ @type quoted_type :: Ecto.Type.primitive | {non_neg_integer, atom | Macro.t} @doc """ Smart escapes a query expression and extracts interpolated values in a map. Everything that is a query expression will be escaped, interpolated expressions (`^foo`) will be moved to a map unescaped and replaced with `^index` in the query where index is a number indexing into the map. """ @spec escape(Macro.t, quoted_type, {list, term}, Keyword.t, Macro.Env.t | {Macro.Env.t, fun}) :: {Macro.t, {map, term}} def escape(expr, type, params_acc, vars, env) # var.x - where var is bound def escape({{:., _, [{var, _, context}, field]}, _, []}, _type, params_acc, vars, _env) when is_atom(var) and is_atom(context) and is_atom(field) do {escape_field!(var, field, vars), params_acc} end # field macro def escape({:field, _, [{var, _, context}, field]}, _type, params_acc, vars, _env) when is_atom(var) and is_atom(context) do {escape_field!(var, field, vars), params_acc} end # param interpolation def escape({:^, _, [arg]}, type, {params, acc}, _vars, _env) do expr = {:{}, [], [:^, [], [length(params)]]} params = [{arg, type} | params] {expr, {params, acc}} end # tagged types def escape({:type, _, [{:^, _, [arg]}, type]}, _type, {params, acc}, vars, env) do type = validate_type!(type, vars, env) expr = {:{}, [], [:type, [], [{:{}, [], [:^, [], [length(params)]]}, type]]} params = [{arg, type} | params] {expr, {params, acc}} end def escape({:type, _, [{math_op, _, [_, _]} = op_expr, type]}, _type, params_acc, vars, env) when math_op in ~w(+ - * /)a do escape_with_type(op_expr, type, params_acc, vars, env) end def escape({:type, _, [{{:., _, [{var, _, context}, field]}, _, []} = expr, type]}, _type, params_acc, vars, env) when is_atom(var) and is_atom(context) and is_atom(field) do escape_with_type(expr, type, params_acc, vars, env) end def escape({:type, _, [{:fragment, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) do escape_with_type(expr, type, params_acc, vars, env) end def escape({:type, _, [{:field, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) do escape_with_type(expr, type, params_acc, vars, env) end def escape({:type, _, [{agg, _, [_ | _]} = expr, type]}, _type, params_acc, vars, env) when agg in ~w(avg count max min sum)a do escape_with_type(expr, type, params_acc, vars, env) end # fragments def escape({:fragment, _, [query]}, _type, params_acc, vars, env) when is_list(query) do {escaped, params_acc} = Enum.map_reduce(query, params_acc, &escape_fragment(&1, :any, &2, vars, env)) {{:{}, [], [:fragment, [], [escaped]]}, params_acc} end def escape({:fragment, _, [{:^, _, [var]} = _expr]}, _type, params_acc, _vars, _env) do expr = quote do Ecto.Query.Builder.fragment!(unquote(var)) end {{:{}, [], [:fragment, [], [expr]]}, params_acc} end def escape({:fragment, _, [query | frags]}, _type, params_acc, vars, env) do pieces = expand_and_split_fragment(query, env) if length(pieces) != length(frags) + 1 do error! "fragment(...) expects extra arguments in the same amount of question marks in string. " <> "It received #{length(frags)} extra argument(s) but expected #{length(pieces) - 1}" end {frags, params_acc} = Enum.map_reduce(frags, params_acc, &escape(&1, :any, &2, vars, env)) {{:{}, [], [:fragment, [], merge_fragments(pieces, frags)]}, params_acc} end # interval def escape({:from_now, meta, [count, interval]}, type, params_acc, vars, env) do utc = quote do: ^DateTime.utc_now escape({:datetime_add, meta, [utc, count, interval]}, type, params_acc, vars, env) end def escape({:ago, meta, [count, interval]}, type, params_acc, vars, env) do utc = quote do: ^DateTime.utc_now count = case count do {:^, meta, [value]} -> negate = quote do: Ecto.Query.Builder.negate!(unquote(value)) {:^, meta, [negate]} value -> {:-, [], [value]} end escape({:datetime_add, meta, [utc, count, interval]}, type, params_acc, vars, env) end def escape({:datetime_add, _, [datetime, count, interval]} = expr, type, params_acc, vars, env) do assert_type!(expr, type, :naive_datetime) {datetime, params_acc} = escape(datetime, :naive_datetime, params_acc, vars, env) {count, interval, params_acc} = escape_interval(count, interval, params_acc, vars, env) {{:{}, [], [:datetime_add, [], [datetime, count, interval]]}, params_acc} end def escape({:date_add, _, [date, count, interval]} = expr, type, params_acc, vars, env) do assert_type!(expr, type, :date) {date, params_acc} = escape(date, :date, params_acc, vars, env) {count, interval, params_acc} = escape_interval(count, interval, params_acc, vars, env) {{:{}, [], [:date_add, [], [date, count, interval]]}, params_acc} end # sigils def escape({name, _, [_, []]} = sigil, type, params_acc, vars, _env) when name in ~w(sigil_s sigil_S sigil_w sigil_W)a do {literal(sigil, type, vars), params_acc} end # lists def escape(list, type, params_acc, vars, env) when is_list(list) do if Enum.all?(list, &is_binary(&1) or is_number(&1) or is_boolean(&1)) do {literal(list, type, vars), params_acc} else fun = case type do {:array, inner_type} -> &escape(&1, inner_type, &2, vars, env) _ -> # In case we don't have an array nor a literal at compile-time, # such as p.links == [^value], we don't do any casting nor validation. # We may want to tackle this if the expression above is ever used. &escape(&1, :any, &2, vars, env) end Enum.map_reduce(list, params_acc, fun) end end # literals def escape({:<<>>, _, args} = expr, type, params_acc, vars, _env) do valid? = Enum.all?(args, fn {:::, _, [left, _]} -> is_integer(left) or is_binary(left) left -> is_integer(left) or is_binary(left) end) unless valid? do error! "`#{Macro.to_string(expr)}` is not a valid query expression. " <> "Only literal binaries and strings are allowed, " <> "dynamic values need to be explicitly interpolated in queries with ^" end {literal(expr, type, vars), params_acc} end def escape({:-, _, [number]}, type, params_acc, vars, _env) when is_number(number), do: {literal(-number, type, vars), params_acc} def escape(number, type, params_acc, vars, _env) when is_number(number), do: {literal(number, type, vars), params_acc} def escape(binary, type, params_acc, vars, _env) when is_binary(binary), do: {literal(binary, type, vars), params_acc} def escape(boolean, type, params_acc, vars, _env) when is_boolean(boolean), do: {literal(boolean, type, vars), params_acc} def escape(nil, _type, params_acc, _vars, _env), do: {nil, params_acc} # comparison operators def escape({comp_op, _, [left, right]} = expr, type, params_acc, vars, env) when comp_op in ~w(== != < > <= >=)a do assert_type!(expr, type, :boolean) if is_nil(left) or is_nil(right) do error! "comparison with nil is forbidden as it is unsafe. " <> "If you want to check if a value is nil, use is_nil/1 instead" end ltype = quoted_type(right, vars) rtype = quoted_type(left, vars) {left, params_acc} = escape(left, ltype, params_acc, vars, env) {right, params_acc} = escape(right, rtype, params_acc, vars, env) {params, acc} = params_acc {{:{}, [], [comp_op, [], [left, right]]}, {params |> wrap_nil(left) |> wrap_nil(right), acc}} end # mathematical operators def escape({math_op, _, [left, right]}, type, params_acc, vars, env) when math_op in ~w(+ - * /)a do {left, params_acc} = escape(left, type, params_acc, vars, env) {right, params_acc} = escape(right, type, params_acc, vars, env) {{:{}, [], [math_op, [], [left, right]]}, params_acc} end # in operator def escape({:in, _, [left, right]} = expr, type, params_acc, vars, env) when is_list(right) when is_tuple(right) and elem(right, 0) in ~w(sigil_w sigil_W)a do assert_type!(expr, type, :boolean) {:array, ltype} = quoted_type(right, vars) rtype = {:array, quoted_type(left, vars)} {left, params_acc} = escape(left, ltype, params_acc, vars, env) {right, params_acc} = escape(right, rtype, params_acc, vars, env) {{:{}, [], [:in, [], [left, right]]}, params_acc} end def escape({:in, _, [left, right]} = expr, type, params_acc, vars, env) do assert_type!(expr, type, :boolean) ltype = {:out, quoted_type(right, vars)} rtype = {:in, quoted_type(left, vars)} {left, params_acc} = escape(left, ltype, params_acc, vars, env) {right, params_acc} = escape(right, rtype, params_acc, vars, env) # Remove any type wrapper from the right side right = case right do {:{}, [], [:type, [], [right, _]]} -> right _ -> right end {{:{}, [], [:in, [], [left, right]]}, params_acc} end def escape({:count, _, [arg, :distinct]}, type, params_acc, vars, env) do {arg, params_acc} = escape(arg, type, params_acc, vars, env) expr = {:{}, [], [:count, [], [arg, :distinct]]} {expr, params_acc} end def escape({:filter, _, [aggregate]}, type, params_acc, vars, env) do escape(aggregate, type, params_acc, vars, env) end def escape({:filter, _, [aggregate, filter_expr]}, type, params_acc, vars, env) do {aggregate, params_acc} = escape(aggregate, type, params_acc, vars, env) {filter_expr, params_acc} = escape(filter_expr, type, params_acc, vars, env) {{:{}, [], [:filter, [], [aggregate, filter_expr]]}, params_acc} end def escape({:coalesce, _, [left, right]}, type, params_acc, vars, env) do {left, params_acc} = escape(left, type, params_acc, vars, env) {right, params_acc} = escape(right, type, params_acc, vars, env) {{:{}, [], [:coalesce, [], [left, right]]}, params_acc} end def escape({:over, _, [{agg_name, _, agg_args} | over_args]}, type, params_acc, vars, env) do aggregate = {agg_name, [], agg_args || []} {aggregate, params_acc} = escape_window_function(aggregate, type, params_acc, vars, env) {window, params_acc} = escape_window_description(over_args, params_acc, vars, env) {{:{}, [], [:over, [], [aggregate, window]]}, params_acc} end def escape({:=, _, _} = expr, _type, _params_acc, _vars, _env) do error! "`#{Macro.to_string(expr)}` is not a valid query expression. " <> "The match operator is not supported: `=`. " <> "Did you mean to use `==` instead?" end def escape({op, _, _}, _type, _params_acc, _vars, _env) when op in ~w(|| && !)a do error! "short-circuit operators are not supported: `#{op}`. " <> "Instead use boolean operators: `and`, `or`, and `not`" end # Tuple def escape({left, right}, type, params_acc, vars, env) do escape({:{}, [], [left, right]}, type, params_acc, vars, env) end # Tuple def escape({:{}, _, list}, {:tuple, types}, params_acc, vars, env) do if Enum.count(list) == Enum.count(types) do {list, params_acc} = list |> Enum.zip(types) |> Enum.map_reduce(params_acc, fn {expr, type}, params_acc -> escape(expr, type, params_acc, vars, env) end) expr = {:{}, [], [:{}, [], list]} {expr, params_acc} else escape({:{}, [], list}, :any, params_acc, vars, env) end end # Tuple def escape({:{}, _, _}, _, _, _, _) do error! "Tuples can only be used in comparisons with literal tuples of the same size" end # Other functions - no type casting def escape({name, _, args} = expr, type, params_acc, vars, env) when is_atom(name) and is_list(args) do case call_type(name, length(args)) do {in_type, out_type} -> assert_type!(expr, type, out_type) escape_call(expr, in_type, params_acc, vars, env) nil -> try_expansion(expr, type, params_acc, vars, env) end end # Finally handle vars def escape({var, _, context}, _type, params_acc, vars, _env) when is_atom(var) and is_atom(context) do {escape_var!(var, vars), params_acc} end # Raise nice error messages for fun calls. def escape({fun, _, args} = other, _type, _params_acc, _vars, _env) when is_atom(fun) and is_list(args) do error! """ `#{Macro.to_string(other)}` is not a valid query expression. \ If you are trying to invoke a function that is not supported by Ecto, \ you can use fragments: fragment("some_function(?, ?, ?)", m.some_field, 1) See Ecto.Query.API to learn more about the supported functions and \ Ecto.Query.API.fragment/1 to learn more about fragments. """ end # Raise nice error message for remote calls def escape({{:., _, [mod, fun]}, _, args} = other, _type, _params_acc, _vars, _env) when is_atom(fun) do fun_arity = "#{fun}/#{length(args)}" error! """ `#{Macro.to_string(other)}` is not a valid query expression. \ If you want to invoke #{Macro.to_string(mod)}.#{fun_arity} in \ a query, make sure that the module #{Macro.to_string(mod)} \ is required and that #{fun_arity} is a macro """ end # For everything else we raise def escape(other, _type, _params_acc, _vars, _env) do error! "`#{Macro.to_string(other)}` is not a valid query expression" end defp escape_with_type(expr, type, params_acc, vars, env) do type = validate_type!(type, vars, env) {expr, params_acc} = escape(expr, type, params_acc, vars, env) {{:{}, [], [:type, [], [expr, Macro.escape(type)]]}, params_acc} end defp wrap_nil(params, {:{}, _, [:^, _, [ix]]}), do: wrap_nil(params, ix, []) defp wrap_nil(params, _other), do: params defp wrap_nil([{val, type} | params], 0, acc) do val = quote do: Ecto.Query.Builder.not_nil!(unquote(val)) Enum.reverse(acc, [{val, type} | params]) end defp wrap_nil([pair | params], i, acc) do wrap_nil(params, i - 1, [pair | acc]) end defp expand_and_split_fragment(query, {env, _}) do expand_and_split_fragment(query, env) end defp expand_and_split_fragment(query, env) do case Macro.expand(query, env) do binary when is_binary(binary) -> split_fragment(binary, "") _ -> error! bad_fragment_message(Macro.to_string(query)) end end defp bad_fragment_message(arg) do "to prevent SQL injection attacks, fragment(...) does not allow strings " <> "to be interpolated as the first argument via the `^` operator, got: `#{arg}`" end defp split_fragment(<<>>, consumed), do: [consumed] defp split_fragment(<<??, rest :: binary>>, consumed), do: [consumed | split_fragment(rest, "")] defp split_fragment(<<?\\, ??, rest :: binary>>, consumed), do: split_fragment(rest, consumed <> <<??>>) defp split_fragment(<<first :: utf8, rest :: binary>>, consumed), do: split_fragment(rest, consumed <> <<first :: utf8>>) defp escape_window_description([], params_acc, _vars, _env), do: {[], params_acc} defp escape_window_description([window_name], params_acc, _vars, _env) when is_atom(window_name), do: {window_name, params_acc} defp escape_window_description([kw], params_acc, vars, env), do: Ecto.Query.Builder.Windows.escape(kw, params_acc, vars, env) defp escape_window_function(expr, type, params_acc, vars, env) do expr |> validate_window_function!() |> escape(type, params_acc, vars, env) end defp validate_window_function!({:fragment, _, _} = expr), do: expr defp validate_window_function!({agg, _, args} = expr) when is_atom(agg) and is_list(args) do if Code.ensure_loaded?(Ecto.Query.WindowAPI) and not function_exported?(Ecto.Query.WindowAPI, agg, length(args)) do error! "unknown window function #{agg}/#{length(args)}. " <> "See Ecto.Query.WindowAPI for all available functions" end expr end defp validate_window_function!(expr) do expr end defp escape_call({name, _, args}, type, params_acc, vars, env) do {args, params_acc} = Enum.map_reduce(args, params_acc, &escape(&1, type, &2, vars, env)) expr = {:{}, [], [name, [], args]} {expr, params_acc} end defp escape_field!(var, field, vars) do var = escape_var!(var, vars) field = quoted_field!(field) dot = {:{}, [], [:., [], [var, field]]} {:{}, [], [dot, [], []]} end defp escape_interval(count, interval, params_acc, vars, env) do type = cond do is_float(count) -> :float is_integer(count) -> :integer true -> :decimal end {count, params_acc} = escape(count, type, params_acc, vars, env) {count, quoted_interval!(interval), params_acc} end defp escape_fragment({key, [{_, _}|_] = exprs}, type, params_acc, vars, env) when is_atom(key) do {escaped, params_acc} = Enum.map_reduce(exprs, params_acc, &escape_fragment(&1, type, &2, vars, env)) {{key, escaped}, params_acc} end defp escape_fragment({key, expr}, type, params_acc, vars, env) when is_atom(key) do {escaped, params_acc} = escape(expr, type, params_acc, vars, env) {{key, escaped}, params_acc} end defp escape_fragment({key, _expr}, _type, _params_acc, _vars, _env) do error! "fragment(...) with keywords accepts only atoms as keys, got `#{Macro.to_string(key)}`" end defp merge_fragments([h1|t1], [h2|t2]), do: [{:raw, h1}, {:expr, h2}|merge_fragments(t1, t2)] defp merge_fragments([h1], []), do: [{:raw, h1}] for {agg, arity} <- @dynamic_aggregates do defp call_type(unquote(agg), unquote(arity)), do: {:any, :any} end for {agg, {arity, return}} <- @static_aggregates do defp call_type(unquote(agg), unquote(arity)), do: {:any, unquote(return)} end for {comp, arity} <- @comparisons do defp call_type(unquote(comp), unquote(arity)), do: {:any, :boolean} end defp call_type(:or, 2), do: {:boolean, :boolean} defp call_type(:and, 2), do: {:boolean, :boolean} defp call_type(:not, 1), do: {:boolean, :boolean} defp call_type(:like, 2), do: {:string, :boolean} defp call_type(:ilike, 2), do: {:string, :boolean} defp call_type(_, _), do: nil defp assert_type!(_expr, {int, _field}, _actual) when is_integer(int) do :ok end defp assert_type!(expr, type, actual) do if Ecto.Type.match?(type, actual) do :ok else error! "expression `#{Macro.to_string(expr)}` does not type check. " <> "It returns a value of type #{inspect actual} but a value of " <> "type #{inspect type} is expected" end end @doc """ Validates the type with the given vars. """ def validate_type!({composite, type}, vars, env) do {composite, validate_type!(type, vars, env)} end def validate_type!({:^, _, [type]}, _vars, _env), do: type def validate_type!({:__aliases__, _, _} = type, _vars, {env, _}), do: Macro.expand(type, env) def validate_type!({:__aliases__, _, _} = type, _vars, env), do: Macro.expand(type, env) def validate_type!(type, _vars, _env) when is_atom(type), do: type def validate_type!({{:., _, [{var, _, context}, field]}, _, []}, vars, _env) when is_atom(var) and is_atom(context) and is_atom(field), do: {find_var!(var, vars), field} def validate_type!({:field, _, [{var, _, context}, field]}, vars, _env) when is_atom(var) and is_atom(context) and is_atom(field), do: {find_var!(var, vars), field} def validate_type!(type, _vars, _env) do error! "type/2 expects an alias, atom or source.field as second argument, got: `#{Macro.to_string(type)}`" end @always_tagged [:binary] defp literal(value, expected, vars), do: do_literal(value, expected, quoted_type(value, vars)) defp do_literal(value, _, current) when current in @always_tagged, do: {:%, [], [Ecto.Query.Tagged, {:%{}, [], [value: value, type: current]}]} defp do_literal(value, :any, _current), do: value defp do_literal(value, expected, expected), do: value defp do_literal(value, expected, _current), do: {:%, [], [Ecto.Query.Tagged, {:%{}, [], [value: value, type: expected]}]} @doc """ Escape the params entries list. """ @spec escape_params(list()) :: list() def escape_params(list), do: Enum.reverse(list) @doc """ Escapes a variable according to the given binds. A escaped variable is represented internally as `&0`, `&1` and so on. """ @spec escape_var!(atom, Keyword.t) :: Macro.t def escape_var!(var, vars) do {:{}, [], [:&, [], [find_var!(var, vars)]]} end @doc """ Escapes a list of bindings as a list of atoms. Only variables or `{:atom, value}` tuples are allowed in the `bindings` list, otherwise an `Ecto.Query.CompileError` is raised. ## Examples iex> escape_binding(%Ecto.Query{}, quote(do: [x, y, z]), __ENV__) {%Ecto.Query{}, [x: 0, y: 1, z: 2]} iex> escape_binding(%Ecto.Query{}, quote(do: [{x, 0}, {z, 2}]), __ENV__) {%Ecto.Query{}, [x: 0, z: 2]} iex> escape_binding(%Ecto.Query{}, quote(do: [x, y, x]), __ENV__) ** (Ecto.Query.CompileError) variable `x` is bound twice iex> escape_binding(%Ecto.Query{}, quote(do: [a, b, :foo]), __ENV__) ** (Ecto.Query.CompileError) binding list should contain only variables or `{as, var}` tuples, got: :foo """ @spec escape_binding(Macro.t, list, Macro.Env.t) :: {Macro.t, Keyword.t} def escape_binding(query, binding, _env) when is_list(binding) do vars = binding |> Enum.with_index |> Enum.map(&escape_bind/1) assert_no_duplicate_binding!(vars) {positional_vars, named_vars} = Enum.split_while(vars, &not named_bind?(&1)) assert_named_binds_in_tail!(named_vars, binding) {query, positional_binds} = calculate_positional_binds(query, positional_vars) {query, named_binds} = calculate_named_binds(query, named_vars) {query, positional_binds ++ named_binds} end def escape_binding(_query, bind, _env) do error! "binding should be list of variables and `{as, var}` tuples " <> "at the end, got: #{Macro.to_string(bind)}" end defp named_bind?({kind, _, _}), do: kind == :named defp assert_named_binds_in_tail!(named_vars, binding) do if Enum.all?(named_vars, &named_bind?/1) do :ok else error! "named binds in the form of `{as, var}` tuples must be at the end " <> "of the binding list, got: #{Macro.to_string(binding)}" end end defp assert_no_duplicate_binding!(vars) do bound_vars = for {_, var, _} <- vars, var != :_, do: var case bound_vars -- Enum.uniq(bound_vars) do [] -> :ok [var | _] -> error! "variable `#{var}` is bound twice" end end defp calculate_positional_binds(query, vars) do case Enum.split_while(vars, &elem(&1, 1) != :...) do {vars, []} -> vars = for {:pos, var, count} <- vars, do: {var, count} {query, vars} {vars, [_ | tail]} -> query = quote do query = Ecto.Queryable.to_query(unquote(query)) escape_count = Ecto.Query.Builder.count_binds(query) query end tail = tail |> Enum.with_index(-length(tail)) |> Enum.map(fn {{:pos, k, _}, count} -> {k, quote(do: escape_count + unquote(count))} end) vars = for {:pos, var, count} <- vars, do: {var, count} {query, vars ++ tail} end end def calculate_named_binds(query, []), do: {query, []} def calculate_named_binds(query, vars) do query = quote do query = Ecto.Queryable.to_query(unquote(query)) end vars = for {:named, key, name} <- vars do {key, quote do Ecto.Query.Builder.count_alias!(query, unquote(name)) end} end {query, vars} end @doc """ Count the alias for the given query. """ def count_alias!(%{aliases: aliases} = query, name) do case aliases do %{^name => ix} -> ix %{} -> raise Ecto.QueryError, message: "unknown bind name `#{inspect name}`", query: query end end defp escape_bind({{{var, _, context}, ix}, _}) when is_atom(var) and is_atom(context), do: {:pos, var, ix} defp escape_bind({{var, _, context}, ix}) when is_atom(var) and is_atom(context), do: {:pos, var, ix} defp escape_bind({{name, {var, _, context}}, _ix}) when is_atom(name) and is_atom(var) and is_atom(context), do: {:named, var, name} defp escape_bind({bind, _ix}), do: error!("binding list should contain only variables or " <> "`{as, var}` tuples, got: #{Macro.to_string(bind)}") defp try_expansion(expr, type, params, vars, %Macro.Env{} = env) do try_expansion(expr, type, params, vars, {env, &escape/5}) end defp try_expansion(expr, type, params, vars, {env, fun}) do case Macro.expand_once(expr, env) do ^expr -> error! """ `#{Macro.to_string(expr)}` is not a valid query expression. * If you intended to call a database function, please check the documentation for Ecto.Query to see the supported database expressions * If you intended to call an Elixir function or introduce a value, you need to explicitly interpolate it with ^ """ expanded -> fun.(expanded, type, params, vars, env) end end @doc """ Finds the index value for the given var in vars or raises. """ def find_var!(var, vars) do vars[var] || error! "unbound variable `#{var}` in query. If you are attempting to interpolate a value, use ^var" end @doc """ Checks if the field is an atom at compilation time or delegate the check to runtime for interpolation. """ def quoted_field!({:^, _, [expr]}), do: quote(do: Ecto.Query.Builder.field!(unquote(expr))) def quoted_field!(atom) when is_atom(atom), do: atom def quoted_field!(other), do: error!("expected literal atom or interpolated value in field/2, got: `#{inspect other}`") @doc """ Called by escaper at runtime to verify that value is an atom. """ def field!(atom) when is_atom(atom), do: atom def field!(other), do: error!("expected atom in field/2, got: `#{inspect other}`") @doc """ Called by escaper at runtime to verify that a value is not nil. """ def not_nil!(nil) do raise ArgumentError, "comparison with nil is forbidden as it is unsafe. " <> "If you want to check if a value is nil, use is_nil/1 instead" end def not_nil!(not_nil) do not_nil end @doc """ Checks if the field is a valid interval at compilation time or delegate the check to runtime for interpolation. """ def quoted_interval!({:^, _, [expr]}), do: quote(do: Ecto.Query.Builder.interval!(unquote(expr))) def quoted_interval!(other), do: interval!(other) @doc """ Called by escaper at runtime to verify keywords. """ def fragment!(kw) do if Keyword.keyword?(kw) do kw else raise ArgumentError, bad_fragment_message(inspect(kw)) end end @doc """ Called by escaper at runtime to verify that value is a valid interval. """ @interval ~w(year month week day hour minute second millisecond microsecond) def interval!(interval) when interval in @interval, do: interval def interval!(other_string) when is_binary(other_string), do: error!("invalid interval: `#{inspect other_string}` (expected one of #{Enum.join(@interval, ", ")})") def interval!(not_string), do: error!("invalid interval: `#{inspect not_string}` (expected a string)") @doc """ Negates the given number. """ def negate!(%Decimal{} = decimal) do Decimal.minus(decimal) end def negate!(number) when is_number(number) do -number end @doc """ Returns the type of an expression at build time. """ @spec quoted_type(Macro.t, Keyword.t) :: quoted_type # Fields def quoted_type({{:., _, [{var, _, context}, field]}, _, []}, vars) when is_atom(var) and is_atom(context) and is_atom(field), do: {find_var!(var, vars), field} def quoted_type({:field, _, [{var, _, context}, field]}, vars) when is_atom(var) and is_atom(context) and is_atom(field), do: {find_var!(var, vars), field} # Unquoting code here means the second argument of field will # always be unquoted twice, one by the type checking and another # in the query itself. We are assuming this is not an issue # as the solution is somewhat complicated. def quoted_type({:field, _, [{var, _, context}, {:^, _, [code]}]}, vars) when is_atom(var) and is_atom(context), do: {find_var!(var, vars), code} # Interval def quoted_type({:datetime_add, _, [_, _, __]}, _vars), do: :naive_datetime def quoted_type({:date_add, _, [_, _, __]}, _vars), do: :date # Tagged def quoted_type({:<<>>, _, _}, _vars), do: :binary def quoted_type({:type, _, [_, type]}, _vars), do: type # Sigils def quoted_type({sigil, _, [_, []]}, _vars) when sigil in ~w(sigil_s sigil_S)a, do: :string def quoted_type({sigil, _, [_, []]}, _vars) when sigil in ~w(sigil_w sigil_W)a, do: {:array, :string} # Lists def quoted_type(list, vars) when is_list(list) do case list |> Enum.map(&quoted_type(&1, vars)) |> Enum.uniq() do [type] -> {:array, type} _ -> {:array, :any} end end # Negative numbers def quoted_type({:-, _, [number]}, _vars) when is_integer(number), do: :integer def quoted_type({:-, _, [number]}, _vars) when is_float(number), do: :float # Dynamic aggregates for {agg, arity} <- @dynamic_aggregates do args = 1..arity |> Enum.map(fn _ -> Macro.var(:_, __MODULE__) end) |> tl() def quoted_type({unquote(agg), _, [expr, unquote_splicing(args)]}, vars) do quoted_type(expr, vars) end end # Literals def quoted_type(literal, _vars) when is_float(literal), do: :float def quoted_type(literal, _vars) when is_binary(literal), do: :string def quoted_type(literal, _vars) when is_boolean(literal), do: :boolean def quoted_type(literal, _vars) when is_integer(literal), do: :integer # Tuples def quoted_type({left, right}, vars), do: quoted_type({:{}, [], [left, right]}, vars) def quoted_type({:{}, _, elems}, vars), do: {:tuple, Enum.map(elems, &quoted_type(&1, vars))} def quoted_type({name, _, args}, _vars) when is_atom(name) and is_list(args) do case call_type(name, length(args)) do {_in, out} -> out nil -> :any end end def quoted_type(_, _vars), do: :any @doc """ Raises a query building error. """ def error!(message) when is_binary(message) do {:current_stacktrace, [_|t]} = Process.info(self(), :current_stacktrace) t = Enum.drop_while t, fn {mod, _, _, _} -> String.starts_with?(Atom.to_string(mod), ["Elixir.Ecto.Query.", "Elixir.Enum"]) _ -> false end reraise Ecto.Query.CompileError, [message: message], t end @doc """ Counts the bindings in a query expression. ## Examples iex> count_binds(%Ecto.Query{joins: [1,2,3]}) 4 """ @spec count_binds(Ecto.Query.t) :: non_neg_integer def count_binds(%Query{joins: joins}) do 1 + length(joins) end @doc """ Applies a query at compilation time or at runtime. This function is responsible for checking if a given query is an `Ecto.Query` struct at compile time. If it is not it will act accordingly. If a query is available, it invokes the `apply` function in the given `module`, otherwise, it delegates the call to runtime. It is important to keep in mind the complexities introduced by this function. In particular, a %Query{} is mixture of escaped and unescaped expressions which makes it impossible for this function to properly escape or unescape it at compile/runtime. For this reason, the apply function should be ready to handle arguments in both escaped and unescaped form. For example, take into account the `Builder.OrderBy`: select = %Ecto.Query.QueryExpr{expr: expr, file: env.file, line: env.line} Builder.apply_query(query, __MODULE__, [order_by], env) `expr` is already an escaped expression and we must not escape it again. However, it is wrapped in an Ecto.Query.QueryExpr, which must be escaped! Furthermore, the `apply/2` function in `Builder.OrderBy` very likely will inject the QueryExpr inside Query, which again, is a mixture of escaped and unescaped expressions. That said, you need to obey the following rules: 1. In order to call this function, the arguments must be escapable values supported by the `escape/1` function below; 2. The apply function may not manipulate the given arguments, with exception to the query. In particular, when invoked at compilation time, all arguments (except the query) will be escaped, so they can be injected into the query properly, but they will be in their runtime form when invoked at runtime. """ def apply_query(query, module, args, env) do query = Macro.expand(query, env) case unescape_query(query) do %Query{} = unescaped -> apply(module, :apply, [unescaped|args]) |> escape_query _ -> quote do query = unquote(query) # Unquote the query for any binding variable unquote(module).apply(query, unquote_splicing(args)) end end end # Unescapes an `Ecto.Query` struct. defp unescape_query({:%, _, [Query, {:%{}, _, list}]}) do struct(Query, list) end defp unescape_query({:%{}, _, list} = ast) do if List.keyfind(list, :__struct__, 0) == {:__struct__, Query} do Map.new(list) else ast end end defp unescape_query(other) do other end # Escapes an `Ecto.Query` and associated structs. defp escape_query(%Query{} = query), do: {:%{}, [], Map.to_list(query)} defp escape_query(other), do: other end
34.596457
116
0.629929
0306f1dd11584d83bb9bd0cda5585ae264913e3a
38,430
exs
Elixir
lib/elixir/test/elixir/stream_test.exs
kenichi/elixir
8c27da88c70623cbe516d5310c885943395a82a2
[ "Apache-2.0" ]
1
2019-08-13T23:22:33.000Z
2019-08-13T23:22:33.000Z
lib/elixir/test/elixir/stream_test.exs
kenichi/elixir
8c27da88c70623cbe516d5310c885943395a82a2
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/stream_test.exs
kenichi/elixir
8c27da88c70623cbe516d5310c885943395a82a2
[ "Apache-2.0" ]
null
null
null
Code.require_file("test_helper.exs", __DIR__) defmodule StreamTest do use ExUnit.Case, async: true doctest Stream defmodule Pdict do defstruct [] defimpl Collectable do def into(struct) do fun = fn _, {:cont, x} -> Process.put(:stream_cont, [x | Process.get(:stream_cont)]) _, :done -> Process.put(:stream_done, true) _, :halt -> Process.put(:stream_halt, true) end {struct, fun} end end end defmodule HaltAcc do defstruct [:acc] defimpl Enumerable do def count(_lazy), do: {:error, __MODULE__} def member?(_lazy, _value), do: {:error, __MODULE__} def slice(_lazy), do: {:error, __MODULE__} def reduce(lazy, _acc, _fun) do {:halted, Enum.to_list(lazy.acc)} end end end test "streams as enumerables" do stream = Stream.map([1, 2, 3], &(&1 * 2)) # Reduce assert Enum.map(stream, &(&1 + 1)) == [3, 5, 7] # Member assert Enum.member?(stream, 4) refute Enum.member?(stream, 1) # Count assert Enum.count(stream) == 3 end test "streams are composable" do stream = Stream.map([1, 2, 3], &(&1 * 2)) assert lazy?(stream) stream = Stream.map(stream, &(&1 + 1)) assert lazy?(stream) assert Enum.to_list(stream) == [3, 5, 7] end test "chunk_every/2, chunk_every/3 and chunk_every/4" do assert Stream.chunk_every([1, 2, 3, 4, 5], 2) |> Enum.to_list() == [[1, 2], [3, 4], [5]] assert Stream.chunk_every([1, 2, 3, 4, 5], 2, 2, [6]) |> Enum.to_list() == [[1, 2], [3, 4], [5, 6]] assert Stream.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard) |> Enum.to_list() == [[1, 2, 3], [3, 4, 5]] assert Stream.chunk_every([1, 2, 3, 4, 5, 6], 2, 3, :discard) |> Enum.to_list() == [[1, 2], [4, 5]] assert Stream.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, []) |> Enum.to_list() == [[1, 2, 3], [3, 4, 5], [5, 6]] assert Stream.chunk_every([1, 2, 3, 4, 5, 6], 3, 3, []) |> Enum.to_list() == [[1, 2, 3], [4, 5, 6]] assert Stream.chunk_every([1, 2, 3, 4, 5], 4, 4, 6..10) |> Enum.to_list() == [[1, 2, 3, 4], [5, 6, 7, 8]] end test "chunk_every/4 is zippable" do stream = Stream.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, []) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end test "chunk_every/4 is haltable" do assert 1..10 |> Stream.take(6) |> Stream.chunk_every(4, 4, [7, 8]) |> Enum.to_list() == [[1, 2, 3, 4], [5, 6, 7, 8]] assert 1..10 |> Stream.take(6) |> Stream.chunk_every(4, 4, [7, 8]) |> Stream.take(3) |> Enum.to_list() == [[1, 2, 3, 4], [5, 6, 7, 8]] assert 1..10 |> Stream.take(6) |> Stream.chunk_every(4, 4, [7, 8]) |> Stream.take(2) |> Enum.to_list() == [[1, 2, 3, 4], [5, 6, 7, 8]] assert 1..10 |> Stream.take(6) |> Stream.chunk_every(4, 4, [7, 8]) |> Stream.take(1) |> Enum.to_list() == [[1, 2, 3, 4]] assert 1..6 |> Stream.take(6) |> Stream.chunk_every(4, 4, [7, 8]) |> Enum.to_list() == [[1, 2, 3, 4], [5, 6, 7, 8]] end test "chunk_by/2" do stream = Stream.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1)) assert lazy?(stream) assert Enum.to_list(stream) == [[1], [2, 2], [3], [4, 4, 6], [7, 7]] assert stream |> Stream.take(3) |> Enum.to_list() == [[1], [2, 2], [3]] assert 1..10 |> Stream.chunk_every(2) |> Enum.take(2) == [[1, 2], [3, 4]] end test "chunk_by/2 is zippable" do stream = Stream.chunk_by([1, 2, 2, 3], &(rem(&1, 2) == 1)) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end test "chunk_while/4" do chunk_fun = fn i, acc -> cond do i > 10 -> {:halt, acc} rem(i, 2) == 0 -> {:cont, Enum.reverse([i | acc]), []} true -> {:cont, [i | acc]} end end after_fun = fn [] -> {:cont, []} acc -> {:cont, Enum.reverse(acc), []} end assert Stream.chunk_while([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [], chunk_fun, after_fun) |> Enum.to_list() == [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] assert Stream.chunk_while(0..9, [], chunk_fun, after_fun) |> Enum.to_list() == [[0], [1, 2], [3, 4], [5, 6], [7, 8], [9]] assert Stream.chunk_while(0..10, [], chunk_fun, after_fun) |> Enum.to_list() == [[0], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] assert Stream.chunk_while(0..11, [], chunk_fun, after_fun) |> Enum.to_list() == [[0], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] assert Stream.chunk_while([5, 7, 9, 11], [], chunk_fun, after_fun) |> Enum.to_list() == [[5, 7, 9]] end test "chunk_while/4 with inner halt" do chunk_fun = fn i, [] -> {:cont, [i]} i, chunk -> if rem(i, 2) == 0 do {:cont, Enum.reverse(chunk), [i]} else {:cont, [i | chunk]} end end after_fun = fn [] -> {:cont, []} chunk -> {:cont, Enum.reverse(chunk), []} end assert Stream.chunk_while([1, 2, 3, 4, 5], [], chunk_fun, after_fun) |> Enum.at(0) == [1] end test "concat/1" do stream = Stream.concat([1..3, [], [4, 5, 6], [], 7..9]) assert is_function(stream) assert Enum.to_list(stream) == [1, 2, 3, 4, 5, 6, 7, 8, 9] assert Enum.take(stream, 5) == [1, 2, 3, 4, 5] stream = Stream.concat([1..3, [4, 5, 6], Stream.cycle(7..100)]) assert is_function(stream) assert Enum.take(stream, 13) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] end test "concat/2" do stream = Stream.concat(1..3, 4..6) assert is_function(stream) assert Stream.cycle(stream) |> Enum.take(16) == [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4] stream = Stream.concat(1..3, []) assert is_function(stream) assert Stream.cycle(stream) |> Enum.take(5) == [1, 2, 3, 1, 2] stream = Stream.concat(1..6, Stream.cycle(7..9)) assert is_function(stream) assert Stream.drop(stream, 3) |> Enum.take(13) == [4, 5, 6, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7] stream = Stream.concat(Stream.cycle(1..3), Stream.cycle(4..6)) assert is_function(stream) assert Enum.take(stream, 13) == [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1] end test "concat/2 is zippable" do stream = 1..2 |> Stream.take(2) |> Stream.concat(3..4) assert Enum.zip(1..4, [1, 2, 3, 4]) == Enum.zip(1..4, stream) end test "concat/2 does not intercept wrapped lazy enumeration" do # concat returns a lazy enumeration that does not halt assert Stream.concat([[0], Stream.map([1, 2, 3], & &1), [4]]) |> Stream.take_while(fn x -> x <= 4 end) |> Enum.to_list() == [0, 1, 2, 3, 4] # concat returns a lazy enumeration that does halts assert Stream.concat([[0], Stream.take_while(1..6, &(&1 <= 3)), [4]]) |> Stream.take_while(fn x -> x <= 4 end) |> Enum.to_list() == [0, 1, 2, 3, 4] end test "cycle/1" do stream = Stream.cycle([1, 2, 3]) assert is_function(stream) assert_raise ArgumentError, "cannot cycle over empty enumerable", fn -> Stream.cycle([]) end assert_raise ArgumentError, "cannot cycle over empty enumerable", fn -> Stream.cycle(%{}) |> Enum.to_list() end assert Stream.cycle([1, 2, 3]) |> Stream.take(5) |> Enum.to_list() == [1, 2, 3, 1, 2] assert Enum.take(stream, 5) == [1, 2, 3, 1, 2] end test "cycle/1 is zippable" do stream = Stream.cycle([1, 2, 3]) assert Enum.zip(1..6, [1, 2, 3, 1, 2, 3]) == Enum.zip(1..6, stream) end test "cycle/1 with inner stream" do assert [1, 2, 3] |> Stream.take(2) |> Stream.cycle() |> Enum.take(4) == [1, 2, 1, 2] end test "dedup/1 is lazy" do assert lazy?(Stream.dedup([1, 2, 3])) end test "dedup/1" do assert Stream.dedup([1, 1, 2, 1, 1, 2, 1]) |> Enum.to_list() == [1, 2, 1, 2, 1] assert Stream.dedup([2, 1, 1, 2, 1]) |> Enum.to_list() == [2, 1, 2, 1] assert Stream.dedup([1, 2, 3, 4]) |> Enum.to_list() == [1, 2, 3, 4] assert Stream.dedup([1, 1.0, 2.0, 2]) |> Enum.to_list() == [1, 1.0, 2.0, 2] assert Stream.dedup([]) |> Enum.to_list() == [] assert Stream.dedup([nil, nil, true, {:value, true}]) |> Enum.to_list() == [nil, true, {:value, true}] assert Stream.dedup([nil]) |> Enum.to_list() == [nil] end test "dedup_by/2" do assert Stream.dedup_by([{1, :x}, {2, :y}, {2, :z}, {1, :x}], fn {x, _} -> x end) |> Enum.to_list() == [{1, :x}, {2, :y}, {1, :x}] end test "drop/2" do stream = Stream.drop(1..10, 5) assert lazy?(stream) assert Enum.to_list(stream) == [6, 7, 8, 9, 10] assert Enum.to_list(Stream.drop(1..5, 0)) == [1, 2, 3, 4, 5] assert Enum.to_list(Stream.drop(1..3, 5)) == [] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.drop(nats, 2) |> Enum.take(5) == [3, 4, 5, 6, 7] end test "drop/2 with negative count" do stream = Stream.drop(1..10, -5) assert lazy?(stream) assert Enum.to_list(stream) == [1, 2, 3, 4, 5] stream = Stream.drop(1..10, -5) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end test "drop/2 with negative count stream entries" do par = self() pid = spawn_link(fn -> Enum.each(Stream.drop(&inbox_stream/2, -3), fn x -> send(par, {:stream, x}) end) end) send(pid, {:stream, 1}) send(pid, {:stream, 2}) send(pid, {:stream, 3}) refute_receive {:stream, 1} send(pid, {:stream, 4}) assert_receive {:stream, 1} send(pid, {:stream, 5}) assert_receive {:stream, 2} refute_receive {:stream, 3} end test "drop_every/2" do assert 1..10 |> Stream.drop_every(2) |> Enum.to_list() == [2, 4, 6, 8, 10] assert 1..10 |> Stream.drop_every(3) |> Enum.to_list() == [2, 3, 5, 6, 8, 9] assert 1..10 |> Stream.drop(2) |> Stream.drop_every(2) |> Stream.drop(1) |> Enum.to_list() == [6, 8, 10] assert 1..10 |> Stream.drop_every(0) |> Enum.to_list() == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] assert [] |> Stream.drop_every(10) |> Enum.to_list() == [] end test "drop_every/2 without non-negative integer" do assert_raise FunctionClauseError, fn -> Stream.drop_every(1..10, -1) end assert_raise FunctionClauseError, fn -> Stream.drop_every(1..10, 3.33) end end test "drop_while/2" do stream = Stream.drop_while(1..10, &(&1 <= 5)) assert lazy?(stream) assert Enum.to_list(stream) == [6, 7, 8, 9, 10] assert Enum.to_list(Stream.drop_while(1..5, &(&1 <= 0))) == [1, 2, 3, 4, 5] assert Enum.to_list(Stream.drop_while(1..3, &(&1 <= 5))) == [] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.drop_while(nats, &(&1 <= 5)) |> Enum.take(5) == [6, 7, 8, 9, 10] end test "each/2" do Process.put(:stream_each, []) stream = Stream.each([1, 2, 3], fn x -> Process.put(:stream_each, [x | Process.get(:stream_each)]) end) assert lazy?(stream) assert Enum.to_list(stream) == [1, 2, 3] assert Process.get(:stream_each) == [3, 2, 1] end test "filter/2" do stream = Stream.filter([1, 2, 3], fn x -> rem(x, 2) == 0 end) assert lazy?(stream) assert Enum.to_list(stream) == [2] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.filter(nats, &(rem(&1, 2) == 0)) |> Enum.take(5) == [2, 4, 6, 8, 10] end test "flat_map/2" do stream = Stream.flat_map([1, 2, 3], &[&1, &1 * 2]) assert lazy?(stream) assert Enum.to_list(stream) == [1, 2, 2, 4, 3, 6] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.flat_map(nats, &[&1, &1 * 2]) |> Enum.take(6) == [1, 2, 2, 4, 3, 6] end test "flat_map/2 does not intercept wrapped lazy enumeration" do # flat_map returns a lazy enumeration that does not halt assert [1, 2, 3, -1, -2] |> Stream.flat_map(fn x -> Stream.map([x, x + 1], & &1) end) |> Stream.take_while(fn x -> x >= 0 end) |> Enum.to_list() == [1, 2, 2, 3, 3, 4] # flat_map returns a lazy enumeration that does halts assert [1, 2, 3, -1, -2] |> Stream.flat_map(fn x -> Stream.take_while([x, x + 1, x + 2], &(&1 <= x + 1)) end) |> Stream.take_while(fn x -> x >= 0 end) |> Enum.to_list() == [1, 2, 2, 3, 3, 4] # flat_map returns a lazy enumeration that does halts wrapped in an enumerable assert [1, 2, 3, -1, -2] |> Stream.flat_map(fn x -> Stream.concat([x], Stream.take_while([x + 1, x + 2], &(&1 <= x + 1))) end) |> Stream.take_while(fn x -> x >= 0 end) |> Enum.to_list() == [1, 2, 2, 3, 3, 4] end test "flat_map/2 is zippable" do stream = [1, 2, 3, -1, -2] |> Stream.flat_map(fn x -> Stream.map([x, x + 1], & &1) end) |> Stream.take_while(fn x -> x >= 0 end) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end test "flat_map/2 does not leave inner stream suspended" do stream = Stream.flat_map([1, 2, 3], fn i -> Stream.resource(fn -> i end, fn acc -> {[acc], acc + 1} end, fn _ -> Process.put(:stream_flat_map, true) end) end) Process.put(:stream_flat_map, false) assert stream |> Enum.take(3) == [1, 2, 3] assert Process.get(:stream_flat_map) end test "flat_map/2 does not leave outer stream suspended" do stream = Stream.resource(fn -> 1 end, fn acc -> {[acc], acc + 1} end, fn _ -> Process.put(:stream_flat_map, true) end) stream = Stream.flat_map(stream, fn i -> [i, i + 1, i + 2] end) Process.put(:stream_flat_map, false) assert stream |> Enum.take(3) == [1, 2, 3] assert Process.get(:stream_flat_map) end test "flat_map/2 closes on error" do stream = Stream.resource(fn -> 1 end, fn acc -> {[acc], acc + 1} end, fn _ -> Process.put(:stream_flat_map, true) end) stream = Stream.flat_map(stream, fn _ -> throw(:error) end) Process.put(:stream_flat_map, false) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_flat_map) end test "flat_map/2 with inner flat_map/2" do stream = Stream.flat_map(1..5, fn x -> Stream.flat_map([x], fn x -> x..(x * x) end) |> Stream.map(&(&1 * 1)) end) assert Enum.take(stream, 5) == [1, 2, 3, 4, 3] end test "flat_map/2 properly halts both inner and outer stream when inner stream is halted" do # Fixes a bug that, when the inner stream was done, # sending it a halt would cause it to return the # inner stream was halted, forcing flat_map to get # the next value from the outer stream, evaluate it, # get another inner stream, just to halt it. # 2 should never be used assert [1, 2] |> Stream.flat_map(fn 1 -> Stream.repeatedly(fn -> 1 end) end) |> Stream.flat_map(fn 1 -> Stream.repeatedly(fn -> 1 end) end) |> Enum.take(1) == [1] end test "interval/1" do stream = Stream.interval(10) now = :os.timestamp() assert Enum.take(stream, 5) == [0, 1, 2, 3, 4] assert :timer.now_diff(:os.timestamp(), now) >= 50000 end test "into/2 and run/1" do Process.put(:stream_cont, []) Process.put(:stream_done, false) Process.put(:stream_halt, false) stream = Stream.into([1, 2, 3], %Pdict{}) assert lazy?(stream) assert Stream.run(stream) == :ok assert Process.get(:stream_cont) == [3, 2, 1] assert Process.get(:stream_done) refute Process.get(:stream_halt) stream = Stream.into(fn _, _ -> raise "error" end, %Pdict{}) catch_error(Stream.run(stream)) assert Process.get(:stream_halt) end test "into/3" do Process.put(:stream_cont, []) Process.put(:stream_done, false) Process.put(:stream_halt, false) stream = Stream.into([1, 2, 3], %Pdict{}, fn x -> x * 2 end) assert lazy?(stream) assert Enum.to_list(stream) == [1, 2, 3] assert Process.get(:stream_cont) == [6, 4, 2] assert Process.get(:stream_done) refute Process.get(:stream_halt) end test "into/2 with halting" do Process.put(:stream_cont, []) Process.put(:stream_done, false) Process.put(:stream_halt, false) stream = Stream.into([1, 2, 3], %Pdict{}) assert lazy?(stream) assert Enum.take(stream, 1) == [1] assert Process.get(:stream_cont) == [1] assert Process.get(:stream_done) refute Process.get(:stream_halt) end test "transform/3" do stream = Stream.transform([1, 2, 3], 0, &{[&1, &2], &1 + &2}) assert lazy?(stream) assert Enum.to_list(stream) == [1, 0, 2, 1, 3, 3] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.transform(nats, 0, &{[&1, &2], &1 + &2}) |> Enum.take(6) == [1, 0, 2, 1, 3, 3] end test "transform/3 with early halt" do stream = fn -> throw(:error) end |> Stream.repeatedly() |> Stream.transform(nil, &{[&1, &2], &1}) assert {:halted, nil} = Enumerable.reduce(stream, {:halt, nil}, fn _, _ -> throw(:error) end) end test "transform/3 with early suspend" do stream = Stream.repeatedly(fn -> throw(:error) end) |> Stream.transform(nil, &{[&1, &2], &1}) assert {:suspended, nil, _} = Enumerable.reduce(stream, {:suspend, nil}, fn _, _ -> throw(:error) end) end test "transform/3 with halt" do stream = Stream.resource(fn -> 1 end, fn acc -> {[acc], acc + 1} end, fn _ -> Process.put(:stream_transform, true) end) stream = Stream.transform(stream, 0, fn i, acc -> if acc < 3, do: {[i], acc + 1}, else: {:halt, acc} end) Process.put(:stream_transform, false) assert Enum.to_list(stream) == [1, 2, 3] assert Process.get(:stream_transform) end test "transform/3 (via flat_map) handles multiple returns from suspension" do assert [false] |> Stream.take(1) |> Stream.concat([true]) |> Stream.flat_map(&[&1]) |> Enum.to_list() == [false, true] end test "iterate/2" do stream = Stream.iterate(0, &(&1 + 2)) assert Enum.take(stream, 5) == [0, 2, 4, 6, 8] stream = Stream.iterate(5, &(&1 + 2)) assert Enum.take(stream, 5) == [5, 7, 9, 11, 13] # Only calculate values if needed stream = Stream.iterate("HELLO", &raise/1) assert Enum.take(stream, 1) == ["HELLO"] end test "map/2" do stream = Stream.map([1, 2, 3], &(&1 * 2)) assert lazy?(stream) assert Enum.to_list(stream) == [2, 4, 6] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.map(nats, &(&1 * 2)) |> Enum.take(5) == [2, 4, 6, 8, 10] assert Stream.map(nats, &(&1 - 2)) |> Stream.map(&(&1 * 2)) |> Enum.take(3) == [-2, 0, 2] end test "map_every/3" do assert 1..10 |> Stream.map_every(2, &(&1 * 2)) |> Enum.to_list() == [2, 2, 6, 4, 10, 6, 14, 8, 18, 10] assert 1..10 |> Stream.map_every(3, &(&1 * 2)) |> Enum.to_list() == [2, 2, 3, 8, 5, 6, 14, 8, 9, 20] assert 1..10 |> Stream.drop(2) |> Stream.map_every(2, &(&1 * 2)) |> Stream.drop(1) |> Enum.to_list() == [4, 10, 6, 14, 8, 18, 10] assert 1..5 |> Stream.map_every(0, &(&1 * 2)) |> Enum.to_list() == [1, 2, 3, 4, 5] assert [] |> Stream.map_every(10, &(&1 * 2)) |> Enum.to_list() == [] assert_raise FunctionClauseError, fn -> Stream.map_every(1..10, -1, &(&1 * 2)) end assert_raise FunctionClauseError, fn -> Stream.map_every(1..10, 3.33, &(&1 * 2)) end end test "reject/2" do stream = Stream.reject([1, 2, 3], fn x -> rem(x, 2) == 0 end) assert lazy?(stream) assert Enum.to_list(stream) == [1, 3] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.reject(nats, &(rem(&1, 2) == 0)) |> Enum.take(5) == [1, 3, 5, 7, 9] end test "repeatedly/1" do stream = Stream.repeatedly(fn -> 1 end) assert Enum.take(stream, 5) == [1, 1, 1, 1, 1] stream = Stream.repeatedly(&:rand.uniform/0) [r1, r2] = Enum.take(stream, 2) assert r1 != r2 end test "resource/3 closes on outer errors" do stream = Stream.resource( fn -> 1 end, fn 2 -> throw(:error) acc -> {[acc], acc + 1} end, fn 2 -> Process.put(:stream_resource, true) end ) Process.put(:stream_resource, false) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_resource) end test "resource/3 is zippable" do transform_fun = fn 10 -> {:halt, 10} acc -> {[acc], acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) list = Enum.to_list(stream) Process.put(:stream_resource, false) assert Enum.zip(list, list) == Enum.zip(stream, stream) assert Process.get(:stream_resource) end test "resource/3 halts with inner list" do transform_fun = fn acc -> {[acc, acc + 1, acc + 2], acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) Process.put(:stream_resource, false) assert Enum.take(stream, 5) == [1, 2, 3, 2, 3] assert Process.get(:stream_resource) end test "resource/3 closes on errors with inner list" do transform_fun = fn acc -> {[acc, acc + 1, acc + 2], acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) Process.put(:stream_resource, false) stream = Stream.map(stream, fn x -> if x > 2, do: throw(:error), else: x end) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_resource) end test "resource/3 is zippable with inner list" do transform_fun = fn 10 -> {:halt, 10} acc -> {[acc, acc + 1, acc + 2], acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) list = Enum.to_list(stream) Process.put(:stream_resource, false) assert Enum.zip(list, list) == Enum.zip(stream, stream) assert Process.get(:stream_resource) end test "resource/3 halts with inner enum" do transform_fun = fn acc -> {acc..(acc + 2), acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) Process.put(:stream_resource, false) assert Enum.take(stream, 5) == [1, 2, 3, 2, 3] assert Process.get(:stream_resource) end test "resource/3 closes on errors with inner enum" do transform_fun = fn acc -> {acc..(acc + 2), acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) Process.put(:stream_resource, false) stream = Stream.map(stream, fn x -> if x > 2, do: throw(:error), else: x end) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_resource) end test "resource/3 is zippable with inner enum" do transform_fun = fn 10 -> {:halt, 10} acc -> {acc..(acc + 2), acc + 1} end after_fun = fn _ -> Process.put(:stream_resource, true) end stream = Stream.resource(fn -> 1 end, transform_fun, after_fun) list = Enum.to_list(stream) Process.put(:stream_resource, false) assert Enum.zip(list, list) == Enum.zip(stream, stream) assert Process.get(:stream_resource) end test "transform/4" do transform_fun = fn x, acc -> {[x, x + acc], x} end after_fun = fn 10 -> Process.put(:stream_transform, true) end stream = Stream.transform(1..10, fn -> 0 end, transform_fun, after_fun) Process.put(:stream_transform, false) assert Enum.to_list(stream) == [1, 1, 2, 3, 3, 5, 4, 7, 5, 9, 6, 11, 7, 13, 8, 15, 9, 17, 10, 19] assert Process.get(:stream_transform) end test "transform/4 with early halt" do after_fun = fn nil -> Process.put(:stream_transform, true) end stream = fn -> throw(:error) end |> Stream.repeatedly() |> Stream.transform(fn -> nil end, &{[&1, &2], &1}, after_fun) Process.put(:stream_transform, false) assert {:halted, nil} = Enumerable.reduce(stream, {:halt, nil}, fn _, _ -> throw(:error) end) assert Process.get(:stream_transform) end test "transform/4 with early suspend" do after_fun = fn nil -> Process.put(:stream_transform, true) end stream = fn -> throw(:error) end |> Stream.repeatedly() |> Stream.transform(fn -> nil end, &{[&1, &2], &1}, after_fun) refute Process.get(:stream_transform) assert {:suspended, nil, _} = Enumerable.reduce(stream, {:suspend, nil}, fn _, _ -> throw(:error) end) end test "transform/4 closes on outer errors" do transform_fun = fn 3, _ -> throw(:error) x, acc -> {[x + acc], x} end after_fun = fn 2 -> Process.put(:stream_transform, true) end stream = Stream.transform(1..10, fn -> 0 end, transform_fun, after_fun) Process.put(:stream_transform, false) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_transform) end test "transform/4 closes on nested errors" do transform_fun = fn 3, _ -> throw(:error) x, acc -> {[x + acc], x} end after_fun = fn _ -> Process.put(:stream_transform_inner, true) end outer_after_fun = fn 0 -> Process.put(:stream_transform_outer, true) end stream = 1..10 |> Stream.transform(fn -> 0 end, transform_fun, after_fun) |> Stream.transform(fn -> 0 end, fn x, acc -> {[x], acc} end, outer_after_fun) Process.put(:stream_transform_inner, false) Process.put(:stream_transform_outer, false) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_transform_inner) assert Process.get(:stream_transform_outer) end test "transform/4 is zippable" do transform_fun = fn 10, acc -> {:halt, acc} x, acc -> {[x + acc], x} end after_fun = fn 9 -> Process.put(:stream_transform, true) end stream = Stream.transform(1..20, fn -> 0 end, transform_fun, after_fun) list = Enum.to_list(stream) Process.put(:stream_transform, false) assert Enum.zip(list, list) == Enum.zip(stream, stream) assert Process.get(:stream_transform) end test "transform/4 halts with inner list" do transform_fun = fn x, acc -> {[x, x + 1, x + 2], acc} end after_fun = fn :acc -> Process.put(:stream_transform, true) end stream = Stream.transform(1..10, fn -> :acc end, transform_fun, after_fun) Process.put(:stream_transform, false) assert Enum.take(stream, 5) == [1, 2, 3, 2, 3] assert Process.get(:stream_transform) end test "transform/4 closes on errors with inner list" do transform_fun = fn x, acc -> {[x, x + 1, x + 2], acc} end after_fun = fn :acc -> Process.put(:stream_transform, true) end stream = Stream.transform(1..10, fn -> :acc end, transform_fun, after_fun) Process.put(:stream_transform, false) stream = Stream.map(stream, fn x -> if x > 2, do: throw(:error), else: x end) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_transform) end test "transform/4 is zippable with inner list" do transform_fun = fn 10, acc -> {:halt, acc} x, acc -> {[x, x + 1, x + 2], acc} end after_fun = fn :inner -> Process.put(:stream_transform, true) end stream = Stream.transform(1..20, fn -> :inner end, transform_fun, after_fun) list = Enum.to_list(stream) Process.put(:stream_transform, false) assert Enum.zip(list, list) == Enum.zip(stream, stream) assert Process.get(:stream_transform) end test "transform/4 halts with inner enum" do transform_fun = fn x, acc -> {x..(x + 2), acc} end after_fun = fn :acc -> Process.put(:stream_transform, true) end stream = Stream.transform(1..10, fn -> :acc end, transform_fun, after_fun) Process.put(:stream_transform, false) assert Enum.take(stream, 5) == [1, 2, 3, 2, 3] assert Process.get(:stream_transform) end test "transform/4 closes on errors with inner enum" do transform_fun = fn x, acc -> {x..(x + 2), acc} end after_fun = fn :acc -> Process.put(:stream_transform, true) end stream = Stream.transform(1..10, fn -> :acc end, transform_fun, after_fun) Process.put(:stream_transform, false) stream = Stream.map(stream, fn x -> if x > 2, do: throw(:error), else: x end) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_transform) end test "transform/4 is zippable with inner enum" do transform_fun = fn 10, acc -> {:halt, acc} x, acc -> {x..(x + 2), acc} end after_fun = fn :inner -> Process.put(:stream_transform, true) end stream = Stream.transform(1..20, fn -> :inner end, transform_fun, after_fun) list = Enum.to_list(stream) Process.put(:stream_transform, false) assert Enum.zip(list, list) == Enum.zip(stream, stream) assert Process.get(:stream_transform) end test "scan/2" do stream = Stream.scan(1..5, &(&1 + &2)) assert lazy?(stream) assert Enum.to_list(stream) == [1, 3, 6, 10, 15] assert Stream.scan([], &(&1 + &2)) |> Enum.to_list() == [] end test "scan/3" do stream = Stream.scan(1..5, 0, &(&1 + &2)) assert lazy?(stream) assert Enum.to_list(stream) == [1, 3, 6, 10, 15] assert Stream.scan([], 0, &(&1 + &2)) |> Enum.to_list() == [] end test "take/2" do stream = Stream.take(1..1000, 5) assert lazy?(stream) assert Enum.to_list(stream) == [1, 2, 3, 4, 5] assert Enum.to_list(Stream.take(1..1000, 0)) == [] assert Enum.to_list(Stream.take([], 5)) == [] assert Enum.to_list(Stream.take(1..3, 5)) == [1, 2, 3] nats = Stream.iterate(1, &(&1 + 1)) assert Enum.to_list(Stream.take(nats, 5)) == [1, 2, 3, 4, 5] stream = Stream.drop(1..100, 5) assert Stream.take(stream, 5) |> Enum.to_list() == [6, 7, 8, 9, 10] stream = 1..5 |> Stream.take(10) |> Stream.drop(15) assert {[], []} = Enum.split(stream, 5) stream = 1..20 |> Stream.take(10 + 5) |> Stream.drop(4) assert Enum.to_list(stream) == [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] end test "take/2 does not consume next element on halt" do assert [false, true] |> Stream.each(&(&1 && raise("oops"))) |> Stream.take(1) |> Stream.take_while(& &1) |> Enum.to_list() == [] end test "take/2 does not consume next element on suspend" do assert [false, true] |> Stream.each(&(&1 && raise("oops"))) |> Stream.take(1) |> Stream.flat_map(&[&1]) |> Enum.to_list() == [false] end test "take/2 with negative count" do Process.put(:stream_each, []) stream = Stream.take(1..100, -5) assert lazy?(stream) stream = Stream.each(stream, &Process.put(:stream_each, [&1 | Process.get(:stream_each)])) assert Enum.to_list(stream) == [96, 97, 98, 99, 100] assert Process.get(:stream_each) == [100, 99, 98, 97, 96] end test "take/2 is zippable" do stream = Stream.take(1..1000, 5) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end test "take_every/2" do assert 1..10 |> Stream.take_every(2) |> Enum.to_list() == [1, 3, 5, 7, 9] assert 1..10 |> Stream.take_every(3) |> Enum.to_list() == [1, 4, 7, 10] assert 1..10 |> Stream.drop(2) |> Stream.take_every(2) |> Stream.drop(1) |> Enum.to_list() == [5, 7, 9] assert 1..10 |> Stream.take_every(0) |> Enum.to_list() == [] assert [] |> Stream.take_every(10) |> Enum.to_list() == [] end test "take_every/2 without non-negative integer" do assert_raise FunctionClauseError, fn -> Stream.take_every(1..10, -1) end assert_raise FunctionClauseError, fn -> Stream.take_every(1..10, 3.33) end end test "take_while/2" do stream = Stream.take_while(1..1000, &(&1 <= 5)) assert lazy?(stream) assert Enum.to_list(stream) == [1, 2, 3, 4, 5] assert Enum.to_list(Stream.take_while(1..1000, &(&1 <= 0))) == [] assert Enum.to_list(Stream.take_while(1..3, &(&1 <= 5))) == [1, 2, 3] nats = Stream.iterate(1, &(&1 + 1)) assert Enum.to_list(Stream.take_while(nats, &(&1 <= 5))) == [1, 2, 3, 4, 5] stream = Stream.drop(1..100, 5) assert Stream.take_while(stream, &(&1 < 11)) |> Enum.to_list() == [6, 7, 8, 9, 10] end test "timer/1" do stream = Stream.timer(10) now = :os.timestamp() assert Enum.to_list(stream) == [0] # We check for >= 5000 (us) instead of >= 10000 (us) # because the resolution on Windows system is not high # enough and we would get a difference of 9000 from # time to time. So a value halfway is good enough. assert :timer.now_diff(:os.timestamp(), now) >= 5000 end test "unfold/2" do stream = Stream.unfold(10, fn x -> if x > 0, do: {x, x - 1} end) assert Enum.take(stream, 5) == [10, 9, 8, 7, 6] stream = Stream.unfold(5, fn x -> if x > 0, do: {x, x - 1} end) assert Enum.to_list(stream) == [5, 4, 3, 2, 1] end test "unfold/2 only calculates values if needed" do stream = Stream.unfold(1, fn x -> if x > 0, do: {x, x - 1}, else: throw(:boom) end) assert Enum.take(stream, 1) == [1] stream = Stream.unfold(5, fn x -> if x > 0, do: {x, x - 1} end) assert Enum.to_list(Stream.take(stream, 2)) == [5, 4] end test "unfold/2 is zippable" do stream = Stream.unfold(10, fn x -> if x > 0, do: {x, x - 1} end) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end test "uniq/1 & uniq/2" do assert Stream.uniq([1, 2, 3, 2, 1]) |> Enum.to_list() == [1, 2, 3] end test "uniq_by/2" do assert Stream.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end) |> Enum.to_list() == [{1, :x}, {2, :y}] assert Stream.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end) |> Enum.to_list() == [a: {:tea, 2}, c: {:coffee, 1}] end test "zip/2" do concat = Stream.concat(1..3, 4..6) cycle = Stream.cycle([:a, :b, :c]) assert Stream.zip(concat, cycle) |> Enum.to_list() == [{1, :a}, {2, :b}, {3, :c}, {4, :a}, {5, :b}, {6, :c}] end test "zip/1" do concat = Stream.concat(1..3, 4..6) cycle = Stream.cycle([:a, :b, :c]) assert Stream.zip([concat, cycle]) |> Enum.to_list() == [{1, :a}, {2, :b}, {3, :c}, {4, :a}, {5, :b}, {6, :c}] assert Stream.chunk_every([0, 1, 2, 3], 2) |> Stream.zip() |> Enum.to_list() == [{0, 2}, {1, 3}] stream = %HaltAcc{acc: 1..3} assert Stream.zip([1..3, stream]) |> Enum.to_list() == [{1, 1}, {2, 2}, {3, 3}] range_cycle = Stream.cycle(1..2) assert Stream.zip([1..3, range_cycle]) |> Enum.to_list() == [{1, 1}, {2, 2}, {3, 1}] end test "zip/1 does not leave streams suspended" do stream = Stream.resource(fn -> 1 end, fn acc -> {[acc], acc + 1} end, fn _ -> Process.put(:stream_zip, true) end) Process.put(:stream_zip, false) assert Stream.zip([[:a, :b, :c], stream]) |> Enum.to_list() == [a: 1, b: 2, c: 3] assert Process.get(:stream_zip) Process.put(:stream_zip, false) assert Stream.zip([stream, [:a, :b, :c]]) |> Enum.to_list() == [{1, :a}, {2, :b}, {3, :c}] assert Process.get(:stream_zip) end test "zip/1 does not leave streams suspended on halt" do stream = Stream.resource(fn -> 1 end, fn acc -> {[acc], acc + 1} end, fn _ -> Process.put(:stream_zip, :done) end) assert Stream.zip([[:a, :b, :c, :d, :e], stream]) |> Enum.take(3) == [a: 1, b: 2, c: 3] assert Process.get(:stream_zip) == :done end test "zip/1 closes on inner error" do stream = Stream.into([1, 2, 3], %Pdict{}) stream = Stream.zip([stream, Stream.map([:a, :b, :c], fn _ -> throw(:error) end)]) Process.put(:stream_done, false) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_done) end test "zip/1 closes on outer error" do stream = Stream.zip([Stream.into([1, 2, 3], %Pdict{}), [:a, :b, :c]]) |> Stream.map(fn _ -> throw(:error) end) Process.put(:stream_done, false) assert catch_throw(Enum.to_list(stream)) == :error assert Process.get(:stream_done) end test "with_index/2" do stream = Stream.with_index([1, 2, 3]) assert lazy?(stream) assert Enum.to_list(stream) == [{1, 0}, {2, 1}, {3, 2}] stream = Stream.with_index([1, 2, 3], 10) assert Enum.to_list(stream) == [{1, 10}, {2, 11}, {3, 12}] nats = Stream.iterate(1, &(&1 + 1)) assert Stream.with_index(nats) |> Enum.take(3) == [{1, 0}, {2, 1}, {3, 2}] end test "intersperse/2 is lazy" do assert lazy?(Stream.intersperse([], 0)) end test "intersperse/2 on an empty list" do assert Enum.to_list(Stream.intersperse([], 0)) == [] end test "intersperse/2 on a single element list" do assert Enum.to_list(Stream.intersperse([1], 0)) == [1] end test "intersperse/2 on a multiple elements list" do assert Enum.to_list(Stream.intersperse(1..3, 0)) == [1, 0, 2, 0, 3] end test "intersperse/2 is zippable" do stream = Stream.intersperse(1..10, 0) list = Enum.to_list(stream) assert Enum.zip(list, list) == Enum.zip(stream, stream) end defp lazy?(stream) do match?(%Stream{}, stream) or is_function(stream, 2) end defp inbox_stream({:suspend, acc}, f) do {:suspended, acc, &inbox_stream(&1, f)} end defp inbox_stream({:halt, acc}, _f) do {:halted, acc} end defp inbox_stream({:cont, acc}, f) do receive do {:stream, item} -> inbox_stream(f.(item, acc), f) end end end
31.5
97
0.566042
0306f636da20266c17626875d3ad78a16a2836a2
4,805
ex
Elixir
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__job.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__job.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__job.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.MachineLearning.V1.Model.GoogleCloudMlV1_Job do @moduledoc """ Represents a training or prediction job. ## Attributes * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. When the job was created. * `endTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. When the job processing was completed. * `errorMessage` (*type:* `String.t`, *default:* `nil`) - Output only. The details of a failure or a cancellation. * `etag` (*type:* `String.t`, *default:* `nil`) - `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a job from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform job updates in order to avoid race conditions: An `etag` is returned in the response to `GetJob`, and systems are expected to put that etag in the request to `UpdateJob` to ensure that their change will be applied to the same version of the job. * `jobId` (*type:* `String.t`, *default:* `nil`) - Required. The user-specified id of the job. * `labels` (*type:* `map()`, *default:* `nil`) - Optional. One or more labels that you can add, to organize your jobs. Each label is a key-value pair, where both the key and the value are arbitrary strings that you supply. For more information, see the documentation on using labels. * `predictionInput` (*type:* `GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_PredictionInput.t`, *default:* `nil`) - Input parameters to create a prediction job. * `predictionOutput` (*type:* `GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_PredictionOutput.t`, *default:* `nil`) - The current prediction job result. * `startTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. When the job processing was started. * `state` (*type:* `String.t`, *default:* `nil`) - Output only. The detailed state of a job. * `trainingInput` (*type:* `GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_TrainingInput.t`, *default:* `nil`) - Input parameters to create a training job. * `trainingOutput` (*type:* `GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_TrainingOutput.t`, *default:* `nil`) - The current training job result. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :createTime => DateTime.t() | nil, :endTime => DateTime.t() | nil, :errorMessage => String.t() | nil, :etag => String.t() | nil, :jobId => String.t() | nil, :labels => map() | nil, :predictionInput => GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_PredictionInput.t() | nil, :predictionOutput => GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_PredictionOutput.t() | nil, :startTime => DateTime.t() | nil, :state => String.t() | nil, :trainingInput => GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_TrainingInput.t() | nil, :trainingOutput => GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_TrainingOutput.t() | nil } field(:createTime, as: DateTime) field(:endTime, as: DateTime) field(:errorMessage) field(:etag) field(:jobId) field(:labels, type: :map) field(:predictionInput, as: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_PredictionInput) field(:predictionOutput, as: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_PredictionOutput) field(:startTime, as: DateTime) field(:state) field(:trainingInput, as: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_TrainingInput) field(:trainingOutput, as: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_TrainingOutput) end defimpl Poison.Decoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Job do def decode(value, options) do GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Job.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Job do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
55.872093
536
0.714048
0306f7fa07449f279330e0f85b69c6e04e617912
36,047
ex
Elixir
lib/phoenix_live_view/engine.ex
whitepaperclip/phoenix_live_view
750ad38fce23ae09aa80fbaea9bc696bc6645f22
[ "MIT" ]
null
null
null
lib/phoenix_live_view/engine.ex
whitepaperclip/phoenix_live_view
750ad38fce23ae09aa80fbaea9bc696bc6645f22
[ "MIT" ]
null
null
null
lib/phoenix_live_view/engine.ex
whitepaperclip/phoenix_live_view
750ad38fce23ae09aa80fbaea9bc696bc6645f22
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.Component do @moduledoc """ The struct returned by components in .heex templates. This component is never meant to be output directly into the template. It should always be handled by the diffing algorithm. """ defstruct [:id, :component, :assigns] @type t :: %__MODULE__{ id: binary(), component: module(), assigns: map() } defimpl Phoenix.HTML.Safe do def to_iodata(%{id: id, component: component}) do raise ArgumentError, """ cannot convert component #{inspect(component)} with id #{inspect(id)} to HTML. A component must always be returned directly as part of a LiveView template. For example, this is not allowed: <%= content_tag :div do %> <.live_component module={SomeComponent} id="myid" /> <% end %> That's because the component is inside `content_tag`. However, this works: <div> <.live_component module={SomeComponent} id="myid" /> </div> Components are also allowed inside Elixir's special forms, such as `if`, `for`, `case`, and friends. <%= for item <- items do %> <.live_component module={SomeComponent} id={item} /> <% end %> However, using other module functions such as `Enum`, will not work: <%= Enum.map(items, fn item -> %> <.live_component module={SomeComponent} id={item} /> <% end %> """ end end end defmodule Phoenix.LiveView.Comprehension do @moduledoc """ The struct returned by for-comprehensions in .heex templates. See a description about its fields and use cases in `Phoenix.LiveView.Engine` docs. """ defstruct [:static, :dynamics, :fingerprint] @type t :: %__MODULE__{ static: [String.t()], dynamics: [ [ iodata() | Phoenix.LiveView.Rendered.t() | Phoenix.LiveView.Comprehension.t() | Phoenix.LiveView.Component.t() ] ], fingerprint: integer() } defimpl Phoenix.HTML.Safe do def to_iodata(%Phoenix.LiveView.Comprehension{static: static, dynamics: dynamics}) do for dynamic <- dynamics, do: to_iodata(static, dynamic) end defp to_iodata([static_head | static_tail], [%_{} = struct | dynamic_tail]) do dynamic_head = Phoenix.HTML.Safe.to_iodata(struct) [static_head, dynamic_head | to_iodata(static_tail, dynamic_tail)] end defp to_iodata([static_head | static_tail], [dynamic_head | dynamic_tail]) do [static_head, dynamic_head | to_iodata(static_tail, dynamic_tail)] end defp to_iodata([static_head], []) do [static_head] end end end defmodule Phoenix.LiveView.Rendered do @moduledoc """ The struct returned by .heex templates. See a description about its fields and use cases in `Phoenix.LiveView.Engine` docs. """ defstruct [:static, :dynamic, :fingerprint, :root] @type t :: %__MODULE__{ static: [String.t()], dynamic: (boolean() -> [ nil | iodata() | Phoenix.LiveView.Rendered.t() | Phoenix.LiveView.Comprehension.t() | Phoenix.LiveView.Component.t() ]), fingerprint: integer(), root: nil | true | false } defimpl Phoenix.HTML.Safe do def to_iodata(%Phoenix.LiveView.Rendered{static: static, dynamic: dynamic}) do to_iodata(static, dynamic.(false), []) end def to_iodata(%_{} = struct) do Phoenix.HTML.Safe.to_iodata(struct) end def to_iodata(nil) do raise "cannot convert .heex/.leex template with change tracking to iodata" end def to_iodata(other) do other end defp to_iodata([static_head | static_tail], [dynamic_head | dynamic_tail], acc) do to_iodata(static_tail, dynamic_tail, [to_iodata(dynamic_head), static_head | acc]) end defp to_iodata([static_head], [], acc) do Enum.reverse([static_head | acc]) end end end defmodule Phoenix.LiveView.Engine do @moduledoc ~S""" An `EEx` template engine that tracks changes. This is often used by `Phoenix.LiveView.HTMLEngine` which also adds HTML validation. In the documentation below, we will explain how it works internally. For user-facing documentation, see `Phoenix.LiveView`. ## Phoenix.LiveView.Rendered Whenever you render a live template, it returns a `Phoenix.LiveView.Rendered` structure. This structure has three fields: `:static`, `:dynamic` and `:fingerprint`. The `:static` field is a list of literal strings. This allows the Elixir compiler to optimize this list and avoid allocating its strings on every render. The `:dynamic` field contains a function that takes a boolean argument (see "Tracking changes" below), and returns a list of dynamic content. Each element in the list is either one of: 1. iodata - which is the dynamic content 2. nil - the dynamic content did not change 3. another `Phoenix.LiveView.Rendered` struct, see "Nesting and fingerprinting" below 4. a `Phoenix.LiveView.Comprehension` struct, see "Comprehensions" below 5. a `Phoenix.LiveView.Component` struct, see "Component" below When you render a live template, you can convert the rendered structure to iodata by alternating the static and dynamic fields, always starting with a static entry followed by a dynamic entry. The last entry will always be static too. So the following structure: %Phoenix.LiveView.Rendered{ static: ["foo", "bar", "baz"], dynamic: fn track_changes? -> ["left", "right"] end } Results in the following content to be sent over the wire as iodata: ["foo", "left", "bar", "right", "baz"] This is also what calling `Phoenix.HTML.Safe.to_iodata/1` with a `Phoenix.LiveView.Rendered` structure returns. Of course, the benefit of live templates is exactly that you do not need to send both static and dynamic segments every time. So let's talk about tracking changes. ## Tracking changes By default, a live template does not track changes. Change tracking can be enabled by including a changed map in the assigns with the key `__changed__` and passing `true` to the dynamic parts. The map should contain the name of any changed field as key and the boolean true as value. If a field is not listed in `__changed__`, then it is always considered unchanged. If a field is unchanged and live believes a dynamic expression no longer needs to be computed, its value in the `dynamic` list will be `nil`. This information can be leveraged to avoid sending data to the client. ## Nesting and fingerprinting `Phoenix.LiveView` also tracks changes across live templates. Therefore, if your view has this: <%= render "form.html", assigns %> Phoenix will be able to track what is static and dynamic across templates, as well as what changed. A rendered nested `live` template will appear in the `dynamic` list as another `Phoenix.LiveView.Rendered` structure, which must be handled recursively. However, because the rendering of live templates can be dynamic in itself, it is important to distinguish which live template was rendered. For example, imagine this code: <%= if something?, do: render("one.html", assigns), else: render("other.html", assigns) %> To solve this, all `Phoenix.LiveView.Rendered` structs also contain a fingerprint field that uniquely identifies it. If the fingerprints are equal, you have the same template, and therefore it is possible to only transmit its changes. ## Comprehensions Another optimization done by live templates is to track comprehensions. If your code has this: <%= for point <- @points do %> x: <%= point.x %> y: <%= point.y %> <% end %> Instead of rendering all points with both static and dynamic parts, it returns a `Phoenix.LiveView.Comprehension` struct with the static parts, that are shared across all points, and a list of dynamics to be interpolated inside the static parts. If `@points` is a list with `%{x: 1, y: 2}` and `%{x: 3, y: 4}`, the above expression would return: %Phoenix.LiveView.Comprehension{ static: ["\n x: ", "\n y: ", "\n"], dynamics: [ ["1", "2"], ["3", "4"] ] } This allows live templates to drastically optimize the data sent by comprehensions, as the static parts are emitted only once, regardless of the number of items. The list of dynamics is always a list of iodatas or components, as we don't perform change tracking inside the comprehensions themselves. Similarly, comprehensions do not have fingerprints because they are only optimized at the root, so conditional evaluation, as the one seen in rendering, is not possible. The only possible outcome for a dynamic field that returns a comprehension is `nil`. ## Components Live also supports stateful components defined with `Phoenix.LiveComponent`. Since they are stateful, they are always handled lazily by the diff algorithm. """ @behaviour Phoenix.Template.Engine # TODO: Use @impl true instead of @doc false when we require Elixir v1.12 @doc false def compile(path, _name) do trim = Application.get_env(:phoenix, :trim_on_html_eex_engine, true) EEx.compile_file(path, engine: __MODULE__, line: 1, trim: trim) end @behaviour EEx.Engine @assigns_var Macro.var(:assigns, nil) @doc false def init(_opts) do # Phoenix.LiveView.HTMLEngine calls this engine in a non-linear order # to evaluate slots, which can lead to variable conflicts. Therefore we # use a counter to ensure all variable names are unique. %{ static: [], dynamic: [], counter: :counters.new(1, []) } end @doc false def handle_begin(state) do %{state | static: [], dynamic: []} end @doc false def handle_end(state) do %{static: static, dynamic: dynamic} = state safe = {:safe, Enum.reverse(static)} {:__block__, [live_rendered: true], Enum.reverse([safe | dynamic])} end @doc false def handle_body(state, opts \\ []) do {:ok, rendered} = to_rendered_struct(handle_end(state), {:untainted, %{}}, %{}, opts) quote do require Phoenix.LiveView.Engine unquote(rendered) end end @doc false def handle_text(state, text) do handle_text(state, [], text) end @doc false def handle_text(state, _meta, text) do %{static: static} = state %{state | static: [text | static]} end @doc false def handle_expr(state, "=", ast) do %{static: static, dynamic: dynamic, counter: counter} = state i = :counters.get(counter, 1) var = Macro.var(:"v#{i}", __MODULE__) ast = quote do: unquote(var) = unquote(__MODULE__).to_safe(unquote(ast)) :counters.add(counter, 1, 1) %{state | dynamic: [ast | dynamic], static: [var | static]} end def handle_expr(state, "", ast) do %{dynamic: dynamic} = state %{state | dynamic: [ast | dynamic]} end def handle_expr(state, marker, ast) do EEx.Engine.handle_expr(state, marker, ast) end ## Entry point for rendered structs defp to_rendered_struct(expr, vars, assigns, opts) do with {:__block__, [live_rendered: true], entries} <- expr, {dynamic, [{:safe, static}]} <- Enum.split(entries, -1) do {block, static, dynamic, fingerprint} = analyze_static_and_dynamic(static, dynamic, vars, assigns) changed = quote generated: true do case unquote(@assigns_var) do %{__changed__: changed} when track_changes? -> changed _ -> nil end end {:ok, quote do dynamic = fn track_changes? -> changed = unquote(changed) unquote({:__block__, [], block}) unquote(dynamic) end %Phoenix.LiveView.Rendered{ static: unquote(static), dynamic: dynamic, fingerprint: unquote(fingerprint), root: unquote(opts[:root]) } end} else _ -> :error end end defmacrop to_safe_match(var, ast) do quote do {:=, [], [ {_, _, __MODULE__} = unquote(var), {{:., _, [__MODULE__, :to_safe]}, _, [unquote(ast)]} ]} end end defp analyze_static_and_dynamic(static, dynamic, initial_vars, assigns) do {block, _} = Enum.map_reduce(dynamic, initial_vars, fn to_safe_match(var, ast), vars -> vars = set_vars(initial_vars, vars) {ast, keys, vars} = analyze_and_return_tainted_keys(ast, vars, assigns) live_struct = to_live_struct(ast, vars, assigns) {to_conditional_var(keys, var, live_struct), vars} ast, vars -> vars = set_vars(initial_vars, vars) {ast, vars, _} = analyze(ast, vars, assigns) {ast, vars} end) {static, dynamic} = bins_and_vars(static) {block, static, dynamic, fingerprint(block, static)} end ## Optimize possible expressions into live structs (rendered / comprehensions) defp to_live_struct({:for, _, [_ | _]} = expr, vars, _assigns) do with {:for, meta, [_ | _] = args} <- expr, {filters, [[do: {:__block__, _, block}]]} <- Enum.split(args, -1), {dynamic, [{:safe, static}]} <- Enum.split(block, -1) do {block, static, dynamic, fingerprint} = analyze_static_and_dynamic(static, dynamic, taint_vars(vars), %{}) for = {:for, meta, filters ++ [[do: {:__block__, [], block ++ [dynamic]}]]} quote do %Phoenix.LiveView.Comprehension{ static: unquote(static), dynamics: unquote(for), fingerprint: unquote(fingerprint) } end else _ -> to_safe(expr, true) end end defp to_live_struct({left, meta, [_ | _] = args}, vars, assigns) do call = extract_call(left) args = if classify_taint(call, args) in [:live, :render] do {args, [opts]} = Enum.split(args, -1) # The reason we can safely ignore assigns here is because # each branch in the live/render constructs are their own # rendered struct and, if the rendered has a new fingerpint, # then change tracking is fully disabled. # # For example, take this code: # # <%= if @foo do %> # <%= @bar %> # <% else %> # <%= @baz %> # <% end %> # # In theory, @bar and @baz should be recomputed whenever # @foo changes, because changing @foo may require a value # that was not available on the page to show. However, # given the branches have different fingerprints, the # diff mechanism takes care of forcing all assigns to # be rendered without us needing to handle it here. # # Similarly, when expanding the blocks, we can remove all # untainting, as the parent untainting is already causing # the block to be rendered and then we can proceed with # its own tainting. {args, vars, _} = analyze_list(args, vars, assigns, []) opts = for {key, value} <- opts do {key, maybe_block_to_rendered(value, vars)} end args ++ [opts] else args end args = case {call, args} do # If we have a component, we provide change tracking to individual keys. {:component, [fun, expr]} -> [fun, to_component_tracking(fun, expr, [], vars)] {_, _} -> args end to_safe({left, meta, args}, true) end defp to_live_struct(expr, _vars, _assigns) do to_safe(expr, true) end defp extract_call({:., _, [{:__aliases__, _, [:Phoenix, :LiveView, :Helpers]}, func]}), do: func defp extract_call(call), do: call defp maybe_block_to_rendered([{:->, _, _} | _] = blocks, vars) do for {:->, meta, [args, block]} <- blocks do {args, vars, assigns} = analyze_list(args, vars, %{}, []) case to_rendered_struct(block, untaint_vars(vars), assigns, []) do {:ok, rendered} -> {:->, meta, [args, rendered]} :error -> {:->, meta, [args, block]} end end end defp maybe_block_to_rendered(block, vars) do case to_rendered_struct(block, untaint_vars(vars), %{}, []) do {:ok, rendered} -> rendered :error -> block end end defp to_conditional_var(:all, var, live_struct) do quote do: unquote(var) = unquote(live_struct) end defp to_conditional_var(keys, var, live_struct) when keys == %{} do quote generated: true do unquote(var) = case changed do %{} -> nil _ -> unquote(live_struct) end end end defp to_conditional_var(keys, var, live_struct) do quote do unquote(var) = case unquote(changed_assigns(keys)) do true -> unquote(live_struct) false -> nil end end end defp changed_assigns(assigns) do checks = for {key, _} <- assigns, not nested_and_parent_is_checked?(key, assigns) do case key do [assign] -> quote do unquote(__MODULE__).changed_assign?(changed, unquote(assign)) end [assign | tail] -> quote do unquote(__MODULE__).nested_changed_assign?( unquote(@assigns_var), changed, unquote(assign), unquote(tail) ) end end end Enum.reduce(checks, &{:or, [], [&1, &2]}) end # If we are accessing @foo.bar.baz but in the same place we also pass # @foo.bar or @foo, we don't need to check for @foo.bar.baz. # If there is no nesting, then we are not nesting. defp nested_and_parent_is_checked?([_], _assigns), do: false # Otherwise, we convert @foo.bar.baz into [:baz, :bar, :foo], discard :baz, # and then check if [:foo, :bar] and then [:foo] is in it. defp nested_and_parent_is_checked?(keys, assigns), do: parent_is_checked?(tl(Enum.reverse(keys)), assigns) defp parent_is_checked?([], _assigns), do: false defp parent_is_checked?(rest, assigns), do: Map.has_key?(assigns, Enum.reverse(rest)) or parent_is_checked?(tl(rest), assigns) ## Component keys change tracking defp to_component_tracking(fun, expr, extra, vars) do # Separate static and dynamic parts {static, dynamic} = case expr do {{:., _, [{:__aliases__, _, [:Map]}, :merge]}, _, [dynamic, {:%{}, _, static}]} -> {static, dynamic} {:%{}, _, static} -> {static, %{}} static -> {static, %{}} end # And now validate the static bits. If they are not valid, # treat the whole thing as dynamic. {static, dynamic} = if Keyword.keyword?(static) do {static, dynamic} else {[], expr} end static_extra = extra ++ static static_changed = if static_extra != [] do keys = for {key, value} <- static_extra, # We pass empty assigns because if this code is rendered, # it means that upstream assigns were change tracked. {_, keys, _} = analyze_and_return_tainted_keys(value, vars, %{}), # If keys are empty, it is never changed. keys != %{}, do: {key, to_component_keys(keys)} quote do unquote(__MODULE__).to_component_static(unquote(keys), unquote(@assigns_var), changed) end else Macro.escape(%{}) end static = slots_to_rendered(static, vars) cond do # We can't infer anything, so return the expression as is. static_extra == [] and dynamic == %{} -> expr # Live components do not need to compute the changed because they track their own changed. match?({:&, _, [{:/, _, [{:live_component, _, _}, 1]}]}, fun) -> if dynamic == %{} do quote do: %{unquote_splicing(static)} else quote do: Map.merge(unquote(dynamic), %{unquote_splicing(static)}) end # We were actually able to find some static bits, but no dynamic. # Embed the static parts alongside the computed changed. dynamic == %{} -> quote do %{unquote_splicing([__changed__: static_changed] ++ static)} end # Merge both static and dynamic. true -> {_, keys, _} = analyze_and_return_tainted_keys(dynamic, vars, %{}) quote do unquote(__MODULE__).to_component_dynamic( %{unquote_splicing(static)}, unquote(dynamic), unquote(static_changed), unquote(to_component_keys(keys)), unquote(@assigns_var), changed ) end end end defp to_component_keys(:all), do: :all defp to_component_keys(map), do: Map.keys(map) @doc false def to_component_static(_keys, _assigns, nil) do nil end def to_component_static(keys, assigns, changed) do for {assign, entries} <- keys, changed = component_changed(entries, assigns, changed), into: %{}, do: {assign, changed} end @doc false def to_component_dynamic(static, dynamic, _static_changed, _keys, _assigns, nil) do merge_dynamic_static_changed(dynamic, static, nil) end def to_component_dynamic(static, dynamic, static_changed, keys, assigns, changed) do component_changed = if component_changed(keys, assigns, changed) do Enum.reduce(dynamic, static_changed, fn {k, _}, acc -> Map.put(acc, k, true) end) else static_changed end merge_dynamic_static_changed(dynamic, static, component_changed) end defp merge_dynamic_static_changed(dynamic, static, changed) do dynamic |> Map.merge(static) |> Map.put(:__changed__, changed) end defp component_changed(:all, _assigns, _changed), do: true defp component_changed([path], assigns, changed) do case path do [key] -> changed_assign(changed, key) [key | tail] -> nested_changed_assign(assigns, changed, key, tail) end end defp component_changed(entries, assigns, changed) do Enum.any?(entries, fn [key] -> changed_assign?(changed, key) [key | tail] -> nested_changed_assign?(assigns, changed, key, tail) end) end defp slots_to_rendered(static, vars) do Macro.postwalk(static, fn {call, meta, [name, [do: block]]} = node -> if extract_call(call) == :inner_block do {call, meta, [name, [do: maybe_block_to_rendered(block, vars)]]} else node end node -> node end) end ## Extracts binaries and variable from iodata defp bins_and_vars(acc), do: bins_and_vars(acc, [], []) defp bins_and_vars([bin1, bin2 | acc], bins, vars) when is_binary(bin1) and is_binary(bin2), do: bins_and_vars([bin1 <> bin2 | acc], bins, vars) defp bins_and_vars([bin, var | acc], bins, vars) when is_binary(bin) and is_tuple(var), do: bins_and_vars(acc, [bin | bins], [var | vars]) defp bins_and_vars([var | acc], bins, vars) when is_tuple(var), do: bins_and_vars(acc, ["" | bins], [var | vars]) defp bins_and_vars([bin], bins, vars) when is_binary(bin), do: {Enum.reverse([bin | bins]), Enum.reverse(vars)} defp bins_and_vars([], bins, vars), do: {Enum.reverse(["" | bins]), Enum.reverse(vars)} ## Assigns tracking # Here we compute if an expression should be always computed, # never computed, or some times computed based on assigns. # # If any assign is used, we store it in the assigns and use it to compute # if it should be changed or not. # # However, operations that change the lexical scope, such as imports and # defining variables, taint the analysis. Because variables can be set at # any moment in Elixir, via macros, without appearing on the left side of # `=` or in a clause, whenever we see a variable, we consider it as tainted, # regardless of its position. # # The tainting that happens from lexical scope is called weak-tainting, # because it is disabled under certain special forms. There is also # strong-tainting, which are always computed. Strong-tainting only happens # if the `assigns` variable is used. defp analyze_and_return_tainted_keys(ast, vars, assigns) do {ast, vars, assigns} = analyze(ast, vars, assigns) {tainted_assigns?, assigns} = Map.pop(assigns, __MODULE__, false) keys = if match?({:tainted, _}, vars) or tainted_assigns?, do: :all, else: assigns {ast, keys, vars} end # Expanded assign access. The non-expanded form is handled on root, # then all further traversals happen on the expanded form defp analyze_assign( {{:., _, [{:assigns, _, nil}, name]}, _, args} = expr, vars, assigns, nest ) when is_atom(name) and args in [[], nil] do {expr, vars, Map.put(assigns, [name | nest], true)} end # Nested assign defp analyze_assign({{:., dot_meta, [Access, :get]}, meta, [left, right]}, vars, assigns, nest) do {args, vars, assigns} = if Macro.quoted_literal?(right) do {left, vars, assigns} = analyze_assign(left, vars, assigns, [{:access, right} | nest]) {[left, right], vars, assigns} else {left, vars, assigns} = analyze(left, vars, assigns) {right, vars, assigns} = analyze(right, vars, assigns) {[left, right], vars, assigns} end {{{:., dot_meta, [Access, :get]}, meta, args}, vars, assigns} end defp analyze_assign({{:., dot_meta, [left, right]}, meta, args}, vars, assigns, nest) when args in [[], nil] do {left, vars, assigns} = analyze_assign(left, vars, assigns, [{:struct, right} | nest]) {{{:., dot_meta, [left, right]}, meta, []}, vars, assigns} end # Non-expanded assign defp analyze_assign({:@, meta, [{name, _, context}]}, vars, assigns, nest) when is_atom(name) and is_atom(context) do expr = {{:., meta, [@assigns_var, name]}, [no_parens: true] ++ meta, []} {expr, vars, Map.put(assigns, [name | nest], true)} end defp analyze_assign(expr, vars, assigns, _nest) do analyze(expr, vars, assigns) end # Delegates to analyze assign defp analyze({{:., _, [Access, :get]}, _, [_, _]} = expr, vars, assigns) do analyze_assign(expr, vars, assigns, []) end defp analyze({{:., _, [_, _]}, _, args} = expr, vars, assigns) when args in [[], nil] do analyze_assign(expr, vars, assigns, []) end defp analyze({:@, _, [{name, _, context}]} = expr, vars, assigns) when is_atom(name) and is_atom(context) do analyze_assign(expr, vars, assigns, []) end # Assigns is a strong-taint defp analyze({:assigns, _, nil} = expr, vars, assigns) do {expr, vars, taint_assigns(assigns)} end # Our own vars are ignored. They appear from nested do/end in EEx templates. defp analyze({_, _, __MODULE__} = expr, vars, assigns) do {expr, vars, assigns} end # Ignore underscore defp analyze({:_, _, context} = expr, vars, assigns) when is_atom(context) do {expr, vars, assigns} end # Also skip special variables defp analyze({name, _, context} = expr, vars, assigns) when name in [:__MODULE__, :__ENV__, :__STACKTRACE__, :__DIR__] and is_atom(context) do {expr, vars, assigns} end # Vars always taint unless we are in restricted mode. defp analyze({name, _, context} = expr, {:restricted, map}, assigns) when is_atom(name) and is_atom(context) do if Map.has_key?(map, {name, context}) do {expr, {:tainted, map}, assigns} else {expr, {:restricted, map}, assigns} end end defp analyze({name, _, context} = expr, {_, map}, assigns) when is_atom(name) and is_atom(context) do {expr, {:tainted, Map.put(map, {name, context}, true)}, assigns} end # Ignore binary modifiers defp analyze({:"::", meta, [left, right]}, vars, assigns) do {left, vars, assigns} = analyze(left, vars, assigns) {{:"::", meta, [left, right]}, vars, assigns} end # Classify calls defp analyze({left, meta, args}, vars, assigns) do call = extract_call(left) case classify_taint(call, args) do :special_form -> code = quote do: unquote(__MODULE__).__raise__(unquote(call), unquote(length(args))) {code, vars, assigns} :render -> {args, [opts]} = Enum.split(args, -1) {args, vars, assigns} = analyze_list(args, vars, assigns, []) {opts, vars, assigns} = analyze_with_restricted_vars(opts, vars, assigns) {{left, meta, args ++ [opts]}, vars, assigns} :none -> {left, vars, assigns} = analyze(left, vars, assigns) {args, vars, assigns} = analyze_list(args, vars, assigns, []) {{left, meta, args}, vars, assigns} # :never or :live _ -> {args, vars, assigns} = analyze_with_restricted_vars(args, vars, assigns) {{left, meta, args}, vars, assigns} end end defp analyze({left, right}, vars, assigns) do {left, vars, assigns} = analyze(left, vars, assigns) {right, vars, assigns} = analyze(right, vars, assigns) {{left, right}, vars, assigns} end defp analyze([_ | _] = list, vars, assigns) do analyze_list(list, vars, assigns, []) end defp analyze(other, vars, assigns) do {other, vars, assigns} end defp analyze_list([head | tail], vars, assigns, acc) do {head, vars, assigns} = analyze(head, vars, assigns) analyze_list(tail, vars, assigns, [head | acc]) end defp analyze_list([], vars, assigns, acc) do {Enum.reverse(acc), vars, assigns} end # vars is one of: # # * {:tainted, map} # * {:restricted, map} # * {:untainted, map} # # Seeing a variable at any moment taints it unless we are inside a # scope. For example, in case/cond/with/fn/try, the variable is only # tainted if it came from outside of the case/cond/with/fn/try. # So for those constructs we set the mode to restricted and stop # collecting vars. defp analyze_with_restricted_vars(ast, {kind, map}, assigns) do {ast, {new_kind, _}, assigns} = analyze(ast, {unless_tainted(kind, :restricted), map}, assigns) {ast, {unless_tainted(new_kind, kind), map}, assigns} end defp set_vars({kind, _}, {_, map}), do: {kind, map} defp taint_vars({_, map}), do: {:tainted, map} defp untaint_vars({_, map}), do: {:untainted, map} defp unless_tainted(:tainted, _), do: :tainted defp unless_tainted(_, kind), do: kind defp taint_assigns(assigns), do: Map.put(assigns, __MODULE__, true) ## Callbacks defp fingerprint(block, static) do <<fingerprint::8*16>> = [block | static] |> :erlang.term_to_binary() |> :erlang.md5() fingerprint end @doc false defmacro __raise__(special_form, arity) do message = "cannot invoke special form #{special_form}/#{arity} inside HEEx templates" reraise ArgumentError.exception(message), Macro.Env.stacktrace(__CALLER__) end @doc false defmacro to_safe(ast) do to_safe(ast, false) end defp to_safe(ast, bool) do to_safe(ast, line_from_expr(ast), bool) end defp line_from_expr({_, meta, _}) when is_list(meta), do: Keyword.get(meta, :line, 0) defp line_from_expr(_), do: 0 defp to_safe(literal, _line, _extra_clauses?) when is_binary(literal) or is_atom(literal) or is_number(literal) do literal |> Phoenix.HTML.Safe.to_iodata() |> IO.iodata_to_binary() end defp to_safe(literal, line, _extra_clauses?) when is_list(literal) do quote line: line, do: Phoenix.HTML.Safe.List.to_iodata(unquote(literal)) end # Calls to attributes escape is always safe defp to_safe( {{:., _, [{:__aliases__, _, [:Phoenix, :HTML]}, :attributes_escape]}, _, [_]} = safe, line, _extra_clauses? ) do quote line: line do elem(unquote(safe), 1) end end defp to_safe(expr, line, false) do quote line: line, do: unquote(__MODULE__).safe_to_iodata(unquote(expr)) end defp to_safe(expr, line, true) do quote line: line, do: unquote(__MODULE__).live_to_iodata(unquote(expr)) end @doc false def safe_to_iodata(expr) do case expr do {:safe, data} -> data bin when is_binary(bin) -> Plug.HTML.html_escape_to_iodata(bin) other -> Phoenix.HTML.Safe.to_iodata(other) end end @doc false def live_to_iodata(expr) do case expr do {:safe, data} -> data %{__struct__: Phoenix.LiveView.Rendered} = other -> other %{__struct__: Phoenix.LiveView.Component} = other -> other %{__struct__: Phoenix.LiveView.Comprehension} = other -> other bin when is_binary(bin) -> Plug.HTML.html_escape_to_iodata(bin) other -> Phoenix.HTML.Safe.to_iodata(other) end end @doc false def changed_assign?(changed, name) do case changed do %{^name => _} -> true %{} -> false nil -> true end end defp changed_assign(changed, name) do case changed do %{^name => value} -> value %{} -> false nil -> true end end @doc false def nested_changed_assign?(assigns, changed, head, tail), do: nested_changed_assign(assigns, changed, head, tail) != false defp nested_changed_assign(assigns, changed, head, tail) do case changed do %{^head => changed} -> case assigns do %{^head => assigns} -> recur_changed_assign(assigns, changed, tail) %{} -> true end %{} -> false nil -> true end end defp recur_changed_assign(assigns, changed, [{:struct, head} | tail]) do recur_changed_assign(assigns, changed, head, tail) end defp recur_changed_assign(assigns, changed, [{:access, head} | tail]) do if match?(%_{}, assigns) or match?(%_{}, changed) do true else recur_changed_assign(assigns, changed, head, tail) end end defp recur_changed_assign(assigns, changed, head, []) do case {assigns, changed} do {%{^head => value}, %{^head => value}} -> false {_, %{^head => value}} when is_map(value) -> value {_, _} -> true end end defp recur_changed_assign(assigns, changed, head, tail) do case {assigns, changed} do {%{^head => assigns_value}, %{^head => changed_value}} -> recur_changed_assign(assigns_value, changed_value, tail) {_, _} -> true end end # For case/if/unless, we are not leaking the variable given as argument, # such as `if var = ... do`. This does not follow Elixir semantics, but # yields better optimizations. defp classify_taint(:case, [_, _]), do: :live defp classify_taint(:if, [_, _]), do: :live defp classify_taint(:unless, [_, _]), do: :live defp classify_taint(:cond, [_]), do: :live defp classify_taint(:try, [_]), do: :live defp classify_taint(:receive, [_]), do: :live defp classify_taint(:with, _), do: :live # TODO: Remove me when live_component/2/3 are removed defp classify_taint(:live_component, [_, [do: _]]), do: :render defp classify_taint(:live_component, [_, _, [do: _]]), do: :render defp classify_taint(:inner_block, [_, [do: _]]), do: :render defp classify_taint(:render_layout, [_, _, _, [do: _]]), do: :render defp classify_taint(:alias, [_]), do: :special_form defp classify_taint(:import, [_]), do: :special_form defp classify_taint(:require, [_]), do: :special_form defp classify_taint(:alias, [_, _]), do: :special_form defp classify_taint(:import, [_, _]), do: :special_form defp classify_taint(:require, [_, _]), do: :special_form defp classify_taint(:&, [_]), do: :never defp classify_taint(:for, _), do: :never defp classify_taint(:fn, _), do: :never defp classify_taint(_, _), do: :none end
31.427201
100
0.630094
0306fd573fe5653ff6dc3bd34658eea3b4e7750f
2,462
ex
Elixir
clients/content/lib/google_api/content/v2/model/test_order_line_item.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/test_order_line_item.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/test_order_line_item.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.Content.V2.Model.TestOrderLineItem do @moduledoc """ ## Attributes - product (TestOrderLineItemProduct): Product data from the time of the order placement. Defaults to: `null`. - quantityOrdered (integer()): Number of items ordered. Defaults to: `null`. - returnInfo (OrderLineItemReturnInfo): Details of the return policy for the line item. Defaults to: `null`. - shippingDetails (OrderLineItemShippingDetails): Details of the requested shipping for the line item. Defaults to: `null`. - unitTax (Price): Unit tax for the line item. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :product => GoogleApi.Content.V2.Model.TestOrderLineItemProduct.t(), :quantityOrdered => any(), :returnInfo => GoogleApi.Content.V2.Model.OrderLineItemReturnInfo.t(), :shippingDetails => GoogleApi.Content.V2.Model.OrderLineItemShippingDetails.t(), :unitTax => GoogleApi.Content.V2.Model.Price.t() } field(:product, as: GoogleApi.Content.V2.Model.TestOrderLineItemProduct) field(:quantityOrdered) field(:returnInfo, as: GoogleApi.Content.V2.Model.OrderLineItemReturnInfo) field(:shippingDetails, as: GoogleApi.Content.V2.Model.OrderLineItemShippingDetails) field(:unitTax, as: GoogleApi.Content.V2.Model.Price) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.TestOrderLineItem do def decode(value, options) do GoogleApi.Content.V2.Model.TestOrderLineItem.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.TestOrderLineItem do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.033333
125
0.748578
030710ddece3339dcd1e7a07410de49b0d9d27b7
88
ex
Elixir
test/support/web/views/live2_view.ex
Gamecode-HQ/drab
dfbe73c0675831f42829f0f3f7fe12d47a78badc
[ "MIT" ]
933
2017-01-14T13:47:37.000Z
2022-03-21T18:14:41.000Z
test/support/web/views/live2_view.ex
Gamecode-HQ/drab
dfbe73c0675831f42829f0f3f7fe12d47a78badc
[ "MIT" ]
189
2017-01-15T18:35:06.000Z
2022-01-24T17:41:22.000Z
test/support/web/views/live2_view.ex
Gamecode-HQ/drab
dfbe73c0675831f42829f0f3f7fe12d47a78badc
[ "MIT" ]
54
2017-01-15T18:10:48.000Z
2021-02-06T17:21:44.000Z
defmodule DrabTestApp.Live2View do @moduledoc false use DrabTestApp.Web, :view end
14.666667
34
0.784091
030710f9bf532a7588aaa3998cd9d7ddd4ccdc22
417
ex
Elixir
lib/go_champs_api/recently_views/recently_view.ex
lairjr/tournamentsapi
dde8f8f659074527d3861391af3ab29f070179f2
[ "MIT" ]
null
null
null
lib/go_champs_api/recently_views/recently_view.ex
lairjr/tournamentsapi
dde8f8f659074527d3861391af3ab29f070179f2
[ "MIT" ]
2
2019-08-30T04:44:20.000Z
2019-08-30T04:44:28.000Z
lib/go_champs_api/recently_views/recently_view.ex
lairjr/tournamentsapi
dde8f8f659074527d3861391af3ab29f070179f2
[ "MIT" ]
null
null
null
defmodule GoChampsApi.RecentlyViews.RecentlyView do use Ecto.Schema use GoChampsApi.Schema import Ecto.Changeset alias GoChampsApi.Tournaments.Tournament schema "recently_view" do belongs_to :tournament, Tournament timestamps() end @doc false def changeset(recently_view, attrs) do recently_view |> cast(attrs, [:tournament_id]) |> validate_required([:tournament_id]) end end
20.85
51
0.745803
03071aff19b50d4e19e952684793c7a5f776aa2b
4,792
exs
Elixir
elixir/test/homework/transactions_test.exs
Koyamot/Divvy-EngineerExercise
de2f2c0d1ad461b2bbb937fa1483c18d4ececc6a
[ "MIT" ]
null
null
null
elixir/test/homework/transactions_test.exs
Koyamot/Divvy-EngineerExercise
de2f2c0d1ad461b2bbb937fa1483c18d4ececc6a
[ "MIT" ]
8
2022-01-17T20:50:29.000Z
2022-01-17T20:54:41.000Z
elixir/test/homework/transactions_test.exs
Koyamot/Divvy-EngineerExercise
de2f2c0d1ad461b2bbb937fa1483c18d4ececc6a
[ "MIT" ]
1
2022-01-19T06:55:41.000Z
2022-01-19T06:55:41.000Z
defmodule Homework.TransactionsTest do use Homework.DataCase alias Ecto.UUID alias Homework.Merchants alias Homework.Transactions alias Homework.Users describe "transactions" do alias Homework.Transactions.Transaction setup do {:ok, merchant1} = Merchants.create_merchant(%{description: "some description", name: "some name"}) {:ok, merchant2} = Merchants.create_merchant(%{ description: "some updated description", name: "some updated name" }) {:ok, user1} = Users.create_user(%{ dob: "some dob", first_name: "some first_name", last_name: "some last_name" }) {:ok, user2} = Users.create_user(%{ dob: "some updated dob", first_name: "some updated first_name", last_name: "some updated last_name" }) valid_attrs = %{ amount: 42, credit: true, debit: true, description: "some description", merchant_id: merchant1.id, user_id: user1.id } update_attrs = %{ amount: 43, credit: false, debit: false, description: "some updated description", merchant_id: merchant2.id, user_id: user2.id } invalid_attrs = %{ amount: nil, credit: nil, debit: nil, description: nil, merchant_id: nil, user_id: nil } {:ok, %{ valid_attrs: valid_attrs, update_attrs: update_attrs, invalid_attrs: invalid_attrs, merchant1: merchant1, merchant2: merchant2, user1: user1, user2: user2 }} end def transaction_fixture(valid_attrs, attrs \\ %{}) do {:ok, transaction} = attrs |> Enum.into(valid_attrs) |> Transactions.create_transaction() transaction end test "list_transactions/1 returns all transactions", %{valid_attrs: valid_attrs} do transaction = transaction_fixture(valid_attrs) assert Transactions.list_transactions([]) == [transaction] end test "get_transaction!/1 returns the transaction with given id", %{valid_attrs: valid_attrs} do transaction = transaction_fixture(valid_attrs) assert Transactions.get_transaction!(transaction.id) == transaction end test "create_transaction/1 with valid data creates a transaction", %{ valid_attrs: valid_attrs, merchant1: merchant1, user1: user1 } do assert {:ok, %Transaction{} = transaction} = Transactions.create_transaction(valid_attrs) assert transaction.amount == 42 assert transaction.credit == true assert transaction.debit == true assert transaction.description == "some description" assert transaction.merchant_id == merchant1.id assert transaction.user_id == user1.id end test "create_transaction/1 with invalid data returns error changeset", %{ invalid_attrs: invalid_attrs } do assert {:error, %Ecto.Changeset{}} = Transactions.create_transaction(invalid_attrs) end test "update_transaction/2 with valid data updates the transaction", %{ valid_attrs: valid_attrs, update_attrs: update_attrs, merchant2: merchant2, user2: user2 } do transaction = transaction_fixture(valid_attrs) assert {:ok, %Transaction{} = transaction} = Transactions.update_transaction(transaction, update_attrs) assert transaction.amount == 43 assert transaction.credit == false assert transaction.debit == false assert transaction.description == "some updated description" assert transaction.merchant_id == merchant2.id assert transaction.user_id == user2.id end test "update_transaction/2 with invalid data returns error changeset", %{ valid_attrs: valid_attrs, invalid_attrs: invalid_attrs } do transaction = transaction_fixture(valid_attrs) assert {:error, %Ecto.Changeset{}} = Transactions.update_transaction(transaction, invalid_attrs) assert transaction == Transactions.get_transaction!(transaction.id) end test "delete_transaction/1 deletes the transaction", %{valid_attrs: valid_attrs} do transaction = transaction_fixture(valid_attrs) assert {:ok, %Transaction{}} = Transactions.delete_transaction(transaction) assert_raise Ecto.NoResultsError, fn -> Transactions.get_transaction!(transaction.id) end end test "change_transaction/1 returns a transaction changeset", %{valid_attrs: valid_attrs} do transaction = transaction_fixture(valid_attrs) assert %Ecto.Changeset{} = Transactions.change_transaction(transaction) end end end
30.522293
99
0.651294
03071b703eb52783e6f2d3b37d771efc55abf891
1,213
exs
Elixir
mix.exs
kentdahl/tiled_map
f1fd98c0f56c4f7676a53fdece0ef511d12787f4
[ "MIT" ]
2
2016-04-20T22:29:24.000Z
2021-01-20T04:40:41.000Z
mix.exs
kentdahl/tiled_map
f1fd98c0f56c4f7676a53fdece0ef511d12787f4
[ "MIT" ]
null
null
null
mix.exs
kentdahl/tiled_map
f1fd98c0f56c4f7676a53fdece0ef511d12787f4
[ "MIT" ]
1
2019-09-27T11:10:18.000Z
2019-09-27T11:10:18.000Z
defmodule TiledMap.Mixfile do use Mix.Project def project do [app: :tiled_map, version: "0.0.1", elixir: "~> 1.2", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: "Basic parsing of JSON Map Format from Tiled map editor", package: package, source_url: "https://github.com/kentdahl/tiled_map", homepage_url: "https://github.com/kentdahl/tiled_map", docs: [ extras: ["README.md"] ], deps: deps] end def package do [ maintainers: ["Kent Dahl"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/kentdahl/tiled_map"} ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: []] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [ {:poison, ">= 2.0.1"}, {:earmark, ">= 0.0.0", only: :dev}, {:ex_doc, "~> 0.10", only: :dev} ] end end
23.326923
77
0.580379
03072e3c7da4b9830244d3ccd977df9ddb3cfc64
12,009
exs
Elixir
lib/iex/test/iex/helpers_test.exs
carlosantoniodasilva/elixir
0b7d1c9d4964cd6699b72298294844d8d7d694b5
[ "Apache-2.0" ]
null
null
null
lib/iex/test/iex/helpers_test.exs
carlosantoniodasilva/elixir
0b7d1c9d4964cd6699b72298294844d8d7d694b5
[ "Apache-2.0" ]
null
null
null
lib/iex/test/iex/helpers_test.exs
carlosantoniodasilva/elixir
0b7d1c9d4964cd6699b72298294844d8d7d694b5
[ "Apache-2.0" ]
null
null
null
Code.require_file "../test_helper.exs", __DIR__ defmodule IEx.HelpersTest do use IEx.Case import IEx.Helpers test "clear helper" do Application.put_env(:elixir, :ansi_enabled, true) assert capture_iex("clear") == "\e[H\e[2J" Application.put_env(:elixir, :ansi_enabled, false) assert capture_iex("clear") =~ "Cannot clear the screen because ANSI escape codes are not enabled on this shell" after Application.delete_env(:elixir, :ansi_enabled) end test "h helper" do assert "* IEx.Helpers\n\nWelcome to Interactive Elixir" <> _ = capture_iex("h") end test "h helper module" do assert "* IEx.Helpers\n\nWelcome to Interactive Elixir" <> _ = capture_io(fn -> h IEx.Helpers end) assert capture_io(fn -> h :whatever end) == "Could not load module :whatever, got: nofile\n" assert capture_io(fn -> h :lists end) == ":lists is an Erlang module and, as such, it does not have Elixir-style docs\n" end test "h helper function" do pwd_h = "* def pwd()\n\nPrints the current working directory.\n\n" c_h = "* def c(files, path \\\\ \".\")\n\nCompiles the given files." assert capture_io(fn -> h IEx.Helpers.pwd/0 end) =~ pwd_h assert capture_io(fn -> h IEx.Helpers.c/2 end) =~ c_h assert capture_io(fn -> h IEx.Helpers.c/1 end) =~ c_h assert capture_io(fn -> h pwd end) =~ pwd_h end test "h helper __info__" do h_output_module = capture_io(fn -> h Module.__info__ end) assert capture_io(fn -> h Module.UnlikelyTo.Exist.__info__ end) == h_output_module assert capture_io(fn -> h Module.UnlikelyTo.Exist.__info__/1 end) == h_output_module assert capture_io(fn -> h __info__ end) == "No documentation for __info__ was found\n" end test "b helper module" do assert capture_io(fn -> b Mix end) == "No callbacks for Mix were found\n" assert capture_io(fn -> b NoMix end) == "Could not load module NoMix, got: nofile\n" assert capture_io(fn -> b Mix.SCM end) =~ """ defcallback accepts_options(app :: atom(), opts()) :: opts() | nil defcallback checked_out?(opts()) :: boolean() """ end test "b helper function" do assert capture_io(fn -> b Mix.Task.stop end) == "No documentation for Mix.Task.stop was found\n" assert capture_io(fn -> b Mix.Task.run end) =~ "* defcallback run([binary()]) :: any()\n\nA task needs to implement `run`" assert capture_io(fn -> b NoMix.run end) == "Could not load module NoMix, got: nofile\n" assert capture_io(fn -> b Exception.message/1 end) == "* defcallback message(t()) :: String.t()\n\n\n" end test "t helper" do assert capture_io(fn -> t IEx end) == "No type information for IEx was found\n" # Test that it shows at least two types assert Enum.count(capture_io(fn -> t Enum end) |> String.split("\n"), fn line -> String.starts_with? line, "@type" end) >= 2 assert "@type t() :: " <> _ = capture_io(fn -> t Enum.t end) assert capture_io(fn -> t Enum.t end) == capture_io(fn -> t Enum.t/0 end) assert "@opaque t()\n" = capture_io(fn -> t HashDict.t end) assert capture_io(fn -> t HashDict.t end) == capture_io(fn -> t HashDict.t/0 end) end test "s helper" do assert capture_io(fn -> s ExUnit end) == "No specification for ExUnit was found\n" # Test that it shows at least two specs assert Enum.count(capture_io(fn -> s Enum end) |> String.split("\n"), fn line -> String.starts_with? line, "@spec" end) >= 2 assert Enum.count(capture_io(fn -> s Enum.all? end) |> String.split("\n"), fn line -> String.starts_with? line, "@spec" end) >= 2 assert capture_io(fn -> s Enum.all?/1 end) == "@spec all?(t()) :: boolean()\n" assert capture_io(fn -> s struct end) == "@spec struct(module() | %{}, Enum.t()) :: %{}\n" end test "v helper" do assert capture_iex("v") == ":ok" assert capture_iex("1\n2\nv") == String.rstrip """ 1 2 1: 1 #=> 1 2: 2 #=> 2 :ok """ assert "** (RuntimeError) v(0) is out of bounds" <> _ = capture_iex("v(0)") assert capture_iex("1\n2\nv(2)") == "1\n2\n2" assert capture_iex("1\n2\nv(2)") == capture_iex("1\n2\nv(-1)") end test "flush helper" do assert capture_io(fn -> send self(), :hello; flush end) == ":hello\n" end test "pwd helper" do File.cd! iex_path, fn -> assert capture_io(fn -> pwd end) =~ ~r"lib[\\/]iex\n$" end end test "ls helper" do File.cd! iex_path, fn -> paths = capture_io(fn -> ls end) |> String.split |> Enum.map(&String.strip(&1)) assert "ebin" in paths assert "mix.exs" in paths assert capture_io(fn -> ls "~" end) == capture_io(fn -> ls System.user_home end) end end test "import_file helper" do with_file "dot-iex", "variable = :hello\nimport IO", fn -> assert "** (CompileError) iex:1: undefined function variable/0" <> _ = capture_iex("variable") assert "** (CompileError) iex:1: undefined function puts/1" <> _ = capture_iex("puts \"hi\"") assert capture_iex("import_file \"dot-iex\"\nvariable\nputs \"hi\"") == "nil\n:hello\nhi\n:ok" end end test "import_file nested" do dot = "parent = true\nimport_file \"dot-iex-1\"" dot_1 = "variable = :hello\nimport IO" with_file ["dot-iex", "dot-iex-1"], [dot, dot_1], fn -> assert "** (CompileError) iex:1: undefined function parent/0" <> _ = capture_iex("parent") assert "** (CompileError) iex:1: undefined function puts/1" <> _ = capture_iex("puts \"hi\"") assert capture_iex("import_file \"dot-iex\"\nvariable\nputs \"hi\"\nparent") == "nil\n:hello\nhi\n:ok\ntrue" end end test "import_file when the file is missing" do assert "nil" == capture_iex("import_file \"nonexistent\", optional: true") failing = capture_iex("import_file \"nonexistent\"") assert "** (File.Error) could not read file" <> _ = failing assert failing =~ "no such file or directory" end test "c helper" do assert_raise UndefinedFunctionError, ~r"undefined function: Sample\.run/0", fn -> Sample.run end filename = "sample.ex" with_file filename, test_module_code, fn -> assert c(filename) == [Sample] assert Sample.run == :run end after cleanup_modules([Sample]) end test "c helper with full path" do filename = "sample.ex" with_file filename, test_module_code, fn -> assert c(Path.expand(filename)) == [Sample] assert Sample.run == :run end after cleanup_modules([Sample]) end test "c helper multiple modules" do assert_raise UndefinedFunctionError, ~r"undefined function: Sample.run/0", fn -> Sample.run end filename = "sample.ex" with_file filename, test_module_code <> "\n" <> another_test_module, fn -> assert c(filename) |> Enum.sort == [Sample, Sample2] assert Sample.run == :run assert Sample2.hello == :world end after cleanup_modules([Sample, Sample2]) end test "c helper list" do assert_raise UndefinedFunctionError, ~r"undefined function: Sample.run/0", fn -> Sample.run end filenames = ["sample1.ex", "sample2.ex"] with_file filenames, [test_module_code, another_test_module], fn -> assert c(filenames) |> Enum.sort == [Sample, Sample2] assert Sample.run == :run assert Sample2.hello == :world end after cleanup_modules([Sample, Sample2]) end test "c helper erlang" do assert_raise UndefinedFunctionError, ~r"undefined function: :sample.hello/0", fn -> :sample.hello end filename = "sample.erl" with_file filename, erlang_module_code, fn -> assert c(filename) == [:sample] assert :sample.hello == :world end after cleanup_modules([:sample]) end test "c helper skips unknown files" do assert_raise UndefinedFunctionError, ~r"undefined function: :sample.hello/0", fn -> :sample.hello end filenames = ["sample.erl", "not_found.ex", "sample2.ex"] with_file filenames, [erlang_module_code, "", another_test_module], fn -> assert c(filenames) |> Enum.sort == [Sample2, :sample] assert :sample.hello == :world assert Sample2.hello == :world end after cleanup_modules([:sample, Sample2]) end test "l helper" do assert_raise UndefinedFunctionError, ~r"undefined function: Sample.run/0", fn -> Sample.run end assert l(:non_existent_module) == {:error, :nofile} filename = "sample.ex" with_file filename, test_module_code, fn -> assert c(filename) == [Sample] assert Sample.run == :run File.write! filename, "defmodule Sample do end" elixirc ["sample.ex"] assert l(Sample) == {:module, Sample} assert_raise UndefinedFunctionError, "undefined function: Sample.run/0", fn -> Sample.run end end after # Clean up the old version left over after l() cleanup_modules([Sample]) end test "r helper unavailable" do assert_raise ArgumentError, "could not load nor find module: :non_existent_module", fn -> r :non_existent_module end end test "r helper elixir" do assert_raise UndefinedFunctionError, ~r"undefined function: Sample.run/0 \(module Sample is not available\)", fn -> Sample.run end filename = "sample.ex" with_file filename, test_module_code, fn -> assert capture_io(:stderr, fn -> assert c(filename) == [Sample] assert Sample.run == :run File.write! filename, "defmodule Sample do end" assert {:reloaded, Sample, [Sample]} = r(Sample) assert_raise UndefinedFunctionError, "undefined function: Sample.run/0", fn -> Sample.run end end) =~ ~r"^.*?sample\.ex:1: warning: redefining module Sample\n$" end after # Clean up old version produced by the r helper cleanup_modules([Sample]) end test "r helper erlang" do assert_raise UndefinedFunctionError, ~r"undefined function: :sample.hello/0", fn -> :sample.hello end filename = "sample.erl" with_file filename, erlang_module_code, fn -> assert c(filename) == [:sample] assert :sample.hello == :world File.write!(filename, other_erlang_module_code) assert {:reloaded, :sample, [:sample]} = r(:sample) assert :sample.hello == :bye end after cleanup_modules([:sample]) end defp test_module_code do """ defmodule Sample do def run do :run end end """ end defp another_test_module do """ defmodule Sample2 do def hello do :world end end """ end defp erlang_module_code do """ -module(sample). -export([hello/0]). hello() -> world. """ end defp other_erlang_module_code do """ -module(sample). -export([hello/0]). hello() -> bye. """ end defp cleanup_modules(mods) do Enum.each mods, fn mod -> File.rm("#{mod}.beam") :code.purge(mod) true = :code.delete(mod) end end defp with_file(names, codes, fun) when is_list(names) and is_list(codes) do Enum.each Enum.zip(names, codes), fn {name, code} -> File.write! name, code end try do fun.() after Enum.each names, &File.rm/1 end end defp with_file(name, code, fun) do with_file(List.wrap(name), List.wrap(code), fun) end defp elixirc(args) do executable = Path.expand("../../../../bin/elixirc", __DIR__) System.cmd("#{executable}#{executable_extension}", args, [stderr_to_stdout: true]) end defp iex_path do Path.expand "../..", __DIR__ end if match? {:win32, _}, :os.type do defp executable_extension, do: ".bat" else defp executable_extension, do: "" end end
29.077482
126
0.619702
0307828e8d1eeadebb0a56c4440317480a232ddd
2,289
exs
Elixir
test/shopmap/location/location_test.exs
Yoosuke/shopmap
5a1892850d2c79b4732e3ee0c40a8b7c7c55d20d
[ "MIT" ]
null
null
null
test/shopmap/location/location_test.exs
Yoosuke/shopmap
5a1892850d2c79b4732e3ee0c40a8b7c7c55d20d
[ "MIT" ]
null
null
null
test/shopmap/location/location_test.exs
Yoosuke/shopmap
5a1892850d2c79b4732e3ee0c40a8b7c7c55d20d
[ "MIT" ]
null
null
null
defmodule Shopmap.LocationTest do use Shopmap.DataCase alias Shopmap.Location describe "shops" do alias Shopmap.Location.Shop @valid_attrs %{info: "some info", lat: 120.5, lng: 120.5, name: "some name", rank: 42} @update_attrs %{info: "some updated info", lat: 456.7, lng: 456.7, name: "some updated name", rank: 43} @invalid_attrs %{info: nil, lat: nil, lng: nil, name: nil, rank: nil} def shop_fixture(attrs \\ %{}) do {:ok, shop} = attrs |> Enum.into(@valid_attrs) |> Location.create_shop() shop end test "list_shops/0 returns all shops" do shop = shop_fixture() assert Location.list_shops() == [shop] end test "get_shop!/1 returns the shop with given id" do shop = shop_fixture() assert Location.get_shop!(shop.id) == shop end test "create_shop/1 with valid data creates a shop" do assert {:ok, %Shop{} = shop} = Location.create_shop(@valid_attrs) assert shop.info == "some info" assert shop.lat == 120.5 assert shop.lng == 120.5 assert shop.name == "some name" assert shop.rank == 42 end test "create_shop/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Location.create_shop(@invalid_attrs) end test "update_shop/2 with valid data updates the shop" do shop = shop_fixture() assert {:ok, %Shop{} = shop} = Location.update_shop(shop, @update_attrs) assert shop.info == "some updated info" assert shop.lat == 456.7 assert shop.lng == 456.7 assert shop.name == "some updated name" assert shop.rank == 43 end test "update_shop/2 with invalid data returns error changeset" do shop = shop_fixture() assert {:error, %Ecto.Changeset{}} = Location.update_shop(shop, @invalid_attrs) assert shop == Location.get_shop!(shop.id) end test "delete_shop/1 deletes the shop" do shop = shop_fixture() assert {:ok, %Shop{}} = Location.delete_shop(shop) assert_raise Ecto.NoResultsError, fn -> Location.get_shop!(shop.id) end end test "change_shop/1 returns a shop changeset" do shop = shop_fixture() assert %Ecto.Changeset{} = Location.change_shop(shop) end end end
31.356164
107
0.638707
0307995d995e5ea70ef41e3dc47994ab18990d66
125
ex
Elixir
lib/excommerce/commands/product_option_type.ex
roger120981/planet
a662006551d11427c08cf6cdbacd37d377bcd9c5
[ "MIT" ]
1
2019-04-01T19:14:16.000Z
2019-04-01T19:14:16.000Z
lib/excommerce/commands/product_option_type.ex
roger120981/planet
a662006551d11427c08cf6cdbacd37d377bcd9c5
[ "MIT" ]
null
null
null
lib/excommerce/commands/product_option_type.ex
roger120981/planet
a662006551d11427c08cf6cdbacd37d377bcd9c5
[ "MIT" ]
1
2019-03-24T01:50:48.000Z
2019-03-24T01:50:48.000Z
defmodule Excommerce.Command.ProductOptionType do use Excommerce.Command, schema: Excommerce.Catalog.ProductOptionType end
31.25
70
0.864
03079fe58405ab053c5c95ec50d795040b424efc
257
ex
Elixir
lib/tablespoon.ex
paulswartz/tablespoon
3637ee22cce16755fa50461058a079fa18d33b1b
[ "MIT" ]
2
2020-04-03T14:39:23.000Z
2020-12-17T23:12:58.000Z
lib/tablespoon.ex
mbta/tablespoon
4303ad8498f3e619b081ffbd6892156e0214b61e
[ "MIT" ]
107
2019-09-16T12:52:17.000Z
2022-02-28T10:25:15.000Z
lib/tablespoon.ex
mbta/tablespoon
4303ad8498f3e619b081ffbd6892156e0214b61e
[ "MIT" ]
null
null
null
defmodule Tablespoon do @moduledoc """ Tablespoon 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.7
66
0.758755
0307a3274c93960fe5383760548762d0bfa659c5
5,454
exs
Elixir
test/zxcvbn/feedback_test.exs
KrisLamote/zxcvbn-ex
26ad9e6f177b6314dc91069137184e7235430e5e
[ "MIT" ]
2
2018-10-09T20:17:08.000Z
2018-10-18T23:30:49.000Z
test/zxcvbn/feedback_test.exs
KrisLamote/zxcvbn-ex
26ad9e6f177b6314dc91069137184e7235430e5e
[ "MIT" ]
13
2018-10-06T08:03:23.000Z
2019-10-02T18:50:43.000Z
test/zxcvbn/feedback_test.exs
KrisLamote/zxcvbn-ex
26ad9e6f177b6314dc91069137184e7235430e5e
[ "MIT" ]
7
2018-10-06T10:14:41.000Z
2019-10-01T09:29:44.000Z
defmodule Zxcvbn.FeedbackTest do use ExUnit.Case alias Zxcvbn.Feedback describe "get_dictionary_match_feedback/2" do setup do %{ token: "", l33t: false, reversed: false, rank: 0, dictionary_name: "", guesses_log10: 0 } end test "warns when rank is less than 10", match do match = %{match | rank: 4, dictionary_name: "passwords"} expected = "This is a top-10 common password" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns when rank is less than 100", match do match = %{match | rank: 40, dictionary_name: "passwords"} expected = "This is a top-100 common password" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns it is similar to a common password", match do match = %{match | rank: 400, dictionary_name: "passwords"} expected = "This is similar to a commonly used password" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns it is a very common password when not a sole match", match do match = %{match | dictionary_name: "passwords"} expected = "This is a very common password" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, false) assert warning == expected end test "warns it is a very common password when l33t", match do match = %{match | dictionary_name: "passwords", l33t: true} expected = "This is a very common password" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns it is a very common password when reversed", match do match = %{match | dictionary_name: "passwords", reversed: true} expected = "This is a very common password" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns when a sole match is an english word", match do match = %{match | dictionary_name: "english_wikipedia"} expected = "A word by itself is easy to guess" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns when a sole match is a surname", match do match = %{match | dictionary_name: "surnames"} expected = "Names and surnames by themselves are easy to guess" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns when a sole match is a male name", match do match = %{match | dictionary_name: "male_names"} expected = "Names and surnames by themselves are easy to guess" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "warns when a sole match is a female name", match do match = %{match | dictionary_name: "female_names"} expected = "Names and surnames by themselves are easy to guess" %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == expected end test "no warnings returns an empty string", match do %{warning: warning} = Feedback.get_dictionary_match_feedback(match, true) assert warning == "" end test "adds suggestion for token starting with a capital letter", match do match = %{match | token: "Capitalized"} %{suggestions: [suggestion]} = Feedback.get_dictionary_match_feedback(match, true) assert suggestion == "Capitalization doesn't help very much" end test "adds suggestion for all caps", match do match = %{match | token: "CAPITALIZED"} %{suggestions: [suggestion]} = Feedback.get_dictionary_match_feedback(match, true) assert suggestion == "All-uppercase is almost as easy to guess as all-lowercase" end test "adds suggestion if token is a short reversed word", match do match = %{match | token: "tab", reversed: true} %{suggestions: [suggestion]} = Feedback.get_dictionary_match_feedback(match, true) assert suggestion == "Reversed words aren't much harder to guess" end test "adds suggestion for basic substitutions", match do match = %{match | token: "b@asic$substitution", l33t: true} %{suggestions: [suggestion]} = Feedback.get_dictionary_match_feedback(match, true) assert suggestion == "Predictable substitutions like '@' instead of 'a' don't help very much" end test "suggestions stack", match do match = %{match | token: "Tab", l33t: true, reversed: true} %{suggestions: suggestions} = Feedback.get_dictionary_match_feedback(match, true) expected = [ "Predictable substitutions like '@' instead of 'a' don't help very much", "Reversed words aren't much harder to guess", "Capitalization doesn't help very much" ] assert suggestions == expected end test "suggestions is empty array when password is strong", match do match = %{match | token: "imaginethiswasagoodpassword"} %{suggestions: suggestions} = Feedback.get_dictionary_match_feedback(match, true) assert suggestions == [] end end end
35.647059
88
0.67125
0307c8ec7241017ad799f8e43d27b69b087a6cff
544
ex
Elixir
lib/kiq/running_job.ex
locaweb/kiq
fa561b9a1a2361e99b4af5eafc4d3c7ece576ea9
[ "MIT" ]
59
2018-07-13T23:17:00.000Z
2021-12-21T07:03:03.000Z
lib/kiq/running_job.ex
locaweb/kiq
fa561b9a1a2361e99b4af5eafc4d3c7ece576ea9
[ "MIT" ]
5
2019-08-05T13:14:42.000Z
2022-03-09T12:38:46.000Z
lib/kiq/running_job.ex
locaweb/kiq
fa561b9a1a2361e99b4af5eafc4d3c7ece576ea9
[ "MIT" ]
6
2018-09-24T13:16:21.000Z
2021-05-03T08:26:52.000Z
defmodule Kiq.RunningJob do @moduledoc false alias Kiq.{Encoder, Job, Timestamp} @type t :: %__MODULE__{key: binary(), encoded: binary()} defstruct [:key, :encoded] @spec new(job :: Job.t()) :: t() def new(%Job{pid: pid, queue: queue} = job) do details = %{queue: queue, payload: Job.to_map(job), run_at: Timestamp.unix_now()} %__MODULE__{key: format_key(pid), encoded: Encoder.encode(details)} end defp format_key(pid) when is_pid(pid) or is_reference(pid) do to_string(:io_lib.format("~p", [pid])) end end
25.904762
85
0.663603
0307d8e5abacbb7b43fc621d00fc16683b5099c2
1,243
exs
Elixir
apps/admin_api/test/admin_api/v1/views/reset_password_view_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/admin_api/test/admin_api/v1/views/reset_password_view_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/admin_api/test/admin_api/v1/views/reset_password_view_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule AdminAPI.V1.ResetPasswordViewTest do use AdminAPI.ViewCase, :v1 alias AdminAPI.V1.ResetPasswordView describe "render/2" do test "renders empty.json with the success: true" do expected = %{ version: @expected_version, success: true, data: %{} } assert ResetPasswordView.render("empty.json", %{success: true}) == expected end test "renders empty.json with the success: false" do expected = %{ version: @expected_version, success: false, data: %{} } assert ResetPasswordView.render("empty.json", %{success: false}) == expected end end end
30.317073
82
0.69107
0307e34ff5f5153e1ea57ab39edf9ebcaa8f2a94
328
ex
Elixir
languages/elixir/exercises/concept/dna-encoding/lib/dna.ex
evelynstender/v3
f002a8c620107f6bf8a5c6d685654b95294963ce
[ "MIT" ]
null
null
null
languages/elixir/exercises/concept/dna-encoding/lib/dna.ex
evelynstender/v3
f002a8c620107f6bf8a5c6d685654b95294963ce
[ "MIT" ]
null
null
null
languages/elixir/exercises/concept/dna-encoding/lib/dna.ex
evelynstender/v3
f002a8c620107f6bf8a5c6d685654b95294963ce
[ "MIT" ]
null
null
null
defmodule DNA do def encode_nucleotide(code_point), do: raise "Please implement encode_nucleotide/1" def decode_nucleotide(encoded_code), do: raise "Please implement decode_nucleotide/1" def encode(dna) do raise "Please implement encode/1" end def decode(dna) do raise "Please implement decode/1" end end
23.428571
87
0.753049
03080e6b0bc0a92fdc91091c6b15af1bc7486ba7
9,272
ex
Elixir
lib/live_qchatex_web/live/chat.ex
fiqus/lqchatex
e5a29cadc2b1eb7fce88be3e612a5ff240a09b59
[ "MIT" ]
8
2019-06-01T18:45:47.000Z
2021-11-10T07:56:20.000Z
lib/live_qchatex_web/live/chat.ex
fiqus/lqchatex
e5a29cadc2b1eb7fce88be3e612a5ff240a09b59
[ "MIT" ]
3
2020-04-19T15:59:27.000Z
2021-05-09T00:33:11.000Z
lib/live_qchatex_web/live/chat.ex
fiqus/lqchatex
e5a29cadc2b1eb7fce88be3e612a5ff240a09b59
[ "MIT" ]
3
2019-10-25T16:03:12.000Z
2021-11-10T07:53:14.000Z
defmodule LiveQchatexWeb.LiveChat.Chat do use LiveQchatexWeb, :live_view @view_name "chat-room" def mount(%{sid: sid}, socket) do setup_logger(socket, @view_name) {:ok, socket |> fetch_user(sid)} end def handle_params(%{"id" => id}, _uri, socket) do try do socket = socket |> fetch_chat!(id) if connected?(socket), do: Chats.track(socket.assigns.chat, socket.assigns.user) {:noreply, socket |> maybe_clear_invite() |> fetch()} rescue err -> Logger.error("Can't mount the chat #{inspect(err)}") {:noreply, socket # @TODO Make this error to be displayed on home screen! (NOT WORKING) |> put_flash(:error, "The chat doesn't exist!") |> live_redirect(to: Routes.live_path(socket, LiveQchatexWeb.LiveChat.Home))} end end def render(assigns) do ChatView.render("chat.html", assigns) end @impl Handlers def handle_chat_created(socket, _chat), do: socket |> update_counter(:chats, 1) @impl Handlers def handle_chat_updated(socket, chat), do: socket |> update_chat(chat) @impl Handlers def handle_chat_cleared(socket, counter), do: socket |> set_counter(:chats, counter) @impl Handlers def handle_user_created(socket, _user), do: socket |> update_counter(:users, 1) @impl Handlers def handle_user_cleared(socket, counter), do: socket |> set_counter(:users, counter) @impl Handlers def handle_presence_payload(socket, topic, payload) do cond do topic == Chats.topic(:presence, :chats) -> socket |> maybe_clear_invite(payload) |> update_invites() topic == Chats.topic(socket.assigns.user) -> socket |> update_invites() true -> socket |> update_members() end end def handle_info({[:user, :typing, :end]} = info, socket) do Logger.debug("HANDLE USER TYPING END: #{inspect(info)}", ansi_color: :magenta) user = Chats.update_last_activity!(socket.assigns.user) Chats.update_member_typing(socket.assigns.chat, socket.assigns.user, false) {:noreply, socket |> assign(:user, user)} end def handle_info({[:message, :created], message} = info, socket) do Logger.debug("HANDLE MESSAGE CREATED: #{inspect(info)}", ansi_color: :magenta) {:noreply, socket |> update_messages(message)} end def handle_info(info, socket) do Logger.warn("UNHANDLED INFO: #{inspect(info)}") {:noreply, socket} end def handle_event("typing", _data, socket) do try do Chats.update_member_typing(socket.assigns.chat, socket.assigns.user, true) Map.get(socket.assigns, :typing_timer, nil) |> maybe_cancel_typing_timer() timer_ref = Process.send_after( self(), {[:user, :typing, :end]}, Application.get_env(:live_qchatex, :timers)[:user_typing_timeout] * 1000 ) {:noreply, socket |> assign(:typing_timer, timer_ref)} rescue err -> Logger.error("Can't update typing status #{inspect(err)}") {:noreply, socket} end end def handle_event("message", %{"message" => data}, %{:assigns => assigns} = socket) do try do case get_message_type(data["text"]) do {:nickname, nick} -> socket |> maybe_update_nickname(nick) {:message, text} -> {:ok, message} = Chats.create_message(assigns.chat, assigns.user, text) {:noreply, socket |> update_messages(message)} _ -> {:noreply, socket} end rescue err -> Logger.error("Can't send the message #{inspect(err)}") response_error(socket, "Couldn't send the message!") end end def handle_event("update_nickname", %{"nick" => nick}, socket) do socket |> assign(click: nil) |> maybe_update_nickname(nick) end def handle_event("update_title", %{"title" => title}, socket) do socket |> assign(click: nil) |> maybe_update_title(title) end def handle_event("toggle_scope", _, socket) do socket |> maybe_toggle_scope() end def handle_event("click", %{"action" => action}, socket) do {:noreply, socket |> assign(:click, action)} end def handle_event(event, data, socket) do Logger.warn("UNHANDLED EVENT '#{event}': #{inspect(data)}") {:noreply, socket} end defp fetch_chat!(socket, id) do socket |> assign(chat_id: id, chat: Chats.get_chat!(id)) end defp fetch_user(socket, sid) do {:ok, %Models.User{} = user} = Chats.get_or_create_user(sid) socket |> assign(sid: sid, user: user) end defp fetch(%{:assigns => %{:chat => chat}} = socket) do socket |> update_members() |> update_invites() |> assign( messages: Chats.get_messages(chat), counters: %{ chats: Chats.count_chats(), users: Chats.count_users() }, error: "", info: "", success: "" ) end defp set_counter(%{:assigns => %{:counters => counters}} = socket, key, amount) do socket |> assign(:counters, counters |> Map.put(key, amount)) end defp update_counter(%{:assigns => %{:counters => counters}} = socket, key, amount) do socket |> set_counter(key, counters[key] + amount) end defp update_chat(%{:assigns => %{:chat => chat}} = socket, key, value) do {:ok, chat} = Chats.update_chat(chat, %{key => value}) socket |> update_chat(chat) end defp update_chat(%{:assigns => %{:chat => chat}} = socket, %Models.Chat{} = updated) do if chat.id == updated.id, do: socket |> assign(chat: updated), else: socket end defp update_user(%{:assigns => %{:chat => chat, :user => user}} = socket, key, value) do {:ok, user} = Chats.update_user(user, %{key => value}) socket |> assign(user: user) |> assign(chat: chat |> Chats.update_chat_member(user)) end defp update_members(%{assigns: %{chat: chat}} = socket) do socket |> assign(members: chat |> Chats.list_chat_members()) end defp update_invites(%{assigns: %{user: user}} = socket) do socket |> assign(invites: user |> Chats.list_chat_invites()) end defp update_messages(%{:assigns => %{:messages => messages}} = socket, message) do socket |> assign(:messages, messages ++ [message]) end defp update_nickname(%{:assigns => %{:user => user}} = socket, nick) do Logger.debug("Changed nickname to: #{inspect(nick)}") message = "Renamed from #{inspect(user.nickname)} to #{inspect(nick)}" handle_event( "message", %{"message" => %{"text" => message}}, socket |> update_user(:nickname, nick) ) end defp maybe_update_nickname(%{:assigns => %{:user => user}} = socket, nick) do nick = nick |> String.trim() if user.nickname != nick and nick |> String.length() > 0 do socket |> update_nickname(nick) else # socket |> response_error("The nickname is not valid!") {:noreply, socket} end end defp update_title(%{:assigns => %{:chat => chat}} = socket, title) do Logger.debug("Changed title to: #{inspect(title)}") message = "Changed chat title from #{inspect(chat.title)} to #{inspect(title)}" handle_event( "message", %{"message" => %{"text" => message}}, socket |> update_chat(:title, title) ) end defp maybe_update_title(%{:assigns => %{:chat => chat, :user => user}} = socket, title) do title = title |> String.trim() if chat.user_id == user.id && chat.title != title and title |> String.length() > 0 do socket |> update_title(title) else # socket |> response_error("The title is not valid!") {:noreply, socket} end end defp maybe_toggle_scope(%{:assigns => %{:chat => chat, :user => user}} = socket) do if chat.user_id == user.id do scope = if chat.private, do: "public", else: "private" Logger.debug("Changing chat scope to: #{scope}") {:noreply, socket |> update_chat(:private, scope == "private")} else {:noreply, socket} end end defp maybe_clear_invite(%{assigns: assigns} = socket) do Chats.topic(assigns.user) |> LiveQchatex.Presence.list_presences() |> Enum.find(&(&1.chat == assigns.chat.id)) |> maybe_clear_invite(socket) end defp maybe_clear_invite(nil, socket), do: socket defp maybe_clear_invite(invite, %{assigns: assigns} = socket) do Chats.private_chat_clear(assigns.user, invite.key) socket end defp maybe_clear_invite(%{assigns: assigns} = socket, %{leaves: leaves}) do leaves |> Enum.each(fn {chat_id, %{metas: [%{user: user_id}]}} -> Chats.topic(assigns.user) |> LiveQchatex.Presence.list_presences() |> Enum.find(&(&1.chat == chat_id and &1.key == user_id)) |> maybe_clear_invite(socket) end) socket end defp maybe_cancel_typing_timer(nil), do: :ignore defp maybe_cancel_typing_timer(typing_timer), do: Process.cancel_timer(typing_timer) defp get_message_type(text) do cond do Regex.match?(~r/^\s*\/nick\s+(.*)/, text) -> [_, nick] = Regex.run(~r/\/nick\s+(.*)/, text) {:nickname, nick |> String.trim()} String.trim(text) != "" -> {:message, text} true -> {:ignore, text} end end defp response_error(socket, error), do: {:noreply, assign(socket, error: error)} end
29.341772
92
0.624137
030818d40cde9d51ef8ef35e0355200726069e09
1,328
exs
Elixir
config/config.exs
casey-chow/pton.co
c794dc6903326dc827f5cbd5c7a8e35868a0fa45
[ "MIT" ]
null
null
null
config/config.exs
casey-chow/pton.co
c794dc6903326dc827f5cbd5c7a8e35868a0fa45
[ "MIT" ]
4
2017-10-18T15:52:20.000Z
2017-10-19T00:18:38.000Z
config/config.exs
casey-chow/pton.co
c794dc6903326dc827f5cbd5c7a8e35868a0fa45
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. use Mix.Config # General application configuration config :pton, ecto_repos: [Pton.Repo], max_lifetime_links: 150, rate_limit_max_requests: 5, rate_limit_interval_seconds: 30 # Configures the endpoint config :pton, PtonWeb.Endpoint, url: [host: "localhost"], secret_key_base: "s4tIoKzMtY/1du9dRJIe/4kUdLNdUjisQvy0XjWAhFyFI63WNwxFWXL5KbyMbzwH", render_errors: [view: PtonWeb.ErrorView, accepts: ~w(html json)], pubsub: [name: Pton.PubSub, adapter: Phoenix.PubSub.PG2] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # For information about Princeton's CAS system, see: # https://sp.princeton.edu/oit/eis/iam/authentication/CAS/CAS%20Developer%20KB.aspx config :ueberauth, Ueberauth, providers: [cas: {Ueberauth.Strategy.CAS, [ base_url: "https://fed.princeton.edu/cas", callback: "https://pton.co/auth/cas/callback", ]}] # 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"
34.051282
86
0.752259
030842fb95ad8b026dab5352ec090a03cc30680e
1,568
ex
Elixir
clients/content/lib/google_api/content/v2/model/orders_cancel_test_order_by_customer_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_cancel_test_order_by_customer_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_cancel_test_order_by_customer_response.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.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse do @moduledoc """ ## Attributes * `kind` (*type:* `String.t`, *default:* `content#ordersCancelTestOrderByCustomerResponse`) - Identifies what kind of resource this is. Value: the fixed string "content#ordersCancelTestOrderByCustomerResponse". """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t() } field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse do def decode(value, options) do GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.361702
214
0.760842
030872a9f6063d9e135b03e1b4a14e1748b7891f
1,742
ex
Elixir
apps/elixir_ls_utils/lib/wire_protocol.ex
SerenityIK/elixir-ls
9569197be87809c241360a6ef1f5a9fffd25ab74
[ "Apache-2.0" ]
null
null
null
apps/elixir_ls_utils/lib/wire_protocol.ex
SerenityIK/elixir-ls
9569197be87809c241360a6ef1f5a9fffd25ab74
[ "Apache-2.0" ]
null
null
null
apps/elixir_ls_utils/lib/wire_protocol.ex
SerenityIK/elixir-ls
9569197be87809c241360a6ef1f5a9fffd25ab74
[ "Apache-2.0" ]
null
null
null
defmodule ElixirLS.Utils.WireProtocol do @moduledoc """ Reads and writes packets using the Language Server Protocol's wire protocol """ alias ElixirLS.Utils.{PacketStream, OutputDevice} @separator "\r\n\r\n" def send(packet) do pid = io_dest() body = JasonVendored.encode_to_iodata!(packet) case IO.binwrite(pid, [ "Content-Length: ", IO.iodata_length(body) |> Integer.to_string(), @separator, body ]) do :ok -> :ok {:error, reason} -> IO.warn("Unable to write to the device: #{inspect(reason)}") :ok end end defp io_dest do Process.whereis(:raw_user) || Process.group_leader() end def io_intercepted? do !!Process.whereis(:raw_user) end def intercept_output(print_fn, print_err_fn) do raw_user = Process.whereis(:user) raw_standard_error = Process.whereis(:standard_error) :ok = :io.setopts(raw_user, binary: true, encoding: :latin1) {:ok, user} = OutputDevice.start_link(raw_user, print_fn) {:ok, standard_error} = OutputDevice.start_link(raw_standard_error, print_err_fn) Process.unregister(:user) Process.register(raw_user, :raw_user) Process.register(user, :user) Process.unregister(:standard_error) Process.register(raw_standard_error, :raw_standard_error) Process.register(standard_error, :standard_error) for process <- :erlang.processes(), process not in [raw_user, raw_standard_error] do Process.group_leader(process, user) end end def stream_packets(receive_packets_fn) do PacketStream.stream(Process.whereis(:raw_user)) |> Stream.each(fn packet -> receive_packets_fn.(packet) end) |> Stream.run() end end
27.650794
88
0.677956
03087d904d4320de31047ff48a39daa62e7a8223
201
ex
Elixir
lib/phone/lu.ex
davidkovsky/phone
83108ab1042efe62778c7363f5d02ef888883408
[ "Apache-2.0" ]
97
2016-04-05T13:08:41.000Z
2021-12-25T13:08:34.000Z
lib/phone/lu.ex
davidkovsky/phone
83108ab1042efe62778c7363f5d02ef888883408
[ "Apache-2.0" ]
70
2016-06-14T00:56:00.000Z
2022-02-10T19:43:14.000Z
lib/phone/lu.ex
davidkovsky/phone
83108ab1042efe62778c7363f5d02ef888883408
[ "Apache-2.0" ]
31
2016-04-21T22:26:12.000Z
2022-01-24T21:40:00.000Z
defmodule Phone.LU do @moduledoc false use Helper.Country def regex, do: ~r/^(352)()(.+)/ def country, do: "Luxembourg" def a2, do: "LU" def a3, do: "LUX" matcher(:regex, ["352"]) end
15.461538
33
0.60199
0308879c837e1a00db7875a81a207fe2566e1f49
428
exs
Elixir
config/config.exs
NFIBrokerage/volley
592dc5cbf7cbcfb8648f779fea433c721f3893c0
[ "Apache-2.0" ]
3
2021-05-03T16:33:37.000Z
2021-09-12T08:03:23.000Z
config/config.exs
NFIBrokerage/volley
592dc5cbf7cbcfb8648f779fea433c721f3893c0
[ "Apache-2.0" ]
1
2021-09-08T15:18:58.000Z
2021-09-08T15:19:50.000Z
config/config.exs
NFIBrokerage/volley
592dc5cbf7cbcfb8648f779fea433c721f3893c0
[ "Apache-2.0" ]
null
null
null
import Config case System.get_env("EVENTSTORE_HOST") do nil -> config :volley, Volley.SpearClient, connection_string: "esdb://admin:changeit@localhost:2113?tls=true", mint_opts: [ transport_opts: [ cacertfile: Path.join([__DIR__ | ~w[.. certs ca ca.crt]]) ] ] host -> config :volley, Volley.SpearClient, connection_string: "esdb://admin:changeit@#{host}:2113" end
25.176471
73
0.633178
0308ade9109f690aac5ced1c45e16e9eed97798c
673
ex
Elixir
phoenix_maru/web/router.ex
elixir-maru/maru_examples
f0dcbf3c17c9df8b89b378953b71b54a53047806
[ "MIT" ]
27
2016-12-28T15:00:19.000Z
2021-11-09T12:55:23.000Z
phoenix_maru/web/router.ex
elixir-maru/maru_examples
f0dcbf3c17c9df8b89b378953b71b54a53047806
[ "MIT" ]
5
2017-02-13T13:11:55.000Z
2019-07-22T19:38:09.000Z
phoenix_maru/web/router.ex
elixir-maru/maru_examples
f0dcbf3c17c9df8b89b378953b71b54a53047806
[ "MIT" ]
8
2017-02-08T10:18:50.000Z
2020-06-01T11:42:04.000Z
defmodule PhoenixMaru.Router do use PhoenixMaru.Web, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", PhoenixMaru do pipe_through :browser # Use the default browser stack get "/", PageController, :index end # Other scopes may use custom stacks. scope path: "/api" do pipe_through :api scope "/mob" do forward "/", PhoenixMaru.APIs.Homepage end scope "/mob2" do forward "/", PhoenixMaru.APIs.Versioning.Path end end end
18.694444
57
0.66419
0308c3a446735c235fc6b37edbf677ad4dbf92c8
8,130
exs
Elixir
integration_test/cases/type.exs
photomattmills/ecto
ad3a455aa3d5e4f932a5bb8ae1590b21d95cce54
[ "Apache-2.0" ]
null
null
null
integration_test/cases/type.exs
photomattmills/ecto
ad3a455aa3d5e4f932a5bb8ae1590b21d95cce54
[ "Apache-2.0" ]
null
null
null
integration_test/cases/type.exs
photomattmills/ecto
ad3a455aa3d5e4f932a5bb8ae1590b21d95cce54
[ "Apache-2.0" ]
null
null
null
Code.require_file "../support/types.exs", __DIR__ defmodule Ecto.Integration.TypeTest do use Ecto.Integration.Case alias Ecto.Integration.TestRepo import Ecto.Query alias Ecto.Integration.Post alias Ecto.Integration.Tag alias Ecto.Integration.Custom alias Ecto.Integration.Order alias Ecto.Integration.Item test "primitive types" do integer = 1 float = 0.1 text = <<0,1>> uuid = "00010203-0405-0607-0809-0a0b0c0d0e0f" datetime = %Ecto.DateTime{year: 2014, month: 1, day: 16, hour: 20, min: 26, sec: 51, usec: 0} TestRepo.insert!(%Post{text: text, public: true, visits: integer, uuid: uuid, counter: integer, inserted_at: datetime, intensity: float}) # nil assert [nil] = TestRepo.all(from Post, select: nil) # ID assert [1] = TestRepo.all(from p in Post, where: p.counter == ^integer, select: p.counter) # Integers assert [1] = TestRepo.all(from p in Post, where: p.visits == ^integer, select: p.visits) assert [1] = TestRepo.all(from p in Post, where: p.visits == 1, select: p.visits) # Floats assert [0.1] = TestRepo.all(from p in Post, where: p.intensity == ^float, select: p.intensity) assert [0.1] = TestRepo.all(from p in Post, where: p.intensity == 0.1, select: p.intensity) assert [1500.0] = TestRepo.all(from p in Post, select: 1500.0) # Booleans assert [true] = TestRepo.all(from p in Post, where: p.public == ^true, select: p.public) assert [true] = TestRepo.all(from p in Post, where: p.public == true, select: p.public) # Binaries assert [^text] = TestRepo.all(from p in Post, where: p.text == <<0, 1>>, select: p.text) assert [^text] = TestRepo.all(from p in Post, where: p.text == ^text, select: p.text) # UUID assert [^uuid] = TestRepo.all(from p in Post, where: p.uuid == ^uuid, select: p.uuid) # Datetime assert [^datetime] = TestRepo.all(from p in Post, where: p.inserted_at == ^datetime, select: p.inserted_at) end test "tagged types" do TestRepo.insert!(%Post{}) # Numbers assert [1] = TestRepo.all(from Post, select: type(^"1", :integer)) assert [1.0] = TestRepo.all(from Post, select: type(^1.0, :float)) assert [1] = TestRepo.all(from p in Post, select: type(^"1", p.visits)) assert [1.0] = TestRepo.all(from p in Post, select: type(^"1", p.intensity)) # Datetime datetime = {{2014, 04, 17}, {14, 00, 00, 00}} ecto_datetime = %Ecto.DateTime{year: 2014, month: 4, day: 17, hour: 14, min: 0, sec: 0, usec: 0} assert [^ecto_datetime] = TestRepo.all(from Post, select: type(^datetime, Ecto.DateTime)) # Custom wrappers assert [1] = TestRepo.all(from Post, select: type(^"1", Elixir.Custom.Permalink)) # Custom types datetime = %Ecto.DateTime{year: 2014, month: 1, day: 16, hour: 20, min: 26, sec: 51, usec: 0} assert [^datetime] = TestRepo.all(from Post, select: type(^datetime, Ecto.DateTime)) end test "binary id type" do assert %Custom{} = custom = TestRepo.insert!(%Custom{}) bid = custom.bid assert [^bid] = TestRepo.all(from c in Custom, select: c.bid) assert [^bid] = TestRepo.all(from c in Custom, select: type(^bid, :binary_id)) end test "composite types in select" do assert %Post{} = TestRepo.insert!(%Post{title: "1", text: "hai"}) assert [{"1", "hai"}] == TestRepo.all(from p in Post, select: {p.title, p.text}) assert [["1", "hai"]] == TestRepo.all(from p in Post, select: [p.title, p.text]) assert [%{:title => "1", 3 => "hai", "text" => "hai"}] == TestRepo.all(from p in Post, select: %{ :title => p.title, "text" => p.text, 3 => p.text }) assert [%{:title => "1", "1" => "hai", "text" => "hai"}] == TestRepo.all(from p in Post, select: %{ :title => p.title, p.title => p.text, "text" => p.text }) end @tag :array_type test "array type" do ints = [1, 2, 3] tag = TestRepo.insert!(%Tag{ints: ints}) assert TestRepo.all(from t in Tag, where: t.ints == ^[], select: t.ints) == [] assert TestRepo.all(from t in Tag, where: t.ints == ^[1, 2, 3], select: t.ints) == [ints] # Querying assert TestRepo.all(from t in Tag, where: t.ints == [1, 2, 3], select: t.ints) == [ints] assert TestRepo.all(from t in Tag, where: 0 in t.ints, select: t.ints) == [] assert TestRepo.all(from t in Tag, where: 1 in t.ints, select: t.ints) == [ints] # Update tag = TestRepo.update!(Ecto.Changeset.change tag, ints: [3, 2, 1]) assert TestRepo.get!(Tag, tag.id).ints == [3, 2, 1] # Update all {1, _} = TestRepo.update_all(Tag, push: [ints: 0]) assert TestRepo.get!(Tag, tag.id).ints == [3, 2, 1, 0] {1, _} = TestRepo.update_all(Tag, pull: [ints: 2]) assert TestRepo.get!(Tag, tag.id).ints == [3, 1, 0] end @tag :array_type test "array type with custom types" do uuids = ["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"] TestRepo.insert!(%Tag{uuids: ["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"]}) assert TestRepo.all(from t in Tag, where: t.uuids == ^[], select: t.uuids) == [] assert TestRepo.all(from t in Tag, where: t.uuids == ^["51fcfbdd-ad60-4ccb-8bf9-47aabd66d075"], select: t.uuids) == [uuids] end @tag :map_type test "map type" do post1 = TestRepo.insert!(%Post{meta: %{"foo" => "bar", "baz" => "bat"}}) post2 = TestRepo.insert!(%Post{meta: %{foo: "bar", baz: "bat"}}) assert TestRepo.all(from p in Post, where: p.id == ^post1.id, select: p.meta) == [%{"foo" => "bar", "baz" => "bat"}] assert TestRepo.all(from p in Post, where: p.id == ^post2.id, select: p.meta) == [%{"foo" => "bar", "baz" => "bat"}] end @tag :map_type test "map type on update" do post = TestRepo.insert!(%Post{meta: %{"world" => "hello"}}) assert TestRepo.get!(Post, post.id).meta == %{"world" => "hello"} post = TestRepo.update!(Ecto.Changeset.change post, meta: %{hello: "world"}) assert TestRepo.get!(Post, post.id).meta == %{"hello" => "world"} query = from(p in Post, where: p.id == ^post.id) TestRepo.update_all(query, set: [meta: %{world: "hello"}]) assert TestRepo.get!(Post, post.id).meta == %{"world" => "hello"} end @tag :map_type test "embeds one" do item = %Item{price: 123, valid_at: Ecto.Date.utc} order = %Order{} |> Ecto.Changeset.change |> Ecto.Changeset.put_embed(:item, item) order = TestRepo.insert!(order) dbitem = TestRepo.get!(Order, order.id).item assert item.price == dbitem.price assert item.valid_at == dbitem.valid_at assert dbitem.id [dbitem] = TestRepo.all(from o in Order, select: o.item) assert item.price == dbitem.price assert item.valid_at == dbitem.valid_at assert dbitem.id end @tag :map_type @tag :array_type test "embeds many" do item = %Item{price: 123, valid_at: Ecto.Date.utc} tag = %Tag{} |> Ecto.Changeset.change |> Ecto.Changeset.put_embed(:items, [item]) tag = TestRepo.insert!(tag) [dbitem] = TestRepo.get!(Tag, tag.id).items assert item.price == dbitem.price assert item.valid_at == dbitem.valid_at assert dbitem.id [[dbitem]] = TestRepo.all(from t in Tag, select: t.items) assert item.price == dbitem.price assert item.valid_at == dbitem.valid_at assert dbitem.id end @tag :decimal_type test "decimal type" do decimal = Decimal.new("1.0") TestRepo.insert!(%Post{cost: decimal}) assert [^decimal] = TestRepo.all(from p in Post, where: p.cost == ^decimal, select: p.cost) assert [^decimal] = TestRepo.all(from p in Post, where: p.cost == ^1.0, select: p.cost) assert [^decimal] = TestRepo.all(from p in Post, where: p.cost == ^1, select: p.cost) assert [^decimal] = TestRepo.all(from p in Post, where: p.cost == 1.0, select: p.cost) assert [^decimal] = TestRepo.all(from p in Post, where: p.cost == 1, select: p.cost) end end
36.78733
111
0.603567
0308caa5503ef217a91e3790238832626df84300
72
ex
Elixir
lib/helloworld.ex
OliverLeitner/elixirdemo
4d2f9e4908974e99026dd36df2c23a426ee972b7
[ "Apache-2.0" ]
null
null
null
lib/helloworld.ex
OliverLeitner/elixirdemo
4d2f9e4908974e99026dd36df2c23a426ee972b7
[ "Apache-2.0" ]
null
null
null
lib/helloworld.ex
OliverLeitner/elixirdemo
4d2f9e4908974e99026dd36df2c23a426ee972b7
[ "Apache-2.0" ]
null
null
null
defmodule Hello do def sample do IO.puts "Hello World!" end end
12
26
0.680556
0308ec3564ec9868008fbf534604646ca00c1dcf
520
ex
Elixir
lib/wechat/plugs/request_validator.ex
onionch/wechat_elixir
949ac241dbe40036e88b0438f85395bda87f3784
[ "MIT" ]
null
null
null
lib/wechat/plugs/request_validator.ex
onionch/wechat_elixir
949ac241dbe40036e88b0438f85395bda87f3784
[ "MIT" ]
null
null
null
lib/wechat/plugs/request_validator.ex
onionch/wechat_elixir
949ac241dbe40036e88b0438f85395bda87f3784
[ "MIT" ]
null
null
null
defmodule Wechat.Plugs.RequestValidator do @moduledoc false import Plug.Conn import Wechat.Config, only: [token: 0] alias Wechat.Utils.SignatureVerifier def init(opts) do opts end def call(conn, _opts) do conn = fetch_query_params(conn) %{"timestamp" => timestamp, "nonce" => nonce, "signature" => signature} = conn.query_params if SignatureVerifier.verify?([token(), timestamp, nonce], signature) do conn else conn |> send_resp(400, "") |> halt end end end
21.666667
75
0.663462
0308ff8acb0ac398cdb3696f8d29b9014e9c46e0
1,565
ex
Elixir
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/test_iam_permissions_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/test_iam_permissions_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/test_iam_permissions_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.DataCatalog.V1beta1.Model.TestIamPermissionsResponse do @moduledoc """ Response message for `TestIamPermissions` method. ## Attributes * `permissions` (*type:* `list(String.t)`, *default:* `nil`) - A subset of `TestPermissionsRequest.permissions` that the caller is allowed. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :permissions => list(String.t()) } field(:permissions, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DataCatalog.V1beta1.Model.TestIamPermissionsResponse do def decode(value, options) do GoogleApi.DataCatalog.V1beta1.Model.TestIamPermissionsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DataCatalog.V1beta1.Model.TestIamPermissionsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.297872
143
0.752716
030909aabe6e5b3889e4f0d080a64a865117b8ce
767
ex
Elixir
play_web/test/support/channel_case.ex
axelson/scenic_asteroids
20fb22af441028b0837016337c5e418c033ded29
[ "BSD-3-Clause" ]
31
2018-12-25T19:52:35.000Z
2022-03-20T01:06:46.000Z
play_web/test/support/channel_case.ex
axelson/scenic_asteroids
20fb22af441028b0837016337c5e418c033ded29
[ "BSD-3-Clause" ]
4
2018-12-23T18:34:20.000Z
2021-05-10T04:05:45.000Z
play_web/test/support/channel_case.ex
axelson/scenic_asteroids
20fb22af441028b0837016337c5e418c033ded29
[ "BSD-3-Clause" ]
2
2019-04-09T18:35:51.000Z
2020-12-22T15:19:18.000Z
defmodule PlayWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` 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, 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 # Import conveniences for testing with channels use Phoenix.ChannelTest # The default endpoint for testing @endpoint PlayWeb.Endpoint end end setup _tags do :ok end end
23.96875
59
0.724902
030920306af9b3f9364bbee589bf864617047edd
2,168
ex
Elixir
clients/network_connectivity/lib/google_api/network_connectivity/v1/model/linked_interconnect_attachments.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/network_connectivity/lib/google_api/network_connectivity/v1/model/linked_interconnect_attachments.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/network_connectivity/lib/google_api/network_connectivity/v1/model/linked_interconnect_attachments.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.NetworkConnectivity.V1.Model.LinkedInterconnectAttachments do @moduledoc """ A collection of VLAN attachment resources. These resources should be redundant attachments that all advertise the same prefixes to Google Cloud. Alternatively, in active/passive configurations, all attachments should be capable of advertising the same prefixes. ## Attributes * `siteToSiteDataTransfer` (*type:* `boolean()`, *default:* `nil`) - A value that controls whether site-to-site data transfer is enabled for these resources. Data transfer is available only in [supported locations](https://cloud.google.com/network-connectivity/docs/network-connectivity-center/concepts/locations). * `uris` (*type:* `list(String.t)`, *default:* `nil`) - The URIs of linked interconnect attachment resources """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :siteToSiteDataTransfer => boolean() | nil, :uris => list(String.t()) | nil } field(:siteToSiteDataTransfer) field(:uris, type: :list) end defimpl Poison.Decoder, for: GoogleApi.NetworkConnectivity.V1.Model.LinkedInterconnectAttachments do def decode(value, options) do GoogleApi.NetworkConnectivity.V1.Model.LinkedInterconnectAttachments.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.NetworkConnectivity.V1.Model.LinkedInterconnectAttachments do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.36
318
0.761531
03094456d4b811ea0090f7ece1e8df7304c3aadf
4,211
exs
Elixir
test/acceptance/ast/footnotes_test.exs
michaelforrest/earmark_parser
b18245339cbbe2d6bad2431db8b8cf2df9195da9
[ "Apache-2.0" ]
null
null
null
test/acceptance/ast/footnotes_test.exs
michaelforrest/earmark_parser
b18245339cbbe2d6bad2431db8b8cf2df9195da9
[ "Apache-2.0" ]
null
null
null
test/acceptance/ast/footnotes_test.exs
michaelforrest/earmark_parser
b18245339cbbe2d6bad2431db8b8cf2df9195da9
[ "Apache-2.0" ]
null
null
null
defmodule Acceptance.Ast.FootnotesTest do use ExUnit.Case, async: true import Support.Helpers, only: [as_ast: 2] import EarmarkAstDsl describe "Correct Footnotes" do test "plain text" do markdown = "foo[^1] again\n\n[^1]: bar baz" ast = [ {"p", '', [ "foo", {"a", [ {"href", "#fn:1"}, {"id", "fnref:1"}, {"class", "footnote"}, {"title", "see footnote"} ], ["1"], %{}}, " again" ], %{}}, { "div", [{"class", "footnotes"}], [ {"hr", '', '', %{}}, { "ol", '', [ { "li", [{"id", "fn:1"}], [ { "p", '', [ "bar baz", {"a", [ {"class", "reversefootnote"}, {"href", "#fnref:1"}, {"title", "return to article"} ], ["&#x21A9;"], %{}} ], %{} } ], %{} } ], %{} } ], %{} } ] messages = [] assert as_ast(markdown, footnotes: true) == {:ok, ast, messages} end test "A footnote in a list" do markdown = """ * here is a footnote in a list[^1] [^1]: my footnote from the list """ ast = [] # beyond my pay grade... messages = [] assert as_ast(markdown, footnotes: true, pure_links: true) == {:ok, ast, messages} end test "A link inside the footnote" do markdown = """ here is my footnote[^1] [^1]: which [is a link](http://to.some.site) """ ast = [ {"p", [], [ "here is my footnote", {"a", [ {"href", "#fn:1"}, {"id", "fnref:1"}, {"class", "footnote"}, {"title", "see footnote"} ], ["1"], %{}} ], %{}}, {"div", [{"class", "footnotes"}], [ {"hr", [], [], %{}}, {"ol", [], [ {"li", [{"id", "fn:1"}], [ {"p", [], [ "which ", {"a", [{"href", "http://to.some.site"}], ["is a link"], %{}}, {"a", [ {"class", "reversefootnote"}, {"href", "#fnref:1"}, {"title", "return to article"} ], ["&#x21A9;"], %{}} ], %{}} ], %{}} ], %{}} ], %{}} ] messages = [] # as_ast(markdown, footnotes: true, pure_links: true) assert as_ast(markdown, footnotes: true, pure_links: true) == {:ok, ast, messages} end end describe "Incorrect Footnotes" do test "undefined footnotes" do markdown = "foo[^1]\nhello\n\n[^2]: bar baz" ast = p("foo[^1]\nhello") messages = [{:error, 1, "footnote 1 undefined, reference to it ignored"}] assert as_ast(markdown, footnotes: true) == {:error, [ast], messages} end test "undefined footnotes (none at all)" do markdown = "foo[^1]\nhello" ast = p("foo[^1]\nhello") messages = [{:error, 1, "footnote 1 undefined, reference to it ignored"}] assert as_ast(markdown, footnotes: true) == {:error, [ast], messages} end test "illdefined footnotes" do markdown = "foo[^1]\nhello\n\n[^1]:bar baz" ast = [p("foo[^1]\nhello"), p("[^1]:bar baz")] messages = [ {:error, 1, "footnote 1 undefined, reference to it ignored"}, {:error, 4, "footnote 1 undefined, reference to it ignored"} ] assert as_ast(markdown, footnotes: true) == {:error, ast, messages} end end end # SPDX-License-Identifier: Apache-2.0
26.484277
88
0.367371
03094fcfa118d1a4863cd1c494ec30e04cda3635
558
exs
Elixir
priv/repo/migrations/20191027221057_create_workbench_balances.exs
fremantle-industries/back_office
e5aeda7abd72ccffabe5b21f26d48b5c573f9670
[ "MIT" ]
85
2020-05-03T22:23:18.000Z
2022-02-22T14:45:37.000Z
priv/repo/migrations/20191027221057_create_workbench_balances.exs
fremantle-industries/workbench
5d299c77f0271332651b4f0510265f676301a5f3
[ "MIT" ]
101
2020-04-26T03:07:51.000Z
2022-03-27T06:17:52.000Z
priv/repo/migrations/20191027221057_create_workbench_balances.exs
fremantle-capital/back_office
91474fad1bf27d913aecd6b36b898eff5d29a831
[ "MIT" ]
18
2020-04-26T10:57:55.000Z
2022-01-26T01:50:03.000Z
defmodule Workbench.Repo.Migrations.CreateWorkbenchBalances do use Ecto.Migration def change do create table(:balances) do add(:usd, :decimal, null: false) add(:start_time, :utc_datetime, null: false) add(:finish_time, :utc_datetime, null: false) add(:btc_usd_venue, :string, null: false) add(:btc_usd_symbol, :string, null: false) add(:btc_usd_price, :decimal, null: false) add(:usd_quote_venue, :string, null: false) add(:usd_quote_asset, :string, null: false) timestamps() end end end
29.368421
62
0.673835
03095fce3f23f7d26f75513b18b2a57937323264
29
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_addition_operation_parsing_test_case/UnaryNonNumericOperation.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_addition_operation_parsing_test_case/UnaryNonNumericOperation.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_addition_operation_parsing_test_case/UnaryNonNumericOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
!one + not two !one - not two
14.5
14
0.62069
030975da59e9a453d1f99409692d7dabf61c8175
2,673
exs
Elixir
test/foundation/log_test.exs
clangley/foundation
ed75c1adf1f4c9a237056a82f4c7720d87c2458c
[ "MIT" ]
null
null
null
test/foundation/log_test.exs
clangley/foundation
ed75c1adf1f4c9a237056a82f4c7720d87c2458c
[ "MIT" ]
null
null
null
test/foundation/log_test.exs
clangley/foundation
ed75c1adf1f4c9a237056a82f4c7720d87c2458c
[ "MIT" ]
null
null
null
defmodule FoundationTest.Log do use ExUnit.Case alias Foundation.Log test "Bucket Test" do db = :erlfdb_util.get_test_db(empty: true) ledger_events = [ {["bank_account", "sally"], {:deposit, 100}}, {["bank_account", "bob"], {:withdraw, 10}} ] Foundation.trans(db, fn tx -> Enum.each(ledger_events, fn {path, value} -> Log.append(tx, path, value) end) end) # Return should be something like this for reference # [ # {["bank_account", "bob", {:versionstamp, _, _, _}], {:withdraw, 100}}, # {["bank_account", "sally", {:versionstamp, _, _, _}], {:deposit, 100}}, # ] # Given that string "bob" is before string "sally", the keys are sorted in FDB and thus returned in that exact order Foundation.trans(db, fn tx -> [bob, sally] = Log.since(tx, ["bank_account"]) assert match?({["bank_account", "bob", {:versionstamp, _, _, _}], {:withdraw, 10}}, bob) assert match?({["bank_account", "sally", {:versionstamp, _, _, _}], {:deposit, 100}}, sally) assert [bob] == Log.before(tx, ["bank_account", "sally"]) end) end test "Simple log" do db = :erlfdb_util.get_test_db(empty: true) Foundation.trans(db, fn tx -> Log.append(tx, ["a", 1], 1, version: false) Log.append(tx, ["a", 6], 1, version: false) Log.append(tx, ["a", 123], 1, version: false) Log.append(tx, ["b", 123_023], 1, version: false) Log.append(tx, ["c", "a"], 1, version: false) Log.append(tx, ["d", true], 1, version: false) Log.append(tx, ["e", false], 1, version: false) end) Foundation.trans(db, fn tx -> assert Log.before(tx, ["b"]) == [{["a", 123], 1}, {["a", 6], 1}, {["a", 1], 1}] assert Log.since(tx, ["c"]) == [{["c", "a"], 1}] end) end test "Since" do db = :erlfdb_util.get_test_db(empty: true) Foundation.trans(db, fn tx -> Log.append(tx, ["bank_account", "bob"], 100) Log.append(tx, ["bank_account", "bob"], 101) Log.append(tx, ["bank_account", "bob"], 102) Log.append(tx, ["bank_account", "bob"], 103) Log.append(tx, ["bank_account", "bob"], 104) Log.append(tx, ["bank_account", "bp"], 666) end) Foundation.trans(db, fn tx -> assert length(Log.since(tx, ["bank_account", "bob"])) == 5 # [{["bank_account", "bob", {:versionstamp, 4737478030, 0, 0}], 100}] [{key, v}] = Log.since(tx, ["bank_account", "bob"], limit: 1) assert v == 100 assert Enum.map(Log.since(tx, key, limit: 100), &elem(&1, 1)) == [ 101, 102, 103, 104 ] end) end end
32.597561
120
0.548447
03097858a8e639531f6e63d976bf65c32f66cef6
1,002
exs
Elixir
apps/mishka_api/config/config.exs
mojtaba-naserei/mishka-cms
1f31f61347bab1aae6ba0d47c5515a61815db6c9
[ "Apache-2.0" ]
35
2021-06-26T09:05:50.000Z
2022-03-30T15:41:22.000Z
apps/mishka_api/config/config.exs
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
101
2021-01-01T09:54:07.000Z
2022-03-28T10:02:24.000Z
apps/mishka_api/config/config.exs
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
8
2021-01-17T17:08:07.000Z
2022-03-11T16:12:06.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration use Mix.Config # Configures the endpoint # config :mishka_api, MishkaApiWeb.Endpoint, # url: [host: "localhost"], # secret_key_base: "qP5c9diga3k115/empFNEEi/fgwXkhArZvpvFaiLqdi3Um1ntPh0P2AkleLzEpzY", # render_errors: [view: MishkaApiWeb.ErrorView, accepts: ~w(json), layout: false], # pubsub_server: MishkaApi.PubSub, # live_view: [signing_salt: "e1v5FAl7"] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # 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"
34.551724
88
0.764471
03097fb9e511af3e0bdeac3ef8d5d6f312703655
192
ex
Elixir
example/lib/phoenix_datatables_example_web/controllers/page_controller.ex
JohnKacz/phoenix_datatables
747b184972614d87aeb0cd644593951703d718db
[ "MIT" ]
null
null
null
example/lib/phoenix_datatables_example_web/controllers/page_controller.ex
JohnKacz/phoenix_datatables
747b184972614d87aeb0cd644593951703d718db
[ "MIT" ]
null
null
null
example/lib/phoenix_datatables_example_web/controllers/page_controller.ex
JohnKacz/phoenix_datatables
747b184972614d87aeb0cd644593951703d718db
[ "MIT" ]
null
null
null
defmodule PhoenixDatatablesExampleWeb.PageController do use PhoenixDatatablesExampleWeb, :controller def index(conn, _params) do redirect(conn, to: item_path(conn, :index)) end end
24
55
0.786458
0309a7a97e56ab127868c58c0540f50905666be0
1,905
ex
Elixir
clients/app_engine/lib/google_api/app_engine/v1/model/file_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/app_engine/lib/google_api/app_engine/v1/model/file_info.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/app_engine/lib/google_api/app_engine/v1/model/file_info.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.AppEngine.V1.Model.FileInfo do @moduledoc """ Single source file that is part of the version to be deployed. Each source file that is deployed must be specified separately. ## Attributes * `mimeType` (*type:* `String.t`, *default:* `nil`) - The MIME type of the file.Defaults to the value from Google Cloud Storage. * `sha1Sum` (*type:* `String.t`, *default:* `nil`) - The SHA1 hash of the file, in hex. * `sourceUrl` (*type:* `String.t`, *default:* `nil`) - URL source to use to fetch this file. Must be a URL to a resource in Google Cloud Storage in the form 'http(s)://storage.googleapis.com//'. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :mimeType => String.t(), :sha1Sum => String.t(), :sourceUrl => String.t() } field(:mimeType) field(:sha1Sum) field(:sourceUrl) end defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.FileInfo do def decode(value, options) do GoogleApi.AppEngine.V1.Model.FileInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.FileInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.943396
198
0.710236
0309b280c8c51550d4b1fb8ebfb5bb09a70de0ec
4,046
ex
Elixir
lib/hand.ex
pkhodakovsky/elixir-poker-game
4191283f31b236d311e412c37045ad5d4fdc4f9e
[ "MIT" ]
null
null
null
lib/hand.ex
pkhodakovsky/elixir-poker-game
4191283f31b236d311e412c37045ad5d4fdc4f9e
[ "MIT" ]
null
null
null
lib/hand.ex
pkhodakovsky/elixir-poker-game
4191283f31b236d311e412c37045ad5d4fdc4f9e
[ "MIT" ]
null
null
null
defmodule Hand do @moduledoc """ A single poker hand of cards. """ def name(hand) do cond do Hand.is_straight_flush_ace_high(hand) -> "straight flush" Hand.is_straight_flush_ace_low(hand) -> "straight flush" Hand.is_four_of_a_kind(hand) -> "four of a kind" Hand.is_full_house(hand) -> "full house" Hand.is_flush(hand) -> "flush" Hand.is_straight_ace_high(hand) -> "straight" Hand.is_straight_ace_low(hand) -> "straight" Hand.is_three_of_a_kind(hand) -> "three of a kind" Hand.is_two_pair(hand) -> "two pair" Hand.is_pair(hand) -> "pair" Hand.is_high_card(hand) -> "high card" end end def format(hand) do Enum.map(hand, fn card -> Card.format(card) end) |> Enum.join(" ") end def parse(hand) do card_codes = String.split(hand, " ") Enum.map(card_codes, fn card -> Card.parse(card) end) end def winner(hand1, hand2) do rank1 = Rank.rank(hand1) rank2 = Rank.rank(hand2) cond do rank1 > rank2 -> hand1 rank1 < rank2 -> hand2 true -> false end end # # Hand identification # # Input: [[:heart, :seven], [:club, :seven], [:diamond, :two], [:spade, :seven], [:diamond, :three]] # def is_high_card(_) do true end @doc "Pair: 2 of the 5 cards in the hand have the same value." def is_pair(hand) do Enum.group_by(hand, fn [_, face] -> face end) |> Enum.find(fn {_, cards} -> length(cards) == 2 end) end @doc "Two Pairs: The hand contains 2 different pairs." def is_two_pair(hand) do 2 == Enum.group_by(hand, fn [_, face] -> face end) |> Enum.filter(fn {_, cards} -> length(cards) == 2 end) |> length end @doc "Three of a Kind: Three of the cards in the hand have the same value." def is_three_of_a_kind(hand) do Enum.group_by(hand, fn [_, face] -> face end) |> Enum.filter(fn {_, cards} -> length(cards) == 3 end) |> Enum.empty?() == false end @doc "Straight: Hand contains 5 cards with consecutive values. ace high" def is_straight_ace_high(hand) do Enum.sort(hand, fn [_, face1], [_, face2] -> Card.rank(face1, :ace) < Card.rank(face2, :ace) end) |> face_differences(:ace) == [1, 1, 1, 1] end @doc "Straight: Hand contains 5 cards with consecutive values. ace low" def is_straight_ace_low(hand) do Enum.sort(hand, fn [_, face1], [_, face2] -> Card.rank(face1, :ace_low) < Card.rank(face2, :ace_low) end) |> face_differences(:ace_low) == [1, 1, 1, 1] end defp face_differences(cards, ace) do face_differences(cards, [], ace) end defp face_differences([_ | []], differences, _), do: differences defp face_differences([last_card | remaining_cards], differences, ace) do next_card = hd(remaining_cards) last_value = String.to_integer(Card.rank(last_card, ace)) next_value = String.to_integer(Card.rank(next_card, ace)) differences = differences ++ [next_value - last_value] face_differences(remaining_cards, differences, ace) end @doc "Flush: Hand contains 5 cards of the same suit" def is_flush(hand) do 1 == Enum.group_by(hand, fn [suit, _] -> suit end) |> Map.size() end @doc "Full House: 3 cards of the same value, with the remaining 2 cards forming a pair." def is_full_house(hand) do face_group([2, 3], hand) end @doc "Four of a kind: 4 cards with the same value" def is_four_of_a_kind(hand) do face_group([1, 4], hand) end defp face_group(members, hand) do by_face = Enum.group_by(hand, fn [_, face] -> face end) Map.size(by_face) == 2 && Enum.count(by_face, fn {_, cards} -> Enum.member?(members, length(cards)) end) == 2 end @doc "Straight flush: 5 cards of the same suit with consecutive values" def is_straight_flush_ace_high(hand) do is_straight_ace_high(hand) && is_flush(hand) end @doc "Straight flush: 5 cards of the same suit with consecutive values" def is_straight_flush_ace_low(hand) do is_straight_ace_low(hand) && is_flush(hand) end end
29.107914
104
0.645823
0309b6f6fcd01d759e11e12953b1d22af48ae1c7
708
ex
Elixir
discuss/lib/discuss_web/gettext.ex
ivoferro/elixir_phoenix_bootcamp
e3445dbf90c1eea81e8aa34cc7801934a516d7d7
[ "MIT" ]
null
null
null
discuss/lib/discuss_web/gettext.ex
ivoferro/elixir_phoenix_bootcamp
e3445dbf90c1eea81e8aa34cc7801934a516d7d7
[ "MIT" ]
null
null
null
discuss/lib/discuss_web/gettext.ex
ivoferro/elixir_phoenix_bootcamp
e3445dbf90c1eea81e8aa34cc7801934a516d7d7
[ "MIT" ]
null
null
null
defmodule DiscussWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import DiscussWeb.Gettext # Simple translation gettext "Here is the string to translate" # Plural translation ngettext "Here is the string to translate", "Here are the strings to translate", 3 # Domain-based translation dgettext "errors", "Here is the error message to translate" See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :discuss end
28.32
72
0.680791
0309d1a7d6be417a2620a8f82bc4ab956f35980e
4,041
ex
Elixir
lib/simple_pool/v2/behaviours/service_management_behaviour.ex
noizu/simple_pool
59251a3391ff82152a31626072955b95f83c18ee
[ "MIT" ]
12
2018-07-03T10:14:54.000Z
2020-04-07T02:04:39.000Z
lib/simple_pool/v2/behaviours/service_management_behaviour.ex
noizu/simple_pool
59251a3391ff82152a31626072955b95f83c18ee
[ "MIT" ]
1
2018-12-02T06:05:59.000Z
2018-12-02T06:05:59.000Z
lib/simple_pool/v2/behaviours/service_management_behaviour.ex
noizu/simple_pool
59251a3391ff82152a31626072955b95f83c18ee
[ "MIT" ]
2
2018-03-05T12:01:51.000Z
2018-07-03T10:15:04.000Z
#------------------------------------------------------------------------------- # Author: Keith Brings # Copyright (C) 2019 Noizu Labs, Inc. All rights reserved. #------------------------------------------------------------------------------- defmodule Noizu.SimplePool.V2.ServiceManagementBehaviour do require Logger @callback default_definition() :: any @callback enable_server!(any) :: any @callback disable_server!(any) :: any @callback status(any) :: any @callback load_pool(any, any) :: any @callback load_complete(any, any, any) :: any @callback load_begin(any, any, any) :: any @callback status_wait(any, any, any) :: any @callback entity_status(any, any) :: any @callback server_kill!(any, any) :: any @callback service_health_check!(any) :: any @callback service_health_check!(any, any) :: any @callback service_health_check!(any, any, any) :: any @callback record_service_event!(any, any, any, any) :: any defmodule DefaultProvider do defmacro __using__(_options) do quote do require Logger @behaviour Noizu.SimplePool.V2.ServiceManagementBehaviour @pool_server Module.split(__MODULE__) |> Enum.slice(0..-2) |> Module.concat() alias Noizu.SimplePool.V2.Server.State, as: ServerState alias Noizu.SimplePool.Server.EnvironmentDetails alias Noizu.SimplePool.V2.ServiceManagement.ServiceManagementProvider, as: Provider @doc """ """ def default_definition(), do: Provider.default_definition(@pool_server) @doc """ """ def enable_server!(node), do: Provider.enable_server!(@pool_server, node) @doc """ """ def disable_server!(node), do: Provider.disable_server!(@pool_server, node) @doc """ """ def status(args \\ {}, context \\ nil), do: Provider.status(@pool_server, args, context) @doc """ """ def load_pool(args \\ {}, context \\ nil, options \\ nil), do: Provider.load_pool(@pool_server, args, context, options) @doc """ """ def load_complete(this, process, context), do: Provider.load_complete(@pool_server, this, process, context) @doc """ """ def load_begin(this, process, context), do: Provider.load_begin(@pool_server, this, process, context) @doc """ """ def status_wait(target_state, context, timeout \\ :infinity), do: Provider.status_wait(@pool_server, target_state, context, timeout) @doc """ """ def entity_status(context, options \\ %{}), do: Provider.entity_status(@pool_server, context, options) @doc """ """ def server_kill!(args \\ {}, context \\ nil, options \\ %{}), do: Provider.server_kill!(@pool_server, args, context, options) @doc """ """ def service_health_check!(%Noizu.ElixirCore.CallingContext{} = context), do: Provider.service_health_check!(@pool_server, context) def service_health_check!(health_check_options, %Noizu.ElixirCore.CallingContext{} = context), do: Provider.service_health_check!(@pool_server, health_check_options, context) def service_health_check!(health_check_options, %Noizu.ElixirCore.CallingContext{} = context, options), do: Provider.service_health_check!(@pool_server, health_check_options, context, options) @doc """ """ def record_service_event!(event, details, context, options), do: Provider.record_service_event!(@pool_server, event, details, context, options) defoverridable [ default_definition: 0, enable_server!: 1, disable_server!: 1, status: 1, load_pool: 2, load_complete: 3, load_begin: 3, status_wait: 3, entity_status: 2, server_kill!: 2, service_health_check!: 1, service_health_check!: 2, service_health_check!: 3, record_service_event!: 4, ] end end end end
31.818898
200
0.611235
0309f3bb97bad039864b3b0ea2c455021c95bd3b
1,115
ex
Elixir
lib/noven/application.ex
ConnorRigby/noven
2c34953490585b77b6c7ae8dd772da5028f6a948
[ "Apache-2.0" ]
8
2020-09-10T09:18:17.000Z
2022-03-25T03:43:25.000Z
lib/noven/application.ex
ConnorRigby/noven
2c34953490585b77b6c7ae8dd772da5028f6a948
[ "Apache-2.0" ]
null
null
null
lib/noven/application.ex
ConnorRigby/noven
2c34953490585b77b6c7ae8dd772da5028f6a948
[ "Apache-2.0" ]
4
2020-12-28T06:13:51.000Z
2021-04-27T18:00:06.000Z
defmodule Noven.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Ecto repository Noven.Repo, # Start the Telemetry supervisor NovenWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Noven.PubSub}, Noven.DevicePresence, {Registry, [keys: :unique, name: NovenMedia.NameRegistry]}, NovenMedia.Supervisor, # Start the Endpoint (http/https) NovenWeb.Endpoint # Start a worker by calling: Noven.Worker.start_link(arg) # {Noven.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Noven.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do NovenWeb.Endpoint.config_change(changed, removed) :ok end end
29.342105
65
0.69417
0309f5c740a2aae5de41bd9b8c0772de2b883dbb
736
ex
Elixir
oeml-sdk/elixir/lib/oeml_restapi/model/message.ex
oskaralfons/coinapi-sdk
2c79b6d91d0f702040dd865e79f0774a4bba9bb3
[ "MIT" ]
1
2020-07-23T05:47:52.000Z
2020-07-23T05:47:52.000Z
oeml-sdk/elixir/lib/oeml_restapi/model/message.ex
oskaralfons/coinapi-sdk
2c79b6d91d0f702040dd865e79f0774a4bba9bb3
[ "MIT" ]
null
null
null
oeml-sdk/elixir/lib/oeml_restapi/model/message.ex
oskaralfons/coinapi-sdk
2c79b6d91d0f702040dd865e79f0774a4bba9bb3
[ "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 OEML-RESTAPI.Model.Message do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"type", :"severity", :"exchange_id", :"message" ] @type t :: %__MODULE__{ :"type" => String.t | nil, :"severity" => Severity | nil, :"exchange_id" => String.t | nil, :"message" => String.t | nil } end defimpl Poison.Decoder, for: OEML-RESTAPI.Model.Message do import OEML-RESTAPI.Deserializer def decode(value, options) do value |> deserialize(:"severity", :struct, OEML-RESTAPI.Model.Severity, options) end end
21.647059
91
0.649457
030a0a76fc836eff3fe4f7b72b49649d55654d38
604
exs
Elixir
yaki_core/mix.exs
aaripurna/yaki
42bd854d72799de748b2171badb1d047952973f1
[ "MIT" ]
null
null
null
yaki_core/mix.exs
aaripurna/yaki
42bd854d72799de748b2171badb1d047952973f1
[ "MIT" ]
null
null
null
yaki_core/mix.exs
aaripurna/yaki
42bd854d72799de748b2171badb1d047952973f1
[ "MIT" ]
null
null
null
defmodule YakiCore.MixProject do use Mix.Project def project do [ app: :yaki_core, version: "0.1.0", elixir: "~> 1.12", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:mogrify, "~> 0.9.1"} # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end end
20.133333
87
0.567881
030a5a31ab0eeb30be8e0e98c1151d184d58b1d7
2,006
ex
Elixir
lib/odd_job/job.ex
msimonborg/odd_job
99c662b21e7a6ed34ebae6bdd79cb6ad997e9724
[ "MIT" ]
3
2022-02-01T13:49:51.000Z
2022-02-04T05:56:34.000Z
lib/odd_job/job.ex
msimonborg/odd_job
99c662b21e7a6ed34ebae6bdd79cb6ad997e9724
[ "MIT" ]
null
null
null
lib/odd_job/job.ex
msimonborg/odd_job
99c662b21e7a6ed34ebae6bdd79cb6ad997e9724
[ "MIT" ]
null
null
null
defmodule OddJob.Job do @moduledoc """ The `OddJob.Job` struct holds all of the useful information about a job. """ @moduledoc since: "0.1.0" @spec __struct__ :: OddJob.Job.t() defstruct [:ref, :owner, :function, :results, :proxy, async: false] @typedoc """ The `OddJob.Job` struct is the datatype that is passed between processes charged with performing the job. It holds all of the data that is necessary to link, monitor, perform work, and return results to the caller. The job struct is only returned to the caller when using the async/await pattern. When the caller receives the struct after calling `OddJob.async_perform/2` the `:results` field is always `nil`, even though the work could conceivably already be done. This is because the results are not waited on at the time the struct is created. The results are only known when passing the job to `OddJob.await/2` or matching on the `{ref, results}` message. * `:function` is the anonymous function that will be performed by the worker * `:results` is the term that is returned by `function`. This is only used internally by the processes performing the work. * `:async` is an boolean identifying if the job's results can be awaited on * `:ref` is the unique monitor reference of the job * `:owner` is the pid of the calling process, i.e. `self()` * `:proxy` is the `pid` of the proxy server that creates the job and routes the results. The `owner` links and monitors the `proxy`, while the `proxy` links and monitors the worker. Exit messages and failures cascade up to the `owner`. The worker sends results back to the `proxy`, which then sends them to the `owner` before exiting with reason `:normal`. """ @typedoc since: "0.1.0" @type t :: %__MODULE__{ async: boolean, ref: reference | nil, owner: pid | nil, proxy: pid | nil, function: function | nil, results: term | nil } end
40.938776
113
0.684447
030a6197d92af8935eae1b1f4774ad51be315812
1,154
ex
Elixir
lib/web/controllers/api/document_controller.ex
jennstein2017/Challenge_gov
e0820df8b124a32ff8b78cb827ae43551492988b
[ "CC0-1.0" ]
9
2020-02-26T20:24:38.000Z
2022-03-22T21:14:52.000Z
lib/web/controllers/api/document_controller.ex
jennstein2017/Challenge_gov
e0820df8b124a32ff8b78cb827ae43551492988b
[ "CC0-1.0" ]
15
2020-04-22T19:33:24.000Z
2022-03-26T15:11:17.000Z
lib/web/controllers/api/document_controller.ex
jennstein2017/Challenge_gov
e0820df8b124a32ff8b78cb827ae43551492988b
[ "CC0-1.0" ]
4
2020-04-27T22:58:57.000Z
2022-01-14T13:42:09.000Z
defmodule Web.Api.DocumentController do use Web, :controller alias ChallengeGov.Challenges alias ChallengeGov.SupportingDocuments alias Web.ErrorView action_fallback(Web.FallbackController) def create(conn, %{"challenge_id" => challenge_id, "document" => params}) do with {:ok, challenge} <- Challenges.get(challenge_id), {:ok, document} <- SupportingDocuments.upload(challenge.user, params), {:ok, document} <- SupportingDocuments.attach_to_challenge( document, challenge, Map.get(params, "section"), Map.get(params, "name") ) do conn |> put_status(:ok) |> assign(:document, document) |> render("show.json") else _error -> conn |> put_status(:unprocessable_entity) |> put_view(ErrorView) |> render("errors.json") end end def delete(conn, %{"id" => id}) do with {:ok, document} <- SupportingDocuments.get(id), {:ok, _document} <- SupportingDocuments.delete(document) do conn |> put_status(:ok) |> render("delete.json") end end end
27.47619
79
0.602253
030a8b56d8d76bcbba032a4790bf67172e8f3c35
1,809
exs
Elixir
mix.exs
codelation/elixir-messenger
4d83e5dd3de5331a771e0960c9613336fe6be90b
[ "MIT" ]
null
null
null
mix.exs
codelation/elixir-messenger
4d83e5dd3de5331a771e0960c9613336fe6be90b
[ "MIT" ]
null
null
null
mix.exs
codelation/elixir-messenger
4d83e5dd3de5331a771e0960c9613336fe6be90b
[ "MIT" ]
null
null
null
defmodule CodelationMessenger.Mixfile do use Mix.Project def project do [app: :codelation_messenger, name: "Codelation Messenger", description: description(), package: package(), source_url: "https://github.com/codelation/elixir-messenger", version: "0.1.1", elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps()] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do # Specify extra applications you'll use from Erlang/Elixir [ extra_applications: [:logger, :cowboy, :plug, :httpoison] ] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # To depend on another app inside the umbrella: # # {:my_app, in_umbrella: true} # # Type "mix help deps" for more examples and options defp deps do [ {:cowboy, ">= 1.0.0"}, {:plug, "~> 1.3"}, {:httpoison, "0.11.1"}, {:poison, "~> 3.1"}, {:ex_doc, ">= 0.0.0", only: :dev} ] end defp description do """ Simple HTTP/HTTPS message handler for running tasks from other apps. Used in combination to the Ruby Gem Codelation Messenger. This allows for both async and sync message sending between the apps for use on Heroku. """ end defp package do # These are the default files included in the package [ name: :codelation_messenger, files: ["lib", "mix.exs", "README*", "LICENSE*"], maintainers: ["Jake Humphrey"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/codelation/elixir-messenger"} ] end end
26.602941
131
0.616363
030aa64c03f985c78da88a6e3b5d189f045b8089
2,140
ex
Elixir
lib/versioned/absinthe.ex
rossvz/versioned
22fd40ce7833d0ede80ac9c3dd2e2b8482b50322
[ "MIT" ]
null
null
null
lib/versioned/absinthe.ex
rossvz/versioned
22fd40ce7833d0ede80ac9c3dd2e2b8482b50322
[ "MIT" ]
null
null
null
lib/versioned/absinthe.ex
rossvz/versioned
22fd40ce7833d0ede80ac9c3dd2e2b8482b50322
[ "MIT" ]
null
null
null
defmodule Versioned.Absinthe do @moduledoc """ Helpers for Absinthe schemas. """ @doc """ Declare an object, versioned compliment, and interface, based off name `name`. The caller should `use Absinthe.Schema.Notation` as here we return code which invokes its `object` macro. Both objects belong to an interface which encompasses the common fields. All common fields (except `:id` and `:inserted_at`) are included under an interface, named by the entity name and suffixed `_base`. The generated object will have the following fields: * `:id` - ID of the record. * `:version_id` - ID of the most recent record's version. * `:inserted_at` - Timestamp when the record was created. * `:updated_at` - Timestamp when the record was last updated. * Additionally, all fields declared in the block. The generated version object will have the following fields: * `:id` - ID of the version record. * `:foo_id` - If the entity was `:foo`, then this would be the id of the main record for which this version is based. * `:is_deleted` - Boolean indicating if the record was deleted as of this version. * `:inserted_at` - Timestamp when the version record was created. * Additionally, all fields declared in the block. """ defmacro versioned_object(name, do: block) do quote do object unquote(name) do field :id, non_null(:id) field :version_id, :id field :inserted_at, non_null(:datetime) field :updated_at, non_null(:datetime) unquote(block) interface(unquote(:"#{name}_base")) end object unquote(:"#{name}_version") do field :id, non_null(:id) field unquote(:"#{name}_id"), :id field :is_deleted, :boolean field :inserted_at, :datetime unquote(block) interface(unquote(:"#{name}_base")) end interface unquote(:"#{name}_base") do unquote(block) resolve_type(fn %{version_id: _}, _ -> unquote(name) %{unquote(:"#{name}_id") => _}, _ -> unquote(:"#{name}_version") _, _ -> nil end) end end end end
32.923077
84
0.65
030ac4bec345b6674d0c6555a7d5859a62ec21aa
226
ex
Elixir
lib/apus/adapters/local_adapter.ex
deniskulicek/apus
be40b09a5507a56feee87d98d68d8720826f5bda
[ "MIT" ]
null
null
null
lib/apus/adapters/local_adapter.ex
deniskulicek/apus
be40b09a5507a56feee87d98d68d8720826f5bda
[ "MIT" ]
null
null
null
lib/apus/adapters/local_adapter.ex
deniskulicek/apus
be40b09a5507a56feee87d98d68d8720826f5bda
[ "MIT" ]
null
null
null
defmodule Apus.LocalAdapter do @moduledoc """ """ @behaviour Apus.Adapter alias Apus.SentMessages def deliver(message, _config) do SentMessages.push(message) end def handle_config(config), do: config end
15.066667
39
0.716814
030acd78cc8a2df3d9d09de1878ecdd5c5696492
1,570
ex
Elixir
web/controllers/admin_controller.ex
8thlight/ex_admin
314d4068270c47799ec54f719073a565222bcfad
[ "MIT" ]
1
2018-08-30T20:20:56.000Z
2018-08-30T20:20:56.000Z
web/controllers/admin_controller.ex
8thlight/ex_admin
314d4068270c47799ec54f719073a565222bcfad
[ "MIT" ]
null
null
null
web/controllers/admin_controller.ex
8thlight/ex_admin
314d4068270c47799ec54f719073a565222bcfad
[ "MIT" ]
null
null
null
defmodule ExAdmin.AdminController do @moduledoc false use ExAdmin.Web, :controller require Logger plug :set_theme plug :set_layout def page(conn, params) do page = Map.get(params, "page", "dashboard") defn = get_registered_by_controller_route!(conn, page) conn = assign(conn, :defn, defn) contents = defn.__struct__.page_view(conn) render(conn, "admin.html", html: contents, resource: nil, scope_counts: [], filters: (if false in defn.index_filters, do: false, else: defn.index_filters)) end def dashboard(conn, params) do page(conn, Map.put(params, "page", "dashboard")) end def select_theme(conn, %{"id" => id} = params) do {id, _} = Integer.parse(id) {_, theme} = Application.get_env(:ex_admin, :theme_selector, []) |> Enum.at(id) loc = Map.get(params, "loc", admin_path()) |> URI.parse |> Map.get(:path) Application.put_env :ex_admin, :theme, theme redirect conn, to: loc end def switch_user(conn, %{"id" => id} = params) do {id, _} = Integer.parse(id) current_user = ExAdmin.Authentication.current_user(conn) repo = Application.get_env(:ex_admin, :repo) user = repo.get current_user.__struct__, id require Logger loc = Map.get(params, "loc", admin_path()) |> URI.parse |> Map.get(:path) {mod, fun} = Application.get_env :ex_admin, :logout_user apply mod, fun, [conn] conn = conn |> assign(:current_user, user) {mod, fun} = Application.get_env :ex_admin, :login_user apply(mod, fun, [conn, user, params]) |> redirect(to: loc) end end
33.404255
85
0.663057
030adc48e017f4075cfaf265a17c6fb2c1c92dc1
321
exs
Elixir
test/test_helper.exs
rebpdx/eeyeore
944ddbfe8fafd67137658948c03492baa340d4de
[ "MIT" ]
2
2021-11-17T17:16:17.000Z
2021-12-08T04:39:42.000Z
test/test_helper.exs
rebpdx/eeyeore
944ddbfe8fafd67137658948c03492baa340d4de
[ "MIT" ]
null
null
null
test/test_helper.exs
rebpdx/eeyeore
944ddbfe8fafd67137658948c03492baa340d4de
[ "MIT" ]
null
null
null
# Used as a mock GenServer to catch casts defmodule ProcessGenServerCasts do def init(state) do {:ok, state} end def handle_cast(message, _) do {:noreply, message} end end ExUnit.start() Mox.defmock(Tortoise.BaseMock, for: Tortoise.Base) Application.put_env(:eeyeore, :mqtt_client, Tortoise.BaseMock)
18.882353
62
0.735202
030b012e207a4a018c8474c4824c8d24256b91eb
2,514
exs
Elixir
test/wanikani/review_statistic_test.exs
eltercero/wanikani
5ed47f315ee9800ab5dbbc21848a337d24d52778
[ "MIT" ]
2
2018-01-29T02:02:05.000Z
2018-07-09T18:24:28.000Z
test/wanikani/review_statistic_test.exs
eltercero/wanikani
5ed47f315ee9800ab5dbbc21848a337d24d52778
[ "MIT" ]
null
null
null
test/wanikani/review_statistic_test.exs
eltercero/wanikani
5ed47f315ee9800ab5dbbc21848a337d24d52778
[ "MIT" ]
null
null
null
defmodule Wanikani.ReviewStatisticTest do use ExUnit.Case defmodule MockApi do def request(_params, _paths) do {:ok, %{"data" => [%{"data" => %{"created_at" => "2017-04-20T21:31:10.806649Z", "meaning_correct" => 11, "meaning_current_streak" => 11, "meaning_incorrect" => 1, "meaning_max_streak" => 11, "percentage_correct" => 92, "reading_correct" => 11, "reading_current_streak" => 3, "reading_incorrect" => 1, "reading_max_streak" => 8, "subject_id" => 1377, "subject_type" => "kanji"}, "data_updated_at" => "2017-11-28T07:55:20.016831Z", "id" => 411994, "object" => "review_statistic", "url" => "https://www.wanikani.com/api/v2/review_statistics/411994"}, %{"data" => %{"created_at" => "2017-04-07T21:34:57.751344Z", "meaning_correct" => 14, "meaning_current_streak" => 1, "meaning_incorrect" => 4, "meaning_max_streak" => 6, "percentage_correct" => 85, "reading_correct" => 14, "reading_current_streak" => 14, "reading_incorrect" => 1, "reading_max_streak" => 14, "subject_id" => 1339, "subject_type" => "kanji"}, "data_updated_at" => "2017-11-28T07:53:56.674025Z", "id" => 412199, "object" => "review_statistic", "url" => "https://www.wanikani.com/api/v2/review_statistics/412199"}]}} end def request(_path) do {:ok, %{"data" => %{"created_at" => "2017-04-07T21:34:57.751344Z", "meaning_correct" => 14, "meaning_current_streak" => 1, "meaning_incorrect" => 4, "meaning_max_streak" => 6, "percentage_correct" => 85, "reading_correct" => 14, "reading_current_streak" => 14, "reading_incorrect" => 1, "reading_max_streak" => 14, "subject_id" => 1339, "subject_type" => "kanji"}, "data_updated_at" => "2017-11-28T07:53:56.674025Z", "id" => 412199, "object" => "review_statistic", "url" => "https://www.wanikani.com/api/v2/review_statistics/412199"}} end end test ".list" do params = %{subject_type: "kanji"} {status, body} = Wanikani.ReviewStatistic.list(params, MockApi) assert :ok == status assert 2 == Enum.count(body["data"]) end test ".get" do {status, body} = Wanikani.ReviewStatistic.get(412199, MockApi) assert :ok == status assert "https://www.wanikani.com/api/v2/review_statistics/412199" == body["url"] end end
44.105263
84
0.584726
030b017f588df34382006dd66744a33474186307
218
ex
Elixir
lib/phone/ba.ex
net/phone
18e1356d2f8d32fe3f95638c3c44bceab0164fb2
[ "Apache-2.0" ]
null
null
null
lib/phone/ba.ex
net/phone
18e1356d2f8d32fe3f95638c3c44bceab0164fb2
[ "Apache-2.0" ]
null
null
null
lib/phone/ba.ex
net/phone
18e1356d2f8d32fe3f95638c3c44bceab0164fb2
[ "Apache-2.0" ]
null
null
null
defmodule Phone.BA do @moduledoc false use Helper.Country def regex, do: ~r/^(387)(..)(.{5,6})/ def country, do: "Bosnia and Herzegovina" def a2, do: "BA" def a3, do: "BIH" matcher :regex, ["387"] end
16.769231
43
0.610092
030b0c4f1f23cb5f2a09c1a4f7e7b6ff08190b9f
2,795
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/public_delegated_prefix_public_delegated_sub_prefix.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/public_delegated_prefix_public_delegated_sub_prefix.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/public_delegated_prefix_public_delegated_sub_prefix.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.Compute.V1.Model.PublicDelegatedPrefixPublicDelegatedSubPrefix do @moduledoc """ Represents a sub PublicDelegatedPrefix. ## Attributes * `delegateeProject` (*type:* `String.t`, *default:* `nil`) - Name of the project scoping this PublicDelegatedSubPrefix. * `description` (*type:* `String.t`, *default:* `nil`) - An optional description of this resource. Provide this property when you create the resource. * `ipCidrRange` (*type:* `String.t`, *default:* `nil`) - The IPv4 address range, in CIDR format, represented by this sub public delegated prefix. * `isAddress` (*type:* `boolean()`, *default:* `nil`) - Whether the sub prefix is delegated to create Address resources in the delegatee project. * `name` (*type:* `String.t`, *default:* `nil`) - The name of the sub public delegated prefix. * `region` (*type:* `String.t`, *default:* `nil`) - [Output Only] The region of the sub public delegated prefix if it is regional. If absent, the sub prefix is global. * `status` (*type:* `String.t`, *default:* `nil`) - [Output Only] The status of the sub public delegated prefix. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :delegateeProject => String.t() | nil, :description => String.t() | nil, :ipCidrRange => String.t() | nil, :isAddress => boolean() | nil, :name => String.t() | nil, :region => String.t() | nil, :status => String.t() | nil } field(:delegateeProject) field(:description) field(:ipCidrRange) field(:isAddress) field(:name) field(:region) field(:status) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.PublicDelegatedPrefixPublicDelegatedSubPrefix do def decode(value, options) do GoogleApi.Compute.V1.Model.PublicDelegatedPrefixPublicDelegatedSubPrefix.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.PublicDelegatedPrefixPublicDelegatedSubPrefix do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.928571
171
0.699821
030b2aa8bef33b5a149d2da11fe6f772e095031c
6,151
ex
Elixir
lib/cldr/number/symbol.ex
jeroenvisser101/cldr_numbers
9a529817fe8d9f61be330fa970a5a0ffa443a177
[ "Apache-2.0" ]
21
2019-12-21T23:25:14.000Z
2022-03-22T00:40:34.000Z
lib/cldr/number/symbol.ex
jeroenvisser101/cldr_numbers
9a529817fe8d9f61be330fa970a5a0ffa443a177
[ "Apache-2.0" ]
15
2019-06-14T16:29:23.000Z
2022-03-02T07:56:33.000Z
lib/cldr/number/symbol.ex
jeroenvisser101/cldr_numbers
9a529817fe8d9f61be330fa970a5a0ffa443a177
[ "Apache-2.0" ]
5
2019-06-14T16:10:26.000Z
2022-02-28T15:32:01.000Z
defmodule Cldr.Number.Symbol do @moduledoc """ Functions to manage the symbol definitions for a locale and number system. """ alias Cldr.Locale alias Cldr.LanguageTag alias Cldr.Number.System defstruct [ :decimal, :group, :exponential, :infinity, :list, :minus_sign, :nan, :per_mille, :percent_sign, :plus_sign, :superscripting_exponent, :time_separator ] @type t :: %__MODULE__{ decimal: String.t(), group: String.t(), exponential: String.t(), infinity: String.t(), list: String.t(), minus_sign: String.t(), nan: String.t(), per_mille: String.t(), percent_sign: String.t(), plus_sign: String.t(), superscripting_exponent: String.t(), time_separator: String.t() } @doc """ Returns a map of `Cldr.Number.Symbol.t` structs of the number symbols for each of the number systems of a locale. ## Arguments * `locale` is any valid locale name returned by `Cldr.known_locale_names/1` or a `Cldr.LanguageTag` struct returned by `Cldr.Locale.new!/2`. The default is `Cldr.get_locale/1`. * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module ## Example: iex> Cldr.Number.Symbol.number_symbols_for("th", TestBackend.Cldr) {:ok, %{ latn: %Cldr.Number.Symbol{ decimal: ".", exponential: "E", group: ",", infinity: "∞", list: ";", minus_sign: "-", nan: "NaN", per_mille: "‰", percent_sign: "%", plus_sign: "+", superscripting_exponent: "×", time_separator: ":" }, thai: %Cldr.Number.Symbol{ decimal: ".", exponential: "E", group: ",", infinity: "∞", list: ";", minus_sign: "-", nan: "NaN", per_mille: "‰", percent_sign: "%", plus_sign: "+", superscripting_exponent: "×", time_separator: ":" } }} """ @spec number_symbols_for(LanguageTag.t() | Locale.locale_name(), Cldr.backend()) :: {:ok, map()} | {:error, {module(), String.t()}} def number_symbols_for(locale, backend) do Module.concat(backend, Number.Symbol).number_symbols_for(locale) end @doc """ Returns the number sysbols for a specific locale and number system. ## Options * `locale` is any valid locale name returned by `Cldr.known_locale_names/1` or a `Cldr.LanguageTag` struct returned by `Cldr.Locale.new!/2`. The default is `Cldr.get_locale/1`. * `number_system` is any number system name returned by `Cldr.known_number_systems/0` or a number system type returned by `Cldr.known_number_system_types/0` * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module ## Example iex> Cldr.Number.Symbol.number_symbols_for("th", "thai", TestBackend.Cldr) {:ok, %Cldr.Number.Symbol{ decimal: ".", exponential: "E", group: ",", infinity: "∞", list: ";", minus_sign: "-", nan: "NaN", per_mille: "‰", percent_sign: "%", plus_sign: "+", superscripting_exponent: "×", time_separator: ":" }} """ @spec number_symbols_for( LanguageTag.t() | Locale.locale_name(), System.system_name(), Cldr.backend() ) :: {:ok, map()} | {:error, {Cldr.NoNumberSymbols, String.t()}} def number_symbols_for(%LanguageTag{} = locale, number_system, backend) do with {:ok, system_name} <- Cldr.Number.System.system_name_from(number_system, locale, backend), {:ok, symbols} <- number_symbols_for(locale, backend) do symbols |> Map.get(system_name) |> symbols_return(locale, number_system) end end def number_symbols_for(locale_name, number_system, backend) when is_binary(locale_name) do with {:ok, locale} <- Cldr.validate_locale(locale_name, backend) do number_symbols_for(locale, number_system, backend) end end @doc """ Returns a list of all decimal symbols defined by the locales configured in the given backend as a list. ## Arguments * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module """ def all_decimal_symbols(backend) do Module.concat(backend, Number.Symbol).all_decimal_symbols end @doc """ Returns a list of all grouping symbols defined by the locales configured in the given backend as a list. ## Arguments * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module """ def all_grouping_symbols(backend) do Module.concat(backend, Number.Symbol).all_grouping_symbols end @doc """ Returns a list of all decimal symbols defined by the locales configured in the given backend as a string. This string can be used as a character class when builing a regular expression. ## Arguments * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module """ def all_decimal_symbols_class(backend) do Module.concat(backend, Number.Symbol).all_decimal_symbols_class end @doc """ Returns a list of all grouping symbols defined by the locales configured in the given backend as a string. This string can be used as a character class when builing a regular expression. ## Arguments * `backend` is any module that includes `use Cldr` and therefore is a `Cldr` backend module """ def all_grouping_symbols_class(backend) do Module.concat(backend, Number.Symbol).all_grouping_symbols_class end @doc false def symbols_return(nil, locale, number_system) do { :error, { Cldr.NoNumberSymbols, "The locale #{inspect(locale)} does not have " <> "any symbols for number system #{inspect(number_system)}" } } end @doc false def symbols_return(symbols, _locale, _number_system) do {:ok, symbols} end end
25.953586
92
0.623151
030b429056ce6fb0db3936be476ce232502bd8b9
2,163
ex
Elixir
lib/cards.ex
shahnCM/card_game
e9aa8c3074c395886b6e082a2e3dd1338f9b8dd1
[ "MIT" ]
null
null
null
lib/cards.ex
shahnCM/card_game
e9aa8c3074c395886b6e082a2e3dd1338f9b8dd1
[ "MIT" ]
null
null
null
lib/cards.ex
shahnCM/card_game
e9aa8c3074c395886b6e082a2e3dd1338f9b8dd1
[ "MIT" ]
null
null
null
defmodule Cards do @moduledoc """ Provides methods for creating and handling a deck of cards """ @doc """ Returns a list of strings representing a deck of playing cards """ def create_deck do values = ["Ace", "Two", "Three", "Four", "Five"] suits = ["Spades", "Clubs", "Hearts", "Diamonds"] # Solution 1 # cards = for value <- values do # for suit <- suits do # "#{value} of #{suit}" # end # end # List.flatten(cards) # Solution 2 for suit <- suits, value <- values do "#{value} of #{suit}" end end @doc """ Shuffles the deck """ def shuffle(deck) do Enum.shuffle(deck) end @doc """ Checks if the deck contains the card you are looking for """ def contains?(deck, card) do Enum.member?(deck, card) end @doc """ Makes a deal with hand_size you provided """ def deal(deck, hand_size) do Enum.split(deck, hand_size) end @doc """ Saves the deck to a file. User has to pass the file name as the second parameter """ def save(deck, filename) do binary = :erlang.term_to_binary(deck) File.write(filename, binary) end # Solution 3 @doc """ Loads the saved file from the storage """ def load(filename) do case File.read(filename) do {:ok, binary} -> :erlang.binary_to_term binary {:error, _reason} -> "That File Doesn't Exist" end end # Solution 2 # def load(filename) do # {status, binary} = File.read(filename) # case status do # :ok -> :erlang.binary_to_term(binary) # :error -> "That File Doesn't Exist" # end # end # Solution 1 # def load(filename) do # {status, binary} = File.read(filename) # :erlang.binary_to_term(binary) # if (status === :error) { # return "Something went wrong !" # } # end @doc """ Creates deck then shuffles the deck then makes deal. User has to provide hand_size as a parameter """ def create_hand(hand_size) do Cards.create_deck |> Cards.shuffle |> Cards.deal(hand_size) end end
21.205882
84
0.580213
030b5995073cdb879c044f810e81c2997f7e0828
19,649
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/api/comments.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/api/comments.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/api/comments.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.YouTube.V3.Api.Comments do @moduledoc """ API calls for all endpoints tagged `Comments`. """ alias GoogleApi.YouTube.V3.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Deletes a resource. ## Parameters * `connection` (*type:* `GoogleApi.YouTube.V3.Connection.t`) - Connection to server * `id` (*type:* `String.t`) - * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec youtube_comments_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()} def youtube_comments_delete(connection, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/youtube/v3/comments", %{}) |> Request.add_param(:query, :id, id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Inserts a new resource into this collection. ## Parameters * `connection` (*type:* `GoogleApi.YouTube.V3.Connection.t`) - Connection to server * `part` (*type:* `list(String.t)`) - The <code><strong>part</strong></code> parameter identifies the properties that the API response will include. Set the parameter value to <code>snippet</code>. The <code>snippet</code> part has a quota cost of 2 units. * `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.YouTube.V3.Model.Comment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.YouTube.V3.Model.Comment{}}` on success * `{:error, info}` on failure """ @spec youtube_comments_insert(Tesla.Env.client(), list(String.t()), keyword(), keyword()) :: {:ok, GoogleApi.YouTube.V3.Model.Comment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def youtube_comments_insert(connection, part, 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("/youtube/v3/comments", %{}) |> Request.add_param(:query, :part, part) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.YouTube.V3.Model.Comment{}]) end @doc """ Retrieves a list of resources, possibly filtered. ## Parameters * `connection` (*type:* `GoogleApi.YouTube.V3.Connection.t`) - Connection to server * `part` (*type:* `list(String.t)`) - The <code><strong>part</strong></code> parameter specifies a comma-separated list of one or more <code>comment</code> resource properties that the API response will include. * `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"). * `:id` (*type:* `list(String.t)`) - Returns the comments with the given IDs for One Platform. * `:maxResults` (*type:* `integer()`) - The <code><strong>maxResults</strong></code> parameter specifies the maximum number of items that should be returned in the result set. * `:pageToken` (*type:* `String.t`) - The <code><strong>pageToken</strong></code> parameter identifies a specific page in the result set that should be returned. In an API response, the <code>nextPageToken</code> and <code>prevPageToken</code> properties identify other pages that could be retrieved. * `:parentId` (*type:* `String.t`) - Returns replies to the specified comment. Note, currently YouTube features only one level of replies (ie replies to top level comments). However replies to replies may be supported in the future. * `:textFormat` (*type:* `String.t`) - The requested text format for the returned comments. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.YouTube.V3.Model.CommentListResponse{}}` on success * `{:error, info}` on failure """ @spec youtube_comments_list(Tesla.Env.client(), list(String.t()), keyword(), keyword()) :: {:ok, GoogleApi.YouTube.V3.Model.CommentListResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def youtube_comments_list(connection, part, 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, :id => :query, :maxResults => :query, :pageToken => :query, :parentId => :query, :textFormat => :query } request = Request.new() |> Request.method(:get) |> Request.url("/youtube/v3/comments", %{}) |> Request.add_param(:query, :part, part) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.YouTube.V3.Model.CommentListResponse{}]) end @doc """ Expresses the caller's opinion that one or more comments should be flagged as spam. ## Parameters * `connection` (*type:* `GoogleApi.YouTube.V3.Connection.t`) - Connection to server * `id` (*type:* `list(String.t)`) - Flags the comments with the given IDs as spam in the caller's opinion. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec youtube_comments_mark_as_spam(Tesla.Env.client(), list(String.t()), keyword(), keyword()) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()} def youtube_comments_mark_as_spam(connection, id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:post) |> Request.url("/youtube/v3/comments/markAsSpam", %{}) |> Request.add_param(:query, :id, id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Sets the moderation status of one or more comments. ## Parameters * `connection` (*type:* `GoogleApi.YouTube.V3.Connection.t`) - Connection to server * `id` (*type:* `list(String.t)`) - Modifies the moderation status of the comments with the given IDs * `moderation_status` (*type:* `String.t`) - Specifies the requested moderation status. Note, comments can be in statuses, which are not available through this call. For example, this call does not allow to mark a comment as 'likely spam'. Valid values: MODERATION_STATUS_PUBLISHED, MODERATION_STATUS_HELD_FOR_REVIEW, MODERATION_STATUS_REJECTED. * `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"). * `:banAuthor` (*type:* `boolean()`) - If set to true the author of the comment gets added to the ban list. This means all future comments of the author will autmomatically be rejected. Only valid in combination with STATUS_REJECTED. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec youtube_comments_set_moderation_status( Tesla.Env.client(), list(String.t()), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()} def youtube_comments_set_moderation_status( connection, id, moderation_status, 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, :banAuthor => :query } request = Request.new() |> Request.method(:post) |> Request.url("/youtube/v3/comments/setModerationStatus", %{}) |> Request.add_param(:query, :id, id) |> Request.add_param(:query, :moderationStatus, moderation_status) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Updates an existing resource. ## Parameters * `connection` (*type:* `GoogleApi.YouTube.V3.Connection.t`) - Connection to server * `part` (*type:* `list(String.t)`) - The <code><strong>part</strong></code> parameter identifies the properties that the API response will include. You must at least include the <code>snippet</code> part in the parameter value since that part contains all of the properties that the API request can update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.YouTube.V3.Model.Comment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.YouTube.V3.Model.Comment{}}` on success * `{:error, info}` on failure """ @spec youtube_comments_update(Tesla.Env.client(), list(String.t()), keyword(), keyword()) :: {:ok, GoogleApi.YouTube.V3.Model.Comment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def youtube_comments_update(connection, part, 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(:put) |> Request.url("/youtube/v3/comments", %{}) |> Request.add_param(:query, :part, part) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.YouTube.V3.Model.Comment{}]) end end
47.007177
196
0.622983
030b6fc25cb11bf78338f76c6269a9e7e5097dc9
4,645
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/router.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/compute/lib/google_api/compute/v1/model/router.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/router.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.Compute.V1.Model.Router do @moduledoc """ Represents a Cloud Router resource. For more information about Cloud Router, read the the Cloud Router overview. ## Attributes * `bgp` (*type:* `GoogleApi.Compute.V1.Model.RouterBgp.t`, *default:* `nil`) - BGP information specific to this router. * `bgpPeers` (*type:* `list(GoogleApi.Compute.V1.Model.RouterBgpPeer.t)`, *default:* `nil`) - BGP information that must be configured into the routing stack to establish BGP peering. This information must specify the peer ASN and either the interface name, IP address, or peer IP address. Please refer to RFC4273. * `creationTimestamp` (*type:* `String.t`, *default:* `nil`) - [Output Only] Creation timestamp in RFC3339 text format. * `description` (*type:* `String.t`, *default:* `nil`) - An optional description of this resource. Provide this property when you create the resource. * `id` (*type:* `String.t`, *default:* `nil`) - [Output Only] The unique identifier for the resource. This identifier is defined by the server. * `interfaces` (*type:* `list(GoogleApi.Compute.V1.Model.RouterInterface.t)`, *default:* `nil`) - Router interfaces. Each interface requires either one linked resource, (for example, linkedVpnTunnel), or IP address and IP address range (for example, ipRange), or both. * `kind` (*type:* `String.t`, *default:* `compute#router`) - [Output Only] Type of resource. Always compute#router for routers. * `name` (*type:* `String.t`, *default:* `nil`) - Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * `nats` (*type:* `list(GoogleApi.Compute.V1.Model.RouterNat.t)`, *default:* `nil`) - A list of NAT services created in this router. * `network` (*type:* `String.t`, *default:* `nil`) - URI of the network to which this router belongs. * `region` (*type:* `String.t`, *default:* `nil`) - [Output Only] URI of the region where the router resides. You must specify this field as part of the HTTP request URL. It is not settable as a field in the request body. * `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] Server-defined URL for the resource. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :bgp => GoogleApi.Compute.V1.Model.RouterBgp.t(), :bgpPeers => list(GoogleApi.Compute.V1.Model.RouterBgpPeer.t()), :creationTimestamp => String.t(), :description => String.t(), :id => String.t(), :interfaces => list(GoogleApi.Compute.V1.Model.RouterInterface.t()), :kind => String.t(), :name => String.t(), :nats => list(GoogleApi.Compute.V1.Model.RouterNat.t()), :network => String.t(), :region => String.t(), :selfLink => String.t() } field(:bgp, as: GoogleApi.Compute.V1.Model.RouterBgp) field(:bgpPeers, as: GoogleApi.Compute.V1.Model.RouterBgpPeer, type: :list) field(:creationTimestamp) field(:description) field(:id) field(:interfaces, as: GoogleApi.Compute.V1.Model.RouterInterface, type: :list) field(:kind) field(:name) field(:nats, as: GoogleApi.Compute.V1.Model.RouterNat, type: :list) field(:network) field(:region) field(:selfLink) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.Router do def decode(value, options) do GoogleApi.Compute.V1.Model.Router.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.Router do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
56.646341
490
0.700108
030b89a920e6831f050476a7e5ef78d5c91dbc94
8,721
exs
Elixir
apps/re_web/test/graphql/developments/mutation_test.exs
ruby2elixir/emcasa-backend
70d7f4f233555417941ffa6ada84cf8740c21dd2
[ "MIT" ]
4
2019-11-01T16:29:31.000Z
2020-10-10T21:20:12.000Z
apps/re_web/test/graphql/developments/mutation_test.exs
eduardomartines/emcasa-backend
70d7f4f233555417941ffa6ada84cf8740c21dd2
[ "MIT" ]
null
null
null
apps/re_web/test/graphql/developments/mutation_test.exs
eduardomartines/emcasa-backend
70d7f4f233555417941ffa6ada84cf8740c21dd2
[ "MIT" ]
5
2019-11-04T21:25:45.000Z
2020-02-13T23:49:36.000Z
defmodule ReWeb.GraphQL.Developments.MutationTest do use ReWeb.{AbsintheAssertions, ConnCase} import Re.Factory alias ReWeb.{ AbsintheHelpers } setup %{conn: conn} do conn = put_req_header(conn, "accept", "application/json") admin_user = insert(:user, email: "[email protected]", role: "admin") user_user = insert(:user, email: "[email protected]", role: "user") address = insert(:address) development = build(:development) {:ok, unauthenticated_conn: conn, admin_conn: login_as(conn, admin_user), user_conn: login_as(conn, user_user), old_development: insert(:development), development: development, address: address} end describe "insertDevelopment/2" do @insert_mutation """ mutation InsertDevelopment ($input: DevelopmentInput!) { insertDevelopment(input: $input) { uuid name phase builder description floor_count units_per_floor elevators address { id } } } """ test "admin should insert development", %{ admin_conn: conn, development: development, address: address } do variables = insert_development_variables(development, address) conn = post(conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@insert_mutation, variables)) assert %{ "insertDevelopment" => %{"address" => inserted_address} = insert_development } = json_response(conn, 200)["data"] assert insert_development["uuid"] assert insert_development["name"] == development.name assert insert_development["phase"] == development.phase assert insert_development["builder"] == development.builder assert insert_development["description"] == development.description assert insert_development["floor_count"] == development.floor_count assert insert_development["units_per_floor"] == development.units_per_floor assert insert_development["elevators"] == development.elevators assert inserted_address["id"] == Integer.to_string(address.id) end test "regular user should not insert development", %{ user_conn: conn, development: development, address: address } do variables = insert_development_variables(development, address) conn = post(conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@insert_mutation, variables)) assert %{"insertDevelopment" => nil} == json_response(conn, 200)["data"] assert_forbidden_response(json_response(conn, 200)) end test "unauthenticated user should not insert a development", %{ unauthenticated_conn: conn, development: development, address: address } do variables = insert_development_variables(development, address) conn = post(conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@insert_mutation, variables)) assert %{"insertDevelopment" => nil} == json_response(conn, 200)["data"] assert_unauthorized_response(json_response(conn, 200)) end end describe "updateDevelopment/2" do @update_mutation """ mutation UpdateDevelopment ($uuid: UUID!, $input: DevelopmentInput!) { updateDevelopment(uuid: $uuid, input: $input) { uuid name phase builder description floor_count units_per_floor elevators address { id } } } """ test "admin should update development", %{ admin_conn: conn, old_development: old_development, development: new_development, address: new_address } do variables = update_development_variables(old_development.uuid, new_development, new_address) conn = post(conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@update_mutation, variables)) assert %{ "updateDevelopment" => %{"address" => updated_address} = updated_development } = json_response(conn, 200)["data"] assert updated_development["name"] == new_development.name assert updated_development["builder"] == new_development.builder assert updated_development["phase"] == new_development.phase assert updated_development["description"] == new_development.description assert updated_development["floor_count"] == new_development.floor_count assert updated_development["units_per_floor"] == new_development.units_per_floor assert updated_development["elevators"] == new_development.elevators assert updated_address["id"] == Integer.to_string(new_address.id) end test "regular user should not update a development", %{ user_conn: conn, old_development: old_development, development: new_development, address: new_address } do variables = update_development_variables(old_development.uuid, new_development, new_address) conn = post(conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@update_mutation, variables)) assert %{"updateDevelopment" => nil} == json_response(conn, 200)["data"] assert_forbidden_response(json_response(conn, 200)) end test "unauthenticated user should not update a development", %{ unauthenticated_conn: conn, old_development: old_development, development: new_development, address: new_address } do variables = update_development_variables(old_development.uuid, new_development, new_address) conn = post(conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@update_mutation, variables)) assert %{"updateDevelopment" => nil} == json_response(conn, 200)["data"] assert_unauthorized_response(json_response(conn, 200)) end end describe "scheduleDevelopmentCreationFromOrulo/2" do @import_from_orulo_mutation """ mutation ScheduleDevelopmentCreationFromOrulo ($external_id: ID!) { scheduleDevelopmentCreationFromOrulo(external_id: $external_id) { message } } """ test "admin should create development through Orulo integration", %{ admin_conn: conn } do variables = %{"external_id" => Enum.random(1..1_000_000)} conn = post( conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@import_from_orulo_mutation, variables) ) assert %{ "scheduleDevelopmentCreationFromOrulo" => %{ "message" => "Development syncronization scheduled!" } } == json_response(conn, 200)["data"] end test "regular user shouldn't create development through Orulo integration", %{ user_conn: conn } do variables = %{"external_id" => Enum.random(1..1_000_000)} conn = post( conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@import_from_orulo_mutation, variables) ) assert %{"scheduleDevelopmentCreationFromOrulo" => nil} == json_response(conn, 200)["data"] assert_forbidden_response(json_response(conn, 200)) end test "unauthenticated user shouldn't create development through Orulo integration", %{ unauthenticated_conn: conn } do variables = %{"external_id" => Enum.random(1..1_000_000)} conn = post( conn, "/graphql_api", AbsintheHelpers.mutation_wrapper(@import_from_orulo_mutation, variables) ) assert %{"scheduleDevelopmentCreationFromOrulo" => nil} == json_response(conn, 200)["data"] assert_unauthorized_response(json_response(conn, 200)) end end def insert_development_variables(development, address) do %{ "input" => %{ "name" => development.name, "phase" => development.phase, "builder" => development.builder, "description" => development.description, "floor_count" => development.floor_count, "units_per_floor" => development.units_per_floor, "elevators" => development.elevators, "address_id" => address.id } } end def update_development_variables(uuid, development, address) do %{ "uuid" => uuid, "input" => %{ "name" => development.name, "phase" => development.phase, "builder" => development.builder, "description" => development.description, "floor_count" => development.floor_count, "units_per_floor" => development.units_per_floor, "elevators" => development.elevators, "address_id" => address.id } } end end
31.828467
98
0.651645
030b8e6920f6cb26bd837757ae909abd3064115f
1,032
ex
Elixir
lib/surface/components/form/text_input.ex
lnr0626/surface
11ae4a8cfa167fc11c8f960e9d5821a057c9b5bb
[ "MIT" ]
1
2021-06-04T20:46:52.000Z
2021-06-04T20:46:52.000Z
lib/surface/components/form/text_input.ex
lnr0626/surface
11ae4a8cfa167fc11c8f960e9d5821a057c9b5bb
[ "MIT" ]
null
null
null
lib/surface/components/form/text_input.ex
lnr0626/surface
11ae4a8cfa167fc11c8f960e9d5821a057c9b5bb
[ "MIT" ]
null
null
null
defmodule Surface.Components.Form.TextInput do @moduledoc """ An input field that let the user enter a **single-line text**. Provides a wrapper for Phoenix.HTML.Form's `text_input/3` function. All options passed via `opts` will be sent to `text_input/3`, `value` and `class` can be set directly and will override anything in `opts`. ## Examples ``` <TextInput form="user" field="name" opts={{ autofocus: "autofocus" }} /> ``` """ use Surface.Components.Form.Input import Phoenix.HTML.Form, only: [text_input: 3] import Surface.Components.Utils, only: [events_to_opts: 1] import Surface.Components.Form.Utils def render(assigns) do helper_opts = props_to_opts(assigns) attr_opts = props_to_attr_opts(assigns, [:value, class: get_default_class()]) event_opts = events_to_opts(assigns) ~F""" <InputContext assigns={assigns} :let={form: form, field: field}> {text_input(form, field, helper_opts ++ attr_opts ++ @opts ++ event_opts)} </InputContext> """ end end
28.666667
81
0.69186
030bd018d0df88a936ca4c09e834e5e3ccebc601
83
ex
Elixir
lib/powit_web/views/pow_reset_password/reset_password_view.ex
tenzil-rpx/powit
0feebbfc11c7bd2a45ef0664632deb9b0537fb5c
[ "MIT" ]
null
null
null
lib/powit_web/views/pow_reset_password/reset_password_view.ex
tenzil-rpx/powit
0feebbfc11c7bd2a45ef0664632deb9b0537fb5c
[ "MIT" ]
null
null
null
lib/powit_web/views/pow_reset_password/reset_password_view.ex
tenzil-rpx/powit
0feebbfc11c7bd2a45ef0664632deb9b0537fb5c
[ "MIT" ]
null
null
null
defmodule PowitWeb.PowResetPassword.ResetPasswordView do use PowitWeb, :view end
20.75
56
0.843373
030be5a773d5ee540de0306954f5022811de4e43
1,270
exs
Elixir
test/journal_test.exs
Nimor111/TheElixir
ef6e4cc5a59ce064b85f1f50acac309b606f7ab0
[ "MIT" ]
1
2019-04-27T16:14:50.000Z
2019-04-27T16:14:50.000Z
test/journal_test.exs
Nimor111/TheElixir
ef6e4cc5a59ce064b85f1f50acac309b606f7ab0
[ "MIT" ]
2
2019-03-21T20:26:14.000Z
2019-03-21T20:26:20.000Z
test/journal_test.exs
Nimor111/TheElixir
ef6e4cc5a59ce064b85f1f50acac309b606f7ab0
[ "MIT" ]
null
null
null
defmodule TheElixirJournalTest do use ExUnit.Case, async: true alias TheElixir.Components.Journal alias TheElixir.Models.Quest setup context do {:ok, _} = Journal.start_link(context.test) quest = %Quest{name: "Function defs", description: "Examples of function defs"} {:ok, journal: context.test, quest: quest} end test "adds quest", %{journal: journal, quest: quest} do assert Journal.lookup(journal, "First quest") == :error Journal.add(journal, "First quest", quest) assert {:ok, _} = Journal.lookup(journal, "First quest") end test "deletes quest", %{journal: journal, quest: quest} do Journal.add(journal, "First quest", quest) assert {:ok, _} = Journal.lookup(journal, "First quest") Journal.delete(journal, "First quest") # bogus call so DOWN is processed Journal.add(journal, "Second but still first quest", quest) assert Journal.lookup(journal, "First quest") == :error end test "journal process is restarted correctly", %{journal: journal, quest: quest} do Journal.add(journal, "First quest", quest) assert {:ok, _} = Journal.lookup(journal, "First quest") Journal.stop(journal) :timer.sleep(2) assert Journal.lookup(:journal, "First quest") == :error end end
31.75
85
0.685039
030bf73b6177e69150592806acb588d4378b0a54
1,621
ex
Elixir
sphinx_ex/lib/sphinx_ex_web/endpoint.ex
maxneuvians/sphinx_ex
27109d56ebe51c83cde70d44467dabed70b10103
[ "MIT" ]
null
null
null
sphinx_ex/lib/sphinx_ex_web/endpoint.ex
maxneuvians/sphinx_ex
27109d56ebe51c83cde70d44467dabed70b10103
[ "MIT" ]
null
null
null
sphinx_ex/lib/sphinx_ex_web/endpoint.ex
maxneuvians/sphinx_ex
27109d56ebe51c83cde70d44467dabed70b10103
[ "MIT" ]
null
null
null
defmodule SphinxExWeb.Endpoint do use Phoenix.Endpoint, otp_app: :sphinx_ex # The session will be stored in the cookie and signed, # this means its contents can be read but not tampered with. # Set :encryption_salt if you would also like to encrypt it. @session_options [ store: :cookie, key: "_sphinx_ex_key", signing_salt: "3YLywCo2" ] socket "/socket", SphinxExWeb.UserSocket, websocket: true, longpoll: false socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phx.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :sphinx_ex, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader plug Phoenix.Ecto.CheckRepoStatus, otp_app: :sphinx_ex end plug Phoenix.LiveDashboard.RequestLogger, param_key: "request_logger", cookie_key: "request_logger" plug Plug.RequestId plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Phoenix.json_library() plug Plug.MethodOverride plug Plug.Head plug Plug.Session, @session_options plug SphinxExWeb.Router end
29.472727
97
0.720543
030c2fe5138a00ca902eee4dd49f7e320de06650
1,033
ex
Elixir
kboard/test/support/conn_case.ex
MaxStrange/ArtieInfant
1edbb171a5405d2971227f2d2d83acb523c70034
[ "MIT" ]
1
2018-04-28T16:55:05.000Z
2018-04-28T16:55:05.000Z
kboard/test/support/conn_case.ex
MaxStrange/ArtieInfant
1edbb171a5405d2971227f2d2d83acb523c70034
[ "MIT" ]
null
null
null
kboard/test/support/conn_case.ex
MaxStrange/ArtieInfant
1edbb171a5405d2971227f2d2d83acb523c70034
[ "MIT" ]
null
null
null
defmodule KboardWeb.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 datastructures and query the data layer. 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 # Import conveniences for testing with connections use Phoenix.ConnTest import KboardWeb.Router.Helpers # The default endpoint for testing @endpoint KboardWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Kboard.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Kboard.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
26.487179
68
0.718296
030c393c8ceb96745816485e3b74241102d6451c
7,463
ex
Elixir
clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/app_engine_http_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/app_engine_http_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/app_engine_http_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.CloudTasks.V2beta2.Model.AppEngineHttpRequest do @moduledoc """ App Engine HTTP request. The message defines the HTTP request that is sent to an App Engine app when the task is dispatched. This proto can only be used for tasks in a queue which has app_engine_http_target set. Using AppEngineHttpRequest requires [`appengine.applications.get`](https://cloud.google.com/appengine/docs/admin-api/access-control) Google IAM permission for the project and the following scope: `https://www.googleapis.com/auth/cloud-platform` The task will be delivered to the App Engine app which belongs to the same project as the queue. For more information, see [How Requests are Routed](https://cloud.google.com/appengine/docs/standard/python/how-requests-are-routed) and how routing is affected by [dispatch files](https://cloud.google.com/appengine/docs/python/config/dispatchref). Traffic is encrypted during transport and never leaves Google datacenters. Because this traffic is carried over a communication mechanism internal to Google, you cannot explicitly set the protocol (for example, HTTP or HTTPS). The request to the handler, however, will appear to have used the HTTP protocol. The AppEngineRouting used to construct the URL that the task is delivered to can be set at the queue-level or task-level: * If set, app_engine_routing_override is used for all tasks in the queue, no matter what the setting is for the task-level app_engine_routing. The `url` that the task will be sent to is: * `url =` host `+` relative_url Tasks can be dispatched to secure app handlers, unsecure app handlers, and URIs restricted with [`login: admin`](https://cloud.google.com/appengine/docs/standard/python/config/appref). Because tasks are not run as any user, they cannot be dispatched to URIs restricted with [`login: required`](https://cloud.google.com/appengine/docs/standard/python/config/appref) Task dispatches also do not follow redirects. The task attempt has succeeded if the app's request handler returns an HTTP response code in the range [`200` - `299`]. The task attempt has failed if the app's handler returns a non-2xx response code or Cloud Tasks does not receive response before the deadline. Failed tasks will be retried according to the retry configuration. `503` (Service Unavailable) is considered an App Engine system error instead of an application error and will cause Cloud Tasks' traffic congestion control to temporarily throttle the queue's dispatches. Unlike other types of task targets, a `429` (Too Many Requests) response from an app handler does not cause traffic congestion control to throttle the queue. ## Attributes * `appEngineRouting` (*type:* `GoogleApi.CloudTasks.V2beta2.Model.AppEngineRouting.t`, *default:* `nil`) - Task-level setting for App Engine routing. If set, app_engine_routing_override is used for all tasks in the queue, no matter what the setting is for the task-level app_engine_routing. * `headers` (*type:* `map()`, *default:* `nil`) - HTTP request headers. This map contains the header field names and values. Headers can be set when the task is created. Repeated headers are not supported but a header value can contain commas. Cloud Tasks sets some headers to default values: * `User-Agent`: By default, this header is `"AppEngine-Google; (+http://code.google.com/appengine)"`. This header can be modified, but Cloud Tasks will append `"AppEngine-Google; (+http://code.google.com/appengine)"` to the modified `User-Agent`. If the task has a payload, Cloud Tasks sets the following headers: * `Content-Type`: By default, the `Content-Type` header is set to `"application/octet-stream"`. The default can be overridden by explicitly setting `Content-Type` to a particular media type when the task is created. For example, `Content-Type` can be set to `"application/json"`. * `Content-Length`: This is computed by Cloud Tasks. This value is output only. It cannot be changed. The headers below cannot be set or overridden: * `Host` * `X-Google-*` * `X-AppEngine-*` In addition, Cloud Tasks sets some headers when the task is dispatched, such as headers containing information about the task; see [request headers](https://cloud.google.com/appengine/docs/python/taskqueue/push/creating-handlers#reading_request_headers). These headers are set only when the task is dispatched, so they are not visible when the task is returned in a Cloud Tasks response. Although there is no specific limit for the maximum number of headers or the size, there is a limit on the maximum size of the Task. For more information, see the CreateTask documentation. * `httpMethod` (*type:* `String.t`, *default:* `nil`) - The HTTP method to use for the request. The default is POST. The app's request handler for the task's target URL must be able to handle HTTP requests with this http_method, otherwise the task attempt fails with error code 405 (Method Not Allowed). See [Writing a push task request handler](https://cloud.google.com/appengine/docs/java/taskqueue/push/creating-handlers#writing_a_push_task_request_handler) and the App Engine documentation for your runtime on [How Requests are Handled](https://cloud.google.com/appengine/docs/standard/python3/how-requests-are-handled). * `payload` (*type:* `String.t`, *default:* `nil`) - Payload. The payload will be sent as the HTTP message body. A message body, and thus a payload, is allowed only if the HTTP method is POST or PUT. It is an error to set a data payload on a task with an incompatible HttpMethod. * `relativeUrl` (*type:* `String.t`, *default:* `nil`) - The relative URL. The relative URL must begin with "/" and must be a valid HTTP relative URL. It can contain a path and query string arguments. If the relative URL is empty, then the root path "/" will be used. No spaces are allowed, and the maximum length allowed is 2083 characters. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :appEngineRouting => GoogleApi.CloudTasks.V2beta2.Model.AppEngineRouting.t() | nil, :headers => map() | nil, :httpMethod => String.t() | nil, :payload => String.t() | nil, :relativeUrl => String.t() | nil } field(:appEngineRouting, as: GoogleApi.CloudTasks.V2beta2.Model.AppEngineRouting) field(:headers, type: :map) field(:httpMethod) field(:payload) field(:relativeUrl) end defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2beta2.Model.AppEngineHttpRequest do def decode(value, options) do GoogleApi.CloudTasks.V2beta2.Model.AppEngineHttpRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2beta2.Model.AppEngineHttpRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
126.491525
2,556
0.767654
030c436647a72a3a29e4c99b4da26fc299645b71
10,166
exs
Elixir
practica4/ServicioVistas/servicio_vistas_tests.exs
dmarcob/practicas1920_SSDD
8a3c0a428e21708102d840e7968009fa1cd0246a
[ "CC-BY-3.0" ]
null
null
null
practica4/ServicioVistas/servicio_vistas_tests.exs
dmarcob/practicas1920_SSDD
8a3c0a428e21708102d840e7968009fa1cd0246a
[ "CC-BY-3.0" ]
null
null
null
practica4/ServicioVistas/servicio_vistas_tests.exs
dmarcob/practicas1920_SSDD
8a3c0a428e21708102d840e7968009fa1cd0246a
[ "CC-BY-3.0" ]
null
null
null
# Compilar y cargar ficheros con modulos necesarios Code.require_file("nodo_remoto.exs", __DIR__) Code.require_file("servidor_gv.exs", __DIR__) Code.require_file("cliente_gv.exs", __DIR__) # Poner en marcha el servicio de tests unitarios con : # timeout : ajuste de tiempo máximo de ejecución de todos los tests, en miliseg. # seed: 0 , para que la ejecucion de tests no tenga orden aleatorio # exclusion de ejecución de aquellos tests que tengan el tag :deshabilitado ExUnit.start(timeout: 10000, seed: 0, exclude: [:deshabilitado]) defmodule GestorVistasTest do use ExUnit.Case # @moduletag timeout 100 para timeouts de todos lo test de este modulo # Preparación de contexto de tests de integración # Para gestionar nodos y maquinas setup_all do # Poner en marcha los servidores, obtener nodos # maquinas = ["localhost.localhost", "155.210.154.206", # "155.210.154.207", "155.210.154.208"] maquinas = ["127.0.0.1"] # devuelve una mapa de nodos del servidor y clientes nodos = startServidores(maquinas) on_exit(fn -> # eliminar_nodos Elixir y epmds en maquinas # stopServidores(nodos, maquinas) stopServidores(nodos, maquinas) end) {:ok, nodos} end # Test 1 : No deberia haber primario # @tag :deshabilitado test "No deberia haber primario", %{c1: c1} do IO.puts("Test 1: No deberia haber primario ...") p = ClienteGV.primario(c1) assert p == :undefined IO.puts(" ... Superado") end # # Test 2 : primer primario # # @tag :deshabilitado test "Primer primario", %{c1: c} do IO.puts("Test 2: Primer primario ...") primer_primario(c, ServidorGV.latidos_fallidos() * 2) comprobar_tentativa(c, c, :undefined, 1) IO.puts(" ... Superado") end # Test 3 : primer nodo copia # @tag :deshabilitado test "Primer nodo copia", %{c1: c1, c2: c2} do IO.puts("Test 3: Primer nodo copia ...") # Solo interesa vista tentativa {vista, _} = ClienteGV.latido(c1, -1) primer_nodo_copia(c1, c2, ServidorGV.latidos_fallidos() * 2) # validamos nueva vista por estar completa ClienteGV.latido(c1, vista.num_vista + 1) comprobar_valida(c1, c1, c2, vista.num_vista + 1) IO.puts(" ... Superado") end ## Test 4 : Después, Copia (C2) toma el relevo si Primario (C1) falla. # @tag :deshabilitado test "Copia releva primario", %{c2: c2} do IO.puts("Test4 : copia toma relevo si primario falla ...") {vista, _} = ClienteGV.latido(c2, 2) copia_releva_primario(c2,vista.num_vista, ServidorGV.latidos_fallidos() * 2) comprobar_tentativa(c2, c2, :undefined, vista.num_vista + 1) IO.puts(" ... Superado") end ## Test 5 : Nodo rearrancado (C1) se convierte en copia. # @tag :deshabilitado test "Servidor rearrancado se conviert en copia", %{c1: c1, c2: c2} do IO.puts("Test 5: Servidor rearrancado se convierte en copia ...") # vista tentativa {vista, _} = ClienteGV.latido(c2, 2) servidor_rearranca_a_copia(c1, c2, 2, ServidorGV.latidos_fallidos() * 2) # validamos nueva vista por estar DE NUEVO completa # vista valida debería ser 4 ClienteGV.latido(c2, vista.num_vista + 1) comprobar_valida(c2, c2, c1, vista.num_vista + 1) IO.puts(" ... Superado") end ## Test 6 : C3 como nuevo nodo (en espera), después C2 cae como primario. ## Resultado : copia (C1) pasa a primario y C3 pasa a nodo copia # @tag :deshabilitado test "Servidor en espera se convierte en copia", %{c1: c1, c3: c3} do IO.puts("Test 6: Servidor en espera se convierte en copia ...") # nuevo servidor en espera ClienteGV.latido(c3, 0) # vista tentativa {vista, _} = ClienteGV.latido(c1, 4) espera_pasa_a_copia(c1, c3, 4, ServidorGV.latidos_fallidos() * 2) # validamos nueva vista por estar DE NUEVO completa # vista valida debería ser 5 ClienteGV.latido(c1, vista.num_vista + 1) comprobar_valida(c1, c1, c3, vista.num_vista + 1) IO.puts(" ... Superado") end ## Test 7 : Primario rearrancado (C1) tratado como caido, debe considerarlo # caido aunque envie latido, y es convertido en nodo en espera. # @tag :deshabilitado test "Primario rearrancado tratado como caido", %{c1: c1, c3: c3} do IO.puts("Test 7: Primario rearrancado tratado como caido ...") # cae y recupera c1, pasa de primario a servidor en espera ClienteGV.latido(c1, 0) # vista tentativa {vista, _} = ClienteGV.latido(c1, 5) primario_rearrancado(c1, c3, 5, ServidorGV.latidos_fallidos() * 2) comprobar_tentativa(c3, c3, c1, vista.num_vista) end # Test 8 : Servidor de vistas espera a que primario confirme vista # pero este no lo hace. # Poner C3 como Primario, C1 como Copia, C2 para comprobar # - C3 no confirma vista en que es primario, # - Cae, pero C1 no es promocionado porque C3 no confimo ! #@tag :deshabilitado test "Primario no confirma la vista", %{c1: c1, c2: c2, c3: c3} do IO.puts("Test8: Primario no confirma vista") primario_no_confirma_vista(c1, c2, c3) end ## Test 9 : Si anteriores servidores caen (Primario y Copia), ## un nuevo servidor sin inicializar no puede convertirse en primario. test "Nuevo cliente no se convierte en primario error critico", %{c1: c1, c2: c2, c3: c3} do IO.puts("Test9: Nuevo cliente no se convierte en primario error critico") sin_inicializar_no(c1, c2, c3) end # ------------------ FUNCIONES DE APOYO A TESTS ------------------------ ## defp startServidores(maquinas) do tiempo_antes = :os.system_time(:milli_seconds) # Poner en marcha nodos servidor gestor de vistas y clientes # startNodos(%{tipoNodo: %{maquina: list(nombres)}}) numMaquinas = length(maquinas) sv = ServidorGV.startNodo("sv", Enum.at(maquinas, 0)) clientes = for i <- 1..3 do # solo una máquina : la máquina local if numMaquinas == 4 do ClienteGV.startNodo( "c" <> Integer.to_string(i), Enum.at(maquinas, i) ) else ClienteGV.startNodo( "c" <> Integer.to_string(i), Enum.at(maquinas, 0) ) end end # Poner en marcha servicios de cada uno ServidorGV.startService(sv) c1 = ClienteGV.startService(Enum.at(clientes, 0), sv) c2 = ClienteGV.startService(Enum.at(clientes, 1), sv) c3 = ClienteGV.startService(Enum.at(clientes, 2), sv) # Tiempo de puesta en marcha de nodos t_total = :os.system_time(:milli_seconds) - tiempo_antes [sv: sv, c1: c1, c2: c2, c3: c3] end ## defp stopServidores(servidores, maquinas) do Enum.each(servidores, fn {_, nodo} -> NodoRemoto.stop(nodo) end) # Eliminar epmd en cada maquina con nodos Elixir Enum.each(maquinas, fn m -> NodoRemoto.killEpmd(m) end) end ## defp primer_primario(_c, 0), do: :fin defp primer_primario(c, x) do {vista, _} = ClienteGV.latido(c, 0) if vista.primario != c do Process.sleep(ServidorGV.intervalo_latidos()) primer_primario(c, x - 1) end end ## defp primer_nodo_copia(_c1, _c2, 0), do: :fin defp primer_nodo_copia(c1, c2, x) do # el primario : != 0 para no dar por nuevo y < 0 PARA NO VALIDAR !!! ClienteGV.latido(c1, -1) {vista, _} = ClienteGV.latido(c2, 0) if vista.copia != c2 do Process.sleep(ServidorGV.intervalo_latidos()) primer_nodo_copia(c1, c2, x - 1) end end ## def copia_releva_primario(_, _num_vista_inicial, 0), do: :fin def copia_releva_primario(c2, num_vista_inicial, x) do {vista, _} = ClienteGV.latido(c2, num_vista_inicial) if vista.primario != c2 or vista.copia != :undefined do Process.sleep(ServidorGV.intervalo_latidos()) copia_releva_primario(c2, num_vista_inicial, x - 1) end end ## defp servidor_rearranca_a_copia(_c1, _c2, _num_vista_tentativa, 0), do: :fin defp servidor_rearranca_a_copia(c1, c2, num_vista_tentativa, x) do ClienteGV.latido(c1, 0) {vista, _} = ClienteGV.latido(c2, num_vista_tentativa) if vista.copia != c1 do Process.sleep(ServidorGV.intervalo_latidos()) servidor_rearranca_a_copia(c1, c2, num_vista_tentativa, x - 1) end end ## defp espera_pasa_a_copia(_c1, _c3, _num_vista_tentativa, 0), do: :fin defp espera_pasa_a_copia(c1, c3, num_vista_tentativa, x) do ClienteGV.latido(c3, num_vista_tentativa) {vista, _} = ClienteGV.latido(c1, num_vista_tentativa) if vista.primario != c1 or vista.copia != c3 do Process.sleep(ServidorGV.intervalo_latidos()) espera_pasa_a_copia(c1, c3, num_vista_tentativa, x - 1) end end ## defp primario_rearrancado(_c1, _c3, _num_vista_tentativa, 0), do: :fin defp primario_rearrancado(c1, c3, num_vista_tentativa, x) do ClienteGV.latido(c1, num_vista_tentativa) {vista, _} = ClienteGV.latido(c3, num_vista_tentativa) if vista.primario != c3 do Process.sleep(ServidorGV.intervalo_latidos()) primario_rearrancado(c1, c3, num_vista_tentativa, x - 1) end end defp primario_no_confirma_vista(c1, c2, c3) do {vista, _} = ClienteGV.latido(c1, 0) {vista,_} = ClienteGV.latido(c1, vista.num_vista) {vista,_} = ClienteGV.latido(c3, 0) comprobar_tentativa(c2, :undefined, :undefined, 0) end defp sin_inicializar_no(c1, c2, c3) do comprobar_tentativa(c1, :undefined, :undefined, 0) end defp comprobar_tentativa(nodo_cliente, nodo_primario, nodo_copia, n_vista) do # Solo interesa vista tentativa {vista, _} = ClienteGV.latido(nodo_cliente, -1) comprobar(nodo_primario, nodo_copia, n_vista, vista) end defp comprobar_valida(nodo_cliente, nodo_primario, nodo_copia, n_vista) do {vista, _} = ClienteGV.obten_vista(nodo_cliente) comprobar(nodo_primario, nodo_copia, n_vista, vista) assert ClienteGV.primario(nodo_cliente) == nodo_primario end defp comprobar(nodo_primario, nodo_copia, n_vista, vista) do assert vista.primario == nodo_primario assert vista.copia == nodo_copia assert vista.num_vista == n_vista end end
30.255952
94
0.670175
030c5682594c3bceb8da8d875c7c5e788b650804
7,768
exs
Elixir
test/phoenix/socket/transport_test.exs
bhicks/phoenix
2c43d798c184f6085cd2765d6cb2b463c87edac7
[ "MIT" ]
null
null
null
test/phoenix/socket/transport_test.exs
bhicks/phoenix
2c43d798c184f6085cd2765d6cb2b463c87edac7
[ "MIT" ]
null
null
null
test/phoenix/socket/transport_test.exs
bhicks/phoenix
2c43d798c184f6085cd2765d6cb2b463c87edac7
[ "MIT" ]
null
null
null
System.put_env("TRANSPORT_TEST_HOST", "host.com") defmodule Phoenix.Socket.TransportTest do use ExUnit.Case, async: true use RouterHelper import ExUnit.CaptureLog alias Phoenix.Socket.Transport Application.put_env :phoenix, __MODULE__.Endpoint, force_ssl: [], url: [host: {:system, "TRANSPORT_TEST_HOST"}], check_origin: ["//endpoint.com"] defmodule Endpoint do use Phoenix.Endpoint, otp_app: :phoenix end setup_all do Endpoint.start_link() :ok end setup do Logger.disable(self()) end ## Check origin describe "check_origin/4" do defp check_origin(origin, opts) do conn = conn(:get, "/") |> put_req_header("origin", origin) Transport.check_origin(conn, make_ref(), Endpoint, opts) end test "does not check origin if disabled" do refute check_origin("/", check_origin: false).halted end test "checks origin against host" do refute check_origin("https://host.com/", check_origin: true).halted conn = check_origin("https://another.com/", check_origin: true) assert conn.halted assert conn.status == 403 end test "checks origin from endpoint config" do refute check_origin("https://endpoint.com/", []).halted conn = check_origin("https://another.com/", []) assert conn.halted assert conn.status == 403 end test "can get the host from system variables" do refute check_origin("https://host.com", check_origin: true).halted end test "wildcard subdomains" do origins = ["https://*.ex.com", "http://*.ex.com"] conn = check_origin("http://org1.ex.com", check_origin: origins) refute conn.halted conn = check_origin("https://org1.ex.com", check_origin: origins) refute conn.halted end test "nested wildcard subdomains" do origins = ["http://*.foo.example.com"] conn = check_origin("http://org1.foo.example.com", check_origin: origins) refute conn.halted conn = check_origin("http://org1.bar.example.com", check_origin: origins) assert conn.halted assert conn.status == 403 end test "subdomains do not match without a wildcard" do conn = check_origin("http://org1.ex.com", check_origin: ["//ex.com"]) assert conn.halted end test "halts invalid URIs when check origin is configured" do Logger.enable(self()) origins = ["//example.com", "http://scheme.com", "//port.com:81"] logs = capture_log(fn -> for config <- [origins, true] do assert check_origin("file://", check_origin: config).halted assert check_origin("null", check_origin: config).halted assert check_origin("", check_origin: config).halted end end) assert logs =~ "Origin of the request: file://" assert logs =~ "Origin of the request: null" end def invalid_allowed?(%URI{host: nil}), do: true test "allows custom MFA check to handle invalid host" do mfa = {__MODULE__, :invalid_allowed?, []} refute check_origin("file://", check_origin: mfa).halted refute check_origin("null", check_origin: mfa).halted refute check_origin("", check_origin: mfa).halted end test "does not halt invalid URIs when check_origin is disabled" do refute check_origin("file://", check_origin: false).halted refute check_origin("null", check_origin: false).halted refute check_origin("", check_origin: false).halted end test "checks the origin of requests against allowed origins" do origins = ["//example.com", "http://scheme.com", "//port.com:81"] # not allowed host conn = check_origin("http://notallowed.com/", check_origin: origins) assert conn.halted assert conn.status == 403 # Only host match refute check_origin("http://example.com/", check_origin: origins).halted refute check_origin("https://example.com/", check_origin: origins).halted # Scheme + host match (checks port due to scheme) refute check_origin("http://scheme.com/", check_origin: origins).halted conn = check_origin("https://scheme.com/", check_origin: origins) assert conn.halted assert conn.status == 403 conn = check_origin("http://scheme.com:8080/", check_origin: origins) assert conn.halted assert conn.status == 403 # Scheme + host + port match refute check_origin("http://port.com:81/", check_origin: origins).halted conn = check_origin("http://port.com:82/", check_origin: origins) assert conn.halted assert conn.status == 403 end def check_origin_callback(%URI{host: "example.com"}), do: true def check_origin_callback(%URI{host: _}), do: false test "checks the origin of requests against an MFA" do # callback without additional arguments mfa = {__MODULE__, :check_origin_callback, []} # a not allowed host conn = check_origin("http://notallowed.com/", check_origin: mfa) assert conn.halted assert conn.status == 403 # an allowed host refute check_origin("http://example.com/", check_origin: mfa).halted end def check_origin_additional(%URI{host: allowed}, allowed), do: true def check_origin_additional(%URI{host: _}, _allowed), do: false test "checks the origin of requests against an MFA, passing additional arguments" do # callback with additional argument mfa = {__MODULE__, :check_origin_additional, ["host.com"]} # a not allowed host conn = check_origin("http://notallowed.com/", check_origin: mfa) assert conn.halted assert conn.status == 403 # an allowed host refute check_origin("https://host.com/", check_origin: mfa).halted end end ## Check subprotocols describe "check_subprotocols/2" do defp check_subprotocols(expected, passed) do conn = conn(:get, "/") |> put_req_header("sec-websocket-protocol", Enum.join(passed, ", ")) Transport.check_subprotocols(conn, expected) end test "does not check subprotocols if not passed expected" do refute check_subprotocols(nil, ["sip"]).halted end test "does not check subprotocols if conn is halted" do halted_conn = conn(:get, "/") |> halt() conn = Transport.check_subprotocols(halted_conn, ["sip"]) assert conn == halted_conn end test "returns first matched subprotocol" do conn = check_subprotocols(["sip", "mqtt"], ["sip", "mqtt"]) refute conn.halted assert get_resp_header(conn, "sec-websocket-protocol") == ["sip"] end test "halt if expected and passed subprotocols don't match" do conn = check_subprotocols(["sip"], ["mqtt"]) assert conn.halted assert conn.status == 403 end test "halt if expected subprotocols passed in the wrong format" do conn = check_subprotocols("sip", ["mqtt"]) assert conn.halted assert conn.status == 403 end end describe "force_ssl/4" do test "forces SSL" do # Halts conn = Transport.force_ssl(conn(:get, "http://foo.com/"), make_ref(), Endpoint, []) assert conn.halted assert get_resp_header(conn, "location") == ["https://host.com/"] # Disabled conn = Transport.force_ssl(conn(:get, "http://foo.com/"), make_ref(), Endpoint, force_ssl: false) refute conn.halted # No-op when already halted conn = Transport.force_ssl(conn(:get, "http://foo.com/") |> halt(), make_ref(), Endpoint, []) assert conn.halted assert get_resp_header(conn, "location") == [] # Valid conn = Transport.force_ssl(conn(:get, "https://foo.com/"), make_ref(), Endpoint, []) refute conn.halted end end end
32.366667
103
0.652291
030c58fedbf7a4d5c2e8dfebec335ecf5181539c
1,383
exs
Elixir
test/log_test.exs
coop/verk
cae9bea1426d5b340b3041b29453f17c709d70a8
[ "MIT" ]
null
null
null
test/log_test.exs
coop/verk
cae9bea1426d5b340b3041b29453f17c709d70a8
[ "MIT" ]
null
null
null
test/log_test.exs
coop/verk
cae9bea1426d5b340b3041b29453f17c709d70a8
[ "MIT" ]
1
2018-12-04T03:50:36.000Z
2018-12-04T03:50:36.000Z
defmodule Verk.LogTest do use ExUnit.Case import ExUnit.CaptureLog alias Verk.Time describe "start/2" do test "logs start" do worker = self() job = %Verk.Job{} assert capture_log(fn -> Verk.Log.start(job, worker) end) =~ ~r/start/ end end describe "done/3" do test "logs done with time in milliseconds" do worker = self() job = %Verk.Job{} start_time = Verk.Time.now assert capture_log(fn -> Verk.Log.done(job, start_time, worker) end) =~ ~r/done: \d+ ms/ end test "logs done with time in seconds" do worker = self() job = %Verk.Job{} start_time = Verk.Time.now |> Verk.Time.shift(-2) assert capture_log(fn -> Verk.Log.done(job, start_time, worker) end) =~ ~r/done: \d+ s/ end end describe "fail/3" do test "logs fail with time in milliseconds" do worker = self() job = %Verk.Job{} start_time = Verk.Time.now assert capture_log(fn -> Verk.Log.fail(job, start_time, worker) end) =~ ~r/fail: \d+ ms/ end test "logs fail with time in seconds" do worker = self() job = %Verk.Job{} start_time = Verk.Time.now |> Time.shift(-2, :seconds) assert capture_log(fn -> Verk.Log.fail(job, start_time, worker) end) =~ ~r/fail: \d+ s/ end end end
22.306452
76
0.574114
030cd86f4709e7ae69bc9fa3185e23db46d9cedc
1,993
ex
Elixir
lib/receptar/orderables.ex
johannes-mueller/receptar
6ab2cbf93c5da01409a9d8ed3d56a825e8350a1e
[ "Apache-2.0" ]
null
null
null
lib/receptar/orderables.ex
johannes-mueller/receptar
6ab2cbf93c5da01409a9d8ed3d56a825e8350a1e
[ "Apache-2.0" ]
null
null
null
lib/receptar/orderables.ex
johannes-mueller/receptar
6ab2cbf93c5da01409a9d8ed3d56a825e8350a1e
[ "Apache-2.0" ]
null
null
null
defmodule Receptar.Orderables do def append(orderables, new_item) do new_number = length(orderables) + 1 {new_number, [Map.put(new_item, :number, new_number) | orderables] |> Enum.sort(& &1.number < &2.number) } end def insert_before(orderables, new_item, target_item) do number = target_item.number orderables = orderables |> Enum.map(fn o when o.number < number -> o o -> %{o | number: o.number + 1} end) {number, [Map.put(new_item, :number, number) | orderables] |> Enum.sort(& &1.number < &2.number) } end def delete(orderables, target) do orderables |> Enum.filter(& &1.number != target.number) |> Enum.map(fn o when o.number > target.number -> %{o | number: o.number - 1} o -> o end) |> Enum.sort(& &1.number < &2.number) end def replace(orderables, new_item) do orderables |> Enum.map(fn o when o.number == new_item.number -> new_item o -> o end) |> Enum.sort(& &1.number < &2.number) end def is_pullable(_orderables, item) do item.number != 1 end def is_pushable(orderables, item) do item.number < length(orderables) end def pull(orderables, number) when number == 1 do orderables |> Enum.sort(& &1.number < &2.number) end def pull(orderables, number) do orderables |> Enum.map(fn o when o.number == number -> %{o | number: o.number - 1} o when o.number == number - 1 -> %{o | number: o.number + 1} o -> o end) |> Enum.sort(& &1.number < &2.number) end def push(orderables, number) when number >= length(orderables) do orderables |> Enum.sort(& &1.number < &2.number) end def push(orderables, number) do orderables |> Enum.map(fn o when o.number == number -> %{o | number: o.number + 1} o when o.number == number + 1 -> %{o | number: o.number - 1} o -> o end) |> Enum.sort(& &1.number < &2.number) end end
24.012048
68
0.585549
030ce8a507e4396ee878a0bf2494db7caf1cec33
590
ex
Elixir
web/views/person_view.ex
GoberInfinity/ExamplePhoenix
4f2e016000a55dd4dbc28409dd214f0923e38e32
[ "MIT" ]
null
null
null
web/views/person_view.ex
GoberInfinity/ExamplePhoenix
4f2e016000a55dd4dbc28409dd214f0923e38e32
[ "MIT" ]
null
null
null
web/views/person_view.ex
GoberInfinity/ExamplePhoenix
4f2e016000a55dd4dbc28409dd214f0923e38e32
[ "MIT" ]
null
null
null
defmodule Otherpool.PersonView do use Otherpool.Web, :view def render("index.json", %{persons: persons}) do %{data: render_many(persons, Otherpool.PersonView, "person.json")} end def render("show.json", %{person: person}) do %{data: render_one(person, Otherpool.PersonView, "person.json")} end def render("person.json", %{person: person}) do %{id: person.id, first_name: person.first_name, middle_name: person.middle_name, last_name: person.last_name, email: person.email, age: person.age, birthday: person.birthday} end end
26.818182
70
0.672881
030d12a9888ff0a7fad8e739d2c04ab12fb9edc2
16,508
exs
Elixir
test/absinthe/schema/notation/experimental/import_sdl_test.exs
zoldar/absinthe
72ff9f91fcc0a261f9965cf8120c7c72ff6e4c7c
[ "MIT" ]
null
null
null
test/absinthe/schema/notation/experimental/import_sdl_test.exs
zoldar/absinthe
72ff9f91fcc0a261f9965cf8120c7c72ff6e4c7c
[ "MIT" ]
null
null
null
test/absinthe/schema/notation/experimental/import_sdl_test.exs
zoldar/absinthe
72ff9f91fcc0a261f9965cf8120c7c72ff6e4c7c
[ "MIT" ]
null
null
null
defmodule Absinthe.Schema.Notation.Experimental.ImportSdlTest do use Absinthe.Case import ExperimentalNotationHelpers @moduletag :experimental @moduletag :sdl defmodule WithFeatureDirective do use Absinthe.Schema.Prototype directive :feature do arg :name, non_null(:string) on [:interface] end end defmodule Definition do use Absinthe.Schema @prototype_schema WithFeatureDirective # Embedded SDL import_sdl """ directive @foo(name: String!) on SCALAR | OBJECT directive @bar(name: String!) on SCALAR | OBJECT type Query { "A list of posts" posts(filterBy: PostFilter, reverse: Boolean): [Post] admin: User! droppedField: String defaultsOfVariousFlavors( name: String = "Foo" count: Int = 3 average: Float = 3.14 category: Category = NEWS category: [Category] = [NEWS] valid: Boolean = false complex: ComplexInput = {nested: "String"} ): String metaEcho: String scalarEcho(input: CoolScalar): CoolScalar namedThings: [Named] titledThings: [Titled] } scalar CoolScalar input ComplexInput { nested: String } type Comment { author: User! subject: Post! order: Int deprecatedField: String @deprecated deprecatedFieldWithReason: String @deprecated(reason: "Reason") } enum Category { NEWS OPINION } enum PostState { SUBMITTED ACCEPTED REJECTED } interface Named { name: String! } type Human implements Named { name: String! age: Int! } type City implements Named { name: String! population: Int! } interface Titled @feature(name: "bar") { title: String! } type Book implements Titled { title: String! pages: Int! } type Movie implements Titled { title: String! duration: Int! } scalar B union SearchResult = Post | User union Content = Post | Comment """ # Read SDL from file manually at compile-time import_sdl File.read!("test/support/fixtures/import_sdl_binary_fn.graphql") # Read from file at compile time (with support for automatic recompilation) import_sdl path: "test/support/fixtures/import_sdl_path_option.graphql" import_sdl path: Path.join("test/support", "fixtures/import_sdl_path_option_fn.graphql") def get_posts(_, _, _) do posts = [ %{title: "Foo", body: "A body.", author: %{name: "Bruce"}}, %{title: "Bar", body: "A body.", author: %{name: "Ben"}} ] {:ok, posts} end def upcase_title(post, _, _) do {:ok, Map.get(post, :title) |> String.upcase()} end def meta_echo(_source, _args, resolution) do {:ok, get_in(resolution.definition.schema_node.__private__, [:meta, :echo])} end def scalar_echo(_source, %{input: scalar}, _resolution) do {:ok, scalar} end def named_things(_source, _args, _resolution) do {:ok, [%{name: "Sue", age: 38}, %{name: "Portland", population: 647_000}]} end def titled_things(_source, _args, _resolution) do {:ok, [%{title: "The Matrix", duration: 150}, %{title: "Origin of Species", pages: 502}]} end def hydrate(%{identifier: :admin}, [%{identifier: :query} | _]) do {:description, "The admin"} end def hydrate(%{identifier: :filter_by}, [%{identifier: :posts} | _]) do {:description, "A filter argument"} end def hydrate(%{identifier: :posts}, [%{identifier: :query} | _]) do {:resolve, &__MODULE__.get_posts/3} end def hydrate(%{identifier: :meta_echo}, [%{identifier: :query} | _]) do [ {:meta, echo: "Hello"}, {:resolve, &__MODULE__.meta_echo/3} ] end def hydrate(%{name: "CoolScalar"}, _) do [ {:parse, &__MODULE__.parse_cool_scalar/1}, {:serialize, &__MODULE__.serialize_cool_scalar/1} ] end def hydrate(%{identifier: :scalar_echo}, [%{identifier: :query} | _]) do [{:middleware, {Absinthe.Resolution, &__MODULE__.scalar_echo/3}}] end def hydrate(%{identifier: :titled}, _) do [{:resolve_type, &__MODULE__.titled_resolve_type/2}] end def hydrate(%{identifier: :content}, _) do [{:resolve_type, &__MODULE__.content_resolve_type/2}] end def hydrate(%{identifier: :human}, _) do [{:is_type_of, &__MODULE__.human_is_type_of/1}] end def hydrate(%{identifier: :city}, _) do [{:is_type_of, &__MODULE__.city_is_type_of/1}] end def hydrate(%{identifier: :named_things}, [%{identifier: :query} | _]) do [{:resolve, &__MODULE__.named_things/3}] end def hydrate(%{identifier: :titled_things}, [%{identifier: :query} | _]) do [{:resolve, &__MODULE__.titled_things/3}] end def hydrate(%Absinthe.Blueprint{}, _) do %{ query: %{ posts: %{ reverse: {:description, "Just reverse the list, if you want"} } }, post: %{ upcased_title: [ {:description, "The title, but upcased"}, {:resolve, &__MODULE__.upcase_title/3} ] }, search_result: [ resolve_type: &__MODULE__.search_result_resolve_type/2 ] } end def hydrate(_node, _ancestors) do [] end def city_is_type_of(%{population: _}), do: true def city_is_type_of(_), do: false def human_is_type_of(%{age: _}), do: true def human_is_type_of(_), do: false def titled_resolve_type(%{duration: _}, _), do: :movie def titled_resolve_type(%{pages: _}, _), do: :book def content_resolve_type(_, _), do: :comment def search_result_resolve_type(_, _), do: :post def parse_cool_scalar(value), do: {:ok, value} def serialize_cool_scalar(%{value: value}), do: value end describe "custom prototype schema" do test "is set" do assert Definition.__absinthe_prototype_schema__() == WithFeatureDirective end end describe "locations" do test "have evaluated file values" do Absinthe.Blueprint.prewalk(Definition.__absinthe_blueprint__(), nil, fn %{__reference__: %{location: %{file: file}}} = node, _ -> assert is_binary(file) {node, nil} node, _ -> {node, nil} end) end end describe "directives" do test "can be defined" do assert %{name: "foo", identifier: :foo, locations: [:object, :scalar]} = lookup_compiled_directive(Definition, :foo) assert %{name: "bar", identifier: :bar, locations: [:object, :scalar]} = lookup_compiled_directive(Definition, :bar) end end describe "deprecations" do test "can be defined without a reason" do object = lookup_compiled_type(Definition, :comment) assert %{deprecation: %{}} = object.fields.deprecated_field end test "can be defined with a reason" do object = lookup_compiled_type(Definition, :comment) assert %{deprecation: %{reason: "Reason"}} = object.fields.deprecated_field_with_reason end end describe "query root type" do test "is defined" do assert %{name: "Query", identifier: :query} = lookup_type(Definition, :query) end test "defines fields" do assert %{name: "posts"} = lookup_field(Definition, :query, :posts) end end describe "non-root type" do test "is defined" do assert %{name: "Post", identifier: :post} = lookup_type(Definition, :post) end test "defines fields" do assert %{name: "title"} = lookup_field(Definition, :post, :title) assert %{name: "body"} = lookup_field(Definition, :post, :body) end end describe "descriptions" do test "work on objects" do assert %{description: "A submitted post"} = lookup_type(Definition, :post) end test "work on fields" do assert %{description: "A list of posts"} = lookup_field(Definition, :query, :posts) end test "work on fields, defined deeply" do assert %{description: "The title, but upcased"} = lookup_compiled_field(Definition, :post, :upcased_title) end test "work on arguments, defined deeply" do assert %{description: "Just reverse the list, if you want"} = lookup_compiled_argument(Definition, :query, :posts, :reverse) end test "can be multiline" do assert %{description: "The post author\n(is a user)"} = lookup_field(Definition, :post, :author) end test "can be added by hydrating a field" do assert %{description: "The admin"} = lookup_compiled_field(Definition, :query, :admin) end test "can be added by hydrating an argument" do field = lookup_compiled_field(Definition, :query, :posts) assert %{description: "A filter argument"} = field.args.filter_by end end describe "union types" do test "have correct type references" do assert content_union = Absinthe.Schema.lookup_type(Definition, :content) assert content_union.types == [:comment, :post] end test "have resolve_type via a dedicated clause" do assert content_union = Absinthe.Schema.lookup_type(Definition, :content) assert content_union.resolve_type end test "have resolve_type via the blueprint hydrator" do assert search_union = Absinthe.Schema.lookup_type(Definition, :search_result) assert search_union.resolve_type end end describe "resolve" do test "work on fields, defined deeply" do assert %{middleware: mw} = lookup_compiled_field(Definition, :post, :upcased_title) assert length(mw) > 0 end end describe "multiple invocations" do test "can add definitions" do assert %{name: "User", identifier: :user} = lookup_type(Definition, :user) end end @query """ { admin { name } } """ describe "execution with root_value" do test "works" do assert {:ok, %{data: %{"admin" => %{"name" => "Bruce"}}}} = Absinthe.run(@query, Definition, root_value: %{admin: %{name: "Bruce"}}) end end @query """ { posts { title } } """ describe "execution with hydration-defined resolvers" do test "works" do assert {:ok, %{data: %{"posts" => [%{"title" => "Foo"}, %{"title" => "Bar"}]}}} = Absinthe.run(@query, Definition) end end @query """ { posts { upcasedTitle } } """ describe "execution with deep hydration-defined resolvers" do test "works" do assert {:ok, %{data: %{"posts" => [%{"upcasedTitle" => "FOO"}, %{"upcasedTitle" => "BAR"}]}}} = Absinthe.run(@query, Definition) end end describe "hydration" do @query """ { metaEcho } """ test "allowed for meta data" do assert {:ok, %{data: %{"metaEcho" => "Hello"}}} = Absinthe.run(@query, Definition) end @query """ { scalarEcho(input: "Hey there") } """ test "enables scalar creation" do assert {:ok, %{data: %{"scalarEcho" => "Hey there"}}} = Absinthe.run(@query, Definition) end @query """ { namedThings { __typename name ... on Human { age } ... on City { population } } } """ test "interface via is_type_of" do assert {:ok, %{ data: %{ "namedThings" => [ %{"__typename" => "Human", "name" => "Sue", "age" => 38}, %{"__typename" => "City", "name" => "Portland", "population" => 647_000} ] } }} = Absinthe.run(@query, Definition) end @query """ { titledThings { __typename title ... on Book { pages } ... on Movie { duration } } } """ test "interface via resolve_type" do assert {:ok, %{ data: %{ "titledThings" => [ %{"__typename" => "Movie", "title" => "The Matrix", "duration" => 150}, %{"__typename" => "Book", "title" => "Origin of Species", "pages" => 502} ] } }} = Absinthe.run(@query, Definition) end end @query """ { posts(filterBy: {name: "foo"}) { upcasedTitle } } """ describe "execution with multi word args" do test "works" do assert {:ok, %{data: %{"posts" => [%{"upcasedTitle" => "FOO"}, %{"upcasedTitle" => "BAR"}]}}} = Absinthe.run(@query, Definition) end end describe "Absinthe.Schema.referenced_types/1" do test "works" do assert Absinthe.Schema.referenced_types(Definition) end end defmodule FakerSchema do use Absinthe.Schema query do field :hello, :string end import_sdl path: "test/support/fixtures/fake_definition.graphql" end describe "graphql-faker schema" do test "defines the correct types" do type_names = FakerSchema.__absinthe_types__() |> Map.values() for type <- ~w(fake__Locale fake__Types fake__imageCategory fake__loremSize fake__color fake__options examples__JSON) do assert type in type_names end end test "defines the correct directives" do directive_names = FakerSchema.__absinthe_directives__() |> Map.values() for directive <- ~w(examples) do assert directive in directive_names end end test "default values" do type = Absinthe.Schema.lookup_type(FakerSchema, :fake__options) assert %{red255: _, blue255: _, green255: _} = type.fields.base_color.default_value type = Absinthe.Schema.lookup_type(FakerSchema, :fake__color) assert type.fields.red255.default_value == 0 assert type.fields.green255.default_value == 0 assert type.fields.blue255.default_value == 0 end end test "Keyword extend not yet supported" do schema = """ defmodule KeywordExtend do use Absinthe.Schema import_sdl " type Movie { title: String! } extend type Movie { year: Int } " end """ error = ~r/Keyword `extend` is not yet supported/ assert_raise(Absinthe.Schema.Notation.Error, error, fn -> Code.eval_string(schema) end) end test "Validate known directive arguments in SDL schema" do schema = """ defmodule SchemaWithDirectivesWithNestedArgs do use Absinthe.Schema defmodule Directives do use Absinthe.Schema.Prototype directive :some_directive do on [:field_definition] end end @prototype_schema Directives " type Widget { name: String @some_directive(a: { b: {} }) } type Query { widgets: [Widget!] } " |> import_sdl end """ error = ~r/Unknown argument "a" on directive "@some_directive"./ assert_raise(Absinthe.Schema.Error, error, fn -> Code.eval_string(schema) end) end def handle_event(event, measurements, metadata, config) do send(self(), {event, measurements, metadata, config}) end describe "telemetry" do setup context do :telemetry.attach_many( context.test, [ [:absinthe, :resolve, :field, :start], [:absinthe, :resolve, :field, :stop], [:absinthe, :execute, :operation, :start], [:absinthe, :execute, :operation, :stop] ], &__MODULE__.handle_event/4, %{} ) on_exit(fn -> :telemetry.detach(context.test) end) :ok end test "executes on SDL defined schemas" do assert {:ok, %{data: %{"posts" => [%{"upcasedTitle" => "FOO"}, %{"upcasedTitle" => "BAR"}]}}} = Absinthe.run(@query, Definition) assert_receive {[:absinthe, :execute, :operation, :start], _, %{id: id}, _config} assert_receive {[:absinthe, :execute, :operation, :stop], _measurements, %{id: ^id}, _config} assert_receive {[:absinthe, :resolve, :field, :start], _measurements, %{resolution: %{definition: %{name: "posts"}}}, _config} assert_receive {[:absinthe, :resolve, :field, :stop], _measurements, %{resolution: %{definition: %{name: "posts"}}}, _config} end end end
26.755267
120
0.595166
030d188ab527387c6cab22be1517eadd305f9086
712
ex
Elixir
elixir/kyu6/unique_strings.ex
stallmanifold/codewars
28313881ab1ead1bdfbb6e0724c3794ee14455f3
[ "Apache-2.0", "MIT" ]
null
null
null
elixir/kyu6/unique_strings.ex
stallmanifold/codewars
28313881ab1ead1bdfbb6e0724c3794ee14455f3
[ "Apache-2.0", "MIT" ]
null
null
null
elixir/kyu6/unique_strings.ex
stallmanifold/codewars
28313881ab1ead1bdfbb6e0724c3794ee14455f3
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule Util do def factorial(n) do case n do n when n <= 1 -> 1 _ -> n * factorial(n - 1) end end def product(ns) do Enum.reduce(ns, 1, fn acc, n -> acc * n end) end end defmodule UniqueStrings do def uniq_count(string) do IO.puts(string) char_counts = String.upcase(string) |> String.graphemes() |> Enum.sort() |> Enum.chunk_by(fn x -> x end) |> Enum.map(fn s -> length(s) end) numerator = Util.factorial(String.length(string)) denominator = char_counts |> Enum.map(fn n -> Util.factorial(n) end) |> Util.product() div(numerator, denominator) end end
24.551724
58
0.543539
030d1978384e8597c8d05f9c9df401a249e3aeb3
2,589
exs
Elixir
apps/service_receive/test/receive_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
12
2020-01-27T19:43:02.000Z
2021-07-28T19:46:29.000Z
apps/service_receive/test/receive_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
81
2020-01-28T18:07:23.000Z
2021-11-22T02:12:13.000Z
apps/service_receive/test/receive_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule ReceiveTest do use ExUnit.Case import Events, only: [accept_start: 0] import Definition, only: [identifier: 1] import AssertAsync require Temp.Env @instance Receive.Application.instance() Temp.Env.modify([ %{ app: :service_receive, key: Receive.SocketManager, set: [batch_size: 10] } ]) describe "Receive Udp" do setup do start_supervised({SourceUdpSocket, port: 6789, schedule: true, interval: 100}) accept = Accept.new!( id: "accept-id-1", dataset_id: "test-ds1", subset_id: "test-ss1", destination: Destination.Fake.new!(), connection: Accept.Udp.new!(port: 6789) ) on_exit(fn -> Receive.Accept.Supervisor.kill_all_children() end) [accept: accept] end setup do on_exit(fn -> Brook.Test.clear_view_state(@instance, "accepts") end) :ok end test "receives data from source", %{accept: accept} do Brook.Test.send(@instance, accept_start(), "testing", accept) assert_receive {:destination_start_link, id}, 5_000 assert_receive {:destination_write, messages}, 5_000 assert length(messages) == 10 assert {:ok, ^accept} = Receive.ViewState.Accepts.get(identifier(accept)) end end describe "Receive Websocket" do setup do accept = Accept.new!( id: "accept-id-2", dataset_id: "test-ds2", subset_id: "test-ss2", destination: Destination.Fake.new!(), connection: Accept.Websocket.new!(port: 6790, path: "/receive/ws") ) on_exit(fn -> Receive.Accept.Supervisor.kill_all_children() end) [accept: accept] end setup do on_exit(fn -> Brook.Test.clear_view_state(@instance, "accepts") end) :ok end test "receives data from source", %{accept: accept} do Brook.Test.send(@instance, accept_start(), "testing", accept) {:ok, client} = start_supervised({SourceWebsocket, port: 6790, host: "localhost", path: "/receive/ws"}) assert_async do Enum.map(0..10, fn int -> SourceWebsocket.push(client, "msg#{int}") end) assert_receive {:destination_write, messages} assert length(messages) == 10 refute "msg10" in messages assert {:ok, ^accept} = Receive.ViewState.Accepts.get(identifier(accept)) end flush_queue(client) end end defp flush_queue(client) do stop_supervised(client) Process.sleep(1_000) end end
23.752294
95
0.609502
030d2795c6f939b04ac5f8de164e14454da73aca
8,342
ex
Elixir
clients/admin/lib/google_api/admin/directory_v1/api/tokens.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/admin/lib/google_api/admin/directory_v1/api/tokens.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/admin/lib/google_api/admin/directory_v1/api/tokens.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.Admin.Directory_v1.Api.Tokens do @moduledoc """ API calls for all endpoints tagged `Tokens`. """ alias GoogleApi.Admin.Directory_v1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Delete all access tokens issued by a user for an application. ## Parameters * `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server * `user_key` (*type:* `String.t`) - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * `client_id` (*type:* `String.t`) - The Client ID of the application the token is issued to. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec directory_tokens_delete(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()} def directory_tokens_delete(connection, user_key, client_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/users/{userKey}/tokens/{clientId}", %{ "userKey" => URI.encode(user_key, &URI.char_unreserved?/1), "clientId" => URI.encode(client_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Get information about an access token issued by a user. ## Parameters * `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server * `user_key` (*type:* `String.t`) - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * `client_id` (*type:* `String.t`) - The Client ID of the application the token is issued to. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Admin.Directory_v1.Model.Token{}}` on success * `{:error, info}` on failure """ @spec directory_tokens_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Admin.Directory_v1.Model.Token.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def directory_tokens_get(connection, user_key, client_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/users/{userKey}/tokens/{clientId}", %{ "userKey" => URI.encode(user_key, &URI.char_unreserved?/1), "clientId" => URI.encode(client_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Admin.Directory_v1.Model.Token{}]) end @doc """ Returns the set of tokens specified user has issued to 3rd party applications. ## Parameters * `connection` (*type:* `GoogleApi.Admin.Directory_v1.Connection.t`) - Connection to server * `user_key` (*type:* `String.t`) - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Admin.Directory_v1.Model.Tokens{}}` on success * `{:error, info}` on failure """ @spec directory_tokens_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Admin.Directory_v1.Model.Tokens.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def directory_tokens_list(connection, user_key, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/users/{userKey}/tokens", %{ "userKey" => URI.encode(user_key, &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.Admin.Directory_v1.Model.Tokens{}]) end end
45.584699
187
0.645768
030d2b9f19947540d453c8fd532e74f9d5f07d74
1,235
ex
Elixir
lib/quarto/ecto/cursor_fields.ex
daskycodes/quarto
5169efd8d4816044fdca8a95b8fc5b4c4f0d1de9
[ "MIT" ]
25
2020-04-25T13:43:26.000Z
2022-03-27T22:05:33.000Z
lib/quarto/ecto/cursor_fields.ex
daskycodes/quarto
5169efd8d4816044fdca8a95b8fc5b4c4f0d1de9
[ "MIT" ]
28
2020-05-20T05:28:02.000Z
2022-02-28T04:03:07.000Z
lib/quarto/ecto/cursor_fields.ex
daskycodes/quarto
5169efd8d4816044fdca8a95b8fc5b4c4f0d1de9
[ "MIT" ]
3
2021-04-10T23:06:02.000Z
2021-09-06T04:05:49.000Z
defmodule Quarto.Ecto.CursorFields do @moduledoc """ Derive the cursor fields from a given queryable """ @type field :: atom() @type position :: pos_integer() @type direction :: :asc | :desc @doc """ build/2 accepts an Ecto.Query and inspects the Ecto AST to retrieve the fields the query will order by. These will be used to create the cursor. """ @spec build(queryable :: Ecto.Query.t(), config :: Keyword.t()) :: [ {field(), {position(), direction()}} ] def build(%Ecto.Query{order_bys: order_bys} = queryable, _config) do Enum.map(order_bys, fn %Ecto.Query.QueryExpr{expr: expr} -> case expr do [{direction, {{:., [], [{:&, [], [position]}, field]}, [], []}}] -> {field, {position, direction}} [{_direction, {:fragment, [], _ast}}] -> raise ArgumentError, "Fragments not supported currently, got: #{inspect(queryable)}" [{_direction, _unsupported}] -> raise ArgumentError, "Unsupported clause passed into order by expr #{inspect(queryable)}" end end) end def build(unknown, _config) do raise ArgumentError, "Expecting an `%Ecto.Query{}` struct, got: #{inspect(unknown)}" end end
30.121951
94
0.610526
030d33c22cd3584a59e74c493f9c0397d2def8e1
603
ex
Elixir
lib/stripe/subscriptions/discount.ex
neneboe/stripity_stripe
e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17
[ "BSD-3-Clause" ]
2
2019-05-02T10:42:09.000Z
2019-12-02T21:29:17.000Z
lib/stripe/subscriptions/discount.ex
neneboe/stripity_stripe
e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17
[ "BSD-3-Clause" ]
1
2020-05-20T21:04:19.000Z
2020-05-20T21:04:19.000Z
lib/stripe/subscriptions/discount.ex
neneboe/stripity_stripe
e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17
[ "BSD-3-Clause" ]
1
2021-12-01T21:49:27.000Z
2021-12-01T21:49:27.000Z
defmodule Stripe.Discount do @moduledoc """ Work with Stripe discounts. Stripe API reference: https://stripe.com/docs/api#discounts """ use Stripe.Entity @type t :: %__MODULE__{ object: String.t(), coupon: Stripe.Coupon.t(), customer: Stripe.id() | Stripe.Customer.t() | nil, deleted: boolean | nil, end: Stripe.timestamp() | nil, start: Stripe.timestamp(), subscription: Stripe.id() | nil } defstruct [ :object, :coupon, :customer, :deleted, :end, :start, :subscription ] end
20.1
61
0.565506
030d3de3e0ac3af7b0910070ab73b6c29334bf4b
1,681
ex
Elixir
apps/core/lib/core/schema/docker_image.ex
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
59
2021-09-16T19:29:39.000Z
2022-03-31T20:44:24.000Z
apps/core/lib/core/schema/docker_image.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
111
2021-08-15T09:56:37.000Z
2022-03-31T23:59:32.000Z
apps/core/lib/core/schema/docker_image.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
4
2021-12-13T09:43:01.000Z
2022-03-29T18:08:44.000Z
defmodule Core.Schema.DockerImage do use Piazza.Ecto.Schema alias Core.Schema.{DockerRepository, Vulnerability} defenum Grade, a: 0, b: 1, c: 2, d: 3, f: 4 schema "docker_images" do field :tag, :string field :digest, :string field :grade, Grade field :scanned_at, :utc_datetime_usec has_many :vulnerabilities, Vulnerability, foreign_key: :image_id, on_replace: :delete belongs_to :docker_repository, DockerRepository timestamps() end def for_repositories(query \\ __MODULE__, q) do from(di in query, join: dr in ^subquery(q), where: di.docker_repository_id == dr.id ) end def for_tag(query \\ __MODULE__, tag) do from(di in query, where: di.tag == ^tag) end def scanned_before(query \\ __MODULE__, days) do prior = Timex.now() |> Timex.shift(days: -days) from(di in query, where: di.scanned_at < ^prior or is_nil(di.scanned_at)) end def for_repository(query \\ __MODULE__, repo_id), do: from(di in query, where: di.docker_repository_id == ^repo_id) def ordered(query \\ __MODULE__, order \\ [desc: :inserted_at]), do: from(di in query, order_by: ^order) @valid ~w(tag digest)a def changeset(model, attrs \\ %{}) do model |> cast(attrs, @valid) |> foreign_key_constraint(:repository_id) |> unique_constraint(:name, name: index_name(:docker_images, [:docker_repository_id, :tag])) |> validate_required([:docker_repository_id]) end def vulnerability_changeset(model, attrs \\ %{}) do model |> cast(attrs, [:scanned_at, :grade]) |> cast_assoc(:vulnerabilities) |> validate_required([:scanned_at, :grade]) end end
28.982759
96
0.669839
030d60c628b001dfa26fb664ece07ca61896055f
1,550
ex
Elixir
lib/birdcage_web/views/error_helpers.ex
forest/birdcage
4c1d851d9ae01ebe94c0366a6e2d932db7435d19
[ "Apache-2.0" ]
2
2020-10-04T16:07:25.000Z
2020-12-25T14:28:28.000Z
lib/birdcage_web/views/error_helpers.ex
cognizant-softvision/birdcage
2f766c7bc6d70f1243aab56ad9ac7f7d4c5014fb
[ "Apache-2.0" ]
11
2020-07-10T16:05:17.000Z
2020-08-25T23:44:34.000Z
lib/birdcage_web/views/error_helpers.ex
forest/birdcage
4c1d851d9ae01ebe94c0366a6e2d932db7435d19
[ "Apache-2.0" ]
1
2020-08-06T18:56:52.000Z
2020-08-06T18:56:52.000Z
defmodule BirdcageWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "invalid-feedback", phx_feedback_for: input_id(form, field) ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(BirdcageWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(BirdcageWeb.Gettext, "errors", msg, opts) end end end
32.291667
77
0.665806
030d6463191c4b9e399647b2c23da802be384d06
1,133
ex
Elixir
lib/multiauth_web/controllers/page_controller.ex
drapadubok/multiauth
9ca9294402311c06a082e6972144a2eb8935a797
[ "MIT" ]
1
2018-06-01T02:08:12.000Z
2018-06-01T02:08:12.000Z
lib/multiauth_web/controllers/page_controller.ex
drapadubok/multiauth
9ca9294402311c06a082e6972144a2eb8935a797
[ "MIT" ]
null
null
null
lib/multiauth_web/controllers/page_controller.ex
drapadubok/multiauth
9ca9294402311c06a082e6972144a2eb8935a797
[ "MIT" ]
null
null
null
defmodule MultiauthWeb.PageController do use MultiauthWeb, :controller alias Multiauth.Auth alias Multiauth.Auth.User alias Multiauth.Auth.Guardian def index(conn, _params) do changeset = Auth.change_user(%User{}) maybe_user = Guardian.Plug.current_resource(conn) message = case maybe_user do nil -> "Nobody logged in" _ -> "Someone is logged in" end conn |> put_flash(:info, message) |> render("index.html", changeset: changeset, action: page_path(conn, :login), maybe_user: maybe_user) end def login(conn, %{"user" => %{"username" => username, "password" => password}}) do case Auth.authenticate_user(username, password) do {:ok, user} -> conn |> put_flash(:success, "Welcome back!") |> Guardian.Plug.sign_in(user) |> redirect(to: "/secret") {:error, error} -> conn |> put_flash(:error, error) |> redirect(to: "/") end end def logout(conn, _) do conn |> Guardian.Plug.sign_out() |> redirect(to: "/") end def secret(conn, _params) do render(conn, "secret.html") end end
25.177778
106
0.620477
030d72421aae91ddc226399787651f358728a626
1,046
ex
Elixir
lib/signinsheet/application.ex
Dhall777/signinsheet
703f6f2b0bc4e31888bf7e81939cfd4b05d99cfb
[ "BSD-3-Clause" ]
null
null
null
lib/signinsheet/application.ex
Dhall777/signinsheet
703f6f2b0bc4e31888bf7e81939cfd4b05d99cfb
[ "BSD-3-Clause" ]
null
null
null
lib/signinsheet/application.ex
Dhall777/signinsheet
703f6f2b0bc4e31888bf7e81939cfd4b05d99cfb
[ "BSD-3-Clause" ]
null
null
null
defmodule Signinsheet.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Ecto repository Signinsheet.Repo, # Start the Telemetry supervisor SigninsheetWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Signinsheet.PubSub}, # Start the Endpoint (http/https) SigninsheetWeb.Endpoint # Start a worker by calling: Signinsheet.Worker.start_link(arg) # {Signinsheet.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Signinsheet.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do SigninsheetWeb.Endpoint.config_change(changed, removed) :ok end end
29.885714
69
0.712237
030db974ee59b5473655ed456b994521be3bcb6a
645
ex
Elixir
lib/os/sys_calls/set_pin_io_mode.ex
FarmBot/farmbot_os
5ebdca3afd672eb6b0af5c71cfca02488b32569a
[ "MIT" ]
843
2016-10-05T23:46:05.000Z
2022-03-14T04:31:55.000Z
farmbot_os/lib/farmbot_os/sys_calls/set_pin_io_mode.ex
gdwb/farmbot_os
0ef2697c580c9fbf37a22daa063a64addfcb778d
[ "MIT" ]
455
2016-10-15T08:49:16.000Z
2022-03-15T12:23:04.000Z
farmbot_os/lib/farmbot_os/sys_calls/set_pin_io_mode.ex
gdwb/farmbot_os
0ef2697c580c9fbf37a22daa063a64addfcb778d
[ "MIT" ]
261
2016-10-10T04:37:06.000Z
2022-03-13T21:07:38.000Z
defmodule FarmbotOS.SysCalls.SetPinIOMode do @moduledoc false alias FarmbotCore.Firmware.Command def set_pin_io_mode(pin_number, mode) do mode = extract_set_pin_mode(mode) case Command.set_pin_io_mode(pin_number, mode) do {:ok, _} -> :ok reason -> FarmbotOS.SysCalls.give_firmware_reason("set_pin_io_mode", reason) end end def extract_set_pin_mode("input"), do: 0x0 def extract_set_pin_mode("input_pullup"), do: 0x2 def extract_set_pin_mode("output"), do: 0x1 def extract_set_pin_mode(0x0), do: 0x0 def extract_set_pin_mode(0x2), do: 0x2 def extract_set_pin_mode(0x1), do: 0x1 end
26.875
74
0.724031
030dbab0cf756f92a7da9967d4f42a8ef01b285c
2,328
ex
Elixir
clients/plus_domains/lib/google_api/plus_domains/v1/model/circle.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/plus_domains/lib/google_api/plus_domains/v1/model/circle.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/plus_domains/lib/google_api/plus_domains/v1/model/circle.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.PlusDomains.V1.Model.Circle do @moduledoc """ ## Attributes * `description` (*type:* `String.t`, *default:* `nil`) - The description of this circle. * `displayName` (*type:* `String.t`, *default:* `nil`) - The circle name. * `etag` (*type:* `String.t`, *default:* `nil`) - ETag of this response for caching purposes. * `id` (*type:* `String.t`, *default:* `nil`) - The ID of the circle. * `kind` (*type:* `String.t`, *default:* `plus#circle`) - Identifies this resource as a circle. Value: "plus#circle". * `people` (*type:* `GoogleApi.PlusDomains.V1.Model.CirclePeople.t`, *default:* `nil`) - The people in this circle. * `selfLink` (*type:* `String.t`, *default:* `nil`) - Link to this circle resource """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :description => String.t(), :displayName => String.t(), :etag => String.t(), :id => String.t(), :kind => String.t(), :people => GoogleApi.PlusDomains.V1.Model.CirclePeople.t(), :selfLink => String.t() } field(:description) field(:displayName) field(:etag) field(:id) field(:kind) field(:people, as: GoogleApi.PlusDomains.V1.Model.CirclePeople) field(:selfLink) end defimpl Poison.Decoder, for: GoogleApi.PlusDomains.V1.Model.Circle do def decode(value, options) do GoogleApi.PlusDomains.V1.Model.Circle.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PlusDomains.V1.Model.Circle do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.815385
121
0.675258
030dcddb9dca076e5621362a138bbab3f487b39c
64
ex
Elixir
web/views/user_view.ex
renuo/dev-quotes
dcb187c82697c756f19c40bbe84b0555eda6ae86
[ "MIT" ]
null
null
null
web/views/user_view.ex
renuo/dev-quotes
dcb187c82697c756f19c40bbe84b0555eda6ae86
[ "MIT" ]
null
null
null
web/views/user_view.ex
renuo/dev-quotes
dcb187c82697c756f19c40bbe84b0555eda6ae86
[ "MIT" ]
null
null
null
defmodule DevQuotes.UserView do use DevQuotes.Web, :view end
12.8
31
0.78125
030dd359f830a1bc668b94c072175f54041c51da
1,139
exs
Elixir
clients/dataproc/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/dataproc/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/dataproc/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 :cloud_dataproc_api, key: :value # # And access this configuration in your application as: # # Application.get_env(:cloud_dataproc_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"
36.741935
73
0.755926
030de70575c83f8be5ab14512711d7d240250745
1,284
exs
Elixir
test/freddy/integration/notifications/broadcaster_test.exs
salemove/ex_freddy
78e255121bc722fe3266ceaf04884aadf2f8e2db
[ "MIT" ]
10
2017-06-28T11:39:39.000Z
2021-11-19T23:23:16.000Z
test/freddy/integration/notifications/broadcaster_test.exs
salemove/ex_freddy
78e255121bc722fe3266ceaf04884aadf2f8e2db
[ "MIT" ]
16
2017-01-07T15:34:36.000Z
2021-05-05T11:07:31.000Z
test/freddy/integration/notifications/broadcaster_test.exs
salemove/ex_freddy
78e255121bc722fe3266ceaf04884aadf2f8e2db
[ "MIT" ]
4
2018-10-08T19:54:46.000Z
2021-05-05T10:49:10.000Z
defmodule Freddy.Integration.Notifications.BroadcasterTest do use Freddy.IntegrationCase defmodule TestBroadcaster do use Freddy.Notifications.Broadcaster, warn: false def start_link(conn) do Freddy.Notifications.Broadcaster.start_link(__MODULE__, conn, nil) end end defmodule TestListener do use Freddy.Consumer @config [ queue: [opts: [auto_delete: true]], exchange: [name: "freddy-topic", type: :topic], routing_keys: ["freddy-test"] ] def start_link(conn, pid) do Freddy.Consumer.start_link(__MODULE__, conn, @config, pid) end @impl true def handle_ready(_meta, pid) do send(pid, :consumer_ready) {:noreply, pid} end @impl true def handle_message(message, _meta, pid) do send(pid, {:message_received, message}) {:reply, :ack, pid} end end test "publishes message into freddy-topic exchange", %{connection: connection} do {:ok, broadcaster} = TestBroadcaster.start_link(connection) {:ok, _consumer} = TestListener.start_link(connection, self()) assert_receive :consumer_ready payload = %{"key" => "value"} TestBroadcaster.broadcast(broadcaster, "freddy-test", payload) assert_receive {:message_received, ^payload} end end
25.68
83
0.685358
030dfacf7275db5b5c3aae1e695ab2b314c8875e
2,465
ex
Elixir
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/enum.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/enum.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/enum.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.ServiceConsumerManagement.V1.Model.Enum do @moduledoc """ Enum type definition. ## Attributes * `enumvalue` (*type:* `list(GoogleApi.ServiceConsumerManagement.V1.Model.EnumValue.t)`, *default:* `nil`) - Enum value definitions. * `name` (*type:* `String.t`, *default:* `nil`) - Enum type name. * `options` (*type:* `list(GoogleApi.ServiceConsumerManagement.V1.Model.Option.t)`, *default:* `nil`) - Protocol buffer options. * `sourceContext` (*type:* `GoogleApi.ServiceConsumerManagement.V1.Model.SourceContext.t`, *default:* `nil`) - The source context. * `syntax` (*type:* `String.t`, *default:* `nil`) - The source syntax. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :enumvalue => list(GoogleApi.ServiceConsumerManagement.V1.Model.EnumValue.t()), :name => String.t(), :options => list(GoogleApi.ServiceConsumerManagement.V1.Model.Option.t()), :sourceContext => GoogleApi.ServiceConsumerManagement.V1.Model.SourceContext.t(), :syntax => String.t() } field(:enumvalue, as: GoogleApi.ServiceConsumerManagement.V1.Model.EnumValue, type: :list) field(:name) field(:options, as: GoogleApi.ServiceConsumerManagement.V1.Model.Option, type: :list) field(:sourceContext, as: GoogleApi.ServiceConsumerManagement.V1.Model.SourceContext) field(:syntax) end defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Enum do def decode(value, options) do GoogleApi.ServiceConsumerManagement.V1.Model.Enum.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Enum do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.779661
136
0.727789
030e3f9841d054fcb62010b90690f392a8cbfd16
1,079
ex
Elixir
lib/tap_racer/application.ex
dtcristo/tap-racer
f66a3f4c728d547c85335aea7770e9b9ad857016
[ "MIT" ]
7
2016-06-04T09:24:24.000Z
2017-09-03T16:26:21.000Z
lib/tap_racer/application.ex
dtcristo/tap-racer
f66a3f4c728d547c85335aea7770e9b9ad857016
[ "MIT" ]
10
2020-07-25T02:04:03.000Z
2021-07-28T12:01:20.000Z
lib/tap_racer/application.ex
dtcristo/tap-racer
f66a3f4c728d547c85335aea7770e9b9ad857016
[ "MIT" ]
1
2019-05-17T03:37:43.000Z
2019-05-17T03:37:43.000Z
defmodule TapRacer.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ TapRacer.RoomRegistry, TapRacer.RoomSupervisor, # Start the Ecto repository TapRacer.Repo, # Start the Telemetry supervisor TapRacerWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: TapRacer.PubSub}, # Start the Endpoint (http/https) TapRacerWeb.Endpoint # Start a worker by calling: TapRacer.Worker.start_link(arg) # {TapRacer.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: TapRacer.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do TapRacerWeb.Endpoint.config_change(changed, removed) :ok end end
29.162162
66
0.704356
030e42d305f67e0272b85ed01112febd6c04784b
76
exs
Elixir
test/expyplotplot_test.exs
sezaru/expyplot
17dedaed998042d96293f5912d007d5ad3d0a4df
[ "MIT" ]
30
2017-04-17T09:52:59.000Z
2022-03-28T09:55:05.000Z
test/expyplotplot_test.exs
sezaru/expyplot
17dedaed998042d96293f5912d007d5ad3d0a4df
[ "MIT" ]
1
2020-08-25T17:23:51.000Z
2020-08-27T23:53:19.000Z
test/expyplotplot_test.exs
sezaru/expyplot
17dedaed998042d96293f5912d007d5ad3d0a4df
[ "MIT" ]
4
2019-02-01T07:12:37.000Z
2020-08-24T13:24:07.000Z
defmodule ExpyplotPlotTest do use ExUnit.Case doctest Expyplot.Plot end
15.2
29
0.815789
030e6091094367f3bc7265919fd8ead8585b3b25
331
ex
Elixir
backend/apps/students_crm_v2/lib/students_crm_v2/interactions/academic_group/delete.ex
KyivKrishnaAcademy/students_crm_v2
e0ad9b3c5e52dfef5ab8f9179f3c593f935786e6
[ "MIT" ]
null
null
null
backend/apps/students_crm_v2/lib/students_crm_v2/interactions/academic_group/delete.ex
KyivKrishnaAcademy/students_crm_v2
e0ad9b3c5e52dfef5ab8f9179f3c593f935786e6
[ "MIT" ]
50
2018-07-29T09:17:35.000Z
2019-02-26T05:23:34.000Z
backend/apps/students_crm_v2/lib/students_crm_v2/interactions/academic_group/delete.ex
KyivKrishnaAcademy/students_crm_v2
e0ad9b3c5e52dfef5ab8f9179f3c593f935786e6
[ "MIT" ]
null
null
null
defmodule StudentsCrmV2.Interactions.AcademicGroup.Delete do @moduledoc false alias StudentsCrmV2.Models.AcademicGroup alias StudentsCrmV2.Repo @spec execute(id :: term()) :: {:ok, AcademicGroup.t()} | {:error, Ecto.Changeset.t()} def execute(id) do AcademicGroup |> Repo.get(id) |> Repo.delete() end end
23.642857
88
0.700906
030e78b68108af22be0818cc768ba16843366737
235
ex
Elixir
debian/arakoon.default.ex
Incubaid/arakoon
43a8d0b26e4876ef91d9657149f105c7e57e0cb0
[ "Apache-2.0" ]
41
2015-02-11T03:23:36.000Z
2020-12-27T12:13:52.000Z
debian/arakoon.default.ex
Incubaid/arakoon
43a8d0b26e4876ef91d9657149f105c7e57e0cb0
[ "Apache-2.0" ]
36
2015-01-04T16:58:51.000Z
2020-11-12T12:05:37.000Z
debian/arakoon.default.ex
Incubaid/arakoon
43a8d0b26e4876ef91d9657149f105c7e57e0cb0
[ "Apache-2.0" ]
7
2015-07-10T08:04:01.000Z
2021-09-28T08:09:23.000Z
# Defaults for arakoon initscript # sourced by /etc/init.d/arakoon # installed at /etc/default/arakoon by the maintainer scripts # # This is a POSIX shell fragment # # Additional options that are passed to the Daemon. DAEMON_OPTS=""
21.363636
61
0.761702
030e8fad5c2d6e2fbb8ed38bb60168aea6769ee1
4,669
exs
Elixir
apps/fz_http/test/fz_http_web/live/user_live/show_test.exs
athulspeaks/firezone
98f4709c4d2c03f1ade5167494547ef240a09aed
[ "Apache-2.0" ]
null
null
null
apps/fz_http/test/fz_http_web/live/user_live/show_test.exs
athulspeaks/firezone
98f4709c4d2c03f1ade5167494547ef240a09aed
[ "Apache-2.0" ]
null
null
null
apps/fz_http/test/fz_http_web/live/user_live/show_test.exs
athulspeaks/firezone
98f4709c4d2c03f1ade5167494547ef240a09aed
[ "Apache-2.0" ]
null
null
null
defmodule FzHttpWeb.UserLive.ShowTest do use FzHttpWeb.ConnCase, async: true describe "authenticated show" do setup :create_device test "includes the device name", %{authed_conn: conn, device: device} do path = Routes.user_show_path(conn, :show, device.user_id) {:ok, _view, html} = live(conn, path) assert html =~ device.name end test "opens the edit modal", %{authed_conn: conn, device: device} do path = Routes.user_show_path(conn, :show, device.user_id) {:ok, view, _html} = live(conn, path) view |> element("a", "Change Email or Password") |> render_click() new_path = assert_patch(view) assert new_path == Routes.user_show_path(conn, :edit, device.user_id) end end describe "unauthenticated show" do setup :create_device test "redirects to sign in", %{unauthed_conn: conn, device: device} do path = Routes.user_show_path(conn, :show, device.user_id) expected_path = Routes.session_path(conn, :new) assert {:error, {:redirect, %{to: ^expected_path}}} = live(conn, path) end end describe "delete self" do test "displays flash message with error", %{user_id: user_id, authed_conn: conn} do path = Routes.user_show_path(conn, :show, user_id) {:ok, view, _html} = live(conn, path) new_view = view |> element("button", "Delete User") |> render_click() assert new_view =~ "Use the account section to delete your account." end end describe "delete_user" do setup :create_users test "deletes the user", %{authed_conn: conn, users: users} do user = List.last(users) path = Routes.user_show_path(conn, :show, user.id) {:ok, view, _html} = live(conn, path) view |> element("button", "Delete User") |> render_click() {new_path, flash} = assert_redirect(view) assert flash["info"] == "User deleted successfully." assert new_path == Routes.user_index_path(conn, :index) end end describe "edit user" do setup :create_users setup %{users: users, authed_conn: conn} do user = List.last(users) path = Routes.user_show_path(conn, :edit, user.id) {:ok, view, _html} = live(conn, path) success = fn conn, view, user -> {new_path, flash} = assert_redirect(view) assert flash["info"] == "User updated successfully." assert new_path == Routes.user_show_path(conn, :show, user) end %{success: success, view: view, conn: conn, user: user} end @new_email_attrs %{"user" => %{"email" => "newemail@localhost"}} @new_password_attrs %{ "user" => %{"password" => "new_password", "password_confirmation" => "new_password"} } @new_email_password_attrs %{ "user" => %{ "email" => "newemail@localhost", "password" => "new_password", "password_confirmation" => "new_password" } } @invalid_attrs %{ "user" => %{ "email" => "not_valid", "password" => "short", "password_confirmation" => "short" } } test "successfully changes email", %{success: success, view: view, user: user, conn: conn} do view |> element("form#user-form") |> render_submit(@new_email_attrs) success.(conn, view, user) end test "successfully changes password", %{success: success, view: view, conn: conn, user: user} do view |> element("form#user-form") |> render_submit(@new_password_attrs) success.(conn, view, user) end test "successfully changes email and password", %{ success: success, view: view, conn: conn, user: user } do view |> element("form#user-form") |> render_submit(@new_email_password_attrs) success.(conn, view, user) end test "displays errors for invalid changes", %{view: view} do new_view = view |> element("form#user-form") |> render_submit(@invalid_attrs) assert new_view =~ "has invalid format" assert new_view =~ "should be at least 8 character(s)" end end describe "create_device" do setup :create_users test "creates a new device for user", %{authed_conn: conn, users: users} do user = List.last(users) path = Routes.user_show_path(conn, :show, user.id) {:ok, view, _html} = live(conn, path) view |> element("button", "Add Device") |> render_click() {new_path, flash} = assert_redirect(view) assert flash["info"] == "Device created successfully." assert new_path =~ ~r/\/devices\/\d+/ end end end
28.644172
100
0.613836
030ea14035c2513000e3bcbe0a4ef316efdc8c1b
1,953
ex
Elixir
clients/spanner/lib/google_api/spanner/v1/model/field.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/field.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/field.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.Spanner.V1.Model.Field do @moduledoc """ Message representing a single field of a struct. ## Attributes * `name` (*type:* `String.t`, *default:* `nil`) - The name of the field. For reads, this is the column name. For SQL queries, it is the column alias (e.g., `"Word"` in the query `"SELECT 'hello' AS Word"`), or the column name (e.g., `"ColName"` in the query `"SELECT ColName FROM Table"`). Some columns might have an empty name (e.g., !"SELECT UPPER(ColName)"`). Note that a query result can contain multiple fields with the same name. * `type` (*type:* `GoogleApi.Spanner.V1.Model.Type.t`, *default:* `nil`) - The type of the field. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :name => String.t(), :type => GoogleApi.Spanner.V1.Model.Type.t() } field(:name) field(:type, as: GoogleApi.Spanner.V1.Model.Type) end defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.Field do def decode(value, options) do GoogleApi.Spanner.V1.Model.Field.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.Field do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.875
116
0.697389
030ec4c35a7870833ad01c78817b8781ec8e09d6
1,720
exs
Elixir
test/elexir_test.exs
jonnystorm/elexir
ef197f7c592f1eaa628fcd0970bec856e933284f
[ "WTFPL" ]
null
null
null
test/elexir_test.exs
jonnystorm/elexir
ef197f7c592f1eaa628fcd0970bec856e933284f
[ "WTFPL" ]
null
null
null
test/elexir_test.exs
jonnystorm/elexir
ef197f7c592f1eaa628fcd0970bec856e933284f
[ "WTFPL" ]
2
2021-03-06T19:04:53.000Z
2021-03-07T12:27:54.000Z
defmodule ElexirTest do use ExUnit.Case @moduletag :integrated import Elexir test "generates pattern from line" do string = "access-list outside-ingress extended permit icmp any any log" assert generate_patterns(string, 0) == [~r/^access-list outside-ingress extended permit icmp any any log$/] end test "generates pattern from another line" do string = "access-list outside-ingress extended permit tcp any object AnObject eq https log" assert generate_patterns(string, 0) == [~r/^access-list outside-ingress extended permit tcp any object AnObject eq https log$/] end test "generates patterns for multiple lines" do string = """ access-list outside-ingress extended permit icmp any any log access-list outside-ingress extended permit tcp any object AnObject eq https log """ assert generate_patterns(string, 0.06) == [ ~r/^access-list outside-ingress extended permit \S+ any \S+ \S+ \S+ \S+ log$/, ~r/^access-list outside-ingress extended permit \S+ any \S+ log$/, ] end test "generates patterns for multiple lines with a different threshold" do string = """ access-list outside-ingress extended permit icmp any any log access-list outside-ingress extended permit tcp any object AnObject eq https log """ assert generate_patterns(string, 0.12) == [] end test "generates patterns for multiple lines with threshold at maximum" do string = """ access-list outside-ingress extended permit icmp any any log access-list outside-ingress extended permit tcp any object AnObject eq https log """ assert generate_patterns(string, 1) == [] end end
31.272727
95
0.69186
030edb479208f2ed552743cfd1738d5d5a63dc1d
346
exs
Elixir
sources/Chapter7/mylist1.exs
Geroshabu/ProgrammingElixir
979a835fc728f750af50a3ae771ebbac2ab4000f
[ "MIT" ]
null
null
null
sources/Chapter7/mylist1.exs
Geroshabu/ProgrammingElixir
979a835fc728f750af50a3ae771ebbac2ab4000f
[ "MIT" ]
null
null
null
sources/Chapter7/mylist1.exs
Geroshabu/ProgrammingElixir
979a835fc728f750af50a3ae771ebbac2ab4000f
[ "MIT" ]
null
null
null
defmodule MyList do def len([]), do: 0 def len([_head|tail]), do: 1 + len(tail) def square([]), do: [] def square([head|tail]), do: [head*head | square(tail)] def add_1([]), do: [] def add_1([head|tail]), do: [head+1 | add_1(tail)] def map([], _func), do: [] def map([head|tail], func), do: [func.(head) | map(tail, func)] end
24.714286
65
0.566474
030f085a5c7969856d3617d18802df128ccefd43
802
exs
Elixir
test/strkey/strkey_error_test.exs
kommitters/stellar_base
cf36723d5add4fead1029526230299def68048fe
[ "MIT" ]
3
2021-08-17T20:32:45.000Z
2022-03-13T20:26:02.000Z
test/strkey/strkey_error_test.exs
kommitters/stellar_base
cf36723d5add4fead1029526230299def68048fe
[ "MIT" ]
45
2021-08-12T20:19:41.000Z
2022-03-27T21:00:10.000Z
test/strkey/strkey_error_test.exs
kommitters/stellar_base
cf36723d5add4fead1029526230299def68048fe
[ "MIT" ]
2
2021-09-22T23:11:13.000Z
2022-01-23T03:19:11.000Z
defmodule StellarBase.StrKeyErrorTest do use ExUnit.Case alias StellarBase.StrKeyError test "invalid_binary" do assert_raise StrKeyError, "cannot encode nil data", fn -> raise StrKeyError, :invalid_binary end end test "invalid_data" do assert_raise StrKeyError, "cannot decode nil data", fn -> raise StrKeyError, :invalid_data end end test "invalid_checksum" do assert_raise StrKeyError, "invalid checksum", fn -> raise StrKeyError, :invalid_checksum end end test "unmatched_version_byte" do assert_raise StrKeyError, "version byte does not match", fn -> raise StrKeyError, :unmatched_version_byte end end test "error" do assert_raise StrKeyError, "error", fn -> raise StrKeyError, "error" end end end
22.277778
66
0.703242
030f2063b8fe31f98d4f661d4db82763b6f2ae5d
513
ex
Elixir
exercises/concept/newsletter/lib/newsletter.ex
herminiotorres/exercism-elixir
0464a968f3e37680b2bf34868b889d6f8de5581e
[ "MIT" ]
200
2019-12-12T13:50:59.000Z
2022-02-20T22:38:42.000Z
exercises/concept/newsletter/lib/newsletter.ex
herminiotorres/exercism-elixir
0464a968f3e37680b2bf34868b889d6f8de5581e
[ "MIT" ]
1,938
2019-12-12T08:07:10.000Z
2021-01-29T12:56:13.000Z
exercises/concept/newsletter/lib/newsletter.ex
herminiotorres/exercism-elixir
0464a968f3e37680b2bf34868b889d6f8de5581e
[ "MIT" ]
239
2019-12-12T14:09:08.000Z
2022-03-18T00:04:07.000Z
defmodule Newsletter do def read_emails(path) do raise "Please implement the read_emails/1 function" end def open_log(path) do raise "Please implement the open_log/1 function" end def log_sent_email(pid, email) do raise "Please implement the log_sent_email/2 function" end def close_log(pid) do raise "Please implement the close_log/1 function" end def send_newsletter(emails_path, log_path, send_fun) do raise "Please implement the send_newsletter/3 function" end end
23.318182
59
0.748538
030f396e09701a390abdd3c97557ad24cececde4
15,780
ex
Elixir
clients/android_publisher/lib/google_api/android_publisher/v2/api/inappproducts.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/android_publisher/lib/google_api/android_publisher/v2/api/inappproducts.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/android_publisher/lib/google_api/android_publisher/v2/api/inappproducts.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidPublisher.V2.Api.Inappproducts do @moduledoc """ API calls for all endpoints tagged `Inappproducts`. """ alias GoogleApi.AndroidPublisher.V2.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Delete an in-app product for an app. ## Parameters - connection (GoogleApi.AndroidPublisher.V2.Connection): Connection to server - package_name (String.t): Unique identifier for the Android app with the in-app product; for example, \&quot;com.spiffygame\&quot;. - sku (String.t): Unique identifier for the in-app product. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec androidpublisher_inappproducts_delete( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, nil} | {:error, Tesla.Env.t()} def androidpublisher_inappproducts_delete( connection, package_name, sku, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}", %{ "packageName" => URI.encode(package_name, &URI.char_unreserved?/1), "sku" => URI.encode(sku, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Returns information about the in-app product specified. ## Parameters - connection (GoogleApi.AndroidPublisher.V2.Connection): Connection to server - package_name (String.t): - sku (String.t): Unique identifier for the in-app product. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}} on success {:error, info} on failure """ @spec androidpublisher_inappproducts_get(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.AndroidPublisher.V2.Model.InAppProduct.t()} | {:error, Tesla.Env.t()} def androidpublisher_inappproducts_get( connection, package_name, sku, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}", %{ "packageName" => URI.encode(package_name, &URI.char_unreserved?/1), "sku" => URI.encode(sku, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}]) end @doc """ Creates a new in-app product for an app. ## Parameters - connection (GoogleApi.AndroidPublisher.V2.Connection): Connection to server - package_name (String.t): Unique identifier for the Android app; for example, \&quot;com.spiffygame\&quot;. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :autoConvertMissingPrices (boolean()): If true the prices for all regions targeted by the parent app that don&#39;t have a price specified for this in-app product will be auto converted to the target currency based on the default price. Defaults to false. - :body (InAppProduct): ## Returns {:ok, %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}} on success {:error, info} on failure """ @spec androidpublisher_inappproducts_insert(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.AndroidPublisher.V2.Model.InAppProduct.t()} | {:error, Tesla.Env.t()} def androidpublisher_inappproducts_insert( connection, package_name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :autoConvertMissingPrices => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/androidpublisher/v2/applications/{packageName}/inappproducts", %{ "packageName" => URI.encode(package_name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}]) end @doc """ List all the in-app products for an Android app, both subscriptions and managed in-app products.. ## Parameters - connection (GoogleApi.AndroidPublisher.V2.Connection): Connection to server - package_name (String.t): Unique identifier for the Android app with in-app products; for example, \&quot;com.spiffygame\&quot;. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :maxResults (integer()): - :startIndex (integer()): - :token (String.t): ## Returns {:ok, %GoogleApi.AndroidPublisher.V2.Model.InappproductsListResponse{}} on success {:error, info} on failure """ @spec androidpublisher_inappproducts_list(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.AndroidPublisher.V2.Model.InappproductsListResponse.t()} | {:error, Tesla.Env.t()} def androidpublisher_inappproducts_list( connection, package_name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :maxResults => :query, :startIndex => :query, :token => :query } request = Request.new() |> Request.method(:get) |> Request.url("/androidpublisher/v2/applications/{packageName}/inappproducts", %{ "packageName" => URI.encode(package_name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AndroidPublisher.V2.Model.InappproductsListResponse{}] ) end @doc """ Updates the details of an in-app product. This method supports patch semantics. ## Parameters - connection (GoogleApi.AndroidPublisher.V2.Connection): Connection to server - package_name (String.t): Unique identifier for the Android app with the in-app product; for example, \&quot;com.spiffygame\&quot;. - sku (String.t): Unique identifier for the in-app product. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :autoConvertMissingPrices (boolean()): If true the prices for all regions targeted by the parent app that don&#39;t have a price specified for this in-app product will be auto converted to the target currency based on the default price. Defaults to false. - :body (InAppProduct): ## Returns {:ok, %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}} on success {:error, info} on failure """ @spec androidpublisher_inappproducts_patch( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, GoogleApi.AndroidPublisher.V2.Model.InAppProduct.t()} | {:error, Tesla.Env.t()} def androidpublisher_inappproducts_patch( connection, package_name, sku, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :autoConvertMissingPrices => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}", %{ "packageName" => URI.encode(package_name, &URI.char_unreserved?/1), "sku" => URI.encode(sku, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}]) end @doc """ Updates the details of an in-app product. ## Parameters - connection (GoogleApi.AndroidPublisher.V2.Connection): Connection to server - package_name (String.t): Unique identifier for the Android app with the in-app product; for example, \&quot;com.spiffygame\&quot;. - sku (String.t): Unique identifier for the in-app product. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :autoConvertMissingPrices (boolean()): If true the prices for all regions targeted by the parent app that don&#39;t have a price specified for this in-app product will be auto converted to the target currency based on the default price. Defaults to false. - :body (InAppProduct): ## Returns {:ok, %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}} on success {:error, info} on failure """ @spec androidpublisher_inappproducts_update( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, GoogleApi.AndroidPublisher.V2.Model.InAppProduct.t()} | {:error, Tesla.Env.t()} def androidpublisher_inappproducts_update( connection, package_name, sku, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :autoConvertMissingPrices => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}", %{ "packageName" => URI.encode(package_name, &URI.char_unreserved?/1), "sku" => URI.encode(sku, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.AndroidPublisher.V2.Model.InAppProduct{}]) end end
41.09375
261
0.672243