hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
1c00333a5e465c399a57f0b4e456a56ecdae45e2
182
exs
Elixir
test/fixtures/failure_simple/validate.exs
axelson/mix_machine
f5d2ee0fb98dd8c939671be1993badd41444cad6
[ "MIT" ]
7
2021-09-28T20:57:33.000Z
2021-11-27T19:46:28.000Z
test/fixtures/failure_simple/validate.exs
axelson/mix_machine
f5d2ee0fb98dd8c939671be1993badd41444cad6
[ "MIT" ]
8
2021-09-29T17:55:57.000Z
2022-01-19T11:38:30.000Z
test/fixtures/failure_simple/validate.exs
axelson/mix_machine
f5d2ee0fb98dd8c939671be1993badd41444cad6
[ "MIT" ]
2
2021-09-30T09:47:06.000Z
2021-11-27T02:35:12.000Z
{input, _} = Code.eval_file("../common.exs") import ExUnit.Assertions results_count = input.report |> Enum.map(& &1["results_count"]) |> Enum.sum() assert results_count > 0
16.545455
44
0.67033
1c0036bb105c1e105e1e4ced5246ccdfdb24fc64
198
exs
Elixir
priv/repo/migrations/20210811201246_add_default_item_to_program.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
28
2021-10-11T01:53:53.000Z
2022-03-24T17:45:55.000Z
priv/repo/migrations/20210811201246_add_default_item_to_program.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
20
2021-10-21T08:12:31.000Z
2022-03-31T13:35:53.000Z
priv/repo/migrations/20210811201246_add_default_item_to_program.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
null
null
null
defmodule BikeBrigade.Repo.Migrations.AddDefaultItemToProgram do use Ecto.Migration def change do alter table(:programs) do add :default_item_id, references(:items) end end end
19.8
64
0.747475
1c004f744ac39064f2b7d46c9ae3dc0e78847e0b
7,450
ex
Elixir
apps/vax/lib/vax/adapter.ex
vaxine-io/vaxine
872a83ea8d4935a52c7b850bb17ab099ee9c346b
[ "Apache-2.0" ]
8
2022-03-14T15:33:08.000Z
2022-03-30T22:06:04.000Z
apps/vax/lib/vax/adapter.ex
vaxine-io/vaxine
872a83ea8d4935a52c7b850bb17ab099ee9c346b
[ "Apache-2.0" ]
9
2022-03-15T15:48:28.000Z
2022-03-21T23:11:34.000Z
apps/vax/lib/vax/adapter.ex
vaxine-io/vaxine
872a83ea8d4935a52c7b850bb17ab099ee9c346b
[ "Apache-2.0" ]
null
null
null
defmodule Vax.Adapter do @moduledoc """ Ecto adapter for Vaxine """ alias Vax.ConnectionPool alias Vax.Adapter.AntidoteClient alias Vax.Adapter.Query @bucket "vax" @behaviour Ecto.Adapter @behaviour Ecto.Adapter.Queryable @behaviour Ecto.Adapter.Storage @impl Ecto.Adapter.Queryable def stream(_adapter_meta, _query_meta, _query_cache, _params, _options) do raise "Not implemented" end @impl Ecto.Adapter.Queryable def prepare(:update_all, _query), do: raise("Not implemented") def prepare(:delete_all, _query), do: raise("Not implemented") def prepare(:all, query) do {:nocache, query} end @impl Ecto.Adapter.Queryable def execute(adapter_meta, query_meta, {:nocache, query}, params, _options) do objs = Query.query_to_objs(query, params, @bucket) fields = Query.select_fields(query_meta) schema = Query.select_schema(query) defaults = struct(schema) execute_static_transaction(adapter_meta.repo, fn conn, tx_id -> {:ok, results} = AntidoteClient.read_objects(conn, objs, tx_id) results = for result <- results, {:antidote_map, values, _adds, _removes} = result, values != %{} do Enum.map(fields, fn field -> field_type = schema.__schema__(:type, field) field_default = Map.get(defaults, field) Vax.Adapter.Helpers.get_antidote_map_field_or_default( result, Atom.to_string(field), field_type, field_default ) end) end {Enum.count(results), results} end) end @impl Ecto.Adapter def loaders(_primitive_type, :string), do: [&Vax.Type.client_load/1, :string] def loaders(_primitive_type, :binary_id), do: [&Vax.Type.client_load/1, :binary_id] def loaders(_primitive_type, ecto_type) do if Vax.Type.base_or_composite?(ecto_type) do [&Vax.Type.client_load/1, &binary_to_term/1, ecto_type] else [ecto_type] end end @impl Ecto.Adapter def dumpers(:binary_id, type), do: [type] def dumpers(:string, :string), do: [:string] def dumpers({:in, _primitive_type}, {:in, ecto_type}), do: [&dump_inner(&1, ecto_type)] def dumpers(_primitive_type, ecto_type), do: [ecto_type, &term_to_binary/1] defp term_to_binary(term), do: {:ok, :erlang.term_to_binary(term)} defp binary_to_term(nil), do: {:ok, nil} defp binary_to_term([]), do: {:ok, nil} defp binary_to_term(binary), do: {:ok, :erlang.binary_to_term(binary)} defp dump_inner(values, ecto_type) do values |> Enum.reduce_while([], fn v, acc -> case Ecto.Type.adapter_dump(__MODULE__, ecto_type, v) do {:ok, v} -> {:cont, [v | acc]} :error -> {:halt, :error} end end) |> case do :error -> :error list -> {:ok, Enum.reverse(list)} end end @impl Ecto.Adapter def init(config) do log? = Keyword.get(config, :log, true) if log?, do: Vax.Adapter.Logger.attach() opts = config |> Keyword.update!(:hostname, &String.to_charlist/1) |> Keyword.put_new(:port, 8087) |> Keyword.put_new(:pool_size, 10) {:ok, ConnectionPool.child_spec(opts), %{}} end @impl Ecto.Adapter def ensure_all_started(_config, _type) do {:ok, []} end @impl Ecto.Adapter def checkout(%{repo: repo}, _config, function) do if Process.get(:vax_checked_out_conn) do function.() else pool = ConnectionPool.pool_name(repo) ConnectionPool.checkout(pool, fn {_pid, _ref}, pid -> try do Process.put(:vax_checked_out_conn, pid) result = function.() {result, pid} after Process.put(:vax_checked_out_conn, nil) end end) end end @impl Ecto.Adapter def checked_out?(_adapter_meta) do not is_nil(Process.get(:vax_checked_out_conn)) end @impl Ecto.Adapter defmacro __before_compile__(_env) do quote do @doc """ Increments a counter See `Vax.Adapter.increment_counter/3` for more information """ @spec increment_counter(key :: binary(), amount :: integer()) :: :ok def increment_counter(key, amount) do Vax.Adapter.increment_counter(__MODULE__, key, amount) end @doc """ Reads a counter See `Vax.Adapter.read_counter/2` for more information """ @spec read_counter(key :: binary()) :: integer() def read_counter(key) do Vax.Adapter.read_counter(__MODULE__, key) end def insert(changeset_or_struct, opts \\ []) do Vax.Adapter.Schema.insert(__MODULE__, changeset_or_struct, opts) end def update(changeset, opts \\ []) do Vax.Adapter.Schema.update(__MODULE__, changeset, opts) end def insert_or_update(changeset, opts \\ []) do Vax.Adapter.Schema.insert_or_update(__MODULE__, changeset, opts) end def delete(schema, opts \\ []) do Vax.Adapter.Schema.delete(__MODULE__, schema, opts) end def insert!(changeset_or_struct, opts \\ []) do Vax.Adapter.Schema.insert!(__MODULE__, changeset_or_struct, opts) end def update!(changeset, opts \\ []) do Vax.Adapter.Schema.update!(__MODULE__, changeset, opts) end def insert_or_update!(changeset, opts \\ []) do Vax.Adapter.Schema.insert_or_update!(__MODULE__, changeset, opts) end def delete!(schema, opts \\ []) do Vax.Adapter.Schema.delete!(__MODULE__, schema, opts) end @doc """ Executes a static transaction """ @spec execute_static_transaction((conn :: pid(), tx_id :: term() -> result :: term())) :: term() def execute_static_transaction(fun) do Vax.Adapter.execute_static_transaction(__MODULE__, fun) end end end @impl Ecto.Adapter.Storage def storage_up(_) do :ok end @impl Ecto.Adapter.Storage def storage_down(_) do :ok end @impl Ecto.Adapter.Storage def storage_status(_) do :up end @doc """ Reads a counter """ @spec read_counter(repo :: atom() | pid(), key :: binary()) :: integer() def read_counter(repo, key) do execute_static_transaction(repo, fn conn, tx_id -> obj = {key, :antidote_crdt_counter_pn, @bucket} {:ok, [result]} = AntidoteClient.read_objects(conn, [obj], tx_id) :antidotec_counter.value(result) end) end @doc """ Increases a counter """ @spec increment_counter(repo :: atom() | pid(), key :: binary(), amount :: integer()) :: :ok def increment_counter(repo, key, amount) do execute_static_transaction(repo, fn conn, tx_id -> obj = {key, :antidote_crdt_counter_pn, @bucket} counter = :antidotec_counter.increment(amount, :antidotec_counter.new()) counter_update_ops = :antidotec_counter.to_ops(obj, counter) AntidoteClient.update_objects(conn, counter_update_ops, tx_id) end) end defp get_conn(), do: Process.get(:vax_checked_out_conn) || raise("Missing connection") def execute_static_transaction(repo, fun) when is_atom(repo) or is_pid(repo) do meta = Ecto.Adapter.lookup_meta(repo) execute_static_transaction(meta, fun) end def execute_static_transaction(meta, fun) do checkout(meta, [], fn -> conn = get_conn() {:ok, tx_id} = AntidoteClient.start_transaction(conn, :ignore, static: true) fun.(conn, tx_id) end) end end
28.007519
95
0.64349
1c0061dfb90a60ab5eca9c0e9d1b9991a4655e0f
6,404
ex
Elixir
lib/game/config.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
lib/game/config.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
lib/game/config.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
defmodule Game.Config do @moduledoc """ Hold Config to not query as often """ alias Data.Config alias Data.Repo alias Data.Save alias Data.Stats @color_config %{ color_home_header: "#268bd2", color_home_link: "#268bd2", color_home_link_hover: "#31b5ff", color_home_primary: "#268bd2", color_home_primary_hover: "#2a99e7", color_home_primary_text: "#fff", color_home_secondary: "#fdf6e3", color_home_secondary_hover: "#fcf1d5", color_home_secondary_text: "#657b83", color_background: "#002b36", color_text_color: "#93a1a1", color_panel_border: "#073642", color_prompt_background: "#fdf6e3", color_prompt_color: "#586e75", color_character_info_background: "#073642", color_character_info_text: "#93a1a1", color_room_info_background: "#073642", color_room_info_text: "#93a1a1", color_room_info_exit: "#93a1a1", color_stat_block_background: "#eee8d5", color_health_bar: "#dc322f", color_health_bar_background: "#fdf6e3", color_skill_bar: "#859900", color_skill_bar_background: "#fdf6e3", color_endurance_bar: "#268bd2", color_endurance_bar_background: "#fdf6e3", color_experience_bar: "#6c71c4", color_black: "#003541", color_red: "#dc322f", color_green: "#859900", color_yellow: "#b58900", color_blue: "#268bd2", color_magenta: "#d33682", color_cyan: "#2aa198", color_white: "#eee8d5", color_map_default: "#9cb7ba", color_map_blue: "#005fd7", color_map_brown: "#875f00", color_map_dark_green: "#005f00", color_map_green: "#00af00", color_map_grey: "#7e9693", color_map_light_grey: "#b6c6c6" } @basic_stats %{ health_points: 50, max_health_points: 50, skill_points: 50, max_skill_points: 50, endurance_points: 20, max_endurance_points: 20, strength: 10, agility: 10, vitality: 10, intelligence: 10, awareness: 10 } @doc false def start_link() do Agent.start_link(fn -> %{} end, name: __MODULE__) end def color_config(), do: @color_config @doc """ Reload a config from the database """ @spec reload(String.t()) :: any() def reload(name) do value = Config.find_config(name) Agent.update(__MODULE__, &Map.put(&1, name, value)) value end def find_config(name) do case Agent.get(__MODULE__, &Map.get(&1, name, nil)) do nil -> reload(name) value -> value end end def host() do ExVenture.config(Application.get_env(:ex_venture, :networking)[:host]) end def port() do ExVenture.config(Application.get_env(:ex_venture, :networking)[:port]) end def ssl?(), do: ssl_port() != nil def ssl_port() do port = Keyword.get(Application.get_env(:ex_venture, :networking), :ssl_port, nil) ExVenture.config(port) end @doc """ Number of "ticks" before regeneration occurs """ @spec regen_tick_count(Integer.t()) :: Integer.t() def regen_tick_count(default) do case find_config("regen_tick_count") do nil -> default regen_tick_count -> regen_tick_count |> Integer.parse() |> elem(0) end end @doc """ The Game's name Used in web page titles """ @spec game_name(String.t()) :: String.t() def game_name(default \\ "ExVenture") do case find_config("game_name") do nil -> default game_name -> game_name end end @doc """ Message of the Day Used during sign in """ @spec motd(String.t()) :: String.t() def motd(default \\ "Welcome to ExVenture") do case find_config("motd") do nil -> default motd -> motd end end @doc """ Message after signing into the game Used during sign in """ @spec after_sign_in_message(String.t()) :: String.t() def after_sign_in_message(default \\ "") do case find_config("after_sign_in_message") do nil -> default motd -> motd end end @doc """ Starting save Which room, etc the player will start out with """ @spec starting_save() :: map() def starting_save() do case find_config("starting_save") do nil -> nil save -> {:ok, save} = Save.load(Poison.decode!(save)) save end end def starting_room_ids() do case find_config("starting_room_ids") do nil -> [] room_ids -> Poison.decode!(room_ids) end end def starting_room_id() do starting_room_ids() |> Enum.shuffle() |> List.first() end @doc """ Your pool of random character names to offer to players signing up """ @spec character_names() :: [String.t()] def character_names() do case find_config("character_names") do nil -> [] names -> names |> String.split("\n") |> Enum.map(&String.trim/1) end end @doc """ Pick a random set of 5 names """ @spec random_character_names() :: [String.t()] def random_character_names() do character_names() |> Enum.shuffle() |> Enum.take(5) end @doc """ Remove a name from the list of character names if it was used """ @spec claim_character_name(String.t()) :: :ok def claim_character_name(name) do case name in character_names() do true -> _claim_character_name(name) false -> :ok end end defp _claim_character_name(name) do case Repo.get_by(Config, name: "character_names") do nil -> :ok config -> names = List.delete(character_names(), name) changeset = config |> Config.changeset(%{value: Enum.join(names, "\n")}) Repo.update(changeset) reload("character_names") end end @doc """ Load the game's basic stats """ @spec basic_stats() :: map() def basic_stats() do case find_config("basic_stats") do nil -> @basic_stats stats -> {:ok, stats} = Stats.load(Poison.decode!(stats)) stats end end def discord_client_id() do find_config("discord_client_id") end def discord_invite_url() do find_config("discord_invite_url") end Enum.each(@color_config, fn {config, default} -> def unquote(config)() do case find_config(to_string(unquote(config))) do nil -> unquote(default) color -> color end end end) end
21.708475
85
0.621955
1c006ee5f9e5ad3f43d6bbb40b1ccaf12974acd9
339
ex
Elixir
lesson_05/demo/user_demo_umbrella/apps/user_demo/lib/user_demo/application.ex
martijnmeeldijk/ip_major
867f09975aa8db0b308081216ace639c5677446b
[ "BSD-3-Clause" ]
1
2021-09-22T09:56:35.000Z
2021-09-22T09:56:35.000Z
lesson_05/demo/user_demo_umbrella/apps/user_demo/lib/user_demo/application.ex
martijnmeeldijk/ip_major
867f09975aa8db0b308081216ace639c5677446b
[ "BSD-3-Clause" ]
7
2020-03-14T19:30:29.000Z
2022-02-27T01:20:40.000Z
lesson_05/demo/user_demo_umbrella/apps/user_demo/lib/user_demo/application.ex
martijnmeeldijk/ip_major
867f09975aa8db0b308081216ace639c5677446b
[ "BSD-3-Clause" ]
11
2020-02-13T14:52:45.000Z
2020-08-03T12:18:56.000Z
defmodule UserDemo.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 = [ UserDemo.Repo ] Supervisor.start_link(children, strategy: :one_for_one, name: UserDemo.Supervisor) end end
21.1875
86
0.725664
1c008bc836bcd70587361e2043c0727130f8d541
1,040
exs
Elixir
day_1/day_1.exs
cjschneider2/advent_of_code_2015
347b45ba3201f874aab5fa74ec9a2594e68def48
[ "MIT" ]
null
null
null
day_1/day_1.exs
cjschneider2/advent_of_code_2015
347b45ba3201f874aab5fa74ec9a2594e68def48
[ "MIT" ]
null
null
null
day_1/day_1.exs
cjschneider2/advent_of_code_2015
347b45ba3201f874aab5fa74ec9a2594e68def48
[ "MIT" ]
null
null
null
defmodule AOC2015.Day1 do defp p1(steps) do p1(steps, 0) end defp p1([], floor) do floor end defp p1([head | tail], floor) do case head do ?) -> p1(tail, floor - 1) ?( -> p1(tail, floor + 1) end end defp p2(steps) do p2(steps, 0, 0) end defp p2(_, -1, index) do index end defp p2([head | tail], floor, index) do case head do ?) -> p2(tail, floor - 1, index + 1) ?( -> p2(tail, floor + 1, index + 1) end end @doc """ In the first part for day 1 we need to calculate the final floor that Santa end up on. """ def run_part1() do {:ok, steps} = File.read("day-1_test-input.txt") IO.puts("part 1 : " <> Integer.to_string(p1(to_charlist(steps)))) end @doc """ In the second part we need to find the first step where Santa goes into the basement. """ def run_part2() do {:ok, steps} = File.read("day-1_test-input.txt") IO.puts("part 2 : " <> Integer.to_string(p2(to_charlist(steps)))) end end AOC2015.Day1.run_part1() AOC2015.Day1.run_part2()
24.186047
88
0.601923
1c00a281b52ecdc0e0165f5807547d6a6e47e34d
35
exs
Elixir
test/test_helper.exs
marick/ecto_test_dsl
6d460af093367098b7c78db709753deb45904d77
[ "Unlicense" ]
4
2021-02-09T17:26:34.000Z
2021-08-08T01:42:52.000Z
test/test_helper.exs
marick/transformer_test_support
6d460af093367098b7c78db709753deb45904d77
[ "Unlicense" ]
null
null
null
test/test_helper.exs
marick/transformer_test_support
6d460af093367098b7c78db709753deb45904d77
[ "Unlicense" ]
null
null
null
ExUnit.start() EctoTestDSL.start()
11.666667
19
0.771429
1c00a6782a8bf5da0fb59bd9b5e92cb514c3cbda
1,088
ex
Elixir
skippy/dashboard/lib/dashboard/application.ex
mashbytes/baby_zoo
4554890242a2493d17d9b1c1f4cc90d7ad1e637e
[ "MIT" ]
null
null
null
skippy/dashboard/lib/dashboard/application.ex
mashbytes/baby_zoo
4554890242a2493d17d9b1c1f4cc90d7ad1e637e
[ "MIT" ]
5
2020-07-17T23:35:42.000Z
2021-05-10T07:00:10.000Z
skippy/dashboard/lib/dashboard/application.ex
mashbytes/baby_zoo
4554890242a2493d17d9b1c1f4cc90d7ad1e637e
[ "MIT" ]
null
null
null
defmodule Dashboard.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do import Supervisor.Spec, warn: false # List all child processes to be supervised children = [ supervisor(Phoenix.PubSub.PG2, [Dashboard.PubSub, [pool_size: 1]]), # Start the endpoint when the application starts DashboardWeb.Endpoint, Dashboard.Presence, {DashboardWeb.DeviceListener, Device.Sound.Topic}, # Starts a worker by calling: Dashboard.Worker.start_link(arg) # {Dashboard.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Dashboard.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 DashboardWeb.Endpoint.config_change(changed, removed) :ok end end
30.222222
73
0.71875
1c00b5c7c24bfea939a6156f4ba16cd46ce8fd81
195
exs
Elixir
priv/repo/migrations/20200302105632_flexible_fingerprint_referrer.exs
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
984
2019-09-02T11:36:41.000Z
2020-06-08T06:25:48.000Z
priv/repo/migrations/20200302105632_flexible_fingerprint_referrer.exs
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
24
2019-09-10T09:53:17.000Z
2020-06-08T07:35:26.000Z
priv/repo/migrations/20200302105632_flexible_fingerprint_referrer.exs
wvffle/analytics
2c0fd55bc67f74af1fe1e2641678d44e9fee61d5
[ "MIT" ]
51
2019-09-03T10:48:10.000Z
2020-06-07T00:23:34.000Z
defmodule Plausible.Repo.Migrations.FlexibleFingerprintReferrer do use Ecto.Migration def change do alter table(:fingerprint_sessions) do modify :referrer, :text end end end
19.5
66
0.753846
1c00f9728c0df00ce4d9b7a6aab27bbe5b561c3d
2,114
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/model/country.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/model/country.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/model/country.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DFAReporting.V35.Model.Country do @moduledoc """ Contains information about a country that can be targeted by ads. ## Attributes * `countryCode` (*type:* `String.t`, *default:* `nil`) - Country code. * `dartId` (*type:* `String.t`, *default:* `nil`) - DART ID of this country. This is the ID used for targeting and generating reports. * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#country". * `name` (*type:* `String.t`, *default:* `nil`) - Name of this country. * `sslEnabled` (*type:* `boolean()`, *default:* `nil`) - Whether ad serving supports secure servers in this country. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :countryCode => String.t() | nil, :dartId => String.t() | nil, :kind => String.t() | nil, :name => String.t() | nil, :sslEnabled => boolean() | nil } field(:countryCode) field(:dartId) field(:kind) field(:name) field(:sslEnabled) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V35.Model.Country do def decode(value, options) do GoogleApi.DFAReporting.V35.Model.Country.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V35.Model.Country do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.830508
143
0.689215
1c0102803b7f26826f7337b02aca98eb8bf91110
7,723
ex
Elixir
lib/console_web/router.ex
JeffcoTrading/console
78a6634b0f1cbe922de02488ecc0492b0680e724
[ "Apache-2.0" ]
1
2021-11-18T13:32:47.000Z
2021-11-18T13:32:47.000Z
lib/console_web/router.ex
JeffcoTrading/console
78a6634b0f1cbe922de02488ecc0492b0680e724
[ "Apache-2.0" ]
null
null
null
lib/console_web/router.ex
JeffcoTrading/console
78a6634b0f1cbe922de02488ecc0492b0680e724
[ "Apache-2.0" ]
null
null
null
defmodule ConsoleWeb.Router do use ConsoleWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers plug ConsoleWeb.Plug.RateLimit, ["browser_actions", 60] plug ConsoleWeb.Plug.CheckDomain plug ConsoleWeb.Plug.VerifyRemoteIpRange end pipeline :api do plug :accepts, ["json"] plug ConsoleWeb.Plug.RateLimit, ["auth_actions", 60] plug ConsoleWeb.Plug.CheckDomain plug ConsoleWeb.Plug.VerifyRemoteIpRange end pipeline :router_api do plug :accepts, ["json"] plug ConsoleWeb.Plug.RateLimit, ["router_auth_actions", 10] plug ConsoleWeb.Plug.VerifyRemoteIpRange end scope "/graphql" do pipe_through ConsoleWeb.Plug.GraphqlPipeline forward "/", Absinthe.Plug, schema: ConsoleWeb.Schema end scope "/api", ConsoleWeb do pipe_through :api get "/invitations/:token", InvitationController, :get_by_token post "/subscribe_new_user", Auth0Controller, :subscribe_new_user post "/sessions", SessionController, :create post "/sessions/check_user", SessionController, :check_user end scope "/api", ConsoleWeb do pipe_through ConsoleWeb.AuthApiPipeline post "/users", InvitationController, :accept, as: "user_join_from_invitation" resources "/devices", DeviceController, except: [:index, :new, :edit] post "/devices/delete", DeviceController, :delete post "/devices/set_active", DeviceController, :set_active post "/devices/set_config_profile", DeviceController, :set_config_profile get "/devices/:device_id/events", DeviceController, :get_events get "/ttn/devices", DeviceController, :get_ttn post "/ttn/devices/import", DeviceController, :import_ttn post "/generic/devices/import", DeviceController, :import_generic resources "/labels", LabelController, only: [:create, :update, :delete] post "/labels/swap_label", LabelController, :swap_label resources "/alerts", AlertController, only: [:create, :delete, :update] post "/alerts/add_to_node", AlertController, :add_alert_to_node post "/alerts/remove_from_node", AlertController, :remove_alert_from_node resources "/multi_buys", MultiBuyController, only: [:create, :delete, :update] post "/multi_buys/add_to_node", MultiBuyController, :add_multi_buy_to_node post "/multi_buys/remove_from_node", MultiBuyController, :remove_multi_buy_from_node resources "/channels", ChannelController, except: [:index, :new, :edit] resources "/organizations", OrganizationController, except: [:new, :edit, :show] post "/channels/ubidots", ChannelController, :get_ubidots_url post "/channels/google_sheets", ChannelController, :get_google_form_data get "/mfa_enrollments", Auth0Controller, :get_enrolled_mfa post "/mfa_enrollments", Auth0Controller, :enroll_in_mfa delete "/mfa_enrollments", Auth0Controller, :disable_mfa post "/devices_labels", LabelController, :add_devices_to_label post "/devices_labels/delete", LabelController, :delete_devices_from_labels resources "/config_profiles", ConfigProfileController, only: [:create, :delete, :update] post "/config_profiles/add_to_node", ConfigProfileController, :add_config_profile_to_node post "/config_profiles/remove_from_node", ConfigProfileController, :remove_config_profile_from_node post "/hotspot_group", GroupController, :add_hotspot_to_group post "/delete_hotspot_group", GroupController, :remove_hotspot_from_group resources "/groups", GroupController, only: [:create, :delete, :update] resources "/invitations", InvitationController, only: [:create, :delete] resources "/memberships", MembershipController, only: [:update, :delete] resources "/api_keys", ApiKeyController, only: [:create, :delete] resources "/functions", FunctionController, only: [:create, :delete, :update] post "/data_credits/create_customer_and_charge", DataCreditController, :create_customer_id_and_charge post "/data_credits/create_charge", DataCreditController, :create_charge get "/data_credits/payment_methods", DataCreditController, :get_payment_methods get "/data_credits/setup_payment_method", DataCreditController, :get_setup_payment_method post "/data_credits/set_default_payment_method", DataCreditController, :set_default_payment_method post "/data_credits/remove_payment_method", DataCreditController, :remove_payment_method post "/data_credits/create_dc_purchase", DataCreditController, :create_dc_purchase post "/data_credits/set_automatic_payments", DataCreditController, :set_automatic_payments post "/data_credits/transfer_dc", DataCreditController, :transfer_dc get "/data_credits/generate_memo", DataCreditController, :generate_memo get "/data_credits/router_address", DataCreditController, :get_router_address get "/data_credits/get_hnt_price", DataCreditController, :get_hnt_price post "/flows/update", FlowsController, :update_edges post "/downlink", DownlinkController, :send_downlink post "/clear_downlink_queue", DownlinkController, :clear_downlink_queue get "/downlink_queue", DownlinkController, :fetch_downlink_queue post "/organization_hotspot", OrganizationHotspotController, :update_organization_hotspot post "/organization_hotspots", OrganizationHotspotController, :update_organization_hotspots end scope "/api/router", ConsoleWeb.Router do pipe_through :router_api post "/sessions", SessionController, :create post "/sessions/refresh", SessionController, :refresh end scope "/api/router", ConsoleWeb.Router do pipe_through ConsoleWeb.RouterApiPipeline resources "/devices", DeviceController, only: [:index, :show] do post "/event", DeviceController, :add_device_event end post "/devices/update_in_xor_filter", DeviceController, :update_devices_in_xor_filter resources "/organizations", OrganizationController, only: [:index, :show] post "/organizations/burned", OrganizationController, :burned_dc post "/organizations/manual_update_router_dc", OrganizationController, :manual_update_router_dc end scope "/api/v1", ConsoleWeb.V1 do pipe_through :api post "/down/:channel_id/:downlink_token/:device_id", DownlinkController, :down post "/down/:channel_id/:downlink_token", DownlinkController, :down end scope "/api/v1", ConsoleWeb.V1 do pipe_through ConsoleWeb.V1ApiPipeline get "/organization", OrganizationController, :show resources "/devices", DeviceController, only: [:index, :show, :create, :delete] get "/devices/:device_id/events", DeviceController, :get_events resources "/labels", LabelController, only: [:index, :show, :create, :delete] post "/devices/:device_id/labels", LabelController, :add_device_to_label delete "/devices/:device_id/labels/:label_id", LabelController, :delete_device_from_label post "/devices/discover", DeviceController, :discover_device resources "/alerts", AlertController, only: [:create, :update, :delete] post "/alerts/add_to_node", AlertController, :add_alert_to_node post "/alerts/remove_from_node", AlertController, :remove_alert_from_node end if Mix.env == :dev do forward "/sent_emails", Bamboo.SentEmailViewerPlug end scope "/", ConsoleWeb do pipe_through :browser # Use the default browser stack get "/invitations/accept/:token", InvitationController, :redirect_to_register, as: "accept_invitation" get "/api_keys/accept/:token", ApiKeyController, :accept, as: "accept_api_key" get "/google14b344de8ed0f4f1.html", PageController, :google_verify get "/*path", PageController, :index end end
47.380368
106
0.760974
1c012735931585f93fe91d70f64fbc7a211ca10d
15,141
exs
Elixir
lib/iex/test/iex/autocomplete_test.exs
jwarwick/elixir
de103c0f4e3240aa38967298ccb5f483a9e40c16
[ "Apache-2.0" ]
1
2021-11-17T10:24:48.000Z
2021-11-17T10:24:48.000Z
lib/iex/test/iex/autocomplete_test.exs
jwarwick/elixir
de103c0f4e3240aa38967298ccb5f483a9e40c16
[ "Apache-2.0" ]
6
2021-03-19T12:33:21.000Z
2021-04-02T17:52:45.000Z
lib/iex/test/iex/autocomplete_test.exs
jwarwick/elixir
de103c0f4e3240aa38967298ccb5f483a9e40c16
[ "Apache-2.0" ]
null
null
null
Code.require_file("../test_helper.exs", __DIR__) defmodule IEx.AutocompleteTest do use ExUnit.Case, async: true setup do evaluator = IEx.Server.start_evaluator([]) Process.put(:evaluator, evaluator) :ok end defp eval(line) do ExUnit.CaptureIO.capture_io(fn -> evaluator = Process.get(:evaluator) Process.group_leader(evaluator, Process.group_leader()) send(evaluator, {:eval, self(), line <> "\n", %IEx.State{}}) assert_receive {:evaled, _, _} end) end defp expand(expr) do IEx.Autocomplete.expand(Enum.reverse(expr), self()) end test "Erlang module completion" do assert expand(':zl') == {:yes, 'ib', []} end test "Erlang module no completion" do assert expand(':unknown') == {:no, '', []} end test "Erlang module multiple values completion" do {:yes, '', list} = expand(':user') assert 'user' in list assert 'user_drv' in list end test "Erlang root completion" do {:yes, '', list} = expand(':') assert is_list(list) assert 'lists' in list end test "Elixir proxy" do {:yes, '', list} = expand('E') assert 'Elixir' in list end test "Elixir completion" do assert expand('En') == {:yes, 'um', []} assert expand('Enumera') == {:yes, 'ble', []} end test "Elixir type completion" do assert expand('t :gen_ser') == {:yes, 'ver', []} assert expand('t String') == {:yes, '', ['String', 'StringIO']} assert expand('t String.') == {:yes, '', ['codepoint/0', 'grapheme/0', 'pattern/0', 't/0']} assert expand('t String.grap') == {:yes, 'heme', []} assert expand('t String.grap') == {:yes, 'heme', []} assert {:yes, '', ['date_time/0' | _]} = expand('t :file.') assert expand('t :file.n') == {:yes, 'ame', []} end test "Elixir callback completion" do assert expand('b :strin') == {:yes, 'g', []} assert expand('b String') == {:yes, '', ['String', 'StringIO']} assert expand('b String.') == {:no, '', []} assert expand('b Access.') == {:yes, '', ['fetch/2', 'get_and_update/3', 'pop/2']} assert expand('b GenServer.term') == {:yes, 'inate', []} assert expand('b GenServer.term') == {:yes, 'inate', []} assert expand('b :gen_server.handle_in') == {:yes, 'fo', []} end test "Elixir helper completion with parentheses" do assert expand('t(:gen_ser') == {:yes, 'ver', []} assert expand('t(String') == {:yes, '', ['String', 'StringIO']} assert expand('t(String.') == {:yes, '', ['codepoint/0', 'grapheme/0', 'pattern/0', 't/0']} assert expand('t(String.grap') == {:yes, 'heme', []} end test "do not activate Elixir helper completion no operators" do assert expand('t = String.co') == {:yes, '', ['codepoints/1', 'contains?/2']} assert expand('t > String.grap') == {:yes, 'hemes', []} end test "Elixir completion with self" do assert expand('Enumerable') == {:yes, '.', []} end test "Elixir completion on modules from load path" do assert expand('Str') == {:yes, [], ['Stream', 'String', 'StringIO']} assert expand('Ma') == {:yes, '', ['Macro', 'Map', 'MapSet', 'MatchError']} assert expand('Dic') == {:yes, 't', []} assert expand('Ex') == {:yes, [], ['ExUnit', 'Exception']} end test "Elixir no completion for underscored functions with no doc" do {:module, _, bytecode, _} = defmodule Elixir.Sample do def __foo__(), do: 0 @doc "Bar doc" def __bar__(), do: 1 end File.write!("Elixir.Sample.beam", bytecode) assert {:docs_v1, _, _, _, _, _, _} = Code.fetch_docs(Sample) assert expand('Sample._') == {:yes, '_bar__', []} after File.rm("Elixir.Sample.beam") :code.purge(Sample) :code.delete(Sample) end test "Elixir no completion for default argument functions with doc set to false" do {:yes, '', available} = expand('String.') refute Enum.member?(available, 'rjust/2') assert Enum.member?(available, 'replace/3') assert expand('String.r') == {:yes, 'e', []} {:module, _, bytecode, _} = defmodule Elixir.DefaultArgumentFunctions do def foo(a \\ :a, b, c \\ :c), do: {a, b, c} def _do_fizz(a \\ :a, b, c \\ :c), do: {a, b, c} @doc false def __fizz__(a \\ :a, b, c \\ :c), do: {a, b, c} @doc "bar/0 doc" def bar(), do: :bar @doc false def bar(a \\ :a, b, c \\ :c, d \\ :d), do: {a, b, c, d} @doc false def bar(a, b, c, d, e), do: {a, b, c, d, e} @doc false def baz(a \\ :a), do: {a} @doc "biz/3 doc" def biz(a, b, c \\ :c), do: {a, b, c} end File.write!("Elixir.DefaultArgumentFunctions.beam", bytecode) assert {:docs_v1, _, _, _, _, _, _} = Code.fetch_docs(DefaultArgumentFunctions) functions_list = ['bar/0', 'biz/2', 'biz/3', 'foo/1', 'foo/2', 'foo/3'] assert expand('DefaultArgumentFunctions.') == {:yes, '', functions_list} assert expand('DefaultArgumentFunctions.bi') == {:yes, 'z', []} assert expand('DefaultArgumentFunctions.foo') == {:yes, '', ['foo/1', 'foo/2', 'foo/3']} after File.rm("Elixir.DefaultArgumentFunctions.beam") :code.purge(DefaultArgumentFunctions) :code.delete(DefaultArgumentFunctions) end test "Elixir no completion" do assert expand('.') == {:no, '', []} assert expand('Xyz') == {:no, '', []} assert expand('x.Foo') == {:no, '', []} assert expand('x.Foo.get_by') == {:no, '', []} end test "Elixir root submodule completion" do assert expand('Elixir.Acce') == {:yes, 'ss', []} end test "Elixir submodule completion" do assert expand('String.Cha') == {:yes, 'rs', []} end test "Elixir submodule no completion" do assert expand('IEx.Xyz') == {:no, '', []} end test "function completion" do assert expand('System.ve') == {:yes, 'rsion', []} assert expand(':ets.fun2') == {:yes, 'ms', []} end test "function completion with arity" do assert expand('String.printable?') == {:yes, '', ['printable?/1', 'printable?/2']} assert expand('String.printable?/') == {:yes, '', ['printable?/1', 'printable?/2']} end test "function completion using a variable bound to a module" do eval("mod = String") assert expand('mod.print') == {:yes, 'able?', []} end test "map atom key completion is supported" do eval("map = %{foo: 1, bar_1: 23, bar_2: 14}") assert expand('map.f') == {:yes, 'oo', []} assert expand('map.b') == {:yes, 'ar_', []} assert expand('map.bar_') == {:yes, '', ['bar_1', 'bar_2']} assert expand('map.c') == {:no, '', []} assert expand('map.') == {:yes, '', ['bar_1', 'bar_2', 'foo']} assert expand('map.foo') == {:no, '', []} end test "nested map atom key completion is supported" do eval("map = %{nested: %{deeply: %{foo: 1, bar_1: 23, bar_2: 14, mod: String, num: 1}}}") assert expand('map.nested.deeply.f') == {:yes, 'oo', []} assert expand('map.nested.deeply.b') == {:yes, 'ar_', []} assert expand('map.nested.deeply.bar_') == {:yes, '', ['bar_1', 'bar_2']} assert expand('map.nested.deeply.') == {:yes, '', ['bar_1', 'bar_2', 'foo', 'mod', 'num']} assert expand('map.nested.deeply.mod.print') == {:yes, 'able?', []} assert expand('map.nested') == {:yes, '.', []} assert expand('map.nested.deeply') == {:yes, '.', []} assert expand('map.nested.deeply.foo') == {:no, '', []} assert expand('map.nested.deeply.c') == {:no, '', []} assert expand('map.a.b.c.f') == {:no, '', []} end test "map string key completion is not supported" do eval(~S(map = %{"foo" => 1})) assert expand('map.f') == {:no, '', []} end test "autocompletion off a bound variable only works for modules and maps" do eval("num = 5; map = %{nested: %{num: 23}}") assert expand('num.print') == {:no, '', []} assert expand('map.nested.num.f') == {:no, '', []} assert expand('map.nested.num.key.f') == {:no, '', []} end test "autocompletion using access syntax does is not supported" do eval("map = %{nested: %{deeply: %{num: 23}}}") assert expand('map[:nested][:deeply].n') == {:no, '', []} assert expand('map[:nested].deeply.n') == {:no, '', []} assert expand('map.nested.[:deeply].n') == {:no, '', []} end test "autocompletion off of unbound variables is not supported" do eval("num = 5") assert expand('other_var.f') == {:no, '', []} assert expand('a.b.c.d') == {:no, '', []} end test "macro completion" do {:yes, '', list} = expand('Kernel.is_') assert is_list(list) end test "imports completion" do {:yes, '', list} = expand('') assert is_list(list) assert 'h/1' in list assert 'unquote/1' in list assert 'pwd/0' in list end test "kernel import completion" do assert expand('defstru') == {:yes, 'ct', []} assert expand('put_') == {:yes, '', ['put_elem/3', 'put_in/2', 'put_in/3']} end test "variable name completion" do eval("numeral = 3; number = 3; nothing = nil") assert expand('numb') == {:yes, 'er', []} assert expand('num') == {:yes, '', ['number', 'numeral']} assert expand('no') == {:yes, '', ['nothing', 'node/0', 'node/1', 'not/1']} end test "completion of manually imported functions and macros" do eval("import Enum; import Supervisor, only: [count_children: 1]; import Protocol") functions_list = ['take/2', 'take_every/2', 'take_random/2', 'take_while/2'] assert expand('take') == {:yes, '', functions_list} assert expand('count') == {:yes, '', ['count/1', 'count/2', 'count_children/1', 'count_until/2', 'count_until/3']} assert expand('der') == {:yes, 'ive', []} end defmacro define_var do quote(do: var!(my_var_1, Elixir) = 1) end test "ignores quoted variables when performing variable completion" do eval("require #{__MODULE__}; #{__MODULE__}.define_var(); my_var_2 = 2") assert expand('my_var') == {:yes, '_2', []} end test "kernel special form completion" do assert expand('unquote_spl') == {:yes, 'icing', []} end test "completion inside expression" do assert expand('1 En') == {:yes, 'um', []} assert expand('Test(En') == {:yes, 'um', []} assert expand('Test :zl') == {:yes, 'ib', []} assert expand('[:zl') == {:yes, 'ib', []} assert expand('{:zl') == {:yes, 'ib', []} end test "ampersand completion" do assert expand('&Enu') == {:yes, 'm', []} functions_list = ['all?/1', 'all?/2', 'any?/1', 'any?/2', 'at/2', 'at/3'] assert expand('&Enum.a') == {:yes, [], functions_list} assert expand('f = &Enum.a') == {:yes, [], functions_list} end test "negation operator completion" do assert expand('!is_bin') == {:yes, 'ary', []} end test "pin operator completion" do eval("my_variable = 2") assert expand('^my_va') == {:yes, 'riable', []} end defmodule SublevelTest.LevelA.LevelB do end test "Elixir completion sublevel" do assert expand('IEx.AutocompleteTest.SublevelTest.') == {:yes, 'LevelA', []} end test "complete aliases of Elixir modules" do eval("alias List, as: MyList") assert expand('MyL') == {:yes, 'ist', []} assert expand('MyList') == {:yes, '.', []} assert expand('MyList.to_integer') == {:yes, [], ['to_integer/1', 'to_integer/2']} end test "complete aliases of Erlang modules" do eval("alias :lists, as: EList") assert expand('EL') == {:yes, 'ist', []} assert expand('EList') == {:yes, '.', []} assert expand('EList.map') == {:yes, [], ['map/2', 'mapfoldl/3', 'mapfoldr/3']} end test "completion for functions added when compiled module is reloaded" do {:module, _, bytecode, _} = defmodule Sample do def foo(), do: 0 end File.write!("Elixir.IEx.AutocompleteTest.Sample.beam", bytecode) assert {:docs_v1, _, _, _, _, _, _} = Code.fetch_docs(Sample) assert expand('IEx.AutocompleteTest.Sample.foo') == {:yes, '', ['foo/0']} Code.compiler_options(ignore_module_conflict: true) defmodule Sample do def foo(), do: 0 def foobar(), do: 0 end assert expand('IEx.AutocompleteTest.Sample.foo') == {:yes, '', ['foo/0', 'foobar/0']} after File.rm("Elixir.IEx.AutocompleteTest.Sample.beam") Code.compiler_options(ignore_module_conflict: false) :code.purge(Sample) :code.delete(Sample) end defmodule MyStruct do defstruct [:my_val] end test "completion for struct names" do assert expand('%IEx.AutocompleteTest.MyStr') == {:yes, 'uct', []} end test "completion for struct keys" do eval("struct = %IEx.AutocompleteTest.MyStruct{}") assert expand('struct.my') == {:yes, '_val', []} end test "ignore invalid Elixir module literals" do defmodule(:"Elixir.IEx.AutocompleteTest.Unicodé", do: nil) assert expand('IEx.AutocompleteTest.Unicod') == {:no, '', []} after :code.purge(:"Elixir.IEx.AutocompleteTest.Unicodé") :code.delete(:"Elixir.IEx.AutocompleteTest.Unicodé") end test "signature help for functions and macros" do assert expand('String.graphemes(') == {:yes, '', ['graphemes(string)']} assert expand('def ') == {:yes, '', ['def(call, expr \\\\ nil)']} eval("import Enum; import Protocol") assert ExUnit.CaptureIO.capture_io(fn -> send(self(), expand('reduce(')) end) == "\nreduce(enumerable, acc, fun)" assert_received {:yes, '', ['reduce(enumerable, fun)']} assert expand('take(') == {:yes, '', ['take(enumerable, amount)']} assert expand('derive(') == {:yes, '', ['derive(protocol, module, options \\\\ [])']} defmodule NoDocs do def sample(a), do: a end assert {:yes, [], [_ | _]} = expand('NoDocs.sample(') end @tag :tmp_dir test "path completion inside strings", %{tmp_dir: dir} do dir |> Path.join("single1") |> File.touch() dir |> Path.join("file1") |> File.touch() dir |> Path.join("file2") |> File.touch() dir |> Path.join("dir") |> File.mkdir() dir |> Path.join("dir/file3") |> File.touch() dir |> Path.join("dir/file4") |> File.touch() assert expand('"./') == path_autocompletion(".") assert expand('"/') == path_autocompletion("/") assert expand('"./#\{') == expand('{') assert expand('"./#\{Str') == expand('{Str') assert expand('Path.join("./", is_') == expand('is_') assert expand('"#{dir}/') == path_autocompletion(dir) assert expand('"#{dir}/sin') == {:yes, 'gle1', []} assert expand('"#{dir}/single1') == {:yes, '"', []} assert expand('"#{dir}/fi') == {:yes, 'le', []} assert expand('"#{dir}/file') == path_autocompletion(dir, "file") assert expand('"#{dir}/d') == {:yes, 'ir', []} assert expand('"#{dir}/dir') == {:yes, '/', []} assert expand('"#{dir}/dir/') == {:yes, 'file', []} assert expand('"#{dir}/dir/file') == dir |> Path.join("dir") |> path_autocompletion("file") end defp path_autocompletion(dir, hint \\ "") do dir |> File.ls!() |> Stream.filter(&String.starts_with?(&1, hint)) |> Enum.map(&String.to_charlist/1) |> case do [] -> {:no, '', []} list -> {:yes, '', list} end end end
33.94843
95
0.572485
1c01345a6f73981eec14e47d9d194dacf9222038
7,463
ex
Elixir
clients/cloud_iot/lib/google_api/cloud_iot/v1/model/device.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/cloud_iot/lib/google_api/cloud_iot/v1/model/device.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/cloud_iot/lib/google_api/cloud_iot/v1/model/device.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.CloudIot.V1.Model.Device do @moduledoc """ The device resource. ## Attributes * `blocked` (*type:* `boolean()`, *default:* `nil`) - If a device is blocked, connections or requests from this device will fail. Can be used to temporarily prevent the device from connecting if, for example, the sensor is generating bad data and needs maintenance. * `config` (*type:* `GoogleApi.CloudIot.V1.Model.DeviceConfig.t`, *default:* `nil`) - The most recent device configuration, which is eventually sent from Cloud IoT Core to the device. If not present on creation, the configuration will be initialized with an empty payload and version value of `1`. To update this field after creation, use the `DeviceManager.ModifyCloudToDeviceConfig` method. * `credentials` (*type:* `list(GoogleApi.CloudIot.V1.Model.DeviceCredential.t)`, *default:* `nil`) - The credentials used to authenticate this device. To allow credential rotation without interruption, multiple device credentials can be bound to this device. No more than 3 credentials can be bound to a single device at a time. When new credentials are added to a device, they are verified against the registry credentials. For details, see the description of the `DeviceRegistry.credentials` field. * `gatewayConfig` (*type:* `GoogleApi.CloudIot.V1.Model.GatewayConfig.t`, *default:* `nil`) - Gateway-related configuration and state. * `id` (*type:* `String.t`, *default:* `nil`) - The user-defined device identifier. The device ID must be unique within a device registry. * `lastConfigAckTime` (*type:* `DateTime.t`, *default:* `nil`) - [Output only] The last time a cloud-to-device config version acknowledgment was received from the device. This field is only for configurations sent through MQTT. * `lastConfigSendTime` (*type:* `DateTime.t`, *default:* `nil`) - [Output only] The last time a cloud-to-device config version was sent to the device. * `lastErrorStatus` (*type:* `GoogleApi.CloudIot.V1.Model.Status.t`, *default:* `nil`) - [Output only] The error message of the most recent error, such as a failure to publish to Cloud Pub/Sub. 'last_error_time' is the timestamp of this field. If no errors have occurred, this field has an empty message and the status code 0 == OK. Otherwise, this field is expected to have a status code other than OK. * `lastErrorTime` (*type:* `DateTime.t`, *default:* `nil`) - [Output only] The time the most recent error occurred, such as a failure to publish to Cloud Pub/Sub. This field is the timestamp of 'last_error_status'. * `lastEventTime` (*type:* `DateTime.t`, *default:* `nil`) - [Output only] The last time a telemetry event was received. Timestamps are periodically collected and written to storage; they may be stale by a few minutes. * `lastHeartbeatTime` (*type:* `DateTime.t`, *default:* `nil`) - [Output only] The last time an MQTT `PINGREQ` was received. This field applies only to devices connecting through MQTT. MQTT clients usually only send `PINGREQ` messages if the connection is idle, and no other messages have been sent. Timestamps are periodically collected and written to storage; they may be stale by a few minutes. * `lastStateTime` (*type:* `DateTime.t`, *default:* `nil`) - [Output only] The last time a state event was received. Timestamps are periodically collected and written to storage; they may be stale by a few minutes. * `logLevel` (*type:* `String.t`, *default:* `nil`) - **Beta Feature** The logging verbosity for device activity. If unspecified, DeviceRegistry.log_level will be used. * `metadata` (*type:* `map()`, *default:* `nil`) - The metadata key-value pairs assigned to the device. This metadata is not interpreted or indexed by Cloud IoT Core. It can be used to add contextual information for the device. Keys must conform to the regular expression a-zA-Z+ and be less than 128 bytes in length. Values are free-form strings. Each value must be less than or equal to 32 KB in size. The total size of all keys and values must be less than 256 KB, and the maximum number of key-value pairs is 500. * `name` (*type:* `String.t`, *default:* `nil`) - The resource path name. For example, `projects/p1/locations/us-central1/registries/registry0/devices/dev0` or `projects/p1/locations/us-central1/registries/registry0/devices/{num_id}`. When `name` is populated as a response from the service, it always ends in the device numeric ID. * `numId` (*type:* `String.t`, *default:* `nil`) - [Output only] A server-defined unique numeric ID for the device. This is a more compact way to identify devices, and it is globally unique. * `state` (*type:* `GoogleApi.CloudIot.V1.Model.DeviceState.t`, *default:* `nil`) - [Output only] The state most recently received from the device. If no state has been reported, this field is not present. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :blocked => boolean(), :config => GoogleApi.CloudIot.V1.Model.DeviceConfig.t(), :credentials => list(GoogleApi.CloudIot.V1.Model.DeviceCredential.t()), :gatewayConfig => GoogleApi.CloudIot.V1.Model.GatewayConfig.t(), :id => String.t(), :lastConfigAckTime => DateTime.t(), :lastConfigSendTime => DateTime.t(), :lastErrorStatus => GoogleApi.CloudIot.V1.Model.Status.t(), :lastErrorTime => DateTime.t(), :lastEventTime => DateTime.t(), :lastHeartbeatTime => DateTime.t(), :lastStateTime => DateTime.t(), :logLevel => String.t(), :metadata => map(), :name => String.t(), :numId => String.t(), :state => GoogleApi.CloudIot.V1.Model.DeviceState.t() } field(:blocked) field(:config, as: GoogleApi.CloudIot.V1.Model.DeviceConfig) field(:credentials, as: GoogleApi.CloudIot.V1.Model.DeviceCredential, type: :list) field(:gatewayConfig, as: GoogleApi.CloudIot.V1.Model.GatewayConfig) field(:id) field(:lastConfigAckTime, as: DateTime) field(:lastConfigSendTime, as: DateTime) field(:lastErrorStatus, as: GoogleApi.CloudIot.V1.Model.Status) field(:lastErrorTime, as: DateTime) field(:lastEventTime, as: DateTime) field(:lastHeartbeatTime, as: DateTime) field(:lastStateTime, as: DateTime) field(:logLevel) field(:metadata, type: :map) field(:name) field(:numId) field(:state, as: GoogleApi.CloudIot.V1.Model.DeviceState) end defimpl Poison.Decoder, for: GoogleApi.CloudIot.V1.Model.Device do def decode(value, options) do GoogleApi.CloudIot.V1.Model.Device.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudIot.V1.Model.Device do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
78.557895
521
0.723302
1c017d8da5d2d90a3db50db9aa5f35e9782f1a62
3,204
ex
Elixir
lib/scene/splash.ex
brsg/telluride_sensor
65936295777c2d3edca767ac018af68495e8a775
[ "Apache-2.0" ]
1
2021-02-21T15:18:25.000Z
2021-02-21T15:18:25.000Z
lib/scene/splash.ex
brsg/telluride_sensor
65936295777c2d3edca767ac018af68495e8a775
[ "Apache-2.0" ]
null
null
null
lib/scene/splash.ex
brsg/telluride_sensor
65936295777c2d3edca767ac018af68495e8a775
[ "Apache-2.0" ]
1
2021-02-21T15:18:51.000Z
2021-02-21T15:18:51.000Z
defmodule TellurideSensor.Scene.Splash do @moduledoc """ BRSG Ideas That Scale splash page, transition to landing page. """ use Scenic.Scene alias Scenic.Graph alias Scenic.ViewPort import Scenic.Primitives, only: [{:rect, 3}, {:update_opts, 2}] @brsg_path :code.priv_dir(:telluride_sensor) |> Path.join("/static/images/ideas_that_scale_600_by_173.png") @brsg_hash Scenic.Cache.Support.Hash.file!(@brsg_path, :sha) @brsg_width 600 @brsg_height 173 @graph Graph.build() |> rect( {@brsg_width, @brsg_height}, id: :brsg, fill: {:image, {@brsg_hash, 0}} ) @animate_ms 30 @finish_delay_ms 1_000 def init(first_scene, opts) do viewport = opts[:viewport] # calculate the transform that centers the brsg logo in the viewport {:ok, %ViewPort.Status{size: {vp_width, vp_height}}} = ViewPort.info(viewport) position = { vp_width / 2 - @brsg_width / 2, vp_height / 2 - @brsg_height / 2 } # load the brsg logo texture into the cache Scenic.Cache.Static.Texture.load(@brsg_path, @brsg_hash) # |> IO.inspect(label: "texture_load: ") # move the brsg logo into the correct location graph = Graph.modify(@graph, :brsg, &update_opts(&1, t: position)) # start a simple time {:ok, timer} = :timer.send_interval(@animate_ms, :animate) state = %{ viewport: viewport, timer: timer, graph: graph, first_scene: first_scene, alpha: 0 } {:ok, state, push: graph} end @doc """ An animation to saturate the image according to a timer that increments and whose value is applied to the alpha channel of the BRSG logo. When fully saturated, transition to the landing scene. """ def handle_info( :animate, %{timer: timer, alpha: a} = state ) when a >= 256 do # IO.puts("\nhandle_info :animate 1\n") :timer.cancel(timer) Process.send_after(self(), :finish, @finish_delay_ms) {:noreply, state} end def handle_info(:finish, state) do # IO.puts("\nhandle_info :finish 2\n") go_to_first_scene(state) {:noreply, state} end def handle_info(:animate, %{alpha: alpha, graph: graph} = state) do # IO.puts("\nhandle_info :animate 3 with brsg_hash #{inspect @brsg_hash} alpha #{inspect alpha} BEGIN\n") graph = Graph.modify( graph, :brsg, &update_opts(&1, fill: {:image, {@brsg_hash, alpha}}) ) # IO.puts("\nhandle_info :animate 3 with brsg_hash #{inspect @brsg_hash} alpha #{inspect alpha} END\n") {:noreply, %{state | graph: graph, alpha: alpha + 2}, push: graph} end @doc """ Interrupt animation and go directly to landing scene. """ def handle_input({:cursor_button, {_, :press, _, _}}, _context, state) do go_to_first_scene(state) {:noreply, state} end def handle_input({:key, _}, _context, state) do go_to_first_scene(state) {:noreply, state} end def handle_input(_input, _context, state), do: {:noreply, state} ## Helping defp go_to_first_scene(%{viewport: vp, first_scene: first_scene}) do # IO.puts("go_to_first_scene #{first_scene}") ViewPort.set_root(vp, {first_scene, nil}) end end
27.152542
109
0.651373
1c0193b71a4b065df5a0afb67f0a429da22e1aa6
32,370
exs
Elixir
test/brando/images/processing/operations_test.exs
brandocms/brando
4198e0c0920031bd909969055064e4e2b7230d21
[ "MIT" ]
4
2020-10-30T08:40:38.000Z
2022-01-07T22:21:37.000Z
test/brando/images/processing/operations_test.exs
brandocms/brando
4198e0c0920031bd909969055064e4e2b7230d21
[ "MIT" ]
1,162
2020-07-05T11:20:15.000Z
2022-03-31T06:01:49.000Z
test/brando/images/processing/operations_test.exs
brandocms/brando
4198e0c0920031bd909969055064e4e2b7230d21
[ "MIT" ]
null
null
null
defmodule Brando.OperationsTest do use ExUnit.Case import Brando.Images.Operations @image_struct %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 } @image_struct_png %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 } @image_struct_gif %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 } @img_config %Brando.Type.ImageConfig{ allowed_mimetypes: ["image/jpeg", "image/png", "image/gif"], default_size: "medium", upload_path: Path.join(["images", "exhibitions", "cover"]), random_filename: true, size_limit: 10_240_000, sizes: %{ "micro" => %{"size" => "25x25>", "quality" => 30, "crop" => true}, "thumb" => %{"size" => "150x150>", "quality" => 90, "crop" => true}, "small" => %{"size" => "700", "quality" => 90}, "medium" => %{"size" => "1100", "quality" => 90}, "large" => %{"size" => "1700", "quality" => 90}, "xlarge" => %{"size" => "2100", "quality" => 90} } } @img_config_png %Brando.Type.ImageConfig{ allowed_mimetypes: ["image/jpeg", "image/png", "image/gif"], default_size: "medium", formats: [:png], upload_path: Path.join(["images", "exhibitions", "cover"]), random_filename: true, size_limit: 10_240_000, sizes: %{ "micro" => %{"size" => "25x25>", "quality" => 30, "crop" => true}, "thumb" => %{"size" => "150x150>", "quality" => 90, "crop" => true}, "small" => %{"size" => "700", "quality" => 90}, "medium" => %{"size" => "1100", "quality" => 90}, "large" => %{"size" => "1700", "quality" => 90}, "xlarge" => %{"size" => "2100", "quality" => 90} } } @img_config_gif %Brando.Type.ImageConfig{ allowed_mimetypes: ["image/jpeg", "image/png", "image/gif"], default_size: "medium", upload_path: Path.join(["images", "exhibitions", "cover"]), random_filename: true, size_limit: 10_240_000, sizes: %{ "micro" => %{"size" => "25x25>", "quality" => 30, "crop" => true}, "thumb" => %{"size" => "150x150>", "quality" => 90, "crop" => true}, "small" => %{"size" => "700", "quality" => 90}, "medium" => %{"size" => "1100", "quality" => 90}, "large" => %{"size" => "1700", "quality" => 90}, "xlarge" => %{"size" => "2100", "quality" => 90} }, formats: [:gif] } test "create operations from file" do {:ok, operations} = create( @image_struct, @img_config, "test_id", :system ) assert operations == [ %Brando.Images.Operation{ filename: "image.jpeg", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 }, operation_index: 1, processed_formats: [:jpg], size_cfg: %{"quality" => 90, "size" => "1700"}, size_key: "large", sized_image_dir: "images/exhibitions/cover/large", sized_image_path: "images/exhibitions/cover/large/image.jpg", total_operations: 6, type: :jpg, user: :system }, %Brando.Images.Operation{ filename: "image.jpeg", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 }, operation_index: 2, processed_formats: [:jpg], size_cfg: %{"quality" => 90, "size" => "1100"}, size_key: "medium", sized_image_dir: "images/exhibitions/cover/medium", sized_image_path: "images/exhibitions/cover/medium/image.jpg", total_operations: 6, type: :jpg, user: :system }, %Brando.Images.Operation{ filename: "image.jpeg", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 }, operation_index: 3, processed_formats: [:jpg], size_cfg: %{"quality" => 30, "size" => "25x25>", "crop" => true}, size_key: "micro", sized_image_dir: "images/exhibitions/cover/micro", sized_image_path: "images/exhibitions/cover/micro/image.jpg", total_operations: 6, type: :jpg, user: :system }, %Brando.Images.Operation{ filename: "image.jpeg", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 }, operation_index: 4, processed_formats: [:jpg], size_cfg: %{"quality" => 90, "size" => "700"}, size_key: "small", sized_image_dir: "images/exhibitions/cover/small", sized_image_path: "images/exhibitions/cover/small/image.jpg", total_operations: 6, type: :jpg, user: :system }, %Brando.Images.Operation{ filename: "image.jpeg", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 }, operation_index: 5, processed_formats: [:jpg], size_cfg: %{"crop" => true, "quality" => 90, "size" => "150x150>"}, size_key: "thumb", sized_image_dir: "images/exhibitions/cover/thumb", sized_image_path: "images/exhibitions/cover/thumb/image.jpg", total_operations: 6, type: :jpg, user: :system }, %Brando.Images.Operation{ filename: "image.jpeg", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.jpeg", sizes: %{ "large" => "images/exhibitions/cover/large/image.jpg", "medium" => "images/exhibitions/cover/medium/image.jpg", "micro" => "images/exhibitions/cover/micro/image.jpg", "small" => "images/exhibitions/cover/small/image.jpg", "thumb" => "images/exhibitions/cover/thumb/image.jpg", "xlarge" => "images/exhibitions/cover/xlarge/image.jpg" }, title: nil, width: 2600 }, operation_index: 6, processed_formats: [:jpg], size_cfg: %{"quality" => 90, "size" => "2100"}, size_key: "xlarge", sized_image_dir: "images/exhibitions/cover/xlarge", sized_image_path: "images/exhibitions/cover/xlarge/image.jpg", total_operations: 6, type: :jpg, user: :system } ] end test "create png operations from file" do {:ok, operations} = create( @image_struct_png, @img_config_png, "test_id", :system ) assert operations == [ %Brando.Images.Operation{ filename: "image.png", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 }, operation_index: 1, processed_formats: [:png], size_cfg: %{"quality" => 90, "size" => "1700"}, size_key: "large", sized_image_dir: "images/exhibitions/cover/large", sized_image_path: "images/exhibitions/cover/large/image.png", total_operations: 6, type: :png, user: :system }, %Brando.Images.Operation{ filename: "image.png", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 }, operation_index: 2, processed_formats: [:png], size_cfg: %{"quality" => 90, "size" => "1100"}, size_key: "medium", sized_image_dir: "images/exhibitions/cover/medium", sized_image_path: "images/exhibitions/cover/medium/image.png", total_operations: 6, type: :png, user: :system }, %Brando.Images.Operation{ filename: "image.png", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 }, operation_index: 3, processed_formats: [:png], size_cfg: %{"crop" => true, "quality" => 30, "size" => "25x25>"}, size_key: "micro", sized_image_dir: "images/exhibitions/cover/micro", sized_image_path: "images/exhibitions/cover/micro/image.png", total_operations: 6, type: :png, user: :system }, %Brando.Images.Operation{ filename: "image.png", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 }, operation_index: 4, processed_formats: [:png], size_cfg: %{"quality" => 90, "size" => "700"}, size_key: "small", sized_image_dir: "images/exhibitions/cover/small", sized_image_path: "images/exhibitions/cover/small/image.png", total_operations: 6, type: :png, user: :system }, %Brando.Images.Operation{ filename: "image.png", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 }, operation_index: 5, processed_formats: [:png], size_cfg: %{"crop" => true, "quality" => 90, "size" => "150x150>"}, size_key: "thumb", sized_image_dir: "images/exhibitions/cover/thumb", sized_image_path: "images/exhibitions/cover/thumb/image.png", total_operations: 6, type: :png, user: :system }, %Brando.Images.Operation{ filename: "image.png", id: "test_id", image_struct: %Brando.Images.Image{ alt: nil, cdn: false, credits: nil, dominant_color: nil, focal: %{"x" => 50, "y" => 50}, formats: nil, height: 2600, marked_as_deleted: false, path: "images/exhibitions/cover/image.png", sizes: %{ "large" => "images/exhibitions/cover/large/image.png", "medium" => "images/exhibitions/cover/medium/image.png", "micro" => "images/exhibitions/cover/micro/image.png", "small" => "images/exhibitions/cover/small/image.png", "thumb" => "images/exhibitions/cover/thumb/image.png", "xlarge" => "images/exhibitions/cover/xlarge/image.png" }, title: nil, width: 2600 }, operation_index: 6, processed_formats: [:png], size_cfg: %{"quality" => 90, "size" => "2100"}, size_key: "xlarge", sized_image_dir: "images/exhibitions/cover/xlarge", sized_image_path: "images/exhibitions/cover/xlarge/image.png", total_operations: 6, type: :png, user: :system } ] end test "create gif operations from file" do {:ok, operations} = create( @image_struct_gif, @img_config_gif, "test_id", :system ) assert operations == [ %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"quality" => 90, "size" => "1700"}, size_key: "large", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/large", sized_image_path: "images/exhibitions/cover/large/image.gif", operation_index: 1, processed_formats: [:gif], total_operations: 6 }, %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"quality" => 90, "size" => "1100"}, size_key: "medium", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/medium", sized_image_path: "images/exhibitions/cover/medium/image.gif", operation_index: 2, processed_formats: [:gif], total_operations: 6 }, %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"crop" => true, "quality" => 30, "size" => "25x25>"}, size_key: "micro", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/micro", sized_image_path: "images/exhibitions/cover/micro/image.gif", operation_index: 3, processed_formats: [:gif], total_operations: 6 }, %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"quality" => 90, "size" => "700"}, size_key: "small", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/small", sized_image_path: "images/exhibitions/cover/small/image.gif", operation_index: 4, processed_formats: [:gif], total_operations: 6 }, %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"crop" => true, "quality" => 90, "size" => "150x150>"}, size_key: "thumb", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/thumb", sized_image_path: "images/exhibitions/cover/thumb/image.gif", operation_index: 5, processed_formats: [:gif], total_operations: 6 }, %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "large" => "images/exhibitions/cover/large/image.gif", "medium" => "images/exhibitions/cover/medium/image.gif", "micro" => "images/exhibitions/cover/micro/image.gif", "small" => "images/exhibitions/cover/small/image.gif", "thumb" => "images/exhibitions/cover/thumb/image.gif", "xlarge" => "images/exhibitions/cover/xlarge/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"quality" => 90, "size" => "2100"}, size_key: "xlarge", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/xlarge", sized_image_path: "images/exhibitions/cover/xlarge/image.gif", operation_index: 6, processed_formats: [:gif], total_operations: 6 } ] end test "create_image_size gif" do op = %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "micro" => "images/exhibitions/cover/micro/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"quality" => 1, "size" => "10"}, size_key: "micro", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/micro", sized_image_path: "images/exhibitions/cover/micro/image.gif", operation_index: 6, total_operations: 6 } {:ok, result} = Brando.Images.Operations.Sizing.create_image_size(op) assert result.cmd_params =~ "--resize-fit-width 10" assert result.size_key == "micro" end test "create_image_size cropped gif" do op = %Brando.Images.Operation{ filename: "image.gif", id: "test_id", image_struct: %Brando.Images.Image{ credits: nil, focal: %{"x" => 50, "y" => 50}, height: 2600, path: "images/exhibitions/cover/image.gif", sizes: %{ "micro" => "images/exhibitions/cover/micro/image.gif" }, title: nil, width: 2600 }, size_cfg: %{"quality" => 1, "size" => "10x10", "crop" => true}, size_key: "micro", type: :gif, user: :system, sized_image_dir: "images/exhibitions/cover/micro", sized_image_path: "images/exhibitions/cover/micro/image.gif", operation_index: 6, total_operations: 6 } {:ok, result} = Brando.Images.Operations.Sizing.create_image_size(op) assert result.cmd_params =~ "--crop 0,0-10,10 --resize 10x10" assert result.size_key == "micro" end end
41.130877
82
0.474421
1c01aaec95446675bcf45df267168d80362755d0
222
exs
Elixir
config/config.exs
outstand/plug
e75d542b3028b5c1f348ac9d128306c46a6b6e70
[ "Apache-2.0" ]
null
null
null
config/config.exs
outstand/plug
e75d542b3028b5c1f348ac9d128306c46a6b6e70
[ "Apache-2.0" ]
null
null
null
config/config.exs
outstand/plug
e75d542b3028b5c1f348ac9d128306c46a6b6e70
[ "Apache-2.0" ]
null
null
null
use Mix.Config config :logger, :console, format: "$time $metadata[$level] $message\n" if Mix.env() == :test do config :plug, :statuses, %{ 418 => "Totally not a teapot", 998 => "Not An RFC Status Code" } end
20.181818
70
0.621622
1c01b1449a98ef982bf23ff31bd7a7eb5d67acbf
3,140
ex
Elixir
lib/jsonpatch/operation/copy.ex
webdeb/jsonpatch
193b10745695bbc4dfd6a605e79af36be7c789f7
[ "MIT" ]
19
2020-06-01T17:28:31.000Z
2022-03-20T04:41:56.000Z
lib/jsonpatch/operation/copy.ex
webdeb/jsonpatch
193b10745695bbc4dfd6a605e79af36be7c789f7
[ "MIT" ]
5
2021-03-29T20:32:58.000Z
2022-01-12T08:19:00.000Z
lib/jsonpatch/operation/copy.ex
webdeb/jsonpatch
193b10745695bbc4dfd6a605e79af36be7c789f7
[ "MIT" ]
2
2021-03-29T20:55:32.000Z
2021-08-17T20:38:03.000Z
defmodule Jsonpatch.Operation.Copy do @moduledoc """ Represents the handling of JSON patches with a copy operation. ## Examples iex> copy = %Jsonpatch.Operation.Copy{from: "/a/b", path: "/a/e"} iex> target = %{"a" => %{"b" => %{"c" => "Bob"}}, "d" => false} iex> Jsonpatch.Operation.apply_op(copy, target) %{"a" => %{"b" => %{"c" => "Bob"}, "e" => %{"c" => "Bob"}}, "d" => false} """ @enforce_keys [:from, :path] defstruct [:from, :path] @type t :: %__MODULE__{from: String.t(), path: String.t()} end defimpl Jsonpatch.Operation, for: Jsonpatch.Operation.Copy do @spec apply_op(Jsonpatch.Operation.Copy.t(), map() | Jsonpatch.error()) :: map() def apply_op(_, {:error, _, _} = error), do: error def apply_op(%Jsonpatch.Operation.Copy{from: from, path: path}, target) do # %{"c" => "Bob"} updated_val = target |> Jsonpatch.PathUtil.get_final_destination(from) |> extract_copy_value() |> do_copy(target, path) case updated_val do {:error, _, _} = error -> error updated_val -> updated_val end end # ===== ===== PRIVATE ===== ===== defp do_copy({:error, _, _} = error, _target, _path) do error end defp do_copy(copied_value, target, path) do # copied_value = %{"c" => "Bob"} # "e" copy_path_end = String.split(path, "/") |> List.last() # %{"b" => %{"c" => "Bob"}, "e" => %{"c" => "Bob"}} updated_value = target # %{"b" => %{"c" => "Bob"}} is the "copy target" |> Jsonpatch.PathUtil.get_final_destination(path) # Add copied_value to "copy target" |> do_add(copied_value, copy_path_end) case updated_value do {:error, _, _} = error -> error updated_value -> Jsonpatch.PathUtil.update_final_destination(target, updated_value, path) end end defp extract_copy_value({%{} = final_destination, fragment}) do Map.get(final_destination, fragment, {:error, :invalid_path, fragment}) end defp extract_copy_value({final_destination, fragment}) when is_list(final_destination) do case Integer.parse(fragment) do :error -> {:error, :invalid_index, fragment} {index, _} -> case Enum.fetch(final_destination, index) do :error -> {:error, :invalid_index, fragment} {:ok, val} -> val end end end defp do_add({%{} = copy_target, _last_fragment}, copied_value, copy_path_end) do Map.put(copy_target, copy_path_end, copied_value) end defp do_add({copy_target, _last_fragment}, copied_value, copy_path_end) when is_list(copy_target) do if copy_path_end == "-" do List.insert_at(copy_target, length(copy_target), copied_value) else case Integer.parse(copy_path_end) do :error -> {:error, :invalid_index, copy_path_end} {index, _} -> if index < length(copy_target) do List.update_at(copy_target, index, fn _old -> copied_value end) else {:error, :invalid_index, copy_path_end} end end end end defp do_add({:error, _, _} = error, _, _) do error end end
29.345794
95
0.602229
1c01dac81f02efdf147f5179614a521e31455730
6,486
exs
Elixir
apps/omg_watcher_info/test/omg_watcher_info/db/txoutput_test.exs
omisego/elixir-omg
2c68973d8f29033d137f63a6e060f12e2a7dcd59
[ "Apache-2.0" ]
177
2018-08-24T03:51:02.000Z
2020-05-30T13:29:25.000Z
apps/omg_watcher_info/test/omg_watcher_info/db/txoutput_test.exs
omisego/elixir-omg
2c68973d8f29033d137f63a6e060f12e2a7dcd59
[ "Apache-2.0" ]
1,042
2018-08-25T00:52:39.000Z
2020-06-01T05:15:17.000Z
apps/omg_watcher_info/test/omg_watcher_info/db/txoutput_test.exs
omisego/elixir-omg
2c68973d8f29033d137f63a6e060f12e2a7dcd59
[ "Apache-2.0" ]
47
2018-08-24T12:06:33.000Z
2020-04-28T11:49:25.000Z
# Copyright 2019-2020 OMG Network Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.WatcherInfo.DB.TxOutputTest do use ExUnitFixtures use ExUnit.Case, async: false use OMG.Watcher.Fixtures import OMG.WatcherInfo.Factory alias OMG.Watcher.TestHelper alias OMG.Watcher.Utxo alias OMG.WatcherInfo.DB require Utxo @eth <<0::160>> @tag fixtures: [:phoenix_ecto_sandbox, :alice] test "transaction output schema handles big numbers properly", %{alice: alice} do power_of_2 = fn n -> :lists.duplicate(n, 2) |> Enum.reduce(&(&1 * &2)) end assert 16 == power_of_2.(4) big_amount = power_of_2.(256) - 1 block_application = %{ transactions: [OMG.Watcher.TestHelper.create_recovered([], @eth, [{alice, big_amount}])], number: 11_000, hash: <<?#::256>>, timestamp: :os.system_time(:second), eth_height: 10 } {:ok, _} = DB.Block.insert_from_block_application(block_application) utxo = DB.TxOutput.get_by_position(Utxo.position(11_000, 0, 0)) assert not is_nil(utxo) assert utxo.amount == big_amount end describe "create_outputs/4" do @tag fixtures: [:phoenix_ecto_sandbox, :alice] test "create outputs according to params", %{alice: alice} do blknum = 11_000 amount_1 = 1000 amount_2 = 2000 tx = OMG.Watcher.TestHelper.create_recovered([], @eth, [{alice, amount_1}, {alice, amount_2}]) assert [ %{ amount: amount_1, blknum: blknum, creating_txhash: tx.tx_hash, currency: @eth, oindex: 0, otype: 1, owner: alice.addr, txindex: 0 }, %{ amount: amount_2, blknum: blknum, creating_txhash: tx.tx_hash, currency: @eth, oindex: 1, otype: 1, owner: alice.addr, txindex: 0 } ] == DB.TxOutput.create_outputs(blknum, 0, tx.tx_hash, tx) end end describe "OMG.WatcherInfo.DB.TxOutput.spend_utxos/3" do # a special test for spend_utxos/3 is here because under the hood it calls update_all/3. using # update_all/3 with a queryable means that certain autogenerated columns, such as inserted_at and # updated_at, will not be updated as they would be if you used a plain update. More info # is here: https://hexdocs.pm/ecto/Ecto.Repo.html#c:update_all/3 @tag fixtures: [:phoenix_ecto_sandbox] test "spend_utxos updates the updated_at timestamp correctly" do deposit = :txoutput |> build() |> with_deposit() :transaction |> insert() |> with_inputs([deposit]) txinput = DB.TxOutput.get_by_position(Utxo.position(deposit.blknum, deposit.txindex, deposit.oindex)) spend_utxo_params = spend_uxto_params_from_txoutput(txinput) _ = DB.Repo.transaction(DB.TxOutput.spend_utxos(Ecto.Multi.new(), [spend_utxo_params])) spent_txoutput = DB.TxOutput.get_by_position(Utxo.position(txinput.blknum, txinput.txindex, txinput.oindex)) assert :eq == DateTime.compare(txinput.inserted_at, spent_txoutput.inserted_at) assert :lt == DateTime.compare(txinput.updated_at, spent_txoutput.updated_at) end end describe "get_utxos_grouped_by_currency/1" do @tag fixtures: [:phoenix_ecto_sandbox] test "returns outputs grouped by currency" do alice = TestHelper.generate_entity() currency_1 = <<1::160>> currency_2 = <<2::160>> _ = insert(:txoutput, currency: currency_1, owner: alice.addr) _ = insert(:txoutput, currency: currency_2, owner: alice.addr) _ = insert(:txoutput, currency: currency_1, owner: alice.addr) _ = insert(:txoutput, currency: currency_2, owner: alice.addr) result = DB.TxOutput.get_sorted_grouped_utxos(alice.addr, :desc) assert Map.keys(result) == [currency_1, currency_2] Enum.each(result, fn {currency, outputs} -> assert length(outputs) == 2 Enum.each(outputs, fn output -> assert output.currency == currency end) end) end @tag fixtures: [:phoenix_ecto_sandbox] test "returns outputs for the given address only" do alice = <<1::160>> bob = <<2::160>> _ = insert(:txoutput, owner: alice) _ = insert(:txoutput, owner: alice) _ = insert(:txoutput, owner: bob) result = DB.TxOutput.get_sorted_grouped_utxos(alice, :desc) Enum.each(result, fn {_currency, outputs} -> Enum.each(outputs, fn output -> assert output.owner == alice end) end) end @tag fixtures: [:phoenix_ecto_sandbox] test "returns outputs for a given currency in descending amount order if specified" do alice = <<1::160>> _ = insert(:txoutput, amount: 100, currency: @eth, owner: alice) _ = insert(:txoutput, amount: 200, currency: @eth, owner: alice) _ = insert(:txoutput, amount: 300, currency: @eth, owner: alice) result = alice |> DB.TxOutput.get_sorted_grouped_utxos(:desc) |> Map.get(@eth) assert result |> Enum.at(0) |> Map.get(:amount) == 300 assert result |> Enum.at(1) |> Map.get(:amount) == 200 assert result |> Enum.at(2) |> Map.get(:amount) == 100 end @tag fixtures: [:phoenix_ecto_sandbox] test "returns outputs for a given currency in ascending amount order if specified" do alice = <<1::160>> _ = insert(:txoutput, amount: 100, currency: @eth, owner: alice) _ = insert(:txoutput, amount: 200, currency: @eth, owner: alice) _ = insert(:txoutput, amount: 300, currency: @eth, owner: alice) result = alice |> DB.TxOutput.get_sorted_grouped_utxos(:asc) |> Map.get(@eth) assert result |> Enum.at(0) |> Map.get(:amount) == 100 assert result |> Enum.at(1) |> Map.get(:amount) == 200 assert result |> Enum.at(2) |> Map.get(:amount) == 300 end end end
36.438202
114
0.644157
1c0205e8fff821a3f7bbedf1ba74b953d8a25309
1,660
ex
Elixir
apps/fz_http/test/support/fixtures.ex
jasonboukheir/firezone
79d610b94f67ae25c8ca26f391c0edf288f6aaa5
[ "Apache-2.0" ]
null
null
null
apps/fz_http/test/support/fixtures.ex
jasonboukheir/firezone
79d610b94f67ae25c8ca26f391c0edf288f6aaa5
[ "Apache-2.0" ]
null
null
null
apps/fz_http/test/support/fixtures.ex
jasonboukheir/firezone
79d610b94f67ae25c8ca26f391c0edf288f6aaa5
[ "Apache-2.0" ]
null
null
null
defmodule FzHttp.Fixtures do @moduledoc """ Convenience helpers for inserting records """ alias FzHttp.{Devices, Repo, Rules, Sessions, Users, Users.User} # return user specified by email, or generate a new otherwise def user(attrs \\ %{}) do email = Map.get(attrs, :email, "test-#{counter()}@test") case Repo.get_by(User, email: email) do nil -> {:ok, user} = %{email: email, password: "test", password_confirmation: "test"} |> Map.merge(attrs) |> Users.create_user() user %User{} = user -> user end end def device(attrs \\ %{}) do # don't create a user if user_id is passed user_id = Map.get_lazy(attrs, :user_id, fn -> user().id end) default_attrs = %{ user_id: user_id, public_key: "test-pubkey", name: "factory", private_key: "test-privkey", server_public_key: "test-server-pubkey" } {:ok, device} = Devices.create_device(Map.merge(default_attrs, attrs)) device end def rule4(attrs \\ %{}) do rule(attrs) end def rule6(attrs \\ %{}) do rule(Map.merge(attrs, %{destination: "::/0"})) end def rule(attrs \\ %{}) do default_attrs = %{ destination: "10.10.10.0/24" } {:ok, rule} = Rules.create_rule(Map.merge(default_attrs, attrs)) rule end def session(_attrs \\ %{}) do email = user().email record = Sessions.get_session!(email: email) create_params = %{email: email, password: "test"} {:ok, session} = Sessions.create_session(record, create_params) session end defp counter do System.unique_integer([:positive]) end end
23.714286
74
0.606024
1c0247c100b49fc98f7f3c9aeab1a70b9dfe48d0
10,376
exs
Elixir
test/oli_web/live/sections/overview_live_test.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
test/oli_web/live/sections/overview_live_test.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
test/oli_web/live/sections/overview_live_test.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule OliWeb.Sections.OverviewLiveTest do use ExUnit.Case use OliWeb.ConnCase import Phoenix.LiveViewTest import Oli.Factory alias Oli.Delivery.Sections alias Oli.Delivery.Sections.Section alias Lti_1p3.Tool.ContextRoles defp live_view_overview_route(section_slug) do Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.OverviewView, section_slug) end defp create_section(_conn) do section = insert(:section) [section: section] end describe "user cannot access when is not logged in" do setup [:create_section] test "redirects to new session when accessing the section overview view", %{ conn: conn, section: section } do section_slug = section.slug redirect_path = "/session/new?request_path=%2Fsections%2F#{section_slug}&section=#{section_slug}" {:error, {:redirect, %{to: ^redirect_path}}} = live(conn, live_view_overview_route(section.slug)) end end describe "user cannot access when is logged in as an author but is not a system admin" do setup [:author_conn, :create_section] test "redirects to new session when accessing the section overview view", %{ conn: conn, section: section } do conn = get(conn, live_view_overview_route(section.slug)) redirect_path = "/session/new?request_path=%2Fsections%2F#{section.slug}" assert redirected_to(conn, 302) =~ redirect_path end end describe "user cannot access when is logged in as an instructor but is not enrolled in the section" do setup [:user_conn] test "redirects to new session when accessing the section overview view", %{ conn: conn } do section = insert(:section, %{type: :enrollable}) conn = get(conn, live_view_overview_route(section.slug)) redirect_path = "/unauthorized" assert redirected_to(conn, 302) =~ redirect_path end end describe "user cannot access when is logged in as a student and is enrolled in the section" do setup [:user_conn] test "redirects to new session when accessing the section overview view", %{ conn: conn, user: user } do section = insert(:section, %{type: :enrollable}) Sections.enroll(user.id, section.id, [ContextRoles.get_role(:context_learner)]) conn = get(conn, live_view_overview_route(section.slug)) redirect_path = "/unauthorized" assert redirected_to(conn, 302) =~ redirect_path end end describe "user can access when is logged in as an instructor and is enrolled in the section" do setup [:user_conn] test "loads correctly", %{ conn: conn, user: user } do section = insert(:section, %{type: :enrollable}) Sections.enroll(user.id, section.id, [ContextRoles.get_role(:context_instructor)]) {:ok, _view, html} = live(conn, live_view_overview_route(section.slug)) refute html =~ "<nav aria-label=\"breadcrumb" assert html =~ "Overview" end end describe "admin is prioritized over instructor when both logged in" do setup [:admin_conn, :user_conn] test "loads correctly", %{ conn: conn, user: user } do section = insert(:section, %{type: :enrollable}) Sections.enroll(user.id, section.id, [ContextRoles.get_role(:context_instructor)]) {:ok, _view, html} = live(conn, live_view_overview_route(section.slug)) assert html =~ "<nav aria-label=\"breadcrumb" assert html =~ "Overview" end end describe "overview live view" do setup [:admin_conn, :create_section] test "returns 404 when section not exists", %{conn: conn} do conn = get(conn, live_view_overview_route("not_exists")) assert response(conn, 404) end test "loads section data correctly", %{conn: conn} do section = insert(:section, open_and_free: true) {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "Overview" assert render(view) =~ "Overview of this course section" assert has_element?(view, "input[value=\"#{section.slug}\"]") assert has_element?(view, "input[value=\"#{section.title}\"]") assert has_element?(view, "input[value=\"Direct Delivery\"]") end test "loads section instructors correctly", %{conn: conn, section: section} do user_enrolled = insert(:user) user_not_enrolled = insert(:user, %{given_name: "Other"}) Sections.enroll(user_enrolled.id, section.id, [ContextRoles.get_role(:context_instructor)]) {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "Instructors" assert render(view) =~ "Manage the users with instructor level access" assert render(view) =~ user_enrolled.given_name refute render(view) =~ user_not_enrolled.given_name end test "loads section links correctly", %{conn: conn, section: section} do {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "Curriculum" assert render(view) =~ "Manage the content delivered to students" assert has_element?( view, "a[href=\"#{Routes.page_delivery_path(OliWeb.Endpoint, :index_preview, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.page_delivery_path(OliWeb.Endpoint, :index, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Delivery.RemixSection, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.GatingAndScheduling, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.section_updates_path(OliWeb.Endpoint, OliWeb.Delivery.ManageUpdates, section.slug)}\"]" ) assert render(view) =~ "Manage" assert render(view) =~ "Manage all aspects of course delivery" assert has_element?( view, "a[href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.EnrollmentsView, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.EditView, section.slug)}\"]" ) assert render(view) =~ "Grading" assert render(view) =~ "View and manage student grades and progress" assert has_element?( view, "a[href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Grades.GradebookView, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.page_delivery_path(OliWeb.Endpoint, :export_gradebook, section.slug)}\"]" ) assert has_element?( view, "a[href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Grades.GradesLive, section.slug)}\"]" ) end test "unlink section from lms", %{conn: conn, section: section} do {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "LMS Admin" assert render(view) =~ "Administrator LMS Connection" view |> element("button[phx-click=\"unlink\"]") |> render_click() assert_redirected(view, Routes.delivery_path(OliWeb.Endpoint, :index)) assert %Section{status: :deleted} = Sections.get_section!(section.id) end test "deletes a section when it has no students associated data", %{ conn: conn, section: section } do {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "Delete Section" view |> element("button[phx-click=\"show_delete_modal\"]") |> render_click() assert view |> element("#delete_section_modal") |> render() =~ "This action cannot be undone. Are you sure you want to delete this section?" view |> element("button[phx-click=\"delete_section\"]") |> render_click() assert_redirected(view, Routes.delivery_path(OliWeb.Endpoint, :open_and_free_index)) refute Sections.get_section_by_slug(section.slug) end test "archives a section when it has students associated data", %{conn: conn} do section = insert(:snapshot).section {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "Delete Section" view |> element("button[phx-click=\"show_delete_modal\"]") |> render_click() assert view |> element("#delete_section_modal") |> render() =~ """ This section has student data and will be archived rather than deleted. Are you sure you want to archive it? You will no longer have access to the data. Archiving this section will make it so students can no longer access it. """ view |> element("button[phx-click=\"delete_section\"]") |> render_click() assert_redirected(view, Routes.delivery_path(OliWeb.Endpoint, :open_and_free_index)) assert %Section{status: :archived} = Sections.get_section!(section.id) end test "displays a flash message when there is student activity after the modal shows up", %{ conn: conn, section: section } do {:ok, view, _html} = live(conn, live_view_overview_route(section.slug)) assert render(view) =~ "Delete Section" view |> element("button[phx-click=\"show_delete_modal\"]") |> render_click() assert view |> element("#delete_section_modal") |> render() =~ "This action cannot be undone. Are you sure you want to delete this section?" # Add student activity to the section insert(:snapshot, section: section) view |> element("button[phx-click=\"delete_section\"]") |> render_click() assert render(view) =~ "Section had student activity recently. It can now only be archived, please try again." assert %Section{status: :active} = Sections.get_section!(section.id) end end end
32.835443
168
0.635601
1c025215180e0058032cf477edfc56e3084a0957
262
ex
Elixir
lib/commanded/shredder/events/encryption_key_deleted.ex
KazW/commanded-shredder-middleware
ab4494db84983acfe7cd2d47a9b81dbec7c36a9d
[ "MIT" ]
1
2020-07-30T18:40:11.000Z
2020-07-30T18:40:11.000Z
lib/commanded/shredder/events/encryption_key_deleted.ex
KazW/commanded-shredder-middleware
ab4494db84983acfe7cd2d47a9b81dbec7c36a9d
[ "MIT" ]
null
null
null
lib/commanded/shredder/events/encryption_key_deleted.ex
KazW/commanded-shredder-middleware
ab4494db84983acfe7cd2d47a9b81dbec7c36a9d
[ "MIT" ]
null
null
null
defmodule Commanded.Shredder.EncryptionKeyDeleted do @moduledoc false @derive Jason.Encoder @type t :: %__MODULE__{ encryption_key_uuid: String.t(), name: String.t() } defstruct [ :encryption_key_uuid, :name ] end
17.466667
52
0.637405
1c025640d7bac2dee8d59a2a785f9fa6b544e987
1,815
ex
Elixir
clients/proximity_beacon/lib/google_api/proximity_beacon/v1beta1/model/get_info_for_observed_beacons_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/proximity_beacon/lib/google_api/proximity_beacon/v1beta1/model/get_info_for_observed_beacons_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/proximity_beacon/lib/google_api/proximity_beacon/v1beta1/model/get_info_for_observed_beacons_response.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.ProximityBeacon.V1beta1.Model.GetInfoForObservedBeaconsResponse do @moduledoc """ Information about the requested beacons, optionally including attachment data. ## Attributes - beacons ([BeaconInfo]): Public information about beacons. May be empty if the request matched no beacons. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :beacons => list(GoogleApi.ProximityBeacon.V1beta1.Model.BeaconInfo.t()) } field(:beacons, as: GoogleApi.ProximityBeacon.V1beta1.Model.BeaconInfo, type: :list) end defimpl Poison.Decoder, for: GoogleApi.ProximityBeacon.V1beta1.Model.GetInfoForObservedBeaconsResponse do def decode(value, options) do GoogleApi.ProximityBeacon.V1beta1.Model.GetInfoForObservedBeaconsResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.ProximityBeacon.V1beta1.Model.GetInfoForObservedBeaconsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.245283
130
0.763085
1c02565146e511ce42afc55a0f2ec8fe52ac824d
960
ex
Elixir
lib/speck/printer.ex
fdfzcq/speck
e2f3ed839c11f2de6b7b00259a66c5ffa7c5420c
[ "Apache-2.0" ]
1
2018-11-19T15:54:56.000Z
2018-11-19T15:54:56.000Z
lib/speck/printer.ex
fdfzcq/speck
e2f3ed839c11f2de6b7b00259a66c5ffa7c5420c
[ "Apache-2.0" ]
null
null
null
lib/speck/printer.ex
fdfzcq/speck
e2f3ed839c11f2de6b7b00259a66c5ffa7c5420c
[ "Apache-2.0" ]
null
null
null
defmodule Speck.Printer do def print(report = %{success: true}, sum = %{success: success}) do args = report.arg |> Enum.map(&add_quotes/1) |> Enum.join(", ") log = "#{report.module}.#{report.function}(#{args}) passed" Bunt.puts([:green, log]) %{sum|success: success + 1} end def print(report = %{success: false}, sum = %{failed: failed}) do args = Enum.join(report.arg, ", ") expected = Enum.join(report.expected, "|") log = "#{report.module}.#{report.function}(#{args}) failed with result #{report.result} expected result to be (#{expected})" Bunt.puts([:red, log]) %{sum|failed: failed + 1} end def print_summary(%{success: no_of_success, failed: no_of_failed}) do IO.puts "" Bunt.puts([:green, "success: #{no_of_success} ", :red, "failed: #{no_of_failed}"]) end defp add_quotes(arg) do case is_binary(arg) do true -> "\"" <> arg <> "\"" false -> arg end end end
30.967742
128
0.6
1c0266f336b2671919128f1574ea8075c6432bc5
1,593
ex
Elixir
kousa/lib/broth/message/user/create_bot.ex
samyadel/dogehouse
c9daffbfe81a7488093b07f3f9a274a062dde801
[ "MIT" ]
2
2021-05-01T16:57:50.000Z
2021-07-07T22:01:14.000Z
kousa/lib/broth/message/user/create_bot.ex
samyadel/dogehouse
c9daffbfe81a7488093b07f3f9a274a062dde801
[ "MIT" ]
null
null
null
kousa/lib/broth/message/user/create_bot.ex
samyadel/dogehouse
c9daffbfe81a7488093b07f3f9a274a062dde801
[ "MIT" ]
null
null
null
defmodule Broth.Message.User.CreateBot do use Broth.Message.Call, reply: __MODULE__ @derive {Jason.Encoder, only: [:username]} @primary_key {:id, :binary_id, []} schema "users" do field(:username, :string) end # inbound data. def changeset(initializer \\ %__MODULE__{}, data) do initializer |> cast(data, [:username]) |> validate_required([:username]) end defmodule Reply do use Broth.Message.Push @derive {Jason.Encoder, only: ~w( apiKey isUsernameTaken error )a} @primary_key false embedded_schema do field(:apiKey, :string) field(:isUsernameTaken, :boolean) # @todo conver to proper error handling field(:error, :string) end end alias Beef.Users alias Beef.Schemas.User def execute(changeset!, state) do with {:ok, %{username: username}} <- apply_action(changeset!, :validation) do cond do Users.bot?(state.user_id) -> {:reply, %Reply{error: "bots can't create bots"}, state} Users.count_bot_accounts(state.user_id) > 99 -> {:reply, %Reply{error: "you've reached the max of 100 bot accounts"}, state} true -> case Users.create_bot(state.user_id, username) do {:ok, %User{apiKey: apiKey}} -> {:reply, %Reply{apiKey: apiKey}, state} {:error, %Ecto.Changeset{ errors: [username: {"has already been taken", _}] }} -> {:reply, %Reply{isUsernameTaken: true}, state} end end end end end
24.890625
86
0.588826
1c027b5942a4e714299751d02448d683f82c8d8a
430
exs
Elixir
test/test_helper.exs
epinault/snowflake_elixir_ecto
9f8fc9d272ca140e27acb671af1a1c46ff923b2b
[ "MIT" ]
4
2020-10-30T03:30:01.000Z
2021-08-07T10:27:15.000Z
test/test_helper.exs
epinault/snowflake_elixir_ecto
9f8fc9d272ca140e27acb671af1a1c46ff923b2b
[ "MIT" ]
5
2020-10-25T12:48:17.000Z
2021-12-06T07:29:02.000Z
test/test_helper.exs
epinault/snowflake_elixir_ecto
9f8fc9d272ca140e27acb671af1a1c46ff923b2b
[ "MIT" ]
3
2020-10-25T11:18:58.000Z
2021-10-16T04:00:18.000Z
Code.require_file("./support/repo.exs", __DIR__) defmodule Ecto.Integration.PoolRepo do use Ecto.Integration.Repo, otp_app: :snowflake_elixir_ecto, adapter: Ecto.Adapters.Snowflake def create_prefix(prefix) do "create schema #{prefix}" end def drop_prefix(prefix) do "drop schema #{prefix}" end def uuid do Ecto.UUID end end Code.require_file "./support/quick_migration.exs", __DIR__ ExUnit.start()
20.47619
94
0.737209
1c027df34c821171d6643a2472488a5d41060c91
1,797
exs
Elixir
mix.exs
chernyshof/react-phoenix-users-boilerplate
2642c88aadff377f38dce5a85a3caa7f4b088588
[ "MIT" ]
152
2017-05-29T06:04:01.000Z
2021-12-11T19:24:02.000Z
mix.exs
chernyshof/react-phoenix-users-boilerplate
2642c88aadff377f38dce5a85a3caa7f4b088588
[ "MIT" ]
13
2017-07-29T18:26:37.000Z
2018-10-26T08:33:16.000Z
mix.exs
chernyshof/react-phoenix-users-boilerplate
2642c88aadff377f38dce5a85a3caa7f4b088588
[ "MIT" ]
12
2017-11-18T19:13:44.000Z
2019-10-10T01:29:28.000Z
defmodule Boilerplate.Mixfile do use Mix.Project def project do [ app: :boilerplate, version: "0.0.1", elixir: "~> 1.6", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Boilerplate.Application, []}, extra_applications: [:logger, :runtime_tools, :comeonin] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.3.4"}, {:phoenix_pubsub, "~> 1.1"}, {:phoenix_ecto, "~> 3.5"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.12"}, {:phoenix_live_reload, "~> 1.1", only: :dev}, {:gettext, "~> 0.16"}, {:credo, "~> 0.10", only: [:dev, :test], runtime: false}, {:cowboy, "~> 1.1"}, {:comeonin, "~> 4.1"}, {:bcrypt_elixir, "~> 1.1"}, {:plug_cowboy, "~> 1.0"}, {:guardian, "~> 1.1"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
27.227273
79
0.570395
1c028ab133fda726b8811c422df08f8094bdb751
2,038
ex
Elixir
lib/user_manager/authenticate/authenticate_user_user_lookup.ex
Alezrik/user_manager
ef30f87587f652842b335b38dd2222873dbcb56b
[ "MIT" ]
3
2017-04-02T11:17:31.000Z
2017-09-08T09:12:11.000Z
lib/user_manager/authenticate/authenticate_user_user_lookup.ex
Alezrik/user_manager
ef30f87587f652842b335b38dd2222873dbcb56b
[ "MIT" ]
15
2017-02-11T01:08:54.000Z
2017-02-22T09:45:41.000Z
lib/user_manager/authenticate/authenticate_user_user_lookup.ex
Alezrik/user_manager
ef30f87587f652842b335b38dd2222873dbcb56b
[ "MIT" ]
1
2018-06-19T04:10:53.000Z
2018-06-19T04:10:53.000Z
defmodule UserManager.Authenticate.AuthenticateUserUserLookup do @moduledoc false use GenStage require Logger alias UserManager.Schemas.UserSchema alias UserManager.Repo import Ecto.Query def start_link(_) do GenStage.start_link(__MODULE__, [], [name: __MODULE__]) end def init(_) do {:producer_consumer, [], subscribe_to: [UserManager.Authenticate.AuthenticateUserWorkflowProducer]} end @doc""" get event from workflow producer Input: {:authenticate_user, name, password, source, notify} Output: {:user_not_found_error, notify} {:validate_user, user, password, source, notify} ## Examples: iex> name = Faker.Name.first_name <> Faker.Name.last_name iex> {:notify, _user} = UserManager.UserManagerApi.create_user(name, "secretpassword", "here@there.com") iex> {:noreply, response, _state} = UserManager.Authenticate.AuthenticateUserUserLookup.handle_events([{:authenticate_user, name, "secretpassword", :browser, nil}], self(), []) iex> Enum.at(Tuple.to_list(Enum.at(response, 0)), 0) :validate_user iex>UserManager.Authenticate.AuthenticateUserUserLookup.handle_events([{:authenticate_user, "someothername", "secretpassword", :browser, nil}], self(), []) {:noreply, [], []} """ def handle_events(events, _from, state) do process_events = events |> Flow.from_enumerable |> Flow.flat_map(fn e -> process_event(e) end) |> Enum.to_list {:noreply, process_events, state} end defp process_event({:authenticate_user, name, password, source, notify}) do case GenServer.call(UserManager.UserRepo, {:get_user_id_for_authentication_name, name}) do {:user_not_found} -> UserManager.Notifications.NotificationResponseProcessor.process_notification(:authenticate, :user_not_found, %{}, notify) [] {user_id} -> user = UserSchema |> where(id: ^user_id) |> Repo.one! |> Repo.preload(:user_profile) [{:validate_user, user, password, source, notify}] end end end
38.45283
180
0.701178
1c02df121cc3066af6da7f64ba2ee2ce049b5b84
146
ex
Elixir
lib/elrondex/test.ex
victorflx/elrondex
a90521ce5e39ad37453dcb53f527b8311ae1ae4f
[ "MIT" ]
8
2021-10-02T16:25:19.000Z
2022-02-03T17:50:34.000Z
lib/elrondex/test.ex
victorflx/elrondex
a90521ce5e39ad37453dcb53f527b8311ae1ae4f
[ "MIT" ]
1
2022-01-19T12:10:49.000Z
2022-01-19T12:10:49.000Z
lib/elrondex/test.ex
victorflx/elrondex
a90521ce5e39ad37453dcb53f527b8311ae1ae4f
[ "MIT" ]
2
2022-01-10T07:48:16.000Z
2022-02-06T17:05:57.000Z
defmodule Elrondex.Test do def pad(value) when rem(byte_size(value), 2) == 0 do value end def pad(value) do "0" <> value end end
14.6
54
0.630137
1c0305f3840ed306562b97800f0629f6ca809d14
4,784
ex
Elixir
lib/codes/codes_n07.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_n07.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_n07.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_N07 do alias IcdCode.ICDCode def _N070 do %ICDCode{full_code: "N070", category_code: "N07", short_code: "0", full_name: "Hereditary nephropathy, not elsewhere classified with minor glomerular abnormality", short_name: "Hereditary nephropathy, not elsewhere classified with minor glomerular abnormality", category_name: "Hereditary nephropathy, not elsewhere classified with minor glomerular abnormality" } end def _N071 do %ICDCode{full_code: "N071", category_code: "N07", short_code: "1", full_name: "Hereditary nephropathy, not elsewhere classified with focal and segmental glomerular lesions", short_name: "Hereditary nephropathy, not elsewhere classified with focal and segmental glomerular lesions", category_name: "Hereditary nephropathy, not elsewhere classified with focal and segmental glomerular lesions" } end def _N072 do %ICDCode{full_code: "N072", category_code: "N07", short_code: "2", full_name: "Hereditary nephropathy, not elsewhere classified with diffuse membranous glomerulonephritis", short_name: "Hereditary nephropathy, not elsewhere classified with diffuse membranous glomerulonephritis", category_name: "Hereditary nephropathy, not elsewhere classified with diffuse membranous glomerulonephritis" } end def _N073 do %ICDCode{full_code: "N073", category_code: "N07", short_code: "3", full_name: "Hereditary nephropathy, not elsewhere classified with diffuse mesangial proliferative glomerulonephritis", short_name: "Hereditary nephropathy, not elsewhere classified with diffuse mesangial proliferative glomerulonephritis", category_name: "Hereditary nephropathy, not elsewhere classified with diffuse mesangial proliferative glomerulonephritis" } end def _N074 do %ICDCode{full_code: "N074", category_code: "N07", short_code: "4", full_name: "Hereditary nephropathy, not elsewhere classified with diffuse endocapillary proliferative glomerulonephritis", short_name: "Hereditary nephropathy, not elsewhere classified with diffuse endocapillary proliferative glomerulonephritis", category_name: "Hereditary nephropathy, not elsewhere classified with diffuse endocapillary proliferative glomerulonephritis" } end def _N075 do %ICDCode{full_code: "N075", category_code: "N07", short_code: "5", full_name: "Hereditary nephropathy, not elsewhere classified with diffuse mesangiocapillary glomerulonephritis", short_name: "Hereditary nephropathy, not elsewhere classified with diffuse mesangiocapillary glomerulonephritis", category_name: "Hereditary nephropathy, not elsewhere classified with diffuse mesangiocapillary glomerulonephritis" } end def _N076 do %ICDCode{full_code: "N076", category_code: "N07", short_code: "6", full_name: "Hereditary nephropathy, not elsewhere classified with dense deposit disease", short_name: "Hereditary nephropathy, not elsewhere classified with dense deposit disease", category_name: "Hereditary nephropathy, not elsewhere classified with dense deposit disease" } end def _N077 do %ICDCode{full_code: "N077", category_code: "N07", short_code: "7", full_name: "Hereditary nephropathy, not elsewhere classified with diffuse crescentic glomerulonephritis", short_name: "Hereditary nephropathy, not elsewhere classified with diffuse crescentic glomerulonephritis", category_name: "Hereditary nephropathy, not elsewhere classified with diffuse crescentic glomerulonephritis" } end def _N078 do %ICDCode{full_code: "N078", category_code: "N07", short_code: "8", full_name: "Hereditary nephropathy, not elsewhere classified with other morphologic lesions", short_name: "Hereditary nephropathy, not elsewhere classified with other morphologic lesions", category_name: "Hereditary nephropathy, not elsewhere classified with other morphologic lesions" } end def _N079 do %ICDCode{full_code: "N079", category_code: "N07", short_code: "9", full_name: "Hereditary nephropathy, not elsewhere classified with unspecified morphologic lesions", short_name: "Hereditary nephropathy, not elsewhere classified with unspecified morphologic lesions", category_name: "Hereditary nephropathy, not elsewhere classified with unspecified morphologic lesions" } end end
49.319588
135
0.712584
1c0317b1705e62ad78a912a5920ad95499871b22
2,897
ex
Elixir
clients/bigtable_admin/lib/google_api/bigtable_admin/v2/model/restore_table_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/bigtable_admin/lib/google_api/bigtable_admin/v2/model/restore_table_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/bigtable_admin/lib/google_api/bigtable_admin/v2/model/restore_table_metadata.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.BigtableAdmin.V2.Model.RestoreTableMetadata do @moduledoc """ Metadata type for the long-running operation returned by RestoreTable. ## Attributes * `backupInfo` (*type:* `GoogleApi.BigtableAdmin.V2.Model.BackupInfo.t`, *default:* `nil`) - * `name` (*type:* `String.t`, *default:* `nil`) - Name of the table being created and restored to. * `optimizeTableOperationName` (*type:* `String.t`, *default:* `nil`) - If exists, the name of the long-running operation that will be used to track the post-restore optimization process to optimize the performance of the restored table. The metadata type of the long-running operation is OptimizeRestoreTableMetadata. The response type is Empty. This long-running operation may be automatically created by the system if applicable after the RestoreTable long-running operation completes successfully. This operation may not be created if the table is already optimized or the restore was not successful. * `progress` (*type:* `GoogleApi.BigtableAdmin.V2.Model.OperationProgress.t`, *default:* `nil`) - The progress of the RestoreTable operation. * `sourceType` (*type:* `String.t`, *default:* `nil`) - The type of the restore source. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :backupInfo => GoogleApi.BigtableAdmin.V2.Model.BackupInfo.t() | nil, :name => String.t() | nil, :optimizeTableOperationName => String.t() | nil, :progress => GoogleApi.BigtableAdmin.V2.Model.OperationProgress.t() | nil, :sourceType => String.t() | nil } field(:backupInfo, as: GoogleApi.BigtableAdmin.V2.Model.BackupInfo) field(:name) field(:optimizeTableOperationName) field(:progress, as: GoogleApi.BigtableAdmin.V2.Model.OperationProgress) field(:sourceType) end defimpl Poison.Decoder, for: GoogleApi.BigtableAdmin.V2.Model.RestoreTableMetadata do def decode(value, options) do GoogleApi.BigtableAdmin.V2.Model.RestoreTableMetadata.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigtableAdmin.V2.Model.RestoreTableMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
49.101695
608
0.741802
1c03274d2cd0dccb0ba23c0375a693c84fa2b481
466
ex
Elixir
lib/budget_app/user.ex
djordje/budget_app.backend
3febe64892e700f3174b8eddbc4b96260c444308
[ "MIT" ]
null
null
null
lib/budget_app/user.ex
djordje/budget_app.backend
3febe64892e700f3174b8eddbc4b96260c444308
[ "MIT" ]
null
null
null
lib/budget_app/user.ex
djordje/budget_app.backend
3febe64892e700f3174b8eddbc4b96260c444308
[ "MIT" ]
null
null
null
defmodule BudgetApp.User do use Ecto.Schema import Ecto.Changeset alias BudgetApp.User schema "users" do field :email, :string field :secret, :string timestamps() has_many :api_tokens, BudgetApp.APIToken end @doc false def changeset(%User{} = user, attrs) do user |> cast(attrs, [:email, :secret]) |> validate_required([:email, :secret]) |> validate_format(:email, ~r/@/) |> unique_constraint(:email) end end
18.64
44
0.652361
1c0329d6b374677f5f19490527c6bfa01d056b97
810
ex
Elixir
rockelivery/lib/rockelivery/orders/order.ex
arilsonsouza/rocketseat-ignite-elixir
93e32d52d589336dfd2d81e755d6dd7f05ee40b8
[ "MIT" ]
null
null
null
rockelivery/lib/rockelivery/orders/order.ex
arilsonsouza/rocketseat-ignite-elixir
93e32d52d589336dfd2d81e755d6dd7f05ee40b8
[ "MIT" ]
null
null
null
rockelivery/lib/rockelivery/orders/order.ex
arilsonsouza/rocketseat-ignite-elixir
93e32d52d589336dfd2d81e755d6dd7f05ee40b8
[ "MIT" ]
null
null
null
defmodule Rockelivery.Orders.Order do use Rockelivery.Schema @fields [:user_id, :address, :comments, :payment_type] @derive {Jason.Encoder, only: [:id, :items] ++ @fields} @payment_types [:money, :credit_card, :debit_card] alias Rockelivery.Items.Item alias Rockelivery.Accounts.User schema "orders" do field(:address, :string) field(:comments, :string) field(:payment_type, Ecto.Enum, values: @payment_types) belongs_to(:user, User) many_to_many(:items, Item, join_through: "orders_items") timestamps() end def changeset(%__MODULE__{} = order, attrs, items) do order |> cast(attrs, @fields) |> validate_required(@fields) |> put_assoc(:items, items) |> validate_length(:address, min: 10) |> validate_length(:comments, min: 6) end end
24.545455
60
0.681481
1c032b646455d04dd6612d0c1898989d773f323c
917
ex
Elixir
lib/chat_api_web/views/account_view.ex
rlanga/papercups
358ca46c344908585cd0214a0de96e5676120c68
[ "MIT" ]
1
2020-08-13T15:11:12.000Z
2020-08-13T15:11:12.000Z
lib/chat_api_web/views/account_view.ex
rlanga/papercups
358ca46c344908585cd0214a0de96e5676120c68
[ "MIT" ]
null
null
null
lib/chat_api_web/views/account_view.ex
rlanga/papercups
358ca46c344908585cd0214a0de96e5676120c68
[ "MIT" ]
null
null
null
defmodule ChatApiWeb.AccountView do use ChatApiWeb, :view alias ChatApiWeb.{AccountView, UserView, WidgetSettingsView} def render("index.json", %{accounts: accounts}) do %{data: render_many(accounts, AccountView, "account.json")} end def render("show.json", %{account: account}) do %{data: render_one(account, AccountView, "account.json")} end def render("create.json", %{account: account}) do %{data: render_one(account, AccountView, "basic.json")} end def render("basic.json", %{account: account}) do %{ id: account.id, company_name: account.company_name } end def render("account.json", %{account: account}) do %{ id: account.id, company_name: account.company_name, users: render_many(account.users, UserView, "user.json"), widget_settings: render_one(account.widget_settings, WidgetSettingsView, "basic.json") } end end
27.787879
92
0.68048
1c0336f7031e7a78c6e72dcc1ef509d0489ecb42
63
ex
Elixir
lib/preview_web/views/layout_view.ex
leandrocp/preview
9dd3a9bae4385dc4935e76f63328f70b9d78fe4d
[ "Apache-2.0" ]
26
2021-01-25T20:30:46.000Z
2021-12-16T08:42:35.000Z
lib/preview_web/views/layout_view.ex
leandrocp/preview
9dd3a9bae4385dc4935e76f63328f70b9d78fe4d
[ "Apache-2.0" ]
17
2021-01-25T18:45:43.000Z
2021-07-23T15:15:41.000Z
preview/lib/preview_web/views/layout_view.ex
podlove/podlove-preview
7a12cedf338929762e8ef4dea69771e29a89f132
[ "MIT" ]
4
2021-01-25T21:32:28.000Z
2021-07-07T12:36:19.000Z
defmodule PreviewWeb.LayoutView do use PreviewWeb, :view end
15.75
34
0.809524
1c033db18e5902985c01f9a881c1d8361dd29310
1,789
exs
Elixir
exercises/dot-dsl/example.exs
darktef/elixir-exercism
bcaae351486b1405f0a01cd33b4d39555546298e
[ "MIT" ]
1
2021-08-16T20:24:14.000Z
2021-08-16T20:24:14.000Z
exercises/dot-dsl/example.exs
Triangle-Elixir/xelixir
08d23bf47f57799f286567cb26f635291de2fde5
[ "MIT" ]
null
null
null
exercises/dot-dsl/example.exs
Triangle-Elixir/xelixir
08d23bf47f57799f286567cb26f635291de2fde5
[ "MIT" ]
null
null
null
defmodule Graph do defstruct attrs: [], nodes: [], edges: [] end defmodule Dot do # Normally matching on keywords is a bad idea as keyword lists can have # several orders (i.e. `[a: 1, b: 2]` and `[b: 2, a: 1]`). But in this case # only one keyword is allowed, so it's safe. defmacro graph([do: ast]) do g = do_graph(ast) Macro.escape( %Graph{attrs: Enum.sort(g.attrs), nodes: Enum.sort(g.nodes), edges: Enum.sort(g.edges)}) end defp do_graph(nil) do %Graph{} end defp do_graph({:__block__, _, stmts}) do Enum.reduce(stmts, %Graph{}, &do_stmt/2) end defp do_graph(stmt) do do_stmt(stmt, %Graph{}) end defp do_stmt(stmt = {:graph, _, [kws]}, g) when is_list(kws) do if Keyword.keyword?(kws) do %{g | attrs: kws ++ g.attrs} else raise_invalid_stmt(stmt) end end defp do_stmt({atom, _, nil}, g) when is_atom(atom) and atom != :-- do %{g | nodes: [{atom, []} | g.nodes]} end defp do_stmt(stmt = {atom, _, [kws]}, g) when is_atom(atom) and atom != :-- and is_list(kws) do if Keyword.keyword?(kws) do %{g | nodes: [{atom, kws} | g.nodes]} else raise_invalid_stmt(stmt) end end defp do_stmt({:--, _, [{a, _, nil}, {b, _, nil}]}, g) when is_atom(a) and is_atom(b) do %{g | edges: [{a, b, []} | g.edges]} end defp do_stmt(stmt = {:--, _, [{a, _, nil}, {b, _, [kws]}]}, g) when is_atom(a) and is_atom(b) and is_list(kws) do if Keyword.keyword?(kws) do %{g | edges: [{a, b, kws} | g.edges]} else raise_invalid_stmt(stmt) end end defp do_stmt(stmt, _) do raise_invalid_stmt(stmt) end defp raise_invalid_stmt(stmt) do raise ArgumentError, message: "Invalid statement: #{inspect stmt}" end end
27.106061
77
0.586361
1c034621a3bb47d728042fe5484cc5b3f73d7685
296
ex
Elixir
test/support/auth/test_identity.ex
shuv1824/potionx
a5888413b13a520d8ddf79fb26b7483e441737c3
[ "MIT" ]
31
2021-02-16T20:50:46.000Z
2022-02-03T10:38:07.000Z
test/support/auth/test_identity.ex
shuv1824/potionx
a5888413b13a520d8ddf79fb26b7483e441737c3
[ "MIT" ]
6
2021-04-07T21:50:20.000Z
2022-02-06T21:54:04.000Z
test/support/auth/test_identity.ex
shuv1824/potionx
a5888413b13a520d8ddf79fb26b7483e441737c3
[ "MIT" ]
4
2021-03-25T17:59:44.000Z
2021-04-25T16:28:22.000Z
defmodule PotionxTest.Identity do use Ecto.Schema schema "user_identities" do field :provider, :string field :uid, :string belongs_to :user, PotionxTest.User timestamps() end def changeset(struct, params) do Potionx.Auth.Identity.changeset(struct, params) end end
19.733333
51
0.719595
1c03685156d5e0ef7a32bccca1cc10fb615bdc2b
728
ex
Elixir
lib/panel_tests/panel_border.ex
DwayneDibley/ElixirWxTests
1446a92e6510f31eac2c4d85dfdcf81fdcfd73e4
[ "Apache-2.0" ]
3
2018-10-26T21:12:47.000Z
2020-09-01T02:09:34.000Z
lib/panel_tests/panel_border.ex
DwayneDibley/ElixirWxTests
1446a92e6510f31eac2c4d85dfdcf81fdcfd73e4
[ "Apache-2.0" ]
null
null
null
lib/panel_tests/panel_border.ex
DwayneDibley/ElixirWxTests
1446a92e6510f31eac2c4d85dfdcf81fdcfd73e4
[ "Apache-2.0" ]
null
null
null
defmodule PanelBorders do # import WxFunctions require Logger use WxDefines @moduledoc """ A demo of a simple tool bar. """ def run() do Logger.info("Panel Border Test Starting") Process.spawn(CodeWindow, :run, ["lib/panel_tests/panel_border_window.ex"], []) PanelBorderWindow.createWindow(show: true) # We break out of the loop when the exit button is pressed. Logger.info("Panel Border Test Exiting") {:ok, self()} end def commandButton(PanelBorderWindow, :command_menu_selected, button, _senderObj) do Logger.debug(":command_menu_selected = #{inspect(button)}") # WxMessageDialogTest.run() WxStatusBar.setText("Tool Bar Button clicked: #{inspect(button)}") end end
28
85
0.707418
1c03a919cd592f59a7781723570ee8c5e0e844de
3,652
ex
Elixir
app/lib/registration_api.ex
kljensen/yale-class-chat
b03e72deed967249a64404bff68b1cf22e7e1e6a
[ "Unlicense" ]
1
2020-02-10T21:35:17.000Z
2020-02-10T21:35:17.000Z
app/lib/registration_api.ex
kljensen/yale-class-chat
b03e72deed967249a64404bff68b1cf22e7e1e6a
[ "Unlicense" ]
86
2020-01-24T14:53:27.000Z
2021-05-18T19:16:30.000Z
app/lib/registration_api.ex
kljensen/yale-class-chat
b03e72deed967249a64404bff68b1cf22e7e1e6a
[ "Unlicense" ]
null
null
null
defmodule RegistrationAPI do @moduledoc """ Functions for interacting with the Registration API provided by Yale SOM """ use Tesla plug Tesla.Middleware.BaseUrl, params.url plug Tesla.Middleware.BasicAuth, username: params.username, password: params.password plug Tesla.Middleware.JSON defp params do Map.new(Application.get_env(:app, RegistrationAPI)) end @doc """ Returns the list of users. ## Examples iex> list_users() [%User{}, ...] """ def get_registered_students(crn, term_code) do {:ok, %Tesla.Env{:body => body}} = get("", query: ["CRN": crn, "TermCode": term_code]) output = case body do "" -> {:error, "Invalid parameters for course registration API; please add users manually"} body -> students = body["Course"]["roster"]["student"] initial_list = [] result_list = Enum.reduce students, initial_list, fn student, acc -> net_id = student["netid"] email = student["email"] display_name = student["fullname"] List.insert_at(acc, -1, %{net_id: net_id, email: email, display_name: display_name}) end {:ok, result_list} end output end def get_registered_student_user_ids(crn, term_code, update_existing \\ true) do {:ok, %Tesla.Env{:body => body}} = get("", query: ["CRN": crn, "TermCode": term_code]) output = case body do "" -> {:error, "Invalid parameters for course registration API; please add users manually"} body -> students = body["Course"]["roster"]["student"] initial_list = [] result_list = Enum.reduce students, initial_list, fn student, acc -> net_id = student["netid"] email = student["email"] display_name = student["fullname"] {:ok, user} = case update_existing do false -> App.Accounts.create_user_on_login(net_id) true -> App.Accounts.create_or_update_user(%{net_id: net_id, email: email, display_name: display_name}) end List.insert_at(acc, -1, %{id: user.id}) end {:ok, result_list} end output end def get_registered_student_user_netids(crn, term_code, update_existing \\ true) do {:ok, %Tesla.Env{:body => body}} = get("", query: ["CRN": crn, "TermCode": term_code]) output = case body do "" -> {:error, "Invalid parameters for course registration API; please add users manually"} body -> students = body["Course"]["roster"]["student"] initial_list = [] result_list = Enum.reduce students, initial_list, fn student, acc -> net_id = student["netid"] email = student["email"] display_name = student["fullname"] {:ok, user} = case update_existing do false -> App.Accounts.create_user_on_login(net_id) true -> App.Accounts.create_or_update_user(%{net_id: net_id, email: email, display_name: display_name}) end List.insert_at(acc, -1, user.net_id) end {:ok, result_list} end output end end
33.814815
127
0.523823
1c03c2193c7a6b80bfd19b6275189f3601b95605
1,058
ex
Elixir
deb/prerm.ex
DynomiteDB/docker-build-redis
93167dab6d6b7c3cbc4d4fc8d1c0faa646485ba8
[ "Apache-2.0" ]
3
2016-04-18T05:38:07.000Z
2021-12-31T08:15:07.000Z
deb/prerm.ex
DynomiteDB/docker-build-redis
93167dab6d6b7c3cbc4d4fc8d1c0faa646485ba8
[ "Apache-2.0" ]
null
null
null
deb/prerm.ex
DynomiteDB/docker-build-redis
93167dab6d6b7c3cbc4d4fc8d1c0faa646485ba8
[ "Apache-2.0" ]
2
2016-05-01T03:25:32.000Z
2021-12-31T08:14:55.000Z
#!/bin/sh # prerm script for dynomite # # see: dh_installdeb(1) set -e # summary of how this script can be called: # * <prerm> `remove' # * <old-prerm> `upgrade' <new-version> # * <new-prerm> `failed-upgrade' <old-version> # * <conflictor's-prerm> `remove' `in-favour' <package> <new-version> # * <deconfigured's-prerm> `deconfigure' `in-favour' # <package-being-installed> <version> `removing' # <conflicting-package> <version> # for details, see http://www.debian.org/doc/debian-policy/ or # the debian-policy package case "$1" in remove|upgrade|deconfigure) if which service >/dev/null 2>&1; then if service dynomitedb-redis status >/dev/null 2>&1; then service dynomitedb-redis stop fi elif which invoke-rc.d >/dev/null 2>&1; then invoke-rc.d dynomitedb-redis stop else /etc/init.d/dynomitedb-redis stop fi ;; failed-upgrade) ;; *) echo "prerm called with unknown argument \`$1'" >&2 exit 1 ;; esac exit 0
24.045455
76
0.609641
1c03da1eadc4abb2d0510cdb204ed964cd552813
3,772
ex
Elixir
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/status.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/status.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/status.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudResourceManager.V1.Model.Status do @moduledoc """ The &#x60;Status&#x60; type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The &#x60;Status&#x60; message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package &#x60;google.rpc&#x60; that can be used for common error conditions. # Language mapping The &#x60;Status&#x60; message is the logical representation of the error model, but it is not necessarily the actual wire format. When the &#x60;Status&#x60; message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the &#x60;Status&#x60; message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the &#x60;Status&#x60; in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a &#x60;Status&#x60; message for error reporting. - Batch operations. If a client uses batch request and batch response, the &#x60;Status&#x60; message should be used directly inside batch response, one for each error sub-response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the &#x60;Status&#x60; message. - Logging. If some API errors are stored in logs, the message &#x60;Status&#x60; could be used directly after any stripping needed for security/privacy reasons. """ @derive [Poison.Encoder] defstruct [ :"code", :"details", :"message" ] end defimpl Poison.Decoder, for: GoogleApi.CloudResourceManager.V1.Model.Status do import GoogleApi.CloudResourceManager.V1.Deserializer def decode(value, options) do value |> deserialize(:"details", :list, GoogleApi.CloudResourceManager.V1.Model.Object, options) end end
92
2,549
0.766702
1c03f0d08a495e005508b46906ca32655d0035cb
6,573
exs
Elixir
test/phoenix/controller_test.exs
Havvy/phoenix
37c4053bba75beca5dabf7c1b8cb71cd7e371674
[ "MIT" ]
null
null
null
test/phoenix/controller_test.exs
Havvy/phoenix
37c4053bba75beca5dabf7c1b8cb71cd7e371674
[ "MIT" ]
null
null
null
test/phoenix/controller_test.exs
Havvy/phoenix
37c4053bba75beca5dabf7c1b8cb71cd7e371674
[ "MIT" ]
null
null
null
defmodule Phoenix.ControllerTest do use ExUnit.Case, async: true use ConnHelper import Phoenix.Controller alias Plug.Conn defp get_resp_content_type(conn) do [header] = get_resp_header(conn, "content-type") header |> String.split(";") |> Enum.fetch!(0) end test "action_name/1" do conn = Conn.put_private(%Conn{}, :phoenix_action, :show) assert action_name(conn) == :show end test "controller_module/1" do conn = Conn.put_private(%Conn{}, :phoenix_controller, Hello) assert controller_module(conn) == Hello end test "router_module/1" do conn = Conn.put_private(%Conn{}, :phoenix_router, Hello) assert router_module(conn) == Hello end test "put_layout_formats/2 and layout_formats/1" do conn = conn(:get, "/") assert layout_formats(conn) == ~w(html) conn = put_layout_formats conn, ~w(json xml) assert layout_formats(conn) == ~w(json xml) end test "put_layout/2 and layout/1" do conn = conn(:get, "/") assert layout(conn) == false conn = put_layout conn, {AppView, "application.html"} assert layout(conn) == {AppView, "application.html"} conn = put_layout conn, "print.html" assert layout(conn) == {AppView, "print.html"} conn = put_layout conn, :print assert layout(conn) == {AppView, :print} conn = put_layout conn, false assert layout(conn) == false assert_raise RuntimeError, fn -> put_layout conn, "print" end end test "json/2" do conn = json(conn(:get, "/"), %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "json/2 allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = json(conn, %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert conn.status == 400 end test "text/2" do conn = text(conn(:get, "/"), "foobar") assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/plain" refute conn.halted conn = text(conn(:get, "/"), :foobar) assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/plain" refute conn.halted end test "text/2 allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = text(conn, :foobar) assert conn.resp_body == "foobar" assert conn.status == 400 end test "html/2" do conn = html(conn(:get, "/"), "foobar") assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/html" refute conn.halted end test "html/2 allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = html(conn, "foobar") assert conn.resp_body == "foobar" assert conn.status == 400 end test "redirect/2 with :to" do conn = redirect(conn(:get, "/"), to: "/foobar") assert conn.resp_body =~ "/foobar" assert get_resp_content_type(conn) == "text/html" assert get_resp_header(conn, "Location") == ["/foobar"] refute conn.halted conn = redirect(conn(:get, "/"), to: "/<foobar>") assert conn.resp_body =~ "/&lt;foobar&gt;" assert_raise ArgumentError, ~r/the :to option in redirect expects a path/, fn -> redirect(conn(:get, "/"), to: "http://example.com") end end test "redirect/2 with :external" do conn = redirect(conn(:get, "/"), external: "http://example.com") assert conn.resp_body =~ "http://example.com" assert get_resp_header(conn, "Location") == ["http://example.com"] refute conn.halted end defp with_accept(header) do conn(:get, "/", [], headers: [{"accept", header}]) end test "accepts/2 uses params[:format] when available" do conn = accepts conn(:get, "/", format: "json"), ~w(json) assert conn.params["format"] == "json" exception = assert_raise Phoenix.NotAcceptableError, ~r/unknown format "json"/, fn -> accepts conn(:get, "/", format: "json"), ~w(html) end assert Plug.Exception.status(exception) == 406 end test "accepts/2 uses first accepts on empty or catch-all header" do conn = accepts conn(:get, "/", []), ~w(json) assert conn.params["format"] == "json" conn = accepts with_accept("*/*"), ~w(json) assert conn.params["format"] == "json" end test "accepts/2 on non-empty */*" do # Fallbacks to HTML due to browsers behavior conn = accepts with_accept("application/json, */*"), ~w(html json) assert conn.params["format"] == "html" conn = accepts with_accept("*/*, application/json"), ~w(html json) assert conn.params["format"] == "html" # No HTML is treated normally conn = accepts with_accept("*/*, text/plain, application/json"), ~w(json text) assert conn.params["format"] == "json" conn = accepts with_accept("text/plain, application/json, */*"), ~w(json text) assert conn.params["format"] == "text" end test "accepts/2 ignores invalid media types" do conn = accepts with_accept("foo/bar, bar baz, application/json"), ~w(html json) assert conn.params["format"] == "json" end test "accepts/2 considers q params" do conn = accepts with_accept("text/html; q=0.7, application/json"), ~w(html json) assert conn.params["format"] == "json" conn = accepts with_accept("application/json, text/html; q=0.7"), ~w(html json) assert conn.params["format"] == "json" conn = accepts with_accept("application/json; q=1.0, text/html; q=0.7"), ~w(html json) assert conn.params["format"] == "json" conn = accepts with_accept("application/json; q=0.8, text/html; q=0.7"), ~w(html json) assert conn.params["format"] == "json" conn = accepts with_accept("text/html; q=0.7, application/json; q=0.8"), ~w(html json) assert conn.params["format"] == "json" assert_raise Phoenix.NotAcceptableError, ~r/no supported media type in accept/, fn -> accepts with_accept("text/html; q=0.7, application/json; q=0.8"), ~w(xml) end end test "__view__ returns the view modoule based on controller module" do assert Phoenix.Controller.__view__(MyApp.UserController) == MyApp.UserView assert Phoenix.Controller.__view__(MyApp.Admin.UserController) == MyApp.Admin.UserView end test "__layout__ returns the layout modoule based on controller module" do assert Phoenix.Controller.__layout__(MyApp.UserController) == MyApp.LayoutView assert Phoenix.Controller.__layout__(MyApp.Admin.UserController) == MyApp.LayoutView end end
32.701493
90
0.649779
1c03f152eed80123236b01a47ddb215d8a491c66
111
exs
Elixir
test/rediscl_test.exs
yusuf-demir/elixir-rediscl
94add4947502399f21b82dab7921d7acd6e22188
[ "MIT" ]
14
2018-07-21T14:09:25.000Z
2021-08-28T14:10:46.000Z
test/rediscl_test.exs
yusuf-demir/elixir-rediscl
94add4947502399f21b82dab7921d7acd6e22188
[ "MIT" ]
2
2018-07-29T16:04:24.000Z
2021-08-28T14:11:55.000Z
test/rediscl_test.exs
yusuf-demir/elixir-rediscl
94add4947502399f21b82dab7921d7acd6e22188
[ "MIT" ]
3
2019-02-17T18:56:25.000Z
2021-08-28T13:47:02.000Z
defmodule RedisclTest do use ExUnit.Case doctest Rediscl test "start tests" do assert :ok end end
12.333333
24
0.711712
1c0427e304691859c23ee90cbac9d770cfe5ea36
108
exs
Elixir
.formatter.exs
scorsi/Umbra
16036742db98e39fdc5bf50bc63f6db7cb0e7e92
[ "MIT" ]
null
null
null
.formatter.exs
scorsi/Umbra
16036742db98e39fdc5bf50bc63f6db7cb0e7e92
[ "MIT" ]
7
2020-06-07T08:26:09.000Z
2020-06-07T08:38:36.000Z
.formatter.exs
scorsi/Umbra
16036742db98e39fdc5bf50bc63f6db7cb0e7e92
[ "MIT" ]
null
null
null
# Used by "mix format" [ inputs: ["{mix,.formatter,.committee}.exs", "{config,lib,test}/**/*.{ex,exs}"] ]
21.6
80
0.583333
1c0430e9009467a3a1aefb1d2d77ab3ed00f61f0
1,518
exs
Elixir
mix.exs
jschomay/remote-file-streamer
d029c99b8cd116f00ad81a7bbb2ba80353fbad1b
[ "MIT" ]
null
null
null
mix.exs
jschomay/remote-file-streamer
d029c99b8cd116f00ad81a7bbb2ba80353fbad1b
[ "MIT" ]
null
null
null
mix.exs
jschomay/remote-file-streamer
d029c99b8cd116f00ad81a7bbb2ba80353fbad1b
[ "MIT" ]
null
null
null
defmodule RemoteFileStreamer.MixProject do use Mix.Project @version "1.0.0" @project_url "https://github.com/civilcode/remote-file-streamer" def project do [ app: :remote_file_streamer, version: @version, elixir: "~> 1.6", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, deps: deps(), description: description(), package: package() ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help compile.app" to learn about applications. def application() do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps() do [ {:httpoison, "~> 1.0"}, {:cowboy, "~> 2.4", only: :test}, {:mix_test_watch, "~> 0.6", only: :dev, runtime: false}, {:ex_doc, ">= 0.0.0", only: :dev} ] end defp package() do [ maintainers: ["Nicolas Charlery"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/civilcode/remote-file-streamer", "Civilcode Labs" => "http://labs.civilcode.io" }, source_url: @project_url, homepage_url: @project_url ] end defp description() do """ RemoteFileStreamer is a micro-library to stream a remote file. It's similar to File.stream! but takes an url as input and returns a stream to consume. """ end end
24.885246
91
0.604084
1c04420caaf5b0bdd76c1db27fa21af4f01b0f8e
1,349
ex
Elixir
lib/songmate_web/endpoint.ex
jimytc/music-dating-app
ec46ef2ffa4fb263a8b283a96495b0643467697c
[ "MIT" ]
null
null
null
lib/songmate_web/endpoint.ex
jimytc/music-dating-app
ec46ef2ffa4fb263a8b283a96495b0643467697c
[ "MIT" ]
null
null
null
lib/songmate_web/endpoint.ex
jimytc/music-dating-app
ec46ef2ffa4fb263a8b283a96495b0643467697c
[ "MIT" ]
null
null
null
defmodule SongmateWeb.Endpoint do use Phoenix.Endpoint, otp_app: :songmate # 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: "_songmate_key", signing_salt: "0sBDz1sT" ] socket "/socket", SongmateWeb.UserSocket, websocket: true, longpoll: false # 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: :songmate, 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 end 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 SongmateWeb.Router end
28.104167
69
0.71238
1c044e7652d805dabcad7fbe39ce4cd4e70ccb1b
791
ex
Elixir
lib/vector/payment.ex
o7/bud
36ff93bdaab648044190cf56a6b078664f5c84c2
[ "0BSD" ]
3
2019-06-19T14:00:28.000Z
2019-06-20T23:26:06.000Z
lib/vector/payment.ex
o7/bud
36ff93bdaab648044190cf56a6b078664f5c84c2
[ "0BSD" ]
null
null
null
lib/vector/payment.ex
o7/bud
36ff93bdaab648044190cf56a6b078664f5c84c2
[ "0BSD" ]
null
null
null
defmodule PLM.Rows.Payment do use N2O, with: [:n2o, :kvs, :nitro] use FORM, with: [:form] use BPE require Record require ERP require Logger def doc(), do: "This is the actor trace row (step) representation. " <> "Used to draw trace of the processes" def id(), do: ERP."Payment"() def new(name, ERP."Payment"(invoice: id, price: {_, price}, volume: {_, volume}, from: tic)) do panel( id: FORM.atom([:tr, NITRO.to_list(name)]), class: :td, body: [ panel( class: :column66, body: id ), panel( class: :column10, body: :erlang.integer_to_list(price * volume) ), panel( class: :column10, body: "NYNJA" ) ] ) end end
21.378378
97
0.523388
1c045b5aeb39d7e48adb6db274b2e59f1180c94a
736
ex
Elixir
lib/mix/tasks/floating_ip.reassign.ex
capbash/dioex
4aca1c01fd05917d41a98df4d0f0dab2347f28e8
[ "MIT" ]
5
2017-08-06T09:22:35.000Z
2017-10-22T15:51:45.000Z
lib/mix/tasks/floating_ip.reassign.ex
capbash/doex
4aca1c01fd05917d41a98df4d0f0dab2347f28e8
[ "MIT" ]
null
null
null
lib/mix/tasks/floating_ip.reassign.ex
capbash/doex
4aca1c01fd05917d41a98df4d0f0dab2347f28e8
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Doex.FloatingIp.Reassign do use Mix.Task use FnExpr @shortdoc "Reassign a floating IP from one droplet to another." @moduledoc """ Reassign a floating IP from one droplet to another: doex floating_ip.reassign <old_droplet_name> <new_droplet_name> Or, by tag: doex floating_ip.id <old_droplet_tag> <new_droplet_tag> --tag If by tag, it will grab the `latest`. For example: doex floating_ip.reassign myapp01 myapp02 If you have a specific config file, `mix help doex.config` then add it as an environment variable: DOEX_CONFIG=/tmp/my.doex doex floating_ip.reassign myapp01 myapp02 """ def run(args), do: Doex.Cli.Main.run({:floating_ip_reassign, args}) end
23.741935
78
0.724185
1c04616d02f093bb46d323d4ae0d93a314c5811c
1,188
ex
Elixir
apps/plant_monitor_web/lib/plant_monitor_web/channels/user_socket.ex
bartoszgorka/PlantMonitor
23e18cd76c51bd8eee021ee98668926de885047b
[ "MIT" ]
2
2019-01-25T21:21:56.000Z
2021-02-24T08:18:51.000Z
apps/plant_monitor_web/lib/plant_monitor_web/channels/user_socket.ex
bartoszgorka/PlantMonitor
23e18cd76c51bd8eee021ee98668926de885047b
[ "MIT" ]
null
null
null
apps/plant_monitor_web/lib/plant_monitor_web/channels/user_socket.ex
bartoszgorka/PlantMonitor
23e18cd76c51bd8eee021ee98668926de885047b
[ "MIT" ]
null
null
null
defmodule PlantMonitorWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", PlantMonitorWeb.RoomChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket # transport :longpoll, Phoenix.Transports.LongPoll # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. def connect(_params, socket) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # PlantMonitorWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. def id(_socket), do: nil end
31.263158
87
0.707071
1c04ab830ec8781cb1726ece652cfaa4ce6689d7
834
ex
Elixir
tutorials/plug/plug_example/lib/plug_example/application.ex
idfumg/ElixirSynopsis
74c668d84300812dd41eb18772aecfb89bc7628b
[ "MIT" ]
null
null
null
tutorials/plug/plug_example/lib/plug_example/application.ex
idfumg/ElixirSynopsis
74c668d84300812dd41eb18772aecfb89bc7628b
[ "MIT" ]
null
null
null
tutorials/plug/plug_example/lib/plug_example/application.ex
idfumg/ElixirSynopsis
74c668d84300812dd41eb18772aecfb89bc7628b
[ "MIT" ]
null
null
null
defmodule PlugExample.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application require Logger def start(_type, _args) do # List all child processes to be supervised children = [ # Starts a worker by calling: PlugExample.Worker.start_link(arg) # {PlugExample.Worker, arg} {Plug.Cowboy, scheme: :http, plug: PlugExample.Router, options: [port: cowboy_port()]}, ] Logger.info("Starting application...") # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: PlugExample.Supervisor] Supervisor.start_link(children, opts) end defp cowboy_port(), do: Application.get_env(:plug_example, :cowboy_port, 8080) end
30.888889
93
0.714628
1c04ec2f8bfca0b5410645887dfd98d89bc95afb
126
exs
Elixir
test/elixir_concurrency_code_test.exs
miguelcoba/elixir-concurrency-code
d68fa9c532dc4aebb8800ae2c48504e2d188b0fa
[ "MIT" ]
2
2016-01-23T23:34:44.000Z
2016-06-10T22:16:17.000Z
test/elixir_concurrency_code_test.exs
miguelcoba/elixir-concurrency-code
d68fa9c532dc4aebb8800ae2c48504e2d188b0fa
[ "MIT" ]
null
null
null
test/elixir_concurrency_code_test.exs
miguelcoba/elixir-concurrency-code
d68fa9c532dc4aebb8800ae2c48504e2d188b0fa
[ "MIT" ]
null
null
null
defmodule ElixirMeetupTest do use ExUnit.Case doctest ElixirMeetup test "the truth" do assert 1 + 1 == 2 end end
14
29
0.698413
1c050227f809b776dc919e939dea4347ae534f70
181
exs
Elixir
config/releases.exs
fika-lang/fika
15bffc30daed744670bb2c0fba3e674055adac47
[ "Apache-2.0" ]
220
2020-09-12T18:16:29.000Z
2022-03-15T14:39:05.000Z
config/releases.exs
fika-lang/fika
15bffc30daed744670bb2c0fba3e674055adac47
[ "Apache-2.0" ]
60
2020-09-23T14:20:36.000Z
2021-03-08T08:55:57.000Z
config/releases.exs
fika-lang/fika
15bffc30daed744670bb2c0fba3e674055adac47
[ "Apache-2.0" ]
25
2020-09-19T09:06:10.000Z
2021-08-24T23:48:39.000Z
import Config config :fika, start_cli: true, router_path: "router.fi", dev_token: System.get_env("FIKA_DEV_TOKEN"), remote_endpoint: System.get_env("FIKA_REMOTE_ENDPOINT")
22.625
57
0.762431
1c051b50ad7597a3fd4e407b4c83032066ff9956
7,553
ex
Elixir
lib/oban/queue/executor.ex
fedeotaran/oban
60274b76ff2c59d660ae1bf7721a3ff14854700b
[ "Apache-2.0" ]
2,219
2019-04-10T01:50:19.000Z
2022-03-30T11:20:01.000Z
lib/oban/queue/executor.ex
fedeotaran/oban
60274b76ff2c59d660ae1bf7721a3ff14854700b
[ "Apache-2.0" ]
532
2019-05-16T00:22:28.000Z
2022-03-31T19:04:02.000Z
lib/oban/queue/executor.ex
fedeotaran/oban
60274b76ff2c59d660ae1bf7721a3ff14854700b
[ "Apache-2.0" ]
230
2019-05-15T14:15:18.000Z
2022-03-23T22:59:43.000Z
defmodule Oban.Queue.Executor do @moduledoc false alias Oban.{ Breaker, Config, CrashError, Job, PerformError, Telemetry, TimeoutError, Worker } alias Oban.Queue.Engine require Logger @type success :: {:success, Job.t()} @type failure :: {:failure, Job.t(), Worker.t(), atom(), term()} @type t :: %__MODULE__{ conf: Config.t(), duration: pos_integer(), job: Job.t(), kind: any(), meta: map(), queue_time: integer(), result: term(), start_mono: integer(), start_time: integer(), stop_mono: integer(), worker: Worker.t(), safe: boolean(), snooze: pos_integer(), stacktrace: Exception.stacktrace(), state: :unset | :discard | :failure | :success | :snoozed } @enforce_keys [:conf, :job] defstruct [ :conf, :error, :job, :meta, :result, :snooze, :start_mono, :start_time, :stop_mono, :worker, safe: true, duration: 0, kind: :error, queue_time: 0, stacktrace: [], state: :unset ] @spec new(Config.t(), Job.t()) :: t() def new(%Config{} = conf, %Job{} = job) do struct!(__MODULE__, conf: conf, job: %{job | conf: conf}, meta: event_metadata(conf, job), start_mono: System.monotonic_time(), start_time: System.system_time() ) end @spec put(t(), :safe, boolean()) :: t() def put(%__MODULE__{} = exec, :safe, value) when is_boolean(value) do %{exec | safe: value} end @spec call(t()) :: :success | :failure def call(%__MODULE__{} = exec) do exec = exec |> record_started() |> resolve_worker() |> perform() |> record_finished() Breaker.with_retry(fn -> report_finished(exec).state end) end def record_started(%__MODULE__{} = exec) do Telemetry.execute( exec.conf.telemetry_prefix ++ [:job, :start], %{system_time: exec.start_time}, exec.meta ) exec end @spec resolve_worker(t()) :: t() def resolve_worker(%__MODULE__{} = exec) do case Worker.from_string(exec.job.worker) do {:ok, worker} -> %{exec | worker: worker} {:error, error} -> unless exec.safe, do: raise(error) %{exec | state: :failure, error: error} end end @spec perform(t()) :: t() def perform(%__MODULE__{state: :unset} = exec) do case exec.worker.timeout(exec.job) do :infinity -> perform_inline(exec, exec.safe) timeout when is_integer(timeout) -> perform_timed(exec, timeout) end end def perform(%__MODULE__{} = exec), do: exec @spec record_finished(t()) :: t() def record_finished(%__MODULE__{} = exec) do stop_mono = System.monotonic_time() duration = stop_mono - exec.start_mono queue_time = DateTime.diff(exec.job.attempted_at, exec.job.scheduled_at, :nanosecond) %{exec | duration: duration, queue_time: queue_time, stop_mono: stop_mono} end @spec report_finished(t()) :: t() def report_finished(%__MODULE__{} = exec) do exec |> ack_event() |> emit_event() end @spec ack_event(t()) :: t() def ack_event(%__MODULE__{state: :success} = exec) do Engine.complete_job(exec.conf, exec.job) exec end def ack_event(%__MODULE__{state: :failure} = exec) do job = job_with_unsaved_error(exec) Engine.error_job(exec.conf, job, backoff(exec.worker, job)) %{exec | job: job} end def ack_event(%__MODULE__{state: :snoozed} = exec) do Engine.snooze_job(exec.conf, exec.job, exec.snooze) exec end def ack_event(%__MODULE__{state: :discard} = exec) do job = job_with_unsaved_error(exec) Engine.discard_job(exec.conf, job) %{exec | job: job} end @spec emit_event(t()) :: t() def emit_event(%__MODULE__{state: :failure} = exec) do measurements = %{duration: exec.duration, queue_time: exec.queue_time} meta = Map.merge(exec.meta, %{ job: exec.job, kind: exec.kind, error: exec.error, reason: exec.error, stacktrace: exec.stacktrace, state: exec.state }) Telemetry.execute(exec.conf.telemetry_prefix ++ [:job, :exception], measurements, meta) exec end def emit_event(%__MODULE__{state: state} = exec) when state in [:success, :snoozed, :discard] do measurements = %{duration: exec.duration, queue_time: exec.queue_time} meta = Map.merge(exec.meta, %{ job: exec.job, state: exec.state, result: exec.result }) Telemetry.execute(exec.conf.telemetry_prefix ++ [:job, :stop], measurements, meta) exec end defp perform_inline(exec, true = _safe) do perform_inline(exec, false) rescue error -> %{exec | state: :failure, error: error, stacktrace: __STACKTRACE__} catch kind, reason -> error = CrashError.exception({kind, reason, __STACKTRACE__}) %{exec | state: :failure, error: error, stacktrace: __STACKTRACE__} end defp perform_inline(%{worker: worker, job: job} = exec, _safe) do case worker.perform(job) do :ok -> %{exec | state: :success, result: :ok} {:ok, _value} = result -> %{exec | state: :success, result: result} :discard = result -> %{ exec | result: result, state: :discard, error: PerformError.exception({worker, :discard}) } {:discard, reason} = result -> %{ exec | result: result, state: :discard, error: PerformError.exception({worker, {:discard, reason}}) } {:error, reason} = result -> %{ exec | result: result, state: :failure, error: PerformError.exception({worker, {:error, reason}}) } {:snooze, seconds} = result when is_integer(seconds) and seconds > 0 -> %{exec | result: result, state: :snoozed, snooze: seconds} returned -> maybe_log_warning(exec, returned) %{exec | state: :success, result: returned} end end defp perform_timed(exec, timeout) do task = Task.async(fn -> perform_inline(exec, exec.safe) end) case Task.yield(task, timeout) || Task.shutdown(task) do {:ok, reply} -> reply nil -> error = TimeoutError.exception({exec.worker, timeout}) %{exec | state: :failure, error: error} end end defp backoff(nil, job), do: Worker.backoff(job) defp backoff(worker, job), do: worker.backoff(job) defp event_metadata(conf, job) do job |> Map.take([:id, :args, :queue, :worker, :attempt, :max_attempts, :tags]) |> Map.merge(%{conf: conf, job: job, prefix: conf.prefix}) end defp job_with_unsaved_error(%__MODULE__{} = exec) do unsaved_error = %{kind: exec.kind, reason: exec.error, stacktrace: exec.stacktrace} %{exec.job | unsaved_error: unsaved_error} end defp maybe_log_warning(exec, returned) defp maybe_log_warning(%__MODULE__{safe: false}, _returned), do: :noop defp maybe_log_warning(%__MODULE__{worker: worker}, returned) do Logger.warn(fn -> """ Expected #{worker}.perform/1 to return: - `:ok` - `:discard` - `{:ok, value}` - `{:error, reason}`, - `{:discard, reason}` - `{:snooze, seconds}` Instead received: #{inspect(returned, pretty: true)} The job will be considered a success. """ end) end end
24.364516
98
0.591288
1c0542ec4974f36ce621ce7c53d83f4c4998ba73
189
ex
Elixir
lib/event_loop/event.ex
cruessler/lafamiglia
084915a2d44a5e69fb6ad9321eac08ced0e3016a
[ "MIT" ]
5
2016-10-20T10:00:59.000Z
2017-11-19T08:14:18.000Z
lib/event_loop/event.ex
cruessler/lafamiglia
084915a2d44a5e69fb6ad9321eac08ced0e3016a
[ "MIT" ]
39
2020-04-22T05:27:32.000Z
2022-03-13T17:22:26.000Z
lib/event_loop/event.ex
cruessler/lafamiglia
084915a2d44a5e69fb6ad9321eac08ced0e3016a
[ "MIT" ]
null
null
null
defprotocol LaFamiglia.Event do @fallback_to_any false @doc "Returns the time an event is supposed to happen" def happens_at(event) @doc "Handles an event" def handle(event) end
21
56
0.751323
1c0554b252b9d4ded7c712503e766935dbadd7a3
3,182
exs
Elixir
mix.exs
studzien/wallaby
263f37054d544293e52b751316a5699af54f238f
[ "MIT" ]
null
null
null
mix.exs
studzien/wallaby
263f37054d544293e52b751316a5699af54f238f
[ "MIT" ]
null
null
null
mix.exs
studzien/wallaby
263f37054d544293e52b751316a5699af54f238f
[ "MIT" ]
null
null
null
defmodule Wallaby.Mixfile do use Mix.Project @version "0.21.0" @drivers ~w(phantom selenium chrome) @selected_driver System.get_env("WALLABY_DRIVER") @maintainers [ "Chris Keathley", "Tobias Pfeiffer", "Aaron Renner", ] def project do [app: :wallaby, version: @version, elixir: "~> 1.3", elixirc_paths: elixirc_paths(Mix.env), build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, package: package(), description: "Concurrent feature tests for elixir", deps: deps(), docs: docs(), # Custom testing aliases: ["test.all": ["test", "test.drivers"], "test.drivers": &test_drivers/1], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test, "coveralls.travis": :test, "coveralls.safe_travis": :test, "test.all": :test, "test.drivers": :test], test_coverage: [tool: ExCoveralls], test_paths: test_paths(@selected_driver), dialyzer: [plt_add_apps: [:inets], ignore_warnings: "dialyzer.ignore_warnings"]] end def application do [applications: [:logger, :httpoison, :poolboy, :poison], mod: {Wallaby, []}] end defp elixirc_paths(:test), do: ["lib", "test/support"] # need the testserver in dev for benchmarks to run defp elixirc_paths(:dev), do: ["lib", "integration_test/support/test_server.ex"] defp elixirc_paths(_), do: ["lib"] defp deps do [ {:httpoison, "~> 0.12 or ~> 1.0"}, {:poison, ">= 1.4.0"}, {:poolboy, "~> 1.5"}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false}, {:earmark, "~> 1.2", only: :dev}, {:ex_doc, "~> 0.16", only: :dev}, {:benchee, "~> 0.9", only: :dev}, {:benchee_html, "~> 0.3", only: :dev}, {:bypass, "~> 0.8", only: :test}, {:inch_ex, "~> 0.5", only: [:docs]}, {:excoveralls, "~> 0.7", only: :test}, {:credo, "~> 0.9", only: [:dev, :test], runtime: false}, ] end defp package do [ files: ["lib", "mix.exs", "README.md", "LICENSE.md", "priv"], maintainers: @maintainers, licenses: ["MIT"], links: %{"Github" => "https://github.com/keathley/wallaby"} ] end defp docs do [ extras: ["README.md"], source_ref: "v#{@version}", source_url: "https://github.com/keathley/wallaby", main: "readme", logo: "guides/images/icon.png", ] end defp test_paths(driver) when driver in @drivers, do: ["integration_test/#{driver}"] defp test_paths(_), do: ["test"] defp test_drivers(args) do for driver <- @drivers, do: run_integration_test(driver, args) end defp run_integration_test(driver, args) do args = if IO.ANSI.enabled?, do: ["--color" | args], else: ["--no-color" | args] IO.puts "==> Running tests for WALLABY_DRIVER=#{driver} mix test" {_, res} = System.cmd "mix", ["test" | args], into: IO.binstream(:stdio, :line), env: [{"WALLABY_DRIVER", driver}] if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end end
29.738318
85
0.571653
1c055b4aaeb5f33b6342263fe6a884c1a522844a
331
ex
Elixir
2021-09-15-elixir-australia-prom-ex/prom_ex_demo/lib/prom_ex_demo/todo/todu.ex
rellen/talks
97e123e6cb331b78fa737c90cedc2974a35243e4
[ "CC-BY-4.0" ]
1
2022-02-16T09:00:34.000Z
2022-02-16T09:00:34.000Z
2021-09-15-elixir-australia-prom-ex/prom_ex_demo/lib/prom_ex_demo/todo/todu.ex
rellen/talks
97e123e6cb331b78fa737c90cedc2974a35243e4
[ "CC-BY-4.0" ]
null
null
null
2021-09-15-elixir-australia-prom-ex/prom_ex_demo/lib/prom_ex_demo/todo/todu.ex
rellen/talks
97e123e6cb331b78fa737c90cedc2974a35243e4
[ "CC-BY-4.0" ]
null
null
null
defmodule PromExDemo.Todo.Todu do use Ecto.Schema import Ecto.Changeset schema "todu" do field :done, :boolean, default: false field :title, :string timestamps() end @doc false def changeset(todu, attrs) do todu |> cast(attrs, [:title, :done]) |> validate_required([:title, :done]) end end
17.421053
41
0.649547
1c0570702ec5a825023976d1d01c85003a8afefb
459
ex
Elixir
lib/console/watchers/handlers/upgrade.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
6
2021-11-17T21:10:49.000Z
2022-02-16T19:45:28.000Z
lib/console/watchers/handlers/upgrade.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
18
2021-11-25T04:31:06.000Z
2022-03-27T04:54:00.000Z
lib/console/watchers/handlers/upgrade.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
null
null
null
defmodule Console.Watchers.Handlers.Upgrade do alias Console.Services.{Builds, Users, Policies} def create_build(%{"message" => msg, "repository" => %{"name" => name}} = upgr) do bot = Users.get_bot!("console") with {:ok, type} when type != :ignore <- {:ok, Policies.upgrade_type(name, upgr["type"])}, {:error, :invalid_repository} <- Builds.create(%{message: msg, repository: name, type: type}, bot), do: {:ok, :ignore} end end
41.727273
108
0.642702
1c058230c7fc2d3e362e197b4d6fd8399bedf930
1,576
ex
Elixir
priv/cabbage/apps/itest/lib/gas.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
4
2020-10-31T15:16:16.000Z
2021-02-06T22:44:19.000Z
priv/cabbage/apps/itest/lib/gas.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
4
2020-11-02T17:12:09.000Z
2021-02-10T20:35:19.000Z
priv/cabbage/apps/itest/lib/gas.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2020 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule Itest.Gas do @moduledoc """ Functions to pull gas charges from the transaction hash """ require Logger @doc """ Nil for when exit queue hash is nil (because it's already added) """ def get_gas_used(nil), do: 0 def get_gas_used(receipt_hash) do result = {Ethereumex.HttpClient.eth_get_transaction_receipt(receipt_hash), Ethereumex.HttpClient.eth_get_transaction_by_hash(receipt_hash)} case result do {{:ok, %{"gasUsed" => gas_used}}, {:ok, %{"gasPrice" => gas_price}}} -> {gas_price_value, ""} = gas_price |> String.replace_prefix("0x", "") |> Integer.parse(16) {gas_used_value, ""} = gas_used |> String.replace_prefix("0x", "") |> Integer.parse(16) gas_price_value * gas_used_value {{:ok, nil}, {:ok, nil}} -> 0 # reorg {{:ok, nil}, {:ok, %{"blockHash" => nil, "blockNumber" => nil}}} -> Logger.info("transaction #{receipt_hash} is in reorg") 0 end end end
33.531915
97
0.670685
1c059f6a5167ce8f839b5fcc502ccaf60563bc60
1,111
ex
Elixir
lib/midifile/sequence.ex
lucidstack/elixir-midifile
7eac20c6da3b84804987a5ec0eb3c6f40bce3a8c
[ "Apache-2.0" ]
7
2016-10-09T06:59:31.000Z
2022-02-09T22:23:09.000Z
lib/midifile/sequence.ex
lucidstack/elixir-midifile
7eac20c6da3b84804987a5ec0eb3c6f40bce3a8c
[ "Apache-2.0" ]
null
null
null
lib/midifile/sequence.ex
lucidstack/elixir-midifile
7eac20c6da3b84804987a5ec0eb3c6f40bce3a8c
[ "Apache-2.0" ]
5
2016-01-06T17:37:04.000Z
2022-02-09T22:23:24.000Z
defmodule Midifile.Sequence do @default_bpm 120 use Bitwise defstruct format: 1, division: 480, conductor_track: nil, tracks: [] def name(%Midifile.Sequence{conductor_track: nil}), do: "" def name(%Midifile.Sequence{conductor_track: %Midifile.Track{events: []}}), do: "" def name(%Midifile.Sequence{conductor_track: %Midifile.Track{events: list}}) do Enum.find(list, %Midifile.Event{}, &(&1.symbol == :seq_name)).bytes end def bpm(%Midifile.Sequence{conductor_track: nil}), do: @default_bpm def bpm(%Midifile.Sequence{conductor_track: %Midifile.Track{events: []}}), do: "" def bpm(%Midifile.Sequence{conductor_track: %Midifile.Track{events: list}}) do tempo_event = Enum.find(list, %Midifile.Event{}, &(&1.symbol == :tempo)) if tempo_event do microsecs_per_beat = hd(tempo_event.bytes) trunc(60_000_000 / microsecs_per_beat) else @default_bpm end end def ppqn(seq) do <<0::size(1), ppqn::size(15)>> = <<seq.division::size(16)>> ppqn end # TODO: handle SMPTE (first bit 1, -frame/sec (7 bits), ticks/frame (8 bits)) end
31.742857
85
0.673267
1c05b6fdfb16deb4f7da5e9749441e83d38db00c
474
exs
Elixir
test/models/exclusion_rule_test.exs
marick/elixir-critter4us
eeea901c1debf6c77969d80a55320daf909df053
[ "MIT" ]
null
null
null
test/models/exclusion_rule_test.exs
marick/elixir-critter4us
eeea901c1debf6c77969d80a55320daf909df053
[ "MIT" ]
null
null
null
test/models/exclusion_rule_test.exs
marick/elixir-critter4us
eeea901c1debf6c77969d80a55320daf909df053
[ "MIT" ]
null
null
null
defmodule Critter4us.ExclusionRuleTest do use Critter4us.ModelCase alias Critter4us.ExclusionRule @valid_attrs %{rule: "some content"} @invalid_attrs %{} test "changeset with valid attributes" do changeset = ExclusionRule.changeset(%ExclusionRule{}, @valid_attrs) assert changeset.valid? end test "changeset with invalid attributes" do changeset = ExclusionRule.changeset(%ExclusionRule{}, @invalid_attrs) refute changeset.valid? end end
24.947368
73
0.755274
1c05c2a5e52741a6c058efcc948ddbeab8acbe95
86
exs
Elixir
test/ephemeral2_web/views/page_view_test.exs
losvedir/ephemeral2
4d48d6b7724127efc4f416ec45c4c2cb28472fc3
[ "MIT" ]
864
2015-05-12T13:00:28.000Z
2022-02-03T20:17:12.000Z
test/ephemeral2_web/views/page_view_test.exs
losvedir/ephemeral2
4d48d6b7724127efc4f416ec45c4c2cb28472fc3
[ "MIT" ]
4
2015-05-13T22:07:17.000Z
2015-07-10T17:03:31.000Z
test/ephemeral2_web/views/page_view_test.exs
losvedir/ephemeral2
4d48d6b7724127efc4f416ec45c4c2cb28472fc3
[ "MIT" ]
71
2015-05-12T13:30:05.000Z
2021-10-01T03:37:40.000Z
defmodule Ephemeral2Web.PageViewTest do use Ephemeral2Web.ConnCase, async: true end
21.5
41
0.837209
1c05e1ac8917509aba88089caead4622cfc5cc8b
688
ex
Elixir
lib/findmeajob/parsers/remote_jobs.ex
Adsidera/findmeajob
5a2df0267bd29b7fd55441f7dd1de21dcd4c13ea
[ "MIT" ]
1
2021-07-31T16:28:53.000Z
2021-07-31T16:28:53.000Z
lib/findmeajob/parsers/remote_jobs.ex
Adsidera/findmeajob
5a2df0267bd29b7fd55441f7dd1de21dcd4c13ea
[ "MIT" ]
null
null
null
lib/findmeajob/parsers/remote_jobs.ex
Adsidera/findmeajob
5a2df0267bd29b7fd55441f7dd1de21dcd4c13ea
[ "MIT" ]
null
null
null
defmodule Findmeajob.Parsers.RemoteJobs do alias Findmeajob.Parsers.Shared.Extractor def parse(html) do html |> Floki.find("tr.job") |> Enum.map(&parse_job/1) end def parse_job(job) do %{ title: extract_text(job, "h2[itemprop=title]"), company: extract_text(job, "h3[itemprop=name]"), added_on: extract_text(job, "td.time > a") |> Extractor.parse_date(), link: "https://remoteok.io#{extract_attribute(job, "a[itemprop=url]", "href")}" } end def extract_text(job, selector) do Extractor.text(job, selector) end def extract_attribute(job, selector, attribute) do Extractor.attribute(job, selector, attribute) end end
26.461538
85
0.672965
1c05f31ad87d14b987f49e207e0c3a0f5933825a
1,306
exs
Elixir
test/examples/focus_example.exs
MeneDev/espec
ec4b3d579c5192999e930224a8a2650bb1fdf0bc
[ "Apache-2.0" ]
807
2015-03-25T14:00:19.000Z
2022-03-24T08:08:15.000Z
test/examples/focus_example.exs
MeneDev/espec
ec4b3d579c5192999e930224a8a2650bb1fdf0bc
[ "Apache-2.0" ]
254
2015-03-27T10:12:25.000Z
2021-07-12T01:40:15.000Z
test/examples/focus_example.exs
MeneDev/espec
ec4b3d579c5192999e930224a8a2650bb1fdf0bc
[ "Apache-2.0" ]
85
2015-04-02T10:25:19.000Z
2021-01-30T21:30:43.000Z
defmodule PendingExampleTest do use ExUnit.Case, async: true defmodule SomeSpec do use ESpec it do: "Example" it "with focus", [focus: true], do: "focus true" focus("with focus", do: "focus focus") fit("pending with message", do: "focus fit") fexample("pending with message", do: "focus fexample") fspecify("pending with message", do: "focus fspecify") fcontext "focus context" do it do: "focus fcontext" end end setup_all do ESpec.Configuration.add(focus: true) examples = ESpec.SuiteRunner.run_examples(SomeSpec.examples(), true) {:ok, ex1: Enum.at(examples, 0), ex2: Enum.at(examples, 1), ex3: Enum.at(examples, 2), ex4: Enum.at(examples, 3), ex5: Enum.at(examples, 4), ex6: Enum.at(examples, 5)} end test "ex1", context do assert(context[:ex1].result == "focus true") end test "ex2", context do assert(context[:ex2].result == "focus focus") end test "ex3", context do assert(context[:ex3].result == "focus fit") end test "ex4", context do assert(context[:ex4].result == "focus fexample") end test "ex5", context do assert(context[:ex5].result == "focus fspecify") end test "ex6", context do assert(context[:ex6].result == "focus fcontext") end end
22.912281
72
0.634763
1c06091605144ed074a907a1121d98b241ce42f4
201
ex
Elixir
lib/flix_web/graphql/resolvers/review_resolver.ex
conradwt/flix-elixir
e4d6bf6fd79be12fbed6fb6250f78e929247c1a4
[ "MIT" ]
3
2021-03-21T23:52:16.000Z
2021-06-02T03:47:00.000Z
lib/flix_web/graphql/resolvers/review_resolver.ex
conradwt/flix-elixir
e4d6bf6fd79be12fbed6fb6250f78e929247c1a4
[ "MIT" ]
44
2021-04-09T04:04:13.000Z
2022-03-29T06:29:37.000Z
lib/flix_web/graphql/resolvers/review_resolver.ex
conradwt/flix-elixir
e4d6bf6fd79be12fbed6fb6250f78e929247c1a4
[ "MIT" ]
null
null
null
defmodule FlixWeb.Graphql.Resolvers.ReviewResolver do alias Flix.Catalogs def list_reviews(%Flix.Catalogs.Movie{} = movie, _args, _resolution) do {:ok, Catalogs.list_reviews(movie)} end end
25.125
73
0.761194
1c0642e3a14f3bc2a81c6df9106a9fc95dde38f0
48
exs
Elixir
test/exfile_b2_test.exs
keichan34/exfile-b2
4251f5c8fba6b11980d048c5e8bdcf1d4407984d
[ "MIT" ]
8
2016-01-08T09:16:50.000Z
2019-05-10T19:44:29.000Z
test/exfile_b2_test.exs
keichan34/exfile-b2
4251f5c8fba6b11980d048c5e8bdcf1d4407984d
[ "MIT" ]
3
2016-03-28T12:10:10.000Z
2016-08-16T06:03:18.000Z
test/exfile_b2_test.exs
keichan34/exfile-b2
4251f5c8fba6b11980d048c5e8bdcf1d4407984d
[ "MIT" ]
2
2016-07-02T23:35:50.000Z
2019-09-15T14:59:43.000Z
defmodule ExfileB2Test do use ExUnit.Case end
12
25
0.8125
1c06929a954478f9fd8163b00380e96322a5d438
4,990
exs
Elixir
mix.exs
hi-rustin/ecto_sql
a09868467827e0a31c74e42ed57d0b8c97277707
[ "Apache-2.0" ]
null
null
null
mix.exs
hi-rustin/ecto_sql
a09868467827e0a31c74e42ed57d0b8c97277707
[ "Apache-2.0" ]
null
null
null
mix.exs
hi-rustin/ecto_sql
a09868467827e0a31c74e42ed57d0b8c97277707
[ "Apache-2.0" ]
null
null
null
defmodule EctoSQL.MixProject do use Mix.Project @source_url "https://github.com/elixir-ecto/ecto_sql" @version "3.6.2" @adapters ~w(pg myxql tds) def project do [ app: :ecto_sql, version: @version, elixir: "~> 1.8", deps: deps(), test_paths: test_paths(System.get_env("ECTO_ADAPTER")), xref: [ exclude: [ MyXQL, Ecto.Adapters.MyXQL.Connection, Postgrex, Ecto.Adapters.Postgres.Connection, Tds, Tds.Ecto.UUID, Ecto.Adapters.Tds.Connection ] ], # Custom testing aliases: [ "test.all": ["test", "test.adapters", "test.as_a_dep"], "test.adapters": &test_adapters/1, "test.as_a_dep": &test_as_a_dep/1 ], preferred_cli_env: ["test.all": :test, "test.adapters": :test], # Hex description: "SQL-based adapters for Ecto and database migrations", package: package(), # Docs name: "Ecto SQL", docs: docs() ] end def application do [ extra_applications: [:logger, :eex], env: [postgres_map_type: "jsonb"], mod: {Ecto.Adapters.SQL.Application, []} ] end defp deps do [ ecto_dep(), {:telemetry, "~> 0.4.0 or ~> 1.0"}, # Drivers {:db_connection, "~> 2.2"}, postgrex_dep(), myxql_dep(), tds_dep(), # Bring something in for JSON during tests {:jason, ">= 0.0.0", only: [:test, :docs]}, # Docs {:ex_doc, "~> 0.21", only: :docs}, # Benchmarks {:benchee, "~> 0.11.0", only: :bench}, {:benchee_json, "~> 0.4.0", only: :bench} ] end defp ecto_dep do if path = System.get_env("ECTO_PATH") do {:ecto, path: path} else {:ecto, github: "elixir-ecto/ecto"} end end defp postgrex_dep do if path = System.get_env("POSTGREX_PATH") do {:postgrex, path: path} else {:postgrex, "~> 0.15.0 or ~> 1.0", optional: true} end end defp myxql_dep do if path = System.get_env("MYXQL_PATH") do {:myxql, path: path} else {:myxql, "~> 0.4.0 or ~> 0.5.0", optional: true} end end defp tds_dep do if path = System.get_env("TDS_PATH") do {:tds, path: path} else {:tds, "~> 2.1.1", optional: true} end end defp test_paths(adapter) when adapter in @adapters, do: ["integration_test/#{adapter}"] defp test_paths(nil), do: ["test"] defp test_paths(other), do: raise("unknown adapter #{inspect(other)}") defp package do [ maintainers: ["Eric Meadows-Jönsson", "José Valim", "James Fish", "Michał Muskała"], licenses: ["Apache-2.0"], links: %{"GitHub" => @source_url}, files: ~w(.formatter.exs mix.exs README.md CHANGELOG.md lib) ++ ~w(integration_test/sql integration_test/support) ] end defp test_as_a_dep(args) do IO.puts("==> Compiling ecto_sql from a dependency") File.rm_rf!("tmp/as_a_dep") File.mkdir_p!("tmp/as_a_dep") File.cd!("tmp/as_a_dep", fn -> File.write!("mix.exs", """ defmodule DepsOnEctoSQL.MixProject do use Mix.Project def project do [ app: :deps_on_ecto_sql, version: "0.0.1", deps: [{:ecto_sql, path: "../.."}] ] end end """) mix_cmd_with_status_check(["do", "deps.get,", "compile", "--force" | args]) end) end defp test_adapters(args) do for adapter <- @adapters, do: env_run(adapter, args) end defp env_run(adapter, args) do IO.puts("==> Running tests for ECTO_ADAPTER=#{adapter} mix test") mix_cmd_with_status_check( ["test", ansi_option() | args], env: [{"ECTO_ADAPTER", adapter}] ) end defp ansi_option do if IO.ANSI.enabled?(), do: "--color", else: "--no-color" end defp mix_cmd_with_status_check(args, opts \\ []) do {_, res} = System.cmd("mix", args, [into: IO.binstream(:stdio, :line)] ++ opts) if res > 0 do System.at_exit(fn _ -> exit({:shutdown, 1}) end) end end defp docs do [ main: "Ecto.Adapters.SQL", source_ref: "v#{@version}", canonical: "http://hexdocs.pm/ecto_sql", source_url: @source_url, extras: ["CHANGELOG.md"], skip_undefined_reference_warnings_on: ["CHANGELOG.md"], groups_for_modules: [ # Ecto.Adapters.SQL, # Ecto.Adapters.SQL.Sandbox, # Ecto.Migration, # Ecto.Migrator, "Built-in adapters": [ Ecto.Adapters.MyXQL, Ecto.Adapters.Tds, Ecto.Adapters.Postgres ], "Adapter specification": [ Ecto.Adapter.Migration, Ecto.Adapter.Structure, Ecto.Adapters.SQL.Connection, Ecto.Migration.Command, Ecto.Migration.Constraint, Ecto.Migration.Index, Ecto.Migration.Reference, Ecto.Migration.Table ] ] ] end end
24.341463
90
0.561723
1c069d63ec6bfbaa349f285e94b4c54d5637ca8d
1,200
exs
Elixir
config/config.exs
lexnapoles/todo-list-elixir
fa68fdd77b3e90950374af9a5ced8f200365e63d
[ "MIT" ]
null
null
null
config/config.exs
lexnapoles/todo-list-elixir
fa68fdd77b3e90950374af9a5ced8f200365e63d
[ "MIT" ]
null
null
null
config/config.exs
lexnapoles/todo-list-elixir
fa68fdd77b3e90950374af9a5ced8f200365e63d
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config config :todo, http_port: 5454 import_config "#{Mix.env()}.exs" # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # third-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :todo_cache, key: :value # # and access this configuration in your application as: # # Application.get_env(:todo_cache, :key) # # You can also configure a third-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
34.285714
73
0.749167
1c070e95fd071723cf949ce217f7a54c7ad45547
253
exs
Elixir
SHED/config/dev.exs
ponyatov/metaL
0cd2614b5cd73280beeba34256a2e1dc736b2828
[ "MIT" ]
8
2019-04-22T12:28:20.000Z
2021-11-09T22:08:17.000Z
SHED/config/dev.exs
ponyatov/metaL
0cd2614b5cd73280beeba34256a2e1dc736b2828
[ "MIT" ]
3
2019-04-23T17:17:55.000Z
2020-10-12T08:43:25.000Z
SHED/config/dev.exs
ponyatov/metaL
0cd2614b5cd73280beeba34256a2e1dc736b2828
[ "MIT" ]
2
2020-09-21T20:38:37.000Z
2021-09-08T13:37:44.000Z
# powered by metaL: https://github.com/ponyatov/metaL/wiki/metaL-manifest # \ <section:top> use Mix.Config # / <section:top> # \ <section:mid> config :shed, # \ <section:dev> # / <section:dev> host: "127.0.0.1", port: 31211 # / <section:mid>
18.071429
74
0.628458
1c0773a066b5e21a319356b92326abc7677384d1
6,999
ex
Elixir
lib/codes/codes_d23.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_d23.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_d23.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_D23 do alias IcdCode.ICDCode def _D230 do %ICDCode{full_code: "D230", category_code: "D23", short_code: "0", full_name: "Other benign neoplasm of skin of lip", short_name: "Other benign neoplasm of skin of lip", category_name: "Other benign neoplasm of skin of lip" } end def _D2310 do %ICDCode{full_code: "D2310", category_code: "D23", short_code: "10", full_name: "Other benign neoplasm of skin of unspecified eyelid, including canthus", short_name: "Other benign neoplasm of skin of unspecified eyelid, including canthus", category_name: "Other benign neoplasm of skin of unspecified eyelid, including canthus" } end def _D2311 do %ICDCode{full_code: "D2311", category_code: "D23", short_code: "11", full_name: "Other benign neoplasm of skin of right eyelid, including canthus", short_name: "Other benign neoplasm of skin of right eyelid, including canthus", category_name: "Other benign neoplasm of skin of right eyelid, including canthus" } end def _D2312 do %ICDCode{full_code: "D2312", category_code: "D23", short_code: "12", full_name: "Other benign neoplasm of skin of left eyelid, including canthus", short_name: "Other benign neoplasm of skin of left eyelid, including canthus", category_name: "Other benign neoplasm of skin of left eyelid, including canthus" } end def _D2320 do %ICDCode{full_code: "D2320", category_code: "D23", short_code: "20", full_name: "Other benign neoplasm of skin of unspecified ear and external auricular canal", short_name: "Other benign neoplasm of skin of unspecified ear and external auricular canal", category_name: "Other benign neoplasm of skin of unspecified ear and external auricular canal" } end def _D2321 do %ICDCode{full_code: "D2321", category_code: "D23", short_code: "21", full_name: "Other benign neoplasm of skin of right ear and external auricular canal", short_name: "Other benign neoplasm of skin of right ear and external auricular canal", category_name: "Other benign neoplasm of skin of right ear and external auricular canal" } end def _D2322 do %ICDCode{full_code: "D2322", category_code: "D23", short_code: "22", full_name: "Other benign neoplasm of skin of left ear and external auricular canal", short_name: "Other benign neoplasm of skin of left ear and external auricular canal", category_name: "Other benign neoplasm of skin of left ear and external auricular canal" } end def _D2330 do %ICDCode{full_code: "D2330", category_code: "D23", short_code: "30", full_name: "Other benign neoplasm of skin of unspecified part of face", short_name: "Other benign neoplasm of skin of unspecified part of face", category_name: "Other benign neoplasm of skin of unspecified part of face" } end def _D2339 do %ICDCode{full_code: "D2339", category_code: "D23", short_code: "39", full_name: "Other benign neoplasm of skin of other parts of face", short_name: "Other benign neoplasm of skin of other parts of face", category_name: "Other benign neoplasm of skin of other parts of face" } end def _D234 do %ICDCode{full_code: "D234", category_code: "D23", short_code: "4", full_name: "Other benign neoplasm of skin of scalp and neck", short_name: "Other benign neoplasm of skin of scalp and neck", category_name: "Other benign neoplasm of skin of scalp and neck" } end def _D235 do %ICDCode{full_code: "D235", category_code: "D23", short_code: "5", full_name: "Other benign neoplasm of skin of trunk", short_name: "Other benign neoplasm of skin of trunk", category_name: "Other benign neoplasm of skin of trunk" } end def _D2360 do %ICDCode{full_code: "D2360", category_code: "D23", short_code: "60", full_name: "Other benign neoplasm of skin of unspecified upper limb, including shoulder", short_name: "Other benign neoplasm of skin of unspecified upper limb, including shoulder", category_name: "Other benign neoplasm of skin of unspecified upper limb, including shoulder" } end def _D2361 do %ICDCode{full_code: "D2361", category_code: "D23", short_code: "61", full_name: "Other benign neoplasm of skin of right upper limb, including shoulder", short_name: "Other benign neoplasm of skin of right upper limb, including shoulder", category_name: "Other benign neoplasm of skin of right upper limb, including shoulder" } end def _D2362 do %ICDCode{full_code: "D2362", category_code: "D23", short_code: "62", full_name: "Other benign neoplasm of skin of left upper limb, including shoulder", short_name: "Other benign neoplasm of skin of left upper limb, including shoulder", category_name: "Other benign neoplasm of skin of left upper limb, including shoulder" } end def _D2370 do %ICDCode{full_code: "D2370", category_code: "D23", short_code: "70", full_name: "Other benign neoplasm of skin of unspecified lower limb, including hip", short_name: "Other benign neoplasm of skin of unspecified lower limb, including hip", category_name: "Other benign neoplasm of skin of unspecified lower limb, including hip" } end def _D2371 do %ICDCode{full_code: "D2371", category_code: "D23", short_code: "71", full_name: "Other benign neoplasm of skin of right lower limb, including hip", short_name: "Other benign neoplasm of skin of right lower limb, including hip", category_name: "Other benign neoplasm of skin of right lower limb, including hip" } end def _D2372 do %ICDCode{full_code: "D2372", category_code: "D23", short_code: "72", full_name: "Other benign neoplasm of skin of left lower limb, including hip", short_name: "Other benign neoplasm of skin of left lower limb, including hip", category_name: "Other benign neoplasm of skin of left lower limb, including hip" } end def _D239 do %ICDCode{full_code: "D239", category_code: "D23", short_code: "9", full_name: "Other benign neoplasm of skin, unspecified", short_name: "Other benign neoplasm of skin, unspecified", category_name: "Other benign neoplasm of skin, unspecified" } end end
41.414201
104
0.646235
1c0778d1e1afda23deb1b00b5f2397a837afb2a0
366
ex
Elixir
apps/webapp/spec/support/factory.ex
iporaitech/phoenix-webpack-react-docker
c454db0b851b9d00db868a64b96e567d4a0cc3d9
[ "MIT" ]
25
2016-08-09T15:04:37.000Z
2021-11-15T12:20:27.000Z
apps/webapp/spec/support/factory.ex
iporaitech/phoenix-webpack-react-docker
c454db0b851b9d00db868a64b96e567d4a0cc3d9
[ "MIT" ]
62
2016-05-23T20:16:40.000Z
2017-04-18T18:36:29.000Z
apps/webapp/spec/support/factory.ex
iporaitech/phoenix-webpack-react-docker
c454db0b851b9d00db868a64b96e567d4a0cc3d9
[ "MIT" ]
10
2016-08-17T15:29:21.000Z
2017-02-28T07:58:30.000Z
defmodule Webapp.Factory do use ExMachina.Ecto, repo: Webapp.Repo def user_factory do %Webapp.User{ first_name: "Jane", last_name: "Smith", email: sequence(:email, &"email#{&1}@example.com") } end def make_admin(user) do %{user | role: "admin"} end def make_superadmin(user) do %{user | role: "superadmin"} end end
18.3
56
0.625683
1c07a29b0bc572a234684cf4855668e76a5e8ced
1,149
exs
Elixir
config/config.exs
TondaHack/recursive_renamer
1811d82d3fb6a61f97d46c744b88f5584e3e8e13
[ "MIT" ]
null
null
null
config/config.exs
TondaHack/recursive_renamer
1811d82d3fb6a61f97d46c744b88f5584e3e8e13
[ "MIT" ]
null
null
null
config/config.exs
TondaHack/recursive_renamer
1811d82d3fb6a61f97d46c744b88f5584e3e8e13
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # third-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :recursive_renamer, key: :value # # and access this configuration in your application as: # # Application.get_env(:recursive_renamer, :key) # # You can also configure a third-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
37.064516
73
0.75544
1c07b8ce048edbcc0ed597f8959a7f88103bda8a
616
ex
Elixir
web/models/room.ex
jusroberts/pingpong_server
fd090413076c84e4f7297349d4c9fd6323bd1ddf
[ "MIT" ]
null
null
null
web/models/room.ex
jusroberts/pingpong_server
fd090413076c84e4f7297349d4c9fd6323bd1ddf
[ "MIT" ]
null
null
null
web/models/room.ex
jusroberts/pingpong_server
fd090413076c84e4f7297349d4c9fd6323bd1ddf
[ "MIT" ]
null
null
null
defmodule PingpongServer.Room do use PingpongServer.Web, :model schema "rooms" do field :client_token, :string field :team_a_score, :integer field :team_b_score, :integer field :name, :string timestamps end @required_fields ~w(client_token name) @optional_fields ~w(team_a_score team_b_score) @doc """ Creates a changeset based on the `model` and `params`. If no params are provided, an invalid changeset is returned with no validation performed. """ def changeset(model, params \\ :empty) do model |> cast(params, @required_fields, @optional_fields) end end
22.814815
61
0.709416
1c07f9538e31797513ba337dc4d8e8dc00c32b6d
921
exs
Elixir
priv/repo/migrations/20151210171117_create_transaction_info.exs
van-mronov/ex_money
39010f02fd822657e3b5694e08b872bd2ab72c26
[ "0BSD" ]
184
2015-11-23T20:51:50.000Z
2022-03-30T01:01:39.000Z
priv/repo/migrations/20151210171117_create_transaction_info.exs
van-mronov/ex_money
39010f02fd822657e3b5694e08b872bd2ab72c26
[ "0BSD" ]
15
2015-11-26T16:00:20.000Z
2018-05-25T20:13:39.000Z
priv/repo/migrations/20151210171117_create_transaction_info.exs
van-mronov/ex_money
39010f02fd822657e3b5694e08b872bd2ab72c26
[ "0BSD" ]
21
2015-11-26T21:34:40.000Z
2022-03-26T02:56:42.000Z
defmodule ExMoney.Repo.Migrations.CreateTransactionInfo do use Ecto.Migration def change do create table(:transactions_info) do add :record_number, :string add :information, :text add :time, :datetime add :posting_date, :date add :posting_time, :datetime add :account_number, :string add :original_amount, :decimal add :original_currency_code, :string add :original_category, :string add :original_subcategory, :string add :customer_category_code, :string add :customer_category_name, :string add :tags, {:array, :string} add :mcc, :integer add :payee, :string add :type, :string add :check_number, :string add :units, :decimal add :additional, :text add :unit_price, :decimal add :transaction_id, references(:transactions, on_delete: :delete_all) timestamps end end end
27.088235
76
0.663409
1c07fc26f3569ffcc13c54a497e3fea8fb523d28
1,685
ex
Elixir
clients/content/lib/google_api/content/v2/model/orders_update_shipment_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/content/lib/google_api/content/v2/model/orders_update_shipment_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_update_shipment_response.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.Content.V2.Model.OrdersUpdateShipmentResponse do @moduledoc """ ## Attributes * `executionStatus` (*type:* `String.t`, *default:* `nil`) - The status of the execution. * `kind` (*type:* `String.t`, *default:* `content#ordersUpdateShipmentResponse`) - Identifies what kind of resource this is. Value: the fixed string "content#ordersUpdateShipmentResponse". """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :executionStatus => String.t(), :kind => String.t() } field(:executionStatus) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse do def decode(value, options) do GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.7
192
0.738872
1c08000ea036081d9c74fad4b788b9e5c8e172dc
188
exs
Elixir
priv/repo/migrations/20171018163534_add_project_id_to_pipelines.exs
crosscloudci/ci_status_repository
335e8b89bbf59e6cf63e49541ce3ea6b60167e52
[ "Apache-2.0" ]
2
2019-03-05T16:29:10.000Z
2020-01-17T14:11:48.000Z
priv/repo/migrations/20171018163534_add_project_id_to_pipelines.exs
crosscloudci/ci_status_repository
335e8b89bbf59e6cf63e49541ce3ea6b60167e52
[ "Apache-2.0" ]
3
2019-03-18T20:26:48.000Z
2020-06-25T14:31:13.000Z
priv/repo/migrations/20171018163534_add_project_id_to_pipelines.exs
crosscloudci/ci_status_repository
335e8b89bbf59e6cf63e49541ce3ea6b60167e52
[ "Apache-2.0" ]
1
2018-06-16T15:32:25.000Z
2018-06-16T15:32:25.000Z
defmodule CncfDashboardApi.Repo.Migrations.AddProjectIdToPipelines do use Ecto.Migration def change do alter table(:pipelines) do add :project_id, :string end end end
18.8
69
0.744681
1c0823ff5ae7ccb9e67761626bd10b388f5f2370
1,608
ex
Elixir
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/test_iam_permissions_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/test_iam_permissions_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/test_iam_permissions_response.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.CloudResourceManager.V1.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.CloudResourceManager.V1.Model.TestIamPermissionsResponse do def decode(value, options) do GoogleApi.CloudResourceManager.V1.Model.TestIamPermissionsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudResourceManager.V1.Model.TestIamPermissionsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.5
134
0.753109
1c083ca0772f2fcf4610e01e85a57e2c6670801a
2,518
exs
Elixir
config/prod.exs
MarkESDR/jsonapi_issue_134
6a0d41b1521a8bd9a21442ab6352b12139fb8c1a
[ "MIT" ]
null
null
null
config/prod.exs
MarkESDR/jsonapi_issue_134
6a0d41b1521a8bd9a21442ab6352b12139fb8c1a
[ "MIT" ]
null
null
null
config/prod.exs
MarkESDR/jsonapi_issue_134
6a0d41b1521a8bd9a21442ab6352b12139fb8c1a
[ "MIT" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :jsonapi_issue_134, JsonapiIssue134Web.Endpoint, http: [:inet6, port: System.get_env("PORT") || 4000], url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :jsonapi_issue_134, JsonapiIssue134Web.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # :inet6, # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :jsonapi_issue_134, JsonapiIssue134Web.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases (distillery) # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :jsonapi_issue_134, JsonapiIssue134Web.Endpoint, server: true # # Note you can't rely on `System.get_env/1` when using releases. # See the releases documentation accordingly. # Finally import the config/prod.secret.exs which should be versioned # separately. import_config "prod.secret.exs"
34.972222
74
0.721207
1c083e7d76c0bb9dded57f549b1e1d5b07e74cbd
1,325
ex
Elixir
lib/web/controllers/manage/setting_controller.ex
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
null
null
null
lib/web/controllers/manage/setting_controller.ex
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
null
null
null
lib/web/controllers/manage/setting_controller.ex
sb8244/grapevine
effaaa01294d30114090c20f9cc40b8665d834f2
[ "MIT" ]
null
null
null
defmodule Web.Manage.SettingController do use Web, :controller alias Grapevine.Accounts alias GrapevineData.Games plug(Web.Plugs.VerifyUser) def show(conn, _params) do %{current_user: user} = conn.assigns conn |> assign(:changeset, Accounts.edit(user)) |> assign(:games, Games.for_user(user)) |> render("show.html") end def update(conn, %{"user" => params = %{"current_password" => current_password}}) do %{current_user: user} = conn.assigns case Accounts.change_password(user, current_password, params) do {:ok, _user} -> conn |> put_flash(:info, "Profile updated!") |> redirect(to: manage_setting_path(conn, :show)) {:error, _changeset} -> conn |> put_flash(:error, "There was a problem updating.") |> redirect(to: manage_setting_path(conn, :show)) end end def update(conn, %{"user" => params}) do %{current_user: user} = conn.assigns case Accounts.update(user, params) do {:ok, _user} -> conn |> put_flash(:info, "Profile updated!") |> redirect(to: manage_setting_path(conn, :show)) {:error, _changeset} -> conn |> put_flash(:error, "There was a problem updating.") |> redirect(to: manage_setting_path(conn, :show)) end end end
26.5
86
0.619623
1c08450d7857c910a7ca655a196db2d5d44cfb35
9,780
ex
Elixir
lib/scrub/cip/connection_manager.ex
IslandUsurper/scrub
e36f1c602d53b2534084d8ba21100687a698a1be
[ "Apache-2.0" ]
3
2020-04-30T13:53:42.000Z
2021-04-20T16:53:54.000Z
lib/scrub/cip/connection_manager.ex
IslandUsurper/scrub
e36f1c602d53b2534084d8ba21100687a698a1be
[ "Apache-2.0" ]
3
2020-05-04T19:21:21.000Z
2021-03-31T23:00:36.000Z
lib/scrub/cip/connection_manager.ex
IslandUsurper/scrub
e36f1c602d53b2534084d8ba21100687a698a1be
[ "Apache-2.0" ]
1
2021-12-14T20:31:29.000Z
2021-12-14T20:31:29.000Z
defmodule Scrub.CIP.ConnectionManager do import Scrub.BinaryUtils, warn: false alias Scrub.CIP alias Scrub.CIP.Type alias Scrub.CIP.Connection @services [ large_forward_open: 0x5B, forward_close: 0x4E, read_tag_service: 0x4C, multiple_service_request: 0x0A ] def encode_service(_, _opts \\ []) def encode_service(:large_forward_open, opts) do priority = opts[:priority] || 0 time_ticks = opts[:time_ticks] || 10 timeout_ticks = opts[:timeout_ticks] || 5 orig_conn_id = 0x00 <<target_conn_id::udint>> = :crypto.strong_rand_bytes(4) <<conn_serial::uint>> = :crypto.strong_rand_bytes(2) orig_rpi = opts[:orig_rpi] || 1_000_000 orig_network_conn_params = opts[:orig_network_conn_params] || large_forward_open_network_parameters() target_rpi = opts[:target_rpi] || 1_000_000 target_network_conn_params = opts[:target_network_conn_params] || large_forward_open_network_parameters() transport_class_trigger = opts[:transport_class_trigger] || transport_class_trigger() <<0::size(1), Keyword.get(@services, :large_forward_open)::size(7), 0x02, 0x20, 0x06, 0x24, 0x01>> <> << # Time_ticks/ Priority # Reserved 0::little-size(3), priority::little-size(1), time_ticks::little-size(4), timeout_ticks::usint, # Connection information orig_conn_id::udint, target_conn_id::udint, conn_serial::uint, # Vendor Info Scrub.vendor()::binary, Scrub.serial_number()::binary, # # Connection timeout multiplier 1::usint, # # Reserved 0x00, 0x00, 0x00, # # Packet info orig_rpi::udint, orig_network_conn_params::binary(4, 8), target_rpi::udint, target_network_conn_params::binary(4, 8), transport_class_trigger::binary(1), # Connection path to Message Router # size 0x03, # seg 1 0x01, 0x00, # seg 2 0x20, 0x02, # seg 3 0x24, 0x01 >> end def encode_service(:forward_close, opts) do priority = opts[:priority] || 0 time_ticks = opts[:time_ticks] || 10 timeout_ticks = opts[:timeout_ticks] || 5 conn_serial = opts[:conn].serial <<0::size(1), Keyword.get(@services, :forward_close)::size(7), 0x02, 0x20, 0x06, 0x24, 0x01>> <> << # Time_ticks/ Priority # Reserved 0::little-size(3), priority::little-size(1), time_ticks::little-size(4), timeout_ticks::usint, # # Connection information conn_serial::binary(2, 8), # # Vendor Info Scrub.vendor()::binary, Scrub.serial_number()::binary, # # Connection path to Message Router 0x03::usint, # Reserved 0::usint, 0x01, 0x00, 0x20, 0x02, 0x24, 0x01 >> end def encode_service(:multiple_service_request, opts) do service_count = Enum.count(opts[:tag_list]) offset_start = service_count * 2 + 2 {service_offsets, service_list} = Enum.reduce_while( opts[:tag_list], {1, offset_start, <<offset_start::uint>>, <<>>}, fn request_path, {idx, offset_counter, offset_bin, service_acc} -> service = encode_service(:read_tag_service, request_path: request_path) # make sure that we dont create an offset for the last service if idx < service_count do offset_counter = offset_counter + byte_size(service) {:cont, {idx + 1, offset_counter, <<offset_bin::binary, offset_counter::uint>>, <<service_acc::binary, service::binary>>}} else {:halt, {offset_bin, <<service_acc::binary, service::binary>>}} end end ) << 0::size(1), Keyword.get(@services, :multiple_service_request)::size(7), # Request Path Size 0x02, # message router path 0x20, 0x02, 0x24, 0x01, service_count::uint, # first offset is always the same service_offsets::binary, service_list::binary >> end def encode_service(:read_tag_service, opts) do request_path = encode_request_path(opts[:request_path]) request_words = (byte_size(request_path) / 2) |> floor read_elements = opts[:read_elements] || 1 << 0::size(1), Keyword.get(@services, :read_tag_service)::size(7), request_words::usint, request_path::binary, read_elements::uint >> end def encode_request_path(request_path) when is_binary(request_path) do request_size = byte_size(request_path) request_path_padding = case rem(request_size, 2) do 0 -> 0 num -> 2 - num end request_path_padded = <<request_path::binary, 0x00::size(request_path_padding)-unit(8)>> <<0x91, byte_size(request_path)::usint, request_path_padded::binary>> end def encode_request_path(request_path) when is_integer(request_path) do <<0x28, request_path::size(8)>> end def encode_request_path(request_path) when is_list(request_path) do Enum.reduce(request_path, <<>>, fn member, acc -> <<acc::binary, encode_request_path(member)::binary>> end) end def decode( <<1::size(1), service::size(7), 0, status_code::usint, size::usint, data::binary>>, template_or_tag \\ nil ) do <<service>> = <<0::size(1), service::size(7)>> header = %{ status_code: CIP.status_code(status_code), size: size } case Enum.find(@services, &(elem(&1, 1) == service)) do nil -> {:error, {:not_implemented, data}} {service, _} -> decode_service(service, header, data, template_or_tag) end end # Large Forward Open defp decode_service( :large_forward_open, _header, << orig_network_id::binary(4, 8), target_network_id::binary(4, 8), conn_serial::binary(2, 8), _orig_vendor_id::uint, _orig_serial::udint, orig_api::udint, target_api::udint, 0::usint, _reserved::binary >>, _t ) do {:ok, %Connection{ orig_network_id: orig_network_id, target_network_id: target_network_id, serial: conn_serial, orig_api: orig_api, target_api: target_api }} end defp decode_service(:forward_close, _header, data, _t) do {:ok, data} end defp decode_service( :read_tag_service, %{status_code: :success}, << data::binary >>, template ) do case Type.decode(data, template) do :invalid -> {:error, :invalid} value -> {:ok, value} end end defp decode_service( :multiple_service_request, %{status_code: code}, << service_count::uint, offset_bin::binary(service_count, 16), data::binary >>, _template ) when code in [:success, :embedded_service_failure] do # grab offset data offset_list = for <<offset::uint <- offset_bin>> do offset end {start, offset_list} = List.pop_at(offset_list, 0) {service_data, last_service, _} = Enum.reduce(offset_list, {[], data, start}, fn offset, {data_list, data, previous_offset} -> size = offset - previous_offset <<important_data::binary(size, 8), rest::binary>> = data {[important_data | data_list], rest, offset} end) # combine the final service into the list service_data = [last_service | service_data] final_output = Enum.map(service_data, fn s -> case decode(s) do {:ok, value} -> value error -> error end end) |> Enum.reverse() {:ok, final_output} end defp decode_service( _, %{status_code: code}, _, _ ) do {:error, code} end defp large_forward_open_network_parameters(opts \\ []) do owner = opts[:owner] || 0 connection_type = opts[:connection_type] || :point_to_point priority = opts[:priority] || :low fixed? = opts[:fixed] == true fixed = if fixed?, do: 0, else: 1 connection_size = opts[:connection_size] || 4002 << connection_size::little-size(2)-unit(8), # reserved, 0::size(8), owner::little-size(1), encode_connection_type(connection_type)::little-size(2), # reserved 0::little-size(1), encode_priority(priority)::little-size(2), fixed::little-size(1), # reserved, 0::size(1) >> end defp transport_class_trigger(opts \\ []) do dir = opts[:dir] || :server trigger = opts[:trigger] || :application_object transport_class = opts[:transport_class] || 3 << encode_transport_class_direction(dir)::size(1), encode_production_trigger(trigger)::little-size(3), transport_class::little-size(4) >> end defp encode_connection_type(:null), do: 0 defp encode_connection_type(:multicast), do: 1 defp encode_connection_type(:point_to_point), do: 2 defp encode_connection_type(:reserved), do: 3 defp encode_priority(:low), do: 0 defp encode_priority(:high), do: 1 defp encode_priority(:scheduled), do: 2 defp encode_priority(:urgent), do: 3 defp encode_transport_class_direction(:client), do: 0 defp encode_transport_class_direction(:server), do: 1 defp encode_production_trigger(:cyclic), do: 0 defp encode_production_trigger(:change_of_state), do: 1 defp encode_production_trigger(:application_object), do: 2 end
26.868132
100
0.604908
1c0849aac26b988a81e50641d91850c9d93fd878
1,962
exs
Elixir
clients/accelerated_mobile_page_url/mix.exs
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/accelerated_mobile_page_url/mix.exs
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/accelerated_mobile_page_url/mix.exs
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.AcceleratedMobilePageUrl.Mixfile do use Mix.Project @version "0.11.0" def project() do [ app: :google_api_accelerated_mobile_page_url, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/accelerated_mobile_page_url" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Accelerated Mobile Pages (AMP) URL API client library. Retrieves the list of AMP URLs (and equivalent AMP Cache URLs) for a given list of public URL(s). """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/accelerated_mobile_page_url", "Homepage" => "https://developers.google.com/amp/cache/" } ] end end
29.283582
157
0.667686
1c084ece4ebda1cdb485b70d90c23e63e153a9d8
13,226
ex
Elixir
lib/elixir/lib/string_io.ex
spencerdcarlson/elixir
23d75ecdf58df80969e12f4420282238e19219a1
[ "Apache-2.0" ]
2
2020-06-02T18:00:28.000Z
2021-12-10T03:21:42.000Z
lib/elixir/lib/string_io.ex
spencerdcarlson/elixir
23d75ecdf58df80969e12f4420282238e19219a1
[ "Apache-2.0" ]
1
2020-09-14T16:23:33.000Z
2021-03-25T17:38:59.000Z
lib/elixir/lib/string_io.ex
spencerdcarlson/elixir
23d75ecdf58df80969e12f4420282238e19219a1
[ "Apache-2.0" ]
1
2018-01-09T20:10:59.000Z
2018-01-09T20:10:59.000Z
defmodule StringIO do @moduledoc """ Controls an IO device process that wraps a string. A `StringIO` IO device can be passed as a "device" to most of the functions in the `IO` module. ## Examples iex> {:ok, pid} = StringIO.open("foo") iex> IO.read(pid, 2) "fo" """ use GenServer @doc ~S""" Creates an IO device. `string` will be the initial input of the newly created device. The device will be created and sent to the function given. When the function returns, the device will be closed. The final result will be a tuple with `:ok` and the result of the function. ## Options * `:capture_prompt` - if set to `true`, prompts (specified as arguments to `IO.get*` functions) are captured in the output. Defaults to `false`. * `:encoding` (since v1.10.0) - encoding of the IO device. Allowed values are `:unicode` (default) and `:latin1`. ## Examples iex> StringIO.open("foo", [], fn pid -> ...> input = IO.gets(pid, ">") ...> IO.write(pid, "The input was #{input}") ...> StringIO.contents(pid) ...> end) {:ok, {"", "The input was foo"}} iex> StringIO.open("foo", [capture_prompt: true], fn pid -> ...> input = IO.gets(pid, ">") ...> IO.write(pid, "The input was #{input}") ...> StringIO.contents(pid) ...> end) {:ok, {"", ">The input was foo"}} """ @doc since: "1.7.0" @spec open(binary, keyword, (pid -> res)) :: {:ok, res} when res: var def open(string, options, function) when is_binary(string) and is_list(options) and is_function(function, 1) do {:ok, pid} = GenServer.start_link(__MODULE__, {string, options}, []) try do {:ok, function.(pid)} after {:ok, {_input, _output}} = close(pid) end end @doc ~S""" Creates an IO device. `string` will be the initial input of the newly created device. `options_or_function` can be a keyword list of options or a function. If options are provided, the result will be `{:ok, pid}`, returning the IO device created. The option `:capture_prompt`, when set to `true`, causes prompts (which are specified as arguments to `IO.get*` functions) to be included in the device's output. If a function is provided, the device will be created and sent to the function. When the function returns, the device will be closed. The final result will be a tuple with `:ok` and the result of the function. ## Examples iex> {:ok, pid} = StringIO.open("foo") iex> IO.gets(pid, ">") "foo" iex> StringIO.contents(pid) {"", ""} iex> {:ok, pid} = StringIO.open("foo", capture_prompt: true) iex> IO.gets(pid, ">") "foo" iex> StringIO.contents(pid) {"", ">"} iex> StringIO.open("foo", fn pid -> ...> input = IO.gets(pid, ">") ...> IO.write(pid, "The input was #{input}") ...> StringIO.contents(pid) ...> end) {:ok, {"", "The input was foo"}} """ @spec open(binary, keyword) :: {:ok, pid} @spec open(binary, (pid -> res)) :: {:ok, res} when res: var def open(string, options_or_function \\ []) def open(string, options_or_function) when is_binary(string) and is_list(options_or_function) do GenServer.start_link(__MODULE__, {string, options_or_function}, []) end def open(string, options_or_function) when is_binary(string) and is_function(options_or_function, 1) do open(string, [], options_or_function) end @doc """ Returns the current input/output buffers for the given IO device. ## Examples iex> {:ok, pid} = StringIO.open("in") iex> IO.write(pid, "out") iex> StringIO.contents(pid) {"in", "out"} """ @spec contents(pid) :: {binary, binary} def contents(pid) when is_pid(pid) do GenServer.call(pid, :contents) end @doc """ Flushes the output buffer and returns its current contents. ## Examples iex> {:ok, pid} = StringIO.open("in") iex> IO.write(pid, "out") iex> StringIO.flush(pid) "out" iex> StringIO.contents(pid) {"in", ""} """ @spec flush(pid) :: binary def flush(pid) when is_pid(pid) do GenServer.call(pid, :flush) end @doc """ Stops the IO device and returns the remaining input/output buffers. ## Examples iex> {:ok, pid} = StringIO.open("in") iex> IO.write(pid, "out") iex> StringIO.close(pid) {:ok, {"in", "out"}} """ @spec close(pid) :: {:ok, {binary, binary}} def close(pid) when is_pid(pid) do GenServer.call(pid, :close) end ## callbacks @impl true def init({string, options}) do capture_prompt = options[:capture_prompt] || false encoding = options[:encoding] || :unicode {:ok, %{encoding: encoding, input: string, output: "", capture_prompt: capture_prompt}} end @impl true def handle_info({:io_request, from, reply_as, req}, state) do state = io_request(from, reply_as, req, state) {:noreply, state} end def handle_info(_message, state) do {:noreply, state} end @impl true def handle_call(:contents, _from, %{input: input, output: output} = state) do {:reply, {input, output}, state} end def handle_call(:flush, _from, %{output: output} = state) do {:reply, output, %{state | output: ""}} end def handle_call(:close, _from, %{input: input, output: output} = state) do {:stop, :normal, {:ok, {input, output}}, state} end defp io_request(from, reply_as, req, state) do {reply, state} = io_request(req, state) io_reply(from, reply_as, reply) state end defp io_request({:put_chars, chars} = req, state) do put_chars(:latin1, chars, req, state) end defp io_request({:put_chars, mod, fun, args} = req, state) do put_chars(:latin1, apply(mod, fun, args), req, state) end defp io_request({:put_chars, encoding, chars} = req, state) do put_chars(encoding, chars, req, state) end defp io_request({:put_chars, encoding, mod, fun, args} = req, state) do put_chars(encoding, apply(mod, fun, args), req, state) end defp io_request({:get_chars, prompt, count}, state) when count >= 0 do io_request({:get_chars, :latin1, prompt, count}, state) end defp io_request({:get_chars, encoding, prompt, count}, state) when count >= 0 do get_chars(encoding, prompt, count, state) end defp io_request({:get_line, prompt}, state) do io_request({:get_line, :latin1, prompt}, state) end defp io_request({:get_line, encoding, prompt}, state) do get_line(encoding, prompt, state) end defp io_request({:get_until, prompt, mod, fun, args}, state) do io_request({:get_until, :latin1, prompt, mod, fun, args}, state) end defp io_request({:get_until, encoding, prompt, mod, fun, args}, state) do get_until(encoding, prompt, mod, fun, args, state) end defp io_request({:get_password, encoding}, state) do get_line(encoding, "", state) end defp io_request({:setopts, [encoding: encoding]}, state) when encoding in [:latin1, :unicode] do {:ok, %{state | encoding: encoding}} end defp io_request({:setopts, _opts}, state) do {{:error, :enotsup}, state} end defp io_request(:getopts, state) do {[binary: true, encoding: state.encoding], state} end defp io_request({:get_geometry, :columns}, state) do {{:error, :enotsup}, state} end defp io_request({:get_geometry, :rows}, state) do {{:error, :enotsup}, state} end defp io_request({:requests, reqs}, state) do io_requests(reqs, {:ok, state}) end defp io_request(_, state) do {{:error, :request}, state} end ## put_chars defp put_chars(encoding, chars, req, state) do case :unicode.characters_to_binary(chars, encoding, state.encoding) do string when is_binary(string) -> {:ok, %{state | output: state.output <> string}} {_, _, _} -> {{:error, req}, state} end rescue ArgumentError -> {{:error, req}, state} end ## get_chars defp get_chars(encoding, prompt, count, %{input: input} = state) do case get_chars(input, encoding, count) do {:error, _} = error -> {error, state} {result, input} -> {result, state_after_read(state, input, prompt, 1)} end end defp get_chars("", _encoding, _count) do {:eof, ""} end defp get_chars(input, :latin1, count) when byte_size(input) < count do {input, ""} end defp get_chars(input, :latin1, count) do <<chars::binary-size(count), rest::binary>> = input {chars, rest} end defp get_chars(input, :unicode, count) do with {:ok, count} <- split_at(input, count, 0) do <<chars::binary-size(count), rest::binary>> = input {chars, rest} end end defp split_at(_, 0, acc), do: {:ok, acc} defp split_at(<<h::utf8, t::binary>>, count, acc), do: split_at(t, count - 1, acc + byte_size(<<h::utf8>>)) defp split_at(<<_, _::binary>>, _count, _acc), do: {:error, :invalid_unicode} defp split_at(<<>>, _count, acc), do: {:ok, acc} ## get_line defp get_line(encoding, prompt, %{input: input} = state) do case bytes_until_eol(input, encoding, 0) do {:split, 0} -> {:eof, state_after_read(state, "", prompt, 1)} {:split, count} -> {result, remainder} = :erlang.split_binary(input, count) {result, state_after_read(state, remainder, prompt, 1)} {:replace_split, count} -> {result, remainder} = :erlang.split_binary(input, count) result = binary_part(result, 0, byte_size(result) - 2) <> "\n" {result, state_after_read(state, remainder, prompt, 1)} :error -> {{:error, :collect_line}, state} end end ## get_until defp get_until(encoding, prompt, mod, fun, args, %{input: input} = state) do case get_until(input, encoding, mod, fun, args, [], 0) do {result, input, count} -> input = case input do :eof -> "" _ -> list_to_binary(input, encoding) end {get_until_result(result, encoding), state_after_read(state, input, prompt, count)} :error -> {:error, state} end end defp get_until("", encoding, mod, fun, args, continuation, count) do case apply(mod, fun, [continuation, :eof | args]) do {:done, result, rest} -> {result, rest, count + 1} {:more, next_continuation} -> get_until("", encoding, mod, fun, args, next_continuation, count + 1) end end defp get_until(chars, encoding, mod, fun, args, continuation, count) do case bytes_until_eol(chars, encoding, 0) do {kind, size} when kind in [:split, :replace_split] -> {line, rest} = :erlang.split_binary(chars, size) case apply(mod, fun, [continuation, binary_to_list(line, encoding) | args]) do {:done, result, :eof} -> {result, rest, count + 1} {:done, result, extra} -> {result, extra ++ binary_to_list(rest, encoding), count + 1} {:more, next_continuation} -> get_until(rest, encoding, mod, fun, args, next_continuation, count + 1) end :error -> :error end end defp binary_to_list(data, _) when is_list(data), do: data defp binary_to_list(data, :unicode) when is_binary(data), do: String.to_charlist(data) defp binary_to_list(data, :latin1) when is_binary(data), do: :erlang.binary_to_list(data) defp list_to_binary(data, _) when is_binary(data), do: data defp list_to_binary(data, :unicode) when is_list(data), do: List.to_string(data) defp list_to_binary(data, :latin1) when is_list(data), do: :erlang.list_to_binary(data) # From http://erlang.org/doc/apps/stdlib/io_protocol.html: result can be any # Erlang term, but if it is a list(), the I/O server can convert it to a binary(). defp get_until_result(data, encoding) when is_list(data), do: list_to_binary(data, encoding) defp get_until_result(data, _), do: data ## io_requests defp io_requests([req | rest], {:ok, state}) do io_requests(rest, io_request(req, state)) end defp io_requests(_, result) do result end ## helpers defp state_after_read(%{capture_prompt: false} = state, remainder, _prompt, _count) do %{state | input: remainder} end defp state_after_read(%{capture_prompt: true, output: output} = state, remainder, prompt, count) do output = <<output::binary, :binary.copy(IO.chardata_to_string(prompt), count)::binary>> %{state | input: remainder, output: output} end defp bytes_until_eol("", _, count), do: {:split, count} defp bytes_until_eol(<<"\r\n"::binary, _::binary>>, _, count), do: {:replace_split, count + 2} defp bytes_until_eol(<<"\n"::binary, _::binary>>, _, count), do: {:split, count + 1} defp bytes_until_eol(<<head::utf8, tail::binary>>, :unicode, count) do bytes_until_eol(tail, :unicode, count + byte_size(<<head::utf8>>)) end defp bytes_until_eol(<<_, tail::binary>>, :latin1, count) do bytes_until_eol(tail, :latin1, count + 1) end defp bytes_until_eol(<<_::binary>>, _, _), do: :error defp io_reply(from, reply_as, reply) do send(from, {:io_reply, reply_as, reply}) end end
28.627706
101
0.626115
1c085b8dae712d6b1d194932cd31f49100e560f8
112,344
ex
Elixir
lib/baiji/service/cognito_identity_provider.ex
wrren/baiji
d3d9e1cad875c6e1ddb47bf52511c3a07321764a
[ "MIT" ]
null
null
null
lib/baiji/service/cognito_identity_provider.ex
wrren/baiji
d3d9e1cad875c6e1ddb47bf52511c3a07321764a
[ "MIT" ]
null
null
null
lib/baiji/service/cognito_identity_provider.ex
wrren/baiji
d3d9e1cad875c6e1ddb47bf52511c3a07321764a
[ "MIT" ]
null
null
null
defmodule Baiji.CognitoIdentityProvider do @moduledoc """ Using the Amazon Cognito User Pools API, you can create a user pool to manage directories and users. You can authenticate a user to obtain tokens related to user identity and access policies. This API reference provides information about user pools in Amazon Cognito User Pools. For more information, see the Amazon Cognito Documentation. """ @doc """ Describes a resource server. """ def describe_resource_server(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DescribeResourceServer", method: :post, input_shape: "DescribeResourceServerRequest", output_shape: "DescribeResourceServerResponse", endpoint: __spec__() } end @doc """ Deletes an identity provider for a user pool. """ def delete_identity_provider(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteIdentityProvider", method: :post, input_shape: "DeleteIdentityProviderRequest", output_shape: "", endpoint: __spec__() } end @doc """ Updates the device status as an administrator. Requires developer credentials. """ def admin_update_device_status(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminUpdateDeviceStatus", method: :post, input_shape: "AdminUpdateDeviceStatusRequest", output_shape: "AdminUpdateDeviceStatusResponse", endpoint: __spec__() } end @doc """ Changes the password for a specified user in a user pool. """ def change_password(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ChangePassword", method: :post, input_shape: "ChangePasswordRequest", output_shape: "ChangePasswordResponse", endpoint: __spec__() } end @doc """ Signs out users from all devices, as an administrator. Requires developer credentials. """ def admin_user_global_sign_out(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminUserGlobalSignOut", method: :post, input_shape: "AdminUserGlobalSignOutRequest", output_shape: "AdminUserGlobalSignOutResponse", endpoint: __spec__() } end @doc """ Removes the specified user from the specified group. Requires developer credentials. """ def admin_remove_user_from_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminRemoveUserFromGroup", method: :post, input_shape: "AdminRemoveUserFromGroupRequest", output_shape: "", endpoint: __spec__() } end @doc """ Returns the configuration information and metadata of the specified user pool. """ def describe_user_pool(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DescribeUserPool", method: :post, input_shape: "DescribeUserPoolRequest", output_shape: "DescribeUserPoolResponse", endpoint: __spec__() } end @doc """ Confirms tracking of the device. This API call is the call that begins device tracking. """ def confirm_device(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ConfirmDevice", method: :post, input_shape: "ConfirmDeviceRequest", output_shape: "ConfirmDeviceResponse", endpoint: __spec__() } end @doc """ Responds to the authentication challenge. """ def respond_to_auth_challenge(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "RespondToAuthChallenge", method: :post, input_shape: "RespondToAuthChallengeRequest", output_shape: "RespondToAuthChallengeResponse", endpoint: __spec__() } end @doc """ Stops the user import job. """ def stop_user_import_job(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "StopUserImportJob", method: :post, input_shape: "StopUserImportJobRequest", output_shape: "StopUserImportJobResponse", endpoint: __spec__() } end @doc """ Creates an identity provider for a user pool. """ def create_identity_provider(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateIdentityProvider", method: :post, input_shape: "CreateIdentityProviderRequest", output_shape: "CreateIdentityProviderResponse", endpoint: __spec__() } end @doc """ Lists the user pools associated with an AWS account. """ def list_user_pools(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListUserPools", method: :post, input_shape: "ListUserPoolsRequest", output_shape: "ListUserPoolsResponse", endpoint: __spec__() } end @doc """ Lists the clients that have been created for the specified user pool. """ def list_user_pool_clients(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListUserPoolClients", method: :post, input_shape: "ListUserPoolClientsRequest", output_shape: "ListUserPoolClientsResponse", endpoint: __spec__() } end @doc """ Updates the device status. """ def update_device_status(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateDeviceStatus", method: :post, input_shape: "UpdateDeviceStatusRequest", output_shape: "UpdateDeviceStatusResponse", endpoint: __spec__() } end @doc """ Sets all the user settings for a specified user name. Works on any user. Requires developer credentials. """ def admin_set_user_settings(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminSetUserSettings", method: :post, input_shape: "AdminSetUserSettingsRequest", output_shape: "AdminSetUserSettingsResponse", endpoint: __spec__() } end @doc """ Initiates the authentication flow, as an administrator. Requires developer credentials. """ def admin_initiate_auth(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminInitiateAuth", method: :post, input_shape: "AdminInitiateAuthRequest", output_shape: "AdminInitiateAuthResponse", endpoint: __spec__() } end @doc """ Gets the user attributes and metadata for a user. """ def get_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetUser", method: :post, input_shape: "GetUserRequest", output_shape: "GetUserResponse", endpoint: __spec__() } end @doc """ Updates the specified user pool with the specified attributes. """ def update_user_pool(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateUserPool", method: :post, input_shape: "UpdateUserPoolRequest", output_shape: "UpdateUserPoolResponse", endpoint: __spec__() } end @doc """ Gets the user attribute verification code for the specified attribute name. """ def get_user_attribute_verification_code(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetUserAttributeVerificationCode", method: :post, input_shape: "GetUserAttributeVerificationCodeRequest", output_shape: "GetUserAttributeVerificationCodeResponse", endpoint: __spec__() } end @doc """ Lists the groups that the user belongs to. Requires developer credentials. """ def admin_list_groups_for_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminListGroupsForUser", method: :post, input_shape: "AdminListGroupsForUserRequest", output_shape: "AdminListGroupsForUserResponse", endpoint: __spec__() } end @doc """ Updates the specified user's attributes, including developer attributes, as an administrator. Works on any user. For custom attributes, you must prepend the `custom:` prefix to the attribute name. In addition to updating user attributes, this API can also be used to mark phone and email as verified. Requires developer credentials. """ def admin_update_user_attributes(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminUpdateUserAttributes", method: :post, input_shape: "AdminUpdateUserAttributesRequest", output_shape: "AdminUpdateUserAttributesResponse", endpoint: __spec__() } end @doc """ Adds the specified user to the specified group. Requires developer credentials. """ def admin_add_user_to_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminAddUserToGroup", method: :post, input_shape: "AdminAddUserToGroupRequest", output_shape: "", endpoint: __spec__() } end @doc """ Lists the resource servers for a user pool. """ def list_resource_servers(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListResourceServers", method: :post, input_shape: "ListResourceServersRequest", output_shape: "ListResourceServersResponse", endpoint: __spec__() } end @doc """ Lists information about all identity providers for a user pool. """ def list_identity_providers(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListIdentityProviders", method: :post, input_shape: "ListIdentityProvidersRequest", output_shape: "ListIdentityProvidersResponse", endpoint: __spec__() } end @doc """ Disables the user from signing in with the specified external (SAML or social) identity provider. If the user to disable is a Cognito User Pools native username + password user, they are not permitted to use their password to sign-in. If the user to disable is a linked external IdP user, any link between that user and an existing user is removed. The next time the external user (no longer attached to the previously linked `DestinationUser`) signs in, they must create a new user account. See [AdminLinkProviderForUser](API_AdminLinkProviderForUser.html). This action is enabled only for admin access and requires developer credentials. The `ProviderName` must match the value specified when creating an IdP for the pool. To disable a native username + password user, the `ProviderName` value must be `Cognito` and the `ProviderAttributeName` must be `Cognito_Subject`, with the `ProviderAttributeValue` being the name that is used in the user pool for the user. The `ProviderAttributeName` must always be `Cognito_Subject` for social identity providers. The `ProviderAttributeValue` must always be the exact subject that was used when the user was originally linked as a source user. For de-linking a SAML identity, there are two scenarios. If the linked identity has not yet been used to sign-in, the `ProviderAttributeName` and `ProviderAttributeValue` must be the same values that were used for the `SourceUser` when the identities were originally linked in the [AdminLinkProviderForUser](API_AdminLinkProviderForUser.html) call. (If the linking was done with `ProviderAttributeName` set to `Cognito_Subject`, the same applies here). However, if the user has already signed in, the `ProviderAttributeName` must be `Cognito_Subject` and `ProviderAttributeValue` must be the subject of the SAML assertion. """ def admin_disable_provider_for_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminDisableProviderForUser", method: :post, input_shape: "AdminDisableProviderForUserRequest", output_shape: "AdminDisableProviderForUserResponse", endpoint: __spec__() } end @doc """ Deletes a user as an administrator. Works on any user. Requires developer credentials. """ def admin_delete_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminDeleteUser", method: :post, input_shape: "AdminDeleteUserRequest", output_shape: "", endpoint: __spec__() } end @doc """ Forgets the device, as an administrator. Requires developer credentials. """ def admin_forget_device(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminForgetDevice", method: :post, input_shape: "AdminForgetDeviceRequest", output_shape: "", endpoint: __spec__() } end @doc """ Gets the specified user by user name in a user pool as an administrator. Works on any user. Requires developer credentials. """ def admin_get_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminGetUser", method: :post, input_shape: "AdminGetUserRequest", output_shape: "AdminGetUserResponse", endpoint: __spec__() } end @doc """ Deletes the user attributes in a user pool as an administrator. Works on any user. Requires developer credentials. """ def admin_delete_user_attributes(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminDeleteUserAttributes", method: :post, input_shape: "AdminDeleteUserAttributesRequest", output_shape: "AdminDeleteUserAttributesResponse", endpoint: __spec__() } end @doc """ Resends the confirmation (for confirmation of registration) to a specific user in the user pool. """ def resend_confirmation_code(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ResendConfirmationCode", method: :post, input_shape: "ResendConfirmationCodeRequest", output_shape: "ResendConfirmationCodeResponse", endpoint: __spec__() } end @doc """ Gets the header information for the .csv file to be used as input for the user import job. """ def get_c_s_v_header(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetCSVHeader", method: :post, input_shape: "GetCSVHeaderRequest", output_shape: "GetCSVHeaderResponse", endpoint: __spec__() } end @doc """ Deletes a group. Currently only groups with no members can be deleted. Requires developer credentials. """ def delete_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteGroup", method: :post, input_shape: "DeleteGroupRequest", output_shape: "", endpoint: __spec__() } end @doc """ Deletes the attributes for a user. """ def delete_user_attributes(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteUserAttributes", method: :post, input_shape: "DeleteUserAttributesRequest", output_shape: "DeleteUserAttributesResponse", endpoint: __spec__() } end @doc """ Creates a new user in the specified user pool and sends a welcome message via email or phone (SMS). This message is based on a template that you configured in your call to [CreateUserPool](API_CreateUserPool.html) or [UpdateUserPool](API_UpdateUserPool.html). This template includes your custom sign-up instructions and placeholders for user name and temporary password. Requires developer credentials. """ def admin_create_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminCreateUser", method: :post, input_shape: "AdminCreateUserRequest", output_shape: "AdminCreateUserResponse", endpoint: __spec__() } end @doc """ Allows the developer to delete the user pool client. """ def delete_user_pool_client(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteUserPoolClient", method: :post, input_shape: "DeleteUserPoolClientRequest", output_shape: "", endpoint: __spec__() } end @doc """ Gets the device. """ def get_device(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetDevice", method: :post, input_shape: "GetDeviceRequest", output_shape: "GetDeviceResponse", endpoint: __spec__() } end @doc """ Allows a user to update a specific attribute (one at a time). """ def update_user_attributes(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateUserAttributes", method: :post, input_shape: "UpdateUserAttributesRequest", output_shape: "UpdateUserAttributesResponse", endpoint: __spec__() } end @doc """ Lists the user import jobs. """ def list_user_import_jobs(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListUserImportJobs", method: :post, input_shape: "ListUserImportJobsRequest", output_shape: "ListUserImportJobsResponse", endpoint: __spec__() } end @doc """ Creates a new Amazon Cognito user pool and sets the password policy for the pool. """ def create_user_pool(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateUserPool", method: :post, input_shape: "CreateUserPoolRequest", output_shape: "CreateUserPoolResponse", endpoint: __spec__() } end @doc """ Creates the user import job. """ def create_user_import_job(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateUserImportJob", method: :post, input_shape: "CreateUserImportJobRequest", output_shape: "CreateUserImportJobResponse", endpoint: __spec__() } end @doc """ Lists the devices. """ def list_devices(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListDevices", method: :post, input_shape: "ListDevicesRequest", output_shape: "ListDevicesResponse", endpoint: __spec__() } end @doc """ Creates the user pool client. """ def create_user_pool_client(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateUserPoolClient", method: :post, input_shape: "CreateUserPoolClientRequest", output_shape: "CreateUserPoolClientResponse", endpoint: __spec__() } end @doc """ Responds to an authentication challenge, as an administrator. Requires developer credentials. """ def admin_respond_to_auth_challenge(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminRespondToAuthChallenge", method: :post, input_shape: "AdminRespondToAuthChallengeRequest", output_shape: "AdminRespondToAuthChallengeResponse", endpoint: __spec__() } end @doc """ Sets the UI customization information for a user pool's built-in app UI. You can specify app UI customization settings for a single client (with a specific `clientId`) or for all clients (by setting the `clientId` to `ALL`). If you specify `ALL`, the default configuration will be used for every client that has no UI customization set previously. If you specify UI customization settings for a particular client, it will no longer fall back to the `ALL` configuration. <note> To use this API, your user pool must have a domain associated with it. Otherwise, there is no place to host the app's pages, and the service will throw an error. </note> """ def set_u_i_customization(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "SetUICustomization", method: :post, input_shape: "SetUICustomizationRequest", output_shape: "SetUICustomizationResponse", endpoint: __spec__() } end @doc """ Gets a group. Requires developer credentials. """ def get_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetGroup", method: :post, input_shape: "GetGroupRequest", output_shape: "GetGroupResponse", endpoint: __spec__() } end @doc """ Lists devices, as an administrator. Requires developer credentials. """ def admin_list_devices(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminListDevices", method: :post, input_shape: "AdminListDevicesRequest", output_shape: "AdminListDevicesResponse", endpoint: __spec__() } end @doc """ Starts the user import. """ def start_user_import_job(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "StartUserImportJob", method: :post, input_shape: "StartUserImportJobRequest", output_shape: "StartUserImportJobResponse", endpoint: __spec__() } end @doc """ Deletes a resource server. """ def delete_resource_server(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteResourceServer", method: :post, input_shape: "DeleteResourceServerRequest", output_shape: "", endpoint: __spec__() } end @doc """ Initiates the authentication flow. """ def initiate_auth(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "InitiateAuth", method: :post, input_shape: "InitiateAuthRequest", output_shape: "InitiateAuthResponse", endpoint: __spec__() } end @doc """ Allows a user to delete himself or herself. """ def delete_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteUser", method: :post, input_shape: "DeleteUserRequest", output_shape: "", endpoint: __spec__() } end @doc """ Creates a new domain for a user pool. """ def create_user_pool_domain(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateUserPoolDomain", method: :post, input_shape: "CreateUserPoolDomainRequest", output_shape: "CreateUserPoolDomainResponse", endpoint: __spec__() } end @doc """ Enables the specified user as an administrator. Works on any user. Requires developer credentials. """ def admin_enable_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminEnableUser", method: :post, input_shape: "AdminEnableUserRequest", output_shape: "AdminEnableUserResponse", endpoint: __spec__() } end @doc """ Forgets the specified device. """ def forget_device(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ForgetDevice", method: :post, input_shape: "ForgetDeviceRequest", output_shape: "", endpoint: __spec__() } end @doc """ Gets the specified identity provider. """ def get_identity_provider_by_identifier(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetIdentityProviderByIdentifier", method: :post, input_shape: "GetIdentityProviderByIdentifierRequest", output_shape: "GetIdentityProviderByIdentifierResponse", endpoint: __spec__() } end @doc """ Lists the users in the Amazon Cognito user pool. """ def list_users(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListUsers", method: :post, input_shape: "ListUsersRequest", output_shape: "ListUsersResponse", endpoint: __spec__() } end @doc """ Adds additional user attributes to the user pool schema. """ def add_custom_attributes(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AddCustomAttributes", method: :post, input_shape: "AddCustomAttributesRequest", output_shape: "AddCustomAttributesResponse", endpoint: __spec__() } end @doc """ Deletes a domain for a user pool. """ def delete_user_pool_domain(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteUserPoolDomain", method: :post, input_shape: "DeleteUserPoolDomainRequest", output_shape: "DeleteUserPoolDomainResponse", endpoint: __spec__() } end @doc """ Lists the groups associated with a user pool. Requires developer credentials. """ def list_groups(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListGroups", method: :post, input_shape: "ListGroupsRequest", output_shape: "ListGroupsResponse", endpoint: __spec__() } end @doc """ Client method for returning the configuration information and metadata of the specified user pool client. """ def describe_user_pool_client(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DescribeUserPoolClient", method: :post, input_shape: "DescribeUserPoolClientRequest", output_shape: "DescribeUserPoolClientResponse", endpoint: __spec__() } end @doc """ Updates identity provider information for a user pool. """ def update_identity_provider(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateIdentityProvider", method: :post, input_shape: "UpdateIdentityProviderRequest", output_shape: "UpdateIdentityProviderResponse", endpoint: __spec__() } end @doc """ Allows a user to enter a confirmation code to reset a forgotten password. """ def confirm_forgot_password(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ConfirmForgotPassword", method: :post, input_shape: "ConfirmForgotPasswordRequest", output_shape: "ConfirmForgotPasswordResponse", endpoint: __spec__() } end @doc """ Resets the specified user's password in a user pool as an administrator. Works on any user. When a developer calls this API, the current password is invalidated, so it must be changed. If a user tries to sign in after the API is called, the app will get a PasswordResetRequiredException exception back and should direct the user down the flow to reset the password, which is the same as the forgot password flow. In addition, if the user pool has phone verification selected and a verified phone number exists for the user, or if email verification is selected and a verified email exists for the user, calling this API will also result in sending a message to the end user with the code to change their password. Requires developer credentials. """ def admin_reset_user_password(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminResetUserPassword", method: :post, input_shape: "AdminResetUserPasswordRequest", output_shape: "AdminResetUserPasswordResponse", endpoint: __spec__() } end @doc """ Lists the users in the specified group. Requires developer credentials. """ def list_users_in_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ListUsersInGroup", method: :post, input_shape: "ListUsersInGroupRequest", output_shape: "ListUsersInGroupResponse", endpoint: __spec__() } end @doc """ Gets information about a specific identity provider. """ def describe_identity_provider(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DescribeIdentityProvider", method: :post, input_shape: "DescribeIdentityProviderRequest", output_shape: "DescribeIdentityProviderResponse", endpoint: __spec__() } end @doc """ Links an existing user account in a user pool (`DestinationUser`) to an identity from an external identity provider (`SourceUser`) based on a specified attribute name and value from the external identity provider. This allows you to create a link from the existing user account to an external federated user identity that has not yet been used to sign in, so that the federated user identity can be used to sign in as the existing user account. For example, if there is an existing user with a username and password, this API links that user to a federated user identity, so that when the federated user identity is used, the user signs in as the existing user account. <important> Because this API allows a user with an external federated identity to sign in as an existing user in the user pool, it is critical that it only be used with external identity providers and provider attributes that have been trusted by the application owner. </important> See also [AdminDisableProviderForUser](API_AdminDisableProviderForUser.html). This action is enabled only for admin access and requires developer credentials. """ def admin_link_provider_for_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminLinkProviderForUser", method: :post, input_shape: "AdminLinkProviderForUserRequest", output_shape: "AdminLinkProviderForUserResponse", endpoint: __spec__() } end @doc """ Creates a new OAuth2.0 resource server and defines custom scopes in it. """ def create_resource_server(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateResourceServer", method: :post, input_shape: "CreateResourceServerRequest", output_shape: "CreateResourceServerResponse", endpoint: __spec__() } end @doc """ Sets the user settings like multi-factor authentication (MFA). If MFA is to be removed for a particular attribute pass the attribute with code delivery as null. If null list is passed, all MFA options are removed. """ def set_user_settings(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "SetUserSettings", method: :post, input_shape: "SetUserSettingsRequest", output_shape: "SetUserSettingsResponse", endpoint: __spec__() } end @doc """ Updates the name and scopes of resource server. All other fields are read-only. """ def update_resource_server(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateResourceServer", method: :post, input_shape: "UpdateResourceServerRequest", output_shape: "UpdateResourceServerResponse", endpoint: __spec__() } end @doc """ Allows the developer to update the specified user pool client and password policy. """ def update_user_pool_client(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateUserPoolClient", method: :post, input_shape: "UpdateUserPoolClientRequest", output_shape: "UpdateUserPoolClientResponse", endpoint: __spec__() } end @doc """ Signs out users from all devices. """ def global_sign_out(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GlobalSignOut", method: :post, input_shape: "GlobalSignOutRequest", output_shape: "GlobalSignOutResponse", endpoint: __spec__() } end @doc """ Confirms registration of a user and handles the existing alias from a previous user. """ def confirm_sign_up(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ConfirmSignUp", method: :post, input_shape: "ConfirmSignUpRequest", output_shape: "ConfirmSignUpResponse", endpoint: __spec__() } end @doc """ Confirms user registration as an admin without using a confirmation code. Works on any user. Requires developer credentials. """ def admin_confirm_sign_up(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminConfirmSignUp", method: :post, input_shape: "AdminConfirmSignUpRequest", output_shape: "AdminConfirmSignUpResponse", endpoint: __spec__() } end @doc """ Gets information about a domain. """ def describe_user_pool_domain(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DescribeUserPoolDomain", method: :post, input_shape: "DescribeUserPoolDomainRequest", output_shape: "DescribeUserPoolDomainResponse", endpoint: __spec__() } end @doc """ Describes the user import job. """ def describe_user_import_job(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DescribeUserImportJob", method: :post, input_shape: "DescribeUserImportJobRequest", output_shape: "DescribeUserImportJobResponse", endpoint: __spec__() } end @doc """ Updates the specified group with the specified attributes. Requires developer credentials. """ def update_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "UpdateGroup", method: :post, input_shape: "UpdateGroupRequest", output_shape: "UpdateGroupResponse", endpoint: __spec__() } end @doc """ Registers the user in the specified user pool and creates a user name, password, and user attributes. """ def sign_up(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "SignUp", method: :post, input_shape: "SignUpRequest", output_shape: "SignUpResponse", endpoint: __spec__() } end @doc """ Deletes the specified Amazon Cognito user pool. """ def delete_user_pool(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "DeleteUserPool", method: :post, input_shape: "DeleteUserPoolRequest", output_shape: "", endpoint: __spec__() } end @doc """ Creates a new group in the specified user pool. Requires developer credentials. """ def create_group(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "CreateGroup", method: :post, input_shape: "CreateGroupRequest", output_shape: "CreateGroupResponse", endpoint: __spec__() } end @doc """ Verifies the specified user attributes in the user pool. """ def verify_user_attribute(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "VerifyUserAttribute", method: :post, input_shape: "VerifyUserAttributeRequest", output_shape: "VerifyUserAttributeResponse", endpoint: __spec__() } end @doc """ Calling this API causes a message to be sent to the end user with a confirmation code that is required to change the user's password. For the `Username` parameter, you can use the username or user alias. If a verified phone number exists for the user, the confirmation code is sent to the phone number. Otherwise, if a verified email exists, the confirmation code is sent to the email. If neither a verified phone number nor a verified email exists, `InvalidParameterException` is thrown. To use the confirmation code for resetting the password, call [ConfirmForgotPassword](API_ConfirmForgotPassword.html). """ def forgot_password(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "ForgotPassword", method: :post, input_shape: "ForgotPasswordRequest", output_shape: "ForgotPasswordResponse", endpoint: __spec__() } end @doc """ Disables the specified user as an administrator. Works on any user. Requires developer credentials. """ def admin_disable_user(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminDisableUser", method: :post, input_shape: "AdminDisableUserRequest", output_shape: "AdminDisableUserResponse", endpoint: __spec__() } end @doc """ Gets the device, as an administrator. Requires developer credentials. """ def admin_get_device(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "AdminGetDevice", method: :post, input_shape: "AdminGetDeviceRequest", output_shape: "AdminGetDeviceResponse", endpoint: __spec__() } end @doc """ Gets the UI Customization information for a particular app client's app UI, if there is something set. If nothing is set for the particular client, but there is an existing pool level customization (app `clientId` will be `ALL`), then that is returned. If nothing is present, then an empty shape is returned. """ def get_u_i_customization(input \\ %{}, options \\ []) do %Baiji.Operation{ path: "/", input: input, options: options, action: "GetUICustomization", method: :post, input_shape: "GetUICustomizationRequest", output_shape: "GetUICustomizationResponse", endpoint: __spec__() } end @doc """ Outputs values common to all actions """ def __spec__ do %Baiji.Endpoint{ service: "cognito-idp", target_prefix: "AWSCognitoIdentityProviderService", endpoint_prefix: "cognito-idp", type: :json, version: "2016-04-18", shapes: __shapes__() } end @doc """ Returns a map containing the input/output shapes for this endpoint """ def __shapes__ do %{"ForceAliasCreation" => %{"type" => "boolean"}, "PoolQueryLimitType" => %{"max" => 60, "min" => 1, "type" => "integer"}, "ListDevicesRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "Limit" => %{"shape" => "QueryLimitType"}, "PaginationToken" => %{"shape" => "SearchPaginationTokenType"}}, "required" => ["AccessToken"], "type" => "structure"}, "ConfirmDeviceResponse" => %{"members" => %{"UserConfirmationNecessary" => %{"shape" => "BooleanType"}}, "type" => "structure"}, "DescriptionType" => %{"max" => 2048, "type" => "string"}, "GroupType" => %{"members" => %{"CreationDate" => %{"shape" => "DateType"}, "Description" => %{"shape" => "DescriptionType"}, "GroupName" => %{"shape" => "GroupNameType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "Precedence" => %{"shape" => "PrecedenceType"}, "RoleArn" => %{"shape" => "ArnType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "AdminUpdateUserAttributesResponse" => %{"members" => %{}, "type" => "structure"}, "OAuthFlowType" => %{"enum" => ["code", "implicit", "client_credentials"], "type" => "string"}, "AdminUserGlobalSignOutRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "DeleteUserPoolClientRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ClientId"], "type" => "structure"}, "CreateUserPoolClientRequest" => %{"members" => %{"AllowedOAuthFlows" => %{"shape" => "OAuthFlowsType"}, "AllowedOAuthFlowsUserPoolClient" => %{"shape" => "BooleanType"}, "AllowedOAuthScopes" => %{"shape" => "ScopeListType"}, "CallbackURLs" => %{"shape" => "CallbackURLsListType"}, "ClientName" => %{"shape" => "ClientNameType"}, "DefaultRedirectURI" => %{"shape" => "RedirectUrlType"}, "ExplicitAuthFlows" => %{"shape" => "ExplicitAuthFlowsListType"}, "GenerateSecret" => %{"shape" => "GenerateSecret"}, "LogoutURLs" => %{"shape" => "LogoutURLsListType"}, "ReadAttributes" => %{"shape" => "ClientPermissionListType"}, "RefreshTokenValidity" => %{"shape" => "RefreshTokenValidityType"}, "SupportedIdentityProviders" => %{"shape" => "SupportedIdentityProvidersListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "WriteAttributes" => %{"shape" => "ClientPermissionListType"}}, "required" => ["UserPoolId", "ClientName"], "type" => "structure"}, "UsernameType" => %{"max" => 128, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "sensitive" => true, "type" => "string"}, "AliasExistsException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "DescribeUserPoolClientResponse" => %{"members" => %{"UserPoolClient" => %{"shape" => "UserPoolClientType"}}, "type" => "structure"}, "DescribeUserPoolResponse" => %{"members" => %{"UserPool" => %{"shape" => "UserPoolType"}}, "type" => "structure"}, "AddCustomAttributesRequest" => %{"members" => %{"CustomAttributes" => %{"shape" => "CustomAttributesListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "CustomAttributes"], "type" => "structure"}, "SearchPaginationTokenType" => %{"min" => 1, "pattern" => "[\\S]+", "type" => "string"}, "ListUsersInGroupRequest" => %{"members" => %{"GroupName" => %{"shape" => "GroupNameType"}, "Limit" => %{"shape" => "QueryLimitType"}, "NextToken" => %{"shape" => "PaginationKey"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "GroupName"], "type" => "structure"}, "SmsConfigurationType" => %{"members" => %{"ExternalId" => %{"shape" => "StringType"}, "SnsCallerArn" => %{"shape" => "ArnType"}}, "required" => ["SnsCallerArn"], "type" => "structure"}, "UpdateGroupRequest" => %{"members" => %{"Description" => %{"shape" => "DescriptionType"}, "GroupName" => %{"shape" => "GroupNameType"}, "Precedence" => %{"shape" => "PrecedenceType"}, "RoleArn" => %{"shape" => "ArnType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["GroupName", "UserPoolId"], "type" => "structure"}, "AdminConfirmSignUpResponse" => %{"members" => %{}, "type" => "structure"}, "ResourceServerNameType" => %{"max" => 256, "min" => 1, "pattern" => "[\\w\\s+=,.@-]+", "type" => "string"}, "InvalidParameterException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AttributeMappingKeyType" => %{"max" => 32, "min" => 1, "type" => "string"}, "UserPoolTaggingException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AWSAccountIdType" => %{"type" => "string"}, "SetUICustomizationResponse" => %{"members" => %{"UICustomization" => %{"shape" => "UICustomizationType"}}, "required" => ["UICustomization"], "type" => "structure"}, "UpdateDeviceStatusResponse" => %{"members" => %{}, "type" => "structure"}, "VerifiedAttributesListType" => %{"member" => %{"shape" => "VerifiedAttributeType"}, "type" => "list"}, "UserImportJobsListType" => %{"max" => 50, "member" => %{"shape" => "UserImportJobType"}, "min" => 1, "type" => "list"}, "CodeDeliveryDetailsType" => %{"members" => %{"AttributeName" => %{"shape" => "AttributeNameType"}, "DeliveryMedium" => %{"shape" => "DeliveryMediumType"}, "Destination" => %{"shape" => "StringType"}}, "type" => "structure"}, "AdminListGroupsForUserRequest" => %{"members" => %{"Limit" => %{"shape" => "QueryLimitType"}, "NextToken" => %{"shape" => "PaginationKey"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["Username", "UserPoolId"], "type" => "structure"}, "ListUserPoolsRequest" => %{"members" => %{"MaxResults" => %{"shape" => "PoolQueryLimitType"}, "NextToken" => %{"shape" => "PaginationKeyType"}}, "required" => ["MaxResults"], "type" => "structure"}, "GetDeviceResponse" => %{"members" => %{"Device" => %{"shape" => "DeviceType"}}, "required" => ["Device"], "type" => "structure"}, "ScopeListType" => %{"max" => 25, "member" => %{"shape" => "ScopeType"}, "type" => "list"}, "AdminRespondToAuthChallengeRequest" => %{"members" => %{"ChallengeName" => %{"shape" => "ChallengeNameType"}, "ChallengeResponses" => %{"shape" => "ChallengeResponsesType"}, "ClientId" => %{"shape" => "ClientIdType"}, "Session" => %{"shape" => "SessionType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ClientId", "ChallengeName"], "type" => "structure"}, "DeleteGroupRequest" => %{"members" => %{"GroupName" => %{"shape" => "GroupNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["GroupName", "UserPoolId"], "type" => "structure"}, "InvalidOAuthFlowException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "UserPoolDescriptionType" => %{"members" => %{"CreationDate" => %{"shape" => "DateType"}, "Id" => %{"shape" => "UserPoolIdType"}, "LambdaConfig" => %{"shape" => "LambdaConfigType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "Name" => %{"shape" => "UserPoolNameType"}, "Status" => %{"shape" => "StatusType"}}, "type" => "structure"}, "UpdateDeviceStatusRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "DeviceKey" => %{"shape" => "DeviceKeyType"}, "DeviceRememberedStatus" => %{"shape" => "DeviceRememberedStatusType"}}, "required" => ["AccessToken", "DeviceKey"], "type" => "structure"}, "GenerateSecret" => %{"type" => "boolean"}, "AdminDisableProviderForUserResponse" => %{"members" => %{}, "type" => "structure"}, "DeleteUserPoolRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "VerifyUserAttributeResponse" => %{"members" => %{}, "type" => "structure"}, "DefaultEmailOptionType" => %{"enum" => ["CONFIRM_WITH_LINK", "CONFIRM_WITH_CODE"], "type" => "string"}, "CreateResourceServerResponse" => %{"members" => %{"ResourceServer" => %{"shape" => "ResourceServerType"}}, "required" => ["ResourceServer"], "type" => "structure"}, "InvalidPasswordException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "GetIdentityProviderByIdentifierResponse" => %{"members" => %{"IdentityProvider" => %{"shape" => "IdentityProviderType"}}, "required" => ["IdentityProvider"], "type" => "structure"}, "DeleteUserPoolDomainRequest" => %{"members" => %{"Domain" => %{"shape" => "DomainType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["Domain", "UserPoolId"], "type" => "structure"}, "ProviderNameType" => %{"max" => 32, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "type" => "string"}, "DeviceType" => %{"members" => %{"DeviceAttributes" => %{"shape" => "AttributeListType"}, "DeviceCreateDate" => %{"shape" => "DateType"}, "DeviceKey" => %{"shape" => "DeviceKeyType"}, "DeviceLastAuthenticatedDate" => %{"shape" => "DateType"}, "DeviceLastModifiedDate" => %{"shape" => "DateType"}}, "type" => "structure"}, "CodeMismatchException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "QueryLimit" => %{"max" => 60, "min" => 1, "type" => "integer"}, "AdminCreateUserRequest" => %{"members" => %{"DesiredDeliveryMediums" => %{"shape" => "DeliveryMediumListType"}, "ForceAliasCreation" => %{"shape" => "ForceAliasCreation"}, "MessageAction" => %{"shape" => "MessageActionType"}, "TemporaryPassword" => %{"shape" => "PasswordType"}, "UserAttributes" => %{"shape" => "AttributeListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}, "ValidationData" => %{"shape" => "AttributeListType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "ListProvidersLimitType" => %{"max" => 60, "min" => 1, "type" => "integer"}, "IdentityProviderType" => %{"members" => %{"AttributeMapping" => %{"shape" => "AttributeMappingType"}, "CreationDate" => %{"shape" => "DateType"}, "IdpIdentifiers" => %{"shape" => "IdpIdentifiersListType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "ProviderDetails" => %{"shape" => "ProviderDetailsType"}, "ProviderName" => %{"shape" => "ProviderNameType"}, "ProviderType" => %{"shape" => "IdentityProviderTypeType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "UpdateUserAttributesResponse" => %{"members" => %{"CodeDeliveryDetailsList" => %{"shape" => "CodeDeliveryDetailsListType"}}, "type" => "structure"}, "AdminConfirmSignUpRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "DeviceConfigurationType" => %{"members" => %{"ChallengeRequiredOnNewDevice" => %{"shape" => "BooleanType"}, "DeviceOnlyRememberedOnUserPrompt" => %{"shape" => "BooleanType"}}, "type" => "structure"}, "CSSVersionType" => %{"type" => "string"}, "MessageTemplateType" => %{"members" => %{"EmailMessage" => %{"shape" => "EmailVerificationMessageType"}, "EmailSubject" => %{"shape" => "EmailVerificationSubjectType"}, "SMSMessage" => %{"shape" => "SmsVerificationMessageType"}}, "type" => "structure"}, "UserPoolType" => %{"members" => %{"AdminCreateUserConfig" => %{"shape" => "AdminCreateUserConfigType"}, "AliasAttributes" => %{"shape" => "AliasAttributesListType"}, "AutoVerifiedAttributes" => %{"shape" => "VerifiedAttributesListType"}, "CreationDate" => %{"shape" => "DateType"}, "DeviceConfiguration" => %{"shape" => "DeviceConfigurationType"}, "EmailConfiguration" => %{"shape" => "EmailConfigurationType"}, "EmailConfigurationFailure" => %{"shape" => "StringType"}, "EmailVerificationMessage" => %{"shape" => "EmailVerificationMessageType"}, "EmailVerificationSubject" => %{"shape" => "EmailVerificationSubjectType"}, "EstimatedNumberOfUsers" => %{"shape" => "IntegerType"}, "Id" => %{"shape" => "UserPoolIdType"}, "LambdaConfig" => %{"shape" => "LambdaConfigType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "MfaConfiguration" => %{"shape" => "UserPoolMfaType"}, "Name" => %{"shape" => "UserPoolNameType"}, "Policies" => %{"shape" => "UserPoolPolicyType"}, "SchemaAttributes" => %{"shape" => "SchemaAttributesListType"}, "SmsAuthenticationMessage" => %{"shape" => "SmsVerificationMessageType"}, "SmsConfiguration" => %{"shape" => "SmsConfigurationType"}, "SmsConfigurationFailure" => %{"shape" => "StringType"}, "SmsVerificationMessage" => %{"shape" => "SmsVerificationMessageType"}, "Status" => %{"shape" => "StatusType"}, "UserPoolTags" => %{"shape" => "UserPoolTagsType"}, "UsernameAttributes" => %{"shape" => "UsernameAttributesListType"}, "VerificationMessageTemplate" => %{"shape" => "VerificationMessageTemplateType"}}, "type" => "structure"}, "DomainType" => %{"max" => 63, "min" => 1, "pattern" => "^[a-z0-9](?:[a-z0-9\\-]{0,61}[a-z0-9])?$", "type" => "string"}, "DeviceKeyType" => %{"max" => 55, "min" => 1, "pattern" => "[\\w-]+_[0-9a-f-]+", "type" => "string"}, "GroupListType" => %{"member" => %{"shape" => "GroupType"}, "type" => "list"}, "UserImportJobStatusType" => %{"enum" => ["Created", "Pending", "InProgress", "Stopping", "Expired", "Stopped", "Failed", "Succeeded"], "type" => "string"}, "ClientNameType" => %{"max" => 128, "min" => 1, "pattern" => "[\\w\\s+=,.@-]+", "type" => "string"}, "StatusType" => %{"enum" => ["Enabled", "Disabled"], "type" => "string"}, "GlobalSignOutResponse" => %{"members" => %{}, "type" => "structure"}, "ConfirmationCodeType" => %{"max" => 2048, "min" => 1, "pattern" => "[\\S]+", "type" => "string"}, "UserPoolListType" => %{"member" => %{"shape" => "UserPoolDescriptionType"}, "type" => "list"}, "VerifyUserAttributeRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "AttributeName" => %{"shape" => "AttributeNameType"}, "Code" => %{"shape" => "ConfirmationCodeType"}}, "required" => ["AccessToken", "AttributeName", "Code"], "type" => "structure"}, "DeviceNameType" => %{"max" => 1024, "min" => 1, "type" => "string"}, "UpdateUserPoolResponse" => %{"members" => %{}, "type" => "structure"}, "InvalidSmsRoleAccessPolicyException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ChangePasswordResponse" => %{"members" => %{}, "type" => "structure"}, "LogoutURLsListType" => %{"max" => 100, "member" => %{"shape" => "RedirectUrlType"}, "min" => 0, "type" => "list"}, "GetUserRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}}, "required" => ["AccessToken"], "type" => "structure"}, "AdminInitiateAuthResponse" => %{"members" => %{"AuthenticationResult" => %{"shape" => "AuthenticationResultType"}, "ChallengeName" => %{"shape" => "ChallengeNameType"}, "ChallengeParameters" => %{"shape" => "ChallengeParametersType"}, "Session" => %{"shape" => "SessionType"}}, "type" => "structure"}, "GroupNameType" => %{"max" => 128, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "type" => "string"}, "VerifiedAttributeType" => %{"enum" => ["phone_number", "email"], "type" => "string"}, "NumberAttributeConstraintsType" => %{"members" => %{"MaxValue" => %{"shape" => "StringType"}, "MinValue" => %{"shape" => "StringType"}}, "type" => "structure"}, "ResourceServerScopeNameType" => %{"max" => 256, "min" => 1, "pattern" => "[\\x21\\x23-\\x2E\\x30-\\x5B\\x5D-\\x7E]+", "type" => "string"}, "AdminForgetDeviceRequest" => %{"members" => %{"DeviceKey" => %{"shape" => "DeviceKeyType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "DeviceKey"], "type" => "structure"}, "MFAMethodNotFoundException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ListGroupsResponse" => %{"members" => %{"Groups" => %{"shape" => "GroupListType"}, "NextToken" => %{"shape" => "PaginationKey"}}, "type" => "structure"}, "AdminDeleteUserAttributesResponse" => %{"members" => %{}, "type" => "structure"}, "AdminDisableUserResponse" => %{"members" => %{}, "type" => "structure"}, "CreateUserImportJobResponse" => %{"members" => %{"UserImportJob" => %{"shape" => "UserImportJobType"}}, "type" => "structure"}, "SearchedAttributeNamesListType" => %{"member" => %{"shape" => "AttributeNameType"}, "type" => "list"}, "UsernameExistsException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminResetUserPasswordResponse" => %{"members" => %{}, "type" => "structure"}, "AdminGetDeviceRequest" => %{"members" => %{"DeviceKey" => %{"shape" => "DeviceKeyType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["DeviceKey", "UserPoolId", "Username"], "type" => "structure"}, "TooManyRequestsException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "IdpIdentifiersListType" => %{"max" => 50, "member" => %{"shape" => "IdpIdentifierType"}, "min" => 0, "type" => "list"}, "GetCSVHeaderResponse" => %{"members" => %{"CSVHeader" => %{"shape" => "ListOfStringTypes"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "AdminResetUserPasswordRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "UsernameAttributeType" => %{"enum" => ["phone_number", "email"], "type" => "string"}, "ExplicitAuthFlowsListType" => %{"member" => %{"shape" => "ExplicitAuthFlowsType"}, "type" => "list"}, "DeleteResourceServerRequest" => %{"members" => %{"Identifier" => %{"shape" => "ResourceServerIdentifierType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "Identifier"], "type" => "structure"}, "ConfirmForgotPasswordResponse" => %{"members" => %{}, "type" => "structure"}, "ProviderDetailsType" => %{"key" => %{"shape" => "StringType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "ResendConfirmationCodeRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "SecretHash" => %{"shape" => "SecretHashType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["ClientId", "Username"], "type" => "structure"}, "DeliveryMediumListType" => %{"member" => %{"shape" => "DeliveryMediumType"}, "type" => "list"}, "UnsupportedUserStateException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "UserPoolMfaType" => %{"enum" => ["OFF", "ON", "OPTIONAL"], "type" => "string"}, "AdminListDevicesRequest" => %{"members" => %{"Limit" => %{"shape" => "QueryLimitType"}, "PaginationToken" => %{"shape" => "SearchPaginationTokenType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "UpdateUserPoolRequest" => %{"members" => %{"AdminCreateUserConfig" => %{"shape" => "AdminCreateUserConfigType"}, "AutoVerifiedAttributes" => %{"shape" => "VerifiedAttributesListType"}, "DeviceConfiguration" => %{"shape" => "DeviceConfigurationType"}, "EmailConfiguration" => %{"shape" => "EmailConfigurationType"}, "EmailVerificationMessage" => %{"shape" => "EmailVerificationMessageType"}, "EmailVerificationSubject" => %{"shape" => "EmailVerificationSubjectType"}, "LambdaConfig" => %{"shape" => "LambdaConfigType"}, "MfaConfiguration" => %{"shape" => "UserPoolMfaType"}, "Policies" => %{"shape" => "UserPoolPolicyType"}, "SmsAuthenticationMessage" => %{"shape" => "SmsVerificationMessageType"}, "SmsConfiguration" => %{"shape" => "SmsConfigurationType"}, "SmsVerificationMessage" => %{"shape" => "SmsVerificationMessageType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "UserPoolTags" => %{"shape" => "UserPoolTagsType"}, "VerificationMessageTemplate" => %{"shape" => "VerificationMessageTemplateType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "SessionType" => %{"max" => 2048, "min" => 20, "type" => "string"}, "GetGroupRequest" => %{"members" => %{"GroupName" => %{"shape" => "GroupNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["GroupName", "UserPoolId"], "type" => "structure"}, "DeviceRememberedStatusType" => %{"enum" => ["remembered", "not_remembered"], "type" => "string"}, "ImageFileType" => %{"type" => "blob"}, "ResourceServerIdentifierType" => %{"max" => 256, "min" => 1, "pattern" => "[\\x21\\x23-\\x5B\\x5D-\\x7E]+", "type" => "string"}, "SchemaAttributeType" => %{"members" => %{"AttributeDataType" => %{"shape" => "AttributeDataType"}, "DeveloperOnlyAttribute" => %{"box" => true, "shape" => "BooleanType"}, "Mutable" => %{"box" => true, "shape" => "BooleanType"}, "Name" => %{"shape" => "CustomAttributeNameType"}, "NumberAttributeConstraints" => %{"shape" => "NumberAttributeConstraintsType"}, "Required" => %{"box" => true, "shape" => "BooleanType"}, "StringAttributeConstraints" => %{"shape" => "StringAttributeConstraintsType"}}, "type" => "structure"}, "CreateGroupRequest" => %{"members" => %{"Description" => %{"shape" => "DescriptionType"}, "GroupName" => %{"shape" => "GroupNameType"}, "Precedence" => %{"shape" => "PrecedenceType"}, "RoleArn" => %{"shape" => "ArnType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["GroupName", "UserPoolId"], "type" => "structure"}, "EmailVerificationMessageType" => %{"max" => 20000, "min" => 6, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*\\{####\\}[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*", "type" => "string"}, "EmailAddressType" => %{"pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+@[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "type" => "string"}, "LambdaConfigType" => %{"members" => %{"CreateAuthChallenge" => %{"shape" => "ArnType"}, "CustomMessage" => %{"shape" => "ArnType"}, "DefineAuthChallenge" => %{"shape" => "ArnType"}, "PostAuthentication" => %{"shape" => "ArnType"}, "PostConfirmation" => %{"shape" => "ArnType"}, "PreAuthentication" => %{"shape" => "ArnType"}, "PreSignUp" => %{"shape" => "ArnType"}, "VerifyAuthChallengeResponse" => %{"shape" => "ArnType"}}, "type" => "structure"}, "OAuthFlowsType" => %{"max" => 3, "member" => %{"shape" => "OAuthFlowType"}, "min" => 0, "type" => "list"}, "ListIdentityProvidersResponse" => %{"members" => %{"NextToken" => %{"shape" => "PaginationKeyType"}, "Providers" => %{"shape" => "ProvidersListType"}}, "required" => ["Providers"], "type" => "structure"}, "AdminLinkProviderForUserResponse" => %{"members" => %{}, "type" => "structure"}, "SetUICustomizationRequest" => %{"members" => %{"CSS" => %{"shape" => "CSSType"}, "ClientId" => %{"shape" => "ClientIdType"}, "ImageFile" => %{"shape" => "ImageFileType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "GetUICustomizationResponse" => %{"members" => %{"UICustomization" => %{"shape" => "UICustomizationType"}}, "required" => ["UICustomization"], "type" => "structure"}, "UserStatusType" => %{"enum" => ["UNCONFIRMED", "CONFIRMED", "ARCHIVED", "COMPROMISED", "UNKNOWN", "RESET_REQUIRED", "FORCE_CHANGE_PASSWORD"], "type" => "string"}, "StringAttributeConstraintsType" => %{"members" => %{"MaxLength" => %{"shape" => "StringType"}, "MinLength" => %{"shape" => "StringType"}}, "type" => "structure"}, "UserNotFoundException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ForgotPasswordRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "SecretHash" => %{"shape" => "SecretHashType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["ClientId", "Username"], "type" => "structure"}, "CreateUserPoolResponse" => %{"members" => %{"UserPool" => %{"shape" => "UserPoolType"}}, "type" => "structure"}, "GetUserResponse" => %{"members" => %{"MFAOptions" => %{"shape" => "MFAOptionListType"}, "UserAttributes" => %{"shape" => "AttributeListType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["Username", "UserAttributes"], "type" => "structure"}, "DescribeResourceServerRequest" => %{"members" => %{"Identifier" => %{"shape" => "ResourceServerIdentifierType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "Identifier"], "type" => "structure"}, "IntegerType" => %{"type" => "integer"}, "GetDeviceRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "DeviceKey" => %{"shape" => "DeviceKeyType"}}, "required" => ["DeviceKey"], "type" => "structure"}, "CreateUserImportJobRequest" => %{"members" => %{"CloudWatchLogsRoleArn" => %{"shape" => "ArnType"}, "JobName" => %{"shape" => "UserImportJobNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["JobName", "UserPoolId", "CloudWatchLogsRoleArn"], "type" => "structure"}, "ClientPermissionType" => %{"max" => 2048, "min" => 1, "type" => "string"}, "MessageActionType" => %{"enum" => ["RESEND", "SUPPRESS"], "type" => "string"}, "AliasAttributeType" => %{"enum" => ["phone_number", "email", "preferred_username"], "type" => "string"}, "ListUserImportJobsResponse" => %{"members" => %{"PaginationToken" => %{"shape" => "PaginationKeyType"}, "UserImportJobs" => %{"shape" => "UserImportJobsListType"}}, "type" => "structure"}, "AttributeNameType" => %{"max" => 32, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "type" => "string"}, "RespondToAuthChallengeRequest" => %{"members" => %{"ChallengeName" => %{"shape" => "ChallengeNameType"}, "ChallengeResponses" => %{"shape" => "ChallengeResponsesType"}, "ClientId" => %{"shape" => "ClientIdType"}, "Session" => %{"shape" => "SessionType"}}, "required" => ["ClientId", "ChallengeName"], "type" => "structure"}, "InvalidLambdaResponseException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminDisableProviderForUserRequest" => %{"members" => %{"User" => %{"shape" => "ProviderUserIdentifierType"}, "UserPoolId" => %{"shape" => "StringType"}}, "required" => ["UserPoolId", "User"], "type" => "structure"}, "UpdateIdentityProviderResponse" => %{"members" => %{"IdentityProvider" => %{"shape" => "IdentityProviderType"}}, "required" => ["IdentityProvider"], "type" => "structure"}, "UpdateUserPoolClientResponse" => %{"members" => %{"UserPoolClient" => %{"shape" => "UserPoolClientType"}}, "type" => "structure"}, "AliasAttributesListType" => %{"member" => %{"shape" => "AliasAttributeType"}, "type" => "list"}, "AdminGetUserRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "StopUserImportJobRequest" => %{"members" => %{"JobId" => %{"shape" => "UserImportJobIdType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "JobId"], "type" => "structure"}, "GetCSVHeaderRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "SignUpRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "Password" => %{"shape" => "PasswordType"}, "SecretHash" => %{"shape" => "SecretHashType"}, "UserAttributes" => %{"shape" => "AttributeListType"}, "Username" => %{"shape" => "UsernameType"}, "ValidationData" => %{"shape" => "AttributeListType"}}, "required" => ["ClientId", "Username", "Password"], "type" => "structure"}, "AdminDeleteUserAttributesRequest" => %{"members" => %{"UserAttributeNames" => %{"shape" => "AttributeNameListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "UserAttributeNames"], "type" => "structure"}, "ChallengeNameType" => %{"enum" => ["SMS_MFA", "PASSWORD_VERIFIER", "CUSTOM_CHALLENGE", "DEVICE_SRP_AUTH", "DEVICE_PASSWORD_VERIFIER", "ADMIN_NO_SRP_AUTH", "NEW_PASSWORD_REQUIRED"], "type" => "string"}, "SetUserSettingsRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "MFAOptions" => %{"shape" => "MFAOptionListType"}}, "required" => ["AccessToken", "MFAOptions"], "type" => "structure"}, "InternalErrorException" => %{"exception" => true, "fault" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminUserGlobalSignOutResponse" => %{"members" => %{}, "type" => "structure"}, "SecretHashType" => %{"max" => 128, "min" => 1, "pattern" => "[\\w+=/]+", "sensitive" => true, "type" => "string"}, "AttributeDataType" => %{"enum" => ["String", "Number", "DateTime", "Boolean"], "type" => "string"}, "DomainStatusType" => %{"enum" => ["CREATING", "DELETING", "UPDATING", "ACTIVE", "FAILED"], "type" => "string"}, "DuplicateProviderException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ListOfStringTypes" => %{"member" => %{"shape" => "StringType"}, "type" => "list"}, "UserFilterType" => %{"max" => 256, "type" => "string"}, "AdminCreateUserConfigType" => %{"members" => %{"AllowAdminCreateUserOnly" => %{"shape" => "BooleanType"}, "InviteMessageTemplate" => %{"shape" => "MessageTemplateType"}, "UnusedAccountValidityDays" => %{"shape" => "AdminCreateUserUnusedAccountValidityDaysType"}}, "type" => "structure"}, "UpdateGroupResponse" => %{"members" => %{"Group" => %{"shape" => "GroupType"}}, "type" => "structure"}, "AttributeType" => %{"members" => %{"Name" => %{"shape" => "AttributeNameType"}, "Value" => %{"shape" => "AttributeValueType"}}, "required" => ["Name"], "type" => "structure"}, "UserPoolTagsType" => %{"key" => %{"shape" => "StringType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "IdentityProviderTypeType" => %{"enum" => ["SAML", "Facebook", "Google", "LoginWithAmazon"], "type" => "string"}, "SchemaAttributesListType" => %{"max" => 50, "member" => %{"shape" => "SchemaAttributeType"}, "min" => 1, "type" => "list"}, "PasswordType" => %{"max" => 256, "min" => 6, "pattern" => "[\\S]+", "sensitive" => true, "type" => "string"}, "GetGroupResponse" => %{"members" => %{"Group" => %{"shape" => "GroupType"}}, "type" => "structure"}, "MFAOptionListType" => %{"member" => %{"shape" => "MFAOptionType"}, "type" => "list"}, "DescribeUserPoolClientRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ClientId"], "type" => "structure"}, "ListResourceServersLimitType" => %{"max" => 50, "min" => 1, "type" => "integer"}, "CodeDeliveryDetailsListType" => %{"member" => %{"shape" => "CodeDeliveryDetailsType"}, "type" => "list"}, "ProviderUserIdentifierType" => %{"members" => %{"ProviderAttributeName" => %{"shape" => "StringType"}, "ProviderAttributeValue" => %{"shape" => "StringType"}, "ProviderName" => %{"shape" => "ProviderNameType"}}, "type" => "structure"}, "SupportedIdentityProvidersListType" => %{"member" => %{"shape" => "ProviderNameType"}, "type" => "list"}, "UserPoolPolicyType" => %{"members" => %{"PasswordPolicy" => %{"shape" => "PasswordPolicyType"}}, "type" => "structure"}, "GetUserAttributeVerificationCodeRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "AttributeName" => %{"shape" => "AttributeNameType"}}, "required" => ["AccessToken", "AttributeName"], "type" => "structure"}, "ListUserPoolsResponse" => %{"members" => %{"NextToken" => %{"shape" => "PaginationKeyType"}, "UserPools" => %{"shape" => "UserPoolListType"}}, "type" => "structure"}, "ChallengeParametersType" => %{"key" => %{"shape" => "StringType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "AdminEnableUserRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "UsernameAttributesListType" => %{"member" => %{"shape" => "UsernameAttributeType"}, "type" => "list"}, "DescribeIdentityProviderRequest" => %{"members" => %{"ProviderName" => %{"shape" => "ProviderNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ProviderName"], "type" => "structure"}, "UnsupportedIdentityProviderException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminCreateUserResponse" => %{"members" => %{"User" => %{"shape" => "UserType"}}, "type" => "structure"}, "GetUICustomizationRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "UpdateUserPoolClientRequest" => %{"members" => %{"AllowedOAuthFlows" => %{"shape" => "OAuthFlowsType"}, "AllowedOAuthFlowsUserPoolClient" => %{"shape" => "BooleanType"}, "AllowedOAuthScopes" => %{"shape" => "ScopeListType"}, "CallbackURLs" => %{"shape" => "CallbackURLsListType"}, "ClientId" => %{"shape" => "ClientIdType"}, "ClientName" => %{"shape" => "ClientNameType"}, "DefaultRedirectURI" => %{"shape" => "RedirectUrlType"}, "ExplicitAuthFlows" => %{"shape" => "ExplicitAuthFlowsListType"}, "LogoutURLs" => %{"shape" => "LogoutURLsListType"}, "ReadAttributes" => %{"shape" => "ClientPermissionListType"}, "RefreshTokenValidity" => %{"shape" => "RefreshTokenValidityType"}, "SupportedIdentityProviders" => %{"shape" => "SupportedIdentityProvidersListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "WriteAttributes" => %{"shape" => "ClientPermissionListType"}}, "required" => ["UserPoolId", "ClientId"], "type" => "structure"}, "ListUserImportJobsRequest" => %{"members" => %{"MaxResults" => %{"shape" => "PoolQueryLimitType"}, "PaginationToken" => %{"shape" => "PaginationKeyType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "MaxResults"], "type" => "structure"}, "NotAuthorizedException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ClientPermissionListType" => %{"member" => %{"shape" => "ClientPermissionType"}, "type" => "list"}, "CustomAttributeNameType" => %{"max" => 20, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "type" => "string"}, "AttributeValueType" => %{"max" => 2048, "sensitive" => true, "type" => "string"}, "ProviderNameTypeV1" => %{"max" => 32, "min" => 1, "pattern" => "[^_][\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}][^_]+", "type" => "string"}, "AdminDisableUserRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "UserPoolIdType" => %{"max" => 55, "min" => 1, "pattern" => "[\\w-]+_[0-9a-zA-Z]+", "type" => "string"}, "UserImportJobNameType" => %{"max" => 128, "min" => 1, "pattern" => "[\\w\\s+=,.@-]+", "type" => "string"}, "PasswordPolicyMinLengthType" => %{"max" => 99, "min" => 6, "type" => "integer"}, "S3BucketType" => %{"max" => 1024, "min" => 3, "pattern" => "^[0-9A-Za-z\\.\\-_]*(?<!\\.)$", "type" => "string"}, "AdminUpdateDeviceStatusResponse" => %{"members" => %{}, "type" => "structure"}, "RespondToAuthChallengeResponse" => %{"members" => %{"AuthenticationResult" => %{"shape" => "AuthenticationResultType"}, "ChallengeName" => %{"shape" => "ChallengeNameType"}, "ChallengeParameters" => %{"shape" => "ChallengeParametersType"}, "Session" => %{"shape" => "SessionType"}}, "type" => "structure"}, "AuthParametersType" => %{"key" => %{"shape" => "StringType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "ConfirmDeviceRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "DeviceKey" => %{"shape" => "DeviceKeyType"}, "DeviceName" => %{"shape" => "DeviceNameType"}, "DeviceSecretVerifierConfig" => %{"shape" => "DeviceSecretVerifierConfigType"}}, "required" => ["AccessToken", "DeviceKey"], "type" => "structure"}, "NewDeviceMetadataType" => %{"members" => %{"DeviceGroupKey" => %{"shape" => "StringType"}, "DeviceKey" => %{"shape" => "DeviceKeyType"}}, "type" => "structure"}, "ChangePasswordRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "PreviousPassword" => %{"shape" => "PasswordType"}, "ProposedPassword" => %{"shape" => "PasswordType"}}, "required" => ["PreviousPassword", "ProposedPassword", "AccessToken"], "type" => "structure"}, "PreSignedUrlType" => %{"max" => 2048, "min" => 0, "type" => "string"}, "ListUsersResponse" => %{"members" => %{"PaginationToken" => %{"shape" => "SearchPaginationTokenType"}, "Users" => %{"shape" => "UsersListType"}}, "type" => "structure"}, "ProvidersListType" => %{"max" => 50, "member" => %{"shape" => "ProviderDescription"}, "min" => 0, "type" => "list"}, "EmailVerificationSubjectByLinkType" => %{"max" => 140, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s]+", "type" => "string"}, "LimitExceededException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ListResourceServersRequest" => %{"members" => %{"MaxResults" => %{"shape" => "ListResourceServersLimitType"}, "NextToken" => %{"shape" => "PaginationKeyType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "DeleteUserRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}}, "required" => ["AccessToken"], "type" => "structure"}, "UserImportJobType" => %{"members" => %{"CloudWatchLogsRoleArn" => %{"shape" => "ArnType"}, "CompletionDate" => %{"shape" => "DateType"}, "CompletionMessage" => %{"shape" => "CompletionMessageType"}, "CreationDate" => %{"shape" => "DateType"}, "FailedUsers" => %{"shape" => "LongType"}, "ImportedUsers" => %{"shape" => "LongType"}, "JobId" => %{"shape" => "UserImportJobIdType"}, "JobName" => %{"shape" => "UserImportJobNameType"}, "PreSignedUrl" => %{"shape" => "PreSignedUrlType"}, "SkippedUsers" => %{"shape" => "LongType"}, "StartDate" => %{"shape" => "DateType"}, "Status" => %{"shape" => "UserImportJobStatusType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "DeviceSecretVerifierConfigType" => %{"members" => %{"PasswordVerifier" => %{"shape" => "StringType"}, "Salt" => %{"shape" => "StringType"}}, "type" => "structure"}, "DescribeUserPoolDomainRequest" => %{"members" => %{"Domain" => %{"shape" => "DomainType"}}, "required" => ["Domain"], "type" => "structure"}, "CreateUserPoolDomainResponse" => %{"members" => %{}, "type" => "structure"}, "DescribeUserPoolRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "ExpiredCodeException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminSetUserSettingsResponse" => %{"members" => %{}, "type" => "structure"}, "UserNotConfirmedException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminListGroupsForUserResponse" => %{"members" => %{"Groups" => %{"shape" => "GroupListType"}, "NextToken" => %{"shape" => "PaginationKey"}}, "type" => "structure"}, "ListResourceServersResponse" => %{"members" => %{"NextToken" => %{"shape" => "PaginationKeyType"}, "ResourceServers" => %{"shape" => "ResourceServersListType"}}, "required" => ["ResourceServers"], "type" => "structure"}, "ChallengeResponsesType" => %{"key" => %{"shape" => "StringType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "UpdateIdentityProviderRequest" => %{"members" => %{"AttributeMapping" => %{"shape" => "AttributeMappingType"}, "IdpIdentifiers" => %{"shape" => "IdpIdentifiersListType"}, "ProviderDetails" => %{"shape" => "ProviderDetailsType"}, "ProviderName" => %{"shape" => "ProviderNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ProviderName"], "type" => "structure"}, "CreateUserPoolRequest" => %{"members" => %{"AdminCreateUserConfig" => %{"shape" => "AdminCreateUserConfigType"}, "AliasAttributes" => %{"shape" => "AliasAttributesListType"}, "AutoVerifiedAttributes" => %{"shape" => "VerifiedAttributesListType"}, "DeviceConfiguration" => %{"shape" => "DeviceConfigurationType"}, "EmailConfiguration" => %{"shape" => "EmailConfigurationType"}, "EmailVerificationMessage" => %{"shape" => "EmailVerificationMessageType"}, "EmailVerificationSubject" => %{"shape" => "EmailVerificationSubjectType"}, "LambdaConfig" => %{"shape" => "LambdaConfigType"}, "MfaConfiguration" => %{"shape" => "UserPoolMfaType"}, "Policies" => %{"shape" => "UserPoolPolicyType"}, "PoolName" => %{"shape" => "UserPoolNameType"}, "Schema" => %{"shape" => "SchemaAttributesListType"}, "SmsAuthenticationMessage" => %{"shape" => "SmsVerificationMessageType"}, "SmsConfiguration" => %{"shape" => "SmsConfigurationType"}, "SmsVerificationMessage" => %{"shape" => "SmsVerificationMessageType"}, "UserPoolTags" => %{"shape" => "UserPoolTagsType"}, "UsernameAttributes" => %{"shape" => "UsernameAttributesListType"}, "VerificationMessageTemplate" => %{"shape" => "VerificationMessageTemplateType"}}, "required" => ["PoolName"], "type" => "structure"}, "CompletionMessageType" => %{"max" => 128, "min" => 1, "pattern" => "[\\w]+", "type" => "string"}, "DeleteUserAttributesRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "UserAttributeNames" => %{"shape" => "AttributeNameListType"}}, "required" => ["UserAttributeNames", "AccessToken"], "type" => "structure"}, "DeleteUserAttributesResponse" => %{"members" => %{}, "type" => "structure"}, "UserPoolClientDescription" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "ClientName" => %{"shape" => "ClientNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "EmailVerificationMessageByLinkType" => %{"max" => 20000, "min" => 6, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*\\{##[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*##\\}[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s*]*", "type" => "string"}, "ResourceServersListType" => %{"member" => %{"shape" => "ResourceServerType"}, "type" => "list"}, "ResourceNotFoundException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "PaginationKey" => %{"min" => 1, "pattern" => "[\\S]+", "type" => "string"}, "GetUserAttributeVerificationCodeResponse" => %{"members" => %{"CodeDeliveryDetails" => %{"shape" => "CodeDeliveryDetailsType"}}, "type" => "structure"}, "ListUserPoolClientsResponse" => %{"members" => %{"NextToken" => %{"shape" => "PaginationKey"}, "UserPoolClients" => %{"shape" => "UserPoolClientListType"}}, "type" => "structure"}, "AttributeListType" => %{"member" => %{"shape" => "AttributeType"}, "type" => "list"}, "DescribeUserPoolDomainResponse" => %{"members" => %{"DomainDescription" => %{"shape" => "DomainDescriptionType"}}, "type" => "structure"}, "ConfirmSignUpRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "ConfirmationCode" => %{"shape" => "ConfirmationCodeType"}, "ForceAliasCreation" => %{"shape" => "ForceAliasCreation"}, "SecretHash" => %{"shape" => "SecretHashType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["ClientId", "Username", "ConfirmationCode"], "type" => "structure"}, "DateType" => %{"type" => "timestamp"}, "UnexpectedLambdaException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminGetDeviceResponse" => %{"members" => %{"Device" => %{"shape" => "DeviceType"}}, "required" => ["Device"], "type" => "structure"}, "DeviceListType" => %{"member" => %{"shape" => "DeviceType"}, "type" => "list"}, "VerificationMessageTemplateType" => %{"members" => %{"DefaultEmailOption" => %{"shape" => "DefaultEmailOptionType"}, "EmailMessage" => %{"shape" => "EmailVerificationMessageType"}, "EmailMessageByLink" => %{"shape" => "EmailVerificationMessageByLinkType"}, "EmailSubject" => %{"shape" => "EmailVerificationSubjectType"}, "EmailSubjectByLink" => %{"shape" => "EmailVerificationSubjectByLinkType"}, "SmsMessage" => %{"shape" => "SmsVerificationMessageType"}}, "type" => "structure"}, "ResourceServerType" => %{"members" => %{"Identifier" => %{"shape" => "ResourceServerIdentifierType"}, "Name" => %{"shape" => "ResourceServerNameType"}, "Scopes" => %{"shape" => "ResourceServerScopeListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "AdminRespondToAuthChallengeResponse" => %{"members" => %{"AuthenticationResult" => %{"shape" => "AuthenticationResultType"}, "ChallengeName" => %{"shape" => "ChallengeNameType"}, "ChallengeParameters" => %{"shape" => "ChallengeParametersType"}, "Session" => %{"shape" => "SessionType"}}, "type" => "structure"}, "AdminLinkProviderForUserRequest" => %{"members" => %{"DestinationUser" => %{"shape" => "ProviderUserIdentifierType"}, "SourceUser" => %{"shape" => "ProviderUserIdentifierType"}, "UserPoolId" => %{"shape" => "StringType"}}, "required" => ["UserPoolId", "DestinationUser", "SourceUser"], "type" => "structure"}, "AdminUpdateUserAttributesRequest" => %{"members" => %{"UserAttributes" => %{"shape" => "AttributeListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "UserAttributes"], "type" => "structure"}, "DeleteIdentityProviderRequest" => %{"members" => %{"ProviderName" => %{"shape" => "ProviderNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ProviderName"], "type" => "structure"}, "DomainDescriptionType" => %{"members" => %{"AWSAccountId" => %{"shape" => "AWSAccountIdType"}, "CloudFrontDistribution" => %{"shape" => "ArnType"}, "Domain" => %{"shape" => "DomainType"}, "S3Bucket" => %{"shape" => "S3BucketType"}, "Status" => %{"shape" => "DomainStatusType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Version" => %{"shape" => "DomainVersionType"}}, "type" => "structure"}, "ListGroupsRequest" => %{"members" => %{"Limit" => %{"shape" => "QueryLimitType"}, "NextToken" => %{"shape" => "PaginationKey"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "MessageType" => %{"type" => "string"}, "ResendConfirmationCodeResponse" => %{"members" => %{"CodeDeliveryDetails" => %{"shape" => "CodeDeliveryDetailsType"}}, "type" => "structure"}, "ListUsersRequest" => %{"members" => %{"AttributesToGet" => %{"shape" => "SearchedAttributeNamesListType"}, "Filter" => %{"shape" => "UserFilterType"}, "Limit" => %{"shape" => "QueryLimitType"}, "PaginationToken" => %{"shape" => "SearchPaginationTokenType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "UserPoolClientListType" => %{"member" => %{"shape" => "UserPoolClientDescription"}, "type" => "list"}, "ClientSecretType" => %{"max" => 64, "min" => 1, "pattern" => "[\\w+]+", "sensitive" => true, "type" => "string"}, "AdminGetUserResponse" => %{"members" => %{"Enabled" => %{"shape" => "BooleanType"}, "MFAOptions" => %{"shape" => "MFAOptionListType"}, "UserAttributes" => %{"shape" => "AttributeListType"}, "UserCreateDate" => %{"shape" => "DateType"}, "UserLastModifiedDate" => %{"shape" => "DateType"}, "UserStatus" => %{"shape" => "UserStatusType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["Username"], "type" => "structure"}, "AdminCreateUserUnusedAccountValidityDaysType" => %{"max" => 90, "min" => 0, "type" => "integer"}, "AdminRemoveUserFromGroupRequest" => %{"members" => %{"GroupName" => %{"shape" => "GroupNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "GroupName"], "type" => "structure"}, "EmailConfigurationType" => %{"members" => %{"ReplyToEmailAddress" => %{"shape" => "EmailAddressType"}, "SourceArn" => %{"shape" => "ArnType"}}, "type" => "structure"}, "DomainVersionType" => %{"max" => 20, "min" => 1, "type" => "string"}, "UserImportInProgressException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "DescribeUserImportJobRequest" => %{"members" => %{"JobId" => %{"shape" => "UserImportJobIdType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "JobId"], "type" => "structure"}, "CreateIdentityProviderResponse" => %{"members" => %{"IdentityProvider" => %{"shape" => "IdentityProviderType"}}, "required" => ["IdentityProvider"], "type" => "structure"}, "DeliveryMediumType" => %{"enum" => ["SMS", "EMAIL"], "type" => "string"}, "ConfirmSignUpResponse" => %{"members" => %{}, "type" => "structure"}, "BooleanType" => %{"type" => "boolean"}, "DescribeIdentityProviderResponse" => %{"members" => %{"IdentityProvider" => %{"shape" => "IdentityProviderType"}}, "required" => ["IdentityProvider"], "type" => "structure"}, "ResourceServerScopeListType" => %{"max" => 25, "member" => %{"shape" => "ResourceServerScopeType"}, "type" => "list"}, "DescribeUserImportJobResponse" => %{"members" => %{"UserImportJob" => %{"shape" => "UserImportJobType"}}, "type" => "structure"}, "TokenModelType" => %{"pattern" => "[A-Za-z0-9-_=.]+", "sensitive" => true, "type" => "string"}, "ForgotPasswordResponse" => %{"members" => %{"CodeDeliveryDetails" => %{"shape" => "CodeDeliveryDetailsType"}}, "type" => "structure"}, "UserLambdaValidationException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "UserImportJobIdType" => %{"max" => 55, "min" => 1, "pattern" => "import-[0-9a-zA-Z-]+", "type" => "string"}, "CreateIdentityProviderRequest" => %{"members" => %{"AttributeMapping" => %{"shape" => "AttributeMappingType"}, "IdpIdentifiers" => %{"shape" => "IdpIdentifiersListType"}, "ProviderDetails" => %{"shape" => "ProviderDetailsType"}, "ProviderName" => %{"shape" => "ProviderNameTypeV1"}, "ProviderType" => %{"shape" => "IdentityProviderTypeType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ProviderName", "ProviderType", "ProviderDetails"], "type" => "structure"}, "UICustomizationType" => %{"members" => %{"CSS" => %{"shape" => "CSSType"}, "CSSVersion" => %{"shape" => "CSSVersionType"}, "ClientId" => %{"shape" => "ClientIdType"}, "CreationDate" => %{"shape" => "DateType"}, "ImageUrl" => %{"shape" => "ImageUrlType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "type" => "structure"}, "InvalidSmsRoleTrustRelationshipException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "SmsVerificationMessageType" => %{"max" => 140, "min" => 6, "pattern" => ".*\\{####\\}.*", "type" => "string"}, "CSSType" => %{"type" => "string"}, "PasswordResetRequiredException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "ArnType" => %{"max" => 2048, "min" => 20, "pattern" => "arn:[\\w+=/,.@-]+:[\\w+=/,.@-]+:([\\w+=/,.@-]*)?:[0-9]+:[\\w+=/,.@-]+(:[\\w+=/,.@-]+)?(:[\\w+=/,.@-]+)?", "type" => "string"}, "GlobalSignOutRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}}, "required" => ["AccessToken"], "type" => "structure"}, "PaginationKeyType" => %{"min" => 1, "pattern" => "[\\S]+", "type" => "string"}, "StopUserImportJobResponse" => %{"members" => %{"UserImportJob" => %{"shape" => "UserImportJobType"}}, "type" => "structure"}, "InvalidUserPoolConfigurationException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "UserPoolNameType" => %{"max" => 128, "min" => 1, "pattern" => "[\\w\\s+=,.@-]+", "type" => "string"}, "UpdateResourceServerResponse" => %{"members" => %{"ResourceServer" => %{"shape" => "ResourceServerType"}}, "required" => ["ResourceServer"], "type" => "structure"}, "InitiateAuthRequest" => %{"members" => %{"AuthFlow" => %{"shape" => "AuthFlowType"}, "AuthParameters" => %{"shape" => "AuthParametersType"}, "ClientId" => %{"shape" => "ClientIdType"}, "ClientMetadata" => %{"shape" => "ClientMetadataType"}}, "required" => ["AuthFlow", "ClientId"], "type" => "structure"}, "AdminEnableUserResponse" => %{"members" => %{}, "type" => "structure"}, "AdminDeleteUserRequest" => %{"members" => %{"UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username"], "type" => "structure"}, "ScopeType" => %{"max" => 256, "min" => 1, "pattern" => "[\\x21\\x23-\\x5B\\x5D-\\x7E]+", "type" => "string"}, "AuthFlowType" => %{"enum" => ["USER_SRP_AUTH", "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN", "CUSTOM_AUTH", "ADMIN_NO_SRP_AUTH"], "type" => "string"}, "ListUserPoolClientsRequest" => %{"members" => %{"MaxResults" => %{"shape" => "QueryLimit"}, "NextToken" => %{"shape" => "PaginationKey"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "ListIdentityProvidersRequest" => %{"members" => %{"MaxResults" => %{"shape" => "ListProvidersLimitType"}, "NextToken" => %{"shape" => "PaginationKeyType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId"], "type" => "structure"}, "ExplicitAuthFlowsType" => %{"enum" => ["ADMIN_NO_SRP_AUTH", "CUSTOM_AUTH_FLOW_ONLY"], "type" => "string"}, "PreconditionNotMetException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminListDevicesResponse" => %{"members" => %{"Devices" => %{"shape" => "DeviceListType"}, "PaginationToken" => %{"shape" => "SearchPaginationTokenType"}}, "type" => "structure"}, "AttributeMappingType" => %{"key" => %{"shape" => "AttributeMappingKeyType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "CreateResourceServerRequest" => %{"members" => %{"Identifier" => %{"shape" => "ResourceServerIdentifierType"}, "Name" => %{"shape" => "ResourceServerNameType"}, "Scopes" => %{"shape" => "ResourceServerScopeListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "Identifier", "Name"], "type" => "structure"}, "ResourceServerScopeDescriptionType" => %{"max" => 256, "min" => 1, "type" => "string"}, "ResourceServerScopeType" => %{"members" => %{"ScopeDescription" => %{"shape" => "ResourceServerScopeDescriptionType"}, "ScopeName" => %{"shape" => "ResourceServerScopeNameType"}}, "required" => ["ScopeName", "ScopeDescription"], "type" => "structure"}, "InvalidEmailRoleAccessPolicyException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "TooManyFailedAttemptsException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "UserType" => %{"members" => %{"Attributes" => %{"shape" => "AttributeListType"}, "Enabled" => %{"shape" => "BooleanType"}, "MFAOptions" => %{"shape" => "MFAOptionListType"}, "UserCreateDate" => %{"shape" => "DateType"}, "UserLastModifiedDate" => %{"shape" => "DateType"}, "UserStatus" => %{"shape" => "UserStatusType"}, "Username" => %{"shape" => "UsernameType"}}, "type" => "structure"}, "AttributeNameListType" => %{"member" => %{"shape" => "AttributeNameType"}, "type" => "list"}, "AdminUpdateDeviceStatusRequest" => %{"members" => %{"DeviceKey" => %{"shape" => "DeviceKeyType"}, "DeviceRememberedStatus" => %{"shape" => "DeviceRememberedStatusType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "DeviceKey"], "type" => "structure"}, "DescribeResourceServerResponse" => %{"members" => %{"ResourceServer" => %{"shape" => "ResourceServerType"}}, "required" => ["ResourceServer"], "type" => "structure"}, "RefreshTokenValidityType" => %{"max" => 3650, "min" => 0, "type" => "integer"}, "CustomAttributesListType" => %{"max" => 25, "member" => %{"shape" => "SchemaAttributeType"}, "min" => 1, "type" => "list"}, "GetIdentityProviderByIdentifierRequest" => %{"members" => %{"IdpIdentifier" => %{"shape" => "IdpIdentifierType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "IdpIdentifier"], "type" => "structure"}, "PrecedenceType" => %{"min" => 0, "type" => "integer"}, "CreateGroupResponse" => %{"members" => %{"Group" => %{"shape" => "GroupType"}}, "type" => "structure"}, "PasswordPolicyType" => %{"members" => %{"MinimumLength" => %{"shape" => "PasswordPolicyMinLengthType"}, "RequireLowercase" => %{"shape" => "BooleanType"}, "RequireNumbers" => %{"shape" => "BooleanType"}, "RequireSymbols" => %{"shape" => "BooleanType"}, "RequireUppercase" => %{"shape" => "BooleanType"}}, "type" => "structure"}, "IdpIdentifierType" => %{"max" => 40, "min" => 1, "pattern" => "[\\w\\s+=.@-]+", "type" => "string"}, "CreateUserPoolDomainRequest" => %{"members" => %{"Domain" => %{"shape" => "DomainType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["Domain", "UserPoolId"], "type" => "structure"}, "DeleteUserPoolDomainResponse" => %{"members" => %{}, "type" => "structure"}, "ClientMetadataType" => %{"key" => %{"shape" => "StringType"}, "type" => "map", "value" => %{"shape" => "StringType"}}, "UsersListType" => %{"member" => %{"shape" => "UserType"}, "type" => "list"}, "CodeDeliveryFailureException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "SignUpResponse" => %{"members" => %{"CodeDeliveryDetails" => %{"shape" => "CodeDeliveryDetailsType"}, "UserConfirmed" => %{"shape" => "BooleanType"}, "UserSub" => %{"shape" => "StringType"}}, "required" => ["UserConfirmed", "UserSub"], "type" => "structure"}, "UpdateUserAttributesRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "UserAttributes" => %{"shape" => "AttributeListType"}}, "required" => ["UserAttributes", "AccessToken"], "type" => "structure"}, "EmailVerificationSubjectType" => %{"max" => 140, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\s]+", "type" => "string"}, "LongType" => %{"type" => "long"}, "StartUserImportJobRequest" => %{"members" => %{"JobId" => %{"shape" => "UserImportJobIdType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "JobId"], "type" => "structure"}, "ConfirmForgotPasswordRequest" => %{"members" => %{"ClientId" => %{"shape" => "ClientIdType"}, "ConfirmationCode" => %{"shape" => "ConfirmationCodeType"}, "Password" => %{"shape" => "PasswordType"}, "SecretHash" => %{"shape" => "SecretHashType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["ClientId", "Username", "ConfirmationCode", "Password"], "type" => "structure"}, "AddCustomAttributesResponse" => %{"members" => %{}, "type" => "structure"}, "ForgetDeviceRequest" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "DeviceKey" => %{"shape" => "DeviceKeyType"}}, "required" => ["DeviceKey"], "type" => "structure"}, "ScopeDoesNotExistException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AuthenticationResultType" => %{"members" => %{"AccessToken" => %{"shape" => "TokenModelType"}, "ExpiresIn" => %{"shape" => "IntegerType"}, "IdToken" => %{"shape" => "TokenModelType"}, "NewDeviceMetadata" => %{"shape" => "NewDeviceMetadataType"}, "RefreshToken" => %{"shape" => "TokenModelType"}, "TokenType" => %{"shape" => "StringType"}}, "type" => "structure"}, "StringType" => %{"type" => "string"}, "QueryLimitType" => %{"max" => 60, "min" => 0, "type" => "integer"}, "ListUsersInGroupResponse" => %{"members" => %{"NextToken" => %{"shape" => "PaginationKey"}, "Users" => %{"shape" => "UsersListType"}}, "type" => "structure"}, "ProviderDescription" => %{"members" => %{"CreationDate" => %{"shape" => "DateType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "ProviderName" => %{"shape" => "ProviderNameType"}, "ProviderType" => %{"shape" => "IdentityProviderTypeType"}}, "type" => "structure"}, "CallbackURLsListType" => %{"max" => 100, "member" => %{"shape" => "RedirectUrlType"}, "min" => 0, "type" => "list"}, "UpdateResourceServerRequest" => %{"members" => %{"Identifier" => %{"shape" => "ResourceServerIdentifierType"}, "Name" => %{"shape" => "ResourceServerNameType"}, "Scopes" => %{"shape" => "ResourceServerScopeListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "Identifier", "Name"], "type" => "structure"}, "UserPoolClientType" => %{"members" => %{"AllowedOAuthFlows" => %{"shape" => "OAuthFlowsType"}, "AllowedOAuthFlowsUserPoolClient" => %{"box" => true, "shape" => "BooleanType"}, "AllowedOAuthScopes" => %{"shape" => "ScopeListType"}, "CallbackURLs" => %{"shape" => "CallbackURLsListType"}, "ClientId" => %{"shape" => "ClientIdType"}, "ClientName" => %{"shape" => "ClientNameType"}, "ClientSecret" => %{"shape" => "ClientSecretType"}, "CreationDate" => %{"shape" => "DateType"}, "DefaultRedirectURI" => %{"shape" => "RedirectUrlType"}, "ExplicitAuthFlows" => %{"shape" => "ExplicitAuthFlowsListType"}, "LastModifiedDate" => %{"shape" => "DateType"}, "LogoutURLs" => %{"shape" => "LogoutURLsListType"}, "ReadAttributes" => %{"shape" => "ClientPermissionListType"}, "RefreshTokenValidity" => %{"shape" => "RefreshTokenValidityType"}, "SupportedIdentityProviders" => %{"shape" => "SupportedIdentityProvidersListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "WriteAttributes" => %{"shape" => "ClientPermissionListType"}}, "type" => "structure"}, "StartUserImportJobResponse" => %{"members" => %{"UserImportJob" => %{"shape" => "UserImportJobType"}}, "type" => "structure"}, "AdminSetUserSettingsRequest" => %{"members" => %{"MFAOptions" => %{"shape" => "MFAOptionListType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "MFAOptions"], "type" => "structure"}, "SetUserSettingsResponse" => %{"members" => %{}, "type" => "structure"}, "InitiateAuthResponse" => %{"members" => %{"AuthenticationResult" => %{"shape" => "AuthenticationResultType"}, "ChallengeName" => %{"shape" => "ChallengeNameType"}, "ChallengeParameters" => %{"shape" => "ChallengeParametersType"}, "Session" => %{"shape" => "SessionType"}}, "type" => "structure"}, "ConcurrentModificationException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}, "AdminInitiateAuthRequest" => %{"members" => %{"AuthFlow" => %{"shape" => "AuthFlowType"}, "AuthParameters" => %{"shape" => "AuthParametersType"}, "ClientId" => %{"shape" => "ClientIdType"}, "ClientMetadata" => %{"shape" => "ClientMetadataType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}}, "required" => ["UserPoolId", "ClientId", "AuthFlow"], "type" => "structure"}, "RedirectUrlType" => %{"max" => 1024, "min" => 1, "pattern" => "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}]+", "type" => "string"}, "CreateUserPoolClientResponse" => %{"members" => %{"UserPoolClient" => %{"shape" => "UserPoolClientType"}}, "type" => "structure"}, "ClientIdType" => %{"max" => 128, "min" => 1, "pattern" => "[\\w+]+", "sensitive" => true, "type" => "string"}, "ImageUrlType" => %{"type" => "string"}, "MFAOptionType" => %{"members" => %{"AttributeName" => %{"shape" => "AttributeNameType"}, "DeliveryMedium" => %{"shape" => "DeliveryMediumType"}}, "type" => "structure"}, "ListDevicesResponse" => %{"members" => %{"Devices" => %{"shape" => "DeviceListType"}, "PaginationToken" => %{"shape" => "SearchPaginationTokenType"}}, "type" => "structure"}, "AdminAddUserToGroupRequest" => %{"members" => %{"GroupName" => %{"shape" => "GroupNameType"}, "UserPoolId" => %{"shape" => "UserPoolIdType"}, "Username" => %{"shape" => "UsernameType"}}, "required" => ["UserPoolId", "Username", "GroupName"], "type" => "structure"}, "GroupExistsException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "MessageType"}}, "type" => "structure"}} end end
73.379491
63,965
0.582612
1c089bbf781238b24790dab1fe0bd0d3e1c93aab
650
ex
Elixir
lib/legato/query/metric_filter.ex
data-twister/legato-ex
3cd919d44e0d0ac02e1eb25ea7ad2b865e05ea2d
[ "MIT" ]
null
null
null
lib/legato/query/metric_filter.ex
data-twister/legato-ex
3cd919d44e0d0ac02e1eb25ea7ad2b865e05ea2d
[ "MIT" ]
null
null
null
lib/legato/query/metric_filter.ex
data-twister/legato-ex
3cd919d44e0d0ac02e1eb25ea7ad2b865e05ea2d
[ "MIT" ]
null
null
null
defmodule Legato.Query.MetricFilter do defstruct metric_name: nil, not: false, operator: :equal, comparison_value: nil # { # "metricName": string, # "not": boolean, # "operator": enum(Operator), # "comparisonValue": string, # } defimpl Jason.Encoder, for: __MODULE__ do def encode(struct, options) do # This is the format for GA report json Jason.Encoder.Map.encode(%{ metric_name: struct.dimension_name, operator: struct.operator, not: struct.not, comparison_value: struct.comparison_value }, options) end end def to_json(filter), do: Jason.encode!(filter) end
27.083333
81
0.656923
1c08a31db75df5b3e96a64ef4a88f60ed64a5489
3,521
exs
Elixir
test/guardian/db_test.exs
forest/guardian_db
fcfc3fb8e3d52033e8c220ddf1dc427b25ca18df
[ "MIT" ]
3
2021-04-22T03:44:56.000Z
2021-11-15T11:13:53.000Z
test/guardian/db_test.exs
forest/guardian_db
fcfc3fb8e3d52033e8c220ddf1dc427b25ca18df
[ "MIT" ]
null
null
null
test/guardian/db_test.exs
forest/guardian_db
fcfc3fb8e3d52033e8c220ddf1dc427b25ca18df
[ "MIT" ]
null
null
null
defmodule Guardian.DBTest do use Guardian.DB.TestSupport.CaseTemplate alias Guardian.DB.Token setup do {:ok, %{ claims: %{ "jti" => "token-uuid", "typ" => "token", "aud" => "token", "sub" => "the_subject", "iss" => "the_issuer", "exp" => Guardian.timestamp() + 1_000_000_000 } }} end test "after_encode_and_sign_in is successful", context do token = get_token() assert token == nil Guardian.DB.after_encode_and_sign(%{}, "token", context.claims, "The JWT") token = get_token() assert token != nil assert token.jti == "token-uuid" assert token.aud == "token" assert token.sub == "the_subject" assert token.iss == "the_issuer" assert token.exp == context.claims["exp"] assert token.claims == context.claims end test "on_verify with a record in the db", context do Token.create(context.claims, "The JWT") token = get_token() assert token != nil assert {:ok, {context.claims, "The JWT"}} == Guardian.DB.on_verify(context.claims, "The JWT") end test "on_verify without a record in the db", context do token = get_token() assert token == nil assert {:error, :token_not_found} == Guardian.DB.on_verify(context.claims, "The JWT") end test "on_refresh without a record in the db", context do token = get_token() assert token == nil Guardian.DB.after_encode_and_sign(%{}, "token", context.claims, "The JWT 1") old_stuff = {get_token(), context.claims} new_claims = %{ "jti" => "token-uuid1", "typ" => "token", "aud" => "token", "sub" => "the_subject", "iss" => "the_issuer", "exp" => Guardian.timestamp() + 2_000_000_000 } Guardian.DB.after_encode_and_sign(%{}, "token", new_claims, "The JWT 2") new_stuff = {get_token("token-uuid1"), new_claims} assert Guardian.DB.on_refresh(old_stuff, new_stuff) == {:ok, old_stuff, new_stuff} end test "on_revoke without a record in the db", context do token = get_token() assert token == nil assert Guardian.DB.on_revoke(context.claims, "The JWT") == {:ok, {context.claims, "The JWT"}} end test "on_revoke with a record in the db", context do Token.create(context.claims, "The JWT") token = get_token() assert token != nil assert Guardian.DB.on_revoke(context.claims, "The JWT") == {:ok, {context.claims, "The JWT"}} token = get_token() assert token == nil end test "purge stale tokens" do Token.create( %{"jti" => "token1", "aud" => "token", "exp" => Guardian.timestamp() + 5000}, "Token 1" ) Token.create( %{"jti" => "token2", "aud" => "token", "exp" => Guardian.timestamp() - 5000}, "Token 2" ) Token.purge_expired_tokens() token1 = get_token("token1") token2 = get_token("token2") assert token1 != nil assert token2 == nil end test "revoke_all deletes all tokens of a sub" do sub = "the_subject" Token.create( %{"jti" => "token1", "aud" => "token", "exp" => Guardian.timestamp(), "sub" => sub}, "Token 1" ) Token.create( %{"jti" => "token2", "aud" => "token", "exp" => Guardian.timestamp(), "sub" => sub}, "Token 2" ) Token.create( %{"jti" => "token3", "aud" => "token", "exp" => Guardian.timestamp(), "sub" => sub}, "Token 3" ) assert Guardian.DB.revoke_all(sub) == {:ok, 3} assert Repo.all(Token.query_schema()) == [] end end
26.877863
97
0.594149
1c08dbe647f86c081f572834ee5acd9966547f61
3,353
ex
Elixir
lib/sanbase_web/graphql/resolvers/price_resolver.ex
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
lib/sanbase_web/graphql/resolvers/price_resolver.ex
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
lib/sanbase_web/graphql/resolvers/price_resolver.ex
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule SanbaseWeb.Graphql.Resolvers.PriceResolver do require Logger import SanbaseWeb.Graphql.Helpers.CalibrateInterval, only: [calibrate: 6] alias Sanbase.Price alias Sanbase.Model.Project @total_market "TOTAL_MARKET" @total_erc20 "TOTAL_ERC20" @doc """ Returns a list of price points for the given ticker. Optimizes the number of queries to the DB by inspecting the requested fields. """ def history_price(_root, %{slug: @total_market} = args, _resolution) do %{from: from, to: to, interval: interval} = args with {:ok, from, to, interval} <- calibrate(Price, @total_market, from, to, interval, 300), {:ok, result} <- Price.timeseries_data(@total_market, from, to, interval) do {:ok, result} end end def history_price(root, %{ticker: @total_market} = args, resolution) do args = args |> Map.delete(:ticker) |> Map.put(:slug, @total_market) history_price(root, args, resolution) end def history_price(_root, %{slug: @total_erc20} = args, _resolution) do %{from: from, to: to, interval: interval} = args with {:ok, from, to, interval} <- calibrate(Price, @total_erc20, from, to, interval, 300), {:ok, result} <- Price.timeseries_data(@total_erc20, from, to, interval) do {:ok, result} end end def history_price(root, %{ticker: @total_erc20} = args, resolution) do args = args |> Map.delete(:ticker) |> Map.put(:slug, @total_erc20) history_price(root, args, resolution) end def history_price(_root, %{ticker: ticker} = args, _resolution) do %{from: from, to: to, interval: interval} = args with {:get_slug, slug} when not is_nil(slug) <- {:get_slug, Project.slug_by_ticker(ticker)}, {:ok, from, to, interval} <- calibrate(Price, slug, from, to, interval, 300), {:ok, result} <- Price.timeseries_data(slug, from, to, interval) do {:ok, result} else {:get_slug, nil} -> {:error, "The provided ticker '#{ticker}' is misspelled or there is no data for this ticker"} error -> {:error, "Cannot fetch history price for #{ticker}. Reason: #{inspect(error)}"} end end def history_price(_root, %{slug: slug} = args, _resolution) do %{from: from, to: to, interval: interval} = args with {:ok, from, to, interval} <- calibrate(Price, slug, from, to, interval, 300), {:ok, result} <- Price.timeseries_data(slug, from, to, interval) do {:ok, result} else {:get_ticker, nil} -> {:error, "The provided slug '#{slug}' is misspelled or there is no data for this slug"} error -> {:error, "Cannot fetch history price for #{slug}. Reason: #{inspect(error)}"} end end def ohlc(_root, %{slug: slug, from: from, to: to, interval: interval}, _resolution) do case Price.timeseries_ohlc_data(slug, from, to, interval) do {:ok, result} -> {:ok, result} {:error, error} -> {:error, "Cannot fetch ohlc for #{slug}. Reason: #{inspect(error)}"} end end def projects_list_stats(_root, %{slugs: slugs, from: from, to: to}, _resolution) do case Price.aggregated_marketcap_and_volume(slugs, from, to) do {:ok, values} -> {:ok, values} _ -> {:error, "Can't fetch combined volume and marketcap for slugs"} end end end
34.214286
96
0.636147
1c08e3410986bf2e6d2bdd10aa6c0f5c9bb2d49b
11,333
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/database_instance.ex
richiboi1977/elixir-google-api
c495bb3548090eb7a63d12f6fb145ec48aecdc0b
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/database_instance.ex
richiboi1977/elixir-google-api
c495bb3548090eb7a63d12f6fb145ec48aecdc0b
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/database_instance.ex
richiboi1977/elixir-google-api
c495bb3548090eb7a63d12f6fb145ec48aecdc0b
[ "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.SQLAdmin.V1beta4.Model.DatabaseInstance do @moduledoc """ A Cloud SQL instance resource. ## Attributes * `backendType` (*type:* `String.t`, *default:* `nil`) - *SECOND_GEN*: Cloud SQL database instance. *EXTERNAL*: A database server that is not managed by Google. This property is read-only; use the *tier* property in the *settings* object to determine the database type. * `connectionName` (*type:* `String.t`, *default:* `nil`) - Connection name of the Cloud SQL instance used in connection strings. * `currentDiskSize` (*type:* `String.t`, *default:* `nil`) - The current disk usage of the instance in bytes. This property has been deprecated. Use the "cloudsql.googleapis.com/database/disk/bytes_used" metric in Cloud Monitoring API instead. Please see this announcement for details. * `databaseVersion` (*type:* `String.t`, *default:* `nil`) - The database engine type and version. The *databaseVersion* field cannot be changed after instance creation. MySQL instances: *MYSQL_8_0*, *MYSQL_5_7* (default), or *MYSQL_5_6*. PostgreSQL instances: *POSTGRES_9_6*, *POSTGRES_10*, *POSTGRES_11*, *POSTGRES_12*, *POSTGRES_13* (default). SQL Server instances: *SQLSERVER_2019_STANDARD*, *SQLSERVER_2019_ENTERPRISE*, *SQLSERVER_2019_EXPRESS*, or *SQLSERVER_2019_WEB*, *SQLSERVER_2017_STANDARD* (default), *SQLSERVER_2017_ENTERPRISE*, *SQLSERVER_2017_EXPRESS*, or *SQLSERVER_2017_WEB*. * `diskEncryptionConfiguration` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionConfiguration.t`, *default:* `nil`) - Disk encryption configuration specific to an instance. * `diskEncryptionStatus` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus.t`, *default:* `nil`) - Disk encryption status specific to an instance. * `etag` (*type:* `String.t`, *default:* `nil`) - This field is deprecated and will be removed from a future version of the API. Use the *settings.settingsVersion* field instead. * `failoverReplica` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.DatabaseInstanceFailoverReplica.t`, *default:* `nil`) - The name and status of the failover replica. * `gceZone` (*type:* `String.t`, *default:* `nil`) - The Compute Engine zone that the instance is currently serving from. This value could be different from the zone that was specified when the instance was created if the instance has failed over to its secondary zone. * `instanceType` (*type:* `String.t`, *default:* `nil`) - The instance type. This can be one of the following. *CLOUD_SQL_INSTANCE*: A Cloud SQL instance that is not replicating from a primary instance. *ON_PREMISES_INSTANCE*: An instance running on the customer's premises. *READ_REPLICA_INSTANCE*: A Cloud SQL instance configured as a read-replica. * `ipAddresses` (*type:* `list(GoogleApi.SQLAdmin.V1beta4.Model.IpMapping.t)`, *default:* `nil`) - The assigned IP addresses for the instance. * `ipv6Address` (*type:* `String.t`, *default:* `nil`) - The IPv6 address assigned to the instance. (Deprecated) This property was applicable only to First Generation instances. * `kind` (*type:* `String.t`, *default:* `nil`) - This is always *sql#instance*. * `masterInstanceName` (*type:* `String.t`, *default:* `nil`) - The name of the instance which will act as primary in the replication setup. * `maxDiskSize` (*type:* `String.t`, *default:* `nil`) - The maximum disk size of the instance in bytes. * `name` (*type:* `String.t`, *default:* `nil`) - Name of the Cloud SQL instance. This does not include the project ID. * `onPremisesConfiguration` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.OnPremisesConfiguration.t`, *default:* `nil`) - Configuration specific to on-premises instances. * `outOfDiskReport` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.SqlOutOfDiskReport.t`, *default:* `nil`) - This field represents the report generated by the proactive database wellness job for OutOfDisk issues. Writers: -- the proactive database wellness job for OOD. Readers: -- the proactive database wellness job * `project` (*type:* `String.t`, *default:* `nil`) - The project ID of the project containing the Cloud SQL instance. The Google apps domain is prefixed if applicable. * `region` (*type:* `String.t`, *default:* `nil`) - The geographical region. Can be *us-central* (*FIRST_GEN* instances only) *us-central1* (*SECOND_GEN* instances only) *asia-east1* or *europe-west1*. Defaults to *us-central* or *us-central1* depending on the instance type. The region cannot be changed after instance creation. * `replicaConfiguration` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.ReplicaConfiguration.t`, *default:* `nil`) - Configuration specific to failover replicas and read replicas. * `replicaNames` (*type:* `list(String.t)`, *default:* `nil`) - The replicas of the instance. * `rootPassword` (*type:* `String.t`, *default:* `nil`) - Initial root password. Use only on creation. * `satisfiesPzs` (*type:* `boolean()`, *default:* `nil`) - The status indicating if instance satisfiesPzs. Reserved for future use. * `scheduledMaintenance` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance.t`, *default:* `nil`) - The start time of any upcoming scheduled maintenance for this instance. * `secondaryGceZone` (*type:* `String.t`, *default:* `nil`) - The Compute Engine zone that the failover instance is currently serving from for a regional instance. This value could be different from the zone that was specified when the instance was created if the instance has failed over to its secondary/failover zone. Reserved for future use. * `selfLink` (*type:* `String.t`, *default:* `nil`) - The URI of this resource. * `serverCaCert` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.SslCert.t`, *default:* `nil`) - SSL configuration. * `serviceAccountEmailAddress` (*type:* `String.t`, *default:* `nil`) - The service account email address assigned to the instance. This property is read-only. * `settings` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.Settings.t`, *default:* `nil`) - The user settings. * `state` (*type:* `String.t`, *default:* `nil`) - The current serving state of the Cloud SQL instance. This can be one of the following. *SQL_INSTANCE_STATE_UNSPECIFIED*: The state of the instance is unknown. *RUNNABLE*: The instance is running, or has been stopped by owner. *SUSPENDED*: The instance is not available, for example due to problems with billing. *PENDING_DELETE*: The instance is being deleted. *PENDING_CREATE*: The instance is being created. *MAINTENANCE*: The instance is down for maintenance. *FAILED*: The instance creation failed. * `suspensionReason` (*type:* `list(String.t)`, *default:* `nil`) - If the instance state is SUSPENDED, the reason for the suspension. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :backendType => String.t() | nil, :connectionName => String.t() | nil, :currentDiskSize => String.t() | nil, :databaseVersion => String.t() | nil, :diskEncryptionConfiguration => GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionConfiguration.t() | nil, :diskEncryptionStatus => GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus.t() | nil, :etag => String.t() | nil, :failoverReplica => GoogleApi.SQLAdmin.V1beta4.Model.DatabaseInstanceFailoverReplica.t() | nil, :gceZone => String.t() | nil, :instanceType => String.t() | nil, :ipAddresses => list(GoogleApi.SQLAdmin.V1beta4.Model.IpMapping.t()) | nil, :ipv6Address => String.t() | nil, :kind => String.t() | nil, :masterInstanceName => String.t() | nil, :maxDiskSize => String.t() | nil, :name => String.t() | nil, :onPremisesConfiguration => GoogleApi.SQLAdmin.V1beta4.Model.OnPremisesConfiguration.t() | nil, :outOfDiskReport => GoogleApi.SQLAdmin.V1beta4.Model.SqlOutOfDiskReport.t() | nil, :project => String.t() | nil, :region => String.t() | nil, :replicaConfiguration => GoogleApi.SQLAdmin.V1beta4.Model.ReplicaConfiguration.t() | nil, :replicaNames => list(String.t()) | nil, :rootPassword => String.t() | nil, :satisfiesPzs => boolean() | nil, :scheduledMaintenance => GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance.t() | nil, :secondaryGceZone => String.t() | nil, :selfLink => String.t() | nil, :serverCaCert => GoogleApi.SQLAdmin.V1beta4.Model.SslCert.t() | nil, :serviceAccountEmailAddress => String.t() | nil, :settings => GoogleApi.SQLAdmin.V1beta4.Model.Settings.t() | nil, :state => String.t() | nil, :suspensionReason => list(String.t()) | nil } field(:backendType) field(:connectionName) field(:currentDiskSize) field(:databaseVersion) field(:diskEncryptionConfiguration, as: GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionConfiguration ) field(:diskEncryptionStatus, as: GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus) field(:etag) field(:failoverReplica, as: GoogleApi.SQLAdmin.V1beta4.Model.DatabaseInstanceFailoverReplica) field(:gceZone) field(:instanceType) field(:ipAddresses, as: GoogleApi.SQLAdmin.V1beta4.Model.IpMapping, type: :list) field(:ipv6Address) field(:kind) field(:masterInstanceName) field(:maxDiskSize) field(:name) field(:onPremisesConfiguration, as: GoogleApi.SQLAdmin.V1beta4.Model.OnPremisesConfiguration) field(:outOfDiskReport, as: GoogleApi.SQLAdmin.V1beta4.Model.SqlOutOfDiskReport) field(:project) field(:region) field(:replicaConfiguration, as: GoogleApi.SQLAdmin.V1beta4.Model.ReplicaConfiguration) field(:replicaNames, type: :list) field(:rootPassword) field(:satisfiesPzs) field(:scheduledMaintenance, as: GoogleApi.SQLAdmin.V1beta4.Model.SqlScheduledMaintenance) field(:secondaryGceZone) field(:selfLink) field(:serverCaCert, as: GoogleApi.SQLAdmin.V1beta4.Model.SslCert) field(:serviceAccountEmailAddress) field(:settings, as: GoogleApi.SQLAdmin.V1beta4.Model.Settings) field(:state) field(:suspensionReason, type: :list) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.DatabaseInstance do def decode(value, options) do GoogleApi.SQLAdmin.V1beta4.Model.DatabaseInstance.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.DatabaseInstance do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
75.553333
596
0.714639
1c08e6a7a2111cb502945225f7ce749ce5c2965a
380
ex
Elixir
lib/drab_spike_web/views/error_view.ex
kimlindholm/drab_spike
f7573dade90d1cc3dcb54a30aa5a1c09445516fa
[ "MIT" ]
null
null
null
lib/drab_spike_web/views/error_view.ex
kimlindholm/drab_spike
f7573dade90d1cc3dcb54a30aa5a1c09445516fa
[ "MIT" ]
8
2019-10-31T11:27:57.000Z
2022-02-09T23:00:28.000Z
lib/drab_spike_web/views/error_view.ex
kimlindholm/drab_spike
f7573dade90d1cc3dcb54a30aa5a1c09445516fa
[ "MIT" ]
null
null
null
defmodule DrabSpikeWeb.ErrorView do use DrabSpikeWeb, :view def render("404.html", _assigns) do "Page not found" end def render("500.html", _assigns) do "Internal server error" end # In case no render clause matches or no # template is found, let's render it as 500 def template_not_found(_template, assigns) do render "500.html", assigns end end
21.111111
47
0.705263
1c08fd656df6e02e038b1ae400e65c81f176ddfb
198
ex
Elixir
web/views/feed_entry_view.ex
mskog/Upfeed
34fad85cbf7c0c7b0a7d0238c312b29edb61b1d1
[ "MIT" ]
null
null
null
web/views/feed_entry_view.ex
mskog/Upfeed
34fad85cbf7c0c7b0a7d0238c312b29edb61b1d1
[ "MIT" ]
null
null
null
web/views/feed_entry_view.ex
mskog/Upfeed
34fad85cbf7c0c7b0a7d0238c312b29edb61b1d1
[ "MIT" ]
null
null
null
defmodule Upfeed.FeedEntryView do use Upfeed.Web, :view def feed_title(feed_name) do "Upfeed - #{feed_name}" end def feed_description(feed_name) do feed_title(feed_name) end end
16.5
36
0.722222
1c09068311ee815b396b29e526aca1da84a12985
2,621
ex
Elixir
apps/cucumber_expressions/test/support/parameter_type/validators/date.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
2
2021-05-18T18:20:05.000Z
2022-02-13T00:15:06.000Z
apps/cucumber_expressions/test/support/parameter_type/validators/date.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
2
2021-04-22T00:28:17.000Z
2021-05-19T21:04:20.000Z
apps/cucumber_expressions/test/support/parameter_type/validators/date.ex
Ajwah/ex_cucumber
f2b9cf06caeef624c66424ae6160f274dc133fc6
[ "Apache-2.0" ]
4
2021-04-14T03:07:45.000Z
2021-12-12T21:23:59.000Z
defmodule Support.ParameterType.Validator.Date do defstruct raw: :none, value: :none, month: "", year: "", day: 0, day_name: "" @valid_months [ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" ] @valid_day_names ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] @regex ~r/^(?<day_name>\b.*\b), (?<day>\d{1,2}) (?<month>\b.*\b) (?<year>\d{4})$/ def run(str, _) do c = Regex.named_captures(@regex, str) with {_, _, {month, true}} <- validate_month(c["month"]), {_, _, {year, true}} <- validate_year(c["year"]), {_, _, {day_name, true}} <- validate_day_name(c["day_name"]), {_, _, {day, true}} <- validate_day(c["day"], month, year) do {:ok, struct(__MODULE__, %{ raw: str, value: str, month: month, year: year, day: day, day_name: day_name })} else {msg, error_code, _} -> {:error, error_code, msg} end end defp validate_month(month) do month = String.downcase(month) if month in @valid_months do {"", :valid_month, {String.capitalize(month), true}} else {"Invalid month: #{month}", :invalid_month, {month, false}} end end defp validate_day_name(day_name) do day_name = String.downcase(day_name) if day_name in @valid_day_names do {"", :valid_day_name, {String.capitalize(day_name), true}} else {"Invalid day_name: #{day_name}", :invalid_day_name, {day_name, false}} end end defp validate_year(year) do year |> Support.ParameterType.Validator.Integer.run() |> case do {:error, :not_integer, _} -> {"Invalid year: #{year}", :invalid_year, {year, false}} {:ok, year} -> if year >= 2010 && year <= 2030 do {"", :valid_year, {year, true}} else {"Year out of range: #{year}", :out_of_range_year, {year, false}} end end end # month and year would allow validation with greater fine granularity if need be defp validate_day(day, _, _) do day |> Support.ParameterType.Validator.Integer.run() |> case do {:error, :not_integer, _} -> {"Invalid day: #{day}", :invalid_day, {day, false}} {:ok, day} -> if day >= 1 && day <= 31 do {"", :valid_day, {day, true}} else {"day out of range: #{day}", :out_of_range_day, {day, false}} end end end end
25.950495
97
0.542923
1c091124bc92a23ad8152fa8d2f29f63faa98bfd
1,712
ex
Elixir
lib/tipalti/api/soap/response_parser.ex
gadabout/tipalti-elixir
4cff4108b343b8d7c30d117494838ad00a46128a
[ "MIT" ]
8
2018-04-26T21:40:07.000Z
2019-08-14T10:55:53.000Z
lib/tipalti/api/soap/response_parser.ex
gadabout/tipalti-elixir
4cff4108b343b8d7c30d117494838ad00a46128a
[ "MIT" ]
198
2018-04-26T21:53:20.000Z
2022-03-23T15:20:11.000Z
lib/tipalti/api/soap/response_parser.ex
gadabout/tipalti-elixir
4cff4108b343b8d7c30d117494838ad00a46128a
[ "MIT" ]
1
2018-11-09T03:10:36.000Z
2018-11-09T03:10:36.000Z
defmodule Tipalti.API.SOAP.ResponseParser do @moduledoc false import SweetXmlFork alias SweetXpathFork, as: SweetXpath alias Tipalti.ClientError def parse(body, root_path, :empty, response_opts) do with :ok <- is_ok?(body, root_path, response_opts) do :ok end end def parse(body, root_path, %SweetXpath{} = path, response_opts) do document = xpath(body, ~x"/"e) with :ok <- is_ok?(document, root_path, response_opts) do element = xpath(document, root_path) {:ok, xpath(element, path)} end end def parse(body, root_path, [%SweetXpath{} = path | mapping], response_opts) do document = xpath(body, ~x"/"e) with :ok <- is_ok?(document, root_path, response_opts) do element = xpath(document, root_path) {:ok, xpath(element, path, mapping)} end end def parse(body, root_path, mapping, response_opts) do document = xpath(body, ~x"/"e) with :ok <- is_ok?(document, root_path, response_opts) do {:ok, xpath(document, root_path, mapping)} end end def parse_without_errors(body, root_path, [path | mapping]) do document = xpath(body, ~x"/"e) element = xpath(document, root_path) xpath(element, path, mapping) end defp is_ok?(document, root_path, response_opts) do ok_code = response_opts[:ok_code] error_paths = response_opts[:error_paths] case xpath(document, root_path, error_paths) do %{error_code: ^ok_code} -> :ok error -> {:error, ClientError.from_map!(error)} end end def parse_errors(body, root_path, error_paths) do document = xpath(body, ~x"/"e) ClientError.from_map!(xpath(document, root_path, error_paths)) end end
25.552239
80
0.666472
1c092be79ef058367c9541d79cbf9a01a12edd52
2,024
ex
Elixir
lib/arkecosystem/crypto/helpers/map_key_transformer.ex
whitehat/elixir-crypto
6347868ee15c7b79676df58bef54376a8dc6fd02
[ "MIT" ]
null
null
null
lib/arkecosystem/crypto/helpers/map_key_transformer.ex
whitehat/elixir-crypto
6347868ee15c7b79676df58bef54376a8dc6fd02
[ "MIT" ]
null
null
null
lib/arkecosystem/crypto/helpers/map_key_transformer.ex
whitehat/elixir-crypto
6347868ee15c7b79676df58bef54376a8dc6fd02
[ "MIT" ]
null
null
null
defmodule ArkEcosystem.Crypto.Helpers.MapKeyTransformer do def underscore(map) when is_map(map) do transform_map(map, &Macro.underscore/1) end def camelCase(map) when is_map(map) do transform_map(map, &camelizer/1) end defp transform_map(map, transformer) when is_map(map) do Map.keys(map) |> transform_keys(map, transformer) end defp transform_keys(keys, map, transformer) when length(keys) > 0 do {key, keys} = List.pop_at(keys, 0) value = Map.get(map, key) transformed_key = transform_key(key, transformer) map = cond do is_map(value) -> nested_keys = Map.keys(value) transformed_map = transform_keys(nested_keys, value, transformer) write_key(map, key, transformed_key, transformed_map) is_list(value) -> transformed_list = Enum.map(value, fn item -> transform_list_value(item, transformer) end) write_key(map, key, transformed_key, transformed_list) true -> write_key(map, key, transformed_key, value) end transform_keys(keys, map, transformer) end defp transform_keys(keys, map, _transformer) when length(keys) == 0 do map end defp transform_list_value(value, transformer) do cond do is_map(value) -> transform_map(value, transformer) is_list(value) -> Enum.map(value, fn item -> transform_list_value(item, transformer) end) true -> value end end defp transform_key(key, transformer) do key |> Atom.to_string() |> transformer.() |> String.to_atom() end defp write_key(map, old_key, new_key, value) do Map.delete(map, old_key) |> Map.put(new_key, value) end # Macro.camelize turns public_key into PublicKey, so # an additional step is necessary to downcase the first character. defp camelizer(key) do camelized = key |> Macro.camelize() String.downcase(String.first(camelized)) <> String.slice(camelized, 1, String.length(camelized)) end end
26.986667
83
0.66996
1c092ccbc1f45581815d37334a2754118184c695
2,097
exs
Elixir
mix.exs
sneako/fastimage
01562b7eb268b207e0a662d27e6f5380c6e40798
[ "MIT" ]
null
null
null
mix.exs
sneako/fastimage
01562b7eb268b207e0a662d27e6f5380c6e40798
[ "MIT" ]
1
2018-10-03T12:02:24.000Z
2018-10-03T12:02:24.000Z
mix.exs
sneako/fastimage
01562b7eb268b207e0a662d27e6f5380c6e40798
[ "MIT" ]
null
null
null
defmodule Fastimage.Mixfile do use Mix.Project @name "Fastimage" @version "1.0.0-rc3" @source "https://github.com/stephenmoloney/fastimage" @maintainers ["Stephen Moloney"] @elixir_versions ">= 1.4.0" @allowed_hackney_versions ~w(1.6 1.7 1.8 1.9 1.13 1.14) @hackney_versions "~> " <> Enum.join(@allowed_hackney_versions, " or ~> ") def project do [ app: :fastimage, name: @name, version: @version, source_url: @source, elixir: @elixir_versions, build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, preferred_cli_env: coveralls(), test_coverage: [ tool: ExCoveralls ], description: description(), deps: deps(), package: package(), docs: docs(), aliases: aliases() ] end def application do [ extra_applications: [] ] end defp deps do [ {:hackney, @hackney_versions}, # dev/test only {:excoveralls, "~> 0.10", only: [:test], runtime: false}, {:benchfella, "~> 0.3", only: [:dev], runtime: false}, {:credo, "~> 0.10", only: [:dev, :test], runtime: false}, {:earmark, "~> 1.2", only: [:dev], runtime: false}, {:ex_doc, "~> 0.19", only: [:dev], runtime: false} ] end defp description do """ #{@name} finds the dimensions/size or file type of a remote or local image file given the file path or uri respectively. """ end defp package do %{ licenses: ["MIT"], maintainers: @maintainers, links: %{"GitHub" => @source}, files: ~w(priv bench/fastimage_bench.exs lib mix.exs README* LICENCE* CHANGELOG*) } end defp docs do [ main: "api-reference" ] end defp aliases do [ prep: ["clean", "format", "compile", "credo #{credo_args()}"] ] end defp credo_args do "--strict --ignore maxlinelength,cyclomaticcomplexity,todo" end def coveralls do [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ] end end
22.793478
87
0.577969
1c098579b1a993ecba2ba5f383ac998d0635b707
912
ex
Elixir
clients/my_business_verifications/lib/google_api/my_business_verifications/v1/metadata.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/my_business_verifications/lib/google_api/my_business_verifications/v1/metadata.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/my_business_verifications/lib/google_api/my_business_verifications/v1/metadata.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 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.MyBusinessVerifications.V1 do @moduledoc """ API client metadata for GoogleApi.MyBusinessVerifications.V1. """ @discovery_revision "20211207" def discovery_revision(), do: @discovery_revision end
33.777778
74
0.766447
1c09bceef4ef412466dfff3185942d414dcb1216
136
ex
Elixir
lib/bible_study_spreadsheet/repo.ex
dbishai/bible-study-spreadsheet
9009cf8c343c215b2d8d6c1d8d24fd1ed2219434
[ "MIT" ]
null
null
null
lib/bible_study_spreadsheet/repo.ex
dbishai/bible-study-spreadsheet
9009cf8c343c215b2d8d6c1d8d24fd1ed2219434
[ "MIT" ]
1
2021-03-10T06:25:15.000Z
2021-03-10T06:25:15.000Z
lib/bible_study_spreadsheet/repo.ex
dbishai/bible-study-spreadsheet
9009cf8c343c215b2d8d6c1d8d24fd1ed2219434
[ "MIT" ]
null
null
null
defmodule BibleStudySpreadsheet.Repo do use Ecto.Repo, otp_app: :bible_study_spreadsheet, adapter: Ecto.Adapters.Postgres end
22.666667
39
0.786765
1c09c755ce3a1b362efbbfc103591dd182dda37b
258
exs
Elixir
apps/snitch_core/priv/repo/migrations/20180828204145_add_product_assoc_to_line_item.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/snitch_core/priv/repo/migrations/20180828204145_add_product_assoc_to_line_item.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/snitch_core/priv/repo/migrations/20180828204145_add_product_assoc_to_line_item.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule Snitch.Repo.Migrations.AddProductAssocToLineItem do use Ecto.Migration def change do alter table("snitch_line_items") do remove :variant_id add :product_id, references("snitch_products", on_delete: :restrict) end end end
23.454545
74
0.744186
1c09cb2a778baeb12b637644606a937bf4801800
1,123
ex
Elixir
lib/jukee_web/controllers/api/session_controller.ex
samuelbriole/Jukee
1f0dd7616d63d742fac17daabaf50b406d9dbede
[ "MIT" ]
3
2018-05-17T17:43:06.000Z
2018-06-09T02:12:25.000Z
lib/jukee_web/controllers/api/session_controller.ex
samuelbriole/Jukee
1f0dd7616d63d742fac17daabaf50b406d9dbede
[ "MIT" ]
2
2018-06-04T15:51:36.000Z
2018-06-20T11:31:23.000Z
lib/jukee_web/controllers/api/session_controller.ex
samuelbriole/jukee
1f0dd7616d63d742fac17daabaf50b406d9dbede
[ "MIT" ]
null
null
null
defmodule JukeeWeb.SessionController do use JukeeWeb, :controller alias Jukee.Accounts action_fallback(JukeeWeb.FallbackController) def create(conn, params) do with {:ok, user} <- Accounts.authenticate(params) do new_conn = Accounts.sign_in_user(conn, user) jwt = Accounts.get_current_token(new_conn) spawn(fn -> Accounts.update_last_login(user) end) new_conn |> put_status(:created) |> render("show.json", user: user, jwt: jwt) end end def delete(conn, _) do user = Accounts.get_current_user(conn) with new_conn = Accounts.sign_out(conn) do spawn(fn -> Accounts.update_last_login(user) end) new_conn |> put_status(:ok) |> render("delete.json") end end def refresh(conn, _params) do user = Accounts.get_current_user(conn) with jwt = Accounts.get_current_token(conn), {:ok, _, {new_jwt, _new_claims}} <- Accounts.refresh_token(jwt) do spawn(fn -> Accounts.update_last_login(user) end) conn |> put_status(:ok) |> render("show.json", user: user, jwt: new_jwt) end end end
24.413043
75
0.66073
1c09d25cdcbc4dc10ce7f12d3086bbf166e8646d
11,125
ex
Elixir
clients/android_management/lib/google_api/android_management/v1/model/device.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/android_management/lib/google_api/android_management/v1/model/device.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/device.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "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.AndroidManagement.V1.Model.Device do @moduledoc """ A device owned by an enterprise. Unless otherwise noted, all fields are read-only and can't be modified by enterprises.devices.patch. ## Attributes * `apiLevel` (*type:* `integer()`, *default:* `nil`) - The API level of the Android platform version running on the device. * `applicationReports` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.ApplicationReport.t)`, *default:* `nil`) - Reports for apps installed on the device. This information is only available when application_reports_enabled is true in the device's policy. * `appliedPolicyName` (*type:* `String.t`, *default:* `nil`) - The name of the policy currently applied to the device. * `appliedPolicyVersion` (*type:* `String.t`, *default:* `nil`) - The version of the policy currently applied to the device. * `appliedState` (*type:* `String.t`, *default:* `nil`) - The state currently applied to the device. * `deviceSettings` (*type:* `GoogleApi.AndroidManagement.V1.Model.DeviceSettings.t`, *default:* `nil`) - Device settings information. This information is only available if deviceSettingsEnabled is true in the device's policy. * `disabledReason` (*type:* `GoogleApi.AndroidManagement.V1.Model.UserFacingMessage.t`, *default:* `nil`) - If the device state is DISABLED, an optional message that is displayed on the device indicating the reason the device is disabled. This field can be modified by a patch request. * `displays` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.Display.t)`, *default:* `nil`) - Detailed information about displays on the device. This information is only available if displayInfoEnabled is true in the device's policy. * `enrollmentTime` (*type:* `DateTime.t`, *default:* `nil`) - The time of device enrollment. * `enrollmentTokenData` (*type:* `String.t`, *default:* `nil`) - If the device was enrolled with an enrollment token with additional data provided, this field contains that data. * `enrollmentTokenName` (*type:* `String.t`, *default:* `nil`) - If the device was enrolled with an enrollment token, this field contains the name of the token. * `hardwareInfo` (*type:* `GoogleApi.AndroidManagement.V1.Model.HardwareInfo.t`, *default:* `nil`) - Detailed information about the device hardware. * `hardwareStatusSamples` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.HardwareStatus.t)`, *default:* `nil`) - Hardware status samples in chronological order. This information is only available if hardwareStatusEnabled is true in the device's policy. * `lastPolicyComplianceReportTime` (*type:* `DateTime.t`, *default:* `nil`) - Deprecated. * `lastPolicySyncTime` (*type:* `DateTime.t`, *default:* `nil`) - The last time the device fetched its policy. * `lastStatusReportTime` (*type:* `DateTime.t`, *default:* `nil`) - The last time the device sent a status report. * `managementMode` (*type:* `String.t`, *default:* `nil`) - The type of management mode Android Device Policy takes on the device. This influences which policy settings are supported. * `memoryEvents` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.MemoryEvent.t)`, *default:* `nil`) - Events related to memory and storage measurements in chronological order. This information is only available if memoryInfoEnabled is true in the device's policy. * `memoryInfo` (*type:* `GoogleApi.AndroidManagement.V1.Model.MemoryInfo.t`, *default:* `nil`) - Memory information. This information is only available if memoryInfoEnabled is true in the device's policy. * `name` (*type:* `String.t`, *default:* `nil`) - The name of the device in the form enterprises/{enterpriseId}/devices/{deviceId}. * `networkInfo` (*type:* `GoogleApi.AndroidManagement.V1.Model.NetworkInfo.t`, *default:* `nil`) - Device network information. This information is only available if networkInfoEnabled is true in the device's policy. * `nonComplianceDetails` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.NonComplianceDetail.t)`, *default:* `nil`) - Details about policy settings that the device is not compliant with. * `policyCompliant` (*type:* `boolean()`, *default:* `nil`) - Whether the device is compliant with its policy. * `policyName` (*type:* `String.t`, *default:* `nil`) - The name of the policy applied to the device, in the form enterprises/{enterpriseId}/policies/{policyId}. If not specified, the policy_name for the device's user is applied. This field can be modified by a patch request. You can specify only the policyId when calling enterprises.devices.patch, as long as the policyId doesn’t contain any slashes. The rest of the policy name is inferred. * `powerManagementEvents` (*type:* `list(GoogleApi.AndroidManagement.V1.Model.PowerManagementEvent.t)`, *default:* `nil`) - Power management events on the device in chronological order. This information is only available if powerManagementEventsEnabled is true in the device's policy. * `previousDeviceNames` (*type:* `list(String.t)`, *default:* `nil`) - If the same physical device has been enrolled multiple times, this field contains its previous device names. The serial number is used as the unique identifier to determine if the same physical device has enrolled previously. The names are in chronological order. * `softwareInfo` (*type:* `GoogleApi.AndroidManagement.V1.Model.SoftwareInfo.t`, *default:* `nil`) - Detailed information about the device software. This information is only available if softwareInfoEnabled is true in the device's policy. * `state` (*type:* `String.t`, *default:* `nil`) - The state to be applied to the device. This field can be modified by a patch request. Note that when calling enterprises.devices.patch, ACTIVE and DISABLED are the only allowable values. To enter the device into a DELETED state, call enterprises.devices.delete. * `systemProperties` (*type:* `map()`, *default:* `nil`) - Map of selected system properties name and value related to the device. * `user` (*type:* `GoogleApi.AndroidManagement.V1.Model.User.t`, *default:* `nil`) - The user who owns the device. * `userName` (*type:* `String.t`, *default:* `nil`) - The resource name of the user that owns this device in the form enterprises/{enterpriseId}/users/{userId}. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :apiLevel => integer(), :applicationReports => list(GoogleApi.AndroidManagement.V1.Model.ApplicationReport.t()), :appliedPolicyName => String.t(), :appliedPolicyVersion => String.t(), :appliedState => String.t(), :deviceSettings => GoogleApi.AndroidManagement.V1.Model.DeviceSettings.t(), :disabledReason => GoogleApi.AndroidManagement.V1.Model.UserFacingMessage.t(), :displays => list(GoogleApi.AndroidManagement.V1.Model.Display.t()), :enrollmentTime => DateTime.t(), :enrollmentTokenData => String.t(), :enrollmentTokenName => String.t(), :hardwareInfo => GoogleApi.AndroidManagement.V1.Model.HardwareInfo.t(), :hardwareStatusSamples => list(GoogleApi.AndroidManagement.V1.Model.HardwareStatus.t()), :lastPolicyComplianceReportTime => DateTime.t(), :lastPolicySyncTime => DateTime.t(), :lastStatusReportTime => DateTime.t(), :managementMode => String.t(), :memoryEvents => list(GoogleApi.AndroidManagement.V1.Model.MemoryEvent.t()), :memoryInfo => GoogleApi.AndroidManagement.V1.Model.MemoryInfo.t(), :name => String.t(), :networkInfo => GoogleApi.AndroidManagement.V1.Model.NetworkInfo.t(), :nonComplianceDetails => list(GoogleApi.AndroidManagement.V1.Model.NonComplianceDetail.t()), :policyCompliant => boolean(), :policyName => String.t(), :powerManagementEvents => list(GoogleApi.AndroidManagement.V1.Model.PowerManagementEvent.t()), :previousDeviceNames => list(String.t()), :softwareInfo => GoogleApi.AndroidManagement.V1.Model.SoftwareInfo.t(), :state => String.t(), :systemProperties => map(), :user => GoogleApi.AndroidManagement.V1.Model.User.t(), :userName => String.t() } field(:apiLevel) field( :applicationReports, as: GoogleApi.AndroidManagement.V1.Model.ApplicationReport, type: :list ) field(:appliedPolicyName) field(:appliedPolicyVersion) field(:appliedState) field(:deviceSettings, as: GoogleApi.AndroidManagement.V1.Model.DeviceSettings) field(:disabledReason, as: GoogleApi.AndroidManagement.V1.Model.UserFacingMessage) field(:displays, as: GoogleApi.AndroidManagement.V1.Model.Display, type: :list) field(:enrollmentTime, as: DateTime) field(:enrollmentTokenData) field(:enrollmentTokenName) field(:hardwareInfo, as: GoogleApi.AndroidManagement.V1.Model.HardwareInfo) field( :hardwareStatusSamples, as: GoogleApi.AndroidManagement.V1.Model.HardwareStatus, type: :list ) field(:lastPolicyComplianceReportTime, as: DateTime) field(:lastPolicySyncTime, as: DateTime) field(:lastStatusReportTime, as: DateTime) field(:managementMode) field(:memoryEvents, as: GoogleApi.AndroidManagement.V1.Model.MemoryEvent, type: :list) field(:memoryInfo, as: GoogleApi.AndroidManagement.V1.Model.MemoryInfo) field(:name) field(:networkInfo, as: GoogleApi.AndroidManagement.V1.Model.NetworkInfo) field( :nonComplianceDetails, as: GoogleApi.AndroidManagement.V1.Model.NonComplianceDetail, type: :list ) field(:policyCompliant) field(:policyName) field( :powerManagementEvents, as: GoogleApi.AndroidManagement.V1.Model.PowerManagementEvent, type: :list ) field(:previousDeviceNames, type: :list) field(:softwareInfo, as: GoogleApi.AndroidManagement.V1.Model.SoftwareInfo) field(:state) field(:systemProperties, type: :map) field(:user, as: GoogleApi.AndroidManagement.V1.Model.User) field(:userName) end defimpl Poison.Decoder, for: GoogleApi.AndroidManagement.V1.Model.Device do def decode(value, options) do GoogleApi.AndroidManagement.V1.Model.Device.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidManagement.V1.Model.Device do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
68.251534
448
0.726112
1c09dac59659f163ba092ce2ebab4874e3ce0c59
541
exs
Elixir
farmbot_ext/test/farmbot_ext/mqtt/support_test.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
843
2016-10-05T23:46:05.000Z
2022-03-14T04:31:55.000Z
farmbot_ext/test/farmbot_ext/mqtt/support_test.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
455
2016-10-15T08:49:16.000Z
2022-03-15T12:23:04.000Z
farmbot_ext/test/farmbot_ext/mqtt/support_test.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
261
2016-10-10T04:37:06.000Z
2022-03-13T21:07:38.000Z
defmodule FarmbotExt.MQTT.SupportTest do use ExUnit.Case use Mimic alias FarmbotExt.MQTT.Support test "forward_message" do msg = {"topic", "message"} assert nil == Support.forward_message(nil, msg) pid = NoOp.new(name: :forward_message_stub) Support.forward_message(pid, msg) assert NoOp.last_message(pid) == {:inbound, "topic", "message"} Support.forward_message(:forward_message_stub, {"topicb", "by name"}) assert NoOp.last_message(pid) == {:inbound, "topicb", "by name"} NoOp.stop(pid) end end
31.823529
73
0.696858
1c0a04c62ec951d16ff24b644be6c0ad165e3277
4,535
ex
Elixir
lib/graph_reasoner/query_info/query_info.ex
langens-jonathan/mu-authorization
3b411460b81b87581af7c7f302b1d3bec4610608
[ "MIT" ]
1
2019-09-05T23:00:48.000Z
2019-09-05T23:00:48.000Z
lib/graph_reasoner/query_info/query_info.ex
langens-jonathan/mu-authorization
3b411460b81b87581af7c7f302b1d3bec4610608
[ "MIT" ]
7
2020-10-27T20:42:06.000Z
2021-11-15T07:41:15.000Z
lib/graph_reasoner/query_info/query_info.ex
langens-jonathan/mu-authorization
3b411460b81b87581af7c7f302b1d3bec4610608
[ "MIT" ]
6
2016-04-06T09:28:43.000Z
2021-08-09T12:29:16.000Z
# A strategy for defining access # # We will attach graph constraints to the predicates # # We will assume the WHERE block has been converted into simple triple # statements. # # 1. Derive types for variables # 2. Derive types for subjects (already known if that is a variable) # 3. Derive types for objects (already known if that is a variable) # # 3. Attach graphs to predicates based on types and predicate # # later: 1 and 2 will be combined so we can iterate on the gained knowledge. # later: 2 will also attach types to the object type of the triple alias GraphReasoner.QueryInfo, as: QueryInfo defmodule QueryInfo do defstruct terms_map: %{ term_ids_index: 0, term_info_index: 0, term_ids: %{}, term_info: %{} } @type t :: %QueryInfo{terms_map: terms_map} @type terms_map :: %{ term_ids_index: integer(), term_info_index: integer(), term_ids: %{optional(number) => number}, term_info: %{optional(number) => %{optional(atom) => any}} } @doc """ Yields the terms map. """ def terms_map(%QueryInfo{terms_map: terms_map}) do terms_map end @doc """ Sets the terms_map to a new value. """ def set_terms_map(query_info, new_terms_map) do %{query_info | terms_map: new_terms_map} end @doc """ Adds a property to the terms map with given name. Currently supported names are: - :related_paths If the info was already known, it is not overwritten. """ @spec push_term_info(t, any, atom(), any) :: t def push_term_info(%QueryInfo{terms_map: terms_map} = query_info, symbol, section, value) do renamed_term_id = renamed_term_id(query_info, symbol) new_terms_map = update_in( terms_map[:term_info][renamed_term_id][section], fn related_paths -> related_paths = related_paths || [] # Push value if it does not exist if Enum.member?(related_paths, value) do related_paths else [value | related_paths] end end ) %{query_info | terms_map: new_terms_map} end @doc """ Initializes a term for use in the QueryInfo. Yields the new QueryInfo instance as well as the term. This embodies calculating a new index, and attaching it to the item. Basic information for this term can optionally be supplied. """ @spec init_term(t, any, %{optional(atom) => any}) :: {t, any} def init_term(%QueryInfo{terms_map: terms_map} = query_info, term, info \\ %{}) do %{ term_ids: term_ids, term_info: term_info, term_ids_index: term_ids_index, term_info_index: term_info_index } = terms_map new_term_ids_index = term_ids_index + 1 new_term_info_index = term_info_index + 1 new_term_ids = Map.put(term_ids, new_term_ids_index, new_term_info_index) new_term_info = Map.put(term_info, new_term_info_index, info) new_term = ExternalInfo.put(term, GraphReasoner, :term_id, new_term_ids_index) new_terms_map = terms_map |> Map.put(:term_ids, new_term_ids) |> Map.put(:term_info, new_term_info) |> Map.put(:term_ids_index, new_term_ids_index) |> Map.put(:term_info_index, new_term_info_index) {%{query_info | terms_map: new_terms_map}, new_term} end @doc """ Retrieves scoped subject info for a term as known by the QueryInfo. """ @spec get_term_info(t, any, atom) :: any def get_term_info(query_info, symbol, section) do query_info.terms_map[:term_info][renamed_term_id(query_info, symbol)][section] end @doc """ Retrieves scoped subject info for a term as known by the QueryInfo identified by its id. """ @spec get_term_info_by_id(t, number, atom) :: any def get_term_info_by_id(query_info, term_id, section) do query_info.terms_map[:term_info][term_id][section] end @doc """ Sets scoped subject info for a term as known by the QueryInfo identified by its id. """ @spec set_term_info_by_id(t, number, atom, any) :: t def set_term_info_by_id(query_info, term_id, section, value) do terms_map = query_info.terms_map new_terms_map = update_in( terms_map[:term_info][term_id][section], fn _old -> value end ) %{query_info | terms_map: new_terms_map} end @spec renamed_term_id(t, any) :: number defp renamed_term_id(%QueryInfo{terms_map: terms_map}, symbol) do term_id = ExternalInfo.get(symbol, GraphReasoner, :term_id) terms_map.term_ids[term_id] end end
30.436242
94
0.676736
1c0a05d771b19271b50523acfdd888e1f2346160
5,559
ex
Elixir
lib/liblink/cluster/protocol/dealer/impl.ex
Xerpa/liblink
7b983431c5b391bb8cf182edd9ca4937601eea35
[ "Apache-2.0" ]
3
2018-10-26T12:55:15.000Z
2019-05-03T22:41:34.000Z
lib/liblink/cluster/protocol/dealer/impl.ex
Xerpa/liblink
7b983431c5b391bb8cf182edd9ca4937601eea35
[ "Apache-2.0" ]
4
2018-08-26T14:43:57.000Z
2020-09-23T21:14:56.000Z
lib/liblink/cluster/protocol/dealer/impl.ex
Xerpa/liblink
7b983431c5b391bb8cf182edd9ca4937601eea35
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2018 Xerpa # 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 Liblink.Cluster.Protocol.Dealer.Impl do use Liblink.Logger alias Liblink.Timeout alias Liblink.Socket alias Liblink.Socket.Device alias Liblink.Data.Keyword alias Liblink.Data.Balance import Liblink.Guards @type state_t :: %{ devices: MapSet.t(Device.t()), balance: Balance.t(), requests: map, timeouts: map } @type sendmsg_opt :: {:timeout_in_ms, timeout} | {:restrict_fn, (MapSet.t(Device.t()) -> MapSet.t(Device.t()))} @type option :: {:balance, :round_robin} @spec new([option]) :: {:ok, state_t} | {:error, {:devices | :balance, :bad_value}} | Keyword.fetch_error() def new(options) when is_list(options) do with {:ok, algorithm} <- Keyword.fetch_atom(options, :balance, :round_robin), {_, true} <- {:balance, algorithm == :round_robin} do {:ok, %{ devices: MapSet.new(), balance: &Balance.round_robin/1, requests: %{}, timeouts: %{} }} else {key, false} -> {:error, {key, :bad_value}} error = {:error, _} -> error end end @spec add_device(Device.t(), state_t) :: {:reply, :ok | :error, state_t} def add_device(device = %Device{}, state) do if MapSet.member?(state.devices, device) do {:reply, :ok, state} else case Socket.consume(device, self()) do :ok -> state = Map.update!(state, :devices, &MapSet.put(&1, device)) {:reply, :ok, state} _error -> {:reply, :error, state} end end end @spec devices(state_t) :: {:reply, [Device.t()], state_t} def devices(state) do {:reply, state.devices, state} end @spec halt(state_t) :: {:stop, :normal, state_t} def halt(state) do {:stop, :normal, %{state | devices: MapSet.new()}} end @spec del_device(Device.t(), state_t) :: {:reply, :ok, state_t} def del_device(device = %Device{}, state) do if MapSet.member?(state.devices, device) do _ = Socket.halt_consumer(device) end state = Map.update!(state, :devices, &MapSet.delete(&1, device)) {:reply, :ok, state} end @spec sendmsg(iodata, pid, [sendmsg_opt], state_t) :: {:reply, {:ok, binary} | {:error, :no_connection}, state_t} def sendmsg(message, from, opts, state) when is_iodata(message) and is_pid(from) and is_list(opts) do tag = new_tag(state) payload = [tag | List.wrap(message)] timeout = case Keyword.fetch(opts, :timeout_in_ms) do {:ok, timeout} when is_integer(timeout) -> timeout {:ok, :infinity} -> :infinity _error -> 1_000 end restrict_fn = case Keyword.fetch_function(opts, :restrict_fn) do {:ok, restrict_fn} when is_function(restrict_fn, 1) -> restrict_fn _error -> fn x -> x end end deadline = if timeout == :infinity do :infinity else Timeout.deadline(timeout, :millisecond) end request_entry = {from, deadline} case state.balance.(restrict_fn.(state.devices)) do :error -> {:reply, {:error, :no_connection}, state} {:ok, device} -> state = if timeout == :infinity do Map.update!(state, :requests, &Map.put_new(&1, tag, request_entry)) else state |> Map.update!(:timeouts, &Map.put_new(&1, tag, deadline)) |> Map.update!(:requests, &Map.put_new(&1, tag, request_entry)) end :ok = Socket.sendmsg_async(device, payload) {:reply, {:ok, tag}, state} end end @spec route_message(iodata, state_t) :: {:noreply, state_t} def route_message([tag | message], state) do case Map.pop(state.requests, tag) do {{from, deadline}, requests} -> unless Timeout.deadline_expired?(deadline) do send(from, {tag, message}) end timeouts = Map.delete(state.timeouts, tag) {:noreply, %{state | requests: requests, timeouts: timeouts}} {nil, _requests} -> Liblink.Logger.warn("ignoring expired reply message=#{inspect(message)}") {:noreply, state} end end @spec timeout_step(state_t) :: {:noreply, state_t} def timeout_step(state, sysnow \\ nil) do sysnow = sysnow || Timeout.current() {expired, timeouts} = Enum.reduce(state.timeouts, {[], %{}}, fn {tag, deadline}, {dead, alive} -> if Timeout.deadline_expired?(deadline, sysnow) do {[tag | dead], alive} else {dead, Map.put(alive, tag, deadline)} end end) state = state |> Map.put(:timeouts, timeouts) |> Map.update!(:requests, &Map.drop(&1, expired)) {:noreply, state} end def timeout_interval, do: 1_000 defp new_tag(state) do tag = :crypto.strong_rand_bytes(16) if Map.has_key?(state.requests, tag) do new_tag(state) else tag end end end
27.384236
94
0.598489
1c0a443cdb8a7dcc6128540743ea54bc70c40dcb
1,970
exs
Elixir
config/prod.exs
SquashConsulting/hopper
d68ac8b4749b2411959c2ba7be7cd9402a3e4b2b
[ "BSD-3-Clause" ]
1
2019-12-22T16:00:11.000Z
2019-12-22T16:00:11.000Z
config/prod.exs
SquashConsulting/hopper
d68ac8b4749b2411959c2ba7be7cd9402a3e4b2b
[ "BSD-3-Clause" ]
2
2021-03-10T02:31:42.000Z
2021-05-10T22:02:29.000Z
config/prod.exs
SquashConsulting/hopper
d68ac8b4749b2411959c2ba7be7cd9402a3e4b2b
[ "BSD-3-Clause" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :hopper, HopperWeb.Endpoint, url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :hopper, HopperWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # :inet6, # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :hopper, HopperWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
35.178571
66
0.71269