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
1c0a58e39a687afdb256a54c1fee7ddff0b91d40
1,527
ex
Elixir
frameworks/Elixir/phoenix/web/controllers/page_controller.ex
xitrum-framework/FrameworkBenchmarks
180d44e1064abc6fe8c703b05e065c0564e6ee05
[ "BSD-3-Clause" ]
1
2016-05-26T09:37:14.000Z
2016-05-26T09:37:14.000Z
frameworks/Elixir/phoenix/web/controllers/page_controller.ex
xitrum-framework/FrameworkBenchmarks
180d44e1064abc6fe8c703b05e065c0564e6ee05
[ "BSD-3-Clause" ]
null
null
null
frameworks/Elixir/phoenix/web/controllers/page_controller.ex
xitrum-framework/FrameworkBenchmarks
180d44e1064abc6fe8c703b05e065c0564e6ee05
[ "BSD-3-Clause" ]
1
2019-05-17T18:29:04.000Z
2019-05-17T18:29:04.000Z
defmodule Hello.PageController do use Hello.Web, :controller alias Hello.World alias Hello.Fortune def index(conn, _params) do json conn, %{"TE Benchmarks\n" => "Started"} end # avoid namespace collision def _json(conn, _params) do json conn, %{message: "Hello, world!"} end def db(conn, _params) do json conn, Repo.get(World, :random.uniform(10000)) end def queries(conn, params) do q = try do case String.to_integer(params["queries"]) do x when x < 1 -> 1 x when x > 500 -> 500 x -> x end rescue ArgumentError -> 1 end json conn, Enum.map(1..q, fn _ -> Repo.get(World, :random.uniform(10000)) end) end def fortunes(conn, _params) do fortunes = List.insert_at(Repo.all(Fortune), 0, %Fortune{:id => 0, :message => "Additional fortune added at request time."}) render conn, "fortunes.html", fortunes: Enum.sort(fortunes, fn f1, f2 -> f1.message < f2.message end) end def updates(conn, params) do q = try do case String.to_integer(params["queries"]) do x when x < 1 -> 1 x when x > 500 -> 500 x -> x end rescue ArgumentError -> 1 end json conn, Enum.map(1..q, fn _ -> w = Repo.get(World, :random.uniform(10000)) changeset = World.changeset(w, %{randomNumber: :random.uniform(10000)}) Repo.update(changeset) w end) end def plaintext(conn, _params) do text conn, "Hello, world!" end end
26.327586
129
0.59725
1c0a5bea1553127ff54509ce64568e0365dbab06
842
ex
Elixir
lib/trace.ex
chaodhib/spandex
58674c5440c7800658a52d199532a620406dcdd2
[ "MIT" ]
null
null
null
lib/trace.ex
chaodhib/spandex
58674c5440c7800658a52d199532a620406dcdd2
[ "MIT" ]
1
2018-10-04T13:29:32.000Z
2018-10-04T13:29:32.000Z
lib/trace.ex
chaodhib/spandex
58674c5440c7800658a52d199532a620406dcdd2
[ "MIT" ]
1
2019-08-08T16:40:10.000Z
2019-08-08T16:40:10.000Z
defmodule Spandex.Trace do @moduledoc """ A representation of an ongoing trace. * `baggage`: Key-value metadata about the overall trace (propagated across distributed service) * `id`: The trace ID, which consistently refers to this trace across distributed services * `priority`: The trace sampling priority for this trace (propagated across distributed services) * `spans`: The set of completed spans for this trace from this proces * `stack`: The stack of active parent spans """ defstruct baggage: [], id: nil, priority: 1, spans: [], stack: [] @typedoc @moduledoc @type t :: %__MODULE__{ baggage: Keyword.t(), id: Spandex.id(), priority: integer(), spans: [Spandex.Span.t()], stack: [Spandex.Span.t()] } end
32.384615
99
0.622328
1c0a72bb2183a3b503400b495631e9df1d2d502f
1,445
exs
Elixir
mix.exs
rhumbertgz/elixir_qlib
dcebca8dac8a2070ba098b209b6754daf1f49235
[ "Apache-2.0" ]
3
2016-10-05T21:34:47.000Z
2021-04-21T15:02:47.000Z
mix.exs
rhumbertgz/elixir_qlib
dcebca8dac8a2070ba098b209b6754daf1f49235
[ "Apache-2.0" ]
null
null
null
mix.exs
rhumbertgz/elixir_qlib
dcebca8dac8a2070ba098b209b6754daf1f49235
[ "Apache-2.0" ]
null
null
null
defmodule ElixirQlib.Mixfile do use Mix.Project @version "0.1.1" def project do [app: :elixir_qlib, version: @version, elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps(), # Hex description: description(), package: package(), # Docs name: "Elixir QLib", source_url: "https://github.com/rhumbertgz/elixir_qlib", docs: [source_ref: "v#{@version}", canonical: "https://hexdocs.com/elixir_qlib/", main: ElixirQlib, extras: ["README.md", "CONTRIBUTING.md"]]] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [{:ex_doc, ">= 0.0.0", only: :dev}] end defp description do """ A simple queue abstraction library to support leasing and buffering in Elixir. """ end defp package do [maintainers: ["Humberto Rodriguez Avila"], licenses: ["Apache 2.0"], links: %{"GitHub" => "https://github.com/rhumbertgz/elixir_qlib"}, files: ~w(mix.exs README.md CHANGELOG.md lib) ] end end
24.083333
82
0.605536
1c0a866e9ecd820e2885784863936b651cefc645
270
ex
Elixir
web/models/jam_stat.ex
jeffcole/loops
8d1f8345140182905dfc1967af135205b82f2cdc
[ "MIT" ]
null
null
null
web/models/jam_stat.ex
jeffcole/loops
8d1f8345140182905dfc1967af135205b82f2cdc
[ "MIT" ]
null
null
null
web/models/jam_stat.ex
jeffcole/loops
8d1f8345140182905dfc1967af135205b82f2cdc
[ "MIT" ]
null
null
null
defmodule LoopsWithFriends.JamStat do @moduledoc """ Jam statistics for a given point in time. """ use LoopsWithFriends.Web, :model schema "jam_stats" do belongs_to :app_stat, AppStat field :jam_id, :string field :user_count, :integer end end
18
43
0.703704
1c0ab2b767aa67efbd773d2f53275e06d2f7843c
11,462
ex
Elixir
lib/web/user.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
lib/web/user.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
lib/web/user.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
defmodule Web.User do @moduledoc """ Bounded context for the Phoenix app talking to the data layer """ import Ecto.Query require Logger alias Data.Repo alias Data.User alias Data.User.OneTimePassword alias ExVenture.Mailer alias Game.Account alias Game.Config alias Game.Emails alias Game.Session.Registry, as: SessionRegistry alias Metrics.PlayerInstrumenter alias Web.Character alias Web.Filter alias Web.Pagination @behaviour Filter @doc """ User flags """ @spec flags() :: [String.t()] def flags(), do: ["admin", "disabled"] @doc """ Check if a player is disabled """ def disabled?(player) do "disabled" in player.flags end @doc """ Fetch a user from a web token """ @spec from_token(token :: String.t()) :: User.t() def from_token(token) do User |> where([u], u.token == ^token) |> preload([:characters]) |> Repo.one() end @doc """ Load all users """ @spec all(opts :: Keyword.t()) :: [User.t()] def all(opts \\ []) do opts = Enum.into(opts, %{}) User |> order_by([u], desc: u.updated_at) |> Filter.filter(opts[:filter], __MODULE__) |> Pagination.paginate(opts) end @impl Filter def filter_on_attribute({"level_from", level}, query) do query |> where([u], fragment("?->>'level' >= ?", u.save, ^to_string(level))) end def filter_on_attribute({"level_to", level}, query) do query |> where([u], fragment("?->>'level' <= ?", u.save, ^to_string(level))) end def filter_on_attribute({"name", name}, query) do query |> where([u], ilike(u.name, ^"%#{name}%")) end def filter_on_attribute({"class_id", class_id}, query) do query |> where([u], u.class_id == ^class_id) end def filter_on_attribute({"race_id", race_id}, query) do query |> where([u], u.race_id == ^race_id) end def filter_on_attribute(_, query), do: query @doc """ Load a user """ @spec get(id :: integer) :: User.t() def get(id) do User |> where([u], u.id == ^id) |> preload([ sessions: ^from(s in User.Session, order_by: [desc: s.started_at], limit: 10) ]) |> preload(characters: [quest_progress: [:quest]]) |> Repo.one() end @doc """ Get a user by their name """ @spec get_by(Keyword.t()) :: {:ok, User.t()} | {:error, :not_found} def get_by(name: name) do case Repo.get_by(User, name: name) do nil -> {:error, :not_found} user -> {:ok, user} end end @doc """ Get a changeset for a new page """ @spec new() :: changeset :: map def new(), do: %User{} |> User.changeset(%{}) @doc """ Get a changeset for an edit page """ @spec edit(User.t()) :: changeset :: map def edit(user), do: user |> User.changeset(%{}) @doc """ Get a changeset for an edit page """ @spec email_changeset(User.t()) :: map() def email_changeset(user), do: user |> User.email_changeset(%{}) @doc """ Get a changeset for finalizing registration """ def finalize(user), do: user |> User.finalize_changeset(%{}) @doc """ Create a new user """ @spec create(params :: map) :: {:ok, User.t()} | {:error, changeset :: map} def create(params) do case Repo.transaction(fn -> _create(params) end) do {:ok, result} -> result {:error, result} -> result end end def _create(params) do with {:ok, user} <- create_user(params) do case Character.create(user, params) do {:ok, character} -> Account.maybe_email_welcome(user) Config.claim_character_name(character.name) {:ok, user, character} {:error, changeset} -> user_changeset = user |> Ecto.Changeset.change() |> Map.put(:action, :insert) |> Map.put(:errors, changeset.errors) Repo.rollback({:error, user_changeset}) end else {:error, changeset} -> Repo.rollback({:error, changeset}) end end defp create_user(params) do %User{} |> User.changeset(params) |> Repo.insert() end @doc """ Update a user """ @spec update(integer(), map()) :: {:ok, User.t()} | {:error, changeset :: map} def update(id, params) do id |> get() |> User.changeset(cast_params(params)) |> Repo.update() end defp cast_params(params) do case Map.has_key?(params, "flags") do true -> flags = params |> Map.get("flags") |> Enum.reject(&(&1 == "")) Map.put(params, "flags", flags) false -> params end end @doc """ Finalize a user """ @spec finalize_user(User.t(), map()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()} def finalize_user(user, params) do user |> User.finalize_changeset(params) |> Repo.update() end @doc """ List out connected players """ @spec connected_players() :: [User.t()] def connected_players() do SessionRegistry.connected_players() |> Enum.map(& &1.player) end @doc """ Change a user's password """ @spec change_password(user :: User.t(), current_password :: String.t(), params :: map) :: {:ok, User.t()} def change_password(user, current_password, params) do case find_and_validate(user.name, current_password) do {:error, :invalid} -> {:error, :invalid} user -> user |> User.password_changeset(params) |> Repo.update() end end @doc """ Start the TOTP validation """ @spec create_totp_secret(User.t()) :: {:ok, OneTimePassword.t()} def create_totp_secret(user) do case {user.totp_secret, user.totp_verified_at} do {secret, nil} when secret != nil -> user _ -> user |> User.totp_changeset() |> Repo.update!() end end @doc """ The token was verified and TOTP should be turned on """ @spec totp_token_verified(User.t()) :: {:ok, OneTimePassword.t()} def totp_token_verified(user) do user |> User.totp_verified_changeset() |> Repo.update!() end @doc """ Clear the user's TOTP state """ @spec reset_totp(User.t()) :: {:ok, OneTimePassword.t()} def reset_totp(user) do user |> User.totp_reset_changeset() |> Repo.update!() end def generate_qr_png(user) do secret = Base.encode32(Base.decode32!(user.totp_secret), padding: false) issuer = URI.encode(Config.game_name()) url = "otpauth://totp/#{issuer}:#{user.name}?secret=#{secret}&issuer=#{issuer}" url |> EQRCode.encode() |> EQRCode.png() end @doc """ Check the TOTP token against the user """ @spec valid_totp_token?(User.t(), String.t()) :: boolean() def valid_totp_token?(user, token) do secret = Base.encode32(Base.decode32!(user.totp_secret, padding: false)) :pot.valid_totp(token, secret) end @doc """ Check if the user has TOTP on and verified """ @spec totp_verified?(User.t()) :: boolean() def totp_verified?(user) do !!user.totp_secret && !!user.totp_verified_at end @doc """ Attempt to find a user and validate their password """ @spec find_and_validate(String.t(), String.t()) :: {:error, :invalid} | User.t() def find_and_validate(name, password) do User |> where([u], ilike(u.name, ^name)) |> Repo.one() |> _find_and_validate(password) end defp _find_and_validate(nil, _password) do Comeonin.Bcrypt.dummy_checkpw() {:error, :invalid} end defp _find_and_validate(%{password_hash: nil}, _password) do Comeonin.Bcrypt.dummy_checkpw() {:error, :invalid} end defp _find_and_validate(user, password) do case Comeonin.Bcrypt.checkpw(password, user.password_hash) do true -> user _ -> {:error, :invalid} end end @doc """ Start password reset """ @spec start_password_reset(String.t()) :: :ok def start_password_reset(email) do PlayerInstrumenter.start_password_reset() query = User |> where([u], u.email == ^email) case query |> Repo.one() do nil -> Logger.warn("Password reset attempted for #{email}") :ok user -> Logger.info("Starting password reset for #{user.email}") user |> User.password_reset_changeset() |> Repo.update!() |> Emails.password_reset() |> Mailer.deliver_now() :ok end end @doc """ Reset a password """ @spec reset_password(String.t(), map()) :: {:ok, User.t()} def reset_password(token, params) do PlayerInstrumenter.password_reset() with {:ok, uuid} <- Ecto.UUID.cast(token), {:ok, user} <- find_user_by_reset_token(uuid), {:ok, user} <- check_password_reset_expired(user) do user |> User.password_changeset(params) |> Repo.update() end end defp find_user_by_reset_token(uuid) do query = User |> where([u], u.password_reset_token == ^uuid) case query |> Repo.one() do nil -> :error user -> {:ok, user} end end defp check_password_reset_expired(user) do case Timex.after?(Timex.now(), user.password_reset_expires_at) do true -> :error false -> {:ok, user} end end @doc """ Reset a password """ @spec change_email(User.t(), map()) :: {:ok, User.t()} def change_email(user, params) do user |> User.email_changeset(params) |> Repo.update() end @doc """ Authorize a connection """ @spec authorize_connection(Data.Character.t(), String.t()) :: :ok def authorize_connection(character, id) do SessionRegistry.authorize_connection(character, id) end @doc """ True if the user needs to be finalized and finish registration """ def finalize_registration?(user) do is_nil(user.name) end @doc """ Find or create a user who signed in from Grapevine """ def from_grapevine(auth) do params = %{ provider: to_string(auth.provider), provider_uid: auth.uid, name: auth.info.name, email: auth.info.email, } auth |> maybe_find_user() |> maybe_fully_register(params) |> maybe_partially_register(params) end defp maybe_find_user(auth) do provider = to_string(auth.provider) case Repo.get_by(User, provider: provider, provider_uid: auth.uid) do nil -> {:error, :not_found} user -> case is_nil(user.name) do true -> {:ok, :finalize_registration, user} false -> {:ok, user} end end end defp maybe_fully_register({:ok, user}, _params), do: {:ok, user} defp maybe_fully_register({:ok, :finalize_registration, user}, _params), do: {:ok, :finalize_registration, user} defp maybe_fully_register({:error, :not_found}, params) do %User{} |> User.grapevine_changeset(params) |> Repo.insert() end defp maybe_partially_register({:ok, user}, _params), do: {:ok, user} defp maybe_partially_register({:ok, :finalize_registration, user}, _params), do: {:ok, :finalize_registration, user} defp maybe_partially_register({:error, _changeset}, params) do params = params |> Map.delete(:email) |> Map.delete(:name) changeset = %User{} |> User.grapevine_changeset(params) case Repo.insert(changeset) do {:ok, user} -> {:ok, :finalize_registration, user} {:error, changeset} -> {:error, changeset} end end end
22.96994
118
0.601204
1c0af60a422704d55189149da78a9902b751b912
14,129
exs
Elixir
test/thrift/generator/service_test.exs
dnlserrano/elixir-thrift
568de9f7bdfa43279c819cb50e16c33b4dc09146
[ "Apache-2.0" ]
1
2020-06-11T03:52:25.000Z
2020-06-11T03:52:25.000Z
test/thrift/generator/service_test.exs
dnlserrano/elixir-thrift
568de9f7bdfa43279c819cb50e16c33b4dc09146
[ "Apache-2.0" ]
77
2018-08-29T00:36:42.000Z
2021-08-02T13:14:35.000Z
test/thrift/generator/service_test.exs
CultivateHQ/elixir-thrift
d285ddc0f134afc6f7d8c5d0b504a8d27157da9a
[ "Apache-2.0" ]
1
2021-02-04T15:58:30.000Z
2021-02-04T15:58:30.000Z
defmodule Thrift.Generator.ServiceTest do use ThriftTestCase @thrift_file name: "simple_service.thrift", contents: """ namespace elixir Services.Simple struct User { 1: optional i64 id, 2: optional string username } exception UsernameTakenException { 1: string message } service SimpleService { bool ping(), void check_username(1: string username) throws(1: UsernameTakenException taken), bool update_username(1: i64 id, 2: string new_username) throws(1: UsernameTakenException taken), User get_by_id(1: i64 user_id), bool are_friends(1: User user_a, 2: User user_b), void mark_inactive(1: i64 user_id), oneway void do_some_work(1: string work), list<i64> friend_ids_of(1: i64 user_id), map<string, i64> friend_nicknames(1: i64 user_id), set<string> tags(1: i64 user_id), bool And(1: bool left, 2: bool right), } """ defmodule ServerSpy do use GenServer def init([]) do {:ok, {nil, nil}} end def ping(), do: handle_function(:ping, []) def check_username(username), do: handle_function(:check_username, [username]) def update_username(id, new_username), do: handle_function(:update_username, [id, new_username]) def get_by_id(user_id), do: handle_function(:get_by_id, [user_id]) def are_friends(user_a, user_b), do: handle_function(:are_friends, [user_a, user_b]) def mark_inactive(user_id), do: handle_function(:mark_inactive, [user_id]) def do_some_work(work), do: handle_function(:do_some_work, [work]) def friend_ids_of(user_id), do: handle_function(:friend_ids_of, [user_id]) def friend_nicknames(user_id), do: handle_function(:friend_nicknames, [user_id]) def tags(user_id), do: handle_function(:tags, [user_id]) def(unquote(:and)(left, right)) do handle_function(:and, [left, right]) end def start_link do GenServer.start_link(__MODULE__, [], name: __MODULE__) end def set_reply(reply), do: GenServer.call(__MODULE__, {:set_reply, reply}) def set_args(args), do: GenServer.call(__MODULE__, {:set_args, args}) def get_reply, do: GenServer.call(__MODULE__, :get_reply) def get_args, do: GenServer.call(__MODULE__, :get_args) def handle_call({:set_reply, reply}, _from, {_, args}) do {:reply, :ok, {reply, args}} end def handle_call(:get_reply, _, {reply, _} = state), do: {:reply, reply, state} def handle_call({:set_args, args}, _from, {reply, _}) do {:reply, :ok, {reply, args}} end def handle_call(:get_args, _, {_, args} = state), do: {:reply, args, state} def handle_function(name, args) do reply = ServerSpy.get_reply() ServerSpy.set_args({name, args}) parse_reply(reply) end defp parse_reply(reply) do case reply do {:exception, module, attributes} -> raise(module, attributes) :noreply -> :ok {:sleep, amount, reply} -> :timer.sleep(amount) parse_reply(reply) reply -> reply end end end alias Thrift.ConnectionError alias Thrift.Generator.ServiceTest.SimpleService.Binary.Framed.Client alias Thrift.Generator.ServiceTest.SimpleService.Binary.Framed.Server alias Thrift.Generator.ServiceTest.User alias Thrift.Generator.ServiceTest.UsernameTakenException alias Thrift.TApplicationException defp start_server(opts \\ []) do {:ok, pid} = Server.start_link(ServerSpy, 0, opts) name = Keyword.get(opts, :name, ServerSpy) port = :ranch.get_port(name) {:ok, pid, port} end defp stop_server(server_pid) when is_pid(server_pid) do ref = Process.monitor(server_pid) :ok = Server.stop(server_pid) assert_receive {:DOWN, ^ref, _, _, _} end defp wait_for_exit(pid) when is_pid(pid) do ref = Process.monitor(pid) assert_receive {:DOWN, ^ref, _, _, _} end setup do {:ok, server, port} = start_server() {:ok, client} = Client.start_link("127.0.0.1", port, tcp_opts: [timeout: 5000]) {:ok, handler_pid} = ServerSpy.start_link() on_exit(fn -> wait_for_exit(handler_pid) wait_for_exit(client) wait_for_exit(server) end) {:ok, port: port, client: client, server: server} end thrift_test "it should generate arg structs" do find_by_id_args = %SimpleService.UpdateUsernameArgs{id: 1234, new_username: "foobar"} assert find_by_id_args.id == 1234 assert find_by_id_args.new_username == "foobar" end thrift_test "it should generate response structs" do response = %SimpleService.UpdateUsernameResponse{success: true} assert :success in Map.keys(response) end thrift_test "it should generate exceptions in response structs" do assert :taken in Map.keys(%SimpleService.UpdateUsernameResponse{}) end thrift_test "it should be able to serialize the request struct" do alias SimpleService.UpdateUsernameArgs serialized = %UpdateUsernameArgs{id: 1234, new_username: "stinkypants"} |> UpdateUsernameArgs.BinaryProtocol.serialize() |> IO.iodata_to_binary() assert <<10, 0, 1, 0, 0, 0, 0, 0, 0, 4, 210, 11, 0, 2, 0, 0, 0, 11, "stinkypants", 0>> == serialized end thrift_test "it should be able to serialize the response struct" do alias SimpleService.UpdateUsernameResponse serialized = %UpdateUsernameResponse{success: true} |> UpdateUsernameResponse.BinaryProtocol.serialize() |> IO.iodata_to_binary() assert <<2, 0, 0, 1, 0>> == serialized end thrift_test "it serializes the exceptions" do # this is because the python client always expects the success struct. # silly python client. alias SimpleService.UpdateUsernameResponse serialized = %UpdateUsernameResponse{taken: %UsernameTakenException{message: "That username is taken"}} |> UpdateUsernameResponse.BinaryProtocol.serialize() |> IO.iodata_to_binary() assert <<12, 0, 1, 11, 0, 1, 0, 0, 0, 22, rest::binary>> = serialized assert <<"That username is taken", 0, 0>> = rest end thrift_test "it should be able to execute a simple ping", ctx do ServerSpy.set_reply(true) {:ok, true} = Client.ping(ctx.client) assert {:ping, []} == ServerSpy.get_args() end thrift_test "it should be able to update the username", ctx do ServerSpy.set_reply(true) assert {:ok, true} = Client.update_username(ctx.client, 1234, "stinkypants") assert {:update_username, [1234, "stinkypants"]} == ServerSpy.get_args() end thrift_test "it should be able to handle structs as function arguments", ctx do ServerSpy.set_reply(true) assert {:ok, true} = Client.are_friends( ctx.client, %User{id: 1, username: "stinky"}, %User{id: 28, username: "less_stinky"} ) expected_args = {:are_friends, [%User{id: 1, username: "stinky"}, %User{id: 28, username: "less_stinky"}]} assert expected_args == ServerSpy.get_args() end thrift_test "it should be able to return structs", ctx do ServerSpy.set_reply(%User{id: 28_392, username: "stinky"}) {:ok, user} = Client.get_by_id(ctx.client, 12_345) assert %User{id: 28_392, username: "stinky"} == user end thrift_test "it should handle expected exceptions", ctx do ServerSpy.set_reply({:exception, UsernameTakenException, [message: "oh noes"]}) {:error, {:exception, exc}} = Client.update_username(ctx.client, 8382, "dude") assert %UsernameTakenException{message: "oh noes"} == exc end thrift_test "it handles a TApplicationException when the server blows up", ctx do ServerSpy.set_reply(:this_isnt_a_valid_reply) {:error, {:exception, ex}} = Client.update_username(ctx.client, 1234, "user") assert %TApplicationException{message: message, type: :internal_error} = ex assert message =~ "Thrift.InvalidValueError" end thrift_test "bang functions return only the value", ctx do ServerSpy.set_reply(%User{id: 2, username: "stinky"}) assert %User{id: 2, username: "stinky"} == Client.get_by_id!(ctx.client, 1234) end thrift_test "it raises ConnectionError with the bang function", %{client: client} do Process.flag(:trap_exit, true) ServerSpy.set_reply({:sleep, 1000, [1, 3, 4]}) assert_raise ConnectionError, "Connection error: timeout", fn -> Client.friend_ids_of!(client, 12_914, tcp_opts: [timeout: 1]) end end thrift_test "it raises a server exception with the bang function", ctx do ServerSpy.set_reply("oh noes") assert_raise TApplicationException, fn -> Client.update_username!(ctx.client, 88, "blow up") end end thrift_test "it raises an exception with a bang function", ctx do ServerSpy.set_reply({:exception, UsernameTakenException, [message: "blowie up"]}) assert_raise UsernameTakenException, fn -> Client.update_username!(ctx.client, 821, "foo") end end thrift_test "it handles void functions", ctx do ServerSpy.set_reply(:noreply) assert {:ok, nil} == Client.mark_inactive(ctx.client, 5529) end thrift_test "it handles void functions that can throw exceptions", ctx do ServerSpy.set_reply(:noreply) assert {:ok, nil} == Client.check_username(ctx.client, "foo") end thrift_test "it handles void functions that do throw exceptions", ctx do ServerSpy.set_reply({:exception, UsernameTakenException, [message: "blowie up"]}) assert_raise UsernameTakenException, fn -> Client.check_username!(ctx.client, "foo") end end thrift_test "it handles void oneway functions", ctx do ServerSpy.set_reply(:noreply) assert {:ok, nil} == Client.do_some_work(ctx.client, "12345") :timer.sleep(10) end thrift_test "it handles returning a list", ctx do friend_ids = [1, 82, 382, 9914, 40_112] ServerSpy.set_reply(friend_ids) assert {:ok, friend_ids} == Client.friend_ids_of(ctx.client, 14_821) end thrift_test "it handles returning a map", ctx do ServerSpy.set_reply(%{"bernie" => 281, "brownie" => 9924}) expected = %{"bernie" => 281, "brownie" => 9924} assert {:ok, expected} == Client.friend_nicknames(ctx.client, 4810) end thrift_test "it handles returning a set", ctx do ServerSpy.set_reply(MapSet.new(["sports", "debate", "motorcycles"])) expected = MapSet.new(["sports", "debate", "motorcycles"]) assert {:ok, expected} == Client.tags(ctx.client, 91_281) end thrift_test "it handles method names that conflict with Elixir keywords", ctx do ServerSpy.set_reply(true) expected = true assert {:ok, expected} == Client.and(ctx.client, true, true) end thrift_test "it has a configurable gen_server timeout", ctx do ServerSpy.set_reply({:sleep, 1000, [1, 3, 4]}) assert catch_exit(Client.friend_ids_of(ctx.client, 1234, gen_server_opts: [timeout: 200])) end thrift_test "it has a configurable socket timeout", %{client: client} do Process.flag(:trap_exit, true) ServerSpy.set_reply({:sleep, 1000, [1, 3, 4]}) assert ExUnit.CaptureLog.capture_log(fn -> assert {:error, :timeout} = Client.friend_ids_of(client, 12_914, tcp_opts: [timeout: 1]) assert_receive {:EXIT, ^client, {:error, :timeout}} end) =~ "1ms" end # connection tests thrift_test "clients can be closed", ctx do ref = Process.monitor(ctx.client) :ok = Client.close(ctx.client) assert_receive {:DOWN, ^ref, _, _, _} refute Process.alive?(ctx.client) end thrift_test "clients exit on connection timeout" do Process.flag(:trap_exit, true) opts = [tcp_opts: [recv_timeout: 20], name: :connection_timeout_test] {:ok, _new_server, new_server_port} = start_server(opts) {:ok, client} = Client.start_link("127.0.0.1", new_server_port, []) # sleep beyond the server's recv_timeout :timer.sleep(50) assert {:error, closed} = Client.friend_ids_of(client, 1234) assert closed in [:closed, :econnaborted] assert_receive {:EXIT, ^client, {:error, ^closed}} end thrift_test "clients exit if they try to use a closed client", %{client: client, server: server} do Process.flag(:trap_exit, true) # Wait for client to connect :sys.get_state(client) stop_server(server) assert Client.friend_ids_of(client, 1234) == {:error, :closed} assert_receive {:EXIT, ^client, {:error, :closed}} end thrift_test "clients exit if the server dies handling a message", ctx do ref = Process.monitor(ctx.server) ServerSpy.set_reply({:sleep, 5000, 1234}) # the server will sleep when the RPC is called, so spawn a # process to make a request, then kill the server out # from under that process. It will trigger the generic # error handler in the server me = self() spawn(fn -> Process.flag(:trap_exit, true) Process.send_after(me, :ok, 20) Client.friend_ids_of(ctx.client, 14_821) end) receive do :ok -> :ok end Process.flag(:trap_exit, true) Process.exit(ctx.server, :kill) client = ctx.client assert_receive {:DOWN, ^ref, _, _, _} assert_receive {:EXIT, ^client, {:error, :closed}} end thrift_test "oneway functions return :ok if the server dies", %{client: client, server: server} do Process.flag(:trap_exit, true) ServerSpy.set_reply(:noreply) :sys.get_state(client) stop_server(server) # this assertion is unusual, as it should exit, but the server # doesn't do reads during oneway functions, so it won't get the # error that the other side has been closed. # see: http://erlang.org/pipermail/erlang-questions/2014-April/078545.html {:ok, nil} = Client.do_some_work(client, "work!") end end
32.111364
101
0.661476
1c0afcb8ec6aab261cd45e03481beca8c4a0444b
85
exs
Elixir
config/dev.exs
still-ex/still
2597587550eeb9bc46ee7cf4e1c30a1af7776d7d
[ "0BSD" ]
202
2021-01-13T15:45:17.000Z
2022-03-22T01:26:27.000Z
config/dev.exs
still-ex/still
2597587550eeb9bc46ee7cf4e1c30a1af7776d7d
[ "0BSD" ]
55
2021-01-26T14:11:34.000Z
2022-03-22T22:34:37.000Z
config/dev.exs
subvisual/still
2597587550eeb9bc46ee7cf4e1c30a1af7776d7d
[ "0BSD" ]
10
2021-02-04T21:14:41.000Z
2022-03-20T10:12:59.000Z
import Config config :still, dev_layout: true, ignore_files: [], watchers: []
12.142857
19
0.670588
1c0b1f2fb23d756b5c256775af062fa34d1a519f
3,935
ex
Elixir
apps/omg_watcher/lib/db/eth_event.ex
hoardexchange/elixir-omg
423528699d467f1cc0d02c596290ab907af38c2c
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/lib/db/eth_event.ex
hoardexchange/elixir-omg
423528699d467f1cc0d02c596290ab907af38c2c
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/lib/db/eth_event.ex
hoardexchange/elixir-omg
423528699d467f1cc0d02c596290ab907af38c2c
[ "Apache-2.0" ]
2
2020-06-07T11:14:54.000Z
2020-08-02T07:36:32.000Z
# Copyright 2018 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.Watcher.DB.EthEvent do @moduledoc """ Ecto schema for events logged by Ethereum: deposits and exits """ use Ecto.Schema alias OMG.API.Crypto alias OMG.API.Utxo alias OMG.Watcher.DB require Utxo @primary_key {:hash, :binary, []} @derive {Phoenix.Param, key: :hash} schema "ethevents" do field(:blknum, :integer) field(:txindex, :integer) field(:event_type, OMG.Watcher.DB.Types.AtomType) has_one(:created_utxo, DB.TxOutput, foreign_key: :creating_deposit) has_one(:exited_utxo, DB.TxOutput, foreign_key: :spending_exit) end def get(hash), do: DB.Repo.get(__MODULE__, hash) def get_all, do: DB.Repo.all(__MODULE__) @doc """ Inserts deposits based on a list of event maps (if not already inserted before) """ @spec insert_deposits!([OMG.API.State.Core.deposit()]) :: :ok def insert_deposits!(deposits) do deposits |> Enum.each(&insert_deposit!/1) end @spec insert_deposit!(OMG.API.State.Core.deposit()) :: {:ok, %__MODULE__{}} | {:error, Ecto.Changeset.t()} defp insert_deposit!(%{blknum: blknum, owner: owner, currency: currency, amount: amount}) do {:ok, _} = if existing_deposit = get(deposit_key(blknum)) != nil, do: {:ok, existing_deposit}, else: %__MODULE__{ hash: deposit_key(blknum), blknum: blknum, txindex: 0, event_type: :deposit, created_utxo: %DB.TxOutput{ blknum: blknum, txindex: 0, oindex: 0, owner: owner, currency: currency, amount: amount } } |> DB.Repo.insert() end @doc """ Uses a list of encoded `Utxo.Position`s to insert the exits (if not already inserted before) """ @spec insert_exits!([non_neg_integer()]) :: :ok def insert_exits!(exits) do exits |> Stream.map(&utxo_pos_from_exit_event/1) |> Enum.each(&insert_exit!/1) end @spec utxo_pos_from_exit_event(%{call_data: %{utxo_pos: pos_integer()}}) :: Utxo.Position.t() defp utxo_pos_from_exit_event(%{call_data: %{utxo_pos: utxo_pos}}), do: Utxo.Position.decode(utxo_pos) @spec insert_exit!(Utxo.Position.t()) :: {:ok, %__MODULE__{}} | {:error, Ecto.Changeset.t()} defp insert_exit!(Utxo.position(blknum, txindex, _oindex) = position) do {:ok, _} = if existing_exit = get(exit_key(position)) != nil do {:ok, existing_exit} else utxo = DB.TxOutput.get_by_position(position) %__MODULE__{ hash: exit_key(position), blknum: blknum, txindex: txindex, event_type: :exit, exited_utxo: utxo } |> DB.Repo.insert() end end @doc """ Good candidate for deposit/exit primary key is a pair (Utxo.position, event_type). Switching to composite key requires careful consideration of data types and schema change, so for now, we'd go with artificial key """ @spec generate_unique_key(Utxo.Position.t(), :deposit | :exit) :: OMG.API.Crypto.hash_t() def generate_unique_key(position, type) do "<#{position |> Utxo.Position.encode()}:#{type}>" |> Crypto.hash() end defp deposit_key(blknum), do: generate_unique_key(Utxo.position(blknum, 0, 0), :deposit) defp exit_key(position), do: generate_unique_key(position, :exit) end
33.632479
108
0.6554
1c0b5df60a87bbb9b5b02ac221ce0c3138a8d016
6,293
ex
Elixir
backend/lib/aptamer/jobs/python_script_job.ex
ui-icts/aptamer-web
a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06
[ "MIT" ]
null
null
null
backend/lib/aptamer/jobs/python_script_job.ex
ui-icts/aptamer-web
a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06
[ "MIT" ]
7
2019-02-08T18:28:49.000Z
2022-02-12T06:44:59.000Z
backend/lib/aptamer/jobs/python_script_job.ex
ui-icts/aptamer-web
a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06
[ "MIT" ]
null
null
null
defmodule Aptamer.Jobs.PythonScriptJob do require Logger alias Aptamer.Repo defstruct script_name: nil, args: [], working_dir: nil, output: [], exit_code: nil, listener: nil, current_user_id: nil, job_id: nil, # The original name of the file input_file_name: nil, # The contents input_file_contents: nil, # The temp path where we've written it for processing input_file_path: nil, output_collector: nil, generated_file: nil def create(script_name, args, input_file) do full_path = Path.expand(input_file) {file_name, file_path, file_contents} = cond do Elixir.File.exists?(full_path) -> {Path.basename(input_file), full_path, nil} true -> {"temp_input", nil, input_file} end %Aptamer.Jobs.PythonScriptJob{ script_name: script_name, args: args, input_file_name: file_name, input_file_path: file_path, input_file_contents: file_contents } end def run(%Aptamer.Jobs.PythonScriptJob{} = state) do Logger.debug("Running python job: #{inspect(state)}") {:ok, state} |> execute_step(:prepare_files) |> execute_step(:run_script) |> execute_step(:process_outputs) |> execute_step(:cleanup) end def execute_step({:ok, state}, step_name) do broadcast(:begin, step_name, state) result = step(step_name, state) broadcast(:finish, step_name, state) result end def broadcast(action, step_name, %Aptamer.Jobs.PythonScriptJob{listener: nil}) do Logger.info("[BROADCAST] - #{action} #{step_name}") end def broadcast(action, step_name, %Aptamer.Jobs.PythonScriptJob{listener: listener}) when is_pid(listener) do send(listener, {:broadcast, {action, step_name}}) end def step(:prepare_files, state) do {:ok, temp_path} = Temp.mkdir(state.job_id) {path, contents} = case {state.input_file_path, state.input_file_contents} do {nil, some} -> Logger.debug("Generating input file from file contents") temp_file = Path.join(temp_path, state.input_file_name) File.write(temp_file, some) {temp_file, some} {some, nil} -> Logger.debug("Generating input file from file path #{some}") {:ok, contents} = Elixir.File.read(some) {some, contents} {x, y} -> {x, y} end {:ok, %{state | working_dir: temp_path, input_file_path: path, input_file_contents: contents}} end def step(:run_script, state) do python_path = path(:python) script_path = path(:script) common_args = [ "#{script_path}/#{state.script_name}", state.input_file_path ] args = common_args ++ state.args collector = state.output_collector || IO.stream(:stdio, :line) {collector, exit_status} = System.cmd( python_path, args, cd: state.working_dir, stderr_to_stdout: true, parallelism: true, into: collector ) output = case collector do %Aptamer.JobControl.RunningJob{output: x} -> x %IO.Stream{} -> [] [_h | _t] = lines -> lines _ -> [] end |> Enum.join("\n") results = """ Program exited with code: #{exit_status} Output --------------------------------------------------------- #{output} """ results_path = Path.join(state.working_dir, "results.log") File.write(results_path, results) state = %{state | output: output, exit_code: exit_status} {:ok, state} end def step(:process_outputs, state) do # if we ran predict_structures create # a structure file from the output state = if state.script_name == "predict_structures.py" && state.exit_code == 0 do Logger.debug("Creating structure file output") case create_structure_file_from_outputs( state.working_dir, "#{state.input_file_name}.struct.fa", state.current_user_id ) do {:ok, file} -> %{state | generated_file: file} _ -> state end else Logger.debug( "Not creating a structure file. script_name: #{inspect(state.script_name)} exit status: #{ inspect(state.exit_code) }" ) state end remove_extraneous_files(state.working_dir) {:ok, _} = zip_outputs( state.working_dir, state.job_id, "#{state.input_file_name}.zip" ) {:ok, state} end def step(:cleanup, state) do File.rmdir(state.working_dir) {:ok, state} end def path(type) do case type do :python -> System.get_env("APTAMER_PYTHON") || "#{System.user_home()}/.virtualenvs/aptamer-runtime-3/bin/python" :script -> System.get_env("APTAMER_SCRIPT") || "#{System.user_home()}/icts/aptamer/scripts/aptamer" end end def zip_outputs(output_directory, job_id, zip_file_name) do ## Gather all files excluding any dot.ps # and create a zip archive files = File.ls!(output_directory) |> Enum.map(&String.to_charlist/1) :zip.create(Path.join(output_directory, zip_file_name), files, [{:cwd, output_directory}]) {:ok, zip_data} = Elixir.File.read(Path.join(output_directory, zip_file_name)) zip_struct = %Aptamer.Jobs.Result{ archive: zip_data, job_id: job_id } Repo.insert(zip_struct) end def remove_extraneous_files(output_directory) do dot_ps = Path.join(output_directory, "dot.ps") if File.exists?(dot_ps) do File.rm(dot_ps) end end def create_structure_file_from_outputs(output_directory, new_file_name, file_owner_id) do structure_file = Path.join(output_directory, new_file_name) case Elixir.File.read(structure_file) do {:ok, file_data} -> file_cs = Aptamer.Jobs.File.new_structure_file_changeset( new_file_name, file_data, file_owner_id ) Repo.insert(file_cs) {:error, e} -> Logger.error("Unable to read generated structure file. #{inspect(e)}") end end end
26.330544
100
0.607341
1c0b870aa27d5db6533285e1c3a926944d4778a8
1,013
exs
Elixir
apps/core/test/test_helper.exs
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
null
null
null
apps/core/test/test_helper.exs
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
2
2019-12-13T23:55:50.000Z
2019-12-17T05:49:58.000Z
apps/core/test/test_helper.exs
michaeljguarino/chartmart
a34c949cc29d6a1ab91c04c5e4f797e6f0daabfc
[ "Apache-2.0" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Core.Repo, :manual) Mimic.copy(Mojito) Mimic.copy(HTTPoison) Mimic.copy(Stripe.Connect.OAuth) Mimic.copy(Stripe.Customer) Mimic.copy(Stripe.Plan) Mimic.copy(Stripe.Token) Mimic.copy(Stripe.Subscription) Mimic.copy(Stripe.SubscriptionItem) Mimic.copy(Stripe.SubscriptionItem.Usage) Mimic.copy(Stripe.Card) Mimic.copy(Core.Conduit.Broker) Mimic.copy(Core.Buffers.Docker) Mimic.copy(Core.Buffers.TokenAudit) Mimic.copy(Core.Clients.Hydra) Mimic.copy(Cloudflare.DnsRecord) Mimic.copy(Kazan) Mimic.copy(Goth.Token) Mimic.copy(GoogleApi.CloudBilling.V1.Api.Projects) Mimic.copy(GoogleApi.CloudResourceManager.V3.Api.Projects) Mimic.copy(GoogleApi.CloudResourceManager.V3.Api.Operations) Mimic.copy(GoogleApi.IAM.V1.Api.Projects) Mimic.copy(GoogleApi.CloudBilling.V1.Api.BillingAccounts) Mimic.copy(GoogleApi.ServiceUsage.V1.Api.Services) Mimic.copy(GoogleApi.ServiceUsage.V1.Api.Operations) Mimic.copy(OAuth2.Client) {:ok, _} = Application.ensure_all_started(:ex_machina)
33.766667
60
0.824284
1c0b9d9bc04bdc1606815943e7edc06b758977c5
4,266
ex
Elixir
lib/kino/data_table.ex
livebook-dev/kino
48e76a351869164cbef307e57fb81cde27a12f28
[ "Apache-2.0" ]
84
2021-07-17T09:19:45.000Z
2022-03-21T20:43:21.000Z
lib/kino/data_table.ex
livebook-dev/kino
48e76a351869164cbef307e57fb81cde27a12f28
[ "Apache-2.0" ]
48
2021-07-21T11:59:20.000Z
2022-03-31T16:34:16.000Z
lib/kino/data_table.ex
livebook-dev/kino
48e76a351869164cbef307e57fb81cde27a12f28
[ "Apache-2.0" ]
11
2021-09-05T16:30:23.000Z
2022-02-19T02:06:48.000Z
defmodule Kino.DataTable do @moduledoc """ A widget for interactively viewing enumerable data. The data must be an enumerable of records, where each record is either map, struct, keyword list or tuple. ## Examples data = [ %{id: 1, name: "Elixir", website: "https://elixir-lang.org"}, %{id: 2, name: "Erlang", website: "https://www.erlang.org"} ] Kino.DataTable.new(data) The tabular view allows you to quickly preview the data and analyze it thanks to sorting capabilities. data = Process.list() |> Enum.map(&Process.info/1) Kino.DataTable.new( data, keys: [:registered_name, :initial_call, :reductions, :stack_size] ) """ @behaviour Kino.Table alias Kino.Utils @type t :: Kino.JS.Live.t() @doc """ Starts a widget process with enumerable tabular data. ## Options * `:keys` - a list of keys to include in the table for each record. The order is reflected in the rendered table. For tuples use 0-based indices. Optional. * `:sorting_enabled` - whether the widget should support sorting the data. Sorting requires traversal of the whole enumerable, so it may not be desirable for lazy enumerables. Defaults to `true` if data is a list and `false` otherwise. * `:show_underscored` - whether to include record keys starting with underscore. This option is ignored if `:keys` is also given. Defaults to `false`. """ @spec new(Enum.t(), keyword()) :: t() def new(data, opts \\ []) do validate_data!(data) keys = opts[:keys] sorting_enabled = Keyword.get(opts, :sorting_enabled, is_list(data)) show_underscored = Keyword.get(opts, :show_underscored, false) opts = %{ data: data, keys: keys, sorting_enabled: sorting_enabled, show_underscored: show_underscored } Kino.Table.new(__MODULE__, opts) end # Validate data only if we have a whole list upfront defp validate_data!(data) when is_list(data) do Enum.reduce(data, nil, fn record, type -> case record_type(record) do :other -> raise ArgumentError, "expected record to be either map, struct, tuple or keyword list, got: #{inspect(record)}" first_type when type == nil -> first_type ^type -> type other_type -> raise ArgumentError, "expected records to have the same data type, found #{type} and #{other_type}" end end) end defp validate_data!(_data), do: :ok defp record_type(record) do cond do is_struct(record) -> :struct is_map(record) -> :map is_tuple(record) -> :tuple Keyword.keyword?(record) -> :keyword_list true -> :other end end @impl true def init(opts) do %{ data: data, keys: keys, sorting_enabled: sorting_enabled, show_underscored: show_underscored } = opts features = Kino.Utils.truthy_keys(pagination: true, sorting: sorting_enabled) info = %{name: "Data", features: features} total_rows = Enum.count(data) {:ok, info, %{ data: data, total_rows: total_rows, keys: keys, show_underscored: show_underscored }} end @impl true def get_data(rows_spec, state) do records = get_records(state.data, rows_spec) keys = if keys = state.keys do keys else keys = Utils.Table.keys_for_records(records) if state.show_underscored do keys else Enum.reject(keys, &underscored?/1) end end columns = Utils.Table.keys_to_columns(keys) rows = Enum.map(records, &Utils.Table.record_to_row(&1, keys)) {:ok, %{columns: columns, rows: rows, total_rows: state.total_rows}, state} end defp get_records(data, rows_spec) do sorted_data = if order_by = rows_spec[:order_by] do Enum.sort_by(data, &Utils.Table.get_field(&1, order_by), rows_spec.order) else data end Enum.slice(sorted_data, rows_spec.offset, rows_spec.limit) end defp underscored?(key) when is_atom(key) do key |> Atom.to_string() |> String.starts_with?("_") end defp underscored?(_key), do: false end
25.854545
106
0.632443
1c0ba3cec061321a3a270d33cd787e470657aa47
1,283
ex
Elixir
metex/lib/worker.ex
mrmarbury/TheLittleElixirAndOTPGuideBook
5aa46cdaee896ab5ecd87d3cf86bd7f9140fcda8
[ "Apache-2.0" ]
null
null
null
metex/lib/worker.ex
mrmarbury/TheLittleElixirAndOTPGuideBook
5aa46cdaee896ab5ecd87d3cf86bd7f9140fcda8
[ "Apache-2.0" ]
null
null
null
metex/lib/worker.ex
mrmarbury/TheLittleElixirAndOTPGuideBook
5aa46cdaee896ab5ecd87d3cf86bd7f9140fcda8
[ "Apache-2.0" ]
null
null
null
defmodule Metex.Worker do def loop do receive do {sender_pid, location} -> send(sender_pid, {:ok, temperature_of(location)}) _ -> IO.puts("Don't know how to process this message") end loop() end def temperature_of(location) do result = location |> url_for |> HTTPoison.get() |> parse_response case result do {:ok, temp} -> "#{location}: #{temp}C" {:error, reason} -> "Error for location: #{location}. Message was: #{reason["message"]}" end end defp url_for(location) do location = URI.encode(location) "http://api.openweathermap.org/data/2.5/weather?q=#{location}&appid=#{apikey()}" end defp apikey do "850bfe7a61f4f5b935c10b21f70d2f1b" end defp parse_response({:ok, %HTTPoison.Response{body: body, status_code: 200}}) do body |> Jason.decode!() |> compute_temperature end defp parse_response({:ok, %HTTPoison.Response{body: body, status_code: 404}}) do {:error, body |> Jason.decode!()} end defp parse_response({:error, %HTTPoison.Error{reason: reason}}) do {:error, reason |> Jason.decode!()} end defp compute_temperature(json) do try do temp = (json["main"]["temp"] - 273.15) |> Float.round(1) {:ok, temp} rescue _ -> :error end end end
25.66
94
0.636789
1c0bb83a9caf122a7904dd12eba44d28e09068c8
1,649
ex
Elixir
apps/asf_web/lib/asf_web/views/error_helpers.ex
LazarRistic/asf
2c557f06839a129b35174142c91f60696be2fa89
[ "MIT" ]
null
null
null
apps/asf_web/lib/asf_web/views/error_helpers.ex
LazarRistic/asf
2c557f06839a129b35174142c91f60696be2fa89
[ "MIT" ]
null
null
null
apps/asf_web/lib/asf_web/views/error_helpers.ex
LazarRistic/asf
2c557f06839a129b35174142c91f60696be2fa89
[ "MIT" ]
null
null
null
defmodule AsfWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "text-input_error appearance-none rounded-none relative block w-full px-3 mb-2 focus:outline-none focus:z-10 sm:text-sm", phx_feedback_for: input_name(form, field) ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(AsfWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(AsfWeb.Gettext, "errors", msg, opts) end end end
33.653061
131
0.667071
1c0bbd48d1cf9d29cdb87e5a07d044204f8ef715
429
ex
Elixir
priv/catalogue/button/playground.ex
joerichsen/surface_bootstrap
14a8b57126ead9a6593d628b9962e167fc01030d
[ "MIT" ]
null
null
null
priv/catalogue/button/playground.ex
joerichsen/surface_bootstrap
14a8b57126ead9a6593d628b9962e167fc01030d
[ "MIT" ]
null
null
null
priv/catalogue/button/playground.ex
joerichsen/surface_bootstrap
14a8b57126ead9a6593d628b9962e167fc01030d
[ "MIT" ]
null
null
null
defmodule SurfaceBootstrap.Catalogue.Button.Playground do use Surface.Catalogue.Playground, subject: SurfaceBootstrap.Button, catalogue: SurfaceBootstrap.Catalogue, height: "110px", container: {:div, class: "buttons is-centered"} data props, :map, default: %{ label: "My Button", color: "success" } def render(assigns) do ~H""" <Button :props={{ @props }} /> """ end end
21.45
57
0.638695
1c0bd33fca832be83ba383894ce89a4b36ae9e8b
632
exs
Elixir
mix.exs
Contraktor-Legal-Tech/ex-block-cypher
dc08d6c4a4fbb066f978579e87cbeb25faae9f25
[ "MIT" ]
null
null
null
mix.exs
Contraktor-Legal-Tech/ex-block-cypher
dc08d6c4a4fbb066f978579e87cbeb25faae9f25
[ "MIT" ]
null
null
null
mix.exs
Contraktor-Legal-Tech/ex-block-cypher
dc08d6c4a4fbb066f978579e87cbeb25faae9f25
[ "MIT" ]
null
null
null
defmodule ExBlockCypher.Mixfile do use Mix.Project def project do [ app: :ex_block_cypher, version: "0.1.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:poison, ">= 1.0.0"}, {:shorter_maps, ">= 2.2.3"}, {:httpoison, "~> 0.8"}, {:exvcr, "~> 0.8", only: :test}, {:credo, "~> 0.8", only: [:dev, :test]} ] end end
19.75
59
0.533228
1c0bd8b44bd050e41876c67410c8cf30c060dcb4
528
ex
Elixir
lib/sptfy/object/play_history.ex
Joe-noh/sptfy
ce94ec2ec61529ab6fe708248a2360f95ec388ea
[ "MIT" ]
5
2020-12-14T15:46:26.000Z
2021-03-20T22:32:58.000Z
lib/sptfy/object/play_history.ex
Joe-noh/sptfy
ce94ec2ec61529ab6fe708248a2360f95ec388ea
[ "MIT" ]
9
2020-12-25T14:36:11.000Z
2021-01-25T14:03:18.000Z
lib/sptfy/object/play_history.ex
Joe-noh/sptfy
ce94ec2ec61529ab6fe708248a2360f95ec388ea
[ "MIT" ]
null
null
null
defmodule Sptfy.Object.PlayHistory do @moduledoc """ Module for recently played history struct. """ use Sptfy.Object alias Sptfy.Object.{Context, SimplifiedTrack} defstruct ~w[ context played_at track ]a def new(fields) do fields = fields |> Helpers.atomize_keys() |> Map.update(:context, nil, &Context.new/1) |> Map.update(:played_at, nil, &Helpers.parse_timestamp/1) |> Map.update(:track, nil, &SimplifiedTrack.new/1) struct(__MODULE__, fields) end end
19.555556
64
0.653409
1c0c1c6d52c8916a009142481fbe795cb75a52d3
1,708
ex
Elixir
lib/central/logging/schemas/aggregate_view_log.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
6
2021-02-08T10:42:53.000Z
2021-04-25T12:12:03.000Z
lib/central/logging/schemas/aggregate_view_log.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
null
null
null
lib/central/logging/schemas/aggregate_view_log.ex
icexuick/teiserver
22f2e255e7e21f977e6b262acf439803626a506c
[ "MIT" ]
2
2021-02-23T22:34:00.000Z
2021-04-08T13:31:36.000Z
defmodule Central.Logging.AggregateViewLog do use CentralWeb, :schema @primary_key false schema "aggregate_view_logs" do field :date, :date, primary_key: true field :total_views, :integer field :total_uniques, :integer field :average_load_time, :integer field :guest_view_count, :integer field :guest_unique_ip_count, :integer field :percentile_load_time_95, :integer field :percentile_load_time_99, :integer field :max_load_time, :integer field :hourly_views, {:array, :integer} field :hourly_uniques, {:array, :integer} field :hourly_average_load_times, {:array, :integer} field :user_data, :map field :section_data, :map end @doc false def changeset(struct, attrs) do struct |> cast(attrs, [ :date, :total_views, :total_uniques, :average_load_time, :guest_view_count, :guest_unique_ip_count, :percentile_load_time_95, :percentile_load_time_99, :max_load_time, :hourly_views, :hourly_uniques, :hourly_average_load_times, :user_data, :section_data ]) |> validate_required([ :date, :total_views, :total_uniques, :average_load_time, :guest_view_count, :guest_unique_ip_count, :percentile_load_time_95, :percentile_load_time_99, :max_load_time, :hourly_views, :hourly_uniques, :hourly_average_load_times, :user_data, :section_data ]) end @spec authorize(any, Plug.Conn.t(), atom) :: boolean def authorize(_, conn, :delete), do: allow?(conn, "logging.aggregate.delete") def authorize(_, conn, _), do: allow?(conn, "logging.aggregate") end
25.117647
79
0.667447
1c0c3c85dca2e7a407ec343f1c36395f98f83d83
35
exs
Elixir
00-learn/02-pattern-matching/main.exs
CrispenGari/elixir-startup
13ef0f693053fc4a1ae740627e0ce3fca7aab375
[ "Apache-2.0" ]
null
null
null
00-learn/02-pattern-matching/main.exs
CrispenGari/elixir-startup
13ef0f693053fc4a1ae740627e0ce3fca7aab375
[ "Apache-2.0" ]
null
null
null
00-learn/02-pattern-matching/main.exs
CrispenGari/elixir-startup
13ef0f693053fc4a1ae740627e0ce3fca7aab375
[ "Apache-2.0" ]
null
null
null
{a, b, c} = {:hello, "world", 42}
11.666667
33
0.428571
1c0c5f3a79c19196bec5a530eb7f0cab7ac04441
214
ex
Elixir
lib/grizzly/zwave/command_classes/alarm.ex
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
76
2019-09-04T16:56:58.000Z
2022-03-29T06:54:36.000Z
lib/grizzly/zwave/command_classes/alarm.ex
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
124
2019-09-05T14:01:24.000Z
2022-02-28T22:58:14.000Z
lib/grizzly/zwave/command_classes/alarm.ex
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
10
2019-10-23T19:25:45.000Z
2021-11-17T13:21:20.000Z
defmodule Grizzly.ZWave.CommandClasses.Alarm do @moduledoc """ Alarm Command Class """ @behaviour Grizzly.ZWave.CommandClass @impl true def byte(), do: 0x71 @impl true def name(), do: :alarm end
15.285714
47
0.686916
1c0c8e583c9950821305934ecdf6fbfa892c70f0
133
ex
Elixir
etc/source.ex
jan-sti/gim
1b8be6c2163577f375825170cc9b01674e59b646
[ "ECL-2.0", "Apache-2.0" ]
4
2020-01-21T09:15:24.000Z
2021-02-04T21:21:56.000Z
etc/source.ex
jan-sti/gim
1b8be6c2163577f375825170cc9b01674e59b646
[ "ECL-2.0", "Apache-2.0" ]
2
2020-04-06T05:20:09.000Z
2020-06-09T09:56:20.000Z
etc/source.ex
jan-sti/gim
1b8be6c2163577f375825170cc9b01674e59b646
[ "ECL-2.0", "Apache-2.0" ]
1
2020-04-22T08:44:35.000Z
2020-04-22T08:44:35.000Z
defmodule Source do use Gim.Schema schema do property(:prop) has_edge(:target, Target, reflect: :target_edge) end end
14.777778
52
0.699248
1c0cc29ce31fec0072984c5f60f93cfc12ed1a55
2,424
ex
Elixir
lib/mimic/dsl.ex
fartek/mimic
38d678b6f018df0c267f73a912bd94dcc6c57cf4
[ "Apache-2.0" ]
null
null
null
lib/mimic/dsl.ex
fartek/mimic
38d678b6f018df0c267f73a912bd94dcc6c57cf4
[ "Apache-2.0" ]
null
null
null
lib/mimic/dsl.ex
fartek/mimic
38d678b6f018df0c267f73a912bd94dcc6c57cf4
[ "Apache-2.0" ]
null
null
null
defmodule Mimic.DSL do @moduledoc """ stubs and expectations can be expressed in a more natural way ```elixir use Mimic.DSL ``` ```elixir test "basic example" do stub Calculator.add(_x, _y), do: :stub expect Calculator.add(x, y), do: x + y expect Calculator.mult(x, y), do: x * y assert Calculator.add(2, 3) == 5 assert Calculator.mult(2, 3) == 6 assert Calculator.add(2, 3) == :stub end ``` Support for expecting multiple calls ```elixir expect Calculator.add(x, y), num_calls: 2 do x + y end ``` """ @doc false defmacro __using__(_opts) do quote do import Mimic, except: [stub: 3, expect: 3, expect: 4] import Mimic.DSL setup :verify_on_exit! end end defmacro stub({{:., _, [module, f]}, _, args}, opts) do body = Keyword.fetch!(opts, :do) function = quote do fn unquote_splicing(args) -> unquote(body) end end quote do Mimic.stub(unquote(module), unquote(f), unquote(function)) end end defmacro stub({:when, _, [{{:., _, [module, f]}, _, args}, guard_args]}, opts) do body = Keyword.fetch!(opts, :do) function = quote do fn unquote_splicing(args) when unquote(guard_args) -> unquote(body) end end quote do Mimic.stub(unquote(module), unquote(f), unquote(function)) end end defmacro expect(ast, opts \\ [], do_block) defmacro expect({{:., _, [module, f]}, _, args}, opts, do_opts) do num_calls = Keyword.get_lazy(opts, :num_calls, fn -> Keyword.get(do_opts, :num_calls, 1) end) body = Keyword.fetch!(do_opts, :do) function = quote do fn unquote_splicing(args) -> unquote(body) end end quote do Mimic.expect(unquote(module), unquote(f), unquote(num_calls), unquote(function)) end end defmacro expect({:when, _, [{{:., _, [module, f]}, _, args}, guard_args]}, opts, do_opts) do num_calls = Keyword.get_lazy(opts, :num_calls, fn -> Keyword.get(do_opts, :num_calls, 1) end) body = Keyword.fetch!(do_opts, :do) function = quote do fn unquote_splicing(args) when unquote(guard_args) -> unquote(body) end end quote do Mimic.expect(unquote(module), unquote(f), unquote(num_calls), unquote(function)) end end end
21.642857
94
0.587046
1c0ccc67e5551f03a82dcfb0628869c53a4adf60
648
exs
Elixir
config/test.exs
mdwaud/nerves_hub_link_http
3fbf93be3607d175688c03b73497d32dd8724a54
[ "Apache-2.0" ]
8
2020-02-29T17:47:41.000Z
2021-06-22T17:58:25.000Z
config/test.exs
mdwaud/nerves_hub_link_http
3fbf93be3607d175688c03b73497d32dd8724a54
[ "Apache-2.0" ]
5
2020-01-15T23:23:53.000Z
2020-10-04T02:31:56.000Z
config/test.exs
mdwaud/nerves_hub_link_http
3fbf93be3607d175688c03b73497d32dd8724a54
[ "Apache-2.0" ]
5
2020-02-27T17:53:36.000Z
2020-10-05T07:54:34.000Z
use Mix.Config config :nerves_hub_cli, home_dir: Path.expand("nerves-hub"), ca_certs: Path.expand("../test/fixtures/ca_certs", __DIR__) # Shared Configuration. config :nerves_hub_link_http, ca_certs: Path.expand("../test/fixtures/ca_certs", __DIR__), client: NervesHubLinkHTTP.ClientMock, # Device HTTP connection. device_api_host: "0.0.0.0", device_api_port: 4001 # API HTTP connection. config :nerves_hub_user_api, host: "0.0.0.0", port: 4002 config :nerves_runtime, :kernel, autoload_modules: false config :nerves_runtime, target: "host" config :nerves_runtime, :modules, [ {Nerves.Runtime.KV, Nerves.Runtime.KV.Mock} ]
24.923077
62
0.742284
1c0cdaa318c754545843d10659fe2a38c8bfe515
964
ex
Elixir
lib/stellar/network/order_books.ex
turbo-play/elixir-stellar-sdk
ed0711d69493ed2723a1197120667a7fa2c97f9f
[ "MIT" ]
1
2019-12-19T14:12:20.000Z
2019-12-19T14:12:20.000Z
lib/stellar/network/order_books.ex
turbo-play/elixir-stellar-sdk
ed0711d69493ed2723a1197120667a7fa2c97f9f
[ "MIT" ]
null
null
null
lib/stellar/network/order_books.ex
turbo-play/elixir-stellar-sdk
ed0711d69493ed2723a1197120667a7fa2c97f9f
[ "MIT" ]
4
2019-10-09T20:58:35.000Z
2021-12-06T23:00:46.000Z
defmodule Stellar.Network.OrderBooks do @moduledoc """ Functions for interacting with OrderBooks """ alias Stellar.Network.Base @doc """ Returns order book details optional `params` can take any of the following.: * `selling_asset_code`: Code of the Asset being sold. * `selling_asset_issuer`: Account ID of the issuer of the Asset being sold. * `buying_asset_code`: Code of the Asset being bought. * `buying_asset_issuer`: Account ID of the issuer of the Asset being bought. * `limit`: Maximum number of records to return. """ @spec get(Stellar.asset_type(), Stellar.asset_type(), Keyword.t()) :: {Stellar.status(), map} def get(selling_asset_type, buying_asset_type, params \\ []) do params = params |> Keyword.put(:selling_asset_type, selling_asset_type) |> Keyword.put(:buying_asset_type, buying_asset_type) query = Base.process_query_params(params) Base.get("/order_book#{query}") end end
29.212121
95
0.709544
1c0d23d754bf6e38d7221f640e071d9d8d5305ff
975
ex
Elixir
domotic_ui/lib/domotic_web/router.ex
gcauchon/domotic-pi
af61102fb946670b3e5ec93def6a5c053d894e79
[ "MIT" ]
1
2020-06-11T17:53:20.000Z
2020-06-11T17:53:20.000Z
domotic_ui/lib/domotic_web/router.ex
gcauchon/domotic-pi
af61102fb946670b3e5ec93def6a5c053d894e79
[ "MIT" ]
9
2020-12-15T21:19:59.000Z
2021-11-23T13:23:11.000Z
domotic_ui/lib/domotic_web/router.ex
gcauchon/domotic-pi
af61102fb946670b3e5ec93def6a5c053d894e79
[ "MIT" ]
1
2021-03-10T15:31:01.000Z
2021-03-10T15:31:01.000Z
defmodule DomoticWeb.Router do use DomoticWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :protect_from_forgery plug :put_secure_browser_headers plug :put_root_layout, {DomoticWeb.LayoutView, :app} end scope "/", DomoticWeb do pipe_through :browser live "/", Live.Dashboard end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through :browser live_dashboard "/dashboard", metrics: DomoticWeb.Telemetry end end end
25
70
0.712821
1c0d4167328c02a910d3a0cfec60665216065d28
921
exs
Elixir
languages/elixir/exercises/concept/lasagna/test/lasagna_test.exs
AlexLeSang/v3
3d35961a961b5a2129b1d42f1d118972d9665357
[ "MIT" ]
200
2019-12-12T13:50:59.000Z
2022-02-20T22:38:42.000Z
languages/elixir/exercises/concept/lasagna/test/lasagna_test.exs
AlexLeSang/v3
3d35961a961b5a2129b1d42f1d118972d9665357
[ "MIT" ]
1,938
2019-12-12T08:07:10.000Z
2021-01-29T12:56:13.000Z
languages/elixir/exercises/concept/lasagna/test/lasagna_test.exs
AlexLeSang/v3
3d35961a961b5a2129b1d42f1d118972d9665357
[ "MIT" ]
239
2019-12-12T14:09:08.000Z
2022-03-18T00:04:07.000Z
defmodule LasagnaTest do use ExUnit.Case doctest Lasagna # @tag :pending test "expected minutes in oven" do assert Lasagna.expected_minutes_in_oven() === 40 end @tag :pending test "remaining minutes in oven" do assert Lasagna.remaining_minutes_in_oven(25) === 15 end @tag :pending test "preparation time in minutes for one layer" do assert Lasagna.preparation_time_in_minutes(1) === 2 end @tag :pending test "preparation time in minutes for multiple layers" do assert Lasagna.preparation_time_in_minutes(4) === 8 end @tag :pending test "total time in minutes for one layer" do assert Lasagna.total_time_in_minutes(1, 30) === 32 end @tag :pending test "total time in minutes for multiple layers" do assert Lasagna.total_time_in_minutes(4, 8) === 16 end @tag :pending test "notification message" do assert Lasagna.alarm() === "Ding!" end end
23.025
59
0.70684
1c0d4345a628ce1b288c1e0a8a1896addf24375b
880
ex
Elixir
clients/ad_sense/lib/google_api/ad_sense/v2/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/ad_sense/lib/google_api/ad_sense/v2/metadata.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/ad_sense/lib/google_api/ad_sense/v2/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.AdSense.V2 do @moduledoc """ API client metadata for GoogleApi.AdSense.V2. """ @discovery_revision "20211209" def discovery_revision(), do: @discovery_revision end
32.592593
74
0.757955
1c0dccf3256988223601d1ad710e44870b30beae
370
ex
Elixir
lib/elixir_rest_api_web/views/photo_view.ex
NtwaliHeritier/elixir_rest_api
9bfe2c6aee75ef27942d1ce4d48ff59b28f10683
[ "MIT" ]
null
null
null
lib/elixir_rest_api_web/views/photo_view.ex
NtwaliHeritier/elixir_rest_api
9bfe2c6aee75ef27942d1ce4d48ff59b28f10683
[ "MIT" ]
null
null
null
lib/elixir_rest_api_web/views/photo_view.ex
NtwaliHeritier/elixir_rest_api
9bfe2c6aee75ef27942d1ce4d48ff59b28f10683
[ "MIT" ]
null
null
null
defmodule ElixirRestApiWeb.PhotoView do use ElixirRestApiWeb, :view alias __MODULE__ def render("show.json", %{photos: photos}) do render_many(photos, PhotoView, "photo.json") end def render("photo.json", %{photo: photo}) do %{ title: photo["title"], thumbnailUrl: photo["thumbnailUrl"] } end end
24.666667
52
0.602703
1c0ddeb4b607fc6aa838f2d28b327b2e0eaa9f9d
2,438
exs
Elixir
config/prod.exs
empex2019liveview/namedb
fd01151dd293f9740204435fed524bc364f81069
[ "MIT" ]
null
null
null
config/prod.exs
empex2019liveview/namedb
fd01151dd293f9740204435fed524bc364f81069
[ "MIT" ]
null
null
null
config/prod.exs
empex2019liveview/namedb
fd01151dd293f9740204435fed524bc364f81069
[ "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 :namedb, NamedbWeb.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 :namedb, NamedbWeb.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 :namedb, NamedbWeb.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 :namedb, NamedbWeb.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"
33.861111
69
0.712059
1c0de20fd725d670cc2d9688cc8450570b7aada4
1,081
exs
Elixir
test/msgpax/plug_parser_test.exs
qcam/msgpax
c846848e69973dc058e45a8b06bd12c953fd5a46
[ "0BSD" ]
null
null
null
test/msgpax/plug_parser_test.exs
qcam/msgpax
c846848e69973dc058e45a8b06bd12c953fd5a46
[ "0BSD" ]
null
null
null
test/msgpax/plug_parser_test.exs
qcam/msgpax
c846848e69973dc058e45a8b06bd12c953fd5a46
[ "0BSD" ]
null
null
null
defmodule Msgpax.PlugParserTest do use ExUnit.Case use Plug.Test test "body with a MessagePack-encoded map" do conn = conn(:post, "/", Msgpax.pack!(%{hello: "world"}) |> IO.iodata_to_binary()) assert {:ok, %{"hello" => "world"}, _conn} = Msgpax.PlugParser.parse(conn, "application", "msgpack", [], []) end test "body with a MessagePack-encoded non-map term" do conn = conn(:post, "/", Msgpax.pack!(100) |> IO.iodata_to_binary()) assert {:ok, %{"_msgpack" => 100}, _conn} = Msgpax.PlugParser.parse(conn, "application", "msgpack", [], []) end test "request with a content-type other than application/msgpack" do conn = conn(:post, "/", Msgpax.pack!(100) |> IO.iodata_to_binary()) assert {:next, ^conn} = Msgpax.PlugParser.parse(conn, "application", "json", [], []) end test "bad MessagePack-encoded body" do conn = conn(:post, "/", "bad body") assert_raise Plug.Parsers.ParseError, ~r/found excess bytes/, fn -> Msgpax.PlugParser.parse(conn, "application", "msgpack", [], []) end end end
33.78125
88
0.625347
1c0de490a88bee25fbd868014efd899699f9550a
1,408
ex
Elixir
lib/hammox/utils.ex
camilleryr/hammox
9f11ffb11bc3c2689c13feca123b6aef2dc66d76
[ "Apache-2.0" ]
430
2019-09-26T05:01:13.000Z
2022-03-30T05:21:11.000Z
lib/hammox/utils.ex
wojtekmach/hammox
c7ea8e598a753a69384a9a08f71a51ff03d4751b
[ "Apache-2.0" ]
48
2019-09-20T16:11:51.000Z
2022-03-23T20:33:16.000Z
lib/hammox/utils.ex
wojtekmach/hammox
c7ea8e598a753a69384a9a08f71a51ff03d4751b
[ "Apache-2.0" ]
18
2019-10-02T19:59:33.000Z
2021-12-07T07:49:16.000Z
defmodule Hammox.Utils do @moduledoc false def module_to_string(module_name) do module_name |> Atom.to_string() |> String.split(".") |> Enum.drop(1) |> Enum.join(".") end def replace_user_types(type, module_name) do type_map(type, fn {:user_type, _, name, args} -> {:remote_type, 0, [{:atom, 0, module_name}, {:atom, 0, name}, args]} other -> other end) end def type_map(type, map_fun) do case map_fun.(type) do {:type, position, name, params} when is_list(params) -> {:type, position, name, Enum.map(params, fn param -> type_map(param, map_fun) end)} {:user_type, position, name, params} when is_list(params) -> {:user_type, position, name, Enum.map(params, fn param -> type_map(param, map_fun) end)} {:ann_type, position, [var, ann_type]} -> {:ann_type, position, [var, type_map(ann_type, map_fun)]} {:remote_type, position, [module_name, name, params]} -> {:remote_type, position, [module_name, name, Enum.map(params, fn param -> type_map(param, map_fun) end)]} other -> other end end def check_module_exists(module) do case Code.ensure_compiled(module) do {:module, _} -> true _ -> raise(ArgumentError, message: "Could not find module #{module_to_string(module)}." ) end end end
26.074074
96
0.600852
1c0dffe6f7f06609c4012828b39bfdb60ce19ddb
17,304
ex
Elixir
clients/logging/lib/google_api/logging/v2/api/v2.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/api/v2.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/api/v2.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Logging.V2.Api.V2 do @moduledoc """ API calls for all endpoints tagged `V2`. """ alias GoogleApi.Logging.V2.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets the Logging CMEK settings for the given resource.Note: CMEK for the Log Router can be configured for Google Cloud projects, folders, organizations and billing accounts. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization.See Enabling CMEK for Log Router (https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `v2_id` (*type:* `String.t`) - Part of `name`. Required. The resource for which to retrieve CMEK settings. "projects/[PROJECT_ID]/cmekSettings" "organizations/[ORGANIZATION_ID]/cmekSettings" "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" "folders/[FOLDER_ID]/cmekSettings" For example:"organizations/12345/cmekSettings"Note: CMEK for the Log Router can be configured for Google Cloud projects, folders, organizations and billing accounts. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization. * `v2_id1` (*type:* `String.t`) - Part of `name`. See documentation of `v2Id`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.CmekSettings{}}` on success * `{:error, info}` on failure """ @spec logging_get_cmek_settings( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.CmekSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def logging_get_cmek_settings(connection, v2_id, v2_id1, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2/{v2Id}/{v2Id1}/cmekSettings", %{ "v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1), "v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.CmekSettings{}]) end @doc """ Gets the Log Router settings for the given resource.Note: Settings for the Log Router can be get for Google Cloud projects, folders, organizations and billing accounts. Currently it can only be configured for organizations. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization.See Enabling CMEK for Log Router (https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `v2_id` (*type:* `String.t`) - Part of `name`. Required. The resource for which to retrieve settings. "projects/[PROJECT_ID]/settings" "organizations/[ORGANIZATION_ID]/settings" "billingAccounts/[BILLING_ACCOUNT_ID]/settings" "folders/[FOLDER_ID]/settings" For example:"organizations/12345/settings"Note: Settings for the Log Router can be get for Google Cloud projects, folders, organizations and billing accounts. Currently it can only be configured for organizations. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization. * `v2_id1` (*type:* `String.t`) - Part of `name`. See documentation of `v2Id`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.Settings{}}` on success * `{:error, info}` on failure """ @spec logging_get_settings(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Logging.V2.Model.Settings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def logging_get_settings(connection, v2_id, v2_id1, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v2/{v2Id}/{v2Id1}/settings", %{ "v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1), "v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.Settings{}]) end @doc """ Updates the Log Router CMEK settings for the given resource.Note: CMEK for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization.UpdateCmekSettings will fail if 1) kms_key_name is invalid, or 2) the associated service account does not have the required roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or 3) access to the key is disabled.See Enabling CMEK for Log Router (https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `v2_id` (*type:* `String.t`) - Part of `name`. Required. The resource name for the CMEK settings to update. "projects/[PROJECT_ID]/cmekSettings" "organizations/[ORGANIZATION_ID]/cmekSettings" "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" "folders/[FOLDER_ID]/cmekSettings" For example:"organizations/12345/cmekSettings"Note: CMEK for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization. * `v2_id1` (*type:* `String.t`) - Part of `name`. See documentation of `v2Id`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:updateMask` (*type:* `String.t`) - Optional. Field mask identifying which fields from cmek_settings should be updated. A field will be overwritten if and only if it is in the update mask. Output only fields cannot be updated.See FieldMask for more information.For example: "updateMask=kmsKeyName" * `:body` (*type:* `GoogleApi.Logging.V2.Model.CmekSettings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.CmekSettings{}}` on success * `{:error, info}` on failure """ @spec logging_update_cmek_settings( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Logging.V2.Model.CmekSettings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def logging_update_cmek_settings(connection, v2_id, v2_id1, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v2/{v2Id}/{v2Id1}/cmekSettings", %{ "v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1), "v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.CmekSettings{}]) end @doc """ Updates the Log Router settings for the given resource.Note: Settings for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization.UpdateSettings will fail if 1) kms_key_name is invalid, or 2) the associated service account does not have the required roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or 3) access to the key is disabled. 4) location_id is not supported by Logging. 5) location_id violate OrgPolicy.See Enabling CMEK for Log Router (https://cloud.google.com/logging/docs/routing/managed-encryption) for more information. ## Parameters * `connection` (*type:* `GoogleApi.Logging.V2.Connection.t`) - Connection to server * `v2_id` (*type:* `String.t`) - Part of `name`. Required. The resource name for the settings to update. "organizations/[ORGANIZATION_ID]/settings" For example:"organizations/12345/settings"Note: Settings for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization. * `v2_id1` (*type:* `String.t`) - Part of `name`. See documentation of `v2Id`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:updateMask` (*type:* `String.t`) - Optional. Field mask identifying which fields from settings should be updated. A field will be overwritten if and only if it is in the update mask. Output only fields cannot be updated.See FieldMask for more information.For example: "updateMask=kmsKeyName" * `:body` (*type:* `GoogleApi.Logging.V2.Model.Settings.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Logging.V2.Model.Settings{}}` on success * `{:error, info}` on failure """ @spec logging_update_settings(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Logging.V2.Model.Settings.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def logging_update_settings(connection, v2_id, v2_id1, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v2/{v2Id}/{v2Id1}/settings", %{ "v2Id" => URI.encode(v2_id, &URI.char_unreserved?/1), "v2Id1" => URI.encode(v2_id1, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Logging.V2.Model.Settings{}]) end end
58.459459
670
0.659847
1c0e13a0299efc209e0a62ec2172ecdcd94cfe68
2,165
exs
Elixir
test/credo/priority_test.exs
sevenseacat/credo
48837401040d9c2340b5fb9c7d786d31f89f6426
[ "MIT" ]
null
null
null
test/credo/priority_test.exs
sevenseacat/credo
48837401040d9c2340b5fb9c7d786d31f89f6426
[ "MIT" ]
null
null
null
test/credo/priority_test.exs
sevenseacat/credo
48837401040d9c2340b5fb9c7d786d31f89f6426
[ "MIT" ]
null
null
null
defmodule Credo.PriorityTest do use Credo.TestHelper alias Credo.Priority test "it should NOT report expected code 2" do source_file = """ defmodule Credo.Sample.Module do def some_function(p1, p2, p3, p4, p5) do some_value = parameter1 + parameter2 end end """ |> to_source_file expected = %{ "Credo.Sample.Module" => 1, "Credo.Sample.Module.some_function" => 4 } assert expected == Priority.scope_priorities(source_file) end test "it should assign priorities based on many_functions" do source_file = """ defmodule Credo.Sample.Module do def fun0, do: 1 def fun1(p1), do: 2 def fun2(p1, p2), do: 3 def fun3(p1, p2, p3), do: 4 def fun4(p1, p2, p3, p4), do: 5 def fun5(p1, p2, p3, p4, p5), do: 5 end """ |> to_source_file expected = %{ "Credo.Sample.Module" => 2, "Credo.Sample.Module.fun0" => 2+0, "Credo.Sample.Module.fun1" => 2+1, "Credo.Sample.Module.fun2" => 2+1, "Credo.Sample.Module.fun3" => 2+2, "Credo.Sample.Module.fun4" => 2+2, "Credo.Sample.Module.fun5" => 2+3 } assert expected == Priority.scope_priorities(source_file) end test "it should not crash if @def_ops attributes provided and and should return correct scope_priorities" do source_file = """ defmodule Credo.Sample.Module do @def \""" Returns a list of `TimeSlice` structs based on the provided `time_slice_selector`. \""" def fun0, do: 1 def fun1(p1), do: 2 def fun2(p1, p2), do: 3 def fun3(p1, p2, p3), do: 4 def fun4(p1, p2, p3, p4), do: 5 def fun5(p1, p2, p3, p4, p5), do: 5 def fun6(p1, p2, p3, p4, p5) do 5 end @defp "and another strange module attribute" @defmacro "and another one" end """ |> to_source_file expected = %{ "Credo.Sample.Module" => 2, "Credo.Sample.Module.fun0" => 2+0, "Credo.Sample.Module.fun1" => 2+1, "Credo.Sample.Module.fun2" => 2+1, "Credo.Sample.Module.fun3" => 2+2, "Credo.Sample.Module.fun4" => 2+2, "Credo.Sample.Module.fun5" => 2+3, "Credo.Sample.Module.fun6" => 2+3 } assert expected == Priority.scope_priorities(source_file) end end
27.405063
110
0.631409
1c0e2874cf99dd5610ab56ee687ade9a0d369550
1,515
ex
Elixir
web/controllers/talk_controller.ex
pbrudnick/pyconar-talks
f0b2fdff9cae7bd7558cb4fdc5e0048403bbde7e
[ "MIT" ]
null
null
null
web/controllers/talk_controller.ex
pbrudnick/pyconar-talks
f0b2fdff9cae7bd7558cb4fdc5e0048403bbde7e
[ "MIT" ]
null
null
null
web/controllers/talk_controller.ex
pbrudnick/pyconar-talks
f0b2fdff9cae7bd7558cb4fdc5e0048403bbde7e
[ "MIT" ]
null
null
null
defmodule PyconarTalks.TalkController do use PyconarTalks.Web, :controller alias PyconarTalks.Talk def index(conn, _params) do talks = Repo.all(Talk) render(conn, "index.json", talks: talks) end def create(conn, %{"talk" => talk_params}) do changeset = Talk.changeset(%Talk{}, talk_params) case Repo.insert(changeset) do {:ok, talk} -> conn |> put_status(:created) |> put_resp_header("location", talk_path(conn, :show, talk)) |> render("show.json", talk: talk) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(PyconarTalks.ChangesetView, "error.json", changeset: changeset) end end def show(conn, %{"id" => id}) do talk = Repo.get!(Talk, id) render(conn, "show.json", talk: talk) end def update(conn, %{"id" => id, "talk" => talk_params}) do talk = Repo.get!(Talk, id) changeset = Talk.changeset(talk, talk_params) case Repo.update(changeset) do {:ok, talk} -> render(conn, "show.json", talk: talk) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(PyconarTalks.ChangesetView, "error.json", changeset: changeset) end end def delete(conn, %{"id" => id}) do talk = Repo.get!(Talk, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(talk) send_resp(conn, :no_content, "") end end
27.053571
81
0.613201
1c0e4d93e6cebe9aa355a24708060bdfcdcefa6f
403
exs
Elixir
backend/test/aptamer/auth/user_test.exs
ui-icts/aptamer-web
a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06
[ "MIT" ]
null
null
null
backend/test/aptamer/auth/user_test.exs
ui-icts/aptamer-web
a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06
[ "MIT" ]
7
2019-02-08T18:28:49.000Z
2022-02-12T06:44:59.000Z
backend/test/aptamer/auth/user_test.exs
ui-icts/aptamer-web
a28502c22a4e55ab1fbae8bbeaa6b11c9a477c06
[ "MIT" ]
null
null
null
defmodule Aptamer.Auth.UserTest do use Aptamer.DataCase import Aptamer.Factory alias Aptamer.Auth.User test "create from registration" do registration = build(:registration) changeset = User.register(registration) assert changeset.valid? user = Ecto.Changeset.apply_changes(changeset) assert Comeonin.Ecto.Password.valid?(registration.password, user.password) end end
22.388889
78
0.759305
1c0e53ca661e824c8730b33cf6d782dc5fd6d3cb
430
ex
Elixir
lib/shopify_api/rest/shop.ex
ProtoJazz/elixir-shopifyapi
759e20baff5afdff235386193bc42b2ecd343f5d
[ "Apache-2.0" ]
18
2019-06-07T13:36:39.000Z
2021-08-03T21:06:36.000Z
lib/shopify_api/rest/shop.ex
ProtoJazz/elixir-shopifyapi
759e20baff5afdff235386193bc42b2ecd343f5d
[ "Apache-2.0" ]
158
2018-08-30T22:09:00.000Z
2021-09-22T01:18:59.000Z
lib/shopify_api/rest/shop.ex
ProtoJazz/elixir-shopifyapi
759e20baff5afdff235386193bc42b2ecd343f5d
[ "Apache-2.0" ]
4
2020-09-05T00:48:46.000Z
2020-09-30T15:53:50.000Z
defmodule ShopifyAPI.REST.Shop do @moduledoc """ ShopifyAPI REST API Shop resource """ alias ShopifyAPI.AuthToken alias ShopifyAPI.REST @doc """ Get a shop's configuration. ## Example iex> ShopifyAPI.REST.Shop.get(auth) {:ok, %{} = shop} """ def get(%AuthToken{} = auth, params \\ [], options \\ []), do: REST.get(auth, "shop.json", params, Keyword.merge([pagination: :none], options)) end
21.5
88
0.630233
1c0e62c6c870967307742faabb4087604e7a5192
59
ex
Elixir
lib/sutur_web/views/layout_view.ex
ab-zu/sutur
f314ed29b344fbe0139bd87ac01caf577b1d592e
[ "MIT" ]
1
2021-11-16T02:18:31.000Z
2021-11-16T02:18:31.000Z
lib/sutur_web/views/layout_view.ex
ab-zu/sutur
f314ed29b344fbe0139bd87ac01caf577b1d592e
[ "MIT" ]
null
null
null
lib/sutur_web/views/layout_view.ex
ab-zu/sutur
f314ed29b344fbe0139bd87ac01caf577b1d592e
[ "MIT" ]
null
null
null
defmodule SuturWeb.LayoutView do use SuturWeb, :view end
14.75
32
0.79661
1c0e82690367604b7f6b1ea9d3376eb7f220256b
1,478
exs
Elixir
test/graphql/response_test.exs
TheRealReal/graphql_client
18b5b93f06a5cac218f8727eb0f7863081b7becf
[ "Apache-2.0" ]
9
2022-03-11T21:14:13.000Z
2022-03-31T14:13:38.000Z
test/graphql/response_test.exs
TheRealReal/graphql_client
18b5b93f06a5cac218f8727eb0f7863081b7becf
[ "Apache-2.0" ]
null
null
null
test/graphql/response_test.exs
TheRealReal/graphql_client
18b5b93f06a5cac218f8727eb0f7863081b7becf
[ "Apache-2.0" ]
null
null
null
defmodule GraphQL.ResponseTest do use ExUnit.Case, async: true alias GraphQL.Response doctest Response, import: true describe "success/1" do test "creates a new Response struct marked as success" do expected = %Response{ success?: true, data: %{ field: %{ name: "Blorgon" } } } result = Response.success(%{ field: %{ name: "Blorgon" } }) assert result == expected end end describe "failure/1" do test "creates a new Response struct marked as failure" do expected = %Response{ success?: false, errors: [%{message: "Some error", locations: [%{line: 1, column: 1}]}] } result = Response.failure([%{message: "Some error", locations: [%{line: 1, column: 1}]}]) assert result == expected end end describe "partial_success/2" do test "creates a new Response struct marked as a partial success" do expected = %Response{ success?: :partial, data: %{ field: %{ name: "Blorgon" } }, errors: [ %{message: "Some error", locations: [%{line: 1, column: 1}]} ] } result = Response.partial_success( %{field: %{name: "Blorgon"}}, [%{message: "Some error", locations: [%{line: 1, column: 1}]}] ) assert result == expected end end end
22.059701
95
0.523681
1c0e9ce3d7bd09dd207dc83808a19bd8accaceaa
1,369
exs
Elixir
apps/astarte_housekeeping_api/config/dev.exs
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
191
2018-03-30T13:23:08.000Z
2022-03-02T12:05:32.000Z
apps/astarte_housekeeping_api/config/dev.exs
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
402
2018-03-30T13:37:00.000Z
2022-03-31T16:47:10.000Z
apps/astarte_housekeeping_api/config/dev.exs
Annopaolo/astarte
f8190e8bf044759a9b84bdeb5786a55b6f793a4f
[ "Apache-2.0" ]
24
2018-03-30T13:29:48.000Z
2022-02-28T11:10:26.000Z
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :astarte_housekeeping_api, Astarte.Housekeeping.APIWeb.Endpoint, http: [port: 4001], debug_errors: true, code_reloader: true, check_origin: false, watchers: [] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Do not include metadata nor timestamps in development logs config :logger, :console, format: {PrettyLog.LogfmtFormatter, :format}, metadata: [:function] # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20
34.225
170
0.742878
1c0ea655f7f79f471326f14057813cbc512d94fa
6,959
ex
Elixir
lib/clickhouse_ecto/migration.ex
julienmarie/clickhouse_ecto
48b556bd93884df3b180a974801d7c09f43ade36
[ "Apache-2.0" ]
1
2020-08-14T18:47:31.000Z
2020-08-14T18:47:31.000Z
lib/clickhouse_ecto/migration.ex
julienmarie/clickhouse_ecto
48b556bd93884df3b180a974801d7c09f43ade36
[ "Apache-2.0" ]
null
null
null
lib/clickhouse_ecto/migration.ex
julienmarie/clickhouse_ecto
48b556bd93884df3b180a974801d7c09f43ade36
[ "Apache-2.0" ]
2
2020-02-25T02:59:10.000Z
2020-09-17T20:43:24.000Z
defmodule ClickhouseEcto.Migration do require IEx alias Ecto.Migration.Table alias Ecto.Migration.Reference import ClickhouseEcto.Helpers @drops [:drop, :drop_if_exists] @doc """ Receives a DDL command and returns a query that executes it. """ @spec execute_ddl(command :: Ecto.Adapter.Migration.command()) :: String.t() def execute_ddl({command, %Table{} = table, columns}) when command in [:create, :create_if_not_exists] do engine = table.engine {_, first_column_name, _, _} = List.first(columns) filtered_columns = cond do first_column_name == :id -> List.delete_at(columns, 0) true -> columns end query = [ if_do(command == :create_if_not_exists, "CREATE TABLE IF NOT EXISTS ", "CREATE TABLE "), quote_table(table.prefix, table.name), ?\s, ?(, column_definitions(table, filtered_columns), ?), options_expr(table.options), if_do(engine != nil, " ENGINE = #{engine} ", " ENGINE = TinyLog ") ] [query] end def execute_ddl({command, %Table{} = table}) when command in @drops do [ [ if_do(command == :drop_if_exists, "DROP TABLE IF EXISTS ", "DROP TABLE "), quote_table(table.prefix, table.name) ] ] end def execute_ddl({:alter, %Table{} = table, changes}) do query = [column_changes(table, changes)] [query] end # TODO: Add 'ON CLUSTER' option. def execute_ddl({:rename, %Table{} = current_table, %Table{} = new_table}) do [ [ "RENAME TABLE ", quote_name([current_table.prefix, current_table.name]), " TO ", quote_name(new_table.name) ] ] end def execute_ddl({:rename, %Table{} = _table, _current_column, _new_column}) do # https://github.com/yandex/ClickHouse/issues/146 raise "It seems like reneaming columns is not supported..." end def execute_ddl(string) when is_binary(string), do: [string] def execute_ddl(keyword) when is_list(keyword), do: error!(nil, "Clickhouse adapter does not support keyword lists in execute") @doc false def supports_ddl_transaction? do false end ## Helpers defp quote_alter([], _table), do: [] defp quote_alter(statement, table), do: ["ALTER TABLE ", quote_table(table.prefix, table.name), statement, "; "] defp column_definitions(table, columns) do intersperse_map(columns, ", ", &column_definition(table, &1)) end defp column_definition(table, {:add, name, %Reference{} = ref, opts}) do [quote_name(name), ?\s, column_options(ref.type, opts, table, name)] end defp column_definition(table, {:add, name, type, opts}) do [quote_name(name), ?\s, column_type(type, opts), column_options(type, opts, table, name)] end defp column_changes(table, columns) do {additions, changes} = Enum.split_with( columns, fn val -> elem(val, 0) == :add end ) [ if_do(additions !== [], column_additions(additions, table)), if_do(changes !== [], Enum.map(changes, &column_change(table, &1))) ] end defp column_additions(additions, table) do Enum.map(additions, fn addition -> [" ADD COLUMN ", column_change(table, addition)] end) |> Enum.join(",") |> quote_alter(table) end defp column_change(table, {:add, name, %Reference{} = ref, opts}) do [quote_name(name), ?\s, column_options(ref.type, opts, table, name)] end defp column_change(table, {:add, name, type, opts}) do [quote_name(name), ?\s, column_type(type, opts), column_options(type, opts, table, name)] end defp column_change(table, {:modify, name, %Reference{} = ref, opts}) do [ quote_alter([" MODIFY COLUMN ", quote_name(name), ?\s, modify_null(name, opts)], table), modify_default(name, ref.type, opts, table, name) ] end defp column_change(table, {:modify, name, type, opts}) do [ quote_alter( [ " MODIFY COLUMN ", quote_name(name), ?\s, column_type(type, opts), modify_null(name, opts) ], table ), modify_default(name, type, opts, table, name) ] end defp column_change(table, {:remove, name}) do [quote_alter([" DROP COLUMN ", quote_name(name)], table)] end defp modify_null(_name, opts) do case Keyword.get(opts, :null) do nil -> [] val -> null_expr(val) end end defp modify_default(name, type, opts, table, name) do case Keyword.fetch(opts, :default) do {:ok, val} -> [ quote_alter( [" ADD", default_expr({:ok, val}, type, table, name), " FOR ", quote_name(name)], table ) ] :error -> [] end end defp column_options(type, opts, table, name) do default = Keyword.fetch(opts, :default) null = Keyword.get(opts, :null) [default_expr(default, type, table, name), null_expr(null)] end # defp null_expr(false), do: " NOT NULL" defp null_expr(false), do: " " defp null_expr(true), do: " NULL" defp null_expr(_), do: [] defp default_expr({:ok, _} = default, type, _table, _name), do: [default_expr(default, type)] defp default_expr(:error, _, _, _), do: [] defp default_expr({:ok, nil}, _type), do: error!(nil, "NULL is not supported") defp default_expr({:ok, []}, _type), do: error!(nil, "arrays are not supported") defp default_expr({:ok, literal}, _type) when is_binary(literal), do: [" DEFAULT '", escape_string(literal), ?'] defp default_expr({:ok, literal}, _type) when is_number(literal), do: [" DEFAULT ", to_string(literal)] defp default_expr({:ok, literal}, _type) when is_boolean(literal), do: [" DEFAULT ", to_string(if literal, do: 1, else: 0)] defp default_expr({:ok, :today}, :date), do: [" DEFAULT today()"] defp default_expr({:ok, {:fragment, expr}}, _type), do: [" DEFAULT ", expr] defp default_expr({:ok, expr}, type), do: raise( ArgumentError, "unknown default `#{inspect(expr)}` for type `#{inspect(type)}`. " <> ":default may be a string, number, boolean, empty list or a fragment(...)" ) defp options_expr(nil), do: [] defp options_expr(keyword) when is_list(keyword), do: error!(nil, "ClickHouse adapter does not support keyword lists in :options") defp options_expr(options), do: [?\s, options] defp column_type({:array, type}, opts), do: [column_type(type, opts), "[]"] defp column_type(type, opts) do size = Keyword.get(opts, :size) precision = Keyword.get(opts, :precision) scale = Keyword.get(opts, :scale) type_name = ecto_to_db(type) cond do size -> [type_name, ?(, to_string(size), ?)] precision -> [type_name, ?(, to_string(precision), ?,, to_string(scale || 0), ?)] type == :string -> [type_name, " "] true -> type_name end end end
27.397638
94
0.614312
1c0ec2e3660a8a81e2724a6c8ec3c1a933708e13
682
ex
Elixir
lib/otto_api/threat.ex
DEVCONSec/otto-api-client-elixir
b74da14fbb7c4e33f0fe15e583630b6efa634d47
[ "MIT" ]
null
null
null
lib/otto_api/threat.ex
DEVCONSec/otto-api-client-elixir
b74da14fbb7c4e33f0fe15e583630b6efa634d47
[ "MIT" ]
1
2020-11-11T15:16:51.000Z
2020-11-11T20:53:34.000Z
lib/otto_api/threat.ex
DEVCONSec/otto-api-client-elixir
b74da14fbb7c4e33f0fe15e583630b6efa634d47
[ "MIT" ]
null
null
null
defmodule OttoApi.Threat do @enforce_keys [:name, :description, :severity] defstruct @enforce_keys ++ [:id] alias OttoApi.Client @spec all(client :: %Client{}) :: {:ok, list(%__MODULE__{id: binary, name: string, description: string, severity: integer})} def all(client) do {:ok, %{ "data" => records }} = Client.get(client, "/threats") threats = Enum.map(records, fn record -> %{"id" => id, "name" => name, "description" => description, "severity" => severity} = record %__MODULE__{id: id, name: name, description: description, severity: severity} end) {:ok, threats} end end
24.357143
95
0.582111
1c0f3a095f979617d85a4c536478c804f7027dd2
1,238
ex
Elixir
lib/twinkly_maha_web/router.ex
TraceyOnim/TwinklyMaHa
cb9d907d8807e00f1e6e44085fd6f39ae32370b6
[ "MIT" ]
null
null
null
lib/twinkly_maha_web/router.ex
TraceyOnim/TwinklyMaHa
cb9d907d8807e00f1e6e44085fd6f39ae32370b6
[ "MIT" ]
null
null
null
lib/twinkly_maha_web/router.ex
TraceyOnim/TwinklyMaHa
cb9d907d8807e00f1e6e44085fd6f39ae32370b6
[ "MIT" ]
null
null
null
defmodule TwinklyMahaWeb.Router do use TwinklyMahaWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :put_root_layout, {TwinklyMahaWeb.LayoutView, :root} plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", TwinklyMahaWeb do pipe_through :browser live "/", PageLive, :index live "/phoenix", PageLive, :index live "/twinkly", TwinklyLive, :twinkly end # Other scopes may use custom stacks. # scope "/api", TwinklyMahaWeb do # pipe_through :api # end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through :browser live_dashboard "/dashboard", metrics: TwinklyMahaWeb.Telemetry end end end
26.913043
70
0.703554
1c0f48e035a17cc70e49f74fde0f715431fa8a05
449
ex
Elixir
lib/addict/interactors/inject_hash.ex
mainframe2/addict
aa70768f20939bf1f4d36a680240cb32f36e2a79
[ "MIT" ]
null
null
null
lib/addict/interactors/inject_hash.ex
mainframe2/addict
aa70768f20939bf1f4d36a680240cb32f36e2a79
[ "MIT" ]
null
null
null
lib/addict/interactors/inject_hash.ex
mainframe2/addict
aa70768f20939bf1f4d36a680240cb32f36e2a79
[ "MIT" ]
null
null
null
defmodule Addict.Interactors.InjectHash do @moduledoc """ Adds `"encrypted_password"` and drops `"password"` from provided hash. Returns the new hash with `"encrypted_password"` and without `"password"`. """ alias Addict.Interactors.GenerateEncryptedPassword def call(user_params) do user_params |> Map.put("encrypted_password", GenerateEncryptedPassword.call(user_params["password"])) |> Map.drop(["password"]) end end
28.0625
93
0.732739
1c0f62e7e3cd07df883642c4de99423b968bcfdc
2,037
ex
Elixir
clients/jobs/lib/google_api/jobs/v2/model/response_metadata.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/jobs/lib/google_api/jobs/v2/model/response_metadata.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/jobs/lib/google_api/jobs/v2/model/response_metadata.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.Jobs.V2.Model.ResponseMetadata do @moduledoc """ Output only. Additional information returned to client, such as debugging information. ## Attributes * `experimentIdList` (*type:* `list(integer())`, *default:* `nil`) - Identifiers for the versions of the search algorithm used during this API invocation if multiple algorithms are used. The default value is empty. For search response only. * `mode` (*type:* `String.t`, *default:* `nil`) - For search response only. Indicates the mode of a performed search. * `requestId` (*type:* `String.t`, *default:* `nil`) - A unique id associated with this call. This id is logged for tracking purposes. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :experimentIdList => list(integer()), :mode => String.t(), :requestId => String.t() } field(:experimentIdList, type: :list) field(:mode) field(:requestId) end defimpl Poison.Decoder, for: GoogleApi.Jobs.V2.Model.ResponseMetadata do def decode(value, options) do GoogleApi.Jobs.V2.Model.ResponseMetadata.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Jobs.V2.Model.ResponseMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.95
137
0.714286
1c0f647fd1d199e403aa283328daebea2c678361
1,560
ex
Elixir
lib/vapor/providers/dotenv.ex
cheerfulstoic/vapor
326a9e8fe0bba706b9726e136b4a51726f9d99f7
[ "Apache-2.0" ]
null
null
null
lib/vapor/providers/dotenv.ex
cheerfulstoic/vapor
326a9e8fe0bba706b9726e136b4a51726f9d99f7
[ "Apache-2.0" ]
null
null
null
lib/vapor/providers/dotenv.ex
cheerfulstoic/vapor
326a9e8fe0bba706b9726e136b4a51726f9d99f7
[ "Apache-2.0" ]
null
null
null
defmodule Vapor.Provider.Dotenv do @moduledoc """ The dotenv config provider will look for a `.env` file and load all of the values for that file. The values can be written like so: ``` DATABASE_URL=https://localhost:9432 PORT=4000 REDIS_HOST=1234 ``` If the file can't be found then this provider will still return an ok but will (obviously) not load any configuration values. The primary use case for this provider is local development where it might be inconvenient to add all of the necessary environment variables on your local machine and it makes tradeoffs for that use case. """ defstruct filename: ".env" defimpl Vapor.Provider do def load(%{filename: filename}) do case File.read(filename) do {:ok, contents} -> for {k, v} <- parse(contents) do System.put_env(k, v) end {:ok, %{}} _ -> {:ok, %{}} end end defp parse(contents) do contents |> String.split(~r/\n/, trim: true) |> Enum.reject(&comment?/1) |> Enum.map(fn pair -> String.split(pair, "=") end) |> Enum.filter(&good_pair/1) |> Enum.map(fn [key, value] -> {String.trim(key), String.trim(value)} end) |> Enum.map(fn {key, value} -> {key, value} end) end defp comment?(line) do Regex.match?(~R/\A\s*#/, line) end defp good_pair(pair) do case pair do [key, value] -> String.length(key) > 0 && String.length(value) > 0 _ -> false end end end end
26.440678
80
0.596795
1c0f7396a6cbd884c5e2db12504eaab621d1e519
368
ex
Elixir
algorithms/medium/validate_ip_address.ex
stackcats/leetcode
8d50cd92ced2ca991ea9f1e5311f5fda5707d81d
[ "MIT" ]
1
2021-05-30T05:06:06.000Z
2021-05-30T05:06:06.000Z
algorithms/medium/validate_ip_address.ex
stackcats/leetcode
8d50cd92ced2ca991ea9f1e5311f5fda5707d81d
[ "MIT" ]
null
null
null
algorithms/medium/validate_ip_address.ex
stackcats/leetcode
8d50cd92ced2ca991ea9f1e5311f5fda5707d81d
[ "MIT" ]
null
null
null
defmodule Solution do @spec valid_ip_address(ip :: String.t) :: String.t def valid_ip_address(ip) do cond do Regex.match?(~r/^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|1[0-9]|[0-9]).){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|1[0-9]|[0-9])$/, ip) -> "IPv4" Regex.match?(~r/^([0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$/i, ip) -> "IPv6" true -> "Neither" end end end
33.454545
134
0.513587
1c0f8d40b58803ea8df1598f6b9ca3d1e2b59518
1,325
ex
Elixir
clients/drive_activity/lib/google_api/drive_activity/v2/model/anonymous_user.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/drive_activity/lib/google_api/drive_activity/v2/model/anonymous_user.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/drive_activity/lib/google_api/drive_activity/v2/model/anonymous_user.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DriveActivity.V2.Model.AnonymousUser do @moduledoc """ Empty message representing an anonymous user or indicating the authenticated user should be anonymized. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.DriveActivity.V2.Model.AnonymousUser do def decode(value, options) do GoogleApi.DriveActivity.V2.Model.AnonymousUser.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DriveActivity.V2.Model.AnonymousUser do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.813953
78
0.766038
1c0f90d05794a6a43a01f8ca534f47cf6e1b4c0b
1,879
exs
Elixir
mix.exs
Raulkumar/bamboo
0fcff1bf61e595eb821bc691ed9370b6a092afbf
[ "MIT" ]
null
null
null
mix.exs
Raulkumar/bamboo
0fcff1bf61e595eb821bc691ed9370b6a092afbf
[ "MIT" ]
null
null
null
mix.exs
Raulkumar/bamboo
0fcff1bf61e595eb821bc691ed9370b6a092afbf
[ "MIT" ]
null
null
null
defmodule Bamboo.Mixfile do use Mix.Project @project_url "https://github.com/thoughtbot/bamboo" def project do [ app: :bamboo, version: "1.5.0", elixir: "~> 1.2", source_url: @project_url, homepage_url: @project_url, compilers: compilers(Mix.env()), test_coverage: [tool: ExCoveralls], preferred_cli_env: [coveralls: :test, "coveralls.circle": :test], elixirc_paths: elixirc_paths(Mix.env()), description: "Straightforward, powerful, and adapter based Elixir email library." <> " Works with Mandrill, Mailgun, SendGrid, SparkPost, Postmark, in-memory, and test.", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, package: package(), docs: [main: "readme", extras: ["README.md"]], deps: deps() ] end defp compilers(:test), do: [:phoenix] ++ Mix.compilers() defp compilers(_), do: Mix.compilers() # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [ applications: [:logger, :hackney], mod: {Bamboo, []} ] end defp package do [ maintainers: ["Paul Smith"], licenses: ["MIT"], links: %{"GitHub" => @project_url} ] end defp elixirc_paths(:test), do: elixirc_paths() ++ ["test/support"] defp elixirc_paths(_), do: elixirc_paths() defp elixirc_paths, do: ["lib"] defp deps do [ {:plug, "~> 1.0"}, {:ex_machina, "~> 2.2", only: :test}, {:cowboy, "~> 1.0", only: [:test, :dev]}, {:phoenix, "~> 1.1", only: :test}, {:phoenix_html, "~> 2.2", only: :test}, {:excoveralls, "~> 0.4", only: :test}, {:floki, "~> 0.8", only: :test}, {:ex_doc, "~> 0.20", only: :dev}, {:hackney, ">= 1.13.0"}, {:jason, "~> 1.0", optional: true} ] end end
27.632353
95
0.569984
1c0f9e4a3bf4369f2067527793250cff221a7c26
183
ex
Elixir
lib/grapevine/client/broadcast.ex
shanesveller/grapevine
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
[ "MIT" ]
null
null
null
lib/grapevine/client/broadcast.ex
shanesveller/grapevine
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
[ "MIT" ]
null
null
null
lib/grapevine/client/broadcast.ex
shanesveller/grapevine
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
[ "MIT" ]
null
null
null
defmodule Grapevine.Client.Broadcast do @moduledoc """ Struct for messages being broadcast on a channel """ @derive Jason.Encoder defstruct [:channel, :name, :message] end
20.333333
50
0.726776
1c0fbcff0d70b4a5a03e8654c94a28547956731f
2,228
ex
Elixir
lib/wechat/work/oa/schedule.ex
feng19/wechat
431c22818c60cd01fc5c676aa060feb303d0c444
[ "Apache-2.0" ]
7
2021-01-22T04:07:29.000Z
2021-12-14T14:01:30.000Z
lib/wechat/work/oa/schedule.ex
feng19/wechat
431c22818c60cd01fc5c676aa060feb303d0c444
[ "Apache-2.0" ]
1
2021-03-17T15:44:26.000Z
2021-03-17T15:44:26.000Z
lib/wechat/work/oa/schedule.ex
feng19/wechat
431c22818c60cd01fc5c676aa060feb303d0c444
[ "Apache-2.0" ]
2
2021-03-17T14:35:56.000Z
2021-08-10T07:44:10.000Z
defmodule WeChat.Work.OA.Schedule do @moduledoc "日程" import Jason.Helpers import WeChat.Utils, only: [work_doc_link_prefix: 0] alias WeChat.Work alias WeChat.Work.OA.Calendar @doc_link "#{work_doc_link_prefix()}/90135/93648" @typedoc "日程ID" @type schedule_id :: String.t() @type schedule_id_list :: [schedule_id] @doc """ 创建日程 - [官方文档](#{@doc_link}#创建日程){:target="_blank"} """ @spec add(Work.client(), Work.agent(), body :: map) :: WeChat.response() def add(client, agent, body) do client.post("/cgi-bin/oa/schedule/add", body, query: [access_token: client.get_access_token(agent)] ) end @doc """ 更新日程 - [官方文档](#{@doc_link}#更新日程){:target="_blank"} """ @spec update(Work.client(), Work.agent(), body :: map) :: WeChat.response() def update(client, agent, body) do client.post("/cgi-bin/oa/schedule/update", body, query: [access_token: client.get_access_token(agent)] ) end @doc """ 获取日程详情 - [官方文档](#{@doc_link}#获取日程详情){:target="_blank"} """ @spec get(Work.client(), Work.agent(), schedule_id_list) :: WeChat.response() def get(client, agent, schedule_id_list) do client.post("/cgi-bin/oa/schedule/get", json_map(schedule_id_list: schedule_id_list), query: [access_token: client.get_access_token(agent)] ) end @doc """ 取消日程 - [官方文档](#{@doc_link}#取消日程){:target="_blank"} """ @spec delete(Work.client(), Work.agent(), schedule_id) :: WeChat.response() def delete(client, agent, schedule_id) do client.post("/cgi-bin/oa/schedule/del", json_map(schedule_id: schedule_id), query: [access_token: client.get_access_token(agent)] ) end @doc """ 获取日历下的日程列表 - [官方文档](#{@doc_link}#获取日历下的日程列表){:target="_blank"} """ @spec get_by_calendar( Work.client(), Work.agent(), Calendar.calendar_id(), offset :: integer, limit :: 1..1000 ) :: WeChat.response() def get_by_calendar(client, agent, calendar_id, offset \\ 0, limit \\ 500) do client.post( "/cgi-bin/oa/schedule/get_by_calendar", json_map(cal_id: calendar_id, offset: offset, limit: limit), query: [access_token: client.get_access_token(agent)] ) end end
28.935065
89
0.643178
1c0fe32b84f42f50604c62e1ab57affcb22a4d8b
232
exs
Elixir
priv/repo/migrations/20170612223827_create_users_user.exs
Apps-Team/conferencetools
ce2e16a3e4a521dc4682e736a209e6dd380c050d
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20170612223827_create_users_user.exs
Apps-Team/conferencetools
ce2e16a3e4a521dc4682e736a209e6dd380c050d
[ "Apache-2.0" ]
6
2017-10-05T20:16:34.000Z
2017-10-05T20:36:11.000Z
priv/repo/migrations/20170612223827_create_users_user.exs
apps-team/events-tools
ce2e16a3e4a521dc4682e736a209e6dd380c050d
[ "Apache-2.0" ]
null
null
null
defmodule EventsTools.Repo.Migrations.CreateEventsTools.Accounts.User do use Ecto.Migration def change do create table(:users) do add :email, :string add :password, :string timestamps() end end end
17.846154
72
0.689655
1c0fee83b8634491c07c236407d8316d0a8b7c8d
250
ex
Elixir
jobsPortalService/lib/models/posting.ex
andraspatka/jobportal-ms
006c8ca212f88566113c4b5c00dfe1d4e421c034
[ "MIT" ]
1
2021-05-25T18:24:27.000Z
2021-05-25T18:24:27.000Z
jobsPortalService/lib/models/posting.ex
andraspatka/jobportal-ms
006c8ca212f88566113c4b5c00dfe1d4e421c034
[ "MIT" ]
1
2021-05-23T09:50:10.000Z
2021-05-23T09:50:10.000Z
jobsPortalService/lib/models/posting.ex
andraspatka/jobportal-ms
006c8ca212f88566113c4b5c00dfe1d4e421c034
[ "MIT" ]
null
null
null
defmodule Models.Postings do defstruct id: nil, postedById: nil, postedAt: nil, deadline: nil, numberOfViews: nil, name: nil, description: nil, categoryId: nil, requirements: nil end
22.727273
28
0.568
1c100b834cfd03324107fca55d9696d769e10b84
2,423
ex
Elixir
clients/content/lib/google_api/content/v2/model/productstatuses_custom_batch_request_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/productstatuses_custom_batch_request_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/productstatuses_custom_batch_request_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V2.Model.ProductstatusesCustomBatchRequestEntry do @moduledoc """ A batch entry encoding a single non-batch productstatuses request. ## Attributes * `batchId` (*type:* `integer()`, *default:* `nil`) - An entry ID, unique within the batch request. * `destinations` (*type:* `list(String.t)`, *default:* `nil`) - If set, only issues for the specified destinations are returned, otherwise only issues for the Shopping destination. * `includeAttributes` (*type:* `boolean()`, *default:* `nil`) - * `merchantId` (*type:* `String.t`, *default:* `nil`) - The ID of the managing account. * `method` (*type:* `String.t`, *default:* `nil`) - The method of the batch entry. Acceptable values are: - "get" * `productId` (*type:* `String.t`, *default:* `nil`) - The ID of the product whose status to get. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :batchId => integer(), :destinations => list(String.t()), :includeAttributes => boolean(), :merchantId => String.t(), :method => String.t(), :productId => String.t() } field(:batchId) field(:destinations, type: :list) field(:includeAttributes) field(:merchantId) field(:method) field(:productId) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.ProductstatusesCustomBatchRequestEntry do def decode(value, options) do GoogleApi.Content.V2.Model.ProductstatusesCustomBatchRequestEntry.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.ProductstatusesCustomBatchRequestEntry do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.276923
184
0.698308
1c10112561efa5379f80d72ac9c582e79497a00c
572
ex
Elixir
lib/ash/resource/actions/destroy.ex
elbow-jason/ash
eb63bc9d4d24187ad07d9892088b4e55ad6258e4
[ "MIT" ]
1
2021-12-27T09:43:29.000Z
2021-12-27T09:43:29.000Z
lib/ash/resource/actions/destroy.ex
elbow-jason/ash
eb63bc9d4d24187ad07d9892088b4e55ad6258e4
[ "MIT" ]
null
null
null
lib/ash/resource/actions/destroy.ex
elbow-jason/ash
eb63bc9d4d24187ad07d9892088b4e55ad6258e4
[ "MIT" ]
null
null
null
defmodule Ash.Resource.Actions.Destroy do @moduledoc "Represents a destroy action on a resource." defstruct [:name, :primary?, type: :destroy] @type t :: %__MODULE__{ type: :destroy, name: atom, primary?: boolean } @opt_schema [ name: [ type: :atom, doc: "The name of the action" ], primary?: [ type: :boolean, default: false, doc: "Whether or not this action should be used when no action is specified by the caller." ] ] @doc false def opt_schema, do: @opt_schema end
21.185185
97
0.592657
1c101f407ab1ae8f10a38838c84cdc1424bc4e0a
197
exs
Elixir
geolocate/test/controllers/page_controller_test.exs
gregoryterlecki/geolocateproject
c283b9f589fbd8046b82a1a027fd5a56f250a8f6
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geolocate/test/controllers/page_controller_test.exs
gregoryterlecki/geolocateproject
c283b9f589fbd8046b82a1a027fd5a56f250a8f6
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geolocate/test/controllers/page_controller_test.exs
gregoryterlecki/geolocateproject
c283b9f589fbd8046b82a1a027fd5a56f250a8f6
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
defmodule Geolocate.PageControllerTest do use Geolocate.ConnCase test "GET /", %{conn: conn} do conn = get conn, "/" assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
21.888889
60
0.680203
1c1020ea70a2d4efeb5f6a5dc699e2d1b024116c
1,377
ex
Elixir
lib/spaceex_web/router.ex
LuizFerK/SpaceEx
ca1a4bd4881692860879b6f2c5d55bc521332c39
[ "MIT" ]
1
2021-12-13T15:50:00.000Z
2021-12-13T15:50:00.000Z
lib/spaceex_web/router.ex
LuizFerK/SpaceEx
ca1a4bd4881692860879b6f2c5d55bc521332c39
[ "MIT" ]
null
null
null
lib/spaceex_web/router.ex
LuizFerK/SpaceEx
ca1a4bd4881692860879b6f2c5d55bc521332c39
[ "MIT" ]
2
2022-01-09T18:12:17.000Z
2022-01-23T22:12:51.000Z
defmodule SpaceexWeb.Router do use SpaceexWeb, :router alias SpaceexWeb.Plugs.IDChecker pipeline :api do plug :accepts, ["json"] plug IDChecker end # coveralls-ignore-start pipeline :docs do plug OpenApiSpex.Plug.PutApiSpec, module: SpaceexWeb.ApiSpec end # coveralls-ignore-stop scope "/", SpaceexWeb do pipe_through :api get "/", WelcomeController, :index resources "/articles", ArticlesController, except: [:new, :edit] end # coveralls-ignore-start scope "/" do pipe_through :docs get "/docs/json", OpenApiSpex.Plug.RenderSpec, [] get "/docs", OpenApiSpex.Plug.SwaggerUI, path: "/docs/json" end # coveralls-ignore-stop # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through [:fetch_session, :protect_from_forgery] # coveralls-ignore-start live_dashboard "/dashboard", metrics: SpaceexWeb.Telemetry # coveralls-ignore-stop end end end
25.981132
70
0.703704
1c1039b2394e2a6eb74118ad755395aace59ae55
4,453
ex
Elixir
lib/helpers.ex
elpulgardelpanda/syscrap
03e5dee924df8cd69db4eddb1e557168ea0ee04f
[ "MIT" ]
null
null
null
lib/helpers.ex
elpulgardelpanda/syscrap
03e5dee924df8cd69db4eddb1e557168ea0ee04f
[ "MIT" ]
null
null
null
lib/helpers.ex
elpulgardelpanda/syscrap
03e5dee924df8cd69db4eddb1e557168ea0ee04f
[ "MIT" ]
null
null
null
alias Keyword, as: K defmodule Syscrap.Helpers do @moduledoc """ require SSHEx.Helpers, as: H # the cool way """ @doc """ Convenience to get environment bits. Avoid all that repetitive `Application.get_env( :myapp, :blah, :blah)` noise. """ def env(key, default \\ nil), do: env(:syscrap, key, default) def env(app, key, default), do: Application.get_env(app, key, default) @doc """ Spit to output any passed variable, with location information. """ defmacro spit(obj \\ "", inspect_opts \\ []) do quote do %{file: file, line: line} = __ENV__ name = Process.info(self)[:registered_name] chain = [ :bright, :red, "\n\n#{file}:#{line}", :normal, "\n #{inspect self}", :green," #{name}"] msg = inspect(unquote(obj),unquote(inspect_opts)) if String.length(msg) > 2, do: chain = chain ++ [:red, "\n\n#{msg}"] # chain = chain ++ [:yellow, "\n\n#{inspect Process.info(self)}"] (chain ++ ["\n\n", :reset]) |> IO.ANSI.format(true) |> IO.puts unquote(obj) end end @doc """ Print to stdout a _TODO_ message, with location information. """ defmacro todo(msg \\ "") do quote do %{file: file, line: line} = __ENV__ [ :yellow, "\nTODO: #{file}:#{line} #{unquote(msg)}\n", :reset] |> IO.ANSI.format(true) |> IO.puts :todo end end @doc """ Apply given defaults to given Keyword. Returns merged Keyword. The inverse of `Keyword.merge`, best suited to apply some defaults in a chainable way. Ex: kw = gather_data |> transform_data |> H.defaults(k1: 1234, k2: 5768) |> here_i_need_defaults Instead of: kw1 = gather_data |> transform_data kw = [k1: 1234, k2: 5768] |> Keyword.merge(kw1) |> here_i_need_defaults iex> [a: 3] |> Syscrap.Helpers.defaults(a: 4, b: 5) [b: 5, a: 3] iex> %{a: 3} |> Syscrap.Helpers.defaults(%{a: 4, b: 5}) %{a: 3, b: 5} """ def defaults(args, defs) when is_map(args) and is_map(defs) do defs |> Map.merge(args) end def defaults(args, defs) do if not([K.keyword?(args), K.keyword?(defs)] === [true, true]), do: raise(ArgumentError, "Both arguments must be Keyword lists.") defs |> K.merge(args) end @doc """ Wait for given function to return true. Optional `msecs` and `step`. Be aware that exceptions raised and thrown messages by given `func` will be discarded. """ def wait_for(func, msecs \\ 5_000, step \\ 100) do res = try do func.() rescue _ -> nil catch :exit, _ -> nil end if res do :ok else if msecs <= 0, do: raise "Timeout!" :timer.sleep step wait_for func, msecs - step, step end end @doc """ Gets names for children in given supervisor. Children with no registered name are not returned. List is sorted. """ def named_children(supervisor) do supervisor |> Supervisor.which_children |> Enum.map(fn({_,pid,_,_})-> Process.info(pid)[:registered_name] end) |> Enum.filter(&(&1)) |> Enum.sort end @doc """ Kill all of given supervisor's children """ def kill_children(supervisor) do children = supervisor |> Supervisor.which_children for {_,pid,_,_} <- children, do: true = Process.exit(pid, :kill) :ok end @doc """ Set given value on given keys coordinates inside given map. If any intermediate coordinate is nil, then it's created as an empty map. If given value is a function, then the function is executed passing it the previous value (which can be nil). iex> Syscrap.Helpers.set_in(%{}, 3, [:a, :b, :c]) %{a: %{b: %{c: 3}}} iex> Syscrap.Helpers.set_in(%{a: %{b: 3}}, 5, [:a, :b]) %{a: %{b: 5}} iex> Syscrap.Helpers.set_in(%{a: %{b: 3}}, 5, [:a, :c]) %{a: %{b: 3, c: 5}} iex> Syscrap.Helpers.set_in(%{}, &("Hey " <> to_string(&1)), [:a, :b]) %{a: %{b: "Hey "}} iex> Syscrap.Helpers.set_in(%{a: %{b: "Hansel"}}, &("Hey " <> to_string(&1)), [:a, :b]) %{a: %{b: "Hey Hansel"}} """ def set_in(map, func, [k | []]) when is_function(func) do Map.update(map, k, func.(nil), func) end def set_in(map, value, [k | []]), do: Map.put(map, k, value) def set_in(map, value, [k | keys]) do m = Map.get(map, k, %{}) Map.put(map, k, set_in(m, value, keys)) end end
28.729032
93
0.573995
1c108fd2ffdbb6a40cb59ece7cd48c4483cd47ba
342
exs
Elixir
priv/repo/seeds.exs
billstclair/readerl
bd81d17109a1fb207d98f1ba1c498f66b195d1ba
[ "BSD-3-Clause" ]
3
2015-10-31T02:33:29.000Z
2016-07-19T06:25:03.000Z
priv/repo/seeds.exs
billstclair/readerl
bd81d17109a1fb207d98f1ba1c498f66b195d1ba
[ "BSD-3-Clause" ]
null
null
null
priv/repo/seeds.exs
billstclair/readerl
bd81d17109a1fb207d98f1ba1c498f66b195d1ba
[ "BSD-3-Clause" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Readerl.Repo.insert!(%SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
28.5
61
0.701754
1c109c87985cee6941c21dc163c12b49f92c89e3
878
ex
Elixir
clients/apigee/lib/google_api/apigee/v1/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/apigee/lib/google_api/apigee/v1/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/apigee/lib/google_api/apigee/v1/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "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.Apigee.V1 do @moduledoc """ API client metadata for GoogleApi.Apigee.V1. """ @discovery_revision "20201002" def discovery_revision(), do: @discovery_revision end
32.518519
74
0.757403
1c10c5195c3ebfcd5e57abf832e67a18d77cee0f
2,180
exs
Elixir
test/game/npc/actions/commands_skill_test.exs
nomicflux/ex_venture
3e87dc8802c24067256d99856198c814d0bae4d6
[ "MIT" ]
null
null
null
test/game/npc/actions/commands_skill_test.exs
nomicflux/ex_venture
3e87dc8802c24067256d99856198c814d0bae4d6
[ "MIT" ]
null
null
null
test/game/npc/actions/commands_skill_test.exs
nomicflux/ex_venture
3e87dc8802c24067256d99856198c814d0bae4d6
[ "MIT" ]
null
null
null
defmodule Game.NPC.Actions.CommandsSkillTest do use ExVenture.NPCCase alias Data.Events.Actions alias Game.Character alias Game.NPC.Actions.CommandsSkill alias Game.NPC.State alias Game.Session.Registry doctest CommandsSkill setup [:basic_setup] describe "using skills" do test "uses the skill", %{state: state, action: action, player: player} do state = %{state | combat: true, target: {:player, player}} {:ok, ^state} = CommandsSkill.act(state, action) assert_receive {:"$gen_cast", {:apply_effects, _, _, _}} end test "no skill found", %{state: state, action: action, player: player} do state = %{state | combat: true, target: {:player, player}} action = %{action | options: %{skill: "bash"}} {:ok, ^state} = CommandsSkill.act(state, action) refute_receive {:"$gen_cast", {:apply_effects, _, _, _}}, 50 end test "with no target", %{state: state, action: action} do state = %{state | combat: true, target: nil} {:ok, state} = CommandsSkill.act(state, action) refute state.combat refute_receive {:"$gen_cast", {:apply_effects, _, _, _}}, 50 end test "with target not in the room", %{state: state, action: action, player: player} do start_room(%{players: []}) state = %{state | combat: true, target: {:player, player}} {:ok, state} = CommandsSkill.act(state, action) refute state.combat refute_receive {:"$gen_cast", {:apply_effects, _, _, _}}, 50 end end def basic_setup(_) do npc = npc_attributes(%{id: 1}) state = %State{ room_id: 1, npc: npc, } player = %Character.Simple{ id: 1, type: :player, name: "Player", } notify_user = %{base_user() | id: player.id} notify_character = %{base_character(notify_user) | id: player.id} Registry.register(notify_character) Registry.catch_up() start_room(%{players: [player]}) start_and_clear_skills() insert_skill(create_skill(%{command: "slash"})) action = %Actions.CommandsSkill{ options: %{skill: "slash"} } %{state: state, action: action, player: player} end end
25.952381
90
0.626606
1c10d9f713ba6da2fd5cd90a110dfc52ceea2bfc
207
ex
Elixir
plugins/one_backup_restore/lib/one_backup_restore_web/controllers/upload_controller.ex
smpallen99/ucx_ucc
47225f205a6ac4aacdb9bb4f7512dcf4092576ad
[ "MIT" ]
11
2017-05-15T18:35:05.000Z
2018-02-05T18:27:40.000Z
plugins/one_backup_restore/lib/one_backup_restore_web/controllers/upload_controller.ex
anndream/infinity_one
47225f205a6ac4aacdb9bb4f7512dcf4092576ad
[ "MIT" ]
15
2017-11-27T10:38:05.000Z
2018-02-09T20:42:08.000Z
plugins/one_backup_restore/lib/one_backup_restore_web/controllers/upload_controller.ex
anndream/infinity_one
47225f205a6ac4aacdb9bb4f7512dcf4092576ad
[ "MIT" ]
4
2017-09-13T11:34:16.000Z
2018-02-26T13:37:06.000Z
defmodule OneBackupRestoreWeb.UploadController do use OneBackupRestoreWeb, :controller require Logger def create(conn, params) do Logger.warn "params: #{inspect params}" halt conn end end
17.25
49
0.748792
1c10dd8530e5af979f935ed848b51f086c4c87f5
503
ex
Elixir
socket_gallows/lib/socket_gallows_web/views/error_view.ex
jeethridge/elixir-hangman
ff1202fd1f54cad887180c900670306a20fe4339
[ "Unlicense" ]
null
null
null
socket_gallows/lib/socket_gallows_web/views/error_view.ex
jeethridge/elixir-hangman
ff1202fd1f54cad887180c900670306a20fe4339
[ "Unlicense" ]
null
null
null
socket_gallows/lib/socket_gallows_web/views/error_view.ex
jeethridge/elixir-hangman
ff1202fd1f54cad887180c900670306a20fe4339
[ "Unlicense" ]
null
null
null
defmodule SocketGallowsWeb.ErrorView do use SocketGallowsWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
29.588235
61
0.741551
1c10f094353504e6bf235d47116f12b036c9d41c
69
ex
Elixir
lib/scentenced_web/views/layout_view.ex
cNille/scentenced
ca6cc97bec1122047be928bb62b5ab0021cb88e8
[ "MIT" ]
null
null
null
lib/scentenced_web/views/layout_view.ex
cNille/scentenced
ca6cc97bec1122047be928bb62b5ab0021cb88e8
[ "MIT" ]
1
2020-07-17T08:20:59.000Z
2020-07-17T08:20:59.000Z
lib/scentenced_web/views/layout_view.ex
cNille/scentenced
ca6cc97bec1122047be928bb62b5ab0021cb88e8
[ "MIT" ]
null
null
null
defmodule ScentencedWeb.LayoutView do use ScentencedWeb, :view end
17.25
37
0.826087
1c113b648e4b65c40cfe8c197d2fb7a098def74d
2,532
exs
Elixir
test/support/mock.exs
raw1z/ex_neo4j
afb778f56ff65c63ceb848b8debe9c3e8b3a375e
[ "MIT" ]
2
2015-07-28T16:12:56.000Z
2015-10-09T21:21:16.000Z
test/support/mock.exs
raw1z/ex_neo4j
afb778f56ff65c63ceb848b8debe9c3e8b3a375e
[ "MIT" ]
1
2015-11-01T16:14:34.000Z
2015-11-02T10:35:48.000Z
test/support/mock.exs
raw1z/ex_neo4j
afb778f56ff65c63ceb848b8debe9c3e8b3a375e
[ "MIT" ]
null
null
null
defmodule Mock do def init_mocks do mock_module Timex.Date :meck.expect(Timex.Date, :now, fn -> %Timex.DateTime{calendar: :gregorian, day: 14, hour: 2, minute: 55, month: 10, ms: 0, second: 3, timezone: %Timex.TimezoneInfo{abbreviation: "UTC", from: :min, full_name: "UTC", offset_std: 0, offset_utc: 0, until: :max}, year: 2014} end) mock_module ExNeo4j.Db, [:unstick, :passthrough] mock_module ExNeo4j.HttpClient, [:unstick, :passthrough] end def unload_mocks do :meck.unload(ExNeo4j.Db) :meck.unload(ExNeo4j.HttpClient) :meck.unload(Timex.Date) end defp mock_module(mod, params \\ []) do already_mocked = Process.list |> Enum.map(&Process.info/1) |> Enum.filter(&(&1 != nil)) |> Enum.map(&(Keyword.get(&1, :registered_name))) |> Enum.filter(&(&1 == :"#{mod}_meck")) |> Enum.any? unless already_mocked, do: do_mock_module(mod, params) end defp do_mock_module(mod, []), do: :meck.new(mod) defp do_mock_module(mod, params), do: :meck.new(mod, params) defmacro enable_mock(do: block) do quote do init_mocks unquote(block) unload_mocks end end defmacro cypher_returns(response, for_query: query) do quote bind_quoted: [query: query, response: response] do :meck.expect(ExNeo4j.Db, :cypher, fn (query) -> response end) end end defmacro cypher_returns(response, for_query: query, with_params: params) do quote bind_quoted: [query: query, response: response, params: params] do :meck.expect(ExNeo4j.Db, :cypher, fn (query, params) -> response end) end end defmacro http_client_returns(response, for_query: query, with_params: params) do quote bind_quoted: [query: query, params: params, response: response] do request_body = ExNeo4j.Helpers.format_statements([{query, params}]) :meck.expect(ExNeo4j.HttpClient, :post!, fn ("http://localhost:7474/db/data/transaction/commit", body=request_body) -> %{ body: response } end) end end defmacro http_client_returns(response, for_queries: queries, with_params: params) do quote bind_quoted: [queries: queries, params: params, response: response] do request_body = ExNeo4j.Helpers.format_statements(Enum.zip(queries, params)) :meck.expect(ExNeo4j.HttpClient, :post!, fn ("http://localhost:7474/db/data/transaction/commit", body=request_body) -> %{ body: response } end) end end end
32.461538
86
0.657188
1c113e7ba93e667855f13ec34d8d26f40bc6759b
1,945
exs
Elixir
ui/config/prod.exs
sparrell/BlinkyHaHa
fc634d09d2427d39263f08c4c1841ccfcdbd0842
[ "MIT" ]
1
2021-06-05T18:04:05.000Z
2021-06-05T18:04:05.000Z
ui/config/prod.exs
sparrell/BlinkyHaHa
fc634d09d2427d39263f08c4c1841ccfcdbd0842
[ "MIT" ]
3
2020-06-29T19:05:32.000Z
2020-07-01T20:52:23.000Z
ui/config/prod.exs
sparrell/BlinkyHaHa
fc634d09d2427d39263f08c4c1841ccfcdbd0842
[ "MIT" ]
null
null
null
import 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 :ui, UiWeb.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 :ui, UiWeb.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 :ui, UiWeb.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"
34.732143
66
0.709512
1c114b5a74f9871b47e00643f404a291977a47f4
3,180
ex
Elixir
clients/connectors/lib/google_api/connectors/v1/model/provider.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/connectors/lib/google_api/connectors/v1/model/provider.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/connectors/lib/google_api/connectors/v1/model/provider.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Connectors.V1.Model.Provider do @moduledoc """ Provider indicates the owner who provides the connectors. ## Attributes * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Created time. * `description` (*type:* `String.t`, *default:* `nil`) - Output only. Description of the resource. * `displayName` (*type:* `String.t`, *default:* `nil`) - Output only. Display name. * `documentationUri` (*type:* `String.t`, *default:* `nil`) - Output only. Link to documentation page. * `externalUri` (*type:* `String.t`, *default:* `nil`) - Output only. Link to external page. * `labels` (*type:* `map()`, *default:* `nil`) - Output only. Resource labels to represent user-provided metadata. Refer to cloud documentation on labels for more details. https://cloud.google.com/compute/docs/labeling-resources * `launchStage` (*type:* `String.t`, *default:* `nil`) - Output only. Flag to mark the version indicating the launch stage. * `name` (*type:* `String.t`, *default:* `nil`) - Output only. Resource name of the Provider. Format: projects/{project}/locations/{location}/providers/{provider} * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Updated time. * `webAssetsLocation` (*type:* `String.t`, *default:* `nil`) - Output only. Cloud storage location of icons etc consumed by UI. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :createTime => DateTime.t() | nil, :description => String.t() | nil, :displayName => String.t() | nil, :documentationUri => String.t() | nil, :externalUri => String.t() | nil, :labels => map() | nil, :launchStage => String.t() | nil, :name => String.t() | nil, :updateTime => DateTime.t() | nil, :webAssetsLocation => String.t() | nil } field(:createTime, as: DateTime) field(:description) field(:displayName) field(:documentationUri) field(:externalUri) field(:labels, type: :map) field(:launchStage) field(:name) field(:updateTime, as: DateTime) field(:webAssetsLocation) end defimpl Poison.Decoder, for: GoogleApi.Connectors.V1.Model.Provider do def decode(value, options) do GoogleApi.Connectors.V1.Model.Provider.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Connectors.V1.Model.Provider do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.972973
232
0.677358
1c11b3f797c4c2eed96e21ce80a485322ecdb2a6
902
ex
Elixir
apps/ewallet/lib/ewallet/policies/role_policy.ex
amadeobrands/ewallet
505b7822721940a7b892a9b35c225e80cc8ac0b4
[ "Apache-2.0" ]
1
2018-12-07T06:21:21.000Z
2018-12-07T06:21:21.000Z
apps/ewallet/lib/ewallet/policies/role_policy.ex
amadeobrands/ewallet
505b7822721940a7b892a9b35c225e80cc8ac0b4
[ "Apache-2.0" ]
null
null
null
apps/ewallet/lib/ewallet/policies/role_policy.ex
amadeobrands/ewallet
505b7822721940a7b892a9b35c225e80cc8ac0b4
[ "Apache-2.0" ]
null
null
null
defmodule EWallet.RolePolicy do @moduledoc """ The authorization policy for roles. """ @behaviour Bodyguard.Policy alias EWalletDB.{Account, User} # Any authenticated key or admin user can retrieve the list of roles def authorize(:all, %{key: _}, _role_id), do: true def authorize(:all, %{admin_user: _}, _role_id), do: true # Any authenticated key or admin user can get a role def authorize(:get, %{key: _}, _role_id), do: true def authorize(:get, %{admin_user: _}, _role_id), do: true # Only keys belonging to master account can perform all operations def authorize(_, %{key: key}, _role_id) do Account.get_master_account().uuid == key.account.uuid end # Only users with an admin role on master account can perform all operations def authorize(_, %{admin_user: user}, _role_id) do User.master_admin?(user.id) end def authorize(_, _, _), do: false end
32.214286
78
0.706208
1c11b692905feb3fb3c0a1e4f5ccdc2ed8f7c25b
1,424
exs
Elixir
spec/assertions/binary/have_byte_size_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
spec/assertions/binary/have_byte_size_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
spec/assertions/binary/have_byte_size_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
defmodule ESpec.Assertions.Binary.HaveByteSizeSpec do use ESpec, async: true let :byte_count, do: byte_size(binary()) let :binary, do: <<116, 188, 252, 155, 9>> context "Success" do it "checks success with `to`" do message = expect(binary()).to(have_byte_size(byte_count())) expect(message) |> to(eq "`<<116, 188, 252, 155, 9>>` has `#{byte_count()}` byte(s).") end it "checks success with `not_to`" do message = expect(binary()).to_not(have_byte_size(byte_count() - 1)) expect(message) |> to(eq "`<<116, 188, 252, 155, 9>>` doesn't have `#{byte_count() - 1}` byte(s).") end end context "Error" do context "with `to`" do before do {:shared, expectation: fn -> expect(binary()).to(have_byte_size(byte_count() - 1)) end, message: "Expected `<<116, 188, 252, 155, 9>>` to have `#{byte_count() - 1}` byte(s) but it has `#{ byte_count() }`."} end it_behaves_like(CheckErrorSharedSpec) end context "with `not_to`" do before do {:shared, expectation: fn -> expect(binary()).to_not(have_byte_size(byte_count())) end, message: "Expected `<<116, 188, 252, 155, 9>>` not to have `#{byte_count()}` byte(s) but it has `#{ byte_count() }`."} end it_behaves_like(CheckErrorSharedSpec) end end end
29.061224
101
0.567416
1c11bbde75288f0beaa2b504c0a2c1d708739441
366
ex
Elixir
lib/ex_algo/queue/impls/enumerable.ex
code-shoily/ex_algo
7837c222fd2844a151b6b92038f94ea088bec0a2
[ "MIT" ]
21
2021-11-21T08:07:38.000Z
2022-03-13T06:19:35.000Z
lib/ex_algo/queue/impls/enumerable.ex
code-shoily/ex_algo
7837c222fd2844a151b6b92038f94ea088bec0a2
[ "MIT" ]
3
2021-11-26T22:54:09.000Z
2022-03-06T21:16:12.000Z
lib/ex_algo/queue/impls/enumerable.ex
code-shoily/ex_algo
7837c222fd2844a151b6b92038f94ea088bec0a2
[ "MIT" ]
null
null
null
alias ExAlgo.Queue defimpl Enumerable, for: Queue do def count(queue), do: {:ok, queue |> Queue.to_list() |> Enum.count()} def member?(queue, item) do {:ok, queue |> Queue.to_list() |> Enum.member?(item)} end def reduce(queue, acc, fun) do Enumerable.List.reduce(Queue.to_list(queue), acc, fun) end def slice(_), do: {:error, __MODULE__} end
22.875
71
0.653005
1c11c53602d891c72591ef976b0669b764d69776
119
ex
Elixir
lib/pennystock_api/repo.ex
TheAlexPorter/pennystock-api
e42d8a8d25a31f1723c5f28a344a4ee7ff7e30e9
[ "MIT" ]
null
null
null
lib/pennystock_api/repo.ex
TheAlexPorter/pennystock-api
e42d8a8d25a31f1723c5f28a344a4ee7ff7e30e9
[ "MIT" ]
null
null
null
lib/pennystock_api/repo.ex
TheAlexPorter/pennystock-api
e42d8a8d25a31f1723c5f28a344a4ee7ff7e30e9
[ "MIT" ]
null
null
null
defmodule PennystockApi.Repo do use Ecto.Repo, otp_app: :pennystock_api, adapter: Ecto.Adapters.Postgres end
19.833333
35
0.756303
1c11d93b8f314f567ae9a666bb6b1aba7b4b2821
1,196
ex
Elixir
test/support/conn_case.ex
lnxbil/asciinema-server
7fd64e52927b5d4afc53a2da3243cff91c9c37c3
[ "Apache-2.0" ]
1
2021-07-07T12:36:10.000Z
2021-07-07T12:36:10.000Z
test/support/conn_case.ex
lnxbil/asciinema-server
7fd64e52927b5d4afc53a2da3243cff91c9c37c3
[ "Apache-2.0" ]
null
null
null
test/support/conn_case.ex
lnxbil/asciinema-server
7fd64e52927b5d4afc53a2da3243cff91c9c37c3
[ "Apache-2.0" ]
null
null
null
defmodule AsciinemaWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias Asciinema.Repo import Ecto import Ecto.Changeset import Ecto.Query import AsciinemaWeb.Router.Helpers import AsciinemaWeb.Router.Helpers.Extra import Asciinema.Fixtures # The default endpoint for testing @endpoint AsciinemaWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Asciinema.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Asciinema.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
25.446809
71
0.712375
1c11fab1cb0e4443ca1e1d83d10ca6fd7c49ebd5
268
exs
Elixir
scripts/benchmark_grids.exs
kbsymanz/maze_generator
f9519b83b53d4e74d51aece6644028f1e577b145
[ "MIT" ]
3
2021-07-07T03:45:24.000Z
2021-07-12T13:12:05.000Z
scripts/benchmark_grids.exs
kbsymanz/maze_generator
f9519b83b53d4e74d51aece6644028f1e577b145
[ "MIT" ]
null
null
null
scripts/benchmark_grids.exs
kbsymanz/maze_generator
f9519b83b53d4e74d51aece6644028f1e577b145
[ "MIT" ]
null
null
null
alias MazeGenerator, as: Mg Benchee.run(%{ grid_recursive_10_10: fn -> Mg.new(10, 10, :recursive_backtracker) end, grid_recursive_20_20: fn -> Mg.new(20, 20, :recursive_backtracker) end, grid_recursive_40_40: fn -> Mg.new(40, 40, :recursive_backtracker) end })
33.5
73
0.735075
1c11ff8a9cd129715df12f01fed238012accac8c
9,552
ex
Elixir
lib/chart/scale/continuous_linear_scale.ex
zdenal/contex
6dfa0507ffd79573e5308a83bc6c9d025b6c23ad
[ "MIT" ]
455
2020-01-15T22:21:40.000Z
2022-03-29T23:20:45.000Z
lib/chart/scale/continuous_linear_scale.ex
zdenal/contex
6dfa0507ffd79573e5308a83bc6c9d025b6c23ad
[ "MIT" ]
48
2020-02-10T06:19:17.000Z
2022-03-29T03:02:52.000Z
lib/chart/scale/continuous_linear_scale.ex
zdenal/contex
6dfa0507ffd79573e5308a83bc6c9d025b6c23ad
[ "MIT" ]
30
2020-01-15T22:21:35.000Z
2022-03-10T18:11:51.000Z
defmodule Contex.ContinuousLinearScale do @moduledoc """ A linear scale to map continuous numberic data to a plotting coordinate system. Implements the general aspects of scale setup and use defined in the `Contex.Scale` protocol The `ContinuousLinearScale` is responsible for mapping to and from values in the data to a visual scale. The two key concepts are "domain" and "range". The "domain" represents values in the dataset to be plotted. The "range" represents the plotting coordinate system use to plot values in the "domain". *Important Note* - When you set domain and range, the scale code makes a few adjustments based on the desired number of tick intervals so that the ticks look "nice" - i.e. on round numbers. So if you have a data range of 0.0 &rarr; 8.7 and you want 10 intervals the scale won't display ticks at 0.0, 0.87, 1.74 etc, it will round up the domain to 10 so you have nice tick intervals of 0, 1, 2, 3 etc. By default the scale creates 10 tick intervals. When domain and range are both set, the scale makes transform functions available to map each way between the domain and range that are then available to the various plots to map data to plotting coordinate systems, and potentially vice-versa. The typical setup of the scale looks like this: ``` y_scale = ContinuousLinearScale.new() |> ContinuousLinearScale.domain(min_value, max_value) |> Scale.set_range(start_of_y_plotting_coord, end_of_y_plotting_coord) ``` Translating a value to plotting coordinates would then look like this: ``` plot_y = Scale.domain_to_range(y_scale, y_value) ``` `ContinuousLinearScale` implements the `Contex.Scale` protocol that provides a nicer way to access the transform functions. Calculation of plotting coordinates is typically done in tight loops so you are more likely to do something like than translating a single value as per the above example: ``` x_tx_fn = Scale.domain_to_range_fn(x_scale) y_tx_fn = Scale.domain_to_range_fn(y_scale) points_to_plot = Enum.map(big_load_of_data, fn %{x: x, y: y}=_row -> {x_tx_fn.(x), y_tx_fn.(y)} end) ``` """ alias __MODULE__ alias Contex.Utils defstruct [ :domain, :nice_domain, :range, :interval_count, :interval_size, :display_decimals, :custom_tick_formatter ] @type t() :: %__MODULE__{} @doc """ Creates a new scale with defaults """ @spec new :: Contex.ContinuousLinearScale.t() def new() do %ContinuousLinearScale{range: {0.0, 1.0}, interval_count: 10, display_decimals: nil} end @doc """ Defines the number of intervals between ticks. Defaults to 10. Tick-rendering is the responsibility of `Contex.Axis`, but calculating tick intervals is the responsibility of the scale. """ @spec interval_count(Contex.ContinuousLinearScale.t(), integer()) :: Contex.ContinuousLinearScale.t() def interval_count(%ContinuousLinearScale{} = scale, interval_count) when is_integer(interval_count) and interval_count > 1 do scale |> struct(interval_count: interval_count) |> nice() end def interval_count(%ContinuousLinearScale{} = scale, _), do: scale @doc """ Sets the extents of the value domain for the scale. """ @spec domain(Contex.ContinuousLinearScale.t(), number, number) :: Contex.ContinuousLinearScale.t() def domain(%ContinuousLinearScale{} = scale, min, max) when is_number(min) and is_number(max) do # We can be flexible with the range start > end, but the domain needs to start from the min {d_min, d_max} = case min < max do true -> {min, max} _ -> {max, min} end scale |> struct(domain: {d_min, d_max}) |> nice() end @doc """ Sets the extents of the value domain for the scale by specifying a list of values to be displayed. The scale will determine the extents of the data. """ @spec domain(Contex.ContinuousLinearScale.t(), list(number())) :: Contex.ContinuousLinearScale.t() def domain(%ContinuousLinearScale{} = scale, data) when is_list(data) do {min, max} = extents(data) domain(scale, min, max) end # NOTE: interval count will likely get adjusted down here to keep things looking nice defp nice( %ContinuousLinearScale{domain: {min_d, max_d}, interval_count: interval_count} = scale ) when is_number(min_d) and is_number(max_d) and is_number(interval_count) and interval_count > 1 do width = max_d - min_d width = if width == 0.0, do: 1.0, else: width unrounded_interval_size = width / interval_count order_of_magnitude = :math.ceil(:math.log10(unrounded_interval_size) - 1) power_of_ten = :math.pow(10, order_of_magnitude) rounded_interval_size = lookup_axis_interval(unrounded_interval_size / power_of_ten) * power_of_ten min_nice = rounded_interval_size * Float.floor(min_d / rounded_interval_size) max_nice = rounded_interval_size * Float.ceil(max_d / rounded_interval_size) adjusted_interval_count = round(1.0001 * (max_nice - min_nice) / rounded_interval_size) display_decimals = guess_display_decimals(order_of_magnitude) %{ scale | nice_domain: {min_nice, max_nice}, interval_size: rounded_interval_size, interval_count: adjusted_interval_count, display_decimals: display_decimals } end defp nice(%ContinuousLinearScale{} = scale), do: scale @axis_interval_breaks [0.1, 0.2, 0.25, 0.4, 0.5, 1.0, 2.0, 2.5, 4.0, 5.0, 10.0] defp lookup_axis_interval(raw_interval) when is_float(raw_interval) do Enum.find(@axis_interval_breaks, fn x -> x >= raw_interval end) end defp guess_display_decimals(power_of_ten) when power_of_ten > 0 do 0 end defp guess_display_decimals(power_of_ten) do 1 + -1 * round(power_of_ten) end @doc false def get_domain_to_range_function(%ContinuousLinearScale{ nice_domain: {min_d, max_d}, range: {min_r, max_r} }) when is_number(min_d) and is_number(max_d) and is_number(min_r) and is_number(max_r) do domain_width = max_d - min_d range_width = max_r - min_r case domain_width do 0 -> fn x -> x end 0.0 -> fn x -> x end _ -> fn domain_val -> case domain_val do nil -> nil _ -> ratio = (domain_val - min_d) / domain_width min_r + ratio * range_width end end end end def get_domain_to_range_function(_), do: fn x -> x end @doc false def get_range_to_domain_function(%ContinuousLinearScale{ nice_domain: {min_d, max_d}, range: {min_r, max_r} }) when is_number(min_d) and is_number(max_d) and is_number(min_r) and is_number(max_r) do domain_width = max_d - min_d range_width = max_r - min_r case range_width do 0 -> fn x -> x end 0.0 -> fn x -> x end _ -> fn range_val -> ratio = (range_val - min_r) / range_width min_d + ratio * domain_width end end end def get_range_to_domain_function(_), do: fn x -> x end @doc false def extents(data) do Enum.reduce(data, {nil, nil}, fn x, {min, max} -> {Utils.safe_min(x, min), Utils.safe_max(x, max)} end) end defimpl Contex.Scale do def domain_to_range_fn(%ContinuousLinearScale{} = scale), do: ContinuousLinearScale.get_domain_to_range_function(scale) def ticks_domain(%ContinuousLinearScale{ nice_domain: {min_d, _}, interval_count: interval_count, interval_size: interval_size }) when is_number(min_d) and is_number(interval_count) and is_number(interval_size) do 0..interval_count |> Enum.map(fn i -> min_d + i * interval_size end) end def ticks_domain(_), do: [] def ticks_range(%ContinuousLinearScale{} = scale) do transform_func = ContinuousLinearScale.get_domain_to_range_function(scale) ticks_domain(scale) |> Enum.map(transform_func) end def domain_to_range(%ContinuousLinearScale{} = scale, range_val) do transform_func = ContinuousLinearScale.get_domain_to_range_function(scale) transform_func.(range_val) end def get_range(%ContinuousLinearScale{range: {min_r, max_r}}), do: {min_r, max_r} def set_range(%ContinuousLinearScale{} = scale, start, finish) when is_number(start) and is_number(finish) do %{scale | range: {start, finish}} end def set_range(%ContinuousLinearScale{} = scale, {start, finish}) when is_number(start) and is_number(finish), do: set_range(scale, start, finish) def get_formatted_tick( %ContinuousLinearScale{ display_decimals: display_decimals, custom_tick_formatter: custom_tick_formatter }, tick_val ) do format_tick_text(tick_val, display_decimals, custom_tick_formatter) end defp format_tick_text(tick, _, custom_tick_formatter) when is_function(custom_tick_formatter), do: custom_tick_formatter.(tick) defp format_tick_text(tick, _, _) when is_integer(tick), do: to_string(tick) defp format_tick_text(tick, display_decimals, _) when display_decimals > 0 do :erlang.float_to_binary(tick, decimals: display_decimals) end defp format_tick_text(tick, _, _), do: :erlang.float_to_binary(tick, [:compact, decimals: 0]) end end
31.946488
109
0.682789
1c120bfc78600c0ced955e1345285c2e7b5251a5
1,121
exs
Elixir
restserver_genserver/config/config.exs
arquitecturas-concurrentes/iasc-otp-elixir-2019c2
c8c6c88db978785f439596e0b5f582473b54a35f
[ "BSD-3-Clause" ]
null
null
null
restserver_genserver/config/config.exs
arquitecturas-concurrentes/iasc-otp-elixir-2019c2
c8c6c88db978785f439596e0b5f582473b54a35f
[ "BSD-3-Clause" ]
null
null
null
restserver_genserver/config/config.exs
arquitecturas-concurrentes/iasc-otp-elixir-2019c2
c8c6c88db978785f439596e0b5f582473b54a35f
[ "BSD-3-Clause" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :clase_otp, key: :value # # And access this configuration in your application as: # # Application.get_env(:clase_otp, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.16129
73
0.752007
1c120d3f20552151ee7a613f28051ad0a3fd80b7
4,164
ex
Elixir
deps/phoenix_html/lib/phoenix_html/form_data.ex
rchervin/phoenixportfolio
a5a6a60168d7261647a10a8dbd395b440db8a4f9
[ "MIT" ]
2
2017-06-08T23:28:13.000Z
2017-06-08T23:28:16.000Z
deps/phoenix_html/lib/phoenix_html/form_data.ex
rchervin/phoenixportfolio
a5a6a60168d7261647a10a8dbd395b440db8a4f9
[ "MIT" ]
null
null
null
deps/phoenix_html/lib/phoenix_html/form_data.ex
rchervin/phoenixportfolio
a5a6a60168d7261647a10a8dbd395b440db8a4f9
[ "MIT" ]
null
null
null
defprotocol Phoenix.HTML.FormData do @moduledoc """ Converts a data structure into a `Phoenix.HTML.Form` struct. """ @doc """ Converts a data structure into a `Phoenix.HTML.Form` struct. The options are the same options given to `form_for/4`. It can be used by implementations to configure their behaviour and it must be stored in the underlying struct, with any custom field removed. """ @spec to_form(t, Keyword.t) :: Phoenix.HTML.Form.t def to_form(data, options) @doc """ Converts the field in the given form based on the data structure into a `Phoenix.HTML.Form` struct. The options are the same options given to `inputs_for/4`. It can be used by implementations to configure their behaviour and it must be stored in the underlying struct, with any custom field removed. """ @spec to_form(t, Phoenix.HTML.Form.t, atom, Keyword.t) :: Phoenix.HTML.Form.t def to_form(data, form, field, options) @doc """ Returns the value for the given field. """ @spec input_value(t, Phoenix.HTML.Form.t, atom) :: term def input_value(data, form, field) @doc """ Returns the HTML5 validations that would apply to the given field. """ @spec input_validations(t, Phoenix.HTML.Form.t, atom) :: Keyword.t def input_validations(data, form, field) @doc """ Receives the given field and returns its input type (:text_input, :select, etc). Returns `nil` if the type is unknown. """ @spec input_type(t, Phoenix.HTML.Form.t, atom) :: atom | nil def input_type(data, form, field) end defimpl Phoenix.HTML.FormData, for: Plug.Conn do def to_form(conn, opts) do {name, opts} = Keyword.pop(opts, :as) name = to_string(name || warn_name(opts) || no_name_error!()) %Phoenix.HTML.Form{ source: conn, impl: __MODULE__, id: name, name: name, params: Map.get(conn.params, name) || %{}, options: opts, data: %{} } end def to_form(conn, form, field, opts) do {default, opts} = Keyword.pop(opts, :default, %{}) {prepend, opts} = Keyword.pop(opts, :prepend, []) {append, opts} = Keyword.pop(opts, :append, []) {name, opts} = Keyword.pop(opts, :as) {id, opts} = Keyword.pop(opts, :id) id = to_string(id || form.id <> "_#{field}") name = to_string(name || warn_name(opts) || form.name <> "[#{field}]") params = Map.get(form.params, Atom.to_string(field)) cond do # cardinality: one is_map(default) -> [%Phoenix.HTML.Form{ source: conn, impl: __MODULE__, id: id, name: name, data: default, params: params || %{}, options: opts}] # cardinality: many is_list(default) -> entries = if params do params |> Enum.sort_by(&elem(&1, 0)) |> Enum.map(&{nil, elem(&1, 1)}) else Enum.map(prepend ++ default ++ append, &{&1, %{}}) end for {{data, params}, index} <- Enum.with_index(entries) do index_string = Integer.to_string(index) %Phoenix.HTML.Form{ source: conn, impl: __MODULE__, index: index, id: id <> "_" <> index_string, name: name <> "[" <> index_string <> "]", data: data, params: params, options: opts} end end end def input_value(_conn, %{data: data, params: params}, field) do case Map.fetch(params, Atom.to_string(field)) do {:ok, value} -> value :error -> Map.get(data, field) end end def input_type(_conn, _form, _field), do: :text_input def input_validations(_conn, _form, _field), do: [] defp no_name_error! do raise ArgumentError, "form_for/4 expects [as: NAME] to be given as option " <> "when used with @conn" end defp warn_name(opts) do if name = Keyword.get(opts, :name) do IO.write :stderr, "the :name option in form_for/inputs_for is deprecated, " <> "please use :as instead\n" <> Exception.format_stacktrace() name end end end
29.742857
84
0.597022
1c1216277b2450a62d719b5df9a7c4b69a2e6b1a
3,396
exs
Elixir
test/phoenix/endpoint/supervisor_test.exs
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
18,092
2015-01-01T01:51:04.000Z
2022-03-31T19:37:14.000Z
test/phoenix/endpoint/supervisor_test.exs
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,905
2015-01-01T00:22:47.000Z
2022-03-31T17:06:21.000Z
test/phoenix/endpoint/supervisor_test.exs
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,205
2015-01-03T10:58:22.000Z
2022-03-30T14:55:57.000Z
defmodule Phoenix.Endpoint.SupervisorTest do use ExUnit.Case, async: true alias Phoenix.Endpoint.Supervisor setup do Application.put_env(:phoenix, SupervisorApp.Endpoint, custom: true) System.put_env("PHOENIX_PORT", "8080") System.put_env("PHOENIX_HOST", "example.org") :ok end test "loads router configuration" do config = Supervisor.config(:phoenix, SupervisorApp.Endpoint) assert config[:otp_app] == :phoenix assert config[:custom] == true assert config[:render_errors] == [view: SupervisorApp.ErrorView, accepts: ~w(html), layout: false] end defmodule HTTPSEndpoint do def path(path), do: path def config(:http), do: false def config(:https), do: [port: 443] def config(:url), do: [host: "example.com"] def config(:otp_app), do: :phoenix end defmodule HTTPEndpoint do def path(path), do: path def config(:https), do: false def config(:http), do: [port: 80] def config(:url), do: [host: "example.com"] def config(:otp_app), do: :phoenix end defmodule HTTPEnvVarEndpoint do def config(:https), do: false def config(:http), do: [port: {:system,"PHOENIX_PORT"}] def config(:url), do: [host: {:system,"PHOENIX_HOST"}] def config(:otp_app), do: :phoenix end defmodule URLEndpoint do def config(:https), do: false def config(:http), do: false def config(:url), do: [host: "example.com", port: 678, scheme: "random"] def config(:static_url), do: nil end defmodule StaticURLEndpoint do def config(:https), do: false def config(:http), do: false def config(:static_url), do: [host: "static.example.com"] end defmodule ForceSslEndpoint do def init(:supervisor, config), do: {:ok, config} def __compile_config__(), do: [force_ssl: [rewrite_on: [:x_forwarded_proto]]] end test "generates the static url based on the static host configuration" do static_host = {:cache, "http://static.example.com"} assert Supervisor.static_url(StaticURLEndpoint) == static_host end test "static url fallbacks to url when there is no configuration for static_url" do assert Supervisor.static_url(URLEndpoint) == {:cache, "random://example.com:678"} end test "generates url" do assert Supervisor.url(URLEndpoint) == {:cache, "random://example.com:678"} assert Supervisor.url(HTTPEndpoint) == {:cache, "http://example.com"} assert Supervisor.url(HTTPSEndpoint) == {:cache, "https://example.com"} assert Supervisor.url(HTTPEnvVarEndpoint) == {:cache, "http://example.org:8080"} end test "static_path/2 returns file's path with lookup cache" do assert {:nocache, {"/phoenix.png", nil}} = Supervisor.static_lookup(HTTPEndpoint, "/phoenix.png") assert {:nocache, {"/images/unknown.png", nil}} = Supervisor.static_lookup(HTTPEndpoint, "/images/unknown.png") end test "compile_config_keys/0 returns config keys we want to store for runtime checks" do assert Supervisor.compile_config_keys() == [:force_ssl] end @tag :capture_log test "init/1 fails when force_ssl check fails" do Application.put_env(:phoenix, ForceSslEndpoint, force_ssl: [hsts: true]) assert_raise ArgumentError, "expected these options to be unchanged from compile time: [:force_ssl]", fn -> Supervisor.init({:phoenix, ForceSslEndpoint, []}) end end end
35.375
102
0.682568
1c123c82b90231f2f3ff9cf46a4329e6a3c184cb
83
ex
Elixir
integration_test/wallaby_example_app/lib/wallaby_example_app_web/views/layout_view.ex
elitau/tix
2aa5fe4d91e7962ebcdc9b668aacf65e09ff9bb8
[ "MIT" ]
1
2021-08-16T18:52:45.000Z
2021-08-16T18:52:45.000Z
integration_test/wallaby_example_app/lib/wallaby_example_app_web/views/layout_view.ex
elitau/tix
2aa5fe4d91e7962ebcdc9b668aacf65e09ff9bb8
[ "MIT" ]
16
2021-03-09T19:39:31.000Z
2022-03-15T15:20:24.000Z
integration_test/wallaby_example_app/lib/wallaby_example_app_web/views/layout_view.ex
elitau/tix
2aa5fe4d91e7962ebcdc9b668aacf65e09ff9bb8
[ "MIT" ]
null
null
null
defmodule WallabyExampleAppWeb.LayoutView do use WallabyExampleAppWeb, :view end
20.75
44
0.855422
1c126bbc398455aed6b0e1564a6bb5308f3cd4b3
295
exs
Elixir
test/mix/tasks/terminator_test.exs
adrianplavka/terminator
794a58f6f05085159e85da7468a091e07d49a98b
[ "MIT" ]
54
2019-01-05T02:07:22.000Z
2022-02-14T22:14:45.000Z
test/mix/tasks/terminator_test.exs
adrianplavka/terminator
794a58f6f05085159e85da7468a091e07d49a98b
[ "MIT" ]
3
2019-07-02T11:23:50.000Z
2021-12-16T13:07:55.000Z
test/mix/tasks/terminator_test.exs
adrianplavka/terminator
794a58f6f05085159e85da7468a091e07d49a98b
[ "MIT" ]
10
2019-02-15T00:24:31.000Z
2022-03-26T11:03:04.000Z
defmodule Mix.Tasks.TerminatorTest do use ExUnit.Case test "provide a list of available terminator mix tasks" do Mix.Tasks.Terminator.run([]) assert_received {:mix_shell, :info, ["Terminator v" <> _]} assert_received {:mix_shell, :info, ["mix terminator.setup" <> _]} end end
29.5
70
0.701695
1c126be62a0ea4ea1bd17479778536c93d6de4af
1,186
ex
Elixir
lib/hunter/report.ex
4DA/hunter
0264d40bc8d3a23f81b7976b636c0726934dac60
[ "Apache-2.0" ]
38
2017-04-09T16:43:58.000Z
2021-10-30T00:47:41.000Z
lib/hunter/report.ex
4DA/hunter
0264d40bc8d3a23f81b7976b636c0726934dac60
[ "Apache-2.0" ]
51
2017-04-14T13:02:42.000Z
2022-02-28T11:16:44.000Z
lib/hunter/report.ex
4DA/hunter
0264d40bc8d3a23f81b7976b636c0726934dac60
[ "Apache-2.0" ]
8
2017-04-14T12:45:18.000Z
2020-09-04T23:08:30.000Z
defmodule Hunter.Report do @moduledoc """ Report entity This module defines a `Hunter.Report` struct and the main functions for working with Reports. ## Fields * `id` - id of the report * `action_taken` - action taken in response to the report """ alias Hunter.Config @type t :: %__MODULE__{ id: non_neg_integer, action_taken: String.t() } @derive [Poison.Encoder] defstruct [:id, :action_taken] @doc """ Retrieve a user's reports ## Parameters * `conn` - connection credentials """ @spec reports(Hunter.Client.t()) :: [Hunter.Report.t()] def reports(conn) do Config.hunter_api().reports(conn) end @doc """ Report a user ## Parameters * `conn` - connection credentials * `account_id` - the ID of the account to report * `status_ids` - the IDs of statuses to report * `comment` - a comment to associate with the report """ @spec report(Hunter.Client.t(), non_neg_integer, [non_neg_integer], String.t()) :: Hunter.Report.t() def report(conn, account_id, status_ids, comment) do Config.hunter_api().report(conn, account_id, status_ids, comment) end end
21.962963
84
0.647555
1c1292180e9a955d2498dea0bd9752ee08615591
178
ex
Elixir
web/router.ex
cdale77/bart_scrape
8696b303f1111a29cfdbea80f15823da3ea5747d
[ "MIT" ]
null
null
null
web/router.ex
cdale77/bart_scrape
8696b303f1111a29cfdbea80f15823da3ea5747d
[ "MIT" ]
null
null
null
web/router.ex
cdale77/bart_scrape
8696b303f1111a29cfdbea80f15823da3ea5747d
[ "MIT" ]
null
null
null
defmodule BartScrape.Router do use BartScrape.Web, :router pipeline :api do plug :accepts, ["json"] end scope "/api", BartScrape do pipe_through :api end end
14.833333
30
0.679775
1c12c0dfb4191bc30df1018804301397f3939fdd
2,637
exs
Elixir
test/mix/tasks/phoenix/pow.phoenix.gen.templates_test.exs
abartier/pow
58a3d082da093e2dc7f07825a950ee133204813f
[ "Unlicense", "MIT" ]
null
null
null
test/mix/tasks/phoenix/pow.phoenix.gen.templates_test.exs
abartier/pow
58a3d082da093e2dc7f07825a950ee133204813f
[ "Unlicense", "MIT" ]
null
null
null
test/mix/tasks/phoenix/pow.phoenix.gen.templates_test.exs
abartier/pow
58a3d082da093e2dc7f07825a950ee133204813f
[ "Unlicense", "MIT" ]
null
null
null
defmodule Mix.Tasks.Pow.Phoenix.Gen.TemplatesTest do use Pow.Test.Mix.TestCase alias Mix.Tasks.Pow.Phoenix.Gen.Templates @tmp_path Path.join(["tmp", inspect(Templates)]) @expected_template_files %{ "registration" => ["edit.html.eex", "new.html.eex"], "session" => ["new.html.eex"] } @expected_views @expected_template_files |> Map.keys() setup do File.rm_rf!(@tmp_path) File.mkdir_p!(@tmp_path) :ok end test "generates templates" do File.cd!(@tmp_path, fn -> Templates.run([]) templates_path = Path.join(["lib", "pow_web", "templates", "pow"]) expected_dirs = Map.keys(@expected_template_files) assert ls(templates_path) == expected_dirs for {dir, expected_files} <- @expected_template_files do files = templates_path |> Path.join(dir) |> ls() assert files == expected_files end views_path = Path.join(["lib", "pow_web", "views", "pow"]) expected_view_files = Enum.map(@expected_views, &"#{&1}_view.ex") view_content = views_path |> Path.join("session_view.ex") |> File.read!() assert ls(views_path) == expected_view_files assert view_content =~ "defmodule PowWeb.Pow.SessionView do" assert view_content =~ "use PowWeb, :view" for _ <- 1..5, do: assert_received({:mix_shell, :info, [_msg]}) assert_received {:mix_shell, :info, [msg]} assert msg =~ "defmodule PowWeb.Endpoint" assert msg =~ "otp_app: :pow" assert msg =~ "repo: Pow.Repo" assert msg =~ "user: Pow.Users.User" assert msg =~ "web_module: PowWeb" end) end test "generates with `:context_app`" do options = ~w(--context-app test) File.cd!(@tmp_path, fn -> Templates.run(options) templates_path = Path.join(["lib", "test_web", "templates", "pow"]) dirs = templates_path |> File.ls!() |> Enum.sort() assert dirs == Map.keys(@expected_template_files) views_path = Path.join(["lib", "test_web", "views", "pow"]) view_content = views_path |> Path.join("session_view.ex") |> File.read!() assert view_content =~ "defmodule TestWeb.Pow.SessionView do" assert view_content =~ "use TestWeb, :view" for _ <- 1..5, do: assert_received({:mix_shell, :info, [_msg]}) assert_received {:mix_shell, :info, [msg]} assert msg =~ "defmodule TestWeb.Endpoint" assert msg =~ "otp_app: :test" assert msg =~ "repo: Test.Repo" assert msg =~ "user: Test.Users.User" assert msg =~ "web_module: TestWeb" end) end defp ls(path), do: path |> File.ls!() |> Enum.sort() end
32.158537
86
0.622677
1c12ccace9080ab0acd87d6e98e1246f1bee4fef
1,924
exs
Elixir
test/request_test.exs
pfitz/bahn_ex
4948e9107a37d4ee3027226578b958059a88524c
[ "MIT" ]
null
null
null
test/request_test.exs
pfitz/bahn_ex
4948e9107a37d4ee3027226578b958059a88524c
[ "MIT" ]
null
null
null
test/request_test.exs
pfitz/bahn_ex
4948e9107a37d4ee3027226578b958059a88524c
[ "MIT" ]
null
null
null
defmodule BahnEx.RequestTest do use ExUnit.Case, async: false import Mock alias BahnEx.{Config, Request} @header %{"Authorization" => "Bearer #{Config.get_api_key()}", "Accept" => "Application/json; Charset=utf-8"} test "location request is getting called with the right url" do with_mock HTTPoison, [get: fn (_url, _header) -> "<html></html>" end] do _response = Request.location("test") assert called HTTPoison.get("https://api.deutschebahn.com/fahrplan-plus/v1/location/test", @header) end end test "arrival board is getting called with the correct url" do with_mock HTTPoison, [get: fn (_url, _header, _date) -> "<html></html>" end] do _response = Request.arrival_board(8000096, "2017-08-20T10:30:00Z") assert called HTTPoison.get( "https://api.deutschebahn.com/fahrplan-plus/v1/arrivalBoard/8000096", @header, params: %{ date: "2017-08-20T10:30:00Z" } ) end end test "departure board is getting called with the correct url" do with_mock HTTPoison, [get: fn (_url, _header, _date) -> "<html></html>" end] do _response = Request.departure_board(8000096, "2017-08-20T10:30:00Z") assert called HTTPoison.get( "https://api.deutschebahn.com/fahrplan-plus/v1/departureBoard/8000096", @header, params: %{ date: "2017-08-20T10:30:00Z" } ) end end test "journey details request is getting called with the right url" do with_mock HTTPoison, [get: fn (_url, _header) -> "<html></html>" end] do _response = Request.journey_details("test") assert called HTTPoison.get("https://api.deutschebahn.com/fahrplan-plus/v1/journeyDetails/test", @header) end end end
38.48
111
0.599272
1c12e54232fa6a4841e2fe056c926f2e373def00
3,888
exs
Elixir
test/acceptances/elastic_search_test.exs
falood/tirexs
9c63532cf2f50f77fb437f617d433741771d3619
[ "Apache-2.0" ]
null
null
null
test/acceptances/elastic_search_test.exs
falood/tirexs
9c63532cf2f50f77fb437f617d433741771d3619
[ "Apache-2.0" ]
null
null
null
test/acceptances/elastic_search_test.exs
falood/tirexs
9c63532cf2f50f77fb437f617d433741771d3619
[ "Apache-2.0" ]
null
null
null
Code.require_file "../../test_helper.exs", __ENV__.file defmodule Acceptances.ElasticSearchTest do use ExUnit.Case import Tirexs.Mapping, only: :macros import Tirexs.Bulk import Tirexs.ElasticSearch require Tirexs.ElasticSearch require Tirexs.Query import Tirexs.Search test :get_elastic_search_server do settings = Tirexs.ElasticSearch.config() {:error, _, _} = get("missing_index", settings) {:ok, _, body} = get("", settings) assert body[:tagline] == "You Know, for Search" end test :create_index do settings = Tirexs.ElasticSearch.config() delete("bear_test", settings) {:ok, _, body} = put("bear_test", settings) assert body[:acknowledged] == true delete("bear_test", settings) end test :delete_index do settings = Tirexs.ElasticSearch.config() put("bear_test", settings) {:ok, _, body} = delete("bear_test", settings) assert body[:acknowledged] == true end test :head do settings = Tirexs.ElasticSearch.config() delete("bear_test", settings) assert exist?("bear_test", settings) == false put("bear_test", settings) assert exist?("bear_test", settings) == true delete("bear_test", settings) end test :create_type_mapping do settings = Tirexs.ElasticSearch.config() index = [index: "bear_test", type: "bear_type"] mappings do indexes "mn_opts_", [type: "object"] do indexes "uk", [type: "object"] do indexes "credentials", [type: "object"] do indexes "available_from", type: "long" indexes "buy", type: "object" indexes "dld", type: "object" indexes "str", type: "object" indexes "t2p", type: "object" indexes "sby", type: "object" indexes "spl", type: "object" indexes "spd", type: "object" indexes "pre", type: "object" indexes "fst", type: "object" end end end indexes "rev_history_", type: "object" end {:ok, _, body} = Tirexs.Mapping.create_resource(index, settings) assert body[:acknowledged] == true delete("bear_test", settings) end test :create_mapping_search do settings = Tirexs.ElasticSearch.config() delete("articles", settings) index = [index: "articles", type: "article"] mappings do indexes "id", type: "string", index: "not_analyzed", include_in_all: false indexes "title", type: "string", boost: 2.0, analyzer: "snowball" indexes "tags", type: "string", analyzer: "keyword" indexes "content", type: "string", analyzer: "snowball" indexes "authors", [type: "object"] do indexes "name", type: "string" indexes "nick_name", type: "string" end end Tirexs.Mapping.create_resource(index, settings) Tirexs.Bulk.store [index: "articles", refresh: true], settings do create id: 1, title: "One", tags: ["elixir"], type: "article" create id: 2, title: "Two", tags: ["elixir", "ruby"], type: "article" create id: 3, title: "Three", tags: ["java"], type: "article" create id: 4, title: "Four", tags: ["erlang"], type: "article" end Tirexs.Manage.refresh("articles", settings) s = search [index: "articles"] do query do query_string "title:T*" end filter do terms "tags", ["elixir", "ruby"] end facets do global_tags [global: true] do terms field: "tags" end current_tags do terms field: "tags" end end sort do [ [title: "desc"] ] end end result = Tirexs.Query.create_resource(s, settings) assert Tirexs.Query.result(result, :count) == 1 assert List.first(Tirexs.Query.result(result, :hits))[:_source][:id] == 2 end end
27.771429
80
0.601852
1c1312c5266b484f5abf63500cd224f27dd60129
5,937
exs
Elixir
server/test/realtime/subscription_manager_test.exs
Omneedia/realtime
90a72170aa1502e211c9f5cbf638c60add6faaf6
[ "Apache-2.0" ]
null
null
null
server/test/realtime/subscription_manager_test.exs
Omneedia/realtime
90a72170aa1502e211c9f5cbf638c60add6faaf6
[ "Apache-2.0" ]
null
null
null
server/test/realtime/subscription_manager_test.exs
Omneedia/realtime
90a72170aa1502e211c9f5cbf638c60add6faaf6
[ "Apache-2.0" ]
null
null
null
defmodule Realtime.SubscriptionManagerTest do use ExUnit.Case import Mock alias Realtime.SubscriptionManager @user_id "bbb51e4e-f371-4463-bf0a-af8f56dc9a71" @user_email "user@test.com" setup_all do start_supervised(Realtime.RLS.Repo) :ok end test "track_topic_subscriber/1" do mess = { :track_topic_subscriber, %{ channel_pid: self(), topic: "test_topic", user_id: @user_id, email: @user_email } } assert :ok == SubscriptionManager.track_topic_subscriber(mess) end test "init/1" do rls_opts = [ subscription_sync_interval: 15_000, replication_mode: "RLS" ] case SubscriptionManager.init(rls_opts) do {:ok, res} -> assert res.replication_mode == "RLS" assert res.sync_interval == 15_000 assert is_reference(res.sync_ref) other -> assert match?({:ok, _}, other) end end test "handle_call/track_topic_subscriber, when subscription_params is empty" do mess = { :track_topic_subscriber, %{ channel_pid: self(), topic: "test_topic", user_id: @user_id, email: @user_email } } state = %{replication_mode: "RLS", subscription_params: %{}} expected = {:reply, :ok, %{ replication_mode: "RLS", subscription_params: %{ self() => %{ entities: [], filters: [], topic: "test_topic", user_id: "bbb51e4e-f371-4463-bf0a-af8f56dc9a71", email: "user@test.com" } } }} assert expected == SubscriptionManager.handle_call(mess, self(), state) end test "handle_call/track_topic_subscriber, when subscription_params is not empty" do {_, bin} = Ecto.UUID.dump(@user_id) mess = { :track_topic_subscriber, %{ channel_pid: self(), topic: "test_topic", user_id: bin, email: @user_email } } state = %{ replication_mode: "RLS", subscription_params: %{ self() => %{ entities: [], filters: [], topic: "test_topic", user_id: bin, email: "user@test.com" } }, sync_interval: 15_000, sync_ref: make_ref() } expected = {:reply, :ok, state} assert expected == SubscriptionManager.handle_call(mess, self(), state) end test "handle_call/track_topic_subscriber, updated state" do {_, bin} = Ecto.UUID.dump(@user_id) mess = { :track_topic_subscriber, %{ channel_pid: self(), topic: "test_topic", user_id: bin, email: @user_email } } prev_sub = %{ entities: [16537], filters: [], topic: "public:todos", user_id: bin, email: @user_email } state = %{ replication_mode: "RLS", subscription_params: %{ some_prev_pid: prev_sub }, sync_interval: 15_000, sync_ref: make_ref() } case SubscriptionManager.handle_call(mess, self(), state) do {:reply, :ok, %{subscription_params: sub_param} = new_state} -> assert new_state.replication_mode == "RLS" assert new_state.sync_interval == 15_000 assert is_reference(new_state.sync_ref) assert sub_param.some_prev_pid == prev_sub assert sub_param[self()] == %{ entities: [], filters: [], topic: "test_topic", user_id: bin, email: @user_email } other -> assert match?({:reply, :ok, _}, other) end end test "handle_info/sync_subscription, recheck" do ref = make_ref() state = %{sync_ref: ref, sync_interval: 15_000, subscription_params: %{}} case SubscriptionManager.handle_info(:sync_subscription, state) do {:noreply, new_state} -> assert new_state.subscription_params == %{} assert new_state.sync_interval == 15_000 assert new_state.sync_ref != ref assert is_reference(new_state.sync_ref) other -> assert match?({:noreply, _}, other) end end test "handle_info/sync_subscription, when subscription_params is list" do state = %{sync_ref: make_ref(), sync_interval: 15_000, subscription_params: []} res = SubscriptionManager.handle_info(:sync_subscription, state) assert match?({:noreply, _}, res) end test "handle_info/sync_subscription, when subscription_params is empty" do msg = {:DOWN, make_ref(), :process, self(), :any} state = %{subscription_params: %{}} expected = {:noreply, state} assert expected == SubscriptionManager.handle_info(msg, state) end test "handle_info/sync_subscription, when subscription_params is not empty" do msg = {:DOWN, make_ref(), :process, self(), :any} {_, bin} = Ecto.UUID.dump(@user_id) state = %{ subscription_params: %{ self() => %{ entities: [], filters: [], topic: "public:todos", user_id: bin, email: @user_email } } } expected = {:noreply, %{subscription_params: %{}}} assert expected == SubscriptionManager.handle_info(msg, state) end test "handle_info, error in Subscriptions.delete_topic_subscriber" do with_mock Realtime.RLS.Subscriptions, delete_topic_subscriber: fn _ -> raise "" end do msg = {:DOWN, make_ref(), :process, self(), :any} {_, bin} = Ecto.UUID.dump(@user_id) state = %{ subscription_params: %{ self() => %{ entities: [], filters: [], topic: "public:todos", user_id: bin, email: @user_email } } } expected = {:noreply, %{subscription_params: %{}}} assert expected == SubscriptionManager.handle_info(msg, state) end end end
25.590517
85
0.580765
1c13402b7a4212f8c02cc4faa3a7521ad430e085
73
ex
Elixir
lib/yourbot_web/views/user_registration_view.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
3
2021-11-08T15:19:19.000Z
2021-11-11T03:18:35.000Z
lib/yourbot_web/views/user_registration_view.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
lib/yourbot_web/views/user_registration_view.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
defmodule YourBotWeb.UserRegistrationView do use YourBotWeb, :view end
18.25
44
0.835616
1c136316c068536697854c2470a8e23291386ec2
576
exs
Elixir
test/controllers/post_controller_test.exs
synion/tilex
ea29646830efaa89fc47fad347f6e495ff7ce48b
[ "MIT" ]
1
2019-05-28T20:43:28.000Z
2019-05-28T20:43:28.000Z
test/controllers/post_controller_test.exs
synion/tilex
ea29646830efaa89fc47fad347f6e495ff7ce48b
[ "MIT" ]
1
2019-02-11T23:14:15.000Z
2019-02-11T23:14:15.000Z
test/controllers/post_controller_test.exs
synion/tilex
ea29646830efaa89fc47fad347f6e495ff7ce48b
[ "MIT" ]
1
2019-12-02T08:59:45.000Z
2019-12-02T08:59:45.000Z
defmodule Tilex.PostControllerTest do use TilexWeb.ConnCase test "lists all entries on index", %{conn: conn} do conn = get(conn, post_path(conn, :index)) assert html_response(conn, 200) =~ "Today I Learned" end test "redirects to root when non-developer visits posts/new path", %{conn: conn} do conn = get(conn, post_path(conn, :new)) assert html_response(conn, 302) end test "throws 404 with slug less than 10 characters", %{conn: conn} do conn = get(conn, post_path(conn, :edit, "123456789")) assert html_response(conn, 404) end end
30.315789
85
0.692708
1c136f37fe522617fc1756af20a148f2b4e63a16
2,839
ex
Elixir
lib/ash/resource/validation/present.ex
kyle5794/ash
82023da84400366d07001593673d1aaa2a418803
[ "MIT" ]
null
null
null
lib/ash/resource/validation/present.ex
kyle5794/ash
82023da84400366d07001593673d1aaa2a418803
[ "MIT" ]
null
null
null
lib/ash/resource/validation/present.ex
kyle5794/ash
82023da84400366d07001593673d1aaa2a418803
[ "MIT" ]
null
null
null
defmodule Ash.Resource.Validation.Present do @moduledoc false alias Ash.Error.Changes.{InvalidAttribute, InvalidChanges} @behaviour Ash.Resource.Validation @opt_schema [ at_least: [ type: :non_neg_integer, doc: "At least this many must be present. Defaults to the number of attributes provided" ], at_most: [ type: :non_neg_integer, doc: "At most this many must be present. Defaults to the number of attributes provided" ], exactly: [ type: :non_neg_integer, doc: "Exactly this many must be present" ], attributes: [ type: {:custom, __MODULE__, :attributes, []}, required: true, doc: "The attributes that the configured amount of must be present" ] ] @doc false def schema, do: @opt_schema @impl true def init(opts) do case NimbleOptions.validate(opts, @opt_schema) do {:ok, opts} -> {:ok, opts} {:error, error} -> {:error, Exception.message(error)} end end @impl true def validate(changeset, opts) do {present, count} = Enum.reduce(opts[:attributes], {0, 0}, fn attribute, {present, count} -> if is_nil(Ash.Changeset.get_attribute(changeset, attribute)) do {present, count + 1} else {present + 1, count + 1} end end) cond do opts[:exactly] && present != opts[:exactly] -> if opts[:exactly] == 0 do changes_error(opts, count, "must be absent") else if count == 1 do attribute_error(opts, count, "must be present") else attribute_error(opts, count, {"exactly %{exactly} must be present", opts}) end end opts[:at_least] && present < opts[:at_least] -> if count == 1 do attribute_error(opts, count, "must be present") else changes_error(opts, count, {"at least %{at_least} must be present", opts}) end opts[:at_most] && present > opts[:at_most] -> if count == 1 do attribute_error(opts, count, "must not be present") else changes_error(opts, count, {"at least %{at_most} must be present", opts}) end true -> :ok end end defp changes_error(opts, _count, message) do {:error, InvalidChanges.exception( fields: opts[:attributes], message: message )} end defp attribute_error(opts, _count, message) do {:error, InvalidAttribute.exception( field: List.first(opts[:attributes]), message: message )} end @doc false def attributes(attributes) do attributes = List.wrap(attributes) if Enum.all?(attributes, &is_atom/1) do {:ok, attributes} else {:error, "Expected all attributes provided to be atoms."} end end end
25.809091
94
0.595632
1c13aee94a154b7b4620283c2d51ce76420268a3
1,266
exs
Elixir
payment_api/config/prod.secret.exs
dennisurtubia/elixir-phoenix
964c6f708e9491e31aafb927a303eec647c03062
[ "MIT" ]
null
null
null
payment_api/config/prod.secret.exs
dennisurtubia/elixir-phoenix
964c6f708e9491e31aafb927a303eec647c03062
[ "MIT" ]
null
null
null
payment_api/config/prod.secret.exs
dennisurtubia/elixir-phoenix
964c6f708e9491e31aafb927a303eec647c03062
[ "MIT" ]
null
null
null
# In this file, we load production configuration and secrets # from environment variables. You can also hardcode secrets, # although such is generally not recommended and you have to # remember to add this file to your .gitignore. use Mix.Config database_url = System.get_env("DATABASE_URL") || raise """ environment variable DATABASE_URL is missing. For example: ecto://USER:PASS@HOST/DATABASE """ config :payment_api, PaymentApi.Repo, # ssl: true, url: database_url, pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10") secret_key_base = System.get_env("SECRET_KEY_BASE") || raise """ environment variable SECRET_KEY_BASE is missing. You can generate one by calling: mix phx.gen.secret """ config :payment_api, PaymentApiWeb.Endpoint, http: [ port: String.to_integer(System.get_env("PORT") || "4000"), transport_options: [socket_opts: [:inet6]] ], secret_key_base: secret_key_base # ## Using releases (Elixir v1.9+) # # If you are doing OTP releases, you need to instruct Phoenix # to start each relevant endpoint: # # config :payment_api, PaymentApiWeb.Endpoint, server: true # # Then you can assemble a release by calling `mix release`. # See `mix help release` for more information.
30.142857
67
0.723539
1c13c8d0ceea53cbaa6af258d933993728df96fd
880
ex
Elixir
clients/logging/lib/google_api/logging/v2/metadata.ex
richiboi1977/elixir-google-api
c495bb3548090eb7a63d12f6fb145ec48aecdc0b
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/logging/lib/google_api/logging/v2/metadata.ex
richiboi1977/elixir-google-api
c495bb3548090eb7a63d12f6fb145ec48aecdc0b
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/metadata.ex
richiboi1977/elixir-google-api
c495bb3548090eb7a63d12f6fb145ec48aecdc0b
[ "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.Logging.V2 do @moduledoc """ API client metadata for GoogleApi.Logging.V2. """ @discovery_revision "20210726" def discovery_revision(), do: @discovery_revision end
32.592593
74
0.757955
1c13e6a076159906db8bc291a4f740503bea063a
2,462
ex
Elixir
clients/content/lib/google_api/content/v2/model/unit_invoice.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/unit_invoice.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/unit_invoice.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.UnitInvoice do @moduledoc """ ## Attributes * `additionalCharges` (*type:* `list(GoogleApi.Content.V2.Model.UnitInvoiceAdditionalCharge.t)`, *default:* `nil`) - Additional charges for a unit, e.g. shipping costs. * `promotions` (*type:* `list(GoogleApi.Content.V2.Model.Promotion.t)`, *default:* `nil`) - Deprecated. * `unitPricePretax` (*type:* `GoogleApi.Content.V2.Model.Price.t`, *default:* `nil`) - [required] Price of the unit, before applying taxes. * `unitPriceTaxes` (*type:* `list(GoogleApi.Content.V2.Model.UnitInvoiceTaxLine.t)`, *default:* `nil`) - Tax amounts to apply to the unit price. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :additionalCharges => list(GoogleApi.Content.V2.Model.UnitInvoiceAdditionalCharge.t()), :promotions => list(GoogleApi.Content.V2.Model.Promotion.t()), :unitPricePretax => GoogleApi.Content.V2.Model.Price.t(), :unitPriceTaxes => list(GoogleApi.Content.V2.Model.UnitInvoiceTaxLine.t()) } field( :additionalCharges, as: GoogleApi.Content.V2.Model.UnitInvoiceAdditionalCharge, type: :list ) field(:promotions, as: GoogleApi.Content.V2.Model.Promotion, type: :list) field(:unitPricePretax, as: GoogleApi.Content.V2.Model.Price) field(:unitPriceTaxes, as: GoogleApi.Content.V2.Model.UnitInvoiceTaxLine, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.UnitInvoice do def decode(value, options) do GoogleApi.Content.V2.Model.UnitInvoice.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.UnitInvoice do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.360656
172
0.728676
1c14031b8c366d5e1d2930749a1189896f088335
1,589
ex
Elixir
apps/web_api/lib/web_api_web.ex
vapordao/staxx
5110167573e67a91c0865c3265896642ebe4012e
[ "Apache-2.0" ]
null
null
null
apps/web_api/lib/web_api_web.ex
vapordao/staxx
5110167573e67a91c0865c3265896642ebe4012e
[ "Apache-2.0" ]
null
null
null
apps/web_api/lib/web_api_web.ex
vapordao/staxx
5110167573e67a91c0865c3265896642ebe4012e
[ "Apache-2.0" ]
null
null
null
defmodule Staxx.WebApiWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use WebApiWeb, :controller use WebApiWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: WebApiWeb import Plug.Conn import Staxx.WebApiWeb.Gettext alias Staxx.WebApiWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/web_api_web/templates", namespace: Staxx.WebApiWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] import Staxx.WebApiWeb.ErrorHelpers import Staxx.WebApiWeb.Gettext alias Staxx.WebApiWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import Staxx.WebApiWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
23.716418
83
0.694147
1c1421d9aeef0d34e18f7bc3756be2b0cf879098
1,054
ex
Elixir
test/support/conn_case.ex
erwald/hangman
38c8b6cc45bb3bf9f44d6fe5d33714b40dd78d26
[ "MIT" ]
1
2016-06-28T10:48:46.000Z
2016-06-28T10:48:46.000Z
test/support/conn_case.ex
erwald/hangman
38c8b6cc45bb3bf9f44d6fe5d33714b40dd78d26
[ "MIT" ]
null
null
null
test/support/conn_case.ex
erwald/hangman
38c8b6cc45bb3bf9f44d6fe5d33714b40dd78d26
[ "MIT" ]
null
null
null
defmodule Hangman.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias Hangman.Repo import Ecto import Ecto.Changeset import Ecto.Query, only: [from: 1, from: 2] import Hangman.Router.Helpers # The default endpoint for testing @endpoint Hangman.Endpoint end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(Hangman.Repo, []) end {:ok, conn: Phoenix.ConnTest.conn()} end end
24.511628
66
0.703036
1c1443612c7e776b28743512dd7de5c4d5b3529e
1,896
ex
Elixir
lib/upvest/clientele/wallet.ex
upvestco/upvest-elixir
4c04e6428e5795b7be88af8e516e604d4ff7009a
[ "MIT" ]
null
null
null
lib/upvest/clientele/wallet.ex
upvestco/upvest-elixir
4c04e6428e5795b7be88af8e516e604d4ff7009a
[ "MIT" ]
6
2019-09-09T00:47:30.000Z
2019-10-23T14:45:13.000Z
lib/upvest/clientele/wallet.ex
upvestco/upvest-elixir
4c04e6428e5795b7be88af8e516e604d4ff7009a
[ "MIT" ]
1
2019-09-16T13:08:06.000Z
2019-09-16T13:08:06.000Z
defmodule Upvest.Clientele.Wallet do @moduledoc """ Handles operations related to Wallet You can: - Retrieve wallet - List all wallets - List specific number of wallets For more details see `https://doc.upvest.co/reference#kms_wallet_list` """ use Upvest.API, [:all, :retrieve, :list] alias Upvest.Clientele.Wallet.Signature defstruct [:address, :balances, :id, :index, :protocol, :status] def endpoint do "/kms/wallets/" end @doc """ Create a new wallet. The password is necessary to decrypt the Seed data to create the private key for the new wallet, and then to encrypt the new private key. """ @spec create(Client.t(), binary, binary, non_neg_integer(), atom()) :: Upvest.response() def create(client, password, asset_id, index \\ 0, type \\ :encrypted) do params = %{asset_id: asset_id, password: password, index: index, type: type} with {:ok, resp} <- request(:post, endpoint(), params, client) do {:ok, to_struct(resp, Wallet)} end end @doc """ Sign (the hash of) data with the private key corresponding to this wallet. """ @spec sign(Client.t(), binary, binary, binary(), binary(), binary()) :: Upvest.response() def sign(client, password, wallet_id, to_sign, input_format, output_format) do url = "#{endpoint()}#{wallet_id}/sign" params = %{ wallet_id: wallet_id, to_sign: to_sign, password: password, input_format: input_format, output_format: output_format } with {:ok, resp} <- request(:post, url, params, client) do {:ok, to_struct(resp, Signature)} end end end defmodule Upvest.Clientele.Wallet.Signature do @moduledoc """ Signature represents the signed wallet signature For more details, see `https://doc.upvest.co/reference#kms_sign` """ defstruct [:big_number_format, :algorithm, :curve, :public_key, :r, :s, :recover] end
29.169231
99
0.67616
1c144dd0375ce8b50dbe34fbc585caa3b472755e
14,476
ex
Elixir
samples/Elixir/regex.ex
davidhq/linguist
59c94ff0bf027e09f59ad312428aaa3ed3624ff7
[ "MIT" ]
1
2019-10-24T03:37:34.000Z
2019-10-24T03:37:34.000Z
samples/Elixir/regex.ex
davidhq/linguist
59c94ff0bf027e09f59ad312428aaa3ed3624ff7
[ "MIT" ]
4
2021-12-12T01:26:16.000Z
2021-12-15T14:07:11.000Z
samples/Elixir/regex.ex
davidhq/linguist
59c94ff0bf027e09f59ad312428aaa3ed3624ff7
[ "MIT" ]
null
null
null
defmodule Regex do @moduledoc ~S""" Provides regular expressions for Elixir. """ defstruct re_pattern: nil, source: "", opts: "", re_version: "" @type t :: %__MODULE__{re_pattern: term, source: binary, opts: binary} defmodule CompileError do defexception message: "regex could not be compiled" end @doc """ Compiles the regular expression. """ @spec compile(binary, binary | [term]) :: {:ok, t} | {:error, any} def compile(source, options \\ "") when is_binary(source) do compile(source, options, version()) end defp compile(source, options, version) when is_binary(options) do case translate_options(options, []) do {:error, rest} -> {:error, {:invalid_option, rest}} translated_options -> compile(source, translated_options, options, version) end end defp compile(source, options, version) when is_list(options) do compile(source, options, "", version) end defp compile(source, opts, doc_opts, version) do case :re.compile(source, opts) do {:ok, re_pattern} -> {:ok, %Regex{re_pattern: re_pattern, re_version: version, source: source, opts: doc_opts}} error -> error end end @doc """ Compiles the regular expression and raises `Regex.CompileError` in case of errors. """ @spec compile!(binary, binary | [term]) :: t def compile!(source, options \\ "") when is_binary(source) do case compile(source, options) do {:ok, regex} -> regex {:error, {reason, at}} -> raise Regex.CompileError, "#{reason} at position #{at}" end end @doc """ Recompiles the existing regular expression if necessary. """ @doc since: "1.4.0" @spec recompile(t) :: {:ok, t} | {:error, any} def recompile(%Regex{} = regex) do version = version() case regex do %{re_version: ^version} -> {:ok, regex} _ -> %{source: source, opts: opts} = regex compile(source, opts, version) end end @doc """ Recompiles the existing regular expression and raises `Regex.CompileError` in case of errors. """ @doc since: "1.4.0" @spec recompile!(t) :: t def recompile!(regex) do case recompile(regex) do {:ok, regex} -> regex {:error, {reason, at}} -> raise Regex.CompileError, "#{reason} at position #{at}" end end @doc """ Returns the version of the underlying Regex engine. """ @doc since: "1.4.0" @spec version :: term() def version do {:re.version(), :erlang.system_info(:endian)} end @doc """ Returns a boolean indicating whether there was a match or not. """ @spec match?(t, String.t()) :: boolean def match?(%Regex{} = regex, string) when is_binary(string) do safe_run(regex, string, [{:capture, :none}]) == :match end @doc """ Returns `true` if the given `term` is a regex. Otherwise returns `false`. """ # TODO: deprecate permanently on Elixir v1.15 @doc deprecated: "Use Kernel.is_struct/2 or pattern match on %Regex{} instead" def regex?(term) def regex?(%Regex{}), do: true def regex?(_), do: false @doc """ Runs the regular expression against the given string until the first match. It returns a list with all captures or `nil` if no match occurred. """ @spec run(t, binary, [term]) :: nil | [binary] | [{integer, integer}] def run(regex, string, options \\ []) def run(%Regex{} = regex, string, options) when is_binary(string) do return = Keyword.get(options, :return, :binary) captures = Keyword.get(options, :capture, :all) offset = Keyword.get(options, :offset, 0) case safe_run(regex, string, [{:capture, captures, return}, {:offset, offset}]) do :nomatch -> nil :match -> [] {:match, results} -> results end end @doc """ Returns the given captures as a map or `nil` if no captures are found. """ @spec named_captures(t, String.t(), [term]) :: map | nil def named_captures(regex, string, options \\ []) when is_binary(string) do names = names(regex) options = Keyword.put(options, :capture, names) results = run(regex, string, options) if results, do: Enum.zip(names, results) |> Enum.into(%{}) end @doc """ Returns the underlying `re_pattern` in the regular expression. """ @spec re_pattern(t) :: term def re_pattern(%Regex{re_pattern: compiled}) do compiled end @doc """ Returns the regex source as a binary. """ @spec source(t) :: String.t() def source(%Regex{source: source}) do source end @doc """ Returns the regex options as a string. """ @spec opts(t) :: String.t() def opts(%Regex{opts: opts}) do opts end @doc """ Returns a list of names in the regex. """ @spec names(t) :: [String.t()] def names(%Regex{re_pattern: compiled, re_version: version, source: source}) do re_pattern = case version() do ^version -> compiled _ -> {:ok, recompiled} = :re.compile(source) recompiled end {:namelist, names} = :re.inspect(re_pattern, :namelist) names end @doc ~S""" Same as `run/3`, but scans the target several times collecting all matches of the regular expression. """ @spec scan(t, String.t(), [term]) :: [[String.t()]] def scan(regex, string, options \\ []) def scan(%Regex{} = regex, string, options) when is_binary(string) do return = Keyword.get(options, :return, :binary) captures = Keyword.get(options, :capture, :all) offset = Keyword.get(options, :offset, 0) options = [{:capture, captures, return}, :global, {:offset, offset}] case safe_run(regex, string, options) do :match -> [] :nomatch -> [] {:match, results} -> results end end defp safe_run( %Regex{re_pattern: compiled, source: source, re_version: version, opts: compile_opts}, string, options ) do case version() do ^version -> :re.run(string, compiled, options) _ -> :re.run(string, source, translate_options(compile_opts, options)) end end @doc """ Splits the given target based on the given pattern and in the given number of parts. """ @spec split(t, String.t(), [term]) :: [String.t()] def split(regex, string, options \\ []) def split(%Regex{}, "", opts) do if Keyword.get(opts, :trim, false) do [] else [""] end end def split(%Regex{} = regex, string, opts) when is_binary(string) and is_list(opts) do on = Keyword.get(opts, :on, :first) case safe_run(regex, string, [:global, capture: on]) do {:match, matches} -> index = parts_to_index(Keyword.get(opts, :parts, :infinity)) trim = Keyword.get(opts, :trim, false) include_captures = Keyword.get(opts, :include_captures, false) do_split(matches, string, 0, index, trim, include_captures) :match -> [string] :nomatch -> [string] end end defp parts_to_index(:infinity), do: 0 defp parts_to_index(n) when is_integer(n) and n > 0, do: n defp do_split(_, string, offset, _counter, true, _with_captures) when byte_size(string) <= offset do [] end defp do_split(_, string, offset, 1, _trim, _with_captures), do: [binary_part(string, offset, byte_size(string) - offset)] defp do_split([], string, offset, _counter, _trim, _with_captures), do: [binary_part(string, offset, byte_size(string) - offset)] defp do_split([[{pos, _} | h] | t], string, offset, counter, trim, with_captures) when pos - offset < 0 do do_split([h | t], string, offset, counter, trim, with_captures) end defp do_split([[] | t], string, offset, counter, trim, with_captures), do: do_split(t, string, offset, counter, trim, with_captures) defp do_split([[{pos, length} | h] | t], string, offset, counter, trim, true) do new_offset = pos + length keep = pos - offset <<_::binary-size(offset), part::binary-size(keep), match::binary-size(length), _::binary>> = string if keep == 0 and trim do [match | do_split([h | t], string, new_offset, counter - 1, trim, true)] else [part, match | do_split([h | t], string, new_offset, counter - 1, trim, true)] end end defp do_split([[{pos, length} | h] | t], string, offset, counter, trim, false) do new_offset = pos + length keep = pos - offset if keep == 0 and trim do do_split([h | t], string, new_offset, counter, trim, false) else <<_::binary-size(offset), part::binary-size(keep), _::binary>> = string [part | do_split([h | t], string, new_offset, counter - 1, trim, false)] end end @doc ~S""" Receives a regex, a binary and a replacement, returns a new binary where all matches are replaced by the replacement. """ @spec replace(t, String.t(), String.t() | (... -> String.t()), [term]) :: String.t() def replace(%Regex{} = regex, string, replacement, options \\ []) when is_binary(string) and is_list(options) do opts = if Keyword.get(options, :global) != false, do: [:global], else: [] opts = [{:capture, :all, :index} | opts] case safe_run(regex, string, opts) do :nomatch -> string {:match, [mlist | t]} when is_list(mlist) -> apply_list(string, precompile_replacement(replacement), [mlist | t]) |> IO.iodata_to_binary() {:match, slist} -> apply_list(string, precompile_replacement(replacement), [slist]) |> IO.iodata_to_binary() end end defp precompile_replacement(replacement) when is_function(replacement) do {:arity, arity} = Function.info(replacement, :arity) {replacement, arity} end defp precompile_replacement(""), do: [] defp precompile_replacement(<<?\\, ?g, ?{, rest::binary>>) when byte_size(rest) > 0 do {ns, <<?}, rest::binary>>} = pick_int(rest) [List.to_integer(ns) | precompile_replacement(rest)] end defp precompile_replacement(<<?\\, ?\\, rest::binary>>) do [<<?\\>> | precompile_replacement(rest)] end defp precompile_replacement(<<?\\, x, rest::binary>>) when x in ?0..?9 do {ns, rest} = pick_int(rest) [List.to_integer([x | ns]) | precompile_replacement(rest)] end defp precompile_replacement(<<x, rest::binary>>) do case precompile_replacement(rest) do [head | t] when is_binary(head) -> [<<x, head::binary>> | t] other -> [<<x>> | other] end end defp pick_int(<<x, rest::binary>>) when x in ?0..?9 do {found, rest} = pick_int(rest) {[x | found], rest} end defp pick_int(bin) do {[], bin} end defp apply_list(string, replacement, list) do apply_list(string, string, 0, replacement, list) end defp apply_list(_, "", _, _, []) do [] end defp apply_list(_, string, _, _, []) do string end defp apply_list(whole, string, pos, replacement, [[{mpos, _} | _] | _] = list) when mpos > pos do length = mpos - pos <<untouched::binary-size(length), rest::binary>> = string [untouched | apply_list(whole, rest, mpos, replacement, list)] end defp apply_list(whole, string, pos, replacement, [[{pos, length} | _] = head | tail]) do <<_::size(length)-binary, rest::binary>> = string new_data = apply_replace(whole, replacement, head) [new_data | apply_list(whole, rest, pos + length, replacement, tail)] end defp apply_replace(string, {fun, arity}, indexes) do apply(fun, get_indexes(string, indexes, arity)) end defp apply_replace(_, [bin], _) when is_binary(bin) do bin end defp apply_replace(string, repl, indexes) do indexes = List.to_tuple(indexes) for part <- repl do cond do is_binary(part) -> part part >= tuple_size(indexes) -> "" true -> get_index(string, elem(indexes, part)) end end end defp get_index(_string, {pos, _length}) when pos < 0 do "" end defp get_index(string, {pos, length}) do <<_::size(pos)-binary, res::size(length)-binary, _::binary>> = string res end defp get_indexes(_string, _, 0) do [] end defp get_indexes(string, [], arity) do ["" | get_indexes(string, [], arity - 1)] end defp get_indexes(string, [h | t], arity) do [get_index(string, h) | get_indexes(string, t, arity - 1)] end @doc ~S""" Escapes a string to be literally matched in a regex. """ @spec escape(String.t()) :: String.t() def escape(string) when is_binary(string) do string |> escape(_length = 0, string) |> IO.iodata_to_binary() end @escapable '.^$*+?()[]{}|#-\\\t\n\v\f\r\s' defp escape(<<char, rest::binary>>, length, original) when char in @escapable do escape_char(rest, length, original, char) end defp escape(<<_, rest::binary>>, length, original) do escape(rest, length + 1, original) end defp escape(<<>>, _length, original) do original end defp escape_char(<<rest::binary>>, 0, _original, char) do [?\\, char | escape(rest, 0, rest)] end defp escape_char(<<rest::binary>>, length, original, char) do [binary_part(original, 0, length), ?\\, char | escape(rest, 0, rest)] end # Helpers @doc false # Unescape map function used by Macro.unescape_string. def unescape_map(?f), do: ?\f def unescape_map(?n), do: ?\n def unescape_map(?r), do: ?\r def unescape_map(?t), do: ?\t def unescape_map(?v), do: ?\v def unescape_map(?a), do: ?\a def unescape_map(_), do: false # Private Helpers defp translate_options(<<?u, t::binary>>, acc), do: translate_options(t, [:unicode, :ucp | acc]) defp translate_options(<<?i, t::binary>>, acc), do: translate_options(t, [:caseless | acc]) defp translate_options(<<?x, t::binary>>, acc), do: translate_options(t, [:extended | acc]) defp translate_options(<<?f, t::binary>>, acc), do: translate_options(t, [:firstline | acc]) defp translate_options(<<?U, t::binary>>, acc), do: translate_options(t, [:ungreedy | acc]) defp translate_options(<<?s, t::binary>>, acc), do: translate_options(t, [:dotall, {:newline, :anycrlf} | acc]) defp translate_options(<<?m, t::binary>>, acc), do: translate_options(t, [:multiline | acc]) defp translate_options(<<?r, t::binary>>, acc) do IO.warn("the /r modifier in regular expressions is deprecated, please use /U instead") translate_options(t, [:ungreedy | acc]) end defp translate_options(<<>>, acc), do: acc defp translate_options(rest, _acc), do: {:error, rest} end
28.952
98
0.622962
1c1452b310b5eb046fdbe9de7313db192a00ed3b
172
ex
Elixir
lib/alumni_book_web/views/link_view.ex
avval-alumni/alumni_book
17b27da849919312a332aaa3b39ce5c65032f2b4
[ "MIT" ]
null
null
null
lib/alumni_book_web/views/link_view.ex
avval-alumni/alumni_book
17b27da849919312a332aaa3b39ce5c65032f2b4
[ "MIT" ]
null
null
null
lib/alumni_book_web/views/link_view.ex
avval-alumni/alumni_book
17b27da849919312a332aaa3b39ce5c65032f2b4
[ "MIT" ]
null
null
null
defmodule AlumniBook.LinkView do @moduledoc false use AlumniBookWeb, :view end defmodule AlumniBookWeb.LinkView do @moduledoc false use AlumniBookWeb, :view end
14.333333
35
0.784884
1c146b21e05c7fd7109b767fa3a45bc3ab017dd2
2,679
ex
Elixir
lib/egghead_scrapper.ex
kerlak/egghead_dl
385aa9cfcfe6138f16a6d7c017f0f5bc06e12a3a
[ "MIT" ]
7
2019-05-28T13:51:15.000Z
2019-08-30T13:33:24.000Z
lib/egghead_scrapper.ex
LordOkami/egghead_dl
385aa9cfcfe6138f16a6d7c017f0f5bc06e12a3a
[ "MIT" ]
null
null
null
lib/egghead_scrapper.ex
LordOkami/egghead_dl
385aa9cfcfe6138f16a6d7c017f0f5bc06e12a3a
[ "MIT" ]
1
2021-08-09T09:22:02.000Z
2021-08-09T09:22:02.000Z
import Algolia defmodule EggheadScrapper do def output_basepath() do "output/" end def output_extension() do ".mp4" end def get_courses(search_filter) do search_options = [ attributesToRetrieve: ["title","url"], # hitsPerPage: 15, hitsPerPage: 1000, page: 0, ] {:ok,results} = "content_production" |> search(search_filter, search_options) results["hits"] |> Enum.map(fn(item) -> %{ title: item["title"] |> String.replace("/", "-"), url: item["url"], lessons: [] } end) |> Enum.filter(fn(course) -> String.contains?(course.url, "/courses/") end) end def get_lessons(course_url) do {"script", _, element} = HTTPoison.get!(course_url, [], [timeout: 60_000, recv_timeout: 60_000]).body |> Floki.find(".js-react-on-rails-component") |> Enum.at(0) Poison.decode!(element)["course"]["course"]["lessons"] |> Enum.map(fn(lesson) -> %{title: lesson["title"] |> String.replace("/", "-"), media_url: lesson["media_urls"]["hls_url"]} end) end def download_courses(search_filter) do courses = get_courses(search_filter) total_courses = Enum.count(courses) courses |> Enum.with_index |> Enum.each(fn({course, index}) -> IO.puts("Start downloading course(" <> Integer.to_string(index + 1) <> "/" <> Integer.to_string(total_courses) <> "): " <> course.title) download(%{course | lessons: get_lessons(course.url)}) end) end def download(course) do total_lessons = Enum.count(course.lessons) folder = gen_folder(course) File.mkdir_p!(folder) course.lessons |> Enum.with_index |> Enum.map(fn({lesson, index}) -> IO.puts("Downloading (" <> Integer.to_string(index + 1) <> "/" <> Integer.to_string(total_lessons) <> "): " <> lesson.title) Task.async(fn -> VideoDownloader.download(lesson.media_url, folder <> get_output_file(lesson, index + 1)) end) end) |> Enum.map(&Task.await(&1, :infinity)) end def gen_folder(course) do output_basepath <> course.title <> "/" end def get_output_file(lesson, index) do padding_index = index |> Integer.to_string |> String.pad_leading(3, "0") padding_index <> "." <> lesson.title <> output_extension end end
31.151163
148
0.533035
1c146b4f69043e358e479abf4e41cd819d6da91c
1,402
ex
Elixir
clients/iam/lib/google_api/iam/v1/model/undelete_role_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/iam/lib/google_api/iam/v1/model/undelete_role_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/iam/lib/google_api/iam/v1/model/undelete_role_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.IAM.V1.Model.UndeleteRoleRequest do @moduledoc """ The request to undelete an existing role. ## Attributes * `etag` (*type:* `String.t`, *default:* `nil`) - Used to perform a consistent read-modify-write. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :etag => String.t() } field(:etag) end defimpl Poison.Decoder, for: GoogleApi.IAM.V1.Model.UndeleteRoleRequest do def decode(value, options) do GoogleApi.IAM.V1.Model.UndeleteRoleRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.IAM.V1.Model.UndeleteRoleRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
29.829787
101
0.733238
1c147a158af1988f6165c0da99293855f9404e35
2,239
exs
Elixir
test/conduit_web/controllers/favorite_article_controller_test.exs
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
null
null
null
test/conduit_web/controllers/favorite_article_controller_test.exs
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
2
2022-01-15T02:09:30.000Z
2022-01-22T10:18:43.000Z
test/conduit_web/controllers/favorite_article_controller_test.exs
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
null
null
null
defmodule ConduitWeb.FavoriteArticleControllerTest do use ConduitWeb.ConnCase setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end describe "favorite article" do setup [ :create_author, :publish_article, :register_user, ] @tag :web test "should be favorited and return article", %{conn: conn, user: user} do conn = post authenticated_conn(conn, user), favorite_article_path(conn, :create, "how-to-train-your-dragon") json = json_response(conn, 201)["article"] created_at = json["createdAt"] updated_at = json["updatedAt"] assert json == %{ "slug" => "how-to-train-your-dragon", "title" => "How to train your dragon", "description" => "Ever wonder how?", "body" => "You have to believe", "tagList" => ["dragons", "training"], "createdAt" => created_at, "updatedAt" => updated_at, "favorited" => true, "favoritesCount" => 1, "author" => %{ "username" => "jake", "bio" => nil, "image" => nil, "following" => false, } } end end describe "unfavorite article" do setup [ :create_author, :publish_article, :register_user, :get_author, :favorite_article, ] @tag :web test "should be unfavorited and return article", %{conn: conn, user: user} do conn = delete authenticated_conn(conn, user), favorite_article_path(conn, :delete, "how-to-train-your-dragon") json = json_response(conn, 201)["article"] created_at = json["createdAt"] updated_at = json["updatedAt"] assert json == %{ "slug" => "how-to-train-your-dragon", "title" => "How to train your dragon", "description" => "Ever wonder how?", "body" => "You have to believe", "tagList" => ["dragons", "training"], "createdAt" => created_at, "updatedAt" => updated_at, "favorited" => false, "favoritesCount" => 0, "author" => %{ "username" => "jake", "bio" => nil, "image" => nil, "following" => false, } } end end end
28.705128
116
0.555605
1c148dc68873bbe8d8100e0366d6460b46ac2206
12,684
ex
Elixir
lib/nostrum/cache/guild_cache.ex
chakrit/nostrum
f0ce383d06bb3bb1786ff0464c95cbd757d38f1f
[ "MIT" ]
null
null
null
lib/nostrum/cache/guild_cache.ex
chakrit/nostrum
f0ce383d06bb3bb1786ff0464c95cbd757d38f1f
[ "MIT" ]
null
null
null
lib/nostrum/cache/guild_cache.ex
chakrit/nostrum
f0ce383d06bb3bb1786ff0464c95cbd757d38f1f
[ "MIT" ]
null
null
null
defmodule Nostrum.Cache.GuildCache do @table_name :nostrum_guilds @moduledoc """ Functions for retrieving guild states. The ETS table name associated with the Guild Cache is `#{@table_name}`. Besides the methods provided here, you can call any other ETS methods on the table. """ alias Nostrum.Cache.Mapping.ChannelGuild alias Nostrum.Snowflake alias Nostrum.Struct.Channel alias Nostrum.Struct.Emoji alias Nostrum.Struct.Guild alias Nostrum.Struct.Guild.Member alias Nostrum.Struct.Guild.Role alias Nostrum.Struct.Message alias Nostrum.Util import Nostrum.Snowflake, only: [is_snowflake: 1] @type clause :: {:id, Guild.id()} | {:channel_id, Channel.id()} | {:message, Message.t()} @type clauses :: [clause] | map @type selector :: (Guild.t() -> any) @type reason :: :id_not_found | :id_not_found_on_guild_lookup defguardp is_selector(term) when is_function(term, 1) @doc "Retrieve the ETS table name used for the cache." @spec tabname :: atom() def tabname, do: @table_name @doc """ Retrieves all `Nostrum.Struct.Guild` from the cache as a list. """ @spec all() :: Enum.t() def all do @table_name |> :ets.tab2list() |> Stream.map(&elem(&1, 1)) end @doc """ Selects values using a `selector` from all `Nostrum.Struct.Guild` in the cache. """ @spec select_all(selector) :: Enum.t() def select_all(selector) def select_all(selector) when is_selector(selector) do :ets.foldl(fn {_id, guild}, acc -> [selector.(guild) | acc] end, [], @table_name) end @doc """ Retrives a single `Nostrum.Struct.Guild` from the cache via its `id`. Returns `{:error, reason}` if no result was found. ## Examples ```Elixir iex> Nostrum.Cache.GuildCache.get(0) {:ok, %Nostrum.Struct.Guild{id: 0}} iex> Nostrum.Cache.GuildCache.get(10) {:error, :id_not_found_on_guild_lookup} ``` """ @spec get(Guild.id()) :: {:ok, Guild.t()} | {:error, reason} def get(id) do select(id, fn guild -> guild end) end @doc ~S""" Same as `get/1`, but raises `Nostrum.Error.CacheError` in case of failure. """ @spec get!(Guild.id()) :: Guild.t() | no_return def get!(id), do: get(id) |> Util.bangify_find(id, __MODULE__) @doc """ Retrives a single `Nostrum.Struct.Guild` where it matches the `clauses`. Returns `{:error, reason}` if no result was found. ```Elixir iex> Nostrum.Cache.GuildCache.get_by(id: 0) {:ok, %Nostrum.Struct.Guild{id: 0}} iex> Nostrum.Cache.GuildCache.get_by(%{id: 0}) {:ok, %Nostrum.Struct.Guild{id: 0}} iex> Nostrum.Cache.GuildCache.get_by(id: 10) {:error, :id_not_found_on_guild_lookup} ``` """ @spec get_by(clauses) :: {:ok, Guild.t()} | {:error, reason} def get_by(clauses) do select_by(clauses, fn guild -> guild end) end @doc ~S""" Same as `get_by/1`, but raises `Nostrum.Error.CacheError` in case of failure. """ @spec get_by!(clauses) :: Guild.t() | no_return def get_by!(clauses), do: get_by(clauses) |> Util.bangify_find(clauses, __MODULE__) @doc """ Selects values using a `selector` from a `Nostrum.Struct.Guild`. Returns `{:error, reason}` if no result was found. ## Examples ```Elixir iex> Nostrum.Cache.GuildCache.select(0, fn guild -> guild.id end) {:ok, 0} iex> Nostrum.Cache.GuildCache.select(10, fn guild -> guild.id end) {:error, :id_not_found_on_guild_lookup} ``` """ @spec select(Guild.id(), selector) :: {:ok, any} | {:error, reason} def select(id, selector) do select_by(%{id: id}, selector) end @doc ~S""" Same as `select/2`, but raises `Nostrum.Error.CacheError` in case of failure. """ @spec select!(Guild.id(), selector) :: any | no_return def select!(id, selector), do: select(id, selector) |> Util.bangify_find(id, __MODULE__) @doc """ Selects values using a `selector` from a `Nostrum.Struct.Guild` that matches the `clauses`. Returns `{:error, reason}` if no result was found. ```Elixir iex> Nostrum.Cache.GuildCache.select_by([id: 0], fn guild -> guild.id end) {:ok, 0} iex> Nostrum.Cache.GuildCache.select_by(%{id: 0}, fn guild -> guild.id end) {:ok, 0} iex> Nostrum.Cache.GuildCache.select_by([id: 10], fn guild -> guild.id end) {:error, :id_not_found_on_guild_lookup} ``` """ @spec select_by(clauses, selector) :: {:ok, any} | {:error, reason} def select_by(clauses, selector) def select_by(clauses, selector) when is_list(clauses) and is_selector(selector), do: select_by(Map.new(clauses), selector) def select_by(%{id: id}, selector) when is_snowflake(id) and is_selector(selector) do case :ets.lookup(@table_name, id) do [{^id, guild}] -> selection = selector.(guild) {:ok, selection} [] -> {:error, :id_not_found_on_guild_lookup} end end def select_by(%{channel_id: channel_id}, selector) when is_snowflake(channel_id) and is_selector(selector) do case ChannelGuild.get_guild(channel_id) do {:ok, guild_id} -> select_by(%{id: guild_id}, selector) {:error, _} = error -> error end end def select_by(%{message: %Message{channel_id: channel_id}}, selector) do select_by(%{channel_id: channel_id}, selector) end @doc ~S""" Same as `select_by/2`, but raises `Nostrum.Error.CacheError` in case of failure. """ @spec select_by!(clauses, selector) :: any | no_return def select_by!(clauses, selector), do: select_by(clauses, selector) |> Util.bangify_find(clauses, __MODULE__) # IMPLEMENTATION @doc false @spec create(Guild.t()) :: true def create(guild) do true = :ets.insert_new(@table_name, {guild.id, guild}) end @doc false @spec update(map()) :: {Guild.t(), Guild.t()} def update(payload) do [{_id, old_guild}] = :ets.lookup(@table_name, payload.id) casted = Util.cast(payload, {:struct, Guild}) new_guild = Map.merge(old_guild, casted) true = :ets.update_element(@table_name, payload.id, {2, new_guild}) {old_guild, new_guild} end @doc false @spec delete(Guild.id()) :: Guild.t() | nil def delete(guild_id) do # Returns the old guild, if cached case :ets.take(@table_name, guild_id) do [guild] -> guild [] -> nil end end @doc false @spec channel_create(Guild.id(), map()) :: Channel.t() def channel_create(guild_id, channel) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) new_channel = Util.cast(channel, {:struct, Channel}) new_channels = Map.put(guild.channels, channel.id, new_channel) new_guild = %{guild | channels: new_channels} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) new_channel end @doc false @spec channel_delete(Guild.id(), Channel.id()) :: Channel.t() | :noop def channel_delete(guild_id, channel_id) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {popped, new_channels} = Map.pop(guild.channels, channel_id) new_guild = %{guild | channels: new_channels} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) if popped, do: popped, else: :noop end @doc false @spec channel_update(Guild.id(), map()) :: {Channel.t(), Channel.t()} def channel_update(guild_id, channel) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {old, new, new_channels} = upsert(guild.channels, channel.id, channel, Channel) new_guild = %{guild | channels: new_channels} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) {old, new} end @doc false @spec emoji_update(Guild.id(), [map()]) :: {[Emoji.t()], [Emoji.t()]} def emoji_update(guild_id, emojis) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) casted = Util.cast(emojis, {:list, {:struct, Emoji}}) new = %{guild | emojis: casted} true = :ets.update_element(@table_name, guild_id, {2, new}) {guild.emojis, casted} end @doc false @spec member_add(Guild.id(), map()) :: Member.t() def member_add(guild_id, payload) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {_old, member, new_members} = upsert(guild.members, payload.user.id, payload, Member) new = %{guild | members: new_members, member_count: guild.member_count + 1} true = :ets.update_element(@table_name, guild_id, {2, new}) member end @doc false @spec member_remove(Guild.id(), map()) :: {Guild.id(), Member.t()} | :noop def member_remove(guild_id, user) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {popped, new_members} = Map.pop(guild.members, user.id) new_guild = %{guild | members: new_members, member_count: guild.member_count - 1} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) if popped, do: {guild_id, popped}, else: :noop end @doc false @spec member_update(Guild.id(), map()) :: {Guild.id(), Member.t() | nil, Member.t()} def member_update(guild_id, member) do # We may retrieve a GUILD_MEMBER_UPDATE event for our own user even if we # have the required intents to retrieve it for other members disabled, as # outlined in issue https://github.com/Kraigie/nostrum/issues/293. In # that case, we will not have the guild cached. case :ets.lookup(@table_name, guild_id) do [{_id, guild}] -> {old, new, new_members} = upsert(guild.members, member.user.id, member, Member) new_guild = %{guild | members: new_members} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) {guild_id, old, new} [] -> new = Util.cast(member, {:struct, Member}) {guild_id, nil, new} end end @doc false def member_chunk(guild_id, member_chunk) do # CHONK like that one cat of craig [{_id, guild}] = :ets.lookup(@table_name, guild_id) new_members = Enum.reduce(member_chunk, guild.members, fn m, acc -> Map.put(acc, m.user.id, Util.cast(m, {:struct, Member})) end) # XXX: do we not need to update member count here? new = %{guild | members: new_members} true = :ets.update_element(@table_name, guild_id, {2, new}) end @doc false @spec role_create(Guild.id(), map()) :: Role.t() def role_create(guild_id, role) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {_old, new, new_roles} = upsert(guild.roles, role.id, role, Role) new_guild = %{guild | roles: new_roles} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) new end @doc false @spec role_delete(Guild.id(), Role.id()) :: {Guild.id(), Role.t()} | :noop def role_delete(guild_id, role_id) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {popped, new_roles} = Map.pop(guild.roles, role_id) new_guild = %{guild | roles: new_roles} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) if popped, do: {guild_id, popped}, else: :noop end @doc false @spec role_update(Guild.id(), map()) :: {Role.t(), Role.t()} def role_update(guild_id, role) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) {old, new_role, new_roles} = upsert(guild.roles, role.id, role, Role) new_guild = %{guild | roles: new_roles} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) {old, new_role} end @doc false @spec voice_state_update(Guild.id(), map()) :: {Guild.id(), [map()]} def voice_state_update(guild_id, payload) do [{_id, guild}] = :ets.lookup(@table_name, guild_id) # Trim the `member` from the update payload. # Remove both `"member"` and `:member` in case of future key changes. trimmed_update = Map.drop(payload, [:member, "member"]) state_without_user = Enum.reject(guild.voice_states, &(&1.user_id == trimmed_update.user_id)) # If the `channel_id` is nil, then the user is leaving. # Otherwise, the voice state was updated. new_state = if(is_nil(trimmed_update.channel_id), do: state_without_user, else: [trimmed_update | state_without_user] ) new_guild = %{guild | voice_states: new_state} true = :ets.update_element(@table_name, guild_id, {2, new_guild}) {guild_id, new_state} end @spec upsert(%{required(Snowflake.t()) => struct}, Snowflake.t(), map, atom) :: {struct | nil, struct, %{required(Snowflake.t()) => struct}} defp upsert(map, key, new, struct) do if Map.has_key?(map, key) do old = Map.get(map, key) new = old |> Map.from_struct() |> Map.merge(new) |> Util.cast({:struct, struct}) new_map = Map.put(map, key, new) {old, new, new_map} else new = Util.cast(new, {:struct, struct}) {nil, new, Map.put(map, key, new)} end end end
32.523077
97
0.65082
1c149f21a8acc6fec435c041c1a5366399907a04
1,228
exs
Elixir
apps/kv_server/test/kv_server_test.exs
tegon/kv.ex
2de981b51f5ca7ef32a67743eb4344460677cbe6
[ "MIT" ]
null
null
null
apps/kv_server/test/kv_server_test.exs
tegon/kv.ex
2de981b51f5ca7ef32a67743eb4344460677cbe6
[ "MIT" ]
null
null
null
apps/kv_server/test/kv_server_test.exs
tegon/kv.ex
2de981b51f5ca7ef32a67743eb4344460677cbe6
[ "MIT" ]
null
null
null
defmodule KVServerTest do use ExUnit.Case @moduletag :capture_log setup do Application.stop(:kv) :ok = Application.start(:kv) end setup do opts = [:binary, packet: :line, active: false] {:ok, socket} = :gen_tcp.connect('localhost', Application.fetch_env!(:kv_server, :port), opts) {:ok, socket: socket} end test "server interaction", %{socket: socket} do assert send_and_recv(socket, "UNKNOWN shopping\r\n") == "UNKNOWN COMMAND\r\n" assert send_and_recv(socket, "GET shopping eggs\r\n") == "NOT FOUND\r\n" assert send_and_recv(socket, "CREATE shopping\r\n") == "OK\r\n" assert send_and_recv(socket, "PUT shopping eggs 3\r\n") == "OK\r\n" # GET returns two lines assert send_and_recv(socket, "GET shopping eggs\r\n") == "3\r\n" assert send_and_recv(socket, "") == "OK\r\n" assert send_and_recv(socket, "DELETE shopping eggs\r\n") == "OK\r\n" # GET returns two lines assert send_and_recv(socket, "GET shopping eggs\r\n") == "\r\n" assert send_and_recv(socket, "") == "OK\r\n" end defp send_and_recv(socket, command) do :ok = :gen_tcp.send(socket, command) {:ok, data} = :gen_tcp.recv(socket, 0, 1000) data end end
28.55814
98
0.64658
1c14bd667bf555176c394343f446c1021f112fe5
54,195
ex
Elixir
lib/scenic/scene.ex
nyaray/scenic
a4e495262b74ff34857bfb5ec237e07d82f4871f
[ "Apache-2.0" ]
1
2020-09-20T14:07:49.000Z
2020-09-20T14:07:49.000Z
lib/scenic/scene.ex
yvc74/scenic
7a1bca453c4d96b64f2593ccaf2ea0e0b88fcc75
[ "Apache-2.0" ]
null
null
null
lib/scenic/scene.ex
yvc74/scenic
7a1bca453c4d96b64f2593ccaf2ea0e0b88fcc75
[ "Apache-2.0" ]
null
null
null
# # Created by Boyd Multerer on 2018-04-07. # Copyright © 2018 Kry10 Industries. All rights reserved. # # Taking the learnings from several previous versions. defmodule Scenic.Scene do alias Scenic.Graph alias Scenic.Scene alias Scenic.ViewPort alias Scenic.ViewPort.Context alias Scenic.Primitive alias Scenic.Utilities require Logger # import IEx @moduledoc """ ## Overview Scenes are the core of the UI model. A `Scene` has three jobs. 1. Maintain any state specific to that part of your application. 1. Build and maintain a graph of UI primitives that gets drawn to the screen. 2. Handle input and events. ### A brief aside Before saying anything else I want to emphasize that the rest of your application, meaning device control logic, sensor reading / writing, services, whatever, does not need to have anything to do with Scenes. In many cases I recommend treating those as separate GenServers in their own supervision trees that you maintain. Then your Scenes would query or send information to/from them via cast or call messages. Part of the point of using Erlang/Elixir/OTP is separating this sort of logic into independent trees. That way, an error in one part of your application does not mean the rest of it will fail. ## Scenes Scenes are the core of the UI model. A scene consists of one ore more graphs, and a set of event handlers and filters to deal with user input and other messages. Think of a scene as being a little like an HTML page. HTML pages have: * Structure (the DOM) * Logic (Javascript) * Links to other pages. A Scene has: * Structure (graphs), * Logic (event handlers and filters) * Transitions to other scenes. Well... it can request the [`ViewPort`](overview_viewport.html) to go to a different scene. Your application is a collection of scenes that are in use at various times. There is only ever **one** scene showing in a [`ViewPort`](overview_viewport.html) at a given time. However, scenes can reference other scenes, effectively embedding their graphs inside the main one. More on that below. ### [Graphs](Scenic.Graph.html) Each scene should maintain at least one graph. You can build graphs at compile time, or dynamically while your scene is running. Building them at compile time has two advantages 1. Performance: It is clearly faster to build the graph once during build time than to build it repeatedly during runtime. 2. Error checking: If your graph has an error in it, it is much better to have it stop compilation than cause an error during runtime. Example of building a graph during compile time: @graph graph.build(font_size: 24) |> button({"Press Me", :button_id}, translate: {20, 20}) Rather than having a single scene maintain a massive graph of UI, graphs can reference graphs in other scenes. On a typical screen of UI, there is one scene that is the root. Each control, is its own scene process with its own state. These child scenes can in turn contain other child scenes. This allows for strong code reuse, isolates knowledge and logic to just the pieces that need it, and keeps the size of any given graph to a reasonable size. For example, The handlers of a check-box scene don't need to know anything about how a slider works, even though they are both used in the same parent scene. At best, they only need to know that they both conform to the `Component.Input` behavior, and can thus query or set each others value. Though it is usually the parent scene that does that. The application developer is responsible for building and maintaining the scene's graph. It only enters the world of the `ViewPort` when you call `push_graph`. Once you have called `push_graph`, that graph is sent to the drivers and is out of your immediate control. You update that graph by calling `push_graph` again. This does mean you could maintain two separate graphs and rapidly switch back and forth between them via push_graph. I have not yet hit a good use case for that. #### Graph ID. This is an advanced feature... Each scene has a default graph id of nil. When you send a graph to the ViewPort by calling `push_graph(graph)`, you are really sending it with a sub-id of nil. This encourages thinking that scenes and graphs have a 1:1 relationship. There are, however, times that you want a single scene to host multiple graphs that can refer to each other via sub-ids. You would push them like this: `push_graph(graph, id)`. Where the id is any term you would like to use as a key. There are several use cases where this makes sense. 1) You have a complex tree (perhaps a lot of text) that you want to animate. Rather than re-rendering the text (relatively expensive) every time you simply transform a rotation matrix, you could place the text into its own static sub-graph and then refer to it from the primary. This will save energy as you animate. 2) Both the Remote and Recording clients make heavy use of sub-ids to make sense of the graph being replayed. The downside of using graph_ids comes with input handling. because you have a single scene handling the input events for multiple graphs, you will need to take extra care to correctly handle position-dependent events, which may not be projected into the coordinate space you think they are. The Remote and Recording clients deal with this by rendering a single, completely transparent rect above all the sub scenes. This invisible, yet present rect hits all the position dependent events and makes sure they are sent to the scene projected in to the main (id is nil) graph's coordinate space. ### Communications Scenes are specialized GenServers. As such, they communicate with each other (and the rest of your application) through messages. You can receive messages with the standard `handle_info`, `handle_cast`, `handle_call` callbacks just like any other scene. Scenes have two new event handling callbacks that you can *optionally* implement. These are about user input vs UI events. ## Input vs. Events Input is data generated by the drivers and sent up to the scenes through the `ViewPort`. There is a limited set of input types and they are standardized so that the drivers can be built independently of the scenes. Input follows certain rules about which scene receives them Events are messages that one scene generates for consumption by other scenes. For example, a `Component.Button` scene would generate a `{:click, msg}` event that is sent to its parent scene. You can generate any message you want, however, the standard component libraries follow certain patterns to keep things sensible. ## Input Handling You handle incoming input events by adding `handle_input/3` functions to your scene. Each `handle_input/3` call passes in the input message itself, an input context struct, and your scene's state. You can then take the appropriate actions, including generating events (below) in response. Under normal operation, input that is not position dependent (keys, window events, more...) is sent to the root scene. Input that does have a screen position (cursor_pos, cursor button presses, etc.) Is sent to the scene that contains the graph that was hit. Your scene can "capture" all input of a given type so that it is sent to itself instead of the default scene for that type. this is how a text input field receives the key input. First, the user selects that field by clicking on it. In response to the cursor input, the text field captures text input (and maybe transforms its graph to show that it is selected). Captured input types should be released when no longer needed so that normal operation can resume. The input messages are passed on to a scene's parent if not processed. ## Event Filtering In response to input, (or anything else... a timer perhaps?), a scene can generate an event (any term), which is sent backwards up the tree of scenes that make up the current aggregate graph. In this way, a `Component.Button` scene can generate a`{:click, msg}` event that is sent to its parent. If the parent doesn't handle it, it is sent to that scene's parent. And so on until the event reaches the root scene. If the root scene doesn't handle it either then the event is dropped. To handle events, you add `filter_event/3` functions to your scene. This function handles the event, and stop its progress backwards up the graph. It can handle it and allow it to continue up the graph. Or it can transform the event and pass the transformed version up the graph. You choose the behavior by returning either {:cont, msg, state} or {:halt, state} Parameters passed in to `filter_event/3` are the event itself, a reference to the originating scene (which you can to communicate back to it), and your scene's state. A pattern I'm using is to handle and event at the filter and stop its progression. It also generates and sends new event to its parent. I do this instead of transforming and continuing when I want to change the originating scene. ## No children There is an optimization you can use. If you know for certain that your component will not attempt to use any components, you can set `has_children` to `false` like this. use Scenic.Component, has_children: false Setting `has_children` to `false` this will do two things. First, it won't create a dynamic supervisor for this scene, which saves some resources. For example, the Button component sets `has_children` to `false`. """ # @viewport :viewport @not_activated :__not_activated__ @type response_opts :: list( {:timeout, non_neg_integer} | {:hibernate, true} | {:continue, term} | {:push, graph :: Graph.t()} ) defmodule Error do @moduledoc false defexception message: nil end # ============================================================================ # client api - working with the scene @doc """ send a filterable event to a scene. This is very similar in feel to casting a message to a GenServer. However, This message will be handled by the Scene's `filter_event\3` function. If the Scene returns `{:continue, msg, state}` from `filter_event\3`, then the event will also be sent to the scene's parent. This will continue until the message reaches the root scene or some other permanently supervised scene. Typically, when a scene wants to initiate an event, it will call `send_event/1` which is a private function injected into the scene during `use Scenic.Scene` This private version of send_event will take care of the housekeeping of tracking the parent's pid. It will, in turn, call this function on the main Scene module to send the event on its way. def handle_input( {:cursor_button, {:left, :release, _, _}}, _, %{msg: msg} = state ) do send_event( {:click, msg} ) {:noreply, state} end On the other hand, if you know you want to send the event to a named scene that you supervise yourself, then you would use `Scenic.Scene.send_event/2` def handle_input( {:cursor_button, {:left, :release, _, _}}, _, %{msg: msg} = state ) do Scenic.Scene.send_event( :some_scene, {:click, msg} ) {:noreply, state} end Be aware that named scenes that your supervise yourself are unable to continue the event to their parent in the graph because they could be referenced by multiple graphs making the continuation ambiguous. """ @spec send_event(scene_server :: GenServer.server(), event :: ViewPort.event()) :: :ok def send_event(scene_server, {evt, _} = event) when is_atom(evt) do GenServer.cast(scene_server, {:event, event, self()}) end # -------------------------------------------------------- @doc """ cast a message to a scene. """ def cast(scene_or_graph_key, msg) do with {:ok, pid} <- ViewPort.Tables.get_scene_pid(scene_or_graph_key) do GenServer.cast(pid, msg) end end # -------------------------------------------------------- def cast_to_refs(graph_key_or_id, msg) def cast_to_refs({:graph, _, _} = graph_key, msg) do with {:ok, refs} <- ViewPort.Tables.get_refs(graph_key) do Enum.each(refs, fn {_, key} -> cast(key, msg) end) end end def cast_to_refs(sub_id, msg) do case Process.get(:scene_ref) do nil -> "cast_to_refs requires a full graph_key or must be called within a scene" |> raise() scene_ref -> cast_to_refs({:graph, scene_ref, sub_id}, msg) end end # ============================================================================ # callback definitions @doc """ Invoked when the `Scene` receives input from a driver. Input is messages sent directly from a driver, usually based on some action by the user. This is opposed to "events", which are generated by other scenes. When input arrives at a scene, you can consume it, or pass it along to the scene above you in the ViewPort's supervision structure. To consume the input and have processing stop afterward, return either a `{:halt, ...}` or `{:noreply, ...}` value. They are effectively the same thing. To allow the scene's parent to process the input, return `{:cont, input, state, ...}`. Note that you can pass along the input unchanged or transform it in the process if you wish. The callback supports all the return values of the [`init`](https://hexdocs.pm/elixir/GenServer.html#c:handle_cast/2) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). In addition to the normal return values defined by GenServer, a `Scene` can add an optional `{push: graph}` term, which pushes the graph to the viewport. This has replaced push_graph() as the preferred way to push a graph. """ @callback handle_input(input :: any, context :: Context.t(), state :: any) :: {:noreply, new_state} | {:noreply, new_state} | {:noreply, new_state, timeout} | {:noreply, new_state, :hibernate} | {:noreply, new_state, opts :: response_opts()} | {:halt, new_state} | {:halt, new_state, timeout} | {:halt, new_state, :hibernate} | {:halt, new_state, opts :: response_opts()} | {:cont, input, new_state} | {:cont, input, new_state, timeout} | {:cont, input, new_state, :hibernate} | {:cont, input, new_state, opts :: response_opts()} | {:stop, reason, new_state} when new_state: term, reason: term, input: term @doc """ Invoked when the `Scene` receives an event from another scene. Events are messages generated by a scene, that are passed backwards up the ViewPort's scene supervision tree. This is opposed to "input", which comes directly from the drivers. When an event arrives at a scene, you can consume it, or pass it along to the scene above you in the ViewPort's supervision structure. To consume the input and have processing stop afterward, return either a `{:halt, ...}` or `{:noreply, ...}` value. They are effectively the same thing. To allow the scene's parent to process the input, return `{:cont, event, state, ...}`. Note that you can pass along the event unchanged or transform it in the process if you wish. The callback supports all the return values of the [`init`](https://hexdocs.pm/elixir/GenServer.html#c:handle_cast/2) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). In addition to the normal return values defined by GenServer, a `Scene` can add an optional `{push: graph}` term, which pushes the graph to the viewport. This has replaced push_graph() as the preferred way to push a graph. """ @callback filter_event(event :: term, from :: pid, state :: term) :: {:noreply, new_state} | {:noreply, new_state} | {:noreply, new_state, timeout} | {:noreply, new_state, :hibernate} | {:noreply, new_state, opts :: response_opts()} | {:halt, new_state} | {:halt, new_state, timeout} | {:halt, new_state, :hibernate} | {:halt, new_state, opts :: response_opts()} | {:cont, event, new_state} | {:cont, event, new_state, timeout} | {:cont, event, new_state, :hibernate} | {:cont, event, new_state, opts :: response_opts()} | {:stop, reason, new_state} when new_state: term, reason: term, event: term @doc """ Invoked when the `Scene` is started. `args` is the argument term you passed in via config or ViewPort.set_root. `options` is a list of information giving you context about the environment the scene is running in. If an option is not in the list, then it should be treated as nil. * `:viewport` - This is the pid of the ViewPort that is managing this dynamic scene. It will be not set, or nil, if you are managing the Scene in a static supervisor yourself. * `:styles` - This is the map of styles that your scene can choose to inherit (or not) from its parent scene. This is typically used by a child control that wants to visually fit into its parent's look. * `:id` - This is the :id term that the parent set a component when it was invoked. The callback supports all the return values of the [`init`](https://hexdocs.pm/elixir/GenServer.html#c:init/1) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). In addition to the normal return values defined by GenServer, a `Scene` can return two new ones that push a graph to the viewport Returning `{:ok, state, push: graph}` will push the indicated graph to the ViewPort. This is preferable to the old push_graph() function. """ @callback init(args :: term, options :: list) :: {:ok, new_state} | {:ok, new_state, timeout :: non_neg_integer} | {:ok, new_state, :hibernate} | {:ok, new_state, opts :: response_opts()} | :ignore | {:stop, reason :: any} when new_state: any @doc """ Invoked to handle synchronous `call/3` messages. `call/3` will block until a reply is received. The callback supports all the return values of the [`handle_call`](https://hexdocs.pm/elixir/GenServer.html#c:handle_call/3) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). In addition to the normal return values defined by GenServer, a `Scene` can add an optional `{push: graph}` term, which pushes the graph to the viewport. This has replaced push_graph() as the preferred way to push a graph. """ @callback handle_call(request :: term, from :: GenServer.from(), state :: term) :: {:reply, reply, new_state} | {:reply, reply, new_state, timeout} | {:reply, reply, new_state, :hibernate} | {:reply, reply, new_state, opts :: response_opts()} | {:noreply, new_state} | {:noreply, new_state, timeout} | {:noreply, new_state, :hibernate} | {:noreply, new_state, opts :: response_opts()} | {:stop, reason, reply, new_state} | {:stop, reason, new_state} when reply: term, new_state: term, reason: term @doc """ Invoked to handle asynchronous `cast/2` messages. `request` is the request message sent by a `cast/2` and `state` is the current state of the `Scene`. The callback supports all the return values of the [`handle_cast`](https://hexdocs.pm/elixir/GenServer.html#c:handle_cast/2) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). In addition to the normal return values defined by GenServer, a `Scene` can add an optional `{push: graph}` term, which pushes the graph to the viewport. This has replaced push_graph() as the preferred way to push a graph. """ @callback handle_cast(request :: term, state :: term) :: {:noreply, new_state} | {:noreply, new_state, timeout} | {:noreply, new_state, :hibernate} | {:noreply, new_state, opts :: response_opts()} | {:stop, reason :: term, new_state} when new_state: term @doc """ Invoked to handle all other messages. `msg` is the message and `state` is the current state of the `Scene`. When a timeout occurs the message is `:timeout`. Return values are the same as `c:handle_cast/2`. In addition to the normal return values defined by GenServer, a `Scene` can add an optional `{push: graph}` term, which pushes the graph to the viewport. This has replaced push_graph() as the preferred way to push a graph. """ @callback handle_info(msg :: :timeout | term, state :: term) :: {:noreply, new_state} | {:noreply, new_state, timeout} | {:noreply, new_state, :hibernate} | {:noreply, new_state, opts :: response_opts()} | {:stop, reason :: term, new_state} when new_state: term @doc """ Invoked to handle `continue` instructions. It is useful for performing work after initialization or for splitting the work in a callback in multiple steps, updating the process state along the way. The callback supports all the return values of the [`handle_continue`](https://hexdocs.pm/elixir/GenServer.html#c:handle_continue/2) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). In addition to the normal return values defined by GenServer, a `Scene` can add an optional `{push: graph}` term, which pushes the graph to the viewport. This has replaced push_graph() as the preferred way to push a graph. """ @callback handle_continue(continue :: term, state :: term) :: {:noreply, new_state} | {:noreply, new_state, timeout} | {:noreply, new_state, :hibernate} | {:noreply, new_state, opts :: response_opts()} | {:stop, reason :: term, new_state} when new_state: term @doc """ Invoked when the Scene is about to exit. It should do any cleanup required. `reason` is exit reason and `state` is the current state of the `Scene`. The return value is ignored. The callback is identical to the [`terminate`](https://hexdocs.pm/elixir/GenServer.html#c:terminate/2) callback in [`Genserver`](https://hexdocs.pm/elixir/GenServer.html). """ @callback terminate(reason, state :: term) :: term when reason: :normal | :shutdown | {:shutdown, term} # ============================================================================ # using macro # =========================================================================== # the using macro for scenes adopting this behavior defmacro __using__(using_opts \\ []) do quote do @behaviour Scenic.Scene # -------------------------------------------------------- # Here so that the scene can override if desired # def init(_, _, _), do: {:ok, nil} @doc false def handle_call(_msg, _from, state), do: {:reply, :err_not_handled, state} @doc false def handle_cast(_msg, state), do: {:noreply, state} @doc false def handle_info(_msg, state), do: {:noreply, state} @doc false def handle_continue(_msg, state), do: {:noreply, state} @doc false def handle_input(event, _, scene_state), do: {:noreply, scene_state} @doc false def filter_event(event, _from, scene_state), do: {:cont, event, scene_state} @doc false def terminate(_reason, _scene_state), do: :ok @doc false def start_dynamic_scene(supervisor, parent, args, opts \\ []) do has_children = case unquote(using_opts)[:has_children] do false -> false _ -> true end Scenic.Scene.start_dynamic_scene( supervisor, parent, __MODULE__, args, opts, has_children ) end defp send_event(event_msg) do case Process.get(:parent_pid) do nil -> {:error, :no_parent} pid -> GenServer.cast(pid, {:event, event_msg, self()}) end end defp push_graph(%Graph{} = graph) do IO.puts(""" #{IO.ANSI.yellow()} Deprecation in #{inspect(__MODULE__)} push_graph/1 has been deprecated and will be removed in a future version Instead, use the returns below from init/2 {:ok, state, push: graph} from filter_event/3 {:halt, state, push: graph} {:cont, event, state, push: graph} from handle_cast/2 {:noreply, state, push: graph} from handle_info/2 {:noreply, state, push: graph} from handle_call/3 {:reply, reply, state, push: graph} {:noreply, state, push: graph} from handle_continue/2 {:noreply, state, push: graph} #{IO.ANSI.default_color()} """) GenServer.cast(self(), {:push_graph, graph, nil}) # return the graph so this can be pipelined graph end # return the local scene process's scene_ref defp scene_ref(), do: Process.get(:scene_ref) # child spec that really starts up scene, with this module as an option @doc false def child_spec({args, opts}) when is_list(opts) do %{ id: make_ref(), start: {Scenic.Scene, :start_link, [__MODULE__, args, opts]}, type: :worker, restart: :permanent, shutdown: 500 } end # -------------------------------------------------------- # add local shortcuts to things like get/put graph and modify element # do not add a put element. keep it at modify to stay atomic # -------------------------------------------------------- defoverridable handle_call: 3, handle_cast: 2, handle_continue: 2, handle_info: 2, handle_input: 3, filter_event: 3, start_dynamic_scene: 3, terminate: 2 # quote end # defmacro end # =========================================================================== # calls for setting up a scene inside of a supervisor # def child_spec({ref, scene_module}), do: # child_spec({ref, scene_module, nil}) @doc false def child_spec({scene_module, args, opts}) do %{ id: make_ref(), start: {__MODULE__, :start_link, [scene_module, args, opts]}, type: :worker, restart: :permanent, shutdown: 500 } end # ============================================================================ # internal server api @doc false def start_link(scene_module, args, opts \\ []) do init_data = {scene_module, args, opts} case opts[:name] do nil -> GenServer.start_link(__MODULE__, init_data) name -> GenServer.start_link(__MODULE__, init_data, name: name) end end # -------------------------------------------------------- @doc false def init({scene_module, args, opts}) do has_children = case opts[:has_children] do false -> false _ -> true end scene_ref = opts[:scene_ref] || opts[:name] Process.put(:scene_ref, scene_ref) # if this is being built as a viewport's dynamic root, let the vp know it is up. # this solves the case where this scene is dynamic and has crashed and is recovering. # The scene_ref is the same, but the pid has changed. This lets the vp know which # is the correct pid to use when it is cleaned up later. case opts[:vp_dynamic_root] do nil -> nil viewport -> GenServer.cast(viewport, {:dyn_root_up, scene_ref, self()}) end # interpret the options parent_pid = case opts[:parent] do nil -> nil parent_pid -> # stash the parent pid away in the process dictionary. This # is for fast lookup during the injected send_event/1 in the # client module Process.put(:parent_pid, parent_pid) parent_pid end # if this scene is named... Meaning it is supervised by the app and is not a # dynamic scene, then we need monitor the ViewPort. If the viewport goes # down while this scene is activated, the scene will need to be able to # deactivate itself while the viewport is recovering. This is especially # true since the viewport may recover to a different default scene than this. if opts[:name], do: Process.monitor(Scenic.ViewPort.Tables) # build up the state state = %{ has_children: has_children, raw_scene_refs: %{}, dyn_scene_pids: %{}, dyn_scene_keys: %{}, parent_pid: parent_pid, children: %{}, scene_module: scene_module, viewport: opts[:viewport], # scene_state: sc_state, # scene_state: nil, scene_ref: scene_ref, supervisor_pid: nil, dynamic_children_pid: nil, activation: @not_activated } {:ok, state, {:continue, {:__scene_init_2__, scene_module, args, opts}}} end # ============================================================================ # terminate def terminate(reason, %{scene_module: mod, scene_state: sc_state}) do mod.terminate(reason, sc_state) end # ============================================================================ # handle_continue # -------------------------------------------------------- def handle_continue( {:__scene_init_2__, scene_module, args, opts}, %{scene_ref: scene_ref} = state ) do # get the scene supervisors [supervisor_pid | _] = self() |> Process.info() |> get_in([:dictionary, :"$ancestors"]) # make sure it is a pid and not a name supervisor_pid = case supervisor_pid do name when is_atom(name) -> Process.whereis(name) pid when is_pid(pid) -> pid end # make sure this is a Scene.Supervisor, not something else {supervisor_pid, dynamic_children_pid} = case Process.info(supervisor_pid) do nil -> {nil, nil} info -> case get_in(info, [:dictionary, :"$initial_call"]) do {:supervisor, Scene.Supervisor, _} -> dynamic_children_pid = Supervisor.which_children(supervisor_pid) # credo:disable-for-next-line Credo.Check.Refactor.Nesting |> Enum.find_value(fn {DynamicSupervisor, pid, :supervisor, [DynamicSupervisor]} -> pid _ -> nil end) {supervisor_pid, dynamic_children_pid} _ -> {nil, nil} end end # register the scene in the scenes ets table Scenic.ViewPort.Tables.register_scene( scene_ref, {self(), dynamic_children_pid, supervisor_pid} ) # store bookeeping in the state state = state |> Map.put(:supervisor_pid, supervisor_pid) |> Map.put(:dynamic_children_pid, dynamic_children_pid) |> Map.put(:scene_state, nil) # set up to init the module # GenServer.cast(self(), {:init_module, scene_module, args, opts}) # reply with the state so far {:noreply, state, {:continue, {:__scene_init_3__, scene_module, args, opts}}} end # -------------------------------------------------------- def handle_continue({:__scene_init_3__, scene_module, args, opts}, state) do # initialize the scene itself try do # handle the result of the scene init and return case scene_module.init(args, opts) do {:ok, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:ok, sc_state, opt} -> deal_with_noreply(:noreply, state, sc_state, opt) :ignore -> :ignore {:stop, reason} -> {:stop, reason} unknown -> # build error message components head_msg = "#{inspect(scene_module)} init returned invalid response" err_msg = "" args_msg = "return value: #{inspect(unknown)}" stack_msg = "" unless Scenic.mix_env() == :test do [ "\n", IO.ANSI.red(), head_msg, "\n", IO.ANSI.yellow(), args_msg, IO.ANSI.default_color() ] |> Enum.join() |> IO.puts() end case opts[:viewport] do nil -> :ok vp -> msgs = {head_msg, err_msg, args_msg, stack_msg} ViewPort.set_root(vp, {Scenic.Scenes.Error, {msgs, scene_module, args}}) end {:noreply, state} end rescue err -> # build error message components module_msg = inspect(scene_module) err_msg = inspect(err) args_msg = inspect(args) stack_msg = Exception.format_stacktrace(__STACKTRACE__) # assemble into a final message to output to the command line unless Scenic.mix_env() == :test do [ "\n", IO.ANSI.red(), module_msg <> " crashed during init", "\n", IO.ANSI.yellow(), "Scene Args: " <> args_msg, "\n", IO.ANSI.red(), err_msg, "\n", "--> ", stack_msg, "\n", IO.ANSI.default_color() ] |> Enum.join() |> IO.puts() end case opts[:viewport] do nil -> :ok vp -> msgs = {module_msg, err_msg, args_msg, stack_msg} ViewPort.set_root(vp, {Scenic.Scenes.Error, {msgs, scene_module, args}}) end # purposefully slow down the reply in the event of a crash. Just in # case it does go into a crazy loop # Process.sleep(400) {:noreply, state} end end # -------------------------------------------------------- # generic handle_continue. give the scene a chance to handle it @doc false def handle_continue(msg, %{scene_module: mod, scene_state: sc_state} = state) do case mod.handle_continue(msg, sc_state) do {:noreply, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:noreply, sc_state, opt} -> deal_with_noreply(:noreply, state, sc_state, opt) {:stop, reason, sc_state} -> {:stop, reason, %{state | scene_state: sc_state}} end end # ============================================================================ # handle_info # -------------------------------------------------------- # generic handle_info. give the scene a chance to handle it @doc false def handle_info(msg, %{scene_module: mod, scene_state: sc_state} = state) do case mod.handle_info(msg, sc_state) do {:noreply, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:noreply, sc_state, opt} -> deal_with_noreply(:noreply, state, sc_state, opt) {:stop, reason, sc_state} -> {:stop, reason, %{state | scene_state: sc_state}} end end # ============================================================================ # handle_call # -------------------------------------------------------- # generic handle_call. give the scene a chance to handle it def handle_call(msg, from, %{scene_module: mod, scene_state: sc_state} = state) do case mod.handle_call(msg, from, sc_state) do {:reply, reply, sc_state} -> deal_with_reply(reply, state, sc_state) {:reply, reply, sc_state, opt} -> deal_with_reply(reply, state, sc_state, opt) {:noreply, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:noreply, sc_state, opt} -> deal_with_noreply(:noreply, state, sc_state, opt) {:stop, reason, sc_state} -> {:stop, reason, %{state | scene_state: sc_state}} end end # ============================================================================ # handle_cast # -------------------------------------------------------- def handle_cast( {:input, event, %Scenic.ViewPort.Context{viewport: vp, raw_input: raw_input} = context}, %{scene_module: mod, scene_state: sc_state} = state ) do case mod.handle_input(event, context, sc_state) do {:noreply, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:noreply, sc_state, opts} -> deal_with_noreply(:noreply, state, sc_state, opts) {:halt, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:halt, sc_state, opts} -> deal_with_noreply(:noreply, state, sc_state, opts) {:cont, sc_state} -> GenServer.cast(vp, {:continue_input, raw_input}) deal_with_noreply(:noreply, state, sc_state) {:cont, sc_state, opts} -> GenServer.cast(vp, {:continue_input, raw_input}) deal_with_noreply(:noreply, state, sc_state, opts) {:stop, sc_state} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated handle_input :stop return in #{inspect(mod)} Please return {:halt, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) deal_with_noreply(:noreply, state, sc_state) {:stop, sc_state, opts} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated handle_input :stop return in #{inspect(mod)} Please return {:halt, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) deal_with_noreply(:noreply, state, sc_state, opts) {:continue, sc_state} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated handle_input :continue return in #{inspect(mod)} Please return {:cont, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) GenServer.cast(vp, {:continue_input, raw_input}) deal_with_noreply(:noreply, state, sc_state) {:continue, sc_state, opts} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated handle_input :continue return in #{inspect(mod)} Please return {:cont, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) GenServer.cast(vp, {:continue_input, raw_input}) deal_with_noreply(:noreply, state, sc_state, opts) end end # -------------------------------------------------------- def handle_cast( {:event, event, from_pid}, %{ parent_pid: parent_pid, scene_module: mod, scene_state: sc_state } = state ) do case mod.filter_event(event, from_pid, sc_state) do {:noreply, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:noreply, sc_state, opts} -> deal_with_noreply(:noreply, state, sc_state, opts) {:halt, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:halt, sc_state, opts} -> deal_with_noreply(:noreply, state, sc_state, opts) {:cont, event, sc_state} -> GenServer.cast(parent_pid, {:event, event, from_pid}) deal_with_noreply(:noreply, state, sc_state) {:cont, event, sc_state, opts} -> GenServer.cast(parent_pid, {:event, event, from_pid}) deal_with_noreply(:noreply, state, sc_state, opts) {:stop, sc_state} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated filter_event :stop return in #{inspect(mod)} Please return {:halt, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) deal_with_noreply(:noreply, state, sc_state) {:stop, sc_state, opts} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated filter_event :stop return in #{inspect(mod)} Please return {:halt, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) deal_with_noreply(:noreply, state, sc_state, opts) {:continue, event, sc_state} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated filter_event :continue return in #{inspect(mod)} Please return {:cont, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) GenServer.cast(parent_pid, {:event, event, from_pid}) deal_with_noreply(:noreply, state, sc_state) {:continue, event, sc_state, opts} -> IO.puts(""" #{IO.ANSI.yellow()} Deprecated filter_event :continue return in #{inspect(mod)} Please return {:cont, state} instead This resolves a naming conflict with the newer GenServer return values #{IO.ANSI.default_color()} """) GenServer.cast(parent_pid, {:event, event, from_pid}) deal_with_noreply(:noreply, state, sc_state, opts) end end # -------------------------------------------------------- def handle_cast({:push_graph, graph, sub_id}, state) do {:ok, state} = internal_push_graph(graph, sub_id, state) {:noreply, state} end # -------------------------------------------------------- # generic handle_cast. give the scene a chance to handle it def handle_cast({:stop, dyn_sup}, %{supervisor_pid: nil} = state) do DynamicSupervisor.terminate_child(dyn_sup, self()) {:noreply, state} end # -------------------------------------------------------- # generic handle_cast. give the scene a chance to handle it def handle_cast({:stop, dyn_sup}, %{supervisor_pid: supervisor_pid} = state) do DynamicSupervisor.terminate_child(dyn_sup, supervisor_pid) {:noreply, state} end # -------------------------------------------------------- # generic handle_cast. give the scene a chance to handle it def handle_cast(msg, %{scene_module: mod, scene_state: sc_state} = state) do case mod.handle_cast(msg, sc_state) do {:noreply, sc_state} -> deal_with_noreply(:noreply, state, sc_state) {:noreply, sc_state, opt} -> deal_with_noreply(:noreply, state, sc_state, opt) {:stop, reason, sc_state} -> {:stop, reason, %{state | scene_state: sc_state}} end end # ============================================================================ # Scene management # -------------------------------------------------------- # this a root-level dynamic scene @doc false def start_dynamic_scene(dynamic_supervisor, parent, mod, args, opts, has_children) when is_list(opts) and is_boolean(has_children) and is_atom(mod) do ref = make_ref() opts = opts |> Keyword.put_new(:parent, parent) |> Keyword.put_new(:scene_ref, ref) do_start_child_scene(dynamic_supervisor, ref, mod, args, opts, has_children) end # -------------------------------------------------------- defp do_start_child_scene(dynamic_supervisor, ref, mod, args, opts, true) do opts = Keyword.put(opts, :has_children, true) # start the scene supervision tree {:ok, supervisor_pid} = DynamicSupervisor.start_child( dynamic_supervisor, {Scenic.Scene.Supervisor, {mod, args, opts}} ) # we want to return the pid of the scene itself. not the supervisor scene_pid = Supervisor.which_children(supervisor_pid) |> Enum.find_value(fn {_, pid, :worker, [Scenic.Scene]} -> pid _ -> nil end) {:ok, scene_pid, ref} end # -------------------------------------------------------- defp do_start_child_scene(dynamic_supervisor, ref, mod, args, opts, false) do opts = Keyword.put(opts, :has_children, true) {:ok, pid} = DynamicSupervisor.start_child( dynamic_supervisor, {Scenic.Scene, {mod, args, opts}} ) {:ok, pid, ref} end # ============================================================================ # push_graph if Scenic.mix_env() == :test do def test_push_graph(graph, sub_id, state) do internal_push_graph(graph, sub_id, state) end end # -------------------------------------------------------- # def internal_push_graph( {graph, sub_id}, state ) do # internal_push_graph( graph, sub_id, state ) # end # not set up for dynamic children. Take the fast path def internal_push_graph( %Graph{} = graph, sub_id, %{ has_children: false, scene_ref: scene_ref } = state ) do graph_key = {:graph, scene_ref, sub_id} # reduce the incoming graph to its minimal form # while simultaneously extracting the SceneRefs {graph, all_keys} = Enum.reduce(graph.primitives, {%{}, %{}}, fn # named reference {uid, %{module: Primitive.SceneRef, data: name} = p}, {g, all_refs} when is_atom(name) -> g = Map.put(g, uid, Primitive.minimal(p)) all_refs = Map.put(all_refs, uid, {:graph, name, nil}) {g, all_refs} # explicit reference {uid, %{module: Primitive.SceneRef, data: {:graph, _, _} = ref} = p}, {g, all_refs} -> g = Map.put(g, uid, Primitive.minimal(p)) all_refs = Map.put(all_refs, uid, ref) {g, all_refs} # dynamic reference # Log an error and remove the ref from the graph {_uid, %{module: Primitive.SceneRef, data: {_, _} = ref}}, {g, all_refs} -> message = """ Attempting to manage dynamic reference on graph with "has_children set to false reference: #{inspect(ref)} """ raise Error, message: message {g, all_refs} # all non-SceneRef primitives {uid, p}, {g, all_refs} -> {Map.put(g, uid, Primitive.minimal(p)), all_refs} end) # insert the proper graph keys back into the graph to finish normalizing # it for the drivers. Yes, the driver could do this from the all_keys term # that is also being written into the :ets table, but it gets done all the # time for each reader and when consuming input, so it is better to do it # once here. Note that the all_keys term is still being written because # otherwise the drivers would need to do a full graph scan in order to prep # whatever translators they need. Again, the info has already been # calculated here, so just pass it along without throwing it out. graph = Enum.reduce(all_keys, graph, fn {uid, key}, g -> put_in(g, [uid, :data], {Scenic.Primitive.SceneRef, key}) end) # write the graph into the ets table ViewPort.Tables.insert_graph(graph_key, self(), graph, all_keys) # write the graph into the ets table # ViewPort.Tables.insert_graph(graph_key, self(), graph, all_keys) {:ok, state} end # -------------------------------------------------------- # push a graph to the ets table and manage embedded dynamic child scenes # to the reader: You have no idea how difficult this was to get right. def internal_push_graph( %Graph{} = raw_graph, sub_id, %{ has_children: true, scene_ref: scene_ref, raw_scene_refs: old_raw_refs, dyn_scene_pids: old_dyn_pids, dyn_scene_keys: old_dyn_keys, dynamic_children_pid: dyn_sup, viewport: viewport } = state ) do # reduce the incoming graph to its minimal form # while simultaneously extracting the SceneRefs # this should be the only full scan when pushing a graph {graph, all_keys, new_raw_refs} = Enum.reduce(raw_graph.primitives, {%{}, %{}, %{}}, fn # named reference {uid, %{module: Primitive.SceneRef, data: name} = p}, {g, all_refs, dyn_refs} when is_atom(name) -> g = Map.put(g, uid, Primitive.minimal(p)) all_refs = Map.put(all_refs, uid, {:graph, name, nil}) {g, all_refs, dyn_refs} # explicit reference {uid, %{module: Primitive.SceneRef, data: {:graph, _, _} = ref} = p}, {g, all_refs, dyn_refs} -> g = Map.put(g, uid, Primitive.minimal(p)) all_refs = Map.put(all_refs, uid, ref) {g, all_refs, dyn_refs} # dynamic reference # don't add to all_refs yet. Will add after it is started (or not) {uid, %{module: Primitive.SceneRef, data: {_, _} = ref} = p}, {g, all_refs, dyn_refs} -> g = Map.put(g, uid, Primitive.minimal(p)) dyn_refs = Map.put(dyn_refs, uid, ref) {g, all_refs, dyn_refs} # all non-SceneRef primitives {uid, p}, {g, all_refs, dyn_refs} -> {Map.put(g, uid, Primitive.minimal(p)), all_refs, dyn_refs} end) # get the difference script between the raw and new dynamic refs raw_diff = Utilities.Map.difference(old_raw_refs, new_raw_refs) # Use the difference script to determine what to start or stop. {new_dyn_pids, new_dyn_keys} = Enum.reduce(raw_diff, {old_dyn_pids, old_dyn_keys}, fn # start this dynamic scene {:put, uid, {mod, init_data}}, {old_pids, old_keys} -> unless dyn_sup do raise "You have set a dynamic SceneRef on a graph in a scene where has_children is false" end styles = Graph.style_stack(raw_graph, uid) # prepare the startup options to send to the new scene id = Map.get(raw_graph.primitives[uid], :id) init_opts = case viewport do nil -> [styles: styles, id: id] vp -> [viewport: vp, styles: styles, id: id] end # start the dynamic scene {:ok, pid, ref} = mod.start_dynamic_scene(dyn_sup, self(), init_data, init_opts) # tell the old scene to stop itself case old_pids[uid] do nil -> :ok old_pid -> GenServer.cast(old_pid, {:stop, dyn_sup}) end # add the this dynamic child scene to tracking { Map.put(old_pids, uid, pid), Map.put(old_keys, uid, {:graph, ref, nil}) } # stop this dynaic scene {:del, uid}, {old_pids, old_keys} -> # get the old dynamic graph reference pid = old_pids[uid] # send the optional deactivate message and terminate. ok to be async Task.start(fn -> GenServer.call(pid, :deactivate) GenServer.cast(pid, {:stop, dyn_sup}) end) # remove old pid and key {Map.delete(old_pids, uid), Map.delete(old_keys, uid)} end) # merge all_refs with the managed dyanmic keys all_keys = Map.merge(all_keys, new_dyn_keys) graph_key = {:graph, scene_ref, sub_id} # insert the proper graph keys back into the graph to finish normalizing # it for the drivers. Yes, the driver could do this from the all_keys term # that is also being written into the :ets table, but it gets done all the # time for each reader and when consuming input, so it is better to do it # once here. Note that the all_keys term is still being written because # otherwise the drivers would need to do a full graph scan in order to prep # whatever translators they need. Again, the info has already been # calculated here, so just pass it along without throwing it out. graph = Enum.reduce(all_keys, graph, fn {uid, key}, g -> put_in(g, [uid, :data], {Scenic.Primitive.SceneRef, key}) end) # write the graph into the ets table ViewPort.Tables.insert_graph(graph_key, self(), graph, all_keys) # store the refs for next time state = state |> Map.put(:raw_scene_refs, new_raw_refs) |> Map.put(:dyn_scene_pids, new_dyn_pids) |> Map.put(:dyn_scene_keys, new_dyn_keys) {:ok, state} end # ============================================================================ # response management defp deal_with_noreply(type, state, sc_state, opts \\ nil) do case deal_with_response_opts(opts, state) do {nil, state} -> {type, %{state | scene_state: sc_state}} {opt, state} -> {type, %{state | scene_state: sc_state}, opt} end end defp deal_with_reply(reply, state, sc_state, opts \\ nil) defp deal_with_reply(reply, state, sc_state, opts) do case deal_with_response_opts(opts, state) do {nil, state} -> {:reply, reply, %{state | scene_state: sc_state}} {opt, state} -> {:reply, reply, %{state | scene_state: sc_state}, opt} end end defp deal_with_response_opts(opts, state) defp deal_with_response_opts(nil, state), do: {nil, state} defp deal_with_response_opts(timeout, state) when is_integer(timeout), do: {timeout, state} defp deal_with_response_opts({:continue, term}, state), do: {{:continue, term}, state} defp deal_with_response_opts(opts, state) when is_list(opts) do {:ok, state} = case opts[:push] do %Graph{} = graph -> internal_push_graph(graph, nil, state) {%Graph{} = graph, sub_id} -> internal_push_graph(graph, sub_id, state) _ -> {:ok, state} end opts |> Keyword.delete(:push) |> case do [{:timeout, timeout}] -> {timeout, state} [{:continue, term}] -> {{:continue, term}, state} _ -> {nil, state} end end end
36.348089
101
0.613138