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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1ce2470cbe5cfccb28f45fa65303950e9e5e6e92 | 1,070 | ex | Elixir | lib/ex_ftx/orders/modify_by_order_id.ex | RaghavSood/ex_ftx | 257ba35221abe4957836eb6e8312ecae0d9d51aa | [
"MIT"
] | 3 | 2021-09-27T17:19:41.000Z | 2022-03-16T09:28:13.000Z | lib/ex_ftx/orders/modify_by_order_id.ex | RaghavSood/ex_ftx | 257ba35221abe4957836eb6e8312ecae0d9d51aa | [
"MIT"
] | 3 | 2021-07-28T19:53:02.000Z | 2021-09-27T15:48:38.000Z | lib/ex_ftx/orders/modify_by_order_id.ex | RaghavSood/ex_ftx | 257ba35221abe4957836eb6e8312ecae0d9d51aa | [
"MIT"
] | 4 | 2021-08-01T11:25:58.000Z | 2021-10-11T22:15:44.000Z | defmodule ExFtx.Orders.ModifyByOrderId do
alias ExFtx.JsonResponse
@type credentials :: ExFtx.Credentials.t()
@type modify_order_payload :: ExFtx.ModifyOrderPayload.t()
@type order :: ExFtx.Order.t()
@type result :: {:ok, order} | {:error, String.t() | :parse_result_item}
@spec post(credentials, ExFtx.Order.id(), modify_order_payload) :: result
def post(credentials, order_id, modify_order_payload) do
"/orders/#{order_id}/modify"
|> ExFtx.HTTPClient.auth_post(credentials, to_payload(modify_order_payload))
|> parse_response()
end
defp to_payload(modify_order_payload) do
modify_order_payload
|> Map.from_struct()
|> ProperCase.to_camel_case()
end
defp parse_response({:ok, %JsonResponse{success: true, result: order}}) do
order
|> Mapail.map_to_struct(ExFtx.Order, transformations: [:snake_case])
|> case do
{:ok, _} = result -> result
_ -> {:error, :parse_result_item}
end
end
defp parse_response({:ok, %JsonResponse{success: false, error: error}}) do
{:error, error}
end
end
| 30.571429 | 80 | 0.696262 |
1ce24ba528d2485d2e29ea8ad88e41b2ffe64144 | 1,938 | ex | Elixir | integration-tests/mysql-client-tests/elixir/lib/simple.ex | HassanAlsamahi/dolt | 8328916026f9ccab8fc396d2e60c40f6c8384a5b | [
"Apache-2.0"
] | 8,776 | 2020-09-24T22:14:40.000Z | 2022-03-31T20:26:02.000Z | integration-tests/mysql-client-tests/elixir/lib/simple.ex | HassanAlsamahi/dolt | 8328916026f9ccab8fc396d2e60c40f6c8384a5b | [
"Apache-2.0"
] | 1,177 | 2020-09-26T02:49:35.000Z | 2022-03-31T22:00:23.000Z | integration-tests/mysql-client-tests/elixir/lib/simple.ex | HassanAlsamahi/dolt | 8328916026f9ccab8fc396d2e60c40f6c8384a5b | [
"Apache-2.0"
] | 247 | 2020-10-05T19:25:29.000Z | 2022-03-30T17:40:45.000Z | defmodule SmokeTest do
def myTestFunc(arg1, arg2) do
if arg1 != arg2 do
raise "Test error"
end
end
@spec run :: nil
def run do
args = System.argv()
user = Enum.at(args, 0)
{port, _} = Integer.parse(Enum.at(args, 1))
database = Enum.at(args, 2)
{:ok, pid} = MyXQL.start_link(username: user, port: port, database: database)
{:ok, _} = MyXQL.query(pid, "drop table if exists test")
{:ok, _} = MyXQL.query(pid, "create table test (pk int, `value` int, primary key(pk))")
{:ok, _} = MyXQL.query(pid, "describe test")
{:ok, result} = MyXQL.query(pid, "select * from test")
myTestFunc(result.num_rows, 0)
{:ok, _} = MyXQL.query(pid, "insert into test (pk, `value`) values (0,0)")
# MyXQL uses the CLIENT_FOUND_ROWS flag so we should return the number of rows matched
{:ok, result} = MyXQL.query(pid, "UPDATE test SET pk = pk where pk = 0")
myTestFunc(result.num_rows, 1)
{:ok, result} = MyXQL.query(pid, "INSERT INTO test VALUES (0, 0) ON DUPLICATE KEY UPDATE `value` = `value`")
myTestFunc(result.num_rows, 1)
{:ok, result} = MyXQL.query(pid, "SELECT * FROM test")
myTestFunc(result.num_rows, 1)
myTestFunc(result.rows, [[0,0]])
{:ok, _} = MyXQL.query(pid, "select dolt_add('-A');")
{:ok, _} = MyXQL.query(pid, "select dolt_commit('-m', 'my commit')")
{:ok, _} = MyXQL.query(pid, "select COUNT(*) FROM dolt_log")
{:ok, _} = MyXQL.query(pid, "select dolt_checkout('-b', 'mybranch')")
{:ok, _} = MyXQL.query(pid, "insert into test (pk, `value`) values (1,1)")
{:ok, _} = MyXQL.query(pid, "select dolt_commit('-a', '-m', 'my commit2')")
{:ok, _} = MyXQL.query(pid, "select dolt_checkout('main')")
{:ok, _} = MyXQL.query(pid, "select dolt_merge('mybranch')")
{:ok, result} = MyXQL.query(pid, "select COUNT(*) FROM dolt_log")
myTestFunc(result.num_rows, 1)
myTestFunc(result.rows, [[3]])
end
end
| 38.76 | 112 | 0.615583 |
1ce274485ad2306a56abad97a18cc007b856d258 | 6,860 | ex | Elixir | lib/plugin_manager/state/plugin_state.ex | mishka-group/mishka_installer | ab19e3e1e8aaa984ec48d6277a77d567eb5f61ea | [
"Apache-2.0"
] | 3 | 2022-03-18T14:32:15.000Z | 2022-03-24T06:33:21.000Z | lib/plugin_manager/state/plugin_state.ex | mishka-group/mishka_installer | ab19e3e1e8aaa984ec48d6277a77d567eb5f61ea | [
"Apache-2.0"
] | 3 | 2022-03-25T08:30:42.000Z | 2022-03-27T17:13:46.000Z | lib/plugin_manager/state/plugin_state.ex | mishka-group/mishka_installer | ab19e3e1e8aaa984ec48d6277a77d567eb5f61ea | [
"Apache-2.0"
] | null | null | null | defmodule MishkaInstaller.PluginState do
use GenServer
require Logger
alias MishkaInstaller.PluginStateDynamicSupervisor, as: PSupervisor
alias MishkaInstaller.Plugin
alias __MODULE__
defstruct [:name, :event, priority: 1, status: :started, depend_type: :soft, depends: [], extra: [], parent_pid: nil]
@type params() :: map()
@type id() :: String.t()
@type module_name() :: String.t()
@type event_name() :: String.t()
@type plugin() :: %PluginState{
name: module_name(),
event: event_name(),
priority: integer(),
status: :started | :stopped | :restarted,
depend_type: :soft | :hard,
parent_pid: any(),
depends: list(String.t()),
extra: list(map())
}
@type t :: plugin()
def start_link(args) do
{id, type, parent_pid} = {Map.get(args, :id), Map.get(args, :type), Map.get(args, :parent_pid)}
GenServer.start_link(__MODULE__, default(id, type, parent_pid), name: via(id, type))
end
def child_spec(process_name) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [process_name]},
restart: :transient,
max_restarts: 4
}
end
defp default(plugin_name, event, parent_pid) do
%PluginState{name: plugin_name, event: event, parent_pid: parent_pid}
end
@spec push(MishkaInstaller.PluginState.t()) :: :ok | {:error, :push, any}
def push(%PluginState{} = element) do
case PSupervisor.start_job(%{id: element.name, type: element.event, parent_pid: element.parent_pid}) do
{:ok, status, pid} -> GenServer.cast(pid, {:push, status, element})
{:error, result} -> {:error, :push, result}
end
end
@spec push_call(MishkaInstaller.PluginState.t()) :: :ok | {:error, :push, any}
def push_call(%PluginState{} = element) do
case PSupervisor.start_job(%{id: element.name, type: element.event, parent_pid: element.parent_pid}) do
{:ok, status, pid} ->
if Mix.env() == :test, do: Logger.warn("Plugin State of #{element.name} is being pushed")
GenServer.call(pid, {:push, status, element})
{:error, result} -> {:error, :push, result}
end
end
@spec get([{:module, module_name()}]) :: plugin() | {:error, :get, :not_found}
def get(module: module_name) do
case PSupervisor.get_plugin_pid(module_name) do
{:ok, :get_plugin_pid, pid} -> GenServer.call(pid, {:pop, :module})
{:error, :get_plugin_pid} -> {:error, :get, :not_found}
end
end
def get_all(event: event_name) do
PSupervisor.running_imports(event_name) |> Enum.map(&get(module: &1.id))
end
def get_all() do
PSupervisor.running_imports() |> Enum.map(&get(module: &1.id))
end
def delete(module: module_name) do
case PSupervisor.get_plugin_pid(module_name) do
{:ok, :get_plugin_pid, pid} ->
GenServer.cast(pid, {:delete, :module})
{:ok, :delete}
{:error, :get_plugin_pid} -> {:error, :delete, :not_found}
end
end
def delete(event: event_name) do
PSupervisor.running_imports(event_name) |> Enum.map(&delete(module: &1.id))
end
def delete_child(module: module_name) do
case PSupervisor.get_plugin_pid(module_name) do
{:ok, :get_plugin_pid, pid} -> DynamicSupervisor.terminate_child(PluginStateOtpRunner, pid)
{:error, :get_plugin_pid} -> {:error, :delete, :not_found}
end
end
def terminate_all_pids() do
Enum.map(PSupervisor.running_imports(), fn item ->
GenServer.cast(item.pid, {:delete, :module})
end)
end
def stop(module: module_name) do
case PSupervisor.get_plugin_pid(module_name) do
{:ok, :get_plugin_pid, pid} ->
GenServer.cast(pid, {:stop, :module})
{:ok, :stop}
{:error, :get_plugin_pid} -> {:error, :stop, :not_found}
end
end
def stop(event: event_name) do
PSupervisor.running_imports(event_name) |> Enum.map(&stop(module: &1.id))
end
# Callbacks
@impl true
def init(%PluginState{} = state) do
if Mix.env == :test, do: MishkaInstaller.Database.Helper.get_parent_pid(state)
Logger.info("#{Map.get(state, :name)} from #{Map.get(state, :event)} event of Plugins manager system was started")
{:ok, state, {:continue, {:sync_with_database, :take}}}
end
@impl true
def handle_call({:pop, :module}, _from, %PluginState{} = state) do
{:reply, state, state}
end
@impl true
def handle_call({:push, _status, %PluginState{} = element}, _from, %PluginState{} = _state) do
element
|> Map.from_struct()
|> Plugin.add_or_edit_by_name()
{:reply, element, element}
end
@impl true
def handle_cast({:push, status, %PluginState{} = element}, _state) do
{:noreply, element, {:continue, {:sync_with_database, status}}}
end
@impl true
def handle_cast({:stop, :module}, %PluginState{} = state) do
new_state = Map.merge(state, %{status: :stopped})
{:noreply, new_state, {:continue, {:sync_with_database, :edit}}}
end
@impl true
def handle_cast({:delete, :module}, %PluginState{} = state) do
MishkaInstaller.plugin_activity("destroy", state, "high", "report")
{:stop, :normal, state}
end
@impl true
def handle_continue({:sync_with_database, _status}, %PluginState{} = state) do
state
|> Map.from_struct()
|> Plugin.add_or_edit_by_name()
|> check_output(state)
{:noreply, state}
end
@impl true
def handle_continue({:sync_with_database, :take}, %PluginState{} = state) do
state =
case Plugin.show_by_name("#{state.name}") do
{:ok, :get_record_by_field, _error_atom, record_info} ->
struct(__MODULE__, Map.from_struct(record_info))
{:error, _result, _error_atom} -> state
end
{:noreply, state}
end
if Mix.env() in [:test, :dev] do
@impl true
def handle_info({:DOWN, _ref, :process, _pid, _reason}, state) do
# log that this happened, etc. Don't use Repo!
{:stop, :normal, state}
end
end
@impl true
def terminate(reason, %PluginState{} = state) do
MishkaInstaller.plugin_activity("read", state, "high", "throw")
if reason != :normal do
Task.Supervisor.start_child(PluginEtsTask, fn -> MishkaInstaller.PluginETS.sync_with_database() end)
Logger.warn(
"#{Map.get(state, :name)} from #{Map.get(state, :event)} event of Plugins manager was Terminated,
Reason of Terminate #{inspect(reason)}"
)
end
end
defp via(id, value) do
{:via, Registry, {PluginStateRegistry, id, value}}
end
defp check_output({:error, status, _, _} = _output, %PluginState{} = state) do
MishkaInstaller.plugin_activity("#{status}", state, "high", "error")
end
defp check_output({:ok, status, _, _} = _output, %PluginState{} = state) do
action = cond do
status == :add -> "add"
state.status == :stopped -> "delete"
true -> "edit"
end
MishkaInstaller.plugin_activity(action, state, "high")
end
end
| 32.358491 | 119 | 0.650146 |
1ce28bcf41c9ceed8d204ed45a07a7876f085a9d | 787 | ex | Elixir | api/lib/grook/web/guardian/error_handler.ex | ukita/grook | add716bf92fcde35b941ea8067933c28c192e01e | [
"MIT"
] | 3 | 2017-05-22T13:28:13.000Z | 2018-06-29T16:39:19.000Z | api/lib/grook/web/guardian/error_handler.ex | ukita/grook | add716bf92fcde35b941ea8067933c28c192e01e | [
"MIT"
] | null | null | null | api/lib/grook/web/guardian/error_handler.ex | ukita/grook | add716bf92fcde35b941ea8067933c28c192e01e | [
"MIT"
] | null | null | null | defmodule Grook.Guardian.ErrorHandler do
import Plug.Conn
def unauthenticated(conn, _params) do
respond(conn, :json, 401, "Unauthenticated")
end
def unauthorized(conn, _params) do
respond(conn, :json, 403, "Unauthorized")
end
def no_resource(conn, _params) do
respond(conn, :json, 403, "Unauthorized")
end
defp respond(conn, :json, status, msg) do
try do
conn
|> configure_session(drop: true)
|> put_resp_content_type("application/json")
|> send_resp(status, encode_message(msg))
rescue ArgumentError ->
conn
|> put_resp_content_type("application/json")
|> send_resp(status, encode_message(msg))
end
end
defp encode_message(message) do
Poison.encode!(%{errors: %{detail: [message]}})
end
end
| 23.848485 | 51 | 0.674714 |
1ce29286c529e6d22a9d70f86c8ab4f96cbe135f | 1,070 | ex | Elixir | lib/credo/cli/command/info/info_command.ex | jlgeering/credo | b952190ed758c262aa0d9bbee01227f9b1f0c63b | [
"MIT"
] | null | null | null | lib/credo/cli/command/info/info_command.ex | jlgeering/credo | b952190ed758c262aa0d9bbee01227f9b1f0c63b | [
"MIT"
] | null | null | null | lib/credo/cli/command/info/info_command.ex | jlgeering/credo | b952190ed758c262aa0d9bbee01227f9b1f0c63b | [
"MIT"
] | null | null | null | defmodule Credo.CLI.Command.Info.InfoCommand do
use Credo.CLI.Command
alias Credo.CLI.Command.Info.InfoOutput
alias Credo.CLI.Task
alias Credo.Execution
@shortdoc "Show useful debug information"
@moduledoc @shortdoc
@doc false
def call(%Execution{help: true} = exec, _opts), do: InfoOutput.print_help(exec)
def call(exec, _opts) do
exec
|> run_task(Task.LoadAndValidateSourceFiles)
|> run_task(Task.PrepareChecksToRun)
|> print_info()
end
defp print_info(exec) do
InfoOutput.print(exec, info(exec))
exec
end
defp info(exec) do
%{
"system" => %{
"credo" => Credo.version(),
"elixir" => System.version(),
"erlang" => System.otp_release()
},
"config" => %{
"checks" => checks(exec),
"files" => files(exec)
}
}
end
defp checks(exec) do
exec.checks
|> Enum.map(fn
{name} -> name
{name, _} -> name
end)
end
defp files(exec) do
exec
|> Execution.get_source_files()
|> Enum.map(& &1.filename)
end
end
| 19.454545 | 81 | 0.603738 |
1ce29665d5909b0c3807eabb369c21885c1dc0ed | 3,192 | ex | Elixir | broker/lib/broker/ledger.ex | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | 1 | 2019-02-04T21:09:16.000Z | 2019-02-04T21:09:16.000Z | broker/lib/broker/ledger.ex | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | null | null | null | broker/lib/broker/ledger.ex | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | null | null | null | defmodule Broker.Ledger do
use GenServer
# GenServer state is a map of
# EventID is the tuple of {type, source, id}
# types -> {eventType -> [EventID]}
# events -> {EventId -> event}
# children -> %{{type, source, id} -> %{trigger -> EventID}}
# children = {{trigger, [{type, source, id}]}}
def start_link(_opts \\ []) do
state = {Map.new(), Map.new(), Map.new()}
GenServer.start_link(__MODULE__, state, name: Ledger)
end
def init(args) do
{%{}, %{}, %{}} = args
{:ok, args}
end
def handle_call({:events_by_type, type}, _from, {types, events, children}) do
rtn_events = Map.get(types, type)
{:reply, rtn_events, {types, events, children}}
end
def handle_call({:get_event, eid = {_type, _source, _id}}, _from, {types, events, children}) do
event = Map.get(events, eid)
{:reply, event, {types, events, children}}
end
def handle_call({:get_children, eid = {_type, _source, _id}}, _from, {types, events, children}) do
rtn_children = Map.get(children, eid)
{:reply, rtn_children, {types, events, children}}
end
def handle_cast({:add_child, parentEventId, trigger}, {types, events, children}) do
children = record_children(children, parentEventId, trigger, [])
IO.puts("LEDGER\n#{inspect types}\n#{inspect events}\n#{inspect children}")
{:noreply, {types, events, children}}
end
def handle_cast({:add_child, parentEventId, trigger, replies}, {types, events, children}) when is_list(replies) do
# Record that trigger was run and event ID of what was returned.
children = record_children(children, parentEventId, trigger, replies)
IO.puts("LEDGER\n#{inspect types}\n#{inspect events}\n#{inspect children}")
{:noreply, {types, events, children}}
end
def handle_cast({:record, event}, {types, events, children}) do
type = CloudEvent.type(event)
source = CloudEvent.source(event)
id = CloudEvent.id(event)
ensure_key(types, type, [])
{_, types} = Map.get_and_update(types, type,
fn
nil -> {nil, [{type, source, id}]}
list -> {list, list ++ [{type, source, id}]}
end)
events = Map.put(events, {type, source, id}, event)
children = ensure_key(children, {type, source, id}, %{})
IO.puts("LEDGER\n#{inspect types}\n#{inspect events}\n#{inspect children}")
{:noreply, {types, events, children}}
end
defp ensure_key(map, key, default) do
case Map.get(map, key) do
nil -> Map.put(map, key, default)
_ -> map
end
end
defp record_children(children, parentEventId, trigger, events) when is_list(events) do
children = ensure_key(children, parentEventId, %{})
childEntry = Map.get(children, parentEventId)
|> ensure_key(trigger, [])
childEventIdList = Map.get(childEntry, trigger)
|> add_child_event_ids(events)
# Put this all back in.
Map.put(children, parentEventId, Map.put(childEntry, trigger, childEventIdList))
end
defp add_child_event_ids(list, []), do: list
defp add_child_event_ids(list, [event | rest]) do
add_child_event_ids(
list ++ [{CloudEvent.type(event), CloudEvent.source(event), CloudEvent.id(event)}],
rest)
end
end
| 35.076923 | 116 | 0.653195 |
1ce2af06b87675dd73a9e956284ab0c10729582e | 2,820 | ex | Elixir | web/models/tariff_plan.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/models/tariff_plan.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/models/tariff_plan.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | defmodule CgratesWebJsonapi.TariffPlan do
use CgratesWebJsonapi.Web, :model
schema "tariff_plans" do
field :alias, :string
field :name, :string
field :description, :string
has_many :tp_account_actions, CgratesWebJsonapi.TpAccountAction, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_action_plans, CgratesWebJsonapi.TpActionPlan, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_actions, CgratesWebJsonapi.TpAction, foreign_key: :tpid, references: :alias, on_delete: :delete_all
has_many :tp_action_triggers, CgratesWebJsonapi.TpActionTrigger, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_aliases, CgratesWebJsonapi.TpAlias, foreign_key: :tpid, references: :alias, on_delete: :delete_all
has_many :tp_cdr_stats, CgratesWebJsonapi.TpCdrStat, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_destination_rates, CgratesWebJsonapi.TpDestinationRate, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_destinations, CgratesWebJsonapi.TpDestination, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_filters, CgratesWebJsonapi.TpFilter, foreign_key: :tpid, references: :alias, on_delete: :delete_all
has_many :tp_lcr_rules, CgratesWebJsonapi.TpLcrRule, foreign_key: :tpid, references: :alias, on_delete: :delete_all
has_many :tp_rates, CgratesWebJsonapi.TpRate, foreign_key: :tpid, references: :alias, on_delete: :delete_all
has_many :tp_rating_plans, CgratesWebJsonapi.TpRatingPlan, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_rating_profiles, CgratesWebJsonapi.TpRatingProfile, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_resources, CgratesWebJsonapi.TpResource, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_suppliers, CgratesWebJsonapi.TpSupplier, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :stats, CgratesWebJsonapi.TpStat, foreign_key: :tpid, references: :alias,
on_delete: :delete_all
has_many :tp_timing, CgratesWebJsonapi.TpTiming, foreign_key: :tpid, references: :alias, on_delete: :delete_all
has_many :tp_threshold, CgratesWebJsonapi.TpThreshold, foreign_key: :tpid, references: :alias, on_delete: :delete_all
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:alias, :name, :description])
|> validate_required([:alias, :name])
|> unique_constraint(:alias)
|> unique_constraint(:name)
|> validate_length(:alias, max: 64)
end
end
| 52.222222 | 121 | 0.748936 |
1ce2df1f192cf9768b4da3886c62632e271263b9 | 197 | exs | Elixir | priv/repo/migrations/20180925202650_change_telegram_id_to_string.exs | elitau/page_change_notifier | 55c02ef0a464040d98cf416c131e39e7a09df975 | [
"MIT"
] | null | null | null | priv/repo/migrations/20180925202650_change_telegram_id_to_string.exs | elitau/page_change_notifier | 55c02ef0a464040d98cf416c131e39e7a09df975 | [
"MIT"
] | null | null | null | priv/repo/migrations/20180925202650_change_telegram_id_to_string.exs | elitau/page_change_notifier | 55c02ef0a464040d98cf416c131e39e7a09df975 | [
"MIT"
] | null | null | null | defmodule PageChangeNotifier.Repo.Migrations.ChangeTelegramIdToString do
use Ecto.Migration
def change do
alter table(:users) do
modify(:telegram_chat_id, :string)
end
end
end
| 19.7 | 72 | 0.751269 |
1ce33815442a1f0a1d0bc514d6adbc60854b05b3 | 1,535 | ex | Elixir | lib/cadet/jobs/autograder/utilities.ex | Hou-Rui/cadet | f9036d76005bf3b267b632dce176067ae1a19f71 | [
"Apache-2.0"
] | null | null | null | lib/cadet/jobs/autograder/utilities.ex | Hou-Rui/cadet | f9036d76005bf3b267b632dce176067ae1a19f71 | [
"Apache-2.0"
] | 2 | 2020-04-22T09:06:38.000Z | 2020-04-22T09:15:33.000Z | lib/cadet/jobs/autograder/utilities.ex | Hou-Rui/cadet | f9036d76005bf3b267b632dce176067ae1a19f71 | [
"Apache-2.0"
] | 1 | 2020-06-01T03:26:02.000Z | 2020-06-01T03:26:02.000Z | defmodule Cadet.Autograder.Utilities do
@moduledoc """
This module defines functions that support the autograder functionality.
"""
use Cadet, :context
require Logger
import Ecto.Query
alias Cadet.Accounts.User
alias Cadet.Assessments.{Answer, Assessment, Question, Submission}
def dispatch_programming_answer(answer = %Answer{}, question = %Question{}) do
# This should never fail
answer =
answer
|> Answer.autograding_changeset(%{autograding_status: :processing})
|> Repo.update!()
Que.add(Cadet.Autograder.LambdaWorker, %{question: question, answer: answer})
end
def fetch_submissions(assessment_id) when is_ecto_id(assessment_id) do
User
|> where(role: "student")
|> join(
:left,
[u],
s in Submission,
on: u.id == s.student_id and s.assessment_id == ^assessment_id
)
|> select([u, s], %{student_id: u.id, submission: s})
|> Repo.all()
end
def fetch_assessments_due_yesterday do
Assessment
|> where(is_published: true)
|> where([a], a.close_at < ^Timex.now() and a.close_at >= ^Timex.shift(Timex.now(), days: -1))
|> where([a], a.type != "contest")
|> join(:inner, [a], q in assoc(a, :questions))
|> preload([_, q], questions: q)
|> Repo.all()
|> Enum.map(&sort_assessment_questions(&1))
end
def sort_assessment_questions(assessment = %Assessment{}) do
sorted_questions = Enum.sort_by(assessment.questions, & &1.id)
Map.put(assessment, :questions, sorted_questions)
end
end
| 28.962264 | 98 | 0.663192 |
1ce36c5b270908e71931948e5782dc70306b7935 | 1,705 | exs | Elixir | test/list_test.exs | openapi-ro/annotations | a141164235d68d20b52ef199e342b5b9bf130acb | [
"WTFPL"
] | null | null | null | test/list_test.exs | openapi-ro/annotations | a141164235d68d20b52ef199e342b5b9bf130acb | [
"WTFPL"
] | null | null | null | test/list_test.exs | openapi-ro/annotations | a141164235d68d20b52ef199e342b5b9bf130acb | [
"WTFPL"
] | null | null | null | defmodule ListTest do
alias Annotations.Annotation
alias Annotations.List
use ExUnit.Case
#doctest Annotations
@alphabet "abcdefghijklmnopqrstuvwxyz"
@ro_alphabet "aăâbcdefghiîjklmnopqrsștțuvwxyz"
test "add tag by regex" do
str = @alphabet
annotations= List.tag(str, ~r/[aeiou]/u, :vowel)
vowels=
annotations
|> Enum.map(
fn ann->
assert ann.tags==[:vowel]
Annotation.str(ann,str)
end)
|> Enum.join("")
assert vowels=="aeiou"
end
test "invert tags" do
str = @alphabet <> "012345\n"
annotations= (
List.tag(str, ~r/[aeiou]/iu, :vowel)++
List.tag(str, ~r/[^[:alpha:]]+/iu, :non_alpha)
)
consonants=
List.tag_all_except(str, annotations, :consonant)
|> Enum.map(&(Annotation.str(&1,str)))
|> Enum.join("")
assert String.length(consonants) == 26-5
assert consonants == "bcdfghjklmnpqrstvwxyz"
end
test "UTF8 add tag by regex" do
str = @ro_alphabet
annotations= List.tag(str, ~r/[aăâeiîou]/u, :vowel)
vowels=
annotations
|> Enum.map(
fn ann->
assert ann.tags==[:vowel]
Annotation.str(ann,str)
end)
|> Enum.join("")
assert vowels=="aăâeiîou"
end
test "UTF8 invert tags" do
str = @ro_alphabet <> "012345\n"
annotations= (
List.tag(str, ~r/[aăâeiîou]/iu, :vowel)++
List.tag(str, ~r/[^[:alpha:]]+/iu, :non_alpha)
)
consonants=
List.tag_all_except(str, annotations, :consonant)
|> Enum.map(&(Annotation.str(&1,str)))
|> Enum.join("")
assert String.length(consonants) == 31-8
assert consonants == "bcdfghjklmnpqrsștțvwxyz"
end
end | 27.5 | 55 | 0.597067 |
1ce38edbcb92d4478a0f77697f3d5ccf0469d635 | 2,351 | ex | Elixir | lib/livebook/runtime/embedded.ex | kianmeng/livebook | 8fe8d27d3d46b64d22126d1b97157330b87e611c | [
"Apache-2.0"
] | null | null | null | lib/livebook/runtime/embedded.ex | kianmeng/livebook | 8fe8d27d3d46b64d22126d1b97157330b87e611c | [
"Apache-2.0"
] | null | null | null | lib/livebook/runtime/embedded.ex | kianmeng/livebook | 8fe8d27d3d46b64d22126d1b97157330b87e611c | [
"Apache-2.0"
] | null | null | null | defmodule Livebook.Runtime.Embedded do
@moduledoc false
# A runtime backed by the same node Livebook is running in.
#
# This runtime is reserved for specific use cases,
# where there is no option of starting a separate
# Elixir runtime.
defstruct [:node, :server_pid]
@type t :: %__MODULE__{
node: node(),
server_pid: pid()
}
alias Livebook.Runtime.ErlDist
@doc """
Initializes new runtime by starting the necessary
processes within the current node.
"""
@spec init() :: {:ok, t()}
def init() do
# As we run in the Livebook node, all the necessary modules
# are in place, so we just start the manager process.
# We make it anonymous, so that multiple embedded runtimes
# can be started (for different notebooks).
# We also disable cleanup, as we don't want to unload any
# modules or revert the configuration (because other runtimes
# may rely on it). If someone uses embedded runtimes,
# this cleanup is not particularly important anyway.
# We tell manager to not override :standard_error,
# as we already do it for the Livebook application globally
# (see Livebook.Application.start/2).
server_pid = ErlDist.initialize(node(), unload_modules_on_termination: false)
{:ok, %__MODULE__{node: node(), server_pid: server_pid}}
end
end
defimpl Livebook.Runtime, for: Livebook.Runtime.Embedded do
alias Livebook.Runtime.ErlDist
def connect(runtime) do
ErlDist.RuntimeServer.set_owner(runtime.server_pid, self())
Process.monitor(runtime.server_pid)
end
def disconnect(runtime) do
ErlDist.RuntimeServer.stop(runtime.server_pid)
end
def evaluate_code(runtime, code, locator, prev_locator, opts \\ []) do
ErlDist.RuntimeServer.evaluate_code(runtime.server_pid, code, locator, prev_locator, opts)
end
def forget_evaluation(runtime, locator) do
ErlDist.RuntimeServer.forget_evaluation(runtime.server_pid, locator)
end
def drop_container(runtime, container_ref) do
ErlDist.RuntimeServer.drop_container(runtime.server_pid, container_ref)
end
def handle_intellisense(runtime, send_to, ref, request, locator) do
ErlDist.RuntimeServer.handle_intellisense(runtime.server_pid, send_to, ref, request, locator)
end
def duplicate(_runtime) do
Livebook.Runtime.Embedded.init()
end
end
| 31.77027 | 97 | 0.729051 |
1ce395d63d43c53664fd62fe7d3bca0ffeeec54a | 2,564 | exs | Elixir | mix.exs | SophieDeBenedetto/elixir-companies | d81111b6e9e4a93cde3aede0af180453a953dfd1 | [
"MIT"
] | null | null | null | mix.exs | SophieDeBenedetto/elixir-companies | d81111b6e9e4a93cde3aede0af180453a953dfd1 | [
"MIT"
] | null | null | null | mix.exs | SophieDeBenedetto/elixir-companies | d81111b6e9e4a93cde3aede0af180453a953dfd1 | [
"MIT"
] | null | null | null | defmodule Companies.MixProject do
use Mix.Project
def project do
[
app: :companies,
version: "0.1.0",
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [coveralls: :test, "coveralls.html": :test],
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Companies.Application, []},
extra_applications: [:appsignal, :logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:appsignal, "~> 1.13"},
{:bamboo, "~> 1.4"},
{:ecto_sql, "~> 3.4"},
{:gettext, "~> 0.17"},
{:html_sanitize_ex, "~> 1.4.0"},
{:httpoison, "~> 1.6"},
{:jason, "~> 1.1"},
{:phoenix, "~> 1.5.1", override: true},
{:phoenix_ecto, "~> 4.1"},
{:phoenix_html, "~> 2.14"},
{:phoenix_live_dashboard, "~> 0.2"},
{:phoenix_pubsub, "~> 2.0"},
{:plug_cowboy, "~> 2.2"},
{:postgrex, ">= 0.0.0"},
{:scrivener_ecto, "~> 2.3"},
{:scrivener_html, "~> 1.8"},
{:set_locale, "~> 0.2.8"},
{:timex, "~> 3.6.1"},
{:ueberauth, "~> 0.6.3"},
{:ueberauth_github, "~> 0.8.0"},
{:bypass, "~> 1.0", only: :test},
{:ex_machina, "~> 2.4", only: :test},
{:excoveralls, "~> 0.12", only: :test},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:earmark, "~> 1.4"},
{:credo, "~> 1.4.0", only: [:dev, :test], runtime: false}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: [
"format --check-formatted --check-equivalent --dry-run",
"compile --warnings-as-errors",
"ecto.drop --quiet",
"ecto.create --quiet",
"ecto.migrate --quiet",
"test"
]
]
end
end
| 29.136364 | 79 | 0.542512 |
1ce3adbca4544797c5d5d4e70e305f46741a98b7 | 1,101 | ex | Elixir | installer/templates/new/lib/app_name.ex | raspo/phoenix | 438b74255e7a4d68b4eaf1a295d0fcd201c71421 | [
"MIT"
] | null | null | null | installer/templates/new/lib/app_name.ex | raspo/phoenix | 438b74255e7a4d68b4eaf1a295d0fcd201c71421 | [
"MIT"
] | null | null | null | installer/templates/new/lib/app_name.ex | raspo/phoenix | 438b74255e7a4d68b4eaf1a295d0fcd201c71421 | [
"MIT"
] | null | null | null | defmodule <%= app_module %> do
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [<%= if ecto do %>
# Start the Ecto repository
supervisor(<%= app_module %>.Repo, []),<% end %>
# Start the endpoint when the application starts
supervisor(<%= app_module %>.Endpoint, []),
# Start your own worker by calling: <%= app_module %>.Worker.start_link(arg1, arg2, arg3)
# worker(<%= app_module %>.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: <%= app_module %>.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
<%= app_module %>.Endpoint.config_change(changed, removed)
:ok
end
end
| 34.40625 | 95 | 0.676658 |
1ce3ce577b9f83b86f95ccc3b8127e86bdaa5ecb | 254 | exs | Elixir | Books/Programming_Elixir-Dave_Thomas/ch_14/spawn/pmap.exs | cjschneider2/book_example_problems | 18192a6d3ddb4371b79f88e4ab3444d25f2e1ce0 | [
"Unlicense"
] | null | null | null | Books/Programming_Elixir-Dave_Thomas/ch_14/spawn/pmap.exs | cjschneider2/book_example_problems | 18192a6d3ddb4371b79f88e4ab3444d25f2e1ce0 | [
"Unlicense"
] | null | null | null | Books/Programming_Elixir-Dave_Thomas/ch_14/spawn/pmap.exs | cjschneider2/book_example_problems | 18192a6d3ddb4371b79f88e4ab3444d25f2e1ce0 | [
"Unlicense"
] | null | null | null | defmodule Parallel do
def pmap(collection, fun) do
me = self
collection
|> Enum.map( fn (elem) -> spawn_link fn -> (send me, {self, fun.(elem)}) end end )
|> Enum.map( fn (pid) -> receive do {^pid, result} -> result end end )
end
end
| 28.222222 | 86 | 0.602362 |
1ce40f0be706bc82ff4036ba00c7ae85d5b5f7a2 | 154 | exs | Elixir | test/test_helper.exs | wholroyd/fake-elixir | 9d67431d12da9f3500fd62a000d76408c40f3b66 | [
"Apache-2.0"
] | null | null | null | test/test_helper.exs | wholroyd/fake-elixir | 9d67431d12da9f3500fd62a000d76408c40f3b66 | [
"Apache-2.0"
] | null | null | null | test/test_helper.exs | wholroyd/fake-elixir | 9d67431d12da9f3500fd62a000d76408c40f3b66 | [
"Apache-2.0"
] | null | null | null | ExUnit.start
Mix.Task.run "ecto.create", ["--quiet"]
Mix.Task.run "ecto.migrate", ["--quiet"]
Ecto.Adapters.SQL.begin_test_transaction(FakeElixir.Repo)
| 22 | 57 | 0.733766 |
1ce425a1cf2c2907e7e93318d05f02ac07ecbbe0 | 2,266 | ex | Elixir | clients/datastream/lib/google_api/datastream/v1/model/oracle_profile.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/datastream/lib/google_api/datastream/v1/model/oracle_profile.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/datastream/lib/google_api/datastream/v1/model/oracle_profile.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Datastream.V1.Model.OracleProfile do
@moduledoc """
Oracle database profile.
## Attributes
* `connectionAttributes` (*type:* `map()`, *default:* `nil`) - Connection string attributes
* `databaseService` (*type:* `String.t`, *default:* `nil`) - Required. Database for the Oracle connection.
* `hostname` (*type:* `String.t`, *default:* `nil`) - Required. Hostname for the Oracle connection.
* `password` (*type:* `String.t`, *default:* `nil`) - Required. Password for the Oracle connection.
* `port` (*type:* `integer()`, *default:* `nil`) - Port for the Oracle connection, default value is 1521.
* `username` (*type:* `String.t`, *default:* `nil`) - Required. Username for the Oracle connection.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:connectionAttributes => map() | nil,
:databaseService => String.t() | nil,
:hostname => String.t() | nil,
:password => String.t() | nil,
:port => integer() | nil,
:username => String.t() | nil
}
field(:connectionAttributes, type: :map)
field(:databaseService)
field(:hostname)
field(:password)
field(:port)
field(:username)
end
defimpl Poison.Decoder, for: GoogleApi.Datastream.V1.Model.OracleProfile do
def decode(value, options) do
GoogleApi.Datastream.V1.Model.OracleProfile.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Datastream.V1.Model.OracleProfile do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.548387 | 110 | 0.688879 |
1ce4462ca674929c07b6a72fdeff20820db9e978 | 781 | ex | Elixir | web/channels/routine_channel.ex | mcousillas6/BioMonitor | 312a903fe19751b6896aca9346340ea502397350 | [
"MIT"
] | null | null | null | web/channels/routine_channel.ex | mcousillas6/BioMonitor | 312a903fe19751b6896aca9346340ea502397350 | [
"MIT"
] | null | null | null | web/channels/routine_channel.ex | mcousillas6/BioMonitor | 312a903fe19751b6896aca9346340ea502397350 | [
"MIT"
] | null | null | null | defmodule BioMonitor.RoutineChannel do
@moduledoc """
Channel used to broadcast all updates for the sensors status.
* Sensor status updates.
* Errors.
"""
use BioMonitor.Web, :channel
intercept(["update", "alert", "started", "stopped"])
def join("routine", _payload, socket) do
{:ok, socket}
end
def handle_out("update", payload, socket) do
push socket, "update", payload
{:noreply, socket}
end
def handle_out("alert", payload, socket) do
push socket, "alert", payload
{:noreply, socket}
end
def handle_out("started", payload, socket) do
push socket, "started", payload
{:noreply, socket}
end
def handle_out("stopped", payload, socket) do
push socket, "stopped", payload
{:noreply, socket}
end
end
| 22.970588 | 65 | 0.659411 |
1ce45e8c508154780e8444007dbe73c0eb3b0759 | 382 | ex | Elixir | lib/radiator/task/supervisor.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 92 | 2019-01-03T11:46:23.000Z | 2022-02-19T21:28:44.000Z | lib/radiator/task/supervisor.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 350 | 2019-04-11T07:55:51.000Z | 2021-08-03T11:19:05.000Z | lib/radiator/task/supervisor.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 10 | 2019-04-18T12:47:27.000Z | 2022-01-25T20:49:15.000Z | defmodule Radiator.Task.Supervisor do
@moduledoc false
use Supervisor
def start_link(opts \\ []) do
Supervisor.start_link(__MODULE__, :ok, [name: __MODULE__] ++ opts)
end
@impl true
def init(_init_arg) do
children = [
Radiator.Task.TaskManager,
Radiator.Task.WorkerSupervisor
]
Supervisor.init(children, strategy: :one_for_one)
end
end
| 19.1 | 70 | 0.691099 |
1ce46267d7b82a79579c76130991461475a91b37 | 12,120 | ex | Elixir | lib/phoenix/live_dashboard/router.ex | geometerio/phoenix_live_dashboard | 349ab9e60e3a0fce7e35a024e1dddcc1715f1ed0 | [
"MIT"
] | null | null | null | lib/phoenix/live_dashboard/router.ex | geometerio/phoenix_live_dashboard | 349ab9e60e3a0fce7e35a024e1dddcc1715f1ed0 | [
"MIT"
] | 4 | 2021-03-04T13:00:52.000Z | 2021-03-12T12:42:09.000Z | deps/phoenix_live_dashboard/lib/phoenix/live_dashboard/router.ex | adrianomota/blog | ef3b2d2ed54f038368ead8234d76c18983caa75b | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveDashboard.Router do
@moduledoc """
Provides LiveView routing for LiveDashboard.
"""
@doc """
Defines a LiveDashboard route.
It expects the `path` the dashboard will be mounted at
and a set of options.
This will also generate a named helper called `live_dashboard_path/2`
which you can use to link directly to the dashboard, such as:
<%= link "Dashboard", to: live_dashboard_path(conn, :home) %>
Note you should only use `link/2` to link to the dashboard (and not
`live_redirect/live_link`, as it has to set its own session on first
render.
## Options
* `:live_socket_path` - Configures the socket path. it must match
the `socket "/live", Phoenix.LiveView.Socket` in your endpoint.
* `:csp_nonce_assign_key` - an assign key to find the CSP nonce
value used for assets. Supports either `atom()` or a map of
type `%{optional(:img) => atom(), optional(:script) => atom(), optional(:style) => atom()}`
* `:ecto_repos` - the repositories to show database information.
Currently only PSQL databases are supported. If you don't specify
but your app is running Ecto, we will try to auto-discover the
available repositories. You can disable this behavior by setting
`[]` to this option.
* `:env_keys` - Configures environment variables to display.
It is defined as a list of string keys. If not set, the environment
information will not be displayed
* `:home_app` - A tuple with the app name and version to show on
the home page. Defaults to `{"Dashboard", :phoenix_live_dashboard}`
* `:metrics` - Configures the module to retrieve metrics from.
It can be a `module` or a `{module, function}`. If nothing is
given, the metrics functionality will be disabled. If `false` is
passed, then the menu item won't be visible.
* `:metrics_history` - Configures a callback for retrieving metric history.
It must be an "MFA" tuple of `{Module, :function, arguments}` such as
metrics_history: {MyStorage, :metrics_history, []}
If not set, metrics will start out empty/blank and only display
data that occurs while the browser page is open.
* `:request_logger` - By default the Request Logger page is enabled. Passing
`false` will disable this page.
* `:request_logger_cookie_domain` - Configures the domain the request_logger
cookie will be written to. It can be a string or `:parent` atom.
When a string is given, it will directly set cookie domain to the given
value. When `:parent` is given, it will take the parent domain from current
endpoint host (if host is "www.acme.com" the cookie will be scoped on
"acme.com"). When not set, the cookie will be scoped to current domain.
* `:allow_destructive_actions` - When true, allow destructive actions directly
from the UI. Defaults to `false`. The following destructive actions are
available in the dashboard:
* "Kill process" - a "Kill process" button on the process modal
Note that custom pages given to "Additional pages" may support their own
destructive actions.
* `:additional_pages` - A keyword list of additional pages
## Examples
defmodule MyAppWeb.Router do
use Phoenix.Router
import Phoenix.LiveDashboard.Router
scope "/", MyAppWeb do
pipe_through [:browser]
live_dashboard "/dashboard",
metrics: {MyAppWeb.Telemetry, :metrics},
env_keys: ["APP_USER", "VERSION"],
metrics_history: {MyStorage, :metrics_history, []},
request_logger_cookie_domain: ".acme.com"
end
end
"""
defmacro live_dashboard(path, opts \\ []) do
quote bind_quoted: binding() do
scope path, alias: false, as: false do
{session_name, session_opts, route_opts} = Phoenix.LiveDashboard.Router.__options__(opts)
import Phoenix.LiveView.Router, only: [live: 4, live_session: 3]
live_session session_name, session_opts do
# All helpers are public contracts and cannot be changed
live "/", Phoenix.LiveDashboard.PageLive, :home, route_opts
live "/:page", Phoenix.LiveDashboard.PageLive, :page, route_opts
live "/:node/:page", Phoenix.LiveDashboard.PageLive, :page, route_opts
end
end
end
end
@doc false
def __options__(options) do
live_socket_path = Keyword.get(options, :live_socket_path, "/live")
metrics =
case options[:metrics] do
nil ->
nil
false ->
:skip
mod when is_atom(mod) ->
{mod, :metrics}
{mod, fun} when is_atom(mod) and is_atom(fun) ->
{mod, fun}
other ->
raise ArgumentError,
":metrics must be a tuple with {Mod, fun}, " <>
"such as {MyAppWeb.Telemetry, :metrics}, got: #{inspect(other)}"
end
env_keys =
case options[:env_keys] do
nil ->
nil
keys when is_list(keys) ->
keys
other ->
raise ArgumentError,
":env_keys must be a list of strings, got: " <> inspect(other)
end
home_app =
case options[:home_app] do
nil ->
{"Dashboard", :phoenix_live_dashboard}
{app_title, app_name} when is_binary(app_title) and is_atom(app_name) ->
{app_title, app_name}
other ->
raise ArgumentError,
":home_app must be a tuple with a binary title and atom app, got: " <>
inspect(other)
end
metrics_history =
case options[:metrics_history] do
nil ->
nil
{module, function, args}
when is_atom(module) and is_atom(function) and is_list(args) ->
{module, function, args}
other ->
raise ArgumentError,
":metrics_history must be a tuple of {module, function, args}, got: " <>
inspect(other)
end
additional_pages =
case options[:additional_pages] do
nil ->
[]
pages when is_list(pages) ->
normalize_additional_pages(pages)
other ->
raise ArgumentError, ":additional_pages must be a keyword, got: " <> inspect(other)
end
request_logger_cookie_domain =
case options[:request_logger_cookie_domain] do
nil ->
nil
domain when is_binary(domain) ->
domain
:parent ->
:parent
other ->
raise ArgumentError,
":request_logger_cookie_domain must be a binary or :parent atom, got: " <>
inspect(other)
end
request_logger_flag =
case options[:request_logger] do
nil ->
true
bool when is_boolean(bool) ->
bool
other ->
raise ArgumentError,
":request_logger must be a boolean, got: " <> inspect(other)
end
request_logger = {request_logger_flag, request_logger_cookie_domain}
ecto_repos = options[:ecto_repos]
ecto_psql_extras_options =
case options[:ecto_psql_extras_options] do
nil ->
[]
args ->
unless Keyword.keyword?(args) and
args |> Keyword.values() |> Enum.all?(&Keyword.keyword?/1) do
raise ArgumentError,
":ecto_psql_extras_options must be a keyword where each value is a keyword, got: " <>
inspect(args)
end
args
end
csp_nonce_assign_key =
case options[:csp_nonce_assign_key] do
nil -> nil
key when is_atom(key) -> %{img: key, style: key, script: key}
%{} = keys -> Map.take(keys, [:img, :style, :script])
end
allow_destructive_actions = options[:allow_destructive_actions] || false
session_args = [
env_keys,
home_app,
allow_destructive_actions,
metrics,
metrics_history,
additional_pages,
request_logger,
ecto_repos,
ecto_psql_extras_options,
csp_nonce_assign_key
]
{
options[:live_session_name] || :live_dashboard,
[
session: {__MODULE__, :__session__, session_args},
root_layout: {Phoenix.LiveDashboard.LayoutView, :dash}
],
[
private: %{live_socket_path: live_socket_path, csp_nonce_assign_key: csp_nonce_assign_key},
as: :live_dashboard
]
}
end
defp normalize_additional_pages(pages) do
Enum.map(pages, fn
{path, module} when is_atom(path) and is_atom(module) ->
{path, {module, []}}
{path, {module, args}} when is_atom(path) and is_atom(module) ->
{path, {module, args}}
other ->
msg =
"invalid value in :additional_pages, " <>
"must be a tuple {path, {module, args}} or {path, module}, where path " <>
"is an atom and the module implements Phoenix.LiveDashboard.PageBuilder, got: "
raise ArgumentError, msg <> inspect(other)
end)
end
@doc false
def __session__(
conn,
env_keys,
home_app,
allow_destructive_actions,
metrics,
metrics_history,
additional_pages,
request_logger,
ecto_repos,
ecto_psql_extras_options,
csp_nonce_assign_key
) do
ecto_session = %{
repos: ecto_repos(ecto_repos),
ecto_psql_extras_options: ecto_psql_extras_options
}
{pages, requirements} =
[
home: {Phoenix.LiveDashboard.HomePage, %{env_keys: env_keys, home_app: home_app}},
os_mon: {Phoenix.LiveDashboard.OSMonPage, %{}}
]
|> Enum.concat(metrics_page(metrics, metrics_history))
|> Enum.concat(request_logger_page(conn, request_logger))
|> Enum.concat(
applications: {Phoenix.LiveDashboard.ApplicationsPage, %{}},
processes: {Phoenix.LiveDashboard.ProcessesPage, %{}},
ports: {Phoenix.LiveDashboard.PortsPage, %{}},
sockets: {Phoenix.LiveDashboard.SocketsPage, %{}},
ets: {Phoenix.LiveDashboard.EtsPage, %{}},
ecto_stats: {Phoenix.LiveDashboard.EctoStatsPage, ecto_session}
)
|> Enum.concat(additional_pages)
|> Enum.map(fn {key, {module, opts}} ->
{session, requirements} = initialize_page(module, opts)
{{key, {module, session}}, requirements}
end)
|> Enum.unzip()
%{
"pages" => pages,
"allow_destructive_actions" => allow_destructive_actions,
"requirements" => requirements |> Enum.concat() |> Enum.uniq(),
"csp_nonces" => %{
img: conn.assigns[csp_nonce_assign_key[:img]],
style: conn.assigns[csp_nonce_assign_key[:style]],
script: conn.assigns[csp_nonce_assign_key[:script]]
}
}
end
defp metrics_page(:skip, _), do: []
defp metrics_page(metrics, metrics_history) do
session = %{
metrics: metrics,
metrics_history: metrics_history
}
[metrics: {Phoenix.LiveDashboard.MetricsPage, session}]
end
defp request_logger_page(_conn, {false, _}), do: []
defp request_logger_page(conn, {true, cookie_domain}) do
session = %{
request_logger: Phoenix.LiveDashboard.RequestLogger.param_key(conn),
cookie_domain: cookie_domain
}
[request_logger: {Phoenix.LiveDashboard.RequestLoggerPage, session}]
end
defp ecto_repos(nil), do: nil
defp ecto_repos(false), do: []
defp ecto_repos(repos), do: List.wrap(repos)
defp initialize_page(module, opts) do
case module.init(opts) do
{:ok, session} ->
{session, []}
{:ok, session, requirements} ->
validate_requirements(module, requirements)
{session, requirements}
end
end
defp validate_requirements(module, requirements) do
Enum.each(requirements, fn
{key, value} when key in [:application, :module, :process] and is_atom(value) ->
:ok
other ->
raise "unknown requirement #{inspect(other)} from #{inspect(module)}"
end)
end
end
| 31.156812 | 103 | 0.62302 |
1ce4862f2edb9c8624b91e4ac805e40f5c219518 | 6,417 | ex | Elixir | lib/commerce_cure/data_type/payment_card.ex | auroche/commerce_cure | 82e2d60d1044f86dd2f491f4713a31132d709ccf | [
"MIT"
] | null | null | null | lib/commerce_cure/data_type/payment_card.ex | auroche/commerce_cure | 82e2d60d1044f86dd2f491f4713a31132d709ccf | [
"MIT"
] | null | null | null | lib/commerce_cure/data_type/payment_card.ex | auroche/commerce_cure | 82e2d60d1044f86dd2f491f4713a31132d709ccf | [
"MIT"
] | null | null | null | defmodule CommerceCure.PaymentCard do
alias __MODULE__
alias CommerceCure.PaymentCardNumber
alias CommerceCure.{ExpiryDate, Year, Month, Name}
@type t :: %__MODULE__{
number: PaymentCardNumber.number,
first_name: Name.first_name,
last_name: Name.last_name,
month: Month.month,
year: Year.year,
brand: PaymentCardNumber.brand,
verification_value: String.t
}
@enforce_keys [:number]
defstruct ~w(first_name last_name month year brand number verification_value)a
@moduledoc """
can cast parameters
first_name last_name month year brand number verification_value name full_name expiry_date
"""
@doc """
iex> PaymentCard.new(4242424242424242)
{:ok, %PaymentCard{number: "4242424242424242", brand: :visa}}
iex> PaymentCard.new("4242424242424242")
{:ok, %PaymentCard{number: "4242424242424242", brand: :visa}}
iex> PaymentCard.new(%{number: 4242424242424242, expiry_date: "02/17", name: "Commerce Cure", verification_value: "245"})
{:ok, %PaymentCard{number: "4242424242424242", brand: :visa, year: 2017, month: 2, first_name: "Commerce", last_name: "Cure", verification_value: "245"}}
iex> PaymentCard.new(%{number: 4242424242424242, expiry_date: "13/17", name: "Commerce Cure", verification_value: "245"})
{:error, :invalid_month}
"""
@spec new(integer | String.t | map) :: {:ok, t}
def new(number) when is_binary(number) or is_integer(number) do
case PaymentCardNumber.new(number) do
{:ok, %{brand: brand, number: number}} ->
{:ok, %__MODULE__{brand: brand, number: number}}
{:error, reason} ->
{:error, reason}
end
end
def new(%{number: number} = map) do
with {:ok, %{brand: brand, number: number}} <- PaymentCardNumber.new(number),
{:ok, %{year: year, month: month}} <- new_expiry(map),
{:ok, %{first_name: first_name, last_name: last_name}} <- new_name(map),
{:ok, %{verification_value: verification_value}} <- new_verification_value(map, brand)
do
{:ok, %__MODULE__{brand: brand, number: number,
year: year, month: month,
first_name: first_name, last_name: last_name,
verification_value: verification_value}}
end
end
def new(%{"number" => number} = map) do
map
|> Map.delete("number")
|> Map.put(:number, number)
|> new()
end
def new(list) when is_list(list) do
list
|> Enum.into(%{})
|> new()
end
@doc """
iex> %PaymentCard{number: "4242424242424242"}[:number]
"4242424242424242"
iex> %PaymentCard{number: "4242424242424242", year: 2015, month: 7}[:expiry_date]
"0715"
iex> %PaymentCard{number: "4242424242424242", first_name: "Commerce", last_name: "Cure"}[:name]
"Commerce Cure"
"""
# TODO: use bang functions and try{}
@spec fetch(t, atom) :: any
def fetch(payment_card, key)
def fetch(%PaymentCard{first_name: first, last_name: last}, :name) do
{:ok, full_name(%{first_name: first, last_name: last})}
end
def fetch(%PaymentCard{year: year, month: month}, :expiry_date) do
{:ok, expiry_date(%{year: year, month: month})}
end
def fetch(%__MODULE__{} = me, key) do
if value = Map.get(me, key),
do: {:ok, value},
else: :error
end
### Shortcuts
@doc """
iex> PaymentCard.full_name(%{first_name: "Commerce", last_name: "Cure"})
"Commerce Cure"
"""
defdelegate full_name(name, opt \\ :first), to: Name
@doc """
iex> PaymentCard.expiry_date(%{year: 2017, month: 5})
"0517"
"""
@spec expiry_date(t) :: String.t
def expiry_date(%{year: year, month: month}) do
ExpiryDate.format(%{year: year, month: month}, "MMYY")
end
# year, month > expiry_date
defp new_expiry(%{year: year, month: month}) do
with {:ok, %{year: year}} <- Year.new(year),
{:ok, %{month: month}} <- Month.new(month)
do
{:ok, %{year: year, month: month}}
end
end
defp new_expiry(%{"year" => year, "month" => month}) do
new_expiry(%{year: year, month: month})
end
defp new_expiry(%{expiry_date: expiry_date}) do
ExpiryDate.parse(expiry_date, "MM/YY")
end
defp new_expiry(%{"expiry_date" => expiry_date}) do
new_expiry(%{expiry_date: expiry_date})
end
defp new_expiry(_), do: {:ok, %{year: nil, month: nil}}
# first_name, last_name > name | full_name
defp new_name(%{first_name: first, last_name: last})
when is_binary(first) and is_binary(last)
do
Name.new(%{first_name: first, last_name: last})
end
defp new_name(%{"first_name" => first, "last_name" => last}) do
Name.new(%{first_name: first, last_name: last})
end
defp new_name(%{"name" => name}), do: Name.parse(name)
defp new_name(%{name: name}), do: Name.parse(name)
defp new_name(%{"full_name" => name}), do: Name.parse(name)
defp new_name(%{full_name: name}), do: Name.parse(name)
defp new_name(_), do: {:ok, %{first_name: nil, last_name: nil}}
### VERIFICATION VALUE
defp new_verification_value(%{verification_value: vv}, brand)
when is_binary(vv)
do
if verification_value?(vv, brand) do
{:ok, %{verification_value: vv}}
else
{:error, :invalid_verification_value}
end
end
defp new_verification_value(%{"verification_value" => vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(%{"vv" => vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(%{"cvv" => vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(%{"cvc" => vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(%{vv: vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(%{cvv: vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(%{cvc: vv}, brand) do
new_verification_value(%{verification_value: vv}, brand)
end
defp new_verification_value(_, _), do: {:ok, %{verification_value: nil}}
defp verification_value?(vv, brand) do
if brand == :american_express do
String.length(vv) == 4
else
String.length(vv) == 3
end
end
end
| 34.875 | 155 | 0.64672 |
1ce4a843ffb75bbbb2befb315a00e0396c173c67 | 327 | ex | Elixir | lib/nsq/producer_supervisor.ex | amokan/elixir_nsq | 26e9cdf8f6c99b6688e540181a501f53aa5e9e4b | [
"MIT"
] | 89 | 2015-11-17T01:15:02.000Z | 2022-01-31T20:17:17.000Z | lib/nsq/producer_supervisor.ex | amokan/elixir_nsq | 26e9cdf8f6c99b6688e540181a501f53aa5e9e4b | [
"MIT"
] | 20 | 2016-06-17T14:15:22.000Z | 2019-09-23T13:31:18.000Z | lib/nsq/producer_supervisor.ex | amokan/elixir_nsq | 26e9cdf8f6c99b6688e540181a501f53aa5e9e4b | [
"MIT"
] | 33 | 2016-01-28T15:20:43.000Z | 2021-12-18T14:36:19.000Z | defmodule NSQ.ProducerSupervisor do
use Supervisor
def start_link(topic, config, opts \\ []) do
Supervisor.start_link(__MODULE__, {topic, config}, opts)
end
def init({topic, config}) do
children = [
worker(NSQ.Producer, [topic, config])
]
supervise(children, strategy: :one_for_one)
end
end
| 19.235294 | 60 | 0.675841 |
1ce4ccde59afab7ad4dbc2dc4a48cd604647fe05 | 1,716 | ex | Elixir | clients/games/lib/google_api/games/v1/model/room_client_address.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/room_client_address.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/room_client_address.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Games.V1.Model.RoomClientAddress do
@moduledoc """
This is a JSON template for the client address when setting up a room.
## Attributes
- kind (String.t): Uniquely identifies the type of this resource. Value is always the fixed string games#roomClientAddress. Defaults to: `null`.
- xmppAddress (String.t): The XMPP address of the client on the Google Games XMPP network. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => any(),
:xmppAddress => any()
}
field(:kind)
field(:xmppAddress)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.RoomClientAddress do
def decode(value, options) do
GoogleApi.Games.V1.Model.RoomClientAddress.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.RoomClientAddress do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.647059 | 146 | 0.738928 |
1ce517a3783a028afe8e6a179134c7575a65d95b | 6,582 | ex | Elixir | clients/run/lib/google_api/run/v1/model/policy.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/model/policy.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/model/policy.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Run.V1.Model.Policy do
@moduledoc """
An Identity and Access Management (IAM) policy, which specifies access
controls for Google Cloud resources.
A `Policy` is a collection of `bindings`. A `binding` binds one or more
`members` to a single `role`. Members can be user accounts, service accounts,
Google groups, and domains (such as G Suite). A `role` is a named list of
permissions; each `role` can be an IAM predefined role or a user-created
custom role.
For some types of Google Cloud resources, a `binding` can also specify a
`condition`, which is a logical expression that allows access to a resource
only if the expression evaluates to `true`. A condition can add constraints
based on attributes of the request, the resource, or both. To learn which
resources support conditions in their IAM policies, see the
[IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
**JSON example:**
{
"bindings": [
{
"role": "roles/resourcemanager.organizationAdmin",
"members": [
"user:mike@example.com",
"group:admins@example.com",
"domain:google.com",
"serviceAccount:my-project-id@appspot.gserviceaccount.com"
]
},
{
"role": "roles/resourcemanager.organizationViewer",
"members": [
"user:eve@example.com"
],
"condition": {
"title": "expirable access",
"description": "Does not grant access after Sep 2020",
"expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')",
}
}
],
"etag": "BwWWja0YfJA=",
"version": 3
}
**YAML example:**
bindings:
- members:
- user:mike@example.com
- group:admins@example.com
- domain:google.com
- serviceAccount:my-project-id@appspot.gserviceaccount.com
role: roles/resourcemanager.organizationAdmin
- members:
- user:eve@example.com
role: roles/resourcemanager.organizationViewer
condition:
title: expirable access
description: Does not grant access after Sep 2020
expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
- etag: BwWWja0YfJA=
- version: 3
For a description of IAM and its features, see the
[IAM documentation](https://cloud.google.com/iam/docs/).
## Attributes
* `auditConfigs` (*type:* `list(GoogleApi.Run.V1.Model.AuditConfig.t)`, *default:* `nil`) - Specifies cloud audit logging configuration for this policy.
* `bindings` (*type:* `list(GoogleApi.Run.V1.Model.Binding.t)`, *default:* `nil`) - Associates a list of `members` to a `role`. Optionally, may specify a
`condition` that determines how and when the `bindings` are applied. Each
of the `bindings` must contain at least one member.
* `etag` (*type:* `String.t`, *default:* `nil`) - `etag` is used for optimistic concurrency control as a way to help
prevent simultaneous updates of a policy from overwriting each other.
It is strongly suggested that systems make use of the `etag` in the
read-modify-write cycle to perform policy updates in order to avoid race
conditions: An `etag` is returned in the response to `getIamPolicy`, and
systems are expected to put that etag in the request to `setIamPolicy` to
ensure that their change will be applied to the same version of the policy.
**Important:** If you use IAM Conditions, you must include the `etag` field
whenever you call `setIamPolicy`. If you omit this field, then IAM allows
you to overwrite a version `3` policy with a version `1` policy, and all of
the conditions in the version `3` policy are lost.
* `version` (*type:* `integer()`, *default:* `nil`) - Specifies the format of the policy.
Valid values are `0`, `1`, and `3`. Requests that specify an invalid value
are rejected.
Any operation that affects conditional role bindings must specify version
`3`. This requirement applies to the following operations:
* Getting a policy that includes a conditional role binding
* Adding a conditional role binding to a policy
* Changing a conditional role binding in a policy
* Removing any role binding, with or without a condition, from a policy
that includes conditions
**Important:** If you use IAM Conditions, you must include the `etag` field
whenever you call `setIamPolicy`. If you omit this field, then IAM allows
you to overwrite a version `3` policy with a version `1` policy, and all of
the conditions in the version `3` policy are lost.
If a policy does not include any conditions, operations on that policy may
specify any valid version or leave the field unset.
To learn which resources support conditions in their IAM policies, see the
[IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:auditConfigs => list(GoogleApi.Run.V1.Model.AuditConfig.t()),
:bindings => list(GoogleApi.Run.V1.Model.Binding.t()),
:etag => String.t(),
:version => integer()
}
field(:auditConfigs, as: GoogleApi.Run.V1.Model.AuditConfig, type: :list)
field(:bindings, as: GoogleApi.Run.V1.Model.Binding, type: :list)
field(:etag)
field(:version)
end
defimpl Poison.Decoder, for: GoogleApi.Run.V1.Model.Policy do
def decode(value, options) do
GoogleApi.Run.V1.Model.Policy.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Run.V1.Model.Policy do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.658228 | 157 | 0.674719 |
1ce524628983c907008b4597b823605cffc6e950 | 2,825 | ex | Elixir | lib/day11.ex | ntwyman/aoc_2019 | 444dfd58ce9272d79a511785d24d5ba8443a2dfa | [
"MIT"
] | null | null | null | lib/day11.ex | ntwyman/aoc_2019 | 444dfd58ce9272d79a511785d24d5ba8443a2dfa | [
"MIT"
] | null | null | null | lib/day11.ex | ntwyman/aoc_2019 | 444dfd58ce9272d79a511785d24d5ba8443a2dfa | [
"MIT"
] | null | null | null | defmodule Day11 do
defmodule Pos do
defstruct x: 0, y: 0
end
@spec do_turn(atom, integer) :: atom
defp do_turn(direction, turn) do
case turn do
# left
0 ->
case direction do
:up -> :left
:right -> :up
:down -> :right
:left -> :down
end
# right
1 ->
case direction do
:up -> :right
:right -> :down
:down -> :left
:left -> :up
end
end
end
@spec advance(Pos.t(), atom) :: Pos.t()
defp advance(position, direction) do
case direction do
:up -> %Pos{x: position.x, y: position.y + 1}
:right -> %Pos{x: position.x + 1, y: position.y}
:down -> %Pos{x: position.x, y: position.y - 1}
:left -> %Pos{x: position.x - 1, y: position.y}
end
end
@spec robot_loop(map(), Pos.t(), atom, pid) :: map()
def robot_loop(paint_map, position, direction, int_pid) do
# Send the position of the current square
color = Map.get(paint_map, position, 0)
# IO.puts("Color of {#{position.x}, #{position.y}} - #{color}")
send(int_pid, {:value, color})
new_map =
receive do
{:value, c} ->
# IO.puts("Coloring {#{position.x}, #{position.y}} - #{c}")
Map.put(paint_map, position, c)
end
new_dir =
receive do
{:value, turn} ->
# IO.puts("Turning: #{turn}")
do_turn(direction, turn)
end
# IO.puts("#{new_dir}: #{position.x}, #{position.y}")
send(int_pid, {:is_halted})
is_halted =
receive do
{:halted, is_halted} -> is_halted
end
if is_halted,
do: new_map,
else: robot_loop(new_map, advance(position, new_dir), new_dir, int_pid)
end
@spec part1(String.t()) :: integer
def part1(file_name) do
int_pid =
Files.read_integers!(file_name)
|> IntComp.run_as_process([], self())
send(int_pid, {:run})
paint_job = robot_loop(%{}, %Pos{}, :up, int_pid)
length(Map.keys(paint_job))
end
@spec part2(String.t()) :: String.t()
def part2(file_name) do
int_pid =
Files.read_integers!(file_name)
|> IntComp.run_as_process([], self())
send(int_pid, {:run})
paint_job = robot_loop(%{%Pos{} => 1}, %Pos{}, :up, int_pid)
{e_min_x, e_min_y, e_max_x, e_max_y} =
Enum.reduce(
Map.keys(paint_job),
{0, 0, 0, 0},
fn tile, {min_x, min_y, max_x, max_y} ->
{min(min_x, tile.x), min(min_y, tile.y), max(max_x, tile.x), max(max_y, tile.y)}
end
)
lines =
Enum.map(e_max_y..e_min_y, fn y ->
to_string(
for x <- e_min_x..e_max_x,
do: if(Map.get(paint_job, %Pos{x: x, y: y}, 0) == 1, do: ?*, else: 0x20)
)
end)
Enum.join(lines, "\n")
end
end
| 24.565217 | 90 | 0.532389 |
1ce57a45e5e1d2447964d40b184e853b8af456bb | 509 | ex | Elixir | example/lib/live_phone_example_web/views/error_view.ex | workwithmax/live_phone | 1a5482a9032735dd201f2468643145f1ee0a3588 | [
"MIT"
] | 3 | 2021-02-28T22:27:58.000Z | 2021-12-08T03:18:10.000Z | example/lib/live_phone_example_web/views/error_view.ex | whitepaperclip/live_phone | bda5d554dd7d3df313fa15cd71eb2bcb8acda897 | [
"MIT"
] | 25 | 2021-02-26T16:15:46.000Z | 2022-03-24T08:10:51.000Z | example/lib/live_phone_example_web/views/error_view.ex | workwithmax/live_phone | 1a5482a9032735dd201f2468643145f1ee0a3588 | [
"MIT"
] | 2 | 2020-11-27T17:33:52.000Z | 2021-01-25T16:05:16.000Z | defmodule LivePhoneExampleWeb.ErrorView do
use LivePhoneExampleWeb, :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.941176 | 61 | 0.744597 |
1ce57d9fe18273ebfa9278abac18725f6f1952dc | 1,953 | ex | Elixir | lib/web/controllers/sync_controller.ex | leonardocouy/accent | 29fb324395ff998cc5cdc6947c60070ffabe647c | [
"BSD-3-Clause"
] | null | null | null | lib/web/controllers/sync_controller.ex | leonardocouy/accent | 29fb324395ff998cc5cdc6947c60070ffabe647c | [
"BSD-3-Clause"
] | null | null | null | lib/web/controllers/sync_controller.ex | leonardocouy/accent | 29fb324395ff998cc5cdc6947c60070ffabe647c | [
"BSD-3-Clause"
] | null | null | null | defmodule Accent.SyncController do
use Plug.Builder
import Canary.Plugs
alias Movement.Builders.ProjectSync, as: SyncBuilder
alias Movement.Persisters.ProjectSync, as: SyncPersister
alias Movement.Comparers.Sync, as: SyncComparer
alias Accent.Project
alias Accent.Hook.Context, as: HookContext
plug(Plug.Assign, canary_action: :sync)
plug(:load_and_authorize_resource, model: Project, id_name: "project_id")
plug(Accent.Plugs.EnsureUnlockedFileOperations)
plug(Accent.Plugs.MovementContextParser)
plug(:assign_comparer)
plug(:create)
@broadcaster Application.get_env(:accent, :hook_broadcaster)
@doc """
Create new sync for a project
## Endpoint
GET /sync
### Required params
- `project_id`
- `file`
- `document_path`
- `document_format`
### Response
#### Success
`200` - Ok.
#### Error
`404` - Unknown project
"""
def create(conn, _) do
conn.assigns[:movement_context]
|> Movement.Context.assign(:project, conn.assigns[:project])
|> Movement.Context.assign(:user_id, conn.assigns[:current_user].id)
|> SyncBuilder.build()
|> SyncPersister.persist()
|> case do
{:ok, {_context, []}} ->
send_resp(conn, :ok, "")
{:ok, {context, _operations}} ->
@broadcaster.fanout(%HookContext{
event: "sync",
project: conn.assigns[:project],
user: conn.assigns[:current_user],
payload: %{
batch_operation_stats: context.assigns[:batch_operation].stats,
document_path: context.assigns[:document].path
}
})
send_resp(conn, :ok, "")
{:error, _reason} ->
send_resp(conn, :unprocessable_entity, "")
end
end
defp assign_comparer(conn, _) do
context =
conn.assigns[:movement_context]
|> Movement.Context.assign(:comparer, &SyncComparer.compare/2)
assign(conn, :movement_context, context)
end
end
| 25.038462 | 75 | 0.651306 |
1ce58ab250832f1e20ad8503a3b4a0ef0e4430fd | 289 | ex | Elixir | test/support/qux.ex | garthk/notion | 08c6288659c23e47f97fbd6c0a9dfbd8bc28019e | [
"MIT"
] | 12 | 2019-06-15T09:08:01.000Z | 2021-11-10T04:25:28.000Z | test/support/qux.ex | garthk/notion | 08c6288659c23e47f97fbd6c0a9dfbd8bc28019e | [
"MIT"
] | 11 | 2019-06-16T01:38:25.000Z | 2022-02-13T06:21:51.000Z | test/support/qux.ex | garthk/notion | 08c6288659c23e47f97fbd6c0a9dfbd8bc28019e | [
"MIT"
] | 2 | 2019-06-16T05:43:22.000Z | 2022-02-09T00:31:30.000Z | defmodule Qux do
use Notion, name: :qux, metadata: %{region: "us-west"}
@moduledoc false
@doc "Received an HTTP Request"
@spec http_request(%{latency: integer}, %{}) :: :ok
defevent([:http, :request])
@spec users_signup(integer, %{}) :: :ok
defevent([:users, :signup])
end
| 24.083333 | 56 | 0.643599 |
1ce59b52c84c6eef24f35bf20ea159b335a072d0 | 2,114 | exs | Elixir | test/credo/check/warning/operation_on_same_values_test.exs | codeclimate-community/credo | b960a25d604b4499a2577321f9d61b39dc4b0437 | [
"MIT"
] | null | null | null | test/credo/check/warning/operation_on_same_values_test.exs | codeclimate-community/credo | b960a25d604b4499a2577321f9d61b39dc4b0437 | [
"MIT"
] | null | null | null | test/credo/check/warning/operation_on_same_values_test.exs | codeclimate-community/credo | b960a25d604b4499a2577321f9d61b39dc4b0437 | [
"MIT"
] | 1 | 2020-09-25T11:48:49.000Z | 2020-09-25T11:48:49.000Z | defmodule Credo.Check.Warning.OperationOnSameValuesTest do
use Credo.TestHelper
@described_check Credo.Check.Warning.OperationOnSameValues
#
# cases NOT raising issues
#
test "it should NOT report expected code" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
assert x == x + 2
end
end
"""
|> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report operator definitions" do
"""
defmodule Red do
@moduledoc false
@spec number - number :: number
def a - a do
a + 1
end
end
"""
|> to_source_file
|> refute_issues(@described_check)
end
test "it should NOT report for function calls" do
"""
defmodule Red do
def my_fun do
a() - a()
Float.round(((:rand.uniform - :rand.uniform) / 100), 13)
end
end
"""
|> to_source_file
|> refute_issues(@described_check)
end
#
# cases raising issues
#
test "it should report a violation for ==" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
assert x == x
end
end
"""
|> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation for module attributes" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
@a 5
@some_module_attribute @a - @a
end
"""
|> to_source_file
|> assert_issue(@described_check)
end
test "it should report a violation for all defined operations" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
x == x # always true
x >= x # always false
x <= x # always false
x != x # always false
x > x # always false
y / y # always 1
y - y # always 0
y -
y # on different lines
y - y + x
end
end
"""
|> to_source_file
|> assert_issues(@described_check, fn issues ->
assert 9 == Enum.count(issues)
end)
end
end
| 19.943396 | 67 | 0.578051 |
1ce5ce3d8e1eb5f9f89985883be37653ca0ba2c4 | 1,238 | ex | Elixir | lib/job_board_web/controllers/config_controller.ex | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | lib/job_board_web/controllers/config_controller.ex | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | lib/job_board_web/controllers/config_controller.ex | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | defmodule JobBoardWeb.ConfigController do
use JobBoardWeb, :controller
alias JobBoard.Siteconfigs
plug JobBoardWeb.Plugs.RequireAuth
plug JobBoardWeb.Plugs.RequireAdmin
def index(conn, _params) do
configs = Siteconfigs.list_configs()
render(conn, "index.html", configs: configs, pagetitle: "Config Index")
end
def show(conn, %{"id" => id}) do
config = Siteconfigs.get_config!(id)
render(conn, "show.html", config: config, pagetitle: "Site Config")
end
def edit(conn, %{"id" => id}) do
config = Siteconfigs.get_config!(id)
changeset = Siteconfigs.change_config(config)
render(conn, "edit.html", config: config, changeset: changeset, pagetitle: "Edit Config")
end
def update(conn, %{"id" => id, "config" => config_params}) do
config = Siteconfigs.get_config!(id)
Cachex.reset(:config)
case Siteconfigs.update_config(config, config_params) do
{:ok, config} ->
conn
|> put_flash(:info, "Config updated successfully.")
|> redirect(to: Routes.config_path(conn, :show, config))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "edit.html", config: config, changeset: changeset, pagetitle: "Edit Config")
end
end
end
| 29.47619 | 97 | 0.675283 |
1ce5d380510f5a262e6041feae31f8b115ffe078 | 730 | ex | Elixir | lib/obelisk/assets.ex | knewter/obelisk | 360425914d36c1c6094820ae035a4555a177ed00 | [
"MIT"
] | 1 | 2017-04-04T15:44:25.000Z | 2017-04-04T15:44:25.000Z | lib/obelisk/assets.ex | knewter/obelisk | 360425914d36c1c6094820ae035a4555a177ed00 | [
"MIT"
] | null | null | null | lib/obelisk/assets.ex | knewter/obelisk | 360425914d36c1c6094820ae035a4555a177ed00 | [
"MIT"
] | null | null | null | defmodule Obelisk.Assets do
alias Obelisk.Config
def copy, do: File.cp_r("./themes/#{Config.config.theme}/assets", "./build/assets")
def css_files do
File.ls!("./build/assets/css")
|> Enum.sort
|> Enum.map(&("assets/css/#{&1}"))
|> Enum.filter(&(!File.dir? "./build/#{&1}"))
end
def js_files do
File.ls!("./build/assets/js")
|> Enum.sort
|> Enum.map(&("assets/js/#{&1}"))
|> Enum.filter(&(!File.dir? "./build/#{&1}"))
end
def css do
css_files
|> Enum.map(&("<link rel=\"stylesheet\" href=\"#{&1}\" />"))
|> Enum.join("\n")
end
def js do
js_files
|> Enum.map(&("<script type=\"text/javascript\" src=\"#{&1}\"></script>"))
|> Enum.join("\n")
end
end
| 22.121212 | 85 | 0.541096 |
1ce61298e509bc3869295abf6ece14da44a4f727 | 3,160 | ex | Elixir | clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1beta/model/google_iam_v1_audit_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1beta/model/google_iam_v1_audit_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/policy_troubleshooter/lib/google_api/policy_troubleshooter/v1beta/model/google_iam_v1_audit_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditConfig do
@moduledoc """
Specifies the audit configuration for a service. The configuration determines which permission types are logged, and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service": "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com", "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [ "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also exempts jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging.
## Attributes
* `auditLogConfigs` (*type:* `list(GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditLogConfig.t)`, *default:* `nil`) - The configuration for logging of each type of permission.
* `service` (*type:* `String.t`, *default:* `nil`) - Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:auditLogConfigs =>
list(GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditLogConfig.t()) | nil,
:service => String.t() | nil
}
field(:auditLogConfigs,
as: GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditLogConfig,
type: :list
)
field(:service)
end
defimpl Poison.Decoder, for: GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditConfig do
def decode(value, options) do
GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.PolicyTroubleshooter.V1beta.Model.GoogleIamV1AuditConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.454545 | 1,106 | 0.754114 |
1ce616c25c2ac061963da6afa8ef0a53c3f4edfd | 847 | ex | Elixir | lib/ash_audit_log/transformers/add_relationship.ex | zimt28/ash_audit_log | cabb2cd19d3ca3139c8beaf17b16aa7dad339947 | [
"MIT"
] | null | null | null | lib/ash_audit_log/transformers/add_relationship.ex | zimt28/ash_audit_log | cabb2cd19d3ca3139c8beaf17b16aa7dad339947 | [
"MIT"
] | 2 | 2021-01-23T14:43:15.000Z | 2021-01-23T14:58:07.000Z | lib/ash_audit_log/transformers/add_relationship.ex | zimt28/ash_audit_log | cabb2cd19d3ca3139c8beaf17b16aa7dad339947 | [
"MIT"
] | null | null | null | defmodule AshAuditLog.Transformers.AddRelationship do
@moduledoc "Adds a relationship to the resource"
use Ash.Dsl.Transformer
import AshAuditLog, only: [private?: 1]
import AshAuditLog.Resource, only: [audit_log_module: 1]
alias Ash.Dsl.Transformer
def before?(Ash.Api.Transformers.EnsureResourcesCompiled), do: true
def before?(_), do: false
def transform(resource, dsl) do
dsl = Map.put_new(dsl, [:relationships], %{entities: [], opts: []})
relationship = %Ash.Resource.Relationships.HasMany{
destination: audit_log_module(resource),
destination_field: :resource_id,
name: :audit_logs,
private?: private?(resource),
source: resource,
source_field: :id,
writable?: false
}
dsl = Transformer.add_entity(dsl, [:relationships], relationship)
{:ok, dsl}
end
end
| 27.322581 | 71 | 0.696576 |
1ce6317760328afa6e6c4a48cc35f2530cca4935 | 112 | ex | Elixir | lib/domain/repo.ex | ideaMarcos/portishead | 0ad09af305e1e663c0d080a9637b8420d0f40fd1 | [
"MIT"
] | 3 | 2020-03-09T04:29:49.000Z | 2020-07-14T16:09:50.000Z | lib/domain/repo.ex | ideaMarcos/portishead | 0ad09af305e1e663c0d080a9637b8420d0f40fd1 | [
"MIT"
] | null | null | null | lib/domain/repo.ex | ideaMarcos/portishead | 0ad09af305e1e663c0d080a9637b8420d0f40fd1 | [
"MIT"
] | null | null | null | defmodule Portishead.Repo do
use Ecto.Repo,
otp_app: :portishead,
adapter: Ecto.Adapters.Postgres
end
| 18.666667 | 35 | 0.741071 |
1ce649d6f4781992e3c307a8367aa54b9136305d | 160 | exs | Elixir | day_1_inverse_captcha/elixir/inverse_captcha/test/inverse_captcha_test.exs | cjschneider2/advent_of_code_2017 | db7907ecb7df22a1173ec4162676a71f4e5d45e8 | [
"MIT"
] | null | null | null | day_1_inverse_captcha/elixir/inverse_captcha/test/inverse_captcha_test.exs | cjschneider2/advent_of_code_2017 | db7907ecb7df22a1173ec4162676a71f4e5d45e8 | [
"MIT"
] | null | null | null | day_1_inverse_captcha/elixir/inverse_captcha/test/inverse_captcha_test.exs | cjschneider2/advent_of_code_2017 | db7907ecb7df22a1173ec4162676a71f4e5d45e8 | [
"MIT"
] | null | null | null | defmodule InverseCaptchaTest do
use ExUnit.Case
doctest InverseCaptcha
test "greets the world" do
assert InverseCaptcha.hello() == :world
end
end
| 16 | 43 | 0.74375 |
1ce69b7b4389686dfdefe262fd067912f91f64d9 | 17,308 | ex | Elixir | lib/scenic/components.ex | milmazz/scenic | 551050797721bda38fcb54188fe362abbc68ddc7 | [
"Apache-2.0"
] | null | null | null | lib/scenic/components.ex | milmazz/scenic | 551050797721bda38fcb54188fe362abbc68ddc7 | [
"Apache-2.0"
] | null | null | null | lib/scenic/components.ex | milmazz/scenic | 551050797721bda38fcb54188fe362abbc68ddc7 | [
"Apache-2.0"
] | null | null | null | #
# Created by Boyd Multerer April 30, 2018.
# Copyright © 2018 Kry10 Industries. All rights reserved.
#
# convenience functions for adding basic components to a graph.
# this module should be updated as new base components are added
defmodule Scenic.Components do
alias Scenic.Component
alias Scenic.Primitive
alias Scenic.Primitive.SceneRef
alias Scenic.Graph
# import IEx
@moduledoc """
## About Components
Components are small scenes that are referenced, and managed, by another scene.
They are useful for reusing bits of UI and containing the logic that runs them.
## Helper Functions
This module contains a set of helper functions to make it easy to add, or modify,
the standard components in a graph.
In general, each helper function is of the form
def name_of_component( graph, data, options \\\\ [] )
Unlike primitives, components are scenes in themselves. Each component
is is run by a GenServer and adding a basic component does two things.
1) A new component GenServer is started and supervised by the owning
scene's dynamic scene supervisor.
2) A reference to the new scene is added to the graph.
This doesn't happen all at once. These helper functions simply add
a reference to a to-be-started component to your graph. When you call
`push_graph/1` to the ViewPort then manages the lifecycle of the components.
You can also supervise components yourself, but then you should add
the scene reference yourself via the `scene_ref/3` function, which is in the
[`Scenic.Primitives`](Scenic.Primitives.html) module.
When adding components to a graph, each helper function accepts a
graph as the first parameter and returns the transformed graph. This
makes is very easy to buid a complex graph by piping helper functions
together.
@graph Graph.build()
|> button( "Press Me", id: :sample_button )
When modifying a graph, you can again use the helpers by passing
in the component to be modified. The transformed component will
be returned.
Graph.modify(graph, :sample_button, fn(p) ->
button( p, "Continue" )
end)
# or, more compactly...
Graph.modify(graph, :sample_button, &button(&1, "Continue") )
In each case, the second parameter is a data term that is specific
to the component being acted on. See the documentation below. If you
pass in invalid data for the second parameter an error will be
thrown along with some explanation of what it expected.
The third parameter is a keyword list of options that are to be
applied to the component. This includes setting the id, styles,
transforms and such.
@graph Graph.build()
|> button( "Press Me", id: :sample_button, rotate: 0.4)
### Event messages
Most basic or input components exist to collect data and/or send
messages to the host scene that references.
For example, when a button scene decides that it has been "clicked",
the generic button component doesn't know how to do anything with that
information. So it sends a `{:click, id}` to the host scene
that referenced it.
That scene can intercept the message, act on it, transform it, and/or
send it up to the host scene that references it. (Components can be
nested many layers deep)
To do this, the **host scene** should implement the `filter_event` callback.
examples:
def filter_event( {:click, :sample_button}, _, state ) do
{:stop, state }
end
def filter_event( {:click, :sample_button}, _, state ) do
{:continue, {:click, :transformed}, state }
end
Inside a filter_event callback you can modify a graph, change state,
send messages, transform the event, stop the event, and much more.
"""
# --------------------------------------------------------
@doc """
Add a button to a graph
A button is a small scene that is pretty much just some text
drawn over a rounded rectangle. The button scene contains logic to detect
when the button is pressed, tracks it as the pointer moves around, and
when it is released.
Data:
text
* `text` must be a bitstring
### Messages
If a button press is successful, it sends an event message to the host
scene in the form of:
{:click, id}
### Styles
Buttons honor the following standard styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped. The default
is `false`.
* `:theme` - The color set used to draw. See below. The default is `:primary`
### Additional Styles
Buttons honor the following list of additional styles.
* `:width` - pass in a number to set the width of the button.
* `:height` - pass in a number to set the height of the button.
* `:radius` - pass in a number to set the radius of the button's rounded rectangle.
* `:alignment` - set the aligment of the text inside the button. Can be one of
`:left, :right, :center`. The default is `:center`.
* `:button_font_size` - the size of the font in the button
Buttons do not use the inherited `:font_size` style as the should look consistent regardless
of what size the surrounding text is.
## Theme
Buttons work well with the following predefined themes:
`:primary`, `:secondary`, `:success`, `:danger`, `:warning`, `:info`, `:text`, `:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:text` - the color of the text in the button
* `:background` - the normal background of the button
* `:active` - the background while the button is pressed
### Examples
The following example creates a simple button and positions it on the screen.
graph
|> button( "Example", id: :button_id, translate: {20, 20} )
The next example makes the same button as before, but colors it as a warning button. See
the options list above for more details.
graph
|> button( "Example", id: :button_id, translate: {20, 20}, theme: :warning )
"""
def button(graph, data, options \\ [])
def button(%Graph{} = g, data, options) do
add_to_graph(g, Component.Button, data, options)
end
def button(%Primitive{module: SceneRef} = p, data, options) do
modify(p, Component.Button, data, options)
end
# --------------------------------------------------------
@doc """
Add a checkbox to a graph
Data:
{text, checked?}
* `text` must be a bitstring
* `checked?` must be a boolean and indicates if the checkbox is set.
### Messages
When the state of the checkbox, it sends an event message to the host
scene in the form of:
{:value_changed, id, checked?}
### Styles
Buttons honor the following standard styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped. The default
is `false`.
* `:theme` - The color set used to draw. See below. The default is `:dark`
## Theme
Checkboxes work well with the following predefined themes:
`:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:text` - the color of the text in the button
* `:background` - the background of the box
* `:border` - the border of the box
* `:active` - the border of the box while the button is pressed
* `:thumb` - the color of the checkmark itself
### Examples
The following example creates a checkbox and positions it on the screen.
graph
|> checkbox( {"Example", true}, id: :checkbox_id, translate: {20, 20} )
"""
def checkbox(graph, data, options \\ [])
def checkbox(%Graph{} = g, data, options) do
add_to_graph(g, Component.Input.Checkbox, data, options)
end
def checkbox(%Primitive{module: SceneRef} = p, data, options) do
modify(p, Component.Input.Checkbox, data, options)
end
# --------------------------------------------------------
@doc """
Add a dropdown to a graph
Data:
{items, initial_item}
* `items` must be a list of items, each of which is: {text, id}. See below...
* `initial_item` is the id of the initial selected item. It can be any term you want, however
it must be an `item_id` in the `items` list. See below.
Per item data:
{text, item_id}
* `text` is a string that will be shown in the dropdown.
* `item_id` can be any term you want. It will identify the item that is currently selected
in the dropdown and will be passed back to you during event messages.
### Messages
When the state of the checkbox, it sends an event message to the host
scene in the form of:
{:value_changed, id, selected_item_id}
### Options
Dropdowns honor the following list of options.
### Styles
Buttons honor the following styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped. The default
is `false`.
* `:theme` - The color set used to draw. See below. The default is `:dark`
### Additional Styles
Buttons honor the following list of additional styles.
* `:width` - pass in a number to set the width of the button.
* `:height` - pass in a number to set the height of the button.
## Theme
Dropdowns work well with the following predefined themes:
`:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:text` - the color of the text
* `:background` - the background of the component
* `:border` - the border of the component
* `:active` - the background of selecte item in the dropdown list
* `:thumb` - the color of the item being hovered over
### Examples
The following example creates a dropdown and positions it on the screen.
graph
|> dropdown({[
{"Dashboard", :dashboard},
{"Controls", :controls},
{"Primitives", :primitives},
], :controls}, id: :dropdown_id, translate: {20, 20} )
"""
def dropdown(graph, data, options \\ [])
def dropdown(%Graph{} = g, data, options) do
add_to_graph(g, Component.Input.Dropdown, data, options)
end
def dropdown(%Primitive{module: SceneRef} = p, data, options) do
modify(p, Component.Input.Dropdown, data, options)
end
# --------------------------------------------------------
@doc """
Add a radio group to a graph
Data:
radio_buttons
* `radio_buttons` must be a list of radio button data. See below.
Radio button data:
{text, radio_id, checked? \\\\ false}
* `text` must be a bitstring
* `button_id` can be any term you want. It will be passed back to you as the group's value.
* `checked?` must be a boolean and indicates if the button is selected. `checked?` is not
required and will default to `false` if not supplied.
### Messages
When the state of the radio group changes, it sends an event message to the host
scene in the form of:
{:value_changed, id, radio_id}
### Options
Radio Buttons honor the following list of options.
* `:theme` - This sets the color scheme of the button. This can be one of
pre-defined button schemes `:light`, `:dark`, or it can be a completly custom
scheme like this: `{text_color, box_background, border_color, pressed_color, checkmark_color}`.
### Styles
Radio Buttons honor the following styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped. The default
is `false`.
* `:theme` - The color set used to draw. See below. The default is `:dark`
## Theme
Radio buttons work well with the following predefined themes:
`:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:text` - the color of the text
* `:background` - the background of the component
* `:border` - the border of the component
* `:active` - the background of the circle while the button is pressed
* `:thumb` - the color of inner selected-mark
### Examples
The following example creates a radio group and positions it on the screen.
graph
|> radio_group([
{"Radio A", :radio_a},
{"Radio B", :radio_b, true},
{"Radio C", :radio_c},
], id: :radio_group_id, translate: {20, 20} )
"""
def radio_group(graph, data, options \\ [])
def radio_group(%Graph{} = g, data, options) do
add_to_graph(g, Component.Input.RadioGroup, data, options)
end
def radio_group(%Primitive{module: SceneRef} = p, data, options) do
modify(p, Component.Input.RadioGroup, data, options)
end
# --------------------------------------------------------
@doc """
Add a slider to a graph
Data:
{ extents, initial_value}
* `extents` gives the range of values. It can take several forms...
* `{min,max}` If min and max are integers, then the slider value will be an integer.
* `{min,max}` If min and max are floats, then the slider value will be an float.
* `[a, b, c]` A list of terms. The value will be one of the terms
* `initial_value` Sets the intial value (and position) of the slider. It must make
sense with the extents you passed in.
### Messages
When the state of the slider changes, it sends an event message to the host
scene in the form of:
{:value_changed, id, value}
### Options
Sliders honor the following list of options.
### Styles
Sliders honor the following styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped. The default
is `false`.
* `:theme` - The color set used to draw. See below. The default is `:dark`
## Theme
Sliders work well with the following predefined themes:
`:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:border` - the color of the slider line
* `:thumb` - the color of slider thumb
### Examples
The following example creates a numeric sliderand positions it on the screen.
graph
|> Component.Input.Slider.add_to_graph( {{0,100}, 0, :num_slider}, translate: {20,20} )
The following example creates a list slider and positions it on the screen.
graph
|> slider( {[
:white,
:cornflower_blue,
:green,
:chartreuse
], :cornflower_blue}, id: :slider_id, translate: {20,20} )
"""
def slider(graph, data, options \\ [])
def slider(%Graph{} = g, data, options) do
add_to_graph(g, Component.Input.Slider, data, options)
end
def slider(%Primitive{module: SceneRef} = p, data, options) do
modify(p, Component.Input.Slider, data, options)
end
# --------------------------------------------------------
@doc """
Add a text field input to a graph
Data: initial_value
* `initial_value` is the string that will be the starting value
### Messages
When the text in the field changes, it sends an event message to the host
scene in the form of:
{:value_changed, id, value}
### Styles
Text fields honor the following styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped. The default
is `false`.
* `:theme` - The color set used to draw. See below. The default is `:dark`
### Additional Styles
Text fields honor the following list of additional styles.
* `:filter` - Adding a filter option restricts which characters can be entered
into the text_field component. The value of filter can be one of:
* `:all` - Accept all characters. This is the default
* `:number` - Any characters from "0123456789.,"
* `"filter_string"` - Pass in a string containing all the characters you will accept
* `function/1` - Pass in an anonymous function. The single parameter will be
the character to be filtered. Return true or false to keep or reject it.
* `:hint` - A string that will be shown (greyed out) when the entered value
of the componenet is empty.
* `:type` - Can be one of the following options:
* `:all` - Show all characters. This is the default.
* `:password` - Display a string of '*' characters instead of the value.
* `:width` - set the width of the control.
## Theme
Text fields work well with the following predefined themes:
`:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:text` - the color of the text
* `:background` - the background of the component
* `:border` - the border of the component
* `:focus` - the border while the component has focus
### Examples
graph
|> text_field( "Sample Text", id: :text_id, translate: {20,20} )
graph
|> text_field(
"", id: :pass_id, type: :password, hint: "Enter password", translate: {20,20}
)
"""
def text_field(graph, data, options \\ [])
def text_field(%Graph{} = g, data, options) do
add_to_graph(g, Component.Input.TextField, data, options)
end
def text_field(%Primitive{module: SceneRef} = p, data, options) do
modify(p, Component.Input.TextField, data, options)
end
# ============================================================================
# generic workhorse versions
defp add_to_graph(%Graph{} = g, mod, data, options) do
mod.verify!(data)
mod.add_to_graph(g, data, options)
end
defp modify(%Primitive{module: SceneRef} = p, mod, data, options) do
mod.verify!(data)
Primitive.put(p, {mod, data}, options)
end
end
| 30.311734 | 98 | 0.661833 |
1ce69dece2e24a724955698e5bf54a37aea22a15 | 1,807 | ex | Elixir | lib/boundary/mix/tasks/find_external_deps.ex | randycoulman/boundary | 2fdea46e702400c152670262d5ca1f31edbd4fa1 | [
"MIT"
] | 490 | 2019-09-07T10:33:15.000Z | 2022-03-30T09:50:03.000Z | lib/boundary/mix/tasks/find_external_deps.ex | randycoulman/boundary | 2fdea46e702400c152670262d5ca1f31edbd4fa1 | [
"MIT"
] | 35 | 2019-09-07T10:49:25.000Z | 2022-03-18T10:02:34.000Z | lib/boundary/mix/tasks/find_external_deps.ex | randycoulman/boundary | 2fdea46e702400c152670262d5ca1f31edbd4fa1 | [
"MIT"
] | 16 | 2019-09-08T15:09:16.000Z | 2022-02-12T21:40:14.000Z | defmodule Mix.Tasks.Boundary.FindExternalDeps do
@shortdoc "Prints information about external dependencies of all application boundaries."
@moduledoc """
Prints information about external dependencies of all application boundaries.
Note that `:stdlib`, `:kernel`, `:elixir`, and `:boundary` will not be included in the output.
"""
# credo:disable-for-this-file Credo.Check.Readability.Specs
use Boundary, classify_to: Boundary.Mix
use Mix.Task
alias Boundary.Mix.Xref
@impl Mix.Task
def run(_argv) do
Mix.Task.run("compile")
Boundary.Mix.load_app()
view = Boundary.view(Boundary.Mix.app_name())
message =
view
|> find_external_deps()
|> Enum.filter(fn {name, _external_deps} -> Boundary.fetch!(view, name).app == Boundary.Mix.app_name() end)
|> Enum.sort()
|> Stream.map(&message/1)
|> Enum.join("\n")
Mix.shell().info("\n" <> message)
end
defp message({boundary_name, external_deps}) do
header = "#{[IO.ANSI.bright()]}#{inspect(boundary_name)}#{IO.ANSI.reset()}"
if Enum.empty?(external_deps) do
header <> " - no external deps\n"
else
"""
#{header}:
#{external_deps |> Enum.sort() |> Stream.map(&inspect/1) |> Enum.join(", ")}
"""
end
end
defp find_external_deps(boundary_view) do
Xref.start_link()
for reference <- Xref.entries(),
boundary = Boundary.for_module(boundary_view, reference.from),
boundary.check.out,
app = Boundary.app(boundary_view, reference.to),
app not in [:boundary, Boundary.Mix.app_name(), nil],
reduce: Enum.into(Boundary.all_names(boundary_view), %{}, &{&1, MapSet.new()}) do
acc ->
Map.update(acc, boundary.name, MapSet.new([app]), &MapSet.put(&1, app))
end
end
end
| 29.145161 | 113 | 0.643055 |
1ce69fa7c4798386b31572123ed10977899247b4 | 1,924 | exs | Elixir | test/judgment_test.exs | MieuxVoter/majority-judgment-library-elixir | 0dd2cb1553d88dedd85585af4046a789c364143d | [
"MIT"
] | null | null | null | test/judgment_test.exs | MieuxVoter/majority-judgment-library-elixir | 0dd2cb1553d88dedd85585af4046a789c364143d | [
"MIT"
] | 1 | 2021-10-18T02:40:58.000Z | 2021-10-18T02:40:58.000Z | test/judgment_test.exs | MieuxVoter/majority-judgment-library-elixir | 0dd2cb1553d88dedd85585af4046a789c364143d | [
"MIT"
] | null | null | null | defmodule JudgmentTest do
use ExUnit.Case
doctest Judgment
# test "WTF is IO.inspect doing?" do
# [13, 13, 13, 13, 13]
# |> IO.inspect(label: "WTF with lucky 13")
# # > '\r\r\r\r\r'
# # Yeah… right.
#
# for i <- 0..20 do
# [i, i, i, i, i]
# |> IO.inspect(label: "WTF with #{i}")
# end
# end
test "Resolve Majority Judgment" do
tallies = [
[0, 1, 2, 3, 4],
[0, 2, 1, 3, 4],
[2, 1, 0, 3, 4]
]
result = Judgment.Majority.resolve(tallies)
assert result != nil
assert result.proposals != nil
assert length(result.proposals) == length(tallies)
assert for(p <- result.proposals, do: p.index) == [0, 1, 2]
assert for(p <- result.proposals, do: p.rank) == [1, 2, 3]
assert for(p <- result.sorted_proposals, do: p.index) == [0, 1, 2]
assert for(p <- result.sorted_proposals, do: p.rank) == [1, 2, 3]
end
test "MJ with equalities" do
tallies = [
[0, 1, 0, 3, 6],
[0, 1, 2, 3, 4],
[0, 1, 0, 3, 6],
[0, 1, 0, 3, 6]
]
result = Judgment.Majority.resolve(tallies)
assert for(p <- result.proposals, do: p.index) == [0, 1, 2, 3]
assert for(p <- result.proposals, do: p.rank) == [1, 4, 1, 1]
assert for(p <- result.sorted_proposals, do: p.index) == [0, 2, 3, 1]
assert for(p <- result.sorted_proposals, do: p.rank) == [1, 1, 1, 4]
end
test "MJ with multiple equalities" do
tallies = [
[1, 2, 3],
[3, 2, 1],
[2, 1, 3],
[1, 2, 3],
[3, 2, 1],
[2, 1, 3]
]
result = Judgment.Majority.resolve(tallies)
assert for(p <- result.proposals, do: p.index) == [0, 1, 2, 3, 4, 5]
assert for(p <- result.proposals, do: p.rank) == [1, 5, 3, 1, 5, 3]
assert for(p <- result.sorted_proposals, do: p.index) == [0, 3, 2, 5, 1, 4]
assert for(p <- result.sorted_proposals, do: p.rank) == [1, 1, 3, 3, 5, 5]
end
end
| 29.151515 | 79 | 0.523909 |
1ce6a34274c92c2f829a823f63a453212dc902e6 | 218 | exs | Elixir | priv/repo/migrations/20160329062749_add_role_id_to_users.exs | davepersing/blog_engine | 8605732f72c169d6cc2c2261a9acef0de7769403 | [
"MIT"
] | null | null | null | priv/repo/migrations/20160329062749_add_role_id_to_users.exs | davepersing/blog_engine | 8605732f72c169d6cc2c2261a9acef0de7769403 | [
"MIT"
] | null | null | null | priv/repo/migrations/20160329062749_add_role_id_to_users.exs | davepersing/blog_engine | 8605732f72c169d6cc2c2261a9acef0de7769403 | [
"MIT"
] | null | null | null | defmodule BlogEngine.Repo.Migrations.AddRoleIdToUsers do
use Ecto.Migration
def change do
alter table(:users) do
add :role_id, references(:roles)
end
create index(:users, [:role_id])
end
end
| 19.818182 | 56 | 0.697248 |
1ce6a5a7c063af17b035d220172f8e3425110868 | 1,538 | ex | Elixir | lib/river/flags.ex | peburrows/river | e8968535d02a86e70a7942a690c8e461fed55913 | [
"MIT"
] | 86 | 2016-08-19T21:59:28.000Z | 2022-01-31T20:14:18.000Z | lib/river/flags.ex | peburrows/river | e8968535d02a86e70a7942a690c8e461fed55913 | [
"MIT"
] | 7 | 2016-09-27T14:44:16.000Z | 2017-08-08T14:57:45.000Z | lib/river/flags.ex | peburrows/river | e8968535d02a86e70a7942a690c8e461fed55913 | [
"MIT"
] | 4 | 2016-09-26T10:57:24.000Z | 2018-04-03T14:30:19.000Z | defmodule River.Flags do
use Bitwise
require River.FrameTypes
alias River.{Frame, FrameTypes}
def encode(%{} = flags) do
flags
|> Enum.filter(fn {_k, v} -> v end)
|> Enum.map(fn {k, _v} -> key_to_val(k) end)
|> Enum.reduce(0, fn el, acc -> el ||| acc end)
end
def flags(FrameTypes.settings(), f) do
get_flags(%{}, f, {0x1, :ack})
end
def flags(FrameTypes.data(), f) do
get_flags(%{}, f, {0x1, :end_stream})
end
def flags(FrameTypes.push_promise(), f) do
%{}
|> get_flags(f, {0x4, :end_headers})
|> get_flags(f, {0x8, :padded})
end
def flags(FrameTypes.headers(), f) do
%{}
|> get_flags(f, {0x1, :end_stream})
|> get_flags(f, {0x4, :end_headers})
|> get_flags(f, {0x8, :padded})
|> get_flags(f, {0x20, :priority})
end
def flags(FrameTypes.rst_stream(), _f), do: %{}
def flags(FrameTypes.goaway(), _f), do: %{}
def has_flag?(%Frame{flags: flags}, f), do: has_flag?(flags, f)
def has_flag?(flags, f) when is_map(flags), do: Map.get(flags, f, false)
def has_flag?(flags, f) do
f = key_to_val(f)
case flags &&& f do
^f -> true
_ -> false
end
end
defp get_flags(into, flags, {f, name}) do
case has_flag?(flags, f) do
true -> Map.put(into, name, true)
_ -> into
end
end
defp key_to_val(:ack), do: 0x1
defp key_to_val(:end_stream), do: 0x1
defp key_to_val(:end_headers), do: 0x4
defp key_to_val(:padded), do: 0x8
defp key_to_val(:priority), do: 0x20
defp key_to_val(k), do: k
end
| 23.661538 | 74 | 0.59883 |
1ce6b5c49633dff907524cff98a505baf94a4bf4 | 69 | ex | Elixir | test/support/test_repo.ex | mazz/beepbop | 9d5930a870904fd84c317d3c2865d6b1c9a1080c | [
"MIT"
] | 3 | 2018-03-26T14:04:26.000Z | 2018-12-09T11:53:18.000Z | test/support/test_repo.ex | mazz/beepbop | 9d5930a870904fd84c317d3c2865d6b1c9a1080c | [
"MIT"
] | 6 | 2018-04-16T13:07:18.000Z | 2018-06-25T09:54:47.000Z | test/support/test_repo.ex | mazz/beepbop | 9d5930a870904fd84c317d3c2865d6b1c9a1080c | [
"MIT"
] | 6 | 2019-04-01T07:58:56.000Z | 2022-03-13T16:08:05.000Z | defmodule BeepBop.TestRepo do
use Ecto.Repo, otp_app: :beepbop
end
| 17.25 | 34 | 0.782609 |
1ce6ce953d8e4b6807bbf310f37156fc5e2ae753 | 22,053 | ex | Elixir | lib/tortoise/connection.ex | lucaong/tortoise | fd2f83527937ba39b47f58eb8d392a1aa927e28f | [
"Apache-2.0"
] | null | null | null | lib/tortoise/connection.ex | lucaong/tortoise | fd2f83527937ba39b47f58eb8d392a1aa927e28f | [
"Apache-2.0"
] | null | null | null | lib/tortoise/connection.ex | lucaong/tortoise | fd2f83527937ba39b47f58eb8d392a1aa927e28f | [
"Apache-2.0"
] | null | null | null | defmodule Tortoise.Connection do
@moduledoc """
Establish a connection to a MQTT broker.
Todo.
"""
use GenServer
require Logger
defstruct [:client_id, :connect, :server, :status, :backoff, :subscriptions, :keep_alive, :opts]
alias __MODULE__, as: State
alias Tortoise.{Transport, Connection, Package, Events}
alias Tortoise.Connection.{Inflight, Controller, Receiver, Backoff}
alias Tortoise.Package.{Connect, Connack}
@doc """
Start a connection process and link it to the current process.
Read the documentation on `child_spec/1` if you want... (todo!)
"""
@spec start_link(options, GenServer.options()) :: GenServer.on_start()
when option:
{:client_id, Tortoise.client_id()}
| {:user_name, String.t()}
| {:password, String.t()}
| {:keep_alive, non_neg_integer()}
| {:will, Tortoise.Package.Publish.t()}
| {:subscriptions,
[{Tortoise.topic_filter(), Tortoise.qos()}] | Tortoise.Package.Subscribe.t()}
| {:handler, {atom(), term()}},
options: [option]
def start_link(connection_opts, opts \\ []) do
client_id = Keyword.fetch!(connection_opts, :client_id)
server = connection_opts |> Keyword.fetch!(:server) |> Transport.new()
connect = %Package.Connect{
client_id: client_id,
user_name: Keyword.get(connection_opts, :user_name),
password: Keyword.get(connection_opts, :password),
keep_alive: Keyword.get(connection_opts, :keep_alive, 60),
will: Keyword.get(connection_opts, :will),
# if we re-spawn from here it means our state is gone
clean_session: true
}
backoff = Keyword.get(connection_opts, :backoff, [])
# This allow us to either pass in a list of topics, or a
# subscription struct. Passing in a subscription struct is helpful
# in tests.
subscriptions =
case Keyword.get(connection_opts, :subscriptions, []) do
topics when is_list(topics) ->
Enum.into(topics, %Package.Subscribe{})
%Package.Subscribe{} = subscribe ->
subscribe
end
# @todo, validate that the handler is valid
connection_opts = Keyword.take(connection_opts, [:client_id, :handler])
initial = {server, connect, backoff, subscriptions, connection_opts}
opts = Keyword.merge(opts, name: via_name(client_id))
GenServer.start_link(__MODULE__, initial, opts)
end
@doc false
@spec via_name(Tortoise.client_id()) ::
pid() | {:via, Registry, {Tortoise.Registry, {atom(), Tortoise.client_id()}}}
def via_name(client_id) do
Tortoise.Registry.via_name(__MODULE__, client_id)
end
@spec child_spec(Keyword.t()) :: %{
id: term(),
start: {__MODULE__, :start_link, [Keyword.t()]},
restart: :transient | :permanent | :temporary,
type: :worker
}
def child_spec(opts) do
%{
id: Keyword.get(opts, :name, __MODULE__),
start: {__MODULE__, :start_link, [opts]},
restart: Keyword.get(opts, :restart, :transient),
type: :worker
}
end
@doc """
Close the connection to the broker.
Given the `client_id` of a running connection it will cancel the
inflight messages and send the proper disconnect message to the
broker. The session will get terminated on the server.
"""
@spec disconnect(Tortoise.client_id()) :: :ok
def disconnect(client_id) do
GenServer.call(via_name(client_id), :disconnect)
end
@doc """
Return the list of subscribed topics.
Given the `client_id` of a running connection return its current
subscriptions. This is helpful in a debugging situation.
"""
@spec subscriptions(Tortoise.client_id()) :: Tortoise.Package.Subscribe.t()
def subscriptions(client_id) do
GenServer.call(via_name(client_id), :subscriptions)
end
@doc """
Subscribe to one or more topics using topic filters on `client_id`
The topic filter should be a 2-tuple, `{topic_filter, qos}`, where
the `topic_filter` is a valid MQTT topic filter, and `qos` an
integer value 0 through 2.
Multiple topics can be given as a list.
The subscribe function is asynchronous, so it will return `{:ok,
ref}`. Eventually a response will get delivered to the process
mailbox, tagged with the reference stored in `ref`. It will take the
form of:
{{Tortoise, ^client_id}, ^ref, ^result}
Where the `result` can be one of `:ok`, or `{:error, reason}`.
Read the documentation for `Tortoise.Connection.subscribe_sync/3`
for a blocking version of this call.
"""
@spec subscribe(Tortoise.client_id(), topic | topics, [options]) :: {:ok, reference()}
when topics: [topic],
topic: {Tortoise.topic_filter(), Tortoise.qos()},
options:
{:timeout, timeout()}
| {:identifier, Tortoise.package_identifier()}
def subscribe(client_id, topics, opts \\ [])
def subscribe(client_id, [{_, n} | _] = topics, opts) when is_number(n) do
caller = {_, ref} = {self(), make_ref()}
{identifier, opts} = Keyword.pop_first(opts, :identifier, nil)
subscribe = Enum.into(topics, %Package.Subscribe{identifier: identifier})
GenServer.cast(via_name(client_id), {:subscribe, caller, subscribe, opts})
{:ok, ref}
end
def subscribe(client_id, {_, n} = topic, opts) when is_number(n) do
subscribe(client_id, [topic], opts)
end
def subscribe(client_id, topic, opts) when is_binary(topic) do
case Keyword.pop_first(opts, :qos) do
{nil, _opts} ->
throw("Please specify a quality of service for the subscription")
{qos, opts} when qos in 0..2 ->
subscribe(client_id, [{topic, qos}], opts)
end
end
@doc """
Subscribe to topics and block until the server acknowledges.
This is a synchronous version of the
`Tortoise.Connection.subscribe/3`. In fact it calls into
`Tortoise.Connection.subscribe/3` but will handle the selective
receive loop, making it much easier to work with. Also, this
function can be used to block a process that cannot continue before
it has a subscription to the given topics.
See `Tortoise.Connection.subscribe/3` for configuration options.
"""
@spec subscribe_sync(Tortoise.client_id(), topic | topics, [options]) ::
:ok | {:error, :timeout}
when topics: [topic],
topic: {Tortoise.topic_filter(), Tortoise.qos()},
options:
{:timeout, timeout()}
| {:identifier, Tortoise.package_identifier()}
def subscribe_sync(client_id, topics, opts \\ [])
def subscribe_sync(client_id, [{_, n} | _] = topics, opts) when is_number(n) do
timeout = Keyword.get(opts, :timeout, 5000)
{:ok, ref} = subscribe(client_id, topics, opts)
receive do
{{Tortoise, ^client_id}, ^ref, result} -> result
after
timeout ->
{:error, :timeout}
end
end
def subscribe_sync(client_id, {_, n} = topic, opts) when is_number(n) do
subscribe_sync(client_id, [topic], opts)
end
def subscribe_sync(client_id, topic, opts) when is_binary(topic) do
case Keyword.pop_first(opts, :qos) do
{nil, _opts} ->
throw("Please specify a quality of service for the subscription")
{qos, opts} ->
subscribe_sync(client_id, [{topic, qos}], opts)
end
end
@doc """
Unsubscribe from one of more topic filters. The topic filters are
given as strings. Multiple topic filters can be given at once by
passing in a list of strings.
Tortoise.Connection.unsubscribe(client_id, ["foo/bar", "quux"])
This operation is asynchronous. When the operation is done a message
will be received in mailbox of the originating process.
"""
@spec unsubscribe(Tortoise.client_id(), topic | topics, [options]) :: {:ok, reference()}
when topics: [topic],
topic: Tortoise.topic_filter(),
options:
{:timeout, timeout()}
| {:identifier, Tortoise.package_identifier()}
def unsubscribe(client_id, topics, opts \\ [])
def unsubscribe(client_id, [topic | _] = topics, opts) when is_binary(topic) do
caller = {_, ref} = {self(), make_ref()}
{identifier, opts} = Keyword.pop_first(opts, :identifier, nil)
unsubscribe = %Package.Unsubscribe{identifier: identifier, topics: topics}
GenServer.cast(via_name(client_id), {:unsubscribe, caller, unsubscribe, opts})
{:ok, ref}
end
def unsubscribe(client_id, topic, opts) when is_binary(topic) do
unsubscribe(client_id, [topic], opts)
end
@doc """
Unsubscribe from topics and block until the server acknowledges.
This is a synchronous version of
`Tortoise.Connection.unsubscribe/3`. It will block until the server
has send the acknowledge message.
See `Tortoise.Connection.unsubscribe/3` for configuration options.
"""
@spec unsubscribe_sync(Tortoise.client_id(), topic | topics, [options]) ::
:ok | {:error, :timeout}
when topics: [topic],
topic: Tortoise.topic_filter(),
options:
{:timeout, timeout()}
| {:identifier, Tortoise.package_identifier()}
def unsubscribe_sync(client_id, topics, opts \\ [])
def unsubscribe_sync(client_id, topics, opts) when is_list(topics) do
timeout = Keyword.get(opts, :timeout, 5000)
{:ok, ref} = unsubscribe(client_id, topics, opts)
receive do
{{Tortoise, ^client_id}, ^ref, result} -> result
after
timeout ->
{:error, :timeout}
end
end
def unsubscribe_sync(client_id, topic, opts) when is_binary(topic) do
unsubscribe_sync(client_id, [topic], opts)
end
@doc """
Ping the broker.
When the round-trip is complete a message with the time taken in
milliseconds will be send to the process that invoked the ping
command.
The connection will automatically ping the broker at the interval
specified in the connection configuration, so there is no need to
setup a reoccurring ping. This ping function is exposed for
debugging purposes. If ping latency over time is desired it is
better to listen on `:ping_response` using the `Tortoise.Events`
PubSub.
"""
@spec ping(Tortoise.client_id()) :: {:ok, reference()}
defdelegate ping(client_id), to: Tortoise.Connection.Controller
@doc """
Ping the server and await the ping latency reply.
Takes a `client_id` and an optional `timeout`.
Like `ping/1` but will block the caller process until a response is
received from the server. The response will contain the ping latency
in milliseconds. The `timeout` defaults to `:infinity`, so it is
advisable to specify a reasonable time one is willing to wait for a
response.
"""
@spec ping_sync(Tortoise.client_id(), timeout()) :: {:ok, reference()} | {:error, :timeout}
defdelegate ping_sync(client_id, timeout \\ :infinity),
to: Tortoise.Connection.Controller
@doc false
@spec connection(Tortoise.client_id(), [opts]) ::
{:ok, {module(), term()}} | {:error, :unknown_connection} | {:error, :timeout}
when opts: {:timeout, timeout()} | {:active, boolean()}
def connection(client_id, opts \\ [active: false]) do
# register a connection subscription in the case we are currently
# in the connect phase; this solves a possible race condition
# where the connection is requested while the status is
# connecting, but will reach the receive block after the message
# has been dispatched from the pubsub; previously we registered
# for the connection message in this window.
{:ok, _} = Events.register(client_id, :connection)
case Tortoise.Registry.meta(via_name(client_id)) do
{:ok, {_transport, _socket} = connection} ->
{:ok, connection}
{:ok, :connecting} ->
timeout = Keyword.get(opts, :timeout, :infinity)
receive do
{{Tortoise, ^client_id}, :connection, {transport, socket}} ->
{:ok, {transport, socket}}
after
timeout ->
{:error, :timeout}
end
:error ->
{:error, :unknown_connection}
end
after
# if the connection subscription is non-active we should remove it
# from the registry, so the process will not receive connection
# messages when the connection is reestablished.
active? = Keyword.get(opts, :active, false)
unless active?, do: Events.unregister(client_id, :connection)
end
# Callbacks
@impl true
def init(
{transport, %Connect{client_id: client_id} = connect, backoff_opts, subscriptions, opts}
) do
state = %State{
client_id: client_id,
server: transport,
connect: connect,
backoff: Backoff.new(backoff_opts),
subscriptions: subscriptions,
opts: opts,
status: :down
}
Tortoise.Registry.put_meta(via_name(client_id), :connecting)
Tortoise.Events.register(client_id, :status)
# eventually, switch to handle_continue
send(self(), :connect)
{:ok, state}
end
@impl true
def terminate(_reason, state) do
:ok = Tortoise.Registry.delete_meta(via_name(state.connect.client_id))
:ok = Events.dispatch(state.client_id, :status, :terminated)
:ok
end
@impl true
def handle_info(:connect, state) do
# make sure we will not fall for a keep alive timeout while we reconnect
state = cancel_keep_alive(state)
with {%Connack{status: :accepted} = connack, socket} <-
do_connect(state.server, state.connect),
{:ok, state} = init_connection(socket, state) do
# we are connected; reset backoff state, etc
state =
%State{state | backoff: Backoff.reset(state.backoff)}
|> update_connection_status(:up)
|> reset_keep_alive()
case connack do
%Connack{session_present: true} ->
{:noreply, state}
%Connack{session_present: false} ->
:ok = Inflight.reset(state.client_id)
unless Enum.empty?(state.subscriptions), do: send(self(), :subscribe)
{:noreply, state}
end
else
%Connack{status: {:refused, reason}} ->
{:stop, {:connection_failed, reason}, state}
{:error, reason} ->
{timeout, state} = Map.get_and_update(state, :backoff, &Backoff.next/1)
case categorize_error(reason) do
:connectivity ->
Process.send_after(self(), :connect, timeout)
{:noreply, state}
:other ->
{:stop, reason, state}
end
end
end
def handle_info(:subscribe, %State{subscriptions: subscriptions} = state) do
client_id = state.connect.client_id
case Enum.empty?(subscriptions) do
true ->
# nothing to subscribe to, just continue
{:noreply, state}
false ->
# subscribe to the predefined topics
case Inflight.track_sync(client_id, {:outgoing, subscriptions}, 5000) do
{:error, :timeout} ->
{:stop, :subscription_timeout, state}
result ->
case handle_suback_result(result, state) do
{:ok, updated_state} ->
{:noreply, updated_state}
{:error, reasons} ->
error = {:unable_to_subscribe, reasons}
{:stop, error, state}
end
end
end
end
def handle_info(:ping, %State{} = state) do
case Controller.ping_sync(state.connect.client_id, 5000) do
{:ok, round_trip_time} ->
Events.dispatch(state.connect.client_id, :ping_response, round_trip_time)
state = reset_keep_alive(state)
{:noreply, state}
{:error, :timeout} ->
{:stop, :ping_timeout, state}
end
end
# dropping connection
def handle_info({transport, _socket}, state) when transport in [:tcp_closed, :ssl_closed] do
Logger.error("Socket closed before we handed it to the receiver")
# communicate that we are down
:ok = Events.dispatch(state.client_id, :status, :down)
{:noreply, state}
end
# react to connection status change events
def handle_info(
{{Tortoise, client_id}, :status, status},
%{client_id: client_id, status: current} = state
) do
case status do
^current ->
{:noreply, state}
:up ->
{:noreply, %State{state | status: status}}
:down ->
send(self(), :connect)
{:noreply, %State{state | status: status}}
end
end
@impl true
def handle_call(:subscriptions, _from, state) do
{:reply, state.subscriptions, state}
end
def handle_call(:disconnect, from, state) do
:ok = Events.dispatch(state.client_id, :status, :terminating)
:ok = Inflight.drain(state.client_id)
:ok = Controller.stop(state.client_id)
:ok = GenServer.reply(from, :ok)
{:stop, :shutdown, state}
end
@impl true
def handle_cast({:subscribe, {caller_pid, ref}, subscribe, opts}, state) do
client_id = state.connect.client_id
timeout = Keyword.get(opts, :timeout, 5000)
case Inflight.track_sync(client_id, {:outgoing, subscribe}, timeout) do
{:error, :timeout} = error ->
send(caller_pid, {{Tortoise, client_id}, ref, error})
{:noreply, state}
result ->
case handle_suback_result(result, state) do
{:ok, updated_state} ->
send(caller_pid, {{Tortoise, client_id}, ref, :ok})
{:noreply, updated_state}
{:error, reasons} ->
error = {:unable_to_subscribe, reasons}
send(caller_pid, {{Tortoise, client_id}, ref, {:error, reasons}})
{:stop, error, state}
end
end
end
def handle_cast({:unsubscribe, {caller_pid, ref}, unsubscribe, opts}, state) do
client_id = state.connect.client_id
timeout = Keyword.get(opts, :timeout, 5000)
case Inflight.track_sync(client_id, {:outgoing, unsubscribe}, timeout) do
{:error, :timeout} = error ->
send(caller_pid, {{Tortoise, client_id}, ref, error})
{:noreply, state}
unsubbed ->
topics = Keyword.drop(state.subscriptions.topics, unsubbed)
subscriptions = %Package.Subscribe{state.subscriptions | topics: topics}
send(caller_pid, {{Tortoise, client_id}, ref, :ok})
{:noreply, %State{state | subscriptions: subscriptions}}
end
end
# Helpers
defp handle_suback_result(%{:error => []} = results, %State{} = state) do
subscriptions = Enum.into(results[:ok], state.subscriptions)
{:ok, %State{state | subscriptions: subscriptions}}
end
defp handle_suback_result(%{:error => errors}, %State{}) do
{:error, errors}
end
defp reset_keep_alive(%State{keep_alive: nil} = state) do
ref = Process.send_after(self(), :ping, state.connect.keep_alive * 1000)
%State{state | keep_alive: ref}
end
defp reset_keep_alive(%State{keep_alive: previous_ref} = state) do
# Cancel the previous timer, just in case one was already set
_ = Process.cancel_timer(previous_ref)
ref = Process.send_after(self(), :ping, state.connect.keep_alive * 1000)
%State{state | keep_alive: ref}
end
defp cancel_keep_alive(%State{keep_alive: nil} = state) do
state
end
defp cancel_keep_alive(%State{keep_alive: keep_alive_ref} = state) do
_ = Process.cancel_timer(keep_alive_ref)
%State{state | keep_alive: nil}
end
# dispatch connection status if the connection status change
defp update_connection_status(%State{status: same} = state, same) do
state
end
defp update_connection_status(%State{} = state, status) do
:ok = Events.dispatch(state.connect.client_id, :status, status)
%State{state | status: status}
end
defp do_connect(server, %Connect{} = connect) do
%Transport{type: transport, host: host, port: port, opts: opts} = server
with {:ok, socket} <- transport.connect(host, port, opts, 10000),
:ok = transport.send(socket, Package.encode(connect)),
{:ok, packet} <- transport.recv(socket, 4, 5000) do
try do
case Package.decode(packet) do
%Connack{status: :accepted} = connack ->
{connack, socket}
%Connack{status: {:refused, _reason}} = connack ->
connack
end
catch
:error, {:badmatch, _unexpected} ->
violation = %{expected: Connect, got: packet}
{:error, {:protocol_violation, violation}}
end
else
{:error, :econnrefused} ->
{:error, {:connection_refused, host, port}}
{:error, :nxdomain} ->
{:error, {:nxdomain, host, port}}
{:error, {:options, {:cacertfile, []}}} ->
{:error, :no_cacartfile_specified}
{:error, :closed} ->
{:error, :server_closed_connection}
{:error, :timeout} ->
{:error, :connection_timeout}
{:error, other} ->
{:error, other}
end
end
defp init_connection(socket, %State{opts: opts, server: transport, connect: connect} = state) do
connection = {transport.type, socket}
:ok = start_connection_supervisor(opts)
:ok = Receiver.handle_socket(connect.client_id, connection)
:ok = Tortoise.Registry.put_meta(via_name(connect.client_id), connection)
:ok = Events.dispatch(connect.client_id, :connection, connection)
# set clean session to false for future reconnect attempts
connect = %Connect{connect | clean_session: false}
{:ok, %State{state | connect: connect}}
end
defp start_connection_supervisor(opts) do
case Connection.Supervisor.start_link(opts) do
{:ok, _pid} ->
:ok
{:error, {:already_started, _pid}} ->
:ok
end
end
defp categorize_error({:nxdomain, _host, _port}) do
:connectivity
end
defp categorize_error({:connection_refused, _host, _port}) do
:connectivity
end
defp categorize_error(:server_closed_connection) do
:connectivity
end
defp categorize_error(:connection_timeout) do
:connectivity
end
defp categorize_error(:enetunreach) do
:connectivity
end
defp categorize_error(_other) do
:other
end
end
| 33.112613 | 98 | 0.649027 |
1ce6e7704d2f67822b4c38d35a310683bc196054 | 64 | ex | Elixir | lib/kirby_web/views/user_session_view.ex | prefeitura-municipal-campos/kirby | 290835751a28cd7e39be2e721de243e495273be7 | [
"BSD-3-Clause"
] | null | null | null | lib/kirby_web/views/user_session_view.ex | prefeitura-municipal-campos/kirby | 290835751a28cd7e39be2e721de243e495273be7 | [
"BSD-3-Clause"
] | null | null | null | lib/kirby_web/views/user_session_view.ex | prefeitura-municipal-campos/kirby | 290835751a28cd7e39be2e721de243e495273be7 | [
"BSD-3-Clause"
] | null | null | null | defmodule KirbyWeb.UserSessionView do
use KirbyWeb, :view
end
| 16 | 37 | 0.8125 |
1ce6eaa436422fedebee6b933ce0e8de495eec62 | 1,617 | ex | Elixir | clients/docs/lib/google_api/docs/v1/model/shading_suggestion_state.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/docs/lib/google_api/docs/v1/model/shading_suggestion_state.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/docs/lib/google_api/docs/v1/model/shading_suggestion_state.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Docs.V1.Model.ShadingSuggestionState do
@moduledoc """
A mask that indicates which of the fields on the base Shading have been changed in this suggested change. For any field set to true, there is a new suggested value.
## Attributes
* `backgroundColorSuggested` (*type:* `boolean()`, *default:* `nil`) - Indicates if there was a suggested change to the Shading.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:backgroundColorSuggested => boolean() | nil
}
field(:backgroundColorSuggested)
end
defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.ShadingSuggestionState do
def decode(value, options) do
GoogleApi.Docs.V1.Model.ShadingSuggestionState.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.ShadingSuggestionState do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.404255 | 166 | 0.749536 |
1ce6eb080be66e3045660f2157ddf1ba40861fc8 | 328 | exs | Elixir | config/test.exs | matrinox/absinthe_phoenix | e0ae14c04a55550f9cd7a6845583ad0bcce79305 | [
"MIT"
] | 263 | 2016-05-12T21:26:08.000Z | 2022-03-29T04:06:46.000Z | config/test.exs | matrinox/absinthe_phoenix | e0ae14c04a55550f9cd7a6845583ad0bcce79305 | [
"MIT"
] | 79 | 2017-06-25T08:18:46.000Z | 2021-12-14T15:13:06.000Z | config/test.exs | matrinox/absinthe_phoenix | e0ae14c04a55550f9cd7a6845583ad0bcce79305 | [
"MIT"
] | 86 | 2016-05-19T09:52:32.000Z | 2022-03-26T13:46:52.000Z | use Mix.Config
config :logger, level: :warn
config :absinthe_phoenix, Absinthe.Phoenix.TestEndpoint,
url: [host: "localhost"],
root: Path.dirname(__DIR__),
secret_key_base: "GSGmIoMRxcLfHBfBhtD/Powy7WaucKbLuB7BTMt41nkm5xS+8LfnXZYNsk6qKOo1",
render_errors: [accepts: ~w(json)],
pubsub_server: Absinthe.Phoenix.PubSub
| 29.818182 | 86 | 0.780488 |
1ce6fbddab35eef2616cee1bc52b5b08a302454d | 2,166 | ex | Elixir | lib/mix/tasks/ecto.drop.ex | jccf091/ecto | 42d47a6da0711f842e1a0e6724a89b318b9b2144 | [
"Apache-2.0"
] | 1 | 2017-11-27T06:00:32.000Z | 2017-11-27T06:00:32.000Z | lib/mix/tasks/ecto.drop.ex | jccf091/ecto | 42d47a6da0711f842e1a0e6724a89b318b9b2144 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/ecto.drop.ex | jccf091/ecto | 42d47a6da0711f842e1a0e6724a89b318b9b2144 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Ecto.Drop do
use Mix.Task
import Mix.Ecto
@shortdoc "Drops the repository storage"
@default_opts [force: false]
@moduledoc """
Drop the storage for the given repository.
The repositories to create are the ones specified under the
`:ecto_repos` option in the current app configuration. However,
if the `-r` option is given, it replaces the `:ecto_repos` config.
Since Ecto tasks can only be executed once, if you need to create
multiple repositories, set `:ecto_repos` accordingly or pass the `-r`
flag multiple times.
## Examples
mix ecto.drop
mix ecto.drop -r Custom.Repo
## Command line options
* `-r`, `--repo` - the repo to drop
* `--no-compile` - do not compile before stopping
* `--force` - do not ask for confirmation
"""
@doc false
def run(args) do
repos = parse_repo(args)
{opts, _, _} = OptionParser.parse args, switches: [quiet: :boolean, force: :boolean]
opts = Keyword.merge(@default_opts, opts)
Enum.each repos, fn repo ->
ensure_repo(repo, args)
ensure_implements(repo.__adapter__, Ecto.Adapter.Storage,
"drop storage for #{inspect repo}")
if skip_safety_warnings?() or
opts[:force] or
Mix.shell.yes?("Are you sure you want to drop the database for repo #{inspect repo}?") do
drop_database(repo, opts)
end
end
end
defp skip_safety_warnings? do
Mix.Project.config[:start_permanent] != true
end
defp drop_database(repo, opts) do
case repo.__adapter__.storage_down(repo.config) do
:ok ->
unless opts[:quiet] do
Mix.shell.info "The database for #{inspect repo} has been dropped"
end
{:error, :already_down} ->
unless opts[:quiet] do
Mix.shell.info "The database for #{inspect repo} has already been dropped"
end
{:error, term} when is_binary(term) ->
Mix.raise "The database for #{inspect repo} couldn't be dropped: #{term}"
{:error, term} ->
Mix.raise "The database for #{inspect repo} couldn't be dropped: #{inspect term}"
end
end
end
| 30.083333 | 98 | 0.643121 |
1ce7004fbf82857c8d905aa493f4a6f9dea73ed9 | 324 | ex | Elixir | lib/arrow/field.ex | nyo16/elixir-arrow | 655b14ac412716c29aa33d0fab178577e3eca330 | [
"Apache-2.0"
] | 16 | 2021-03-21T14:59:33.000Z | 2022-03-11T01:52:16.000Z | lib/arrow/field.ex | nyo16/elixir-arrow | 655b14ac412716c29aa33d0fab178577e3eca330 | [
"Apache-2.0"
] | null | null | null | lib/arrow/field.ex | nyo16/elixir-arrow | 655b14ac412716c29aa33d0fab178577e3eca330 | [
"Apache-2.0"
] | 3 | 2021-09-02T03:25:08.000Z | 2022-03-11T01:53:01.000Z | defmodule Arrow.Field do
@enforce_keys [:name, :data_type, :nullable]
defstruct [:name, :data_type, :nullable, :metadata, dict_id: 0, dict_is_ordered: false]
def from_column({name, values}) do
type = Arrow.Type.infer(values)
%Arrow.Field{name: Atom.to_string(name), data_type: type, nullable: true}
end
end
| 32.4 | 89 | 0.716049 |
1ce701d4c1d400a4f93e8c0d0ba2be1b1c51f118 | 1,472 | ex | Elixir | lib/ash/notifier/pub_sub/publication.ex | kyle5794/ash | 82023da84400366d07001593673d1aaa2a418803 | [
"MIT"
] | null | null | null | lib/ash/notifier/pub_sub/publication.ex | kyle5794/ash | 82023da84400366d07001593673d1aaa2a418803 | [
"MIT"
] | null | null | null | lib/ash/notifier/pub_sub/publication.ex | kyle5794/ash | 82023da84400366d07001593673d1aaa2a418803 | [
"MIT"
] | null | null | null | defmodule Ash.Notifier.PubSub.Publication do
@moduledoc "Represents an individual publication setup"
defstruct [
:action,
:topic,
:event,
:type
]
@schema [
action: [
type: :atom,
doc: "The name of the action that should be published",
required: true
],
topic: [
type: {:custom, __MODULE__, :topic, []},
doc: "The topic to publish",
required: true
],
event: [
type: :string,
doc: "The name of the event to publish. Defaults to the action name"
],
type: [
type: {:one_of, [:create, :update, :destroy]},
doc:
"In the case of multiple actions with the same name, you may need to provide the action type as well."
]
]
@publish_all_schema Keyword.update!(@schema, :action, &Keyword.delete(&1, :required))
def schema, do: @schema
def publish_all_schema, do: @publish_all_schema
@doc false
def topic(topic) when is_binary(topic) do
{:ok, [topic]}
end
def topic(topic) when is_list(topic) do
if Enum.all?(topic, fn item -> is_binary(item) || is_atom(item) end) do
{:ok, topic}
else
{:error,
"Expected topic to be a string or a list of strings or attribute names (as atoms), got: #{
inspect(topic)
}"}
end
end
def topic(other) do
{:error,
"Expected topic to be a string or a list of strings or attribute names (as atoms), got: #{
inspect(other)
}"}
end
end
| 24.131148 | 110 | 0.605299 |
1ce7742fbbeef3ec9490344b7e80f28b33d62952 | 1,834 | exs | Elixir | clients/cloud_profiler/mix.exs | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/cloud_profiler/mix.exs | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/cloud_profiler/mix.exs | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudProfiler.Mixfile do
use Mix.Project
@version "0.4.1"
def project() do
[
app: :google_api_cloud_profiler,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/cloud_profiler"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.2"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Stackdriver Profiler API client library. Manages continuous profiling information.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/cloud_profiler",
"Homepage" => "https://cloud.google.com/profiler/"
}
]
end
end
| 27.373134 | 105 | 0.658124 |
1ce77d20a27be7ce92d311fa55b6eee61a0225d9 | 3,633 | exs | Elixir | test/recurly/webhooks/new_subscription_notification_test.exs | calibr/recurly-client-elixir | a1160a10f90e0919adacf39bd95df3784e11fdcc | [
"MIT"
] | 8 | 2016-08-11T00:45:46.000Z | 2020-05-04T18:55:48.000Z | test/recurly/webhooks/new_subscription_notification_test.exs | calibr/recurly-client-elixir | a1160a10f90e0919adacf39bd95df3784e11fdcc | [
"MIT"
] | 10 | 2016-08-15T20:01:56.000Z | 2019-05-10T02:09:35.000Z | test/recurly/webhooks/new_subscription_notification_test.exs | calibr/recurly-client-elixir | a1160a10f90e0919adacf39bd95df3784e11fdcc | [
"MIT"
] | 4 | 2017-10-16T14:29:58.000Z | 2019-05-09T23:20:56.000Z | defmodule Recurly.Webhooks.NewSubscriptionNotificationTest do
use ExUnit.Case, async: true
alias Recurly.{Webhooks,Account,Subscription,Plan,SubscriptionAddOn}
test "correctly parses payload" do
xml_doc = """
<new_subscription_notification>
<account>
<account_code>1</account_code>
<username nil="true">verena</username>
<email>verena@example.com</email>
<first_name>Verena</first_name>
<last_name>Example</last_name>
<company_name nil="true">Company, Inc.</company_name>
</account>
<subscription>
<plan>
<plan_code>bronze</plan_code>
<name>Bronze Plan</name>
</plan>
<uuid>8047cb4fd5f874b14d713d785436ebd3</uuid>
<state>active</state>
<quantity type="integer">2</quantity>
<total_amount_in_cents type="integer">17000</total_amount_in_cents>
<subscription_add_ons type="array">
<subscription_add_on>
<add_on_code>premium_support</add_on_code>
<name>Premium Support</name>
<quantity type="integer">1</quantity>
<unit_amount_in_cents type="integer">15000</unit_amount_in_cents>
<add_on_type>fixed</add_on_type>
<usage_percentage nil="true"></usage_percentage>
<measured_unit_id nil="true"></measured_unit_id>
</subscription_add_on>
<subscription_add_on>
<add_on_code>email_blasts</add_on_code>
<name>Email Blasts</name>
<quantity type="integer">1</quantity>
<unit_amount_in_cents type="integer">50</unit_amount_in_cents>
<add_on_type>usage</add_on_type>
<usage_percentage nil="true"></usage_percentage>
<measured_unit_id type="integer">394681687402874853</measured_unit_id>
</subscription_add_on>
<subscription_add_on>
<add_on_code>donations</add_on_code>
<name>Donations</name>
<quantity type="integer">1</quantity>
<unit_amount_in_cents nil="true"></unit_amount_in_cents>
<add_on_type>usage</add_on_type>
<usage_percentage>0.6</usage_percentage>
<measured_unit_id type="integer">394681920153192422</measured_unit_id>
</subscription_add_on>
</subscription_add_ons>
<activated_at type="datetime">2009-11-22T13:10:38Z</activated_at>
<canceled_at type="datetime"></canceled_at>
<expires_at type="datetime"></expires_at>
<current_period_started_at type="datetime">2009-11-22T13:10:38Z</current_period_started_at>
<current_period_ends_at type="datetime">2009-11-29T13:10:38Z</current_period_ends_at>
<trial_started_at type="datetime">2009-11-22T13:10:38Z</trial_started_at>
<trial_ends_at type="datetime">2009-11-29T13:10:38Z</trial_ends_at>
<collection_method>automatic</collection_method>
</subscription>
</new_subscription_notification>
"""
notification = %Webhooks.NewSubscriptionNotification{} = Webhooks.parse(xml_doc)
account = %Account{} = notification.account
subscription = %Subscription{} = notification.subscription
plan = %Plan{} = subscription.plan
add_on = %SubscriptionAddOn{} = subscription.subscription_add_ons |> List.first
assert account.account_code == "1"
assert subscription.uuid == "8047cb4fd5f874b14d713d785436ebd3"
assert plan.plan_code == "bronze"
assert add_on.add_on_code == "premium_support"
end
end
| 46.576923 | 101 | 0.649876 |
1ce796bdd908da19050e8b3942d8dd5a851bd940 | 1,616 | ex | Elixir | farmbot_os/lib/farmbot_os/sys_calls/change_ownership.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | 1 | 2019-08-06T11:51:48.000Z | 2019-08-06T11:51:48.000Z | farmbot_os/lib/farmbot_os/sys_calls/change_ownership.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | farmbot_os/lib/farmbot_os/sys_calls/change_ownership.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | defmodule FarmbotOS.SysCalls.ChangeOwnership do
@moduledoc false
require Logger
require FarmbotCore.Logger
import FarmbotCore.Config, only: [get_config_value: 3, update_config_value: 4]
alias FarmbotCore.{Asset, EctoMigrator}
alias FarmbotExt.Bootstrap.Authorization
def change_ownership(email, secret, server) do
server = server || get_config_value(:string, "authorization", "server")
case Authorization.authorize_with_secret(email, secret, server) do
{:ok, _token} ->
FarmbotCore.Logger.warn(1, "Farmbot is changing ownership to #{email} - #{server}")
:ok = replace_credentials(email, secret, server)
_ = clean_assets()
_ = clean_farmwares()
FarmbotCore.Logger.warn(1, "Going down for reboot")
Supervisor.start_child(:elixir_sup, {Task, &FarmbotOS.System.soft_restart/0})
:ok
{:error, _} ->
FarmbotCore.Logger.error(1, "Invalid credentials for change ownership")
{:error, "Invalid credentials for change ownership"}
end
end
defp clean_assets do
EctoMigrator.drop(Asset.Repo)
:ok
end
defp clean_farmwares do
:ok
end
defp replace_credentials(email, secret, server) do
FarmbotCore.Logger.debug(3, "Replacing credentials")
update_config_value(:string, "authorization", "password", nil)
update_config_value(:string, "authorization", "token", nil)
update_config_value(:string, "authorization", "email", email)
update_config_value(:string, "authorization", "server", server)
update_config_value(:string, "authorization", "secret", secret)
:ok
end
end
| 34.382979 | 91 | 0.704827 |
1ce7bbaa6f10d02f1db5b55c220f7e1c49085896 | 72 | ex | Elixir | lib/super_issuer_web/views/lottery_view.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 2 | 2021-02-12T09:21:56.000Z | 2021-02-22T08:52:20.000Z | lib/super_issuer_web/views/lottery_view.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | 4 | 2021-02-22T08:53:43.000Z | 2021-06-09T09:24:46.000Z | lib/super_issuer_web/views/lottery_view.ex | WeLightProject/WeLight-Portal | 6e701469423e3a62affdc415c4e8c186d603d324 | [
"MIT"
] | null | null | null | defmodule SuperIssuerWeb.LotteryView do
use SuperIssuerWeb, :view
end
| 18 | 39 | 0.833333 |
1ce7cc4058beedb73450d5fe566b101cfb175261 | 87 | ex | Elixir | lib/stripe_app_web/views/coherence/unlock_view.ex | hotpyn/stripe_demo | 2a0ac3ab34a616ffcd6d7e979c25517b5f1636b5 | [
"MIT"
] | null | null | null | lib/stripe_app_web/views/coherence/unlock_view.ex | hotpyn/stripe_demo | 2a0ac3ab34a616ffcd6d7e979c25517b5f1636b5 | [
"MIT"
] | null | null | null | lib/stripe_app_web/views/coherence/unlock_view.ex | hotpyn/stripe_demo | 2a0ac3ab34a616ffcd6d7e979c25517b5f1636b5 | [
"MIT"
] | null | null | null | defmodule StripeAppWeb.Coherence.UnlockView do
use StripeAppWeb.Coherence, :view
end
| 21.75 | 46 | 0.83908 |
1ce7e53d8d013890ca1dd81c105dcee172155371 | 437 | exs | Elixir | apps/test_empty_app_web/test/test_empty_app_web/views/error_view_test.exs | baseballlover723/test_empty_app | fd7046ea8ee88e1c0eefee82fe95aecc7ede3f82 | [
"MIT"
] | null | null | null | apps/test_empty_app_web/test/test_empty_app_web/views/error_view_test.exs | baseballlover723/test_empty_app | fd7046ea8ee88e1c0eefee82fe95aecc7ede3f82 | [
"MIT"
] | null | null | null | apps/test_empty_app_web/test/test_empty_app_web/views/error_view_test.exs | baseballlover723/test_empty_app | fd7046ea8ee88e1c0eefee82fe95aecc7ede3f82 | [
"MIT"
] | null | null | null | defmodule TestEmptyAppWeb.ErrorViewTest do
use TestEmptyAppWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(TestEmptyAppWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(TestEmptyAppWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 29.133333 | 97 | 0.745995 |
1ce7f80e8e52a7a2acfcaea89ade13aab4fff802 | 2,327 | exs | Elixir | test/xdr/transactions/muxed_account_med25519_test.exs | einerzg/stellar_base | 2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f | [
"MIT"
] | 3 | 2021-08-17T20:32:45.000Z | 2022-03-13T20:26:02.000Z | test/xdr/transactions/muxed_account_med25519_test.exs | einerzg/stellar_base | 2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f | [
"MIT"
] | 45 | 2021-08-12T20:19:41.000Z | 2022-03-27T21:00:10.000Z | test/xdr/transactions/muxed_account_med25519_test.exs | einerzg/stellar_base | 2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f | [
"MIT"
] | 2 | 2021-09-22T23:11:13.000Z | 2022-01-23T03:19:11.000Z | defmodule StellarBase.XDR.MuxedAccountMed25519Test do
use ExUnit.Case
alias StellarBase.XDR.{UInt64, UInt256, MuxedAccountMed25519}
describe "StellarBase.XDR.MuxedAccountMed25519" do
setup do
account_id =
UInt256.new(
<<18, 27, 249, 51, 160, 215, 152, 50, 153, 222, 53, 177, 115, 224, 92, 243, 51, 242,
249, 40, 118, 78, 128, 109, 86, 239, 171, 232, 42, 171, 210, 35>>
)
account_derived_id = UInt64.new(123)
%{
account_derived_id: account_derived_id,
account_id: account_id,
muxed_account: MuxedAccountMed25519.new(account_derived_id, account_id),
encoded_binary:
<<0, 0, 0, 0, 0, 0, 0, 123, 18, 27, 249, 51, 160, 215, 152, 50, 153, 222, 53, 177, 115,
224, 92, 243, 51, 242, 249, 40, 118, 78, 128, 109, 86, 239, 171, 232, 42, 171, 210,
35>>
}
end
test "new/1", %{account_id: account_id, account_derived_id: account_derived_id} do
%MuxedAccountMed25519{ed25519: ^account_id} =
MuxedAccountMed25519.new(account_derived_id, account_id)
end
test "encode_xdr/1", %{muxed_account: muxed_account, encoded_binary: binary} do
{:ok, ^binary} = MuxedAccountMed25519.encode_xdr(muxed_account)
end
test "encode_xdr!/1", %{muxed_account: muxed_account, encoded_binary: binary} do
^binary = MuxedAccountMed25519.encode_xdr!(muxed_account)
end
test "decode_xdr/2", %{muxed_account: muxed_account, encoded_binary: binary} do
{:ok, {^muxed_account, ""}} = MuxedAccountMed25519.decode_xdr(binary)
end
test "decode_xdr/2 with an invalid binary" do
{:error, :not_binary} = MuxedAccountMed25519.decode_xdr(123)
end
test "decode_xdr!/2", %{muxed_account: muxed_account, encoded_binary: binary} do
{^muxed_account, ^binary} = MuxedAccountMed25519.decode_xdr!(binary <> binary)
end
test "invalid ed25519 value" do
assert_raise FunctionClauseError,
"no function clause matching in StellarBase.XDR.MuxedAccountMed25519.new/2",
fn ->
account_derived_id = UInt64.new(123)
account_id = UInt64.new(321)
MuxedAccountMed25519.new(account_derived_id, account_id)
end
end
end
end
| 36.359375 | 97 | 0.63902 |
1ce815389bededce451f3a8d61c68f75af491709 | 260 | ex | Elixir | lib/forus/repo.ex | finalclass/forus | f745d3ef63684b8fa61a904d4032b5ae26931943 | [
"MIT"
] | null | null | null | lib/forus/repo.ex | finalclass/forus | f745d3ef63684b8fa61a904d4032b5ae26931943 | [
"MIT"
] | 1 | 2018-06-19T10:38:48.000Z | 2018-06-19T10:38:48.000Z | lib/forus/repo.ex | finalclass/forus | f745d3ef63684b8fa61a904d4032b5ae26931943 | [
"MIT"
] | null | null | null | defmodule Forus.Repo do
use Ecto.Repo, otp_app: :forus
@doc """
Dynamically loads the repository url from the
DATABASE_URL environment variable.
"""
def init(_, opts) do
{:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
end
end
| 21.666667 | 66 | 0.692308 |
1ce8187e4046114abc6d54587442d6bc6775e052 | 3,666 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/waterfall_chart_series.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/waterfall_chart_series.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/sheets/lib/google_api/sheets/v4/model/waterfall_chart_series.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Sheets.V4.Model.WaterfallChartSeries do
@moduledoc """
A single series of data for a waterfall chart.
## Attributes
* `customSubtotals` (*type:* `list(GoogleApi.Sheets.V4.Model.WaterfallChartCustomSubtotal.t)`, *default:* `nil`) - Custom subtotal columns appearing in this series. The order in which subtotals are defined is not significant. Only one subtotal may be defined for each data point.
* `data` (*type:* `GoogleApi.Sheets.V4.Model.ChartData.t`, *default:* `nil`) - The data being visualized in this series.
* `dataLabel` (*type:* `GoogleApi.Sheets.V4.Model.DataLabel.t`, *default:* `nil`) - Information about the data labels for this series.
* `hideTrailingSubtotal` (*type:* `boolean()`, *default:* `nil`) - True to hide the subtotal column from the end of the series. By default, a subtotal column will appear at the end of each series. Setting this field to true will hide that subtotal column for this series.
* `negativeColumnsStyle` (*type:* `GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle.t`, *default:* `nil`) - Styles for all columns in this series with negative values.
* `positiveColumnsStyle` (*type:* `GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle.t`, *default:* `nil`) - Styles for all columns in this series with positive values.
* `subtotalColumnsStyle` (*type:* `GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle.t`, *default:* `nil`) - Styles for all subtotal columns in this series.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:customSubtotals => list(GoogleApi.Sheets.V4.Model.WaterfallChartCustomSubtotal.t()),
:data => GoogleApi.Sheets.V4.Model.ChartData.t(),
:dataLabel => GoogleApi.Sheets.V4.Model.DataLabel.t(),
:hideTrailingSubtotal => boolean(),
:negativeColumnsStyle => GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle.t(),
:positiveColumnsStyle => GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle.t(),
:subtotalColumnsStyle => GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle.t()
}
field(:customSubtotals, as: GoogleApi.Sheets.V4.Model.WaterfallChartCustomSubtotal, type: :list)
field(:data, as: GoogleApi.Sheets.V4.Model.ChartData)
field(:dataLabel, as: GoogleApi.Sheets.V4.Model.DataLabel)
field(:hideTrailingSubtotal)
field(:negativeColumnsStyle, as: GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle)
field(:positiveColumnsStyle, as: GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle)
field(:subtotalColumnsStyle, as: GoogleApi.Sheets.V4.Model.WaterfallChartColumnStyle)
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.WaterfallChartSeries do
def decode(value, options) do
GoogleApi.Sheets.V4.Model.WaterfallChartSeries.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.WaterfallChartSeries do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 56.4 | 283 | 0.7485 |
1ce8a87d83b83b6876f8cb651c9021ae488ada1f | 578 | exs | Elixir | config/prod.exs | phoenixframework/plds | 820600e8da6e13f376f8341cb78868bc189ddad8 | [
"MIT"
] | 60 | 2021-09-13T21:53:34.000Z | 2022-03-09T14:31:36.000Z | config/prod.exs | phoenixframework/plds | 820600e8da6e13f376f8341cb78868bc189ddad8 | [
"MIT"
] | 2 | 2021-09-23T17:13:40.000Z | 2021-11-16T15:57:05.000Z | config/prod.exs | phoenixframework/plds | 820600e8da6e13f376f8341cb78868bc189ddad8 | [
"MIT"
] | 2 | 2021-11-16T10:37:42.000Z | 2022-02-18T19:32:38.000Z | 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 :plds, PLDSWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 8090],
server: true
# Do not print debug messages in production
config :logger, level: :info
| 32.111111 | 56 | 0.752595 |
1ce8aedfd0a9d135aa425a019104a358940fe5cb | 12,257 | ex | Elixir | lib/parent/gen_server.ex | axelson/parent | d85e15a1d9129f4a9dec8a881a67fe50a6264910 | [
"MIT"
] | 200 | 2018-04-08T20:36:15.000Z | 2022-03-12T14:43:46.000Z | lib/parent/gen_server.ex | axelson/parent | d85e15a1d9129f4a9dec8a881a67fe50a6264910 | [
"MIT"
] | 15 | 2018-05-31T11:03:21.000Z | 2022-02-19T21:26:21.000Z | lib/parent/gen_server.ex | axelson/parent | d85e15a1d9129f4a9dec8a881a67fe50a6264910 | [
"MIT"
] | 18 | 2018-05-16T02:09:35.000Z | 2022-02-03T18:56:30.000Z | defmodule Parent.GenServer do
@moduledoc """
GenServer with parenting capabilities powered by `Parent`.
This behaviour can be useful in situations where `Parent.Supervisor` won't suffice.
## Example
The following example is roughly similar to a standard
[callback-based Supervisor](https://hexdocs.pm/elixir/Supervisor.html#module-module-based-supervisors):
defmodule MyApp.Supervisor do
# Automatically defines child_spec/1
use Parent.GenServer
def start_link(init_arg),
do: Parent.GenServer.start_link(__MODULE__, init_arg, name: __MODULE__)
@impl GenServer
def init(_init_arg) do
Parent.start_all_children!(children)
{:ok, initial_state}
end
end
The expression `use Parent.GenServer` will also inject `use GenServer` into your code. Your
parent process is a GenServer, and this behaviour doesn't try to hide it. Except when starting
the process, you work with the parent exactly as you work with any GenServer, using the same
functions, such as `GenServer.call/3`, and providing the same callbacks, such as `init/1`, or
`handle_call/3`.
## Interacting with the parent from the outside
You can issue regular `GenServer` calls and casts, and send messages to the parent, which can
be handled by corresponding `GenServer` callbacks. In addition, you can use functions from
the `Parent.Client` module to manipulate or query the parent state from other processes. As a
good practice, it's advised to wrap such invocations in the module which implements
`Parent.GenServer`.
## Interacting with children inside the parent
From within the parent process, you can interact with the child processes using functions from
the `Parent` module. All child processes should be started using `Parent` functions, such as
`Parent.start_child/2`, because otherwise `Parent` won't be aware of these processes and won't
be able to fulfill its guarantees.
Note that you can start children from any callback, not just during `init/1`. In addition, you
don't need to start all children at once. Therefore, `Parent.GenServer` can prove useful when
you need to make some runtime decisions:
{:ok, child1} = Parent.start_child(child1_spec)
if some_condition_met?,
do: Parent.start_child(child2_spec)
Parent.start_child(child3_spec)
However, bear in mind that this code won't be executed again if the processes are restarted.
## Handling child termination
If a child process terminates and isn't restarted, the `c:handle_stopped_children/2` callback is
invoked. The default implementation does nothing.
The following example uses `c:handle_stopped_children/2` to start a child task and report if it
it crashes:
defmodule MyJob do
use Parent.GenServer, restart: :temporary
def start_link(arg), do: Parent.GenServer.start_link(__MODULE__, arg)
@impl GenServer
def init(_) do
{:ok, _} = Parent.start_child(%{
id: :job,
start: {Task, :start_link, [fn -> job(arg) end]},
restart: :temporary,
# handle_stopped_children won't be invoked without this
ephemeral?: true
})
{:ok, nil}
end
@impl Parent.GenServer
def handle_stopped_children(%{job: info}, state) do
if info.reason != :normal do
# report job failure
end
{:stop, reason, state}
end
end
`handle_stopped_children` can be useful to implement arbitrary custom behaviour, such as
restarting after a delay, and using incremental backoff periods between two consecutive starts.
For example, this is how you could introduce a delay between two consecutive starts:
def handle_stopped_children(stopped_children, state) do
Process.send_after(self, {:restart, stopped_children}, delay)
{:noreply, state}
end
def handle_info({:restart, stopped_children}, state) do
Parent.return_children(stopped_children)
{:noreply, state}
end
Keep in mind that `handle_stopped_children` is only invoked if the child crashed on its own,
and if it's not going to be restarted.
If the child was explicitly stopped via a `Parent` function, such as `Parent.shutdown_child/1`,
this callback will not be invoked. The same holds for `Parent.Client` functions. If you want
to unconditionally react to a termination of a child process, setup a monitor with `Process.monitor`
and add a corresponding `handle_info` clause.
If the child was taken down because its lifecycle is bound to some other process, the
corresponding `handle_stopped_children` won't be invoked. For example, if process A is bound to
process B, and process B crashes, only one `handle_stopped_children` will be invoked (for the
crash of process B). However, the corresponding `info` will contain the list of all associated
siblings that have been taken down, and `stopped_children` will include information necessary to
restart all of these siblings. Refer to `Parent` documentation for details on lifecycles binding.
## Parent termination
The behaviour takes down the child processes before it terminates, to ensure that no child
process is running after the parent has terminated. The children are terminated synchronously,
one by one, in the reverse start order.
The termination of the children is done after the `terminate/1` callback returns. Therefore in
`terminate/1` the child processes are still running, and you can interact with them, and even
start additional children.
## Caveats
Like any other `Parent`-based process, `Parent.GenServer` traps exits and uses the `:infinity`
shutdown strategy. As a result, a parent process which blocks for a long time (e.g. because its
communicating with a remote service) won't be able to handle child termination, and your
fault-tolerance might be badly affected. In addition, a blocking parent might completely paralyze
the system (or a subtree) shutdown. Setting a shutdown strategy to a finite time is a hacky
workaround that will lead to lingering orphan processes, and might cause some strange race
conditions which will be very hard to debug.
Therefore, be wary of having too much logic inside a parent process. Try to push as much
responsibilities as possible to other processes, such as children or siblings, and use parent
only for coordination and reporting tasks.
Finally, since parent trap exits, it's possible to receive an occasional stray `:EXIT` message
if the child crashes during its initialization.
By default `use Parent.GenServer` receives such messages and ignores them. If you're implementing
your own `handle_info`, make sure to include a clause for `:EXIT` messages:
def handle_info({:EXIT, _pid, _reason}, state), do: {:noreply, state}
"""
use GenServer
@type state :: term
@type options :: [Parent.option() | GenServer.option()]
@doc """
Invoked when some children have terminated.
The `info` map will contain all the children which have been stopped together. For example,
if child A is bound to child B, and child B terminates, parent will also terminate the child
A. In this case, `handle_stopped_children` is invoked only once, with the `info` map containing
entries for both children.
This callback will not be invoked in the following cases:
- a child is terminated by invoking `Parent` functions such as `Parent.shutdown_child/1`
- a child is restarted
- a child is not ephemeral (see "Ephemeral children" in `Parent` for details)
"""
@callback handle_stopped_children(info :: Parent.stopped_children(), state) ::
{:noreply, new_state}
| {:noreply, new_state, timeout | :hibernate}
| {:stop, reason :: term, new_state}
when new_state: state
@doc "Starts the parent process."
@spec start_link(module, arg :: term, options) :: GenServer.on_start()
def start_link(module, arg, options \\ []) do
{parent_opts, gen_server_opts} =
Keyword.split(options, ~w/max_restarts max_seconds registry?/a)
GenServer.start_link(__MODULE__, {module, arg, parent_opts}, gen_server_opts)
end
@impl GenServer
def init({callback, arg, options}) do
# needed to simulate a supervisor
Process.put(:"$initial_call", {:supervisor, callback, 1})
Process.put({__MODULE__, :callback}, callback)
Parent.initialize(options)
invoke_callback(:init, [arg])
end
@impl GenServer
def handle_info(message, state) do
case Parent.handle_message(message) do
{:stopped_children, info} ->
invoke_callback(:handle_stopped_children, [info, state])
:ignore ->
{:noreply, state}
nil ->
invoke_callback(:handle_info, [message, state])
end
end
@impl GenServer
def handle_call(:which_children, _from, state),
do: {:reply, Parent.supervisor_which_children(), state}
def handle_call(:count_children, _from, state),
do: {:reply, Parent.supervisor_count_children(), state}
def handle_call({:get_childspec, child_id_or_pid}, _from, state),
do: {:reply, Parent.supervisor_get_childspec(child_id_or_pid), state}
def handle_call(message, from, state), do: invoke_callback(:handle_call, [message, from, state])
@impl GenServer
def handle_cast(message, state), do: invoke_callback(:handle_cast, [message, state])
@impl GenServer
# Needed to support `:supervisor.get_callback_module`
def format_status(:normal, [_pdict, state]) do
[
data: [{~c"State", state}],
supervisor: [{~c"Callback", Process.get({__MODULE__, :callback})}]
]
end
def format_status(:terminate, pdict_and_state),
do: invoke_callback(:format_status, [:terminate, pdict_and_state])
@impl GenServer
def code_change(old_vsn, state, extra),
do: invoke_callback(:code_change, [old_vsn, state, extra])
@impl GenServer
def terminate(reason, state) do
invoke_callback(:terminate, [reason, state])
after
Parent.shutdown_all(reason)
end
unless Version.compare(System.version(), "1.7.0") == :lt do
@impl GenServer
def handle_continue(continue, state), do: invoke_callback(:handle_continue, [continue, state])
end
defp invoke_callback(fun, arg), do: apply(Process.get({__MODULE__, :callback}), fun, arg)
@doc false
def child_spec(_arg) do
raise("#{__MODULE__} can't be used in a child spec.")
end
@doc false
defmacro __using__(opts) do
quote location: :keep, bind_quoted: [opts: opts, behaviour: __MODULE__] do
use GenServer, opts
@behaviour behaviour
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
def child_spec(arg) do
default = Parent.parent_spec(id: __MODULE__, start: {__MODULE__, :start_link, [arg]})
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
end
@impl behaviour
def handle_stopped_children(_info, state), do: {:noreply, state}
@impl GenServer
# automatic ignoring of `:EXIT` messages which may occur if a child crashes during its `start_link`
def handle_info({:EXIT, _pid, _reason}, state), do: {:noreply, state}
def handle_info(msg, state) do
# copied over from `GenServer`, b/c calling `super` is not allowed
proc =
case Process.info(self(), :registered_name) do
{_, []} -> self()
{_, name} -> name
end
:logger.error(
%{
label: {GenServer, :no_handle_info},
report: %{
module: __MODULE__,
message: msg,
name: proc
}
},
%{
domain: [:otp, :elixir],
error_logger: %{tag: :error_msg},
report_cb: &GenServer.format_report/1
}
)
{:noreply, state}
end
@impl GenServer
def code_change(_old, state, _extra), do: {:ok, state}
defoverridable handle_info: 2, handle_stopped_children: 2, child_spec: 1, code_change: 3
end
end
end
| 38.065217 | 105 | 0.694705 |
1ce8e8d5aa3e5872ee8e15b4fa7da252d1aa9252 | 1,778 | ex | Elixir | test/support/model_case.ex | ench0/ex_elasr | a97e182d13bc5de56c370b687771a485e51fc6ea | [
"MIT"
] | null | null | null | test/support/model_case.ex | ench0/ex_elasr | a97e182d13bc5de56c370b687771a485e51fc6ea | [
"MIT"
] | null | null | null | test/support/model_case.ex | ench0/ex_elasr | a97e182d13bc5de56c370b687771a485e51fc6ea | [
"MIT"
] | null | null | null | defmodule Elasr.ModelCase do
@moduledoc """
This module defines the test case to be used by
model tests.
You may define functions here to be used as helpers in
your model tests. See `errors_on/2`'s definition as reference.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Elasr.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Elasr.ModelCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Elasr.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Elasr.Repo, {:shared, self()})
end
:ok
end
@doc """
Helper for returning list of errors in a struct when given certain data.
## Examples
Given a User schema that lists `:name` as a required field and validates
`:password` to be safe, it would return:
iex> errors_on(%User{}, %{password: "password"})
[password: "is unsafe", name: "is blank"]
You could then write your assertion like:
assert {:password, "is unsafe"} in errors_on(%User{}, %{password: "password"})
You can also create the changeset manually and retrieve the errors
field directly:
iex> changeset = User.changeset(%User{}, password: "password")
iex> {:password, "is unsafe"} in changeset.errors
true
"""
def errors_on(struct, data) do
struct.__struct__.changeset(struct, data)
|> Ecto.Changeset.traverse_errors(&Elasr.ErrorHelpers.translate_error/1)
|> Enum.flat_map(fn {key, errors} -> for msg <- errors, do: {key, msg} end)
end
end
| 26.939394 | 84 | 0.68279 |
1ce91ca2b8239c6bd1d19314947a42984553f93a | 1,145 | ex | Elixir | apps/tai/lib/tai/venue_adapters/bitmex/stream/process_auth/venue_message.ex | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | 1 | 2019-12-19T05:16:26.000Z | 2019-12-19T05:16:26.000Z | apps/tai/lib/tai/venue_adapters/bitmex/stream/process_auth/venue_message.ex | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/venue_adapters/bitmex/stream/process_auth/venue_message.ex | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | 1 | 2020-05-03T23:32:11.000Z | 2020-05-03T23:32:11.000Z | defmodule Tai.VenueAdapters.Bitmex.Stream.ProcessAuth.VenueMessage do
alias Tai.VenueAdapters.Bitmex.Stream.ProcessAuth
defmodule DefaultProvider do
@empty []
def update_orders(data), do: ProcessAuth.VenueMessages.UpdateOrders.extract(data)
def empty, do: @empty
def unhandled(msg), do: [%ProcessAuth.Messages.Unhandled{msg: msg}]
end
@type venue_message :: map
@type provider :: module
@spec extract(venue_message, provider) :: [struct]
def extract(msg, provider \\ DefaultProvider)
def extract(%{"table" => "order", "action" => "update", "data" => data}, provider) do
provider.update_orders(data)
end
def extract(%{"table" => "order", "action" => "insert"}, provider), do: provider.empty
def extract(%{"table" => "transact"}, provider), do: provider.empty
def extract(%{"table" => "execution"}, provider), do: provider.empty
def extract(%{"table" => "wallet"}, provider), do: provider.empty
def extract(%{"table" => "margin"}, provider), do: provider.empty
def extract(%{"table" => "position"}, provider), do: provider.empty
def extract(msg, provider), do: provider.unhandled(msg)
end
| 38.166667 | 88 | 0.692576 |
1ce932363aa531a8508f921dca13403c3b293a72 | 324 | ex | Elixir | lib/credo/cli/command/list/output/oneline.ex | jlgeering/credo | b952190ed758c262aa0d9bbee01227f9b1f0c63b | [
"MIT"
] | null | null | null | lib/credo/cli/command/list/output/oneline.ex | jlgeering/credo | b952190ed758c262aa0d9bbee01227f9b1f0c63b | [
"MIT"
] | null | null | null | lib/credo/cli/command/list/output/oneline.ex | jlgeering/credo | b952190ed758c262aa0d9bbee01227f9b1f0c63b | [
"MIT"
] | null | null | null | defmodule Credo.CLI.Command.List.Output.Oneline do
alias Credo.CLI.Output.Formatter.Oneline
alias Credo.Execution
def print_before_info(_source_files, _exec), do: nil
def print_after_info(_source_files, exec, _time_load, _time_run) do
exec
|> Execution.get_issues()
|> Oneline.print_issues()
end
end
| 24.923077 | 69 | 0.756173 |
1ce968bed44b40158cc32892cade9762c543d9de | 15,016 | ex | Elixir | lib/phoenix_live_component.ex | toranb/phoenix_live_view | 56868d5c3d1e5f6496e838214d1e952e777c4939 | [
"MIT"
] | 1 | 2020-07-26T12:20:43.000Z | 2020-07-26T12:20:43.000Z | lib/phoenix_live_component.ex | mcrumm/phoenix_live_view | ff2313f42444c27e7652ebc5e4ee94ffa619bf85 | [
"MIT"
] | null | null | null | lib/phoenix_live_component.ex | mcrumm/phoenix_live_view | ff2313f42444c27e7652ebc5e4ee94ffa619bf85 | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveComponent do
@moduledoc """
Components are a mechanism to compartmentalize state, markup, and
events in LiveView.
Components are defined by using `Phoenix.LiveComponent` and are used
by calling `Phoenix.LiveView.Helpers.live_component/3` in a parent LiveView.
Components run inside the LiveView process, but may have their own
state and event handling.
The simplest component only needs to define a `render` function:
defmodule HeroComponent do
use Phoenix.LiveComponent
def render(assigns) do
~L\"""
<div class="hero"><%= @content %></div>
\"""
end
end
When `use Phoenix.LiveComponent` is used, all functions in
`Phoenix.LiveView` are imported. A component can be invoked as:
<%= live_component @socket, HeroComponent, content: @content %>
Components come in two shapes, stateless or stateful. The component
above is a stateless component. Of course, the component above is not
any different compared to a regular function. However, as we will see,
components do provide their own exclusive feature set.
## Stateless components life-cycle
When `live_component` is called, the following callbacks will be invoked
in the component:
mount(socket) -> update(assigns, socket) -> render(assigns)
First `c:mount/1` is called only with the socket. `mount/1` can be used
to set any initial state. Then `c:update/2` is invoked with all of the
assigns given to `live_component/3`. The default implementation of
`c:update/2` simply merges all assigns into the socket. Then, after the
component is updated, `c:render/1` is called with all assigns.
A stateless component is always mounted, updated, and rendered whenever
the parent template changes. That's why they are stateless: no state
is kept after the component.
However, any component can be made stateful by passing an `:id` assign.
## Stateful components life-cycle
A stateful component is a component that receives an `:id` on `live_component/3`:
<%= live_component @socket, HeroComponent, id: :hero, content: @content %>
Stateful components are identified by the component module and their ID.
Therefore, two different component modules with the same ID are different
components. This means we can often tie the component ID to some application
based ID:
<%= live_component @socket, UserComponent, id: @user.id, user: @user %>
Also note the given `:id` is not necessarily used as the DOM ID. If you
want to set a DOM ID, it is your responsibility to set it when rendering:
defmodule UserComponent do
use Phoenix.LiveComponent
def render(assigns) do
~L\"""
<div id="user-<%= @id %>" class="user"><%= @user.name %></div>
\"""
end
end
In stateful components, `c:mount/1` is called only once, when the
component is first rendered. Then for each rendering, the optional
`c:preload/1` and `c:update/2` callbacks are called before `c:render/1`.
## Targeting Component Events
Stateful components can also implement the `c:handle_event/3` callback
that works exactly the same as in LiveView. For a client event to
reach a component, the tag must be annotated with a `phx-target`.
If you want to send the event to yourself, you can simply use the
`@myself` assign, which is an *internal unique reference* to the
component instance:
<a href="#" phx-click="say_hello" phx-target="<%= @myself %>">
Say hello!
</a>
Note `@myself` is not set for stateless components, as they cannot
receive events.
If you want to target another component, you can also pass an ID
or a class selector to any element inside the targeted component.
For example, if there is a `UserComponent` with the DOM ID of `user-13`,
using a query selector, we can send an event to it with:
<a href="#" phx-click="say_hello" phx-target="#user-13">
Say hello!
</a>
In both cases, `c:handle_event/3` will be called with the
"say_hello" event. When `c:handle_event/3` is called for a component,
only the diff of the component is sent to the client, making them
extremely efficient.
Any valid query selector for `phx-target` is supported, provided that the
matched nodes are children of a LiveView or LiveComponent, for example
to send the `close` event to multiple components:
<a href="#" phx-click="close" phx-target="#modal, #sidebar">
Dismiss
</a>
### Preloading and update
Every time a stateful component is rendered, both `c:preload/1` and
`c:update/2` is called. To understand why both callbacks are necessary,
imagine that you implement a component and the component needs to load
some state from the database. For example:
<%= live_component @socket, UserComponent, id: user_id %>
A possible implementation would be to load the user on the `c:update/2`
callback:
def update(assigns, socket) do
user = Repo.get! User, assigns.id
{:ok, assign(socket, :user, user)}
end
However, the issue with said approach is that, if you are rendering
multiple user components in the same page, you have a N+1 query problem.
The `c:preload/1` callback helps address this problem as it is invoked
with a list of assigns for all components of the same type. For example,
instead of implementing `c:update/2` as above, one could implement:
def preload(list_of_assigns) do
list_of_ids = Enum.map(list_of_assigns, & &1.id)
users =
from(u in User, where: u.id in ^list_of_ids, select: {u.id, u})
|> Repo.all()
|> Map.new()
Enum.map(list_of_assigns, fn assigns ->
Map.put(assigns, :user, users[assigns.id])
end)
end
Now only a single query to the database will be made. In fact, the
preloading algorithm is a breadth-first tree traversal, which means
that even for nested components, the amount of queries are kept to
a minimum.
Finally, note that `c:preload/1` must return an updated `list_of_assigns`,
keeping the assigns in the same order as they were given.
## Managing state
Now that we have learned how to define and use components, as well as
how to use `c:preload/1` as a data loading optimization, it is important
to talk about how to manage state in components.
Generally speaking, you want to avoid both the parent LiveView and the
LiveComponent working on two different copies of the state. Instead, you
should assume only one of them to be the source of truth. Let's discuss
these approaches in detail.
Imagine a scenario where LiveView represents a board with each card in
it as a separate component. Each card has a form that allows to update
its title directly in the component. We will see how to organize the
data flow keeping either the view or the component as the source of truth.
### LiveView as the source of truth
If the LiveView is the source of truth, the LiveView will be responsible
for fetching all of the cards in a board. Then it will call `live_component/3`
for each card, passing the card struct as argument to CardComponent:
<%= for card <- @cards do %>
<%= live_component @socket, CardComponent, card: card, id: card.id, board_id: @id %>
<% end %>
Now, when the user submits a form inside the CardComponent to update the
card, `CardComponent.handle_event/3` will be triggered. However, if the
update succeeds, you must not change the card struct inside the component.
If you do so, the card struct in the component will get out of sync with
the LiveView. Since the LiveView is the source of truth, we should instead
tell the LiveView the card was updated.
Luckily, because the component and the view run in the same process,
sending a message from the component to the parent LiveView is as simple
as sending a message to self:
defmodule CardComponent do
...
def handle_event("update_title", %{"title" => title}, socket) do
send self(), {:updated_card, %{socket.assigns.card | title: title}}
{:noreply, socket}
end
end
The LiveView can receive this event using `handle_info`:
defmodule BoardView do
...
def handle_info({:updated_card, card}, socket) do
# update the list of cards in the socket
{:noreply, updated_socket}
end
end
As the list of cards in the parent socket was updated, the parent
will be re-rendered, sending the updated card to the component.
So in the end, the component does get the updated card, but always
driven from the parent.
Alternatively, instead of having the component directly send a
message to the parent, the component could broadcast the update
using `Phoenix.PubSub`. Such as:
defmodule CardComponent do
...
def handle_event("update_title", %{"title" => title}, socket) do
message = {:updated_card, %{socket.assigns.card | title: title}}
Phoenix.PubSub.broadcast(MyApp.PubSub, board_topic(socket), message)
{:noreply, socket}
end
defp board_topic(socket) do
"board:" <> socket.assigns.board_id
end
end
As long as the parent LiveView subscribes to the "board:ID" topic,
it will receive updates. The advantage of using PubSub is that we get
distributed updates out of the box. Now if any user connected to the
board changes a card, all other users will see the change.
### LiveComponent as the source of truth
If the component is the source of truth, then the LiveView must no
longer fetch all of the cards structs from the database. Instead,
the view must only fetch all of the card ids and render the component
only by passing the IDs:
<%= for card_id <- @card_ids do %>
<%= live_component @socket, CardComponent, id: card_id, board_id: @id %>
<% end %>
Now, each CardComponent loads their own card. Of course, doing so per
card would be expensive and lead to N queries, where N is the number
of components, so we must use the `c:preload/1` callback to make it
efficient.
Once all card components are started, they can fully manage each
card as a whole, without concerning themselves with the parent LiveView.
However, note that components do not have a `handle_info/2` callback.
Therefore, if you want to track distributed changes on a card, you
must have the parent LiveView receive those events and redirect them
to the appropriate card. For example, assuming card updates are sent
to the "board:ID" topic, and that the board LiveView is subscribed to
said topic, one could do:
def handle_info({:updated_card, card}, socket) do
send_update CardComponent, id: card.id, board_id: socket.assigns.id
{:noreply, socket}
end
With `send_update`, the CardComponent given by `id` will be invoked,
triggering both preload and update callbacks, which will load the
most up to date data from the database.
## Live component blocks
When `live_component` is invoked, it is also possible to pass a `do/end`
block:
<%= live_component @socket, GridComponent, entries: @entries do %>
New entry: <%= @entry %>
<% end %>
The `do/end` will be available as an anonymous function in an assign named
`@inner_content`. The anonymous function must be invoked passing a new set
of assigns that will be merged into the user assigns. For example, the grid
component above could be implemented as:
defmodule GridComponent do
use Phoenix.LiveComponent
def render(assigns) do
~L\"""
<div class="grid">
<%= for entry <- @entries do %>
<div class="column">
<%= @inner_content.(entry: entry) %>
</div>
<% end %>
</div>
\"""
end
end
Where the `:entry` assign was injected into the `do/end` block.
The approach above is the preferred one when passing blocks to `do/end`.
However, if you are outside of a .leex template and you want to invoke a
component passing `do/end` blocks, you will have to explicitly handle the
assigns by giving it a clause:
live_component @socket, GridComponent, entries: @entries do
new_assigns -> "New entry: " <> new_assigns[:entry]
end
## Live patches and live redirects
A template rendered inside a component can use `live_patch` and
`live_redirect` calls. The `live_patch` is always handled by the parent
`LiveView`, as components do not provide `handle_params`.
## Limitations
Components must only contain HTML tags at their root. At least one HTML
tag must be present. It is not possible to have components that render
only text or text mixed with tags at the root.
Another limitation of components is that they must always be change
tracked. For example, if you render a component inside `form_for`, like
this:
<%= form_for @changeset, "#", fn f -> %>
<%= live_component @socket, SomeComponent, f: f %>
<% end %>
The component ends up enclosed by the form markup, where LiveView
cannot track it. In such cases, you may receive an error such as:
** (ArgumentError) cannot convert component SomeComponent to HTML.
A component must always be returned directly as part of a LiveView template
In this particular case, this can be addressed by using the `form_for`
variant without anonymous functions:
<%= f = form_for @changeset, "#" %>
<%= live_component @socket, SomeComponent, f: f %>
</form>
This issue can also happen with other helpers, such as `content_tag`:
<%= content_tag :div do %>
<%= live_component @socket, SomeComponent, f: f %>
<% end %>
In this case, the solution is to not use `content_tag` and rely on LiveEEx
to build the markup.
"""
alias Phoenix.LiveView.Socket
defmacro __using__(_) do
quote do
import Phoenix.LiveView
import Phoenix.LiveView.Helpers
@behaviour Phoenix.LiveComponent
@before_compile Phoenix.LiveView.Renderer
@doc false
def __live__, do: %{kind: :component, module: __MODULE__}
end
end
@callback mount(socket :: Socket.t()) ::
{:ok, Socket.t()} | {:ok, Socket.t(), keyword()}
@callback preload(list_of_assigns :: [Socket.assigns()]) ::
list_of_assigns :: [Socket.assigns()]
@callback update(assigns :: Socket.assigns(), socket :: Socket.t()) ::
{:ok, Socket.t()}
@callback render(assigns :: Socket.assigns()) :: Phoenix.LiveView.Rendered.t()
@callback handle_event(
event :: binary,
unsigned_params :: Socket.unsigned_params(),
socket :: Socket.t()
) ::
{:noreply, Socket.t()}
@optional_callbacks mount: 1, preload: 1, update: 2, handle_event: 3
end
| 37.634085 | 92 | 0.688998 |
1ce9e32647cf38dcffc19807527fd678ae6456b3 | 1,260 | exs | Elixir | config/dev.exs | erwald/hangman | 38c8b6cc45bb3bf9f44d6fe5d33714b40dd78d26 | [
"MIT"
] | 1 | 2016-06-28T10:48:46.000Z | 2016-06-28T10:48:46.000Z | config/dev.exs | erwald/hangman | 38c8b6cc45bb3bf9f44d6fe5d33714b40dd78d26 | [
"MIT"
] | null | null | null | config/dev.exs | erwald/hangman | 38c8b6cc45bb3bf9f44d6fe5d33714b40dd78d26 | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :hangman, Hangman.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin"]]
# Watch static and templates for browser reloading.
config :hangman, Hangman.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development.
# Do not configure such in production as keeping
# and calculating stacktraces is usually expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :hangman, Hangman.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "hangman_dev",
hostname: "localhost",
pool_size: 10
| 29.302326 | 74 | 0.70873 |
1cea0496ca14da009b003430c1b9809fe4facf3b | 1,048 | ex | Elixir | test/support/channel_case.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | defmodule CgratesWebJsonapi.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build 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 channels
use Phoenix.ChannelTest
alias CgratesWebJsonapi.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
# The default endpoint for testing
@endpoint CgratesWebJsonapi.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(CgratesWebJsonapi.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(CgratesWebJsonapi.Repo, {:shared, self()})
end
:ok
end
end
| 23.818182 | 79 | 0.714695 |
1cea63d148a7bda8fb4d9a55e2f076794547e5cd | 552 | ex | Elixir | Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/backend_address_pool.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/backend_address_pool.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/backend_address_pool.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule Microsoft.Azure.Management.Network.Model.BackendAddressPool do
@moduledoc """
Pool of backend IP addresses.
"""
@derive [Poison.Encoder]
defstruct [
:"id"
]
@type t :: %__MODULE__{
:"id" => String.t
}
end
defimpl Poison.Decoder, for: Microsoft.Azure.Management.Network.Model.BackendAddressPool do
def decode(value, _options) do
value
end
end
| 21.230769 | 91 | 0.71558 |
1cea8caaf2503d9b399b35f590cdb36c4a1f2c4a | 1,495 | exs | Elixir | test/acceptance/html/block_quotes_test.exs | manuel-rubio/earmark | d747d73d31e8b8fa39389b01fc67cc53d946b707 | [
"Apache-1.1"
] | 734 | 2015-01-05T19:08:00.000Z | 2022-03-28T14:04:21.000Z | test/acceptance/html/block_quotes_test.exs | manuel-rubio/earmark | d747d73d31e8b8fa39389b01fc67cc53d946b707 | [
"Apache-1.1"
] | 343 | 2015-01-01T04:56:57.000Z | 2022-02-15T11:00:57.000Z | test/acceptance/html/block_quotes_test.exs | manuel-rubio/earmark | d747d73d31e8b8fa39389b01fc67cc53d946b707 | [
"Apache-1.1"
] | 169 | 2015-02-26T15:18:05.000Z | 2022-03-18T08:00:42.000Z | defmodule Acceptance.Html.BlockQuotesTest do
use ExUnit.Case, async: true
describe "with breaks: true" do
test "acceptance test 490 with breaks" do
markdown = "> bar\nbaz\n> foo\n"
html = "<blockquote>\n <p>\nbar <br />\nbaz <br />\nfoo </p>\n</blockquote>\n"
assert Earmark.as_html!(markdown, breaks: true) == html
end
test "acceptance test 582 with breaks" do
markdown = "* x\n a\n| A | B |"
html = "<ul>\n <li>\nx <br />\na <br />\n| A | B | </li>\n</ul>\n"
assert Earmark.as_html!(markdown, breaks: true) == html
end
end
describe "with breaks: false" do
test "quote my block" do
markdown = "> Foo"
html = "<blockquote>\n <p>\nFoo </p>\n</blockquote>\n"
messages = []
assert Earmark.as_html(markdown) == {:ok, html, messages}
end
test "lists in blockquotes? Coming up Sir" do
markdown = "> - foo\n- bar\n"
html = "<blockquote>\n <ul>\n <li>\nfoo </li>\n </ul>\n</blockquote>\n<ul>\n <li>\nbar </li>\n</ul>\n"
messages = []
assert Earmark.as_html(markdown) == {:ok, html, messages}
end
test "indented case" do
markdown = " > - foo\n- bar\n"
html = "<blockquote>\n <ul>\n <li>\nfoo </li>\n </ul>\n</blockquote>\n<ul>\n <li>\nbar </li>\n</ul>\n"
messages = []
assert Earmark.as_html(markdown) == {:ok, html, messages}
end
end
end
# SPDX-License-Identifier: Apache-2.0
| 31.808511 | 122 | 0.553846 |
1ceaa154299ca62e18936655afd89c3782e6786e | 683 | ex | Elixir | lib/phoenix/endpoint/watcher.ex | benjamintanweihao/phoenix | eb4ef03852f447d67cd61355753147c39b520e1f | [
"MIT"
] | null | null | null | lib/phoenix/endpoint/watcher.ex | benjamintanweihao/phoenix | eb4ef03852f447d67cd61355753147c39b520e1f | [
"MIT"
] | null | null | null | lib/phoenix/endpoint/watcher.ex | benjamintanweihao/phoenix | eb4ef03852f447d67cd61355753147c39b520e1f | [
"MIT"
] | null | null | null | defmodule Phoenix.Endpoint.Watcher do
@moduledoc false
require Logger
def start_link(root, cmd, args) do
Task.start_link(__MODULE__, :watch, [root, to_string(cmd), args])
end
def watch(root, cmd, args) do
if exists?(cmd) do
System.cmd(cmd, args, into: IO.stream(:stdio, :line),
stderr_to_stdout: true, cd: root)
else
relative = Path.relative_to_cwd(cmd)
Logger.error "Could not start watcher #{inspect relative}, executable does not exist"
exit(:shutdown)
end
end
defp exists?(cmd) do
if Path.type(cmd) == :absolute do
File.exists?(cmd)
else
!!System.find_executable(cmd)
end
end
end | 25.296296 | 91 | 0.648609 |
1ceaa83ff0b42d1646058e051ac7491e93bc88b4 | 1,474 | ex | Elixir | lib/screens/config/solari/section/layout.ex | mbta/screens | 4b586970f8844b19543bb2ffd4b032a89f6fa40a | [
"MIT"
] | 3 | 2021-07-27T14:11:00.000Z | 2022-01-03T14:16:43.000Z | lib/screens/config/solari/section/layout.ex | mbta/screens | 4b586970f8844b19543bb2ffd4b032a89f6fa40a | [
"MIT"
] | 444 | 2021-03-10T20:57:17.000Z | 2022-03-31T16:00:35.000Z | lib/screens/config/solari/section/layout.ex | mbta/screens | 4b586970f8844b19543bb2ffd4b032a89f6fa40a | [
"MIT"
] | null | null | null | defmodule Screens.Config.Solari.Section.Layout do
@moduledoc false
alias Screens.Config.Solari.Section.Layout.{Bidirectional, Upcoming}
@behaviour Screens.Config.Behaviour
@type t ::
Bidirectional.t()
| Upcoming.t()
@default_type :upcoming
@opts_modules %{
bidirectional: Bidirectional,
upcoming: Upcoming
}
@impl true
@spec from_json(map() | :default) :: t()
def from_json(%{} = json) do
type = Map.get(json, "type", :default)
opts = Map.get(json, "opts", :default)
opts_from_json(opts, type)
end
def from_json(:default) do
@opts_modules[@default_type].from_json(:default)
end
@impl true
@spec to_json(t()) :: map()
def to_json(%Bidirectional{} = layout) do
%{
"type" => "bidirectional",
"opts" => Bidirectional.to_json(layout)
}
end
def to_json(%Upcoming{} = layout) do
%{
"type" => "upcoming",
"opts" => Upcoming.to_json(layout)
}
end
for type <- ~w[bidirectional upcoming]a do
type_string = Atom.to_string(type)
opts_module = @opts_modules[type]
defp type_to_json(unquote(type)) do
unquote(type_string)
end
defp opts_from_json(opts, unquote(type_string)) do
unquote(opts_module).from_json(opts)
end
defp opts_to_json(opts, unquote(type)) do
unquote(opts_module).to_json(opts)
end
end
defp opts_from_json(_, _) do
@opts_modules[@default_type].from_json(:default)
end
end
| 21.057143 | 70 | 0.648575 |
1ceb2233b019e75d7a7d29e8fe2ffb7d73898f59 | 1,504 | exs | Elixir | test/local_hex_web/plugs/auth_token_check_test.exs | imsoulfly/local_hex_repo | 18fca51c44b3dd01d27684877b3c7bc13471f548 | [
"Apache-2.0"
] | 5 | 2021-11-13T13:58:06.000Z | 2022-03-26T03:47:57.000Z | test/local_hex_web/plugs/auth_token_check_test.exs | imsoulfly/local_hex_repo | 18fca51c44b3dd01d27684877b3c7bc13471f548 | [
"Apache-2.0"
] | 3 | 2021-11-16T18:45:45.000Z | 2021-12-05T13:58:25.000Z | test/local_hex_web/plugs/auth_token_check_test.exs | imsoulfly/local_hex_repo | 18fca51c44b3dd01d27684877b3c7bc13471f548 | [
"Apache-2.0"
] | null | null | null | defmodule LocalHexWeb.Plugs.AuthTokenCheckTest do
use LocalHexWeb.ConnCase
alias LocalHexWeb.Plugs.AuthTokenCheck
test "init just returns opts" do
opts = [test: :foo]
result = AuthTokenCheck.init(opts)
assert ^opts = result
end
test "call successful with not not matching endpoint" do
conn =
build_conn(:get, "/another_endpoint")
|> Plug.Conn.put_req_header(
"authorization",
Application.fetch_env!(:local_hex, :auth_token)
)
|> AuthTokenCheck.call([])
assert conn.halted == false
end
test "call successful with correct authorization header" do
conn =
build_conn(:get, "/api/endpoint")
|> Plug.Conn.put_req_header(
"authorization",
Application.fetch_env!(:local_hex, :auth_token)
)
|> AuthTokenCheck.call([])
assert conn.halted == false
end
test "call unauthorized with wrong authorization header" do
conn =
build_conn(:get, "/api/endpoint")
|> Plug.Conn.put_req_header("authorization", "wrong")
|> AuthTokenCheck.call([])
assert conn.status == 401
assert conn.halted == true
assert :erlang.binary_to_term(conn.resp_body) == "unauthorized"
end
test "call unauthorized with missing authorization header" do
conn =
build_conn(:get, "/api/endpoint")
|> AuthTokenCheck.call([])
assert conn.status == 401
assert conn.halted == true
assert :erlang.binary_to_term(conn.resp_body) == "unauthorized"
end
end
| 25.931034 | 67 | 0.662899 |
1ceb3b6a34bfa01e0a44420f8f2f41df15a66ff3 | 985 | exs | Elixir | test/flatten_and_deepen_test.exs | RobertDober/nested_map | 8b70579401e560929fd5e07c6e6f2c10df7ba084 | [
"Apache-2.0"
] | 1 | 2021-08-23T23:54:35.000Z | 2021-08-23T23:54:35.000Z | test/flatten_and_deepen_test.exs | RobertDober/nested_map | 8b70579401e560929fd5e07c6e6f2c10df7ba084 | [
"Apache-2.0"
] | null | null | null | test/flatten_and_deepen_test.exs | RobertDober/nested_map | 8b70579401e560929fd5e07c6e6f2c10df7ba084 | [
"Apache-2.0"
] | null | null | null | defmodule Test.FlattenAndDeepenTest do
use ExUnit.Case
import NestedMap, only: [deepen: 1, flatten: 1]
import Test.Support.RandomMap
@tests 200
@n 1000
describe "property test" do
(1..@tests)
|> Enum.each(fn test_n ->
expected = rand_flattened_elements(@n) |> deepen()
result = expected |> flatten() |> deepen()
quote do
unquote do
test("property #{test_n}") do
result = unquote(Macro.escape(result))
expected = unquote(Macro.escape(expected))
assert result == expected
end
end
end
end)
end
describe "edge cases" do
test "empty" do
assert_idem %{}
end
test "singleton" do
assert_idem %{a: 1}
end
end
defp assert_idem(map) do
assert _flatten_and_deepen(map) == map
end
defp _flatten_and_deepen(map) do
map
|> NestedMap.flatten
|> NestedMap.deepen
end
end
| 21.888889 | 60 | 0.573604 |
1ceb578965aeb86491469e429192e9d45302771f | 1,348 | exs | Elixir | machine_translation/MorpHIN/Learned/Resources/Set5/TrainingInstances/86.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set5/TrainingInstances/86.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set5/TrainingInstances/86.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | **EXAMPLE FILE**
pnoun cm noun cm quantifier;
verb SYM adjective noun quantifier;
cm cm noun demonstrative quantifier;
cm adjective particle quantifier quantifier;
noun cm noun cm quantifier;
pnoun cm noun pnoun quantifier;
pn adjective noun cm quantifier;
pnoun cm noun cm quantifier;
pnoun cm noun cm quantifier;
noun cm noun cm quantifier;
verb_aux pn noun noun quantifier;
pn cm noun cm quantifier;
cm cm noun adjective quantifier;
pnoun conj noun cm quantifier;
cm nst pnoun adjective quantifier;
pn cm noun adjective quantifier;
verb conj adjective noun quantifier;
noun cm noun verb quantifier;
cm pn noun cm quantifier;
pnoun conj adjective noun quantifier;
cm noun noun verb quantifier;
cm nst noun pn quantifier;
pnoun cm adjective noun quantifier;
verb pn noun verb quantifier;
cm noun noun conj quantifier;
pn cm adjective noun quantifier;
pnoun cm noun pnoun quantifier;
noun cm adjective noun quantifier;
conj pnoun noun cm quantifier;
SYM adjective noun cm quantifier;
verb_aux pn cm noun quantifier;
noun cm adjective noun quantifier;
verb conj quantifier noun quantifier;
verb verb_aux adjective pnoun quantifier;
verb adjective noun pn quantifier;
pn pn noun verb quantifier;
cm adverb noun quantifier quantifier;
nst particle noun adjective quantifier;
pnoun cm adjective noun quantifier;
| 32.095238 | 45 | 0.792285 |
1ceb70965a6dc1b3d68f2929a640da7ebbccdd1e | 1,559 | ex | Elixir | lib/runlet/cmd/limit.ex | msantos/runlet | d9cb44b113295387c296ab4576a09ca4a7ce0f7b | [
"ISC"
] | 4 | 2020-01-12T19:04:46.000Z | 2021-09-20T14:37:22.000Z | lib/runlet/cmd/limit.ex | msantos/runlet | d9cb44b113295387c296ab4576a09ca4a7ce0f7b | [
"ISC"
] | null | null | null | lib/runlet/cmd/limit.ex | msantos/runlet | d9cb44b113295387c296ab4576a09ca4a7ce0f7b | [
"ISC"
] | 1 | 2021-09-20T14:37:25.000Z | 2021-09-20T14:37:25.000Z | defmodule Runlet.Cmd.Limit do
@moduledoc "Limit events to count per seconds"
@doc """
Set upper limit on the number of events permitted per *seconds*
seconds. Events exceeding this rate are discarded.
"""
@spec exec(Enumerable.t(), pos_integer, pos_integer) :: Enumerable.t()
def exec(stream, count, seconds \\ 60) do
exec(stream, count, seconds, inspect(:erlang.make_ref()))
end
@doc false
@spec exec(Enumerable.t(), pos_integer, pos_integer, String.t()) ::
Enumerable.t()
def exec(stream, limit, seconds, name) when limit > 0 and seconds > 0 do
milliseconds = seconds * 1_000
Stream.transform(
stream,
fn -> true end,
fn
%Runlet.Event{event: %Runlet.Event.Signal{}} = t, alert ->
{[t], alert}
t, alert ->
case {ExRated.check_rate(name, milliseconds, limit), alert} do
{{:ok, _}, _} ->
{[t], true}
{{:error, _}, true} ->
{[
%Runlet.Event{
event: %Runlet.Event.Ctrl{
service: "limit",
description:
"limit reached: new events will be dropped (#{limit} events/#{seconds} seconds)",
host: "#{node()}"
},
query: "limit #{limit} #{seconds}"
}
], false}
{{:error, _}, false} ->
{[], false}
end
end,
fn _ ->
ExRated.delete_bucket(name)
end
)
end
end
| 28.87037 | 104 | 0.503528 |
1ceb7849422bb7573022861fc81b0516ba590763 | 2,207 | ex | Elixir | lib/thumbifier/convert/types.ex | sysdia-solutions/thumbifier | b2b71571bb8a33159e5d90ecb5ea3931eafdd62b | [
"MIT"
] | 4 | 2016-10-16T22:22:52.000Z | 2019-05-24T13:44:15.000Z | lib/thumbifier/convert/types.ex | sysdia-solutions/thumbifier | b2b71571bb8a33159e5d90ecb5ea3931eafdd62b | [
"MIT"
] | 1 | 2016-10-21T00:16:16.000Z | 2017-09-24T02:24:23.000Z | lib/thumbifier/convert/types.ex | sysdia-solutions/thumbifier | b2b71571bb8a33159e5d90ecb5ea3931eafdd62b | [
"MIT"
] | null | null | null | defmodule Thumbifier.Convert.Types do
def all() do
basic_image
++ pdf
++ psd
++ video
++ website
++ document
++ spreadsheet
++ presentation
end
def is_supported?(type) do
type in all
end
def is_basic_image?(type) do
type in basic_image
end
def is_pdf?(type) do
type in pdf
end
def is_psd?(type) do
type in psd
end
def is_video?(type) do
type in video
end
def is_website?(type) do
type in website
end
def is_document?(type) do
type in document
end
def is_spreadsheet?(type) do
type in spreadsheet
end
def is_presentation?(type) do
type in presentation
end
defp basic_image() do
[
"image/jpg",
"image/pjpeg",
"image/jpeg",
"image/gif",
"image/png",
"image/bmp",
"image/x-bmp",
"image/x-bitmap",
"image/x-xbitmap",
"image/x-win-bitmap",
"image/x-windows-bmp",
"image/ms-bmp",
"image/x-ms-bmp",
"image/tif",
"image/x-tif",
"image/tiff",
"image/x-tiff"
]
end
defp pdf() do
[
"application/pdf"
]
end
defp psd() do
[
"image/photoshop",
"image/x-photoshop",
"image/psd",
"image/vnd.adobe.photoshop",
"application/photoshop",
"application/psd"
]
end
defp video() do
[
"video/x-ms-asf",
"video/x-ms-wmv",
"video/msvideo",
"video/x-msvideo",
"video/mpeg",
"video/x-mpeg",
"video/mp4"
]
end
defp website() do
[
"website"
]
end
defp document() do
[
"application/msword",
"application/vnd.oasis.opendocument.text",
"application/x-vnd.oasis.opendocument.text"
]
end
defp spreadsheet() do
[
"application/vnd.ms-excel",
"application/vnd.oasis.opendocument.spreadsheet",
"application/x-vnd.oasis.opendocument.spreadsheet",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
]
end
defp presentation() do
[
"application/vnd.ms-powerpoint",
"application/vnd.oasis.opendocument.presentation",
"application/x-vnd.oasis.opendocument.presentation"
]
end
end
| 16.847328 | 73 | 0.583598 |
1ceb959406ddbc3606a0673fa471abd1a502c25a | 84,885 | ex | Elixir | lib/phoenix_live_view.ex | full-stack-biz/phoenix_live_view | 5b9fe24ff1b2e91a97681259df993badcd4cd461 | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | full-stack-biz/phoenix_live_view | 5b9fe24ff1b2e91a97681259df993badcd4cd461 | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | full-stack-biz/phoenix_live_view | 5b9fe24ff1b2e91a97681259df993badcd4cd461 | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveView do
@moduledoc ~S'''
LiveView provides rich, real-time user experiences with
server-rendered HTML.
LiveView programming model is declarative: instead of
saying "once event X happens, change Y on the page",
events in LiveView are regular messages which may cause
changes to its state. Once the state changes, LiveView will
re-render the relevant parts of its HTML template and push it
to the browser, which updates itself in the most efficient
manner. This means developers write LiveView templates as
any other server-rendered HTML and LiveView does the hard
work of tracking changes and sending the relevant diffs to
the browser.
At the end of the day, a LiveView is nothing more than a
process that receives events as messages and updates its
state. The state itself is nothing more than functional
and immutable Elixir data structures. The events are either
internal application messages (usually emitted by `Phoenix.PubSub`)
or sent by the client/browser.
LiveView is first rendered statically as part of regular
HTTP requests, which provides quick times for "First Meaningful
Paint", in addition to helping search and indexing engines.
Then a persistent connection is established between client and
server. This allows LiveView applications to react faster to user
events as there is less work to be done and less data to be sent
compared to stateless requests that have to authenticate, decode, load,
and encode data on every request. The flipside is that LiveView
uses more memory on the server compared to stateless requests.
## Use cases
There are many use cases where LiveView is an excellent
fit right now:
* Handling of user interaction and inputs, buttons, and
forms - such as input validation, dynamic forms,
autocomplete, etc;
* Events and updates pushed by server - such as
notifications, dashboards, etc;
* Page and data navigation - such as navigating between
pages, pagination, etc can be built with LiveView
using the excellent live navigation feature set.
This reduces the amount of data sent over the wire,
gives developers full control over the LiveView
life-cycle, while controlling how the browser
tracks those changes in state;
There are also use cases which are a bad fit for LiveView:
* Animations - animations, menus, and general events
that do not need the server in the first place are a
bad fit for LiveView, as they can be achieved purely
with CSS and/or CSS transitions;
## Life-cycle
A LiveView begins as a regular HTTP request and HTML response,
and then upgrades to a stateful view on client connect,
guaranteeing a regular HTML page even if JavaScript is disabled.
Any time a stateful view changes or updates its socket assigns, it is
automatically re-rendered and the updates are pushed to the client.
You begin by rendering a LiveView typically from your router.
When LiveView is first rendered, the `mount/3` callback is invoked
with the current params, the current session and the LiveView socket.
As in a regular request, `params` contains public data that can be
modified by the user. The `session` always contains private data set
by the application itself. The `mount/3` callback wires up socket
assigns necessary for rendering the view. After mounting, `render/1`
is invoked and the HTML is sent as a regular HTML response to the
client.
After rendering the static page, LiveView connects from the client
to the server where stateful views are spawned to push rendered updates
to the browser, and receive client events via phx bindings. Just like
the first rendering, `mount/3` is invoked with params, session,
and socket state, where mount assigns values for rendering. However
in the connected client case, a LiveView process is spawned on
the server, pushes the result of `render/1` to the client and
continues on for the duration of the connection. If at any point
during the stateful life-cycle a crash is encountered, or the client
connection drops, the client gracefully reconnects to the server,
calling `mount/3` once again.
## Example
First, a LiveView requires two callbacks: `mount/3` and `render/1`:
defmodule MyAppWeb.ThermostatLive do
# If you generated an app with mix phx.new --live,
# the line below would be: use MyAppWeb, :live_view
use Phoenix.LiveView
def render(assigns) do
~L"""
Current temperature: <%= @temperature %>
"""
end
def mount(_params, %{"current_user_id" => user_id}, socket) do
temperature = Thermostat.get_user_reading(user_id)
{:ok, assign(socket, :temperature, temperature)}
end
end
The `render/1` callback receives the `socket.assigns` and is responsible
for returning rendered content. You can use `Phoenix.LiveView.Helpers.sigil_L/2`
to inline LiveView templates. If you want to use `Phoenix.HTML` helpers,
remember to `use Phoenix.HTML` at the top of your `LiveView`.
With a LiveView defined, you first define the `socket` path in your endpoint,
and point it to `Phoenix.LiveView.Socket`:
defmodule MyAppWeb.Endpoint do
use Phoenix.Endpoint
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]]
...
end
Where `@session_options` are the options given to `plug Plug.Session` extracted
to a module attribute.
And configure its signing salt in the endpoint:
config :my_app, MyAppWeb.Endpoint,
...,
live_view: [signing_salt: ...]
You can generate a secure, random signing salt with the `mix phx.gen.secret 32` task.
Next, decide where you want to use your LiveView.
You can serve the LiveView directly from your router (recommended):
defmodule MyAppWeb.Router do
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", MyAppWeb do
live "/thermostat", ThermostatLive
end
end
You can also `live_render` from any template:
<h1>Temperature Control</h1>
<%= live_render(@conn, MyAppWeb.ThermostatLive) %>
Or you can `live_render` your view from any controller:
defmodule MyAppWeb.ThermostatController do
...
import Phoenix.LiveView.Controller
def show(conn, %{"id" => id}) do
live_render(conn, MyAppWeb.ThermostatLive)
end
end
When a LiveView is rendered, all of the data currently stored in the
connection session (see `Plug.Conn.get_session/1`) will be given to
the LiveView.
It is also possible to pass additional session information to the LiveView
through a session parameter:
# In the router
live "/thermostat", ThermostatLive, session: %{"extra_token" => "foo"}
# In a view
<%= live_render(@conn, MyAppWeb.ThermostatLive, session: %{"extra_token" => "foo"}) %>
Notice the `:session` uses string keys as a reminder that session data
is serialized and sent to the client. So you should always keep the data
in the session to a minimum. For example, instead of storing a User struct,
you should store the "user_id" and load the User when the LiveView mounts.
Once the LiveView is rendered, a regular HTML response is sent. Next, your
client code connects to the server:
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
liveSocket.connect()
After the client connects, `mount/3` will be invoked inside a spawned
LiveView process. At this point, you can use `connected?/1` to
conditionally perform stateful work, such as subscribing to pubsub topics,
sending messages, etc. For example, you can periodically update a LiveView
with a timer:
defmodule DemoWeb.ThermostatLive do
use Phoenix.LiveView
...
def mount(_params, %{"current_user_id" => user_id}, socket) do
if connected?(socket), do: Process.send_after(self(), :update, 30000)
case Thermostat.get_user_reading(user_id) do
{:ok, temperature} ->
{:ok, assign(socket, temperature: temperature, user_id: user_id)}
{:error, reason} ->
{:error, reason}
end
end
def handle_info(:update, socket) do
Process.send_after(self(), :update, 30000)
{:ok, temperature} = Thermostat.get_reading(socket.assigns.user_id)
{:noreply, assign(socket, :temperature, temperature)}
end
end
We used `connected?(socket)` on mount to send our view a message every 30s if
the socket is in a connected state. We receive the `:update` message in the
`handle_info/2` callback, just like in an Elixir's `GenServer`, and update our
socket assigns. Whenever a socket's assigns change, `render/1` is automatically
invoked, and the updates are sent to the client.
## Collocating templates
In the examples above, we have placed the template directly inside the
LiveView:
defmodule MyAppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
~L"""
Current temperature: <%= @temperature %>
"""
end
For larger templates, you can place them in a file in the same directory
and same name as the LiveView. For example, if the file above is placed
at `lib/my_app_web/live/thermostat_live.ex`, you can also remove the
`render/1` definition above and instead put the template code at
`lib/my_app_web/live/thermostat_live.html.leex`.
Alternatively, you can keep the `render/1` callback but delegate to an
existing `Phoenix.View` module in your application. For example:
defmodule MyAppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
Phoenix.View.render(MyAppWeb.PageView, "page.html", assigns)
end
end
In all cases, each assign in the template will be accessible as `@assign`.
## Assigns and LiveEEx Templates
All of the data in a LiveView is stored in the socket as assigns.
The `assign/2` and `assign/3` functions help store those values.
Those values can be accessed in the LiveView as `socket.assigns.name`
but they are accessed inside LiveView templates as `@name`.
`Phoenix.LiveView`'s built-in templates are identified by the `.leex`
extension (Live EEx) or `~L` sigil. They are similar to regular `.eex`
templates except they are designed to minimize the amount of data sent
over the wire by splitting static and dynamic parts and tracking changes.
When you first render a `.leex` template, it will send all of the
static and dynamic parts of the template to the client. After that,
any change you do on the server will now send only the dynamic parts,
and only if those parts have changed.
The tracking of changes is done via assigns. Imagine this template:
<h1><%= expand_title(@title) %></h1>
If the `@title` assign changes, then LiveView will execute
`expand_title(@title)` and send the new content. If `@title` is
the same, nothing is executed and nothing is sent.
Change tracking also works when accessing map/struct fields.
Take this template:
<div id="user_<%= @user.id %>">
<%= @user.name %>
</div>
If the `@user.name` changes but `@user.id` doesn't, then LiveView
will re-render only `@user.name` and it will not execute or resend `@user.id`
at all.
The change tracking also works when rendering other templates as
long as they are also `.leex` templates:
<%= render "child_template.html", assigns %>
The assign tracking feature also implies that you MUST avoid performing
direct operations in the template. For example, if you perform a database
query in your template:
<%= for user <- Repo.all(User) do %>
<%= user.name %>
<% end %>
Then Phoenix will never re-render the section above, even if the number of
users in the database changes. Instead, you need to store the users as
assigns in your LiveView before it renders the template:
assign(socket, :users, Repo.all(User))
Generally speaking, **data loading should never happen inside the template**,
regardless if you are using LiveView or not. The difference is that LiveView
enforces this best practice.
### LiveEEx pitfalls
There are two common pitfalls to keep in mind when using the `~L` sigil
or `.leex` templates.
When it comes to `do/end` blocks, change tracking is supported only on blocks
given to Elixir's basic constructs, such as `if`, `case`, `for`, and friends.
If the do/end block is given to a library function or user function, such as
`content_tag`, change tracking won't work. For example, imagine the following
template that renders a `div`:
<%= content_tag :div, id: "user_#{@id}" do %>
<%= @name %>
<%= @description %>
<% end %>
LiveView knows nothing about `content_tag`, which means the whole `div` will
be sent whenever any of the assigns change. This can be easily fixed by
writing the HTML directly:
<div id="user_<%= @id %>">
<%= @name %>
<%= @description %>
</div>
Another pitfall of `.leex` templates is related to variables. Due to the scope
of variables, LiveView has to disable change tracking whenever variables are
used in the template, with the exception of variables introduced by Elixir
basic `case`, `for`, and other block constructs. Therefore, you **must avoid**
code like this in your LiveEEx:
<% some_var = @x + @y %>
<%= some_var %>
Instead, use a function:
<%= sum(@x, @y) %>
Or explicitly precompute the assign in your LiveView:
assign(socket, sum: socket.assigns.x + socket.assigns.y)
Similarly, **do not** define variables at the top of your `render` function:
def render(assigns) do
sum = assigns.x + assigns.y
~L"""
<%= sum %>
"""
end
Instead use functions inside the `~L` or preassign `sum` as explained above.
However, for completeness, note that variables introduced by Elixir's block
constructs are fine:
<%= for post <- @posts do %>
...
<% end %>
To sum up:
1. Avoid passing block expressions to user and library functions
2. Never do anything on `def render(assigns)` besides rendering a template
or invoking the `~L` sigil
3. Avoid defining local variables, except within `for`, `case`, and friends
## Bindings
Phoenix supports DOM element bindings for client-server interaction. For
example, to react to a click on a button, you would render the element:
<button phx-click="inc_temperature">+</button>
Then on the server, all LiveView bindings are handled with the `handle_event`
callback, for example:
def handle_event("inc_temperature", _value, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
| Binding | Attributes |
|------------------------|------------|
| [Params](#module-click-events) | `phx-value-*` |
| [Click Events](#module-click-events) | `phx-click`, `phx-capture-click` |
| [Focus/Blur Events](#module-focus-and-blur-events) | `phx-blur`, `phx-focus` |
| [Form Events](#module-form-events) | `phx-change`, `phx-submit`, `phx-feedback-for`, `phx-disable-with` |
| [Key Events](#module-key-events) | `phx-window-keydown`, `phx-window-keyup` |
| [Rate Limiting](#module-rate-limiting-events-with-debounce-and-throttle) | `phx-debounce`, `phx-throttle` |
| [DOM Patching](#module-dom-patching-and-temporary-assigns) | `phx-update` |
| [JS Interop](#module-js-interop-and-client-controlled-dom) | `phx-hook` |
### Click Events
The `phx-click` binding is used to send click events to the server.
When any client event, such as a `phx-click` click is pushed, the value
sent to the server will be chosen with the following priority:
* Any number of optional `phx-value-` prefixed attributes, such as:
<div phx-click="inc" phx-value-myvar1="val1" phx-value-myvar2="val2">
will send the following map of params to the server:
def handle_event("inc", %{"myvar1" => "val1", "myvar2" => "val2"}, socket) do
If the `phx-value-` prefix is used, the server payload will also contain a `"value"`
if the element's value attribute exists.
* When receiving a map on the server, the payload will also contain metadata of the
client event, containing all literal keys of the event object, such as a click event's
`clientX`, a keydown event's `keyCode`, etc.
The `phx-capture-click` event is just like `phx-click`, but instead of the click event
being dispatched to the closest `phx-click` element as it bubbles up through the DOM, the event
is dispatched as it propagates from the top of the DOM tree down to the target element. This is
useful when wanting to bind click events without receiving bubbled events from child UI elements.
Since capturing happens before bubbling, this can also be important for preparing or preventing
behaviour that will be applied during the bubbling phase.
### Focus and Blur Events
Focus and blur events may be bound to DOM elements that emit
such events, using the `phx-blur`, and `phx-focus` bindings, for example:
<input name="email" phx-focus="myfocus" phx-blur="myblur"/>
To detect when the page itself has received focus or blur,
`phx-window-focus` and `phx-window-blur` may be specified. These window
level events may also be necessary if the element in consideration
(most often a `div` with no tabindex) cannot receive focus. Like other
bindings, `phx-value-*` can be provided on the bound element, and those
values will be sent as part of the payload. For example:
<div class="container"
phx-window-focus="page-active"
phx-window-blur="page-inactive"
phx-value-page="123">
...
</div>
The following window-level bindings are supported:
* `phx-window-focus`
* `phx-window-blur`
* `phx-window-keydown`
* `phx-window-keyup`
### Form Events
To handle form changes and submissions, use the `phx-change` and `phx-submit`
events. In general, it is preferred to handle input changes at the form level,
where all form fields are passed to the LiveView's callback given any
single input change. For example, to handle real-time form validation and
saving, your template would use both `phx_change` and `phx_submit` bindings:
<%= f = form_for @changeset, "#", [phx_change: :validate, phx_submit: :save] %>
<%= label f, :username %>
<%= text_input f, :username %>
<%= error_tag f, :username %>
<%= label f, :email %>
<%= text_input f, :email %>
<%= error_tag f, :email %>
<%= submit "Save" %>
</form>
*Reminder*: `form_for/3` is a `Phoenix.HTML` helper. Don't forget to include
`use Phoenix.HTML` at the top of your LiveView, if using `Phoenix.HTML` helpers.
Next, your LiveView picks up the events in `handle_event` callbacks:
def render(assigns) ...
def mount(_params, _session, socket) do
{:ok, assign(socket, %{changeset: Accounts.change_user(%User{})})}
end
def handle_event("validate", %{"user" => params}, socket) do
changeset =
%User{}
|> Accounts.change_user(params)
|> Map.put(:action, :insert)
{:noreply, assign(socket, changeset: changeset)}
end
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.create_user(user_params) do
{:ok, user} ->
{:noreply,
socket
|> put_flash(:info, "user created")
|> redirect(to: Routes.user_path(MyAppWeb.Endpoint, MyAppWeb.User.ShowView, user))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
The validate callback simply updates the changeset based on all form input
values, then assigns the new changeset to the socket. If the changeset
changes, such as generating new errors, `render/1` is invoked and
the form is re-rendered.
Likewise for `phx-submit` bindings, the same callback is invoked and
persistence is attempted. On success, a `:noreply` tuple is returned and the
socket is annotated for redirect with `Phoenix.LiveView.redirect/2` to
the new user page, otherwise the socket assigns are updated with the errored
changeset to be re-rendered for the client.
*Note*: For proper form error tag updates, the error tag must specify which
input it belongs to. This is accomplished with the `phx-feedback-for` attribute.
Failing to add the `phx-feedback-for` attribute will result in displaying error
messages for form fields that the user has not changed yet (e.g. required
fields further down on the page.)
For example, your `MyAppWeb.ErrorHelpers` may use this function:
def error_tag(form, field) do
form.errors
|> Keyword.get_values(field)
|> Enum.map(fn error ->
content_tag(:span, translate_error(error),
class: "invalid-feedback",
phx_feedback_for: input_id(form, field)
)
end)
end
Now, any DOM container with the `phx-feedback-for` attribute will receive a
`phx-no-feedback` class in cases where the form fields has yet to receive
user input/focus. The following css rules are generated in new projects
to hide the errors:
.phx-no-feedback.invalid-feedback, .phx-no-feedback .invalid-feedback {
display: none;
}
### Submitting the form action over HTTP
The `phx-trigger-action` attribute can be added to a form to trigger a standard
form submit on DOM patch to the URL specified in the form's standard `action`
attribute. This is useful to perform pre-final validation of a LiveView form
submit before posting to a controller route for operations that require
Plug session mutation. For example, in your LiveView template you can
annotate the `phx-trigger-action` with a boolean assign:
<%= f = form_for @changeset, Routes.reset_password_path(@socket, :create),
phx_submit: :save,
phx_trigger_action: @trigger_submit %>
Then in your LiveView, you can toggle the assign to trigger the form with the current
fields on next render:
def handle_event("save", params, socket) do
case validate_change_password(socket.assigns.user, params) do
{:ok, changeset} ->
{:noreply, assign(socket, changeset: changeset, trigger_submit: true)}
{:error, changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
### Number inputs
Number inputs are a special case in LiveView forms. On programmatic updates,
some browsers will clear invalid inputs. So LiveView will not send change events
from the client when an input is invalid, instead allowing the browser's native
validation UI to drive user interaction. Once the input becomes valid, change and
submit events will be sent normally.
<input type="number">
This is known to have a plethora of problems including accessibility, large numbers
are converted to exponential notation and scrolling can accidentally increase or
decrease the number.
As of early 2020, the following avoids these pitfalls and will likely serve your
application's needs and users much better. According to https://caniuse.com/#search=inputmode,
the following is supported by 90% of the global mobile market with Firefox yet to implement.
<input type="text" inputmode="numeric" pattern="[0-9]*">
### Password inputs
Password inputs are also special cased in `Phoenix.HTML`. For security reasons,
password field values are not reused when rendering a password input tag. This
requires explicitly setting the `:value` in your markup, for example:
<%= password_input f, :password, value: input_value(f, :password) %>
<%= password_input f, :password_confirmation, value: input_value(f, :password_confirmation) %>
<%= error_tag f, :password %>
<%= error_tag f, :password_confirmation %>
### Key Events
The `onkeydown`, and `onkeyup` events are supported via the `phx-keydown`,
and `phx-keyup` bindings. When pushed, the value sent to the server will
contain all the client event object's metadata. For example, pressing the
Escape key looks like this:
%{
"altKey" => false, "code" => "Escape", "ctrlKey" => false, "key" => "Escape",
"location" => 0, "metaKey" => false, "repeat" => false, "shiftKey" => false
}
To determine which key has been pressed you should use `key` value. The
available options can be found on
[MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values)
or via the [Key Event Viewer](https://w3c.github.io/uievents/tools/key-event-viewer.html).
By default, the bound element will be the event listener, but a
window-level binding may be provided via `phx-window-keydown`,
for example:
def render(assigns) do
~L"""
<div id="thermostat" phx-window-keyup="update_temp">
Current temperature: <%= @temperature %>
</div>
"""
end
def handle_event("update_temp", %{"code" => "ArrowUp"}, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", %{"code" => "ArrowDown"}, socket) do
{:ok, new_temp} = Thermostat.dec_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", _key, socket) do
{:noreply, socket}
end
### Rate limiting events with Debounce and Throttle
All events can be rate-limited on the client by using the
`phx-debounce` and `phx-throttle` bindings, with the following behavior:
* `phx-debounce` - Accepts either a string integer timeout value, or `"blur"`.
When an int is provided, delays emitting the event by provided milliseconds.
When `"blur"` is provided, delays emitting an input's change event until the
field is blurred by the user. Debounce is typically emitted for inputs.
* `phx-throttle` - Accepts an integer timeout value to throttle the event in milliseconds.
Unlike debounce, throttle will immediately emit the event, then rate limit the
event at one event per provided timeout. Throttle is typically used to rate limit
clicks, mouse and keyboard actions.
For example, to avoid validating an email until the field is blurred, while validating
the username at most every 2 seconds after a user changes the field:
<form phx-change="validate" phx-submit="save">
<input type="text" name="user[email]" phx-debounce="blur"/>
<input type="text" name="user[username]" phx-debounce="2000"/>
</form>
And to rate limit a volume up click to once every second:
<button phx-click="volume_up" phx-throttle="1000">+</button>
Likewise, you may throttle held-down keydown:
<div phx-window-keydown="keydown" phx-throttle="500">
...
</div>
Unless held-down keys are required, a better approach is generally to use
`phx-keyup` bindings which only trigger on key up, thereby being self-limiting.
However, `phx-keydown` is useful for games and other usecases where a constant
press on a key is desired. In such cases, throttle should always be used.
#### Debounce and Throttle special behavior
The following specialized behavior is performed for forms and keydown bindings:
* When a `phx-submit`, or a `phx-change` for a different input is triggered,
any current debounce or throttle timers are reset for existing inputs.
* A `phx-keydown` binding is only throttled for key repeats. Unique keypresses
back-to-back will dispatch the pressed key events.
### LiveView Specific Events
The `lv:` event prefix supports LiveView specific features that are handled
by LiveView without calling the user's `handle_event/3` callbacks. Today,
the following events are supported:
- `lv:clear-flash` – clears the flash when sent to the server. If a
`phx-value-key` is provided, the specific key will be removed from the flash.
For example:
<p class="alert" phx-click="lv:clear-flash" phx-value-key="info">
<%= live_flash(@flash, :info) %>
</p>
## Security considerations of the LiveView model
As we have seen, LiveView begins its life-cycle as a regular HTTP request.
Then a stateful connection is established. Both the HTTP request and
the stateful connection receives the client data via parameters and session.
This means that any session validation must happen both in the HTTP request
and the stateful connection.
### Mounting considerations
For example, if your HTTP request perform user authentication and confirmation
on every request via Plugs, such as this:
plug :ensure_user_authenticated
plug :ensure_user_confirmed
Then the `c:mount/3` callback of your LiveView should execute those same
verifications:
def mount(params, %{"user_id" => user_id} = session, socket) do
socket = assign(socket, current_user: Accounts.get_user!(user_id))
socket =
if socket.assigns.current_user.confirmed_at do
socket
else
redirect(socket, to: "/login")
end
{:ok, socket}
end
Given almost all `c:mount/3` actions in your application will have to
perform these exact steps, we recommend creating a function called
`assign_defaults/2` or similar and put it in a module, such as
`MyAppWeb.LiveHelpers`, which you will use and import of every LiveView:
import MyAppWeb.LiveHelpers
def mount(params, session, socket) do
{:ok, assign_default(session, socket)}
end
where:
defmodule MyAppWeb.LiveHelpers do
import Phoenix.LiveView
def assign_defaults(session, socket) do
socket = assign(socket, current_user: Accounts.get_user!(user_id))
if socket.assigns.current_user.confirmed_at do
socket
else
redirect(socket, to: "/login")
end
end
end
One possible concern in this approach is that in regular HTTP requests the
current user will be fetched twice: one in the HTTP request and another on
`mount`. You can address this by using the `assign_new` function, that will
reuse any of the connection assigns from the HTTP request:
def assign_defaults(session, socket) do
socket = assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)
if socket.assigns.current_user.confirmed_at do
socket
else
redirect(socket, to: "/login")
end
end
### Events considerations
It is also important to keep in mind that LiveView are stateful. Therefore,
if you load any data on `c:mount/3` and the data itself changes, the data
won't be automatically propagated to the LiveView, unless you broadcast
those events with `Phoenix.PubSub`.
Generally speaking, the simplest and safest approach is to perform authorization
whenever there is an action. For example, imagine that you have a LiveView
for a "Blog", and only editors can edit posts. Therefore, it is best to validate
the user is an editor on mount and on every event:
def mount(%{"post_id" => post_id}, session, socket) do
socket = assign_defaults(session, socket)
post = Blog.get_post_for_user!(socket.assigns.current_user, post_id)
{:ok, assign(socket, post: post)}
end
def handle_event("update_post", params, socket) do
updated_post = Blog.update_post(socket.assigns.current_user, socket.assigns.post, params)
{:noreply, assign(socket, post: updated_post)}
end
In the example above, the Blog context receives the user on both `get` and
`update` operations, and always validates according that the user has access,
raising an error otherwise.
### Disconnecting all instances of a given live user
Another security consideration is how to disconnect all instances of a given
live user. For example, imagine the user logs outs, its account is terminated,
or any other reason.
Luckily, it is possible to identify all LiveView sockets by setting a "live_socket_id"
in the session. For example, when signing in a user, you could do:
conn
|> put_session(:current_user_id, user.id)
|> put_session(:live_socket_id, "users_socket:#{user.id}")
Now all LiveView sockets will be identified and listening to the given
`live_socket_id`. You can disconnect all live users identified by said
ID by broadcasting on the topic:
MyAppWeb.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
Once a LiveView is disconnected, the client will attempt to restablish
the connection, re-executing the `c:mount/3` callback. In this case,
if the user is no longer logged in or it no longer has access to its
current resource, `c:mount/3` will fail and the user will be redirected
to the proper page.
This is the same mechanism provided by `Phoenix.Channel`s. Therefore, if
your application uses both channels and LiveViews, you can use the same
technique to disconnect any stateful connection.
## Compartmentalizing markup and events with `render`, `live_render`, and `live_component`
We can render another template directly from a LiveView template by simply
calling `render`:
render SomeOtherView, "child_template", assigns
If the other template has the `.leex` extension, LiveView change tracking
will also work across templates.
When rendering a child template, any of the `phx-*` events in the child
template will be sent to the parent LiveView. In other words, similar to
regular Phoenix templates, a regular `render` call does not start another
LiveView. This means `render` is useful to sharing markup between views.
If you want to start a separate LiveView from within a LiveView, then you
can call `live_render/3` instead of `render/3`. This child LiveView runs
in a separate process than the parent, with its own `mount` and `handle_event`
callbacks. If a child LiveView crashes, it won't affect the parent. If the
parent crashes, all children are terminated.
When rendering a child LiveView, the `:id` option is required to uniquely
identify the child. A child LiveView will only ever be rendered and mounted
a single time, provided its ID remains unchanged. Updates to a child session
will be merged on the client, but not passed back up until either a crash and
re-mount or a connection drop and recovery. To force a child to re-mount with
new session data, a new ID must be provided.
Given that a LiveView runs on its own process, it is an excellent tool for creating
completely isolated UI elements, but it is a slightly expensive abstraction if
all you want is to compartmentalize markup and events. For example, if you are
showing a table with all users in the system, and you want to compartmentalize
this logic, rendering a separate `LiveView` for each user, then using a process
per user would likely be too expensive. For these cases, LiveView provides
`Phoenix.LiveComponent`, which are rendered using `live_component/3`:
<%= live_component(@socket, UserComponent, id: user.id, user: user) %>
Components have their own `mount` and `handle_event` callbacks, as well as their
own state with change tracking support. Components are also lightweight as they
"run" in the same process as the parent `LiveView`. However, this means an error
in a component would cause the whole view to fail to render. See `Phoenix.LiveComponent`
for a complete rundown on components.
To sum it up:
* `render` - compartmentalizes markup
* `live_component` - compartmentalizes state, markup, and events
* `live_render` - compartmentalizes state, markup, events, and error isolation
## DOM patching and temporary assigns
A container can be marked with `phx-update`, allowing the DOM patch
operations to avoid updating or removing portions of the LiveView, or to append
or prepend the updates rather than replacing the existing contents. This
is useful for client-side interop with existing libraries that do their
own DOM operations. The following `phx-update` values are supported:
* `replace` - the default operation. Replaces the element with the contents
* `ignore` - ignores updates to the DOM regardless of new content changes
* `append` - append the new DOM contents instead of replacing
* `prepend` - prepend the new DOM contents instead of replacing
When using `phx-update`, a unique DOM ID must always be set in the
container. If using "append" or "prepend", a DOM ID must also be set
for each child. When appending or prepending elements containing an
ID already present in the container, LiveView will replace the existing
element with the new content instead appending or prepending a new
element.
The "ignore" behaviour is frequently used when you need to integrate
with another JS library. The "append" and "prepend" feature is often
used with "Temporary assigns" to work with large amounts of data. Let's
learn more.
### Temporary assigns
By default, all LiveView assigns are stateful, which enables change
tracking and stateful interactions. In some cases, it's useful to mark
assigns as temporary, meaning they will be reset to a default value after
each update. This allows otherwise large but infrequently updated values
to be discarded after the client has been patched.
Imagine you want to implement a chat application with LiveView. You
could render each message like this:
<%= for message <- @messages do %>
<p><span><%= message.username %>:</span> <%= message.text %></p>
<% end %>
Every time there is a new message, you would append it to the `@messages`
assign and re-render all messages.
As you may suspect, keeping the whole chat conversation in memory
and resending it on every update would be too expensive, even with
LiveView smart change tracking. By using temporary assigns and phx-update,
we don't need to keep any messages in memory, and send messages to be
appended to the UI only when there are new ones.
To do so, the first step is to mark which assigns are temporary and
what values they should be reset to on mount:
def mount(_params, _session, socket) do
socket = assign(socket, :messages, load_last_20_messages())
{:ok, socket, temporary_assigns: [messages: []]}
end
On mount we also load the initial number of messages we want to
send. After the initial render, the initial batch of messages will
be reset back to an empty list.
Now, whenever there are one or more new messages, we will assign
only the new messages to `@messages`:
socket = assign(socket, :messages, new_messages)
In the template, we want to wrap all of the messages in a container
and tag this content with phx-update. Remember, we must add an ID
to the container as well as to each child:
<div id="chat-messages" phx-update="append">
<%= for message <- @messages do %>
<p id="<%= message.id %>">
<span><%= message.username %>:</span> <%= message.text %>
</p>
<% end %>
</div>
When the client receives new messages, it now knows to append to the
old content rather than replace it.
## Live navigation
LiveView provides functionality to allow page navigation using the
[browser's pushState API](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
With live navigation, the page is updated without a full page reload.
You can trigger live navigation in two ways:
* From the client - this is done by replacing `Phoenix.HTML.Link.link/2`
by `Phoenix.LiveView.Helpers.live_patch/2` or
`Phoenix.LiveView.Helpers.live_redirect/2`
* From the server - this is done by replacing `Phoenix.Controller.redirect/2` calls
by `Phoenix.LiveView.push_patch/2` or `Phoenix.LiveView.push_redirect/2`.
For example, in a template you may write:
<%= live_patch "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
or in a LiveView:
{:noreply, push_patch(socket, to: Routes.live_path(socket, MyLive, page + 1))}
The "patch" operations must be used when you want to navigate to the
current LiveView, simply updating the URL and the current parameters,
without mounting a new LiveView. When patch is used, the `c:handle_params/3`
callback is invoked. See the next section for more information.
The "redirect" operations must be used when you want to dismount the
current LiveView and mount a new one. In those cases, the existing root
LiveView is shutdown, and an Ajax request is made to request the necessary
information about the new LiveView without performing a full static render
(which reduces latency and improves performance). Once information is
retrieved, the new LiveView is mounted. While redirecting, a `phx-disconnected`
class is added to the root LiveView, which can be used to indicate to the
user a new page is being loaded.
`live_patch/2`, `live_redirect/2`, `push_redirect/2`, and `push_patch/2`
only work for LiveViews defined at the router with the `live/3` macro.
Once live navigation is triggered, the flash is automatically cleared.
### `handle_params/3`
The `c:handle_params/3` callback is invoked after `c:mount/3`. It receives the
request parameters as first argument, the url as second, and the socket as third.
For example, imagine you have a `UserTable` LiveView to show all users in
the system and you define it in the router as:
live "/users", UserTable
Now to add live sorting, you could do:
<%= live_patch "Sort by name", to: Routes.live_path(@socket, UserTable, %{sort_by: "name"}) %>
When clicked, since we are navigating to the current LiveView, `c:handle_params/3`
will be invoked. Remember you should never trust the received params, so you must
use the callback to validate the user input and change the state accordingly:
def handle_params(params, _uri, socket) do
socket =
case params["sort_by"] do
sort_by when sort_by in ~w(name company) -> assign(socket, sort_by: sort)
_ -> socket
end
{:noreply, load_users(socket)}
end
As with other `handle_*` callback, changes to the state inside `c:handle_params/3`
will trigger a server render.
Note the parameters given to `c:handle_params/3` are the same as the ones given
to `c:mount/3`. So how do you decide which callback to use to load data?
Generally speaking, data should always be loaded on `c:mount/3`, since `c:mount/3`
is invoked once per LiveView life-cycle. Only the params you expect to be changed
via `live_patch/2` or `push_patch/2` must be loaded on `c:handle_params/3`.
Furthermore, it is very important to not access the same parameters on both
`c:mount/3` and `c:handle_params/3`. For example, do NOT do this:
def mount(%{"organization_id" => org_id}, session, socket) do
# do something with org_id
end
def handle_params(%{"organization_id" => org_id, "sort_by" => sort_by}, url, socket) do
# do something with org_id and sort_by
end
If you do that, because `c:mount/3` is called once and `c:handle_params/3` multiple
times, your state can get out of sync. So once a parameter is read on mount, it
should not be read elsewhere. Instead, do this:
def mount(%{"organization_id" => org_id}, session, socket) do
# do something with org_id
end
def handle_params(%{"sort_by" => sort_by}, url, socket) do
# do something with sort_by
end
### Replace page address
LiveView also allows the current browser URL to be replaced. This is useful when you
want certain events to change the URL but without polluting the browser's history.
This can be done by passing the `replace: true` option to any of the navigation helpers.
### Multiple LiveViews in the same page
LiveView allows you to have multiple LiveViews in the same page by calling
`Phoenix.LiveView.Helpers.live_render/3` in your templates. However, only
the LiveViews defined directly in your router and use the "Live Navigation"
functionality described here. This is important because LiveViews work
closely with your router, guaranteeing you can only navigate to known
routes.
## Live Layouts
When working with LiveViews, there are usually three layouts to be
considered:
* the root layout - this is a layout used by both LiveView and
regular views. This layout typically contains the <html>
definition alongside the head and body tags. Any content define
in the root layout will remain the same, even as you live navigate
across LiveViews
* the app layout - this is the default application layout which
is not included or used by LiveViews;
* the live layout - this is the layout which wraps a LiveView and
is rendered as part of the LiveView life-cycle
Overall, those layouts are found in `templates/layout` with the
following names:
* root.html.eex
* app.html.eex
* live.html.leex
The "root" layout is shared by both "app" and "live" layout. It
is rendered only on the initial request and therefore it has
access to the `@conn` assign. The root layout must be defined
in your router:
plug :put_root_layout, {MyAppWeb.LayoutView, :root}
Alternatively, the root layout can be passed to the `live`
macro to your **live routes**:
live "/dashboard", MyApp.Dashboard, layout: {MyAppWeb.LayoutView, :root}
The "app" and "live" layouts are often small and similar to each
other, but the "app" layout uses the `@conn` and is used as part
of the regular request life-cycle, and the "live" layout is part
of the LiveView and therefore has direct access to the `@socket`.
For example, you can define a new `live.html.leex` layout with
dynamic content. You must use `@inner_content` where the output
of the actual template will be placed at:
<p><%= live_flash(@flash, :notice) %></p>
<p><%= live_flash(@flash, :error) %></p>
<%= @inner_content %>
To use the live layout, update your LiveView to pass the `:layout`
option to `use Phoenix.LiveView`:
use Phoenix.LiveView, layout: {MyAppWeb.LayoutView, "live.html"}
If you are using Phoenix v1.5, the layout is automatically set
when generating apps with the `mix phx.new --live` flag.
The `:layout` option does not apply for LiveViews rendered within
other LiveViews. If you are rendering child live views or if you
want to opt-in to a layout only in certain occasions, use the
`:layout` as an option in mount:
def mount(_params, _session, socket) do
socket = assign(socket, new_message_count: 0)
{:ok, socket, layout: {MyAppWeb.LayoutView, "live.html"}}
end
*Note*: The layout will be wrapped by the LiveView's `:container` tag.
### Updating the HTML document title
Because the root layout from the Plug pipeline is rendered outside of
LiveView, the contents cannot be dynamically changed. The one exception
is the `<title>` of the HTML document. Phoenix LiveView special cases
the `@page_title` assign to allow dynamically updating the title of the
page, which is useful when using live navigation, or annotating the browser
tab with a notification. For example, to update the user's notification
count in the browser's title bar, first set the `page_title` assign on
mount:
def mount(_params, _session, socket) do
socket = assign(socket, page_title: "Latest Posts")
{:ok, socket}
end
Then access `@page_title` in the root layout:
<title><%= @page_title %></title>
You can also use `Phoenix.LiveView.Helpers.live_title_tag/2` to support
adding automatic prefix and suffix to the page title when rendered and
on subsequent updates:
<%= live_title_tag @page_title, prefix: "MyApp – " %>
Although the root layout is not updated by LiveView, by simply assigning
to `page_title`, LiveView knows you want the title to be updated:
def handle_info({:new_messages, count}, socket) do
{:noreply, assign(socket, page_title: "Latest Posts (#{count} new)")}
end
*Note*: If you find yourself needing to dynamically patch other parts of the
base layout, such as injecting new scripts or styles into the `<head>` during
live navigation, *then a regular, non-live, page navigation should be used
instead*. Assigning the `@page_title` updates the `document.title` directly,
and therefore cannot be used to update any other part of the base layout.
## Using Gettext for internationalization
For interationalization with [gettext](https://hexdocs.pm/gettext/Gettext.html),
the locale used within your Plug pipeline can be stored in the Plug session and
restored within your LiveView mount. For example, after user signin or preference
changes, you can write the locale to the session:
def put_user_session(conn, current_user) do
locale = get_locale_for_user(current_user)
Gettext.put_locale(MyApp.Gettext, locale)
conn
|> put_session(:user_id, current_user.id)
|> put_session(:locale, locale)
end
Then in your LiveView `mount/3`, you can restore the locale:
def mount(_params, %{"locale" => locale}, socket) do
Gettext.put_locale(MyApp.Gettext, locale)
{:ok socket}
end
## JavaScript Client Specific
As seen earlier, you start by instantiating a single LiveSocket instance to
enable LiveView client/server interaction, for example:
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
liveSocket.connect()
All options are passed directly to the `Phoenix.Socket` constructor,
except for the following LiveView specific options:
* `bindingPrefix` - the prefix to use for phoenix bindings. Defaults `"phx-"`
* `params` - the `connect_params` to pass to the view's mount callback. May be
a literal object or closure returning an object. When a closure is provided,
the function receives the view's phx-view name.
* `hooks` – a reference to a user-defined hooks namespace, containing client
callbacks for server/client interop. See the interop section below for details.
### Debugging Client Events
To aid debugging on the client when troubleshooting issues, the `enableDebug()`
and `disableDebug()` functions are exposed on the `LiveSocket` JavaScript instance.
Calling `enableDebug()` turns on debug logging which includes LiveView life-cycle and
payload events as they come and go from client to server. In practice, you can expose
your instance on `window` for quick access in the browser's web console, for example:
// app.js
let liveSocket = new LiveSocket(...)
liveSocket.connect()
window.liveSocket = liveSocket
// in the browser's web console
>> liveSocket.enableDebug()
The debug state uses the browser's built-in `sessionStorage`, so it will remain in effect
for as long as your browser session lasts.
### Simulating Latency
Proper handling of latency is critical for good UX. LiveView's CSS loading states allow
the client to provide user feedback while awaiting a server response. In development,
near zero latency on localhost does not allow latency to be easily represented or tested,
so LiveView includes a latency simulator with the JavaScript client to ensure your
application provides a pleasant experience. Like the `enableDebug()` function above,
the `LiveSocket` instance includes `enableLatencySim(milliseconds)` and `disableLatencySim()`
functions which apply throughout the current browser session. The `enableLatencySim` function
accepts an integer in milliseconds for the round-trip-time to the server. For example:
// app.js
let liveSocket = new LiveSocket(...)
liveSocket.connect()
window.liveSocket = liveSocket
// in the browser's web console
>> liveSocket.enableLatencySim(1000)
[Log] latency simulator enabled for the duration of this browser session.
Call disableLatencySim() to disable
### Forms and input handling
The JavaScript client is always the source of truth for current input values.
For any given input with focus, LiveView will never overwrite the input's current
value, even if it deviates from the server's rendered updates. This works well
for updates where major side effects are not expected, such as form validation
errors, or additive UX around the user's input values as they fill out a form.
For these use cases, the `phx-change` input does not concern itself with disabling
input editing while an event to the server is in flight. When a `phx-change` event
is sent to the server the input tag and parent form tag receive the `phx-change-loading`
css class, then the payload is pushed to the server with a `"_target"` param in the
root payload containing the keyspace of the input name which triggered the change
event.
For example, if the following input triggered a change event:
<input name="user[username]"/>
The server's `handle_event/3` would receive a payload:
%{"_target" => ["user", "username"], "user" => %{"username" => "Name"}}
The `phx-submit` event is used for form submissions where major side effects
typically happen, such as rendering new containers, calling an external
service, or redirecting to a new page.
On submission of a form bound with a `phx-submit` event:
1. The form's inputs are set to `readonly`
2. Any submit button on the form is disabled
3. The form receives the `"phx-submit-loading"` class
On completion of server processing of the `phx-submit` event:
1. The submitted form is reactivated and loses the `"phx-submit-loading"` class
2. The last input with focus is restored (unless another input has received focus)
3. Updates are patched to the DOM as usual
To handle latent events, any HTML tag can be annotated with
`phx-disable-with`, which swaps the element's `innerText` with the provided
value during event submission. For example, the following code would change
the "Save" button to "Saving...", and restore it to "Save" on acknowledgment:
<button type="submit" phx-disable-with="Saving...">Save</button>
You may also take advantage of LiveView's CSS loading state classes to
swap out your form content while the form is submitting. For example,
with the following rules in your `app.css`:
.while-submitting { display: none; }
.inputs { display: block; }
.phx-submit-loading {
.while-submitting { display: block; }
.inputs { display: none; }
}
You can show and hide content with the following markup:
<form phx-change="update">
<div class="while-submitting">Please wait while we save our content...</div>
<div class="inputs">
<input type="text" name="text" value="<%= @text %>">
</div>
</form>
### Form Recovery following crashes or disconnects
By default, all forms marked with `phx-change` will recover input values
automatically after the user has reconnected or the LiveView has remounted
after a crash. This is achieved by the client triggering the same `phx-change`
to the server as soon as the mount has been completed.
**Note:** if you want to see form recovery working in development, please
make sure to disable live reloading in development by commenting out the
LiveReload plug in your `endpoint.ex` file or by setting `code_reloader: false`
in your `config/dev.exs`. Otherwise live reloading may cause the current page
to be reloaded whenever you restart the server, which will discard all form
state.
For most use cases, this is all you need and form recovery will happen
without consideration. In some cases, where forms are built step-by-step in a
stateful fashion, it may require extra recovery handling on the server outside
of your existing `phx-change` callback code. To enable specialized recovery,
provide a `phx-auto-recover` binding on the form to specify a different event
to trigger for recovery, which will receive the form params as usual. For example,
imagine a LiveView wizard form where the form is stateful and built based on what
step the user is on and by prior selections:
<form phx-change="validate_wizard_step" phx-auto-recover="recover_wizard">
On the server, the `"validate_wizard_step"` event is only concerned with the
current client form data, but the server maintains the entire state of the wizard.
To recover in this scenario, you can specify a recovery event, such as `"recover_wizard"`
above, which would wire up to the following server callbacks in your LiveView:
def handle_event("validate_wizard_step", params, socket) do
# regular validations for current step
{:noreply, socket}
end
def handle_event("recover_wizard", params, socket) do
# rebuild state based on client input data up to the current step
{:noreply, socket}
end
To forgo automatic form recovery, set `phx-auto-recover="ignore"`.
### Loading state and errors
By default, the following classes are applied to the LiveView's parent
container:
- `"phx-connected"` - applied when the view has connected to the server
- `"phx-disconnected"` - applied when the view is not connected to the server
- `"phx-error"` - applied when an error occurs on the server. Note, this
class will be applied in conjunction with `"phx-disconnected"` if connection
to the server is lost.
All `phx-` event bindings apply their own css classes when pushed. For example
the following markup:
<button phx-click="clicked" phx-window-keydown="key">...</button>
On click, would receive the `phx-click-loading` class, and on keydown would receive
the `phx-keydown-loading` class. The css loading classes are maintained until an
acknowledgement is received on the client for the pushed event.
In the case of forms, when a `phx-change` is sent to the server, the input element
which emitted the change receives the `phx-change-loading` class, along with the
parent form tag. The following events receive css loading classes:
- `phx-click` - `phx-click-loading`
- `phx-change` - `phx-change-loading`
- `phx-submit` - `phx-submit-loading`
- `phx-focus` - `phx-focus-loading`
- `phx-blur` - `phx-blur-loading`
- `phx-window-keydown` - `phx-keydown-loading`
- `phx-window-keyup` - `phx-keyup-loading`
For live page navigation via `live_redirect` and `live_patch`, as well as form
submits via `phx-submit`, the JavaScript events `"phx:page-loading-start"` and
`"phx:page-loading-stop"` are dispatched on window. Additionally, any `phx-`
event may dispatch page loading events by annotating the DOM element with
`phx-page-loading`. This is useful for showing main page loading status, for example:
// app.js
import NProgress from "nprogress"
window.addEventListener("phx:page-loading-start", info => NProgress.start())
window.addEventListener("phx:page-loading-stop", info => NProgress.done())
The `info` object will contain a `kind` key, with values one of:
- `"redirect"` - the event was triggered by a redirect
- `"patch"` - the event was triggered by a patch
- `"initial"` - the event was triggered by initial page load
- `"element"` - the event was triggered by a `phx-` bound element, such as `phx-click`
For all kinds of page loading events, all but `"element"` will receive an additional `to`
key in the info metadata pointing to the href associated with the page load.
In the case of an `"element"` page loading, the info will contain a `"target"` key containing
the DOM element which triggered the page loading state.
### JS Interop and client-controlled DOM
To handle custom client-side JavaScript when an element is added, updated,
or removed by the server, a hook object may be provided with the following
life-cycle callbacks:
* `mounted` - the element has been added to the DOM and its server
LiveView has finished mounting
* `beforeUpdate` - the element is about to be updated in the DOM.
*Note*: any call here must be synchronous as the operation cannot
be deferred or cancelled.
* `updated` - the element has been updated in the DOM by the server
* `beforeDestroy` - the element is about to be removed from the DOM.
*Note*: any call here must be synchronous as the operation cannot
be deferred or cancelled.
* `destroyed` - the element has been removed from the page, either
by a parent update, or by the parent being removed entirely
* `disconnected` - the element's parent LiveView has disconnected from the server
* `reconnected` - the element's parent LiveView has reconnected to the server
The above life-cycle callbacks have in-scope access to the following attributes:
* `el` - attribute referencing the bound DOM node,
* `viewName` - attribute matching the dom node's phx-view value
* `pushEvent(event, payload)` - method to push an event from the client to the LiveView server
* `pushEventTo(selector, event, payload)` - method to push targeted events from the client
to LiveViews and LiveComponents.
For example, the markup for a controlled input for phone-number formatting could be written
like this:
<input type="text" name="user[phone_number]" id="user-phone-number" phx-hook="PhoneNumber" />
Then a hook callback object could be defined and passed to the socket:
let Hooks = {}
Hooks.PhoneNumber = {
mounted() {
this.el.addEventListener("input", e => {
let match = this.el.value.replace(/\D/g, "").match(/^(\d{3})(\d{3})(\d{4})$/)
if(match) {
this.el.value = `${match[1]}-${match[2]}-${match[3]}`
}
})
}
}
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, ...})
...
The hook can push events to the LiveView by using the `pushEvent` function.
Communication with hook can be done by using data attributes on the container.
For example, to implement infinite scrolling, one might do:
<div id="infinite-scroll" phx-hook="InfiniteScroll" data-page="<%= @page %>" />
And then in the client:
Hooks.InfiniteScroll = {
page() { return this.el.dataset.page },
mounted(){
this.pending = this.page()
window.addEventListener("scroll", e => {
if(this.pending == this.page() && scrollAt() > 90){
this.pending = this.page() + 1
this.pushEvent("load-more", {})
}
})
},
updated(){ this.pending = this.page() }
}
*Note*: when using `phx-hook`, a unique DOM ID must always be set.
## Endpoint configuration
LiveView accepts the following configuration in your endpoint under
the `:live_view` key:
* `:signing_salt` (required) - the salt used to sign data sent
to the client
* `:hibernate_after` (optional) - the idle time in milliseconds allowed in
the LiveView before compressing its own memory and state.
Defaults to 15000ms (15 seconds)
'''
alias Phoenix.LiveView.Socket
@doc """
The LiveView entry-point.
For each LiveView in the root of a template, `c:mount/3` is invoked twice:
once to do the initial page load and again to establish the live socket.
It expects three parameters:
* `params` - a map of string keys which contain public information that
can be set by the user. The map contains the query params as well as any
router path parameter. If the LiveView was not mounted at the router,
this argument is the atom `:not_mounted_at_router`
* `session` - the connection session
* `socket` - the LiveView socket
It must return either `{:ok, socket}` or `{:ok, socket, options}`, where
`options` is one of:
* `:temporary_assigns` - a keyword list of assigns that are temporary
and must be reset to their value after every render
* `:layout` - the optional layout to be used by the LiveView
"""
@callback mount(
Socket.unsigned_params() | :not_mounted_at_router,
session :: map,
socket :: Socket.t()
) ::
{:ok, Socket.t()} | {:ok, Socket.t(), keyword()}
@callback render(assigns :: Socket.assigns()) :: Phoenix.LiveView.Rendered.t()
@callback terminate(reason, socket :: Socket.t()) :: term
when reason: :normal | :shutdown | {:shutdown, :left | :closed | term}
@callback handle_params(Socket.unsigned_params(), uri :: String.t(), socket :: Socket.t()) ::
{:noreply, Socket.t()}
@callback handle_event(event :: binary, Socket.unsigned_params(), socket :: Socket.t()) ::
{:noreply, Socket.t()}
@callback handle_call(msg :: term, {pid, reference}, socket :: Socket.t()) ::
{:noreply, Socket.t()} | {:reply, term, Socket.t()}
@callback handle_info(msg :: term, socket :: Socket.t()) ::
{:noreply, Socket.t()}
@optional_callbacks mount: 3,
terminate: 2,
handle_params: 3,
handle_event: 3,
handle_call: 3,
handle_info: 2
@doc """
Uses LiveView in the current module to mark it a LiveView.
use Phoenix.LiveView,
namespace: MyAppWeb,
container: {:tr, class: "colorized"},
layout: {MyAppWeb.LayoutView, "live.html"}
## Options
* `:namespace` - configures the namespace the `LiveView` is in
* `:container` - configures the container the `LiveView` will be wrapped in
* `:layout` - configures the layout the `LiveView` will be rendered in
"""
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
import Phoenix.LiveView
import Phoenix.LiveView.Helpers
@behaviour Phoenix.LiveView
@before_compile Phoenix.LiveView.Renderer
@doc false
def __live__, do: unquote(Macro.escape(Phoenix.LiveView.__live__(__MODULE__, opts)))
end
end
@doc false
def __live__(module, opts) do
container = opts[:container] || {:div, []}
namespace = opts[:namespace] || module |> Module.split() |> Enum.take(1) |> Module.concat()
name = module |> Atom.to_string() |> String.replace_prefix("#{namespace}.", "")
layout =
case opts[:layout] do
{mod, template} when is_atom(mod) and is_binary(template) ->
{mod, template}
nil ->
nil
other ->
raise ArgumentError,
":layout expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <>
"got: #{inspect(other)}"
end
%{container: container, name: name, kind: :view, module: module, layout: layout}
end
@doc """
Returns true if the socket is connected.
Useful for checking the connectivity status when mounting the view.
For example, on initial page render, the view is mounted statically,
rendered, and the HTML is sent to the client. Once the client
connects to the server, a LiveView is then spawned and mounted
statefully within a process. Use `connected?/1` to conditionally
perform stateful work, such as subscribing to pubsub topics,
sending messages, etc.
## Examples
defmodule DemoWeb.ClockLive do
use Phoenix.LiveView
...
def mount(_params, _session, socket) do
if connected?(socket), do: :timer.send_interval(1000, self(), :tick)
{:ok, assign(socket, date: :calendar.local_time())}
end
def handle_info(:tick, socket) do
{:noreply, assign(socket, date: :calendar.local_time())}
end
end
"""
def connected?(%Socket{connected?: connected?}), do: connected?
@doc """
Assigns a value into the socket only if it does not exist.
Useful for lazily assigning values and referencing parent assigns.
## Referencing parent assigns
When a LiveView is mounted in a disconnected state, the Plug.Conn assigns
will be available for reference via `assign_new/3`, allowing assigns to
be shared for the initial HTTP request. On connected mount, `assign_new/3`
will be invoked, and the LiveView will use its session to rebuild the
originally shared assign. Likewise, nested LiveView children have access
to their parent's assigns on mount using `assign_new`, which allows
assigns to be shared down the nested LiveView tree.
## Examples
# controller
conn
|> assign(:current_user, user)
|> LiveView.Controller.live_render(MyLive, session: %{"user_id" => user.id})
# LiveView mount
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)}
end
"""
def assign_new(%Socket{} = socket, key, func) when is_function(func, 0) do
validate_assign_key!(key)
case socket do
%{assigns: %{^key => _}} ->
socket
%{private: %{assign_new: {assigns, keys}}} ->
# It is important to store the keys even if they are not in assigns
# because maybe the controller doesn't have it but the view does.
socket = put_in(socket.private.assign_new, {assigns, [key | keys]})
Phoenix.LiveView.Utils.force_assign(socket, key, Map.get_lazy(assigns, key, func))
%{} ->
Phoenix.LiveView.Utils.force_assign(socket, key, func.())
end
end
@doc """
Adds key value pairs to socket assigns.
A single key value pair may be passed, or a keyword list
of assigns may be provided to be merged into existing
socket assigns.
## Examples
iex> assign(socket, :name, "Elixir")
iex> assign(socket, name: "Elixir", logo: "💧")
"""
def assign(%Socket{} = socket, key, value) do
validate_assign_key!(key)
Phoenix.LiveView.Utils.assign(socket, key, value)
end
@doc """
See `assign/3`.
"""
def assign(%Socket{} = socket, attrs) when is_map(attrs) or is_list(attrs) do
Enum.reduce(attrs, socket, fn {key, value}, acc ->
validate_assign_key!(key)
Phoenix.LiveView.Utils.assign(acc, key, value)
end)
end
defp validate_assign_key!(:flash) do
raise ArgumentError,
":flash is a reserved assign by LiveView and it cannot be set directly. " <>
"Use the appropriate flash functions instead."
end
defp validate_assign_key!(_key), do: :ok
@doc """
Updates an existing key in the socket assigns.
The update function receives the current key's value and
returns the updated value. Raises if the key does not exist.
## Examples
iex> update(socket, :count, fn count -> count + 1 end)
iex> update(socket, :count, &(&1 + 1))
"""
def update(%Socket{assigns: assigns} = socket, key, func) do
case Map.fetch(assigns, key) do
{:ok, val} -> assign(socket, [{key, func.(val)}])
:error -> raise KeyError, key: key, term: assigns
end
end
@doc """
Adds a flash message to the socket to be displayed on redirect.
*Note*: While you can use `put_flash/3` inside a `Phoenix.LiveComponent`,
components have their own `@flash` assigns. The `@flash` assign
in a component is only copied to its parent LiveView if the component
calls `push_redirect/2` or `push_patch/2`.
*Note*: You must also place the `Phoenix.LiveView.Router.fetch_live_flash/2`
plug in your browser's pipeline in place of `fetch_flash` to be supported,
for example:
import Phoenix.LiveView.Router
pipeline :browser do
...
plug :fetch_live_flash
end
## Examples
iex> put_flash(socket, :info, "It worked!")
iex> put_flash(socket, :error, "You can't access that page")
"""
defdelegate put_flash(socket, kind, msg), to: Phoenix.LiveView.Utils
@doc """
Clears the flash.
## Examples
iex> clear_flash(socket)
"""
defdelegate clear_flash(socket), to: Phoenix.LiveView.Utils
@doc """
Clears a key from the flash.
## Examples
iex> clear_flash(socket, :info)
"""
defdelegate clear_flash(socket, key), to: Phoenix.LiveView.Utils
@doc """
Annotates the socket for redirect to a destination path.
*Note*: LiveView redirects rely on instructing client
to perform a `window.location` update on the provided
redirect location. The whole page will be reloaded and
all state will be discarded.
## Options
* `:to` - the path to redirect to. It must always be a local path
* `:external` - an external path to redirect to
"""
def redirect(%Socket{} = socket, opts) do
url =
cond do
to = opts[:to] -> validate_local_url!(to, "redirect/2")
external = opts[:external] -> external
true -> raise ArgumentError, "expected :to or :external option in redirect/2"
end
put_redirect(socket, {:redirect, %{to: url}})
end
@doc """
Annotates the socket for navigation within the current LiveView.
When navigating to the current LiveView, `c:handle_params/3` is
immediately invoked to handle the change of params and URL state.
Then the new state is pushed to the client, without reloading the
whole page. For live redirects to another LiveView, use
`push_redirect/2`.
## Options
* `:to` - the required path to link to. It must always be a local path
* `:replace` - the flag to replace the current history or push a new state.
Defaults `false`.
## Examples
{:noreply, push_patch(socket, to: "/")}
{:noreply, push_patch(socket, to: "/", replace: true)}
"""
def push_patch(%Socket{} = socket, opts) do
%{to: to} = opts = push_opts!(opts, "push_patch/2")
case Phoenix.LiveView.Utils.live_link_info!(socket, socket.root_view, to) do
{:internal, params, action, _parsed_uri} ->
put_redirect(socket, {:live, {params, action}, opts})
:external ->
raise ArgumentError,
"cannot push_patch/2 to #{inspect(to)} because the given path " <>
"does not point to the current root view #{inspect(socket.root_view)}"
end
end
@doc """
Annotates the socket for navigation to another LiveView.
The current LiveView will be shutdown and a new one will be mounted
in its place LiveView, without reloading the whole page. This can
also be use to remount the same LiveView, in case you want to start
fresh. If you want to navigate to the same LiveView without remounting
it, use `push_patch/2` instead.
## Options
* `:to` - the required path to link to. It must always be a local path
* `:replace` - the flag to replace the current history or push a new state.
Defaults `false`.
## Examples
{:noreply, push_redirect(socket, to: "/")}
{:noreply, push_redirect(socket, to: "/", replace: true)}
"""
def push_redirect(%Socket{} = socket, opts) do
opts = push_opts!(opts, "push_redirect/2")
put_redirect(socket, {:live, :redirect, opts})
end
defp push_opts!(opts, context) do
to = Keyword.fetch!(opts, :to)
validate_local_url!(to, context)
kind = if opts[:replace], do: :replace, else: :push
%{to: to, kind: kind}
end
defp put_redirect(%Socket{redirected: nil} = socket, command) do
%Socket{socket | redirected: command}
end
defp put_redirect(%Socket{redirected: to} = _socket, _command) do
raise ArgumentError, "socket already prepared to redirect with #{inspect(to)}"
end
@invalid_local_url_chars ["\\"]
defp validate_local_url!("//" <> _ = to, where) do
raise_invalid_local_url!(to, where)
end
defp validate_local_url!("/" <> _ = to, where) do
if String.contains?(to, @invalid_local_url_chars) do
raise ArgumentError, "unsafe characters detected for #{where} in URL #{inspect(to)}"
else
to
end
end
defp validate_local_url!(to, where) do
raise_invalid_local_url!(to, where)
end
defp raise_invalid_local_url!(to, where) do
raise ArgumentError, "the :to option in #{where} expects a path but was #{inspect(to)}"
end
@doc """
Accesses the connect params sent by the client for use on connected mount.
Connect params are only sent when the client connects to the server and
only remain available during mount. `nil` is returned when called in a
disconnected state and a `RuntimeError` is raised if called after mount.
## Examples
def mount(_params, _session, socket) do
{:ok, assign(socket, width: get_connect_params(socket)["width"] || @width)}
end
"""
def get_connect_params(%Socket{private: private} = socket) do
if connect_params = private[:connect_params] do
if connected?(socket), do: connect_params, else: nil
else
raise_connect_only!(socket, "connect_params")
end
end
@doc """
Accesses the connect info from the socket to use on connected mount.
Connect info are only sent when the client connects to the server and
only remain available during mount. `nil` is returned when called in a
disconnected state and a `RuntimeError` is raised if called after mount.
## Examples
First, when invoking the LiveView socket, you need to declare the
`connect_info` you want to receive. Typically, it includes at least
the session but it may include other keys, such as `:peer_data`.
See `Phoenix.Endpoint.socket/3`:
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [:peer_data, session: @session_options]]
Those values can now be accessed on the connected mount as
`get_connect_info/1`:
def mount(_params, _session, socket) do
if info = get_connect_info(socket) do
{:ok, assign(socket, ip: info.peer_data.address)}
else
{:ok, assign(socket, ip: nil)}
end
end
"""
def get_connect_info(%Socket{private: private} = socket) do
if connect_info = private[:connect_info] do
if connected?(socket), do: connect_info, else: nil
else
raise_connect_only!(socket, "connect_info")
end
end
@doc """
Returns true if the socket is connected and the static manifest has changed.
This function is useful to detect if the client is running on an outdated
version of the static files. It works by comparing the static hash parameter
sent by the client with the one on the server.
**Important:** this functionality requires Phoenix v1.5.2 or later.
To use this functionality, the first step is to configure the client to
submit the client cache static manifest hash as a connect parameter. This
is typically done by setting the "_cache_static_manifest_hash" key to the
value of "PHOENIX_CACHE_STATIC_MANIFEST_HASH":
```js
let params = {
_csrf_token: document.querySelector("meta[name='csrf-token']").getAttribute("content"),
_cache_static_manifest_hash: "PHOENIX_CACHE_STATIC_MANIFEST_HASH"
}
let liveSocket = new LiveSocket("/live", Socket, {params: params});
```
Now, whenever you run `mix phx.digest`, Phoenix will automatically replace
"PHOENIX_CACHE_STATIC_MANIFEST_HASH" by the actual hash. At the same time,
the server will automatically load the manifest hash from the
`:cache_static_manifest` file, typically configured in `config/prod.exs`
to point to "priv/static/cache_static_manifest.json".
The value of the hash on the server and on the client are the same in the
huge majority of times. However, if there is a new deployment, those values
may different. You can use this function to detect those cases and show a
banner to the user, asking them to reload the page. To do so, first set the
assign on mount:
def mount(params, session, socket) do
{:ok, assign(socket, static_changed?: static_changed?(socket))}
end
And then in your views:
<%= if @static_change do %>
<div id="reload-static">
The app has been updated. Click here to <a href="#" onclick="window.location.reload()">reload</a>.
</div>
<% end %>
If you prefer, you can also send a JavaScript that directly reloads the
page.
## Testing
In order to force this behaviour in development, you can explicitly set the
values of the hashes on the client and the server.
On the client, open up your `app.js` and replace the LiveSocket connect params
by this:
```js
let params = {
_csrf_token: document.querySelector("meta[name='csrf-token']").getAttribute("content"),
_cache_static_manifest_hash: "0"
}
```
Then on the server, open up `config/dev.exs` and set this under the endpoint
config:
config :app, MyAppWeb.Endpoint,
cache_static_manifest_hash: "1"
Now, as the values differ, `static_changed?/1` should return true.
"""
def static_changed?(%Socket{private: private, endpoint: endpoint} = socket) do
if connect_params = private[:connect_params] do
connected?(socket) and
static_changed?(
connect_params["_cache_static_manifest_hash"],
endpoint.config(:cache_static_manifest_hash)
)
else
raise_connect_only!(socket, "static_changed?")
end
end
defp static_changed?("PHOENIX_CACHE_STATIC_MANIFEST_HASH", _), do: false
defp static_changed?(nil, _), do: false
defp static_changed?(_, nil), do: false
defp static_changed?(params, config), do: params != config
defp raise_connect_only!(socket, fun) do
if child?(socket) do
raise RuntimeError, """
attempted to read #{fun} from a nested child LiveView #{inspect(socket.view)}.
Only the root LiveView has access to #{fun}.
"""
else
raise RuntimeError, """
attempted to read #{fun} outside of #{inspect(socket.view)}.mount/3.
#{fun} only exists while mounting. If you require access to this information
after mount, store the state in socket assigns.
"""
end
end
@doc """
Asynchronously updates a component with new assigns.
Requires a stateful component with a matching `:id` to send
the update to. Following the optional `preload/1` callback being invoked,
the updated values are merged with the component's assigns and `update/2`
is called for the updated component(s).
While a component may always be updated from the parent by updating some
parent assigns which will re-render the child, thus invoking `update/2` on
the child component, `send_update/2` is useful for updating a component
that entirely manages its own state, as well as messaging between components.
## Examples
def handle_event("cancel-order", _, socket) do
...
send_update(Cart, id: "cart", status: "cancelled")
{:noreply, socket}
end
"""
def send_update(module, assigns) do
assigns = Enum.into(assigns, %{})
id =
assigns[:id] ||
raise ArgumentError, "missing required :id in send_update. Got: #{inspect(assigns)}"
Phoenix.LiveView.Channel.send_update(module, id, assigns)
end
@doc """
Returns the transport pid of the socket.
Raises `ArgumentError` if the socket is not connected.
## Examples
iex> transport_pid(socket)
#PID<0.107.0>
"""
def transport_pid(%Socket{}) do
case Process.get(:"$callers") do
[transport_pid | _] -> transport_pid
_ -> raise ArgumentError, "transport_pid/1 may only be called when the socket is connected."
end
end
defp child?(%Socket{parent_pid: pid}), do: is_pid(pid)
end
| 39.153598 | 111 | 0.696436 |
1cebda6296e6b9a9afb92ebb566b6829eb0f0921 | 4,501 | ex | Elixir | clients/fitness/lib/google_api/fitness/v1/model/aggregate_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/fitness/lib/google_api/fitness/v1/model/aggregate_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/fitness/lib/google_api/fitness/v1/model/aggregate_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Fitness.V1.Model.AggregateRequest do
@moduledoc """
Next id: 10
## Attributes
* `aggregateBy` (*type:* `list(GoogleApi.Fitness.V1.Model.AggregateBy.t)`, *default:* `nil`) - The specification of data to be aggregated. At least one aggregateBy spec must be provided. All data that is specified will be aggregated using the same bucketing criteria. There will be one dataset in the response for every aggregateBy spec.
* `bucketByActivitySegment` (*type:* `GoogleApi.Fitness.V1.Model.BucketByActivity.t`, *default:* `nil`) - Specifies that data be aggregated each activity segment recorded for a user. Similar to bucketByActivitySegment, but bucketing is done for each activity segment rather than all segments of the same type. Mutually exclusive of other bucketing specifications.
* `bucketByActivityType` (*type:* `GoogleApi.Fitness.V1.Model.BucketByActivity.t`, *default:* `nil`) - Specifies that data be aggregated by the type of activity being performed when the data was recorded. All data that was recorded during a certain activity type (.for the given time range) will be aggregated into the same bucket. Data that was recorded while the user was not active will not be included in the response. Mutually exclusive of other bucketing specifications.
* `bucketBySession` (*type:* `GoogleApi.Fitness.V1.Model.BucketBySession.t`, *default:* `nil`) - Specifies that data be aggregated by user sessions. Data that does not fall within the time range of a session will not be included in the response. Mutually exclusive of other bucketing specifications.
* `bucketByTime` (*type:* `GoogleApi.Fitness.V1.Model.BucketByTime.t`, *default:* `nil`) - Specifies that data be aggregated by a single time interval. Mutually exclusive of other bucketing specifications.
* `endTimeMillis` (*type:* `String.t`, *default:* `nil`) - The end of a window of time. Data that intersects with this time window will be aggregated. The time is in milliseconds since epoch, inclusive.
* `filteredDataQualityStandard` (*type:* `list(String.t)`, *default:* `nil`) - DO NOT POPULATE THIS FIELD. It is ignored.
* `startTimeMillis` (*type:* `String.t`, *default:* `nil`) - The start of a window of time. Data that intersects with this time window will be aggregated. The time is in milliseconds since epoch, inclusive.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:aggregateBy => list(GoogleApi.Fitness.V1.Model.AggregateBy.t()),
:bucketByActivitySegment => GoogleApi.Fitness.V1.Model.BucketByActivity.t(),
:bucketByActivityType => GoogleApi.Fitness.V1.Model.BucketByActivity.t(),
:bucketBySession => GoogleApi.Fitness.V1.Model.BucketBySession.t(),
:bucketByTime => GoogleApi.Fitness.V1.Model.BucketByTime.t(),
:endTimeMillis => String.t(),
:filteredDataQualityStandard => list(String.t()),
:startTimeMillis => String.t()
}
field(:aggregateBy, as: GoogleApi.Fitness.V1.Model.AggregateBy, type: :list)
field(:bucketByActivitySegment, as: GoogleApi.Fitness.V1.Model.BucketByActivity)
field(:bucketByActivityType, as: GoogleApi.Fitness.V1.Model.BucketByActivity)
field(:bucketBySession, as: GoogleApi.Fitness.V1.Model.BucketBySession)
field(:bucketByTime, as: GoogleApi.Fitness.V1.Model.BucketByTime)
field(:endTimeMillis)
field(:filteredDataQualityStandard, type: :list)
field(:startTimeMillis)
end
defimpl Poison.Decoder, for: GoogleApi.Fitness.V1.Model.AggregateRequest do
def decode(value, options) do
GoogleApi.Fitness.V1.Model.AggregateRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Fitness.V1.Model.AggregateRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 66.191176 | 480 | 0.751166 |
1cebed69d22e0cad82c96167b24f1dd6cbc06cab | 1,656 | ex | Elixir | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/disk_encryption_status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/disk_encryption_status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/disk_encryption_status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus do
@moduledoc """
Disk encryption status for an instance.
## Attributes
* `kind` (*type:* `String.t`, *default:* `nil`) - This is always **sql#diskEncryptionStatus**.
* `kmsKeyVersionName` (*type:* `String.t`, *default:* `nil`) - KMS key version used to encrypt the Cloud SQL instance resource
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t() | nil,
:kmsKeyVersionName => String.t() | nil
}
field(:kind)
field(:kmsKeyVersionName)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus do
def decode(value, options) do
GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.DiskEncryptionStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.12 | 130 | 0.730676 |
1cec12bcc58245d07fdabd7a1bd764db9065f702 | 1,066 | ex | Elixir | blank/test/support/conn_case.ex | unozerocode/turbo-journey | 55c54e4b10bb1e49a1f999fd0eb03acdd35fef98 | [
"MIT"
] | null | null | null | blank/test/support/conn_case.ex | unozerocode/turbo-journey | 55c54e4b10bb1e49a1f999fd0eb03acdd35fef98 | [
"MIT"
] | 2 | 2021-03-10T20:40:33.000Z | 2021-05-11T16:13:21.000Z | blank/test/support/conn_case.ex | unozerocode/turbo-journey | 55c54e4b10bb1e49a1f999fd0eb03acdd35fef98 | [
"MIT"
] | null | null | null | defmodule BlankWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use BlankWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import BlankWeb.ConnCase
alias BlankWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint BlankWeb.Endpoint
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 28.052632 | 60 | 0.731707 |
1cec183c8a01e95416b95a2a048f0bfae10e22b6 | 4,130 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/security_policy.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/security_policy.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/security_policy.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Model.SecurityPolicy do
@moduledoc """
Represents a Cloud Armor Security Policy resource.
Only external backend services that use load balancers can reference a Security Policy. For more information, read Cloud Armor Security Policy Concepts. (== resource_for v1.securityPolicies ==) (== resource_for beta.securityPolicies ==)
## Attributes
* `creationTimestamp` (*type:* `String.t`, *default:* `nil`) - [Output Only] Creation timestamp in RFC3339 text format.
* `description` (*type:* `String.t`, *default:* `nil`) - An optional description of this resource. Provide this property when you create the resource.
* `fingerprint` (*type:* `String.t`, *default:* `nil`) - Specifies a fingerprint for this resource, which is essentially a hash of the metadata's contents and used for optimistic locking. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update metadata. You must always provide an up-to-date fingerprint hash in order to update or change metadata, otherwise the request will fail with error 412 conditionNotMet.
To see the latest fingerprint, make get() request to the security policy.
* `id` (*type:* `String.t`, *default:* `nil`) - [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* `kind` (*type:* `String.t`, *default:* `compute#securityPolicy`) - [Output only] Type of the resource. Always compute#securityPolicyfor security policies
* `name` (*type:* `String.t`, *default:* `nil`) - Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.
* `rules` (*type:* `list(GoogleApi.Compute.V1.Model.SecurityPolicyRule.t)`, *default:* `nil`) - A list of rules that belong to this policy. There must always be a default rule (rule with priority 2147483647 and match "*"). If no rules are provided when creating a security policy, a default rule with action "allow" will be added.
* `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] Server-defined URL for the resource.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:creationTimestamp => String.t(),
:description => String.t(),
:fingerprint => String.t(),
:id => String.t(),
:kind => String.t(),
:name => String.t(),
:rules => list(GoogleApi.Compute.V1.Model.SecurityPolicyRule.t()),
:selfLink => String.t()
}
field(:creationTimestamp)
field(:description)
field(:fingerprint)
field(:id)
field(:kind)
field(:name)
field(:rules, as: GoogleApi.Compute.V1.Model.SecurityPolicyRule, type: :list)
field(:selfLink)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.SecurityPolicy do
def decode(value, options) do
GoogleApi.Compute.V1.Model.SecurityPolicy.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.SecurityPolicy do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.361111 | 490 | 0.722034 |
1cec4b52f57a0069dcd661e162086a8ff6902031 | 70 | exs | Elixir | .formatter.exs | fimars/netease_music_api | 821f19782f482a092b10e3cc39c93f6c131e9075 | [
"MIT"
] | 3 | 2017-12-25T02:40:05.000Z | 2019-05-09T04:01:24.000Z | .formatter.exs | fimars/netease_music_api | 821f19782f482a092b10e3cc39c93f6c131e9075 | [
"MIT"
] | null | null | null | .formatter.exs | fimars/netease_music_api | 821f19782f482a092b10e3cc39c93f6c131e9075 | [
"MIT"
] | null | null | null | [
inputs: [
"lib/**/*.{ex,exs}",
"test/**/*.{ex,exs}"
]
]
| 10 | 24 | 0.328571 |
1cec52ecb39255941b92f0795007d70ecc4227b3 | 1,375 | ex | Elixir | lib/ex_admin/schema.ex | augnustin/ex_admin | 218d0094de8186808924dcca6157875a7bb382c9 | [
"MIT"
] | 2 | 2019-12-21T12:59:19.000Z | 2020-04-01T15:27:12.000Z | lib/ex_admin/schema.ex | augnustin/ex_admin | 218d0094de8186808924dcca6157875a7bb382c9 | [
"MIT"
] | null | null | null | lib/ex_admin/schema.ex | augnustin/ex_admin | 218d0094de8186808924dcca6157875a7bb382c9 | [
"MIT"
] | 1 | 2020-02-29T22:13:24.000Z | 2020-02-29T22:13:24.000Z | defmodule ExAdmin.Schema do
@moduledoc false
defp query_to_module(%Ecto.Query{} = q) do
{_table, module} = q.from.source
module
end
defp resource_to_module(resource) do
Map.get(resource, :__struct__)
end
def primary_key(%Ecto.Query{} = q) do
primary_key(query_to_module(q))
end
def primary_key(module) when is_atom(module) do
case module.__schema__(:primary_key) do
[] -> nil
[key | _] -> key
end
end
def primary_key(resource) do
if resource_to_module(resource) do
primary_key(resource_to_module(resource))
else
:id
end
end
def get_id(resource) do
Map.get(resource, primary_key(resource))
end
def type(%Ecto.Query{} = q, key) do
type(query_to_module(q), key)
end
def type(module, key) when is_atom(module) do
module.__schema__(:type, key)
end
def type(resource, key), do: type(resource_to_module(resource), key)
def get_intersection_keys(resource, assoc_name) do
resource_model = resource.__struct__
%{through: [link1, link2]} = resource_model.__schema__(:association, assoc_name)
intersection_model = resource |> Ecto.build_assoc(link1) |> Map.get(:__struct__)
[
resource_key: resource_model.__schema__(:association, link1).related_key,
assoc_key: intersection_model.__schema__(:association, link2).owner_key
]
end
end
| 24.122807 | 84 | 0.694545 |
1cec63a55e34fbfbf640fbfc654b7cb0b0e8a35a | 906 | ex | Elixir | apps/tag_editor/lib/tag_editor/application.ex | gregredhead/belethor | 255925396b18ba4a6950f386abf8a9e17a7e5e7c | [
"Apache-2.0"
] | 3 | 2018-07-20T22:14:36.000Z | 2018-12-21T19:54:48.000Z | apps/tag_editor/lib/tag_editor/application.ex | gregredhead/belethor | 255925396b18ba4a6950f386abf8a9e17a7e5e7c | [
"Apache-2.0"
] | 36 | 2018-09-15T21:46:54.000Z | 2020-03-28T16:10:18.000Z | apps/tag_editor/lib/tag_editor/application.ex | gregredhead/belethor | 255925396b18ba4a6950f386abf8a9e17a7e5e7c | [
"Apache-2.0"
] | 2 | 2018-07-22T08:47:07.000Z | 2021-12-11T01:39:19.000Z | defmodule TagEditor.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
alias TagEditorWeb.Endpoint
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the endpoint when the application starts
TagEditorWeb.Endpoint
# Starts a worker by calling: TagEditor.Worker.start_link(arg)
# {TagEditor.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: TagEditor.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
Endpoint.config_change(changed, removed)
:ok
end
end
| 28.3125 | 68 | 0.724062 |
1cec741031e325fdc726559acd8c15539d018bdf | 484 | ex | Elixir | apps/sample/lib/sample/application.ex | ODYLIGHT/sample_umbrella | 8b4ef00c732e24ccec6d98555d7542dff10a73f9 | [
"MIT"
] | 1 | 2020-02-20T11:27:02.000Z | 2020-02-20T11:27:02.000Z | apps/sample/lib/sample/application.ex | ODYLIGHT/sample_umbrella | 8b4ef00c732e24ccec6d98555d7542dff10a73f9 | [
"MIT"
] | 1 | 2020-04-30T00:58:40.000Z | 2020-04-30T00:58:40.000Z | apps/sample/lib/sample/application.ex | ODYLIGHT/sample_umbrella | 8b4ef00c732e24ccec6d98555d7542dff10a73f9 | [
"MIT"
] | null | null | null | defmodule Sample.Application do
@moduledoc """
The Sample Application Service.
The sample system business domain lives in this application.
Exposes API to clients such as the `SampleWeb` application
for use in channels, controllers, and elsewhere.
"""
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
Supervisor.start_link([
supervisor(Sample.Repo, []),
], strategy: :one_for_one, name: Sample.Supervisor)
end
end
| 24.2 | 62 | 0.72314 |
1cec78116ba0d3289d4d01462375957e10263b40 | 831 | ex | Elixir | lib/mongooseice/udp/worker_supervisor.ex | glassechidna/MongooseICE | c2ea99f47460fd7293b51eaa72fbce122a60affe | [
"Apache-2.0"
] | 90 | 2017-09-26T12:20:06.000Z | 2022-01-30T17:58:11.000Z | lib/mongooseice/udp/worker_supervisor.ex | glassechidna/MongooseICE | c2ea99f47460fd7293b51eaa72fbce122a60affe | [
"Apache-2.0"
] | 39 | 2017-01-20T08:54:13.000Z | 2017-09-13T11:30:14.000Z | lib/mongooseice/udp/worker_supervisor.ex | glassechidna/MongooseICE | c2ea99f47460fd7293b51eaa72fbce122a60affe | [
"Apache-2.0"
] | 13 | 2018-03-29T07:03:25.000Z | 2022-03-06T10:21:45.000Z | defmodule MongooseICE.UDP.WorkerSupervisor do
@moduledoc false
# Supervisor of `MongooseICE.UDP.Worker` processes
alias MongooseICE.UDP
def start_link(base_name, server_opts) do
import Supervisor.Spec, warn: false
name = UDP.worker_sup_name(base_name)
dispatcher = UDP.dispatcher_name(base_name)
children = [
worker(MongooseICE.UDP.Worker, [dispatcher, server_opts], restart: :temporary)
]
opts = [strategy: :simple_one_for_one, name: name]
Supervisor.start_link(children, opts)
end
# Starts worker under WorkerSupervisor
@spec start_worker(atom, MongooseICE.client_info) :: {:ok, pid} | :error
def start_worker(worker_sup, client) do
case Supervisor.start_child(worker_sup, [client]) do
{:ok, pid} ->
{:ok, pid}
_ ->
:error
end
end
end
| 25.96875 | 84 | 0.694344 |
1cec8ca42253f11934b863bb66986394023e19a9 | 3,737 | ex | Elixir | clients/storage_transfer/lib/google_api/storage_transfer/v1/model/transfer_spec.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/storage_transfer/lib/google_api/storage_transfer/v1/model/transfer_spec.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/storage_transfer/lib/google_api/storage_transfer/v1/model/transfer_spec.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.StorageTransfer.V1.Model.TransferSpec do
@moduledoc """
Configuration for running a transfer.
## Attributes
* `awsS3DataSource` (*type:* `GoogleApi.StorageTransfer.V1.Model.AwsS3Data.t`, *default:* `nil`) - An AWS S3 data source.
* `azureBlobStorageDataSource` (*type:* `GoogleApi.StorageTransfer.V1.Model.AzureBlobStorageData.t`, *default:* `nil`) - An Azure Blob Storage data source.
* `gcsDataSink` (*type:* `GoogleApi.StorageTransfer.V1.Model.GcsData.t`, *default:* `nil`) - A Cloud Storage data sink.
* `gcsDataSource` (*type:* `GoogleApi.StorageTransfer.V1.Model.GcsData.t`, *default:* `nil`) - A Cloud Storage data source.
* `httpDataSource` (*type:* `GoogleApi.StorageTransfer.V1.Model.HttpData.t`, *default:* `nil`) - An HTTP URL data source.
* `objectConditions` (*type:* `GoogleApi.StorageTransfer.V1.Model.ObjectConditions.t`, *default:* `nil`) - Only objects that satisfy these object conditions are included in the set
of data source and data sink objects. Object conditions based on
objects' "last modification time" do not exclude objects in a data sink.
* `transferOptions` (*type:* `GoogleApi.StorageTransfer.V1.Model.TransferOptions.t`, *default:* `nil`) - If the option
delete_objects_unique_in_sink
is `true`, object conditions based on objects' "last modification time" are
ignored and do not exclude objects in a data source or a data sink.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:awsS3DataSource => GoogleApi.StorageTransfer.V1.Model.AwsS3Data.t(),
:azureBlobStorageDataSource =>
GoogleApi.StorageTransfer.V1.Model.AzureBlobStorageData.t(),
:gcsDataSink => GoogleApi.StorageTransfer.V1.Model.GcsData.t(),
:gcsDataSource => GoogleApi.StorageTransfer.V1.Model.GcsData.t(),
:httpDataSource => GoogleApi.StorageTransfer.V1.Model.HttpData.t(),
:objectConditions => GoogleApi.StorageTransfer.V1.Model.ObjectConditions.t(),
:transferOptions => GoogleApi.StorageTransfer.V1.Model.TransferOptions.t()
}
field(:awsS3DataSource, as: GoogleApi.StorageTransfer.V1.Model.AwsS3Data)
field(:azureBlobStorageDataSource, as: GoogleApi.StorageTransfer.V1.Model.AzureBlobStorageData)
field(:gcsDataSink, as: GoogleApi.StorageTransfer.V1.Model.GcsData)
field(:gcsDataSource, as: GoogleApi.StorageTransfer.V1.Model.GcsData)
field(:httpDataSource, as: GoogleApi.StorageTransfer.V1.Model.HttpData)
field(:objectConditions, as: GoogleApi.StorageTransfer.V1.Model.ObjectConditions)
field(:transferOptions, as: GoogleApi.StorageTransfer.V1.Model.TransferOptions)
end
defimpl Poison.Decoder, for: GoogleApi.StorageTransfer.V1.Model.TransferSpec do
def decode(value, options) do
GoogleApi.StorageTransfer.V1.Model.TransferSpec.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.StorageTransfer.V1.Model.TransferSpec do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 52.633803 | 184 | 0.744447 |
1cecda786615ae092312c232929d30e9c4ae62b3 | 438 | exs | Elixir | config/dev.exs | arpieb/annex | 6f472a30361bf0a1646e256d6dfe478706427f64 | [
"MIT"
] | 1 | 2020-10-23T13:41:07.000Z | 2020-10-23T13:41:07.000Z | config/dev.exs | arpieb/annex | 6f472a30361bf0a1646e256d6dfe478706427f64 | [
"MIT"
] | null | null | null | config/dev.exs | arpieb/annex | 6f472a30361bf0a1646e256d6dfe478706427f64 | [
"MIT"
] | null | null | null | use Mix.Config
config :annex, Annex.Data.DTensor, debug: true
config :git_hooks,
hooks: [
pre_commit: [
verbose: true,
tasks: [
"mix format --check-formatted --dry-run --check-equivalent"
]
],
pre_push: [
verbose: true,
tasks: [
"mix clean",
"mix compile --warnings-as-errors",
"mix credo --strict",
"mix dialyzer --halt-exit-status"
]
]
]
| 19.043478 | 67 | 0.53653 |
1cecdb7b51c0cef5da59a4abe6148e0eb22d91f6 | 1,558 | exs | Elixir | test/ex_docker_compose/subcommands_test.exs | amitizle/ex_docker_compose | 55ad38f24771af9f2d30889da5762c3148f87e18 | [
"MIT"
] | 2 | 2020-12-15T02:59:04.000Z | 2021-05-05T02:21:24.000Z | test/ex_docker_compose/subcommands_test.exs | amitizle/ex_docker_compose | 55ad38f24771af9f2d30889da5762c3148f87e18 | [
"MIT"
] | 1 | 2018-01-21T19:00:04.000Z | 2018-01-21T19:00:04.000Z | test/ex_docker_compose/subcommands_test.exs | amitizle/ex_docker_compose | 55ad38f24771af9f2d30889da5762c3148f87e18 | [
"MIT"
] | null | null | null | defmodule ExDockerCompose.SubcommandsTest do
use ExUnit.Case
doctest ExDockerCompose.Subcommands
@compose_bin "/bin/dc"
test "build command without opts should just return the subcommand" do
assert {:ok, "#{@compose_bin} up"} = ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [], [])
end
test "build command with one letter opts and no args" do
assert {:ok, "#{@compose_bin} up -d"} = ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [], [:d])
end
test "build command with one letter opts and multiple args" do
assert {:ok, "#{@compose_bin} up -d -t 10"} = ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [], [:d, {:t, 10}])
end
test "build command with many letters opts and no args" do
assert {:ok, "#{@compose_bin} up --dummy"} = ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [], [:dummy])
end
test "build command with many letters opts" do
assert {:ok, "#{@compose_bin} up --dummy --timeout 10"} = ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [], [:dummy, {:timeout, 10}])
end
test "build command with docker-compose opts only" do
assert {:ok, "#{@compose_bin} -f compose.yml up"} = ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [{:f, "compose.yml"}], [])
end
test "build command with docker-compose and subcommand opts" do
assert {:ok, "#{@compose_bin} -f compose.yml up -d -t 10"} =
ExDockerCompose.Subcommands.build_command(@compose_bin, :up, [{:f, "compose.yml"}], [:d, {:t, 10}])
end
end
| 42.108108 | 152 | 0.685494 |
1ced38458c2143fa8a9a17cc330d5444c3228816 | 1,553 | exs | Elixir | mix.exs | sveredyuk/absinthe_ecto | 3c216d837d39ce8684ccfa7d0052375fdbc127b7 | [
"MIT"
] | null | null | null | mix.exs | sveredyuk/absinthe_ecto | 3c216d837d39ce8684ccfa7d0052375fdbc127b7 | [
"MIT"
] | null | null | null | mix.exs | sveredyuk/absinthe_ecto | 3c216d837d39ce8684ccfa7d0052375fdbc127b7 | [
"MIT"
] | null | null | null | defmodule Absinthe.Ecto.Mixfile do
use Mix.Project
@version "0.1.3"
def project do
[app: :absinthe_ecto,
version: @version,
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
elixirc_paths: elixirc_paths(Mix.env),
package: package(),
source_url: "https://github.com/absinthe-graphql/absinthe_ecto",
docs: [source_ref: "v#{@version}", main: "Absinthe.Ecto"],
deps: deps()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger, :absinthe, :ecto]]
end
defp package do
[description: "GraphQL helpers for Absinthe",
files: ["lib", "priv", "mix.exs", "README*"],
maintainers: ["Bruce Williams", "Ben Wilson"],
licenses: ["MIT"],
links: %{github: "https://github.com/absinthe-graphql/absinthe_ecto"}]
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
[
{:absinthe, "~> 1.6.0"},
{:ecto, ">= 0.0.0"},
{:ex_doc, ">= 0.0.0", only: [:dev]},
{:postgrex, ">= 0.13.0", only: [:test]},
{:ex_machina, ">= 2.0.0", only: [:test]},
]
end
defp elixirc_paths(:test), do: elixirc_paths() ++ ["test/support"]
defp elixirc_paths(_), do: elixirc_paths()
defp elixirc_paths(), do: ["lib"]
end
| 27.245614 | 77 | 0.598197 |
1ced4862e6a2c23464eebab12b5da652660b58b8 | 1,925 | exs | Elixir | config/dev.exs | elixir-china-community/community | b1c52c0530949a60bf4aadf63e60a34c5d58dd66 | [
"MIT"
] | 18 | 2019-10-04T01:49:16.000Z | 2020-07-04T23:53:26.000Z | config/dev.exs | elixirchina/community | b1c52c0530949a60bf4aadf63e60a34c5d58dd66 | [
"MIT"
] | 2 | 2019-10-17T04:56:54.000Z | 2019-11-11T04:05:06.000Z | config/dev.exs | elixir-china-community/community | b1c52c0530949a60bf4aadf63e60a34c5d58dd66 | [
"MIT"
] | 5 | 2019-10-17T06:42:26.000Z | 2020-02-17T18:08:54.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 webpack to recompile .js and .css sources.
config :community, CommunityWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch-stdin",
cd: Path.expand("../assets", __DIR__)
]
]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :community, CommunityWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/community_web/{live,views}/.*(ex)$",
~r"lib/community_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 28.308824 | 68 | 0.685714 |
1ced627e0a008920be64d8baf333bc99328830ac | 767 | exs | Elixir | lib/ex_unit/mix.exs | chulkilee/elixir | 699231dcad52916a76f38856cbd7cf7c7bdadc51 | [
"Apache-2.0"
] | 1 | 2021-04-28T21:35:01.000Z | 2021-04-28T21:35:01.000Z | lib/ex_unit/mix.exs | chulkilee/elixir | 699231dcad52916a76f38856cbd7cf7c7bdadc51 | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/mix.exs | chulkilee/elixir | 699231dcad52916a76f38856cbd7cf7c7bdadc51 | [
"Apache-2.0"
] | 8 | 2018-02-20T18:30:53.000Z | 2019-06-18T14:23:31.000Z | defmodule ExUnit.MixProject do
use Mix.Project
def project do
[
app: :ex_unit,
version: System.version(),
build_per_environment: false
]
end
def application do
[
registered: [ExUnit.Server],
mod: {ExUnit, []},
env: [
# Calculated on demand
# max_cases: System.schedulers_online * 2,
# seed: rand(),
assert_receive_timeout: 100,
autorun: true,
capture_log: false,
module_load_timeout: 60000,
colors: [],
exclude: [],
formatters: [ExUnit.CLIFormatter],
include: [],
refute_receive_timeout: 100,
slowest: 0,
stacktrace_depth: 20,
timeout: 60000,
trace: false
]
]
end
end
| 20.184211 | 50 | 0.551499 |
1cedad561fe89ecc599ad90d04d7109238233ce4 | 2,188 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/reservation_aggregated_list_warning.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/reservation_aggregated_list_warning.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/compute/lib/google_api/compute/v1/model/reservation_aggregated_list_warning.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.Compute.V1.Model.ReservationAggregatedListWarning do
@moduledoc """
[Output Only] Informational warning message.
## Attributes
* `code` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response.
* `data` (*type:* `list(GoogleApi.Compute.V1.Model.ReservationAggregatedListWarningData.t)`, *default:* `nil`) - [Output Only] Metadata about this warning in key: value format. For example:
"data": [ { "key": "scope", "value": "zones/us-east1-d" }
* `message` (*type:* `String.t`, *default:* `nil`) - [Output Only] A human-readable description of the warning code.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => String.t(),
:data => list(GoogleApi.Compute.V1.Model.ReservationAggregatedListWarningData.t()),
:message => String.t()
}
field(:code)
field(:data, as: GoogleApi.Compute.V1.Model.ReservationAggregatedListWarningData, type: :list)
field(:message)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.ReservationAggregatedListWarning do
def decode(value, options) do
GoogleApi.Compute.V1.Model.ReservationAggregatedListWarning.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.ReservationAggregatedListWarning do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.518519 | 194 | 0.72989 |
1cedcf3e4f48ab33c883209a4fe8747dc618dc92 | 868 | ex | Elixir | deps/mazurka/lib/mazurka/utils.ex | conorfoley/dota_hero_combos | d75a3f0673fc1f1d0845c9d5c692c0605d3b445d | [
"MIT"
] | null | null | null | deps/mazurka/lib/mazurka/utils.ex | conorfoley/dota_hero_combos | d75a3f0673fc1f1d0845c9d5c692c0605d3b445d | [
"MIT"
] | null | null | null | deps/mazurka/lib/mazurka/utils.ex | conorfoley/dota_hero_combos | d75a3f0673fc1f1d0845c9d5c692c0605d3b445d | [
"MIT"
] | null | null | null | defmodule Mazurka.Utils do
@moduledoc false
def eval(quoted, env) do
{out, []} = quoted
|> Macro.expand(env)
|> Code.eval_quoted([], env)
out
end
def prewalk(quoted, fun) do
Macro.prewalk(quoted, walk(fun, &prewalk(&1, fun)))
end
def postwalk(quoted, fun) do
Macro.postwalk(quoted, walk(fun, &postwalk(&1, fun)))
end
defp walk(fun, recurse) do
fn
({:__block__, meta, children}) ->
{:__block__, meta, Enum.map(children, recurse)}
([{:do, _} | _] = doblock) ->
Enum.map(doblock, fn({key, children}) ->
children = recurse.(children)
{key, children}
end)
|> fun.()
({name, children}) when is_atom(name) ->
children = recurse.(children)
{name, children}
|> fun.()
(other) ->
other
|> fun.()
end
end
end
| 22.25641 | 57 | 0.539171 |
1cee2e67bdeffdc7947b2517368ec98b6571338d | 2,725 | exs | Elixir | test/mix/tasks/prom_ex.gen.config_test.exs | maartenvanvliet/prom_ex | 8eb4f86c169af3b184a1a45cf42e298af2b05816 | [
"MIT"
] | 354 | 2020-10-21T06:27:15.000Z | 2022-03-29T13:22:46.000Z | test/mix/tasks/prom_ex.gen.config_test.exs | maartenvanvliet/prom_ex | 8eb4f86c169af3b184a1a45cf42e298af2b05816 | [
"MIT"
] | 111 | 2020-11-25T21:27:13.000Z | 2022-03-28T10:42:59.000Z | test/mix/tasks/prom_ex.gen.config_test.exs | maartenvanvliet/prom_ex | 8eb4f86c169af3b184a1a45cf42e298af2b05816 | [
"MIT"
] | 45 | 2020-12-31T20:37:11.000Z | 2022-03-18T13:12:21.000Z | defmodule Mix.Tasks.PromEx.Gen.ConfigTest do
use ExUnit.Case
import ExUnit.CaptureIO
import Mix.Tasks.PromEx.Gen.Config
test "raises if invalid args are present" do
assert_raise RuntimeError, ~r/Invalid CLI args/, fn ->
run(~w(--unexpected unknown))
end
end
test "raises if datasource arg is missing" do
assert_raise RuntimeError, ~r/Missing required arguments/, fn ->
run([])
end
end
test "raises if otp_app directory does not exist" do
assert_raise RuntimeError, ~r/Required directory path/, fn ->
run(~w(-d an_id -o whoa_there))
end
end
setup do
tmp_dir = Path.join(File.cwd!(), "tmp")
sample_app_dir = Path.join([tmp_dir, "lib", "sample"])
File.mkdir_p!(sample_app_dir)
on_exit(fn -> File.rm_rf!(tmp_dir) end)
[sample_app_dir: sample_app_dir, tmp_dir: tmp_dir]
end
test "otp_app can be provided as an arg", ctx do
capture_io(fn ->
File.cd!(ctx.tmp_dir, fn -> run(~w(-d an_id -o sample)) end)
end)
contents =
ctx.sample_app_dir
|> Path.join("prom_ex.ex")
|> File.read!()
# Datasource ID
assert contents =~ ~r/datasource_id: "an_id"/
# Module name
assert contents =~ ~r/defmodule Sample.PromEx/
# OTP app
assert contents =~ ~r/use PromEx, otp_app: :sample/
end
test "prompts user for confirmation if config is already generated", ctx do
# File did not exist previously
assert capture_io(fn ->
File.cd!(ctx.tmp_dir, fn -> run(~w(-d an_id -o sample)) end)
end) =~ "Success"
assert capture_io([input: "n"], fn ->
File.cd!(ctx.tmp_dir, fn -> run(~w(-d an_id -o sample)) end)
end) =~ "Did not write file out"
assert capture_io([input: "y"], fn ->
File.cd!(ctx.tmp_dir, fn -> run(~w(-d an_id -o sample)) end)
end) =~ "Success"
end
setup ctx do
path = Path.join(ctx.tmp_dir, "mix.exs")
contents = """
defmodule Sample.MixProject do
use Mix.Project
def project do
[
app: :sample,
version: "0.1.0"
]
end
end
"""
File.write!(path, contents)
Code.ensure_compiled(Sample.MixProject)
:ok
end
test "otp_app is read from config if missing", ctx do
capture_io(fn ->
Mix.Project.in_project(:sample, ctx.tmp_dir, fn _ ->
run(~w(-d an_id))
end)
end)
contents =
ctx.sample_app_dir
|> Path.join("prom_ex.ex")
|> File.read!()
# Datasource ID
assert contents =~ ~r/datasource_id: "an_id"/
# Module name
assert contents =~ ~r/defmodule Sample.PromEx/
# OTP app
assert contents =~ ~r/use PromEx, otp_app: :sample/
end
end
| 25.46729 | 77 | 0.606606 |
1cee4ab3db7cdf875f37477c18f981a5eb0da257 | 330 | ex | Elixir | src/phoenix/hello/lib/hello_web/controllers/hello_controller.ex | mkdika/learn-elixir | f66defe8c7255f2b36dcf668e10389b0f2b0985a | [
"MIT"
] | null | null | null | src/phoenix/hello/lib/hello_web/controllers/hello_controller.ex | mkdika/learn-elixir | f66defe8c7255f2b36dcf668e10389b0f2b0985a | [
"MIT"
] | null | null | null | src/phoenix/hello/lib/hello_web/controllers/hello_controller.ex | mkdika/learn-elixir | f66defe8c7255f2b36dcf668e10389b0f2b0985a | [
"MIT"
] | null | null | null | defmodule HelloWeb.HelloController do
use HelloWeb, :controller
@spec index(Plug.Conn.t(), any()) :: Plug.Conn.t()
def index(conn, _params), do: render(conn, "index.html") # can use single line naming function
def show(conn, %{"messenger" => messenger}) do
render(conn, "show.html", messenger: messenger)
end
end
| 27.5 | 96 | 0.690909 |
1cee65bac8c370704b8a6697963d0f2398d5a0a5 | 65 | ex | Elixir | apps/ex_figment_web/lib/ex_figment_web/views/page_view.ex | rishenko/ex_figment | 7cb578a0da26dd50a947f6c155adc0c69a37ad4b | [
"Apache-2.0"
] | 1 | 2018-05-05T18:34:53.000Z | 2018-05-05T18:34:53.000Z | apps/ex_figment_web/lib/ex_figment_web/views/page_view.ex | rishenko/ex_figment | 7cb578a0da26dd50a947f6c155adc0c69a37ad4b | [
"Apache-2.0"
] | null | null | null | apps/ex_figment_web/lib/ex_figment_web/views/page_view.ex | rishenko/ex_figment | 7cb578a0da26dd50a947f6c155adc0c69a37ad4b | [
"Apache-2.0"
] | null | null | null | defmodule ExFigmentWeb.PageView do
use ExFigmentWeb, :view
end
| 16.25 | 34 | 0.815385 |
1cee68f2aa492e8c26af752b5ace5ef2301695cd | 10,418 | exs | Elixir | test/controllers/tp_threshold_controller_test.exs | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | test/controllers/tp_threshold_controller_test.exs | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | test/controllers/tp_threshold_controller_test.exs | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | defmodule CgratesWebJsonapi.TpThresholdControllerTest do
use CgratesWebJsonapi.ConnCase
alias CgratesWebJsonapi.TpThreshold
alias CgratesWebJsonapi.Repo
import CgratesWebJsonapi.Factory
setup do
user = insert :user
conn = build_conn()
|> put_req_header("accept", "application/vnd.api+json")
|> put_req_header("content-type", "application/vnd.api+json")
|> Guardian.Plug.api_sign_in(
user,
:token,
perms: %{default: [:read, :write]}
)
{:ok, conn: conn}
end
describe "GET index" do
test "lists all entries related tariff plan on index", %{conn: conn} do
tariff_plan_1 = insert :tariff_plan
tariff_plan_2 = insert :tariff_plan
insert :tp_threshold, tpid: tariff_plan_1.alias
insert :tp_threshold, tpid: tariff_plan_2.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan_1.alias)) |> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by tenant", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{tenant: t1.tenant})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by custom_id", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{custom_id: t1.custom_id})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by action_ids", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{action_ids: t1.action_ids})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by filter_ids", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{filter_ids: t1.filter_ids})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by activation_interval", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{activation_interval: t1.activation_interval})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by min_sleep", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{min_sleep: t1.min_sleep})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by min_hits", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias, min_hits: 3
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{min_hits: t1.min_hits})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by async", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias, async: true
t2 = insert :tp_threshold, tpid: tariff_plan.alias, async: false
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{async: true})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by max_hits", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias
t2 = insert :tp_threshold, tpid: tariff_plan.alias, max_hits: 20
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{max_hits: t1.max_hits})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by blocker", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias, blocker: true
t2 = insert :tp_threshold, tpid: tariff_plan.alias, blocker: false
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{blocker: true})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
test "filtering by weight", %{conn: conn} do
tariff_plan = insert :tariff_plan
t1 = insert :tp_threshold, tpid: tariff_plan.alias, weight: 1
t2 = insert :tp_threshold, tpid: tariff_plan.alias, weight: 2
conn = get(conn, tp_threshold_path(conn, :index, tpid: tariff_plan.alias), filter: %{weight: t1.weight})
|> doc
assert length(json_response(conn, 200)["data"]) == 1
end
end
describe "GET show" do
test "shows chosen resource", %{conn: conn} do
tariff_plan = insert :tariff_plan
tp_threshold = insert :tp_threshold, tpid: tariff_plan.alias
conn = get(conn, tp_threshold_path(conn, :show, tp_threshold)) |> doc
data = json_response(conn, 200)["data"]
assert data["id"] == "#{tp_threshold.pk}"
assert data["type"] == "tp-threshold"
assert data["attributes"]["tpid"] == tp_threshold.tpid
assert data["attributes"]["tenant"] == tp_threshold.tenant
assert data["attributes"]["min-sleep"] == tp_threshold.min_sleep
assert data["attributes"]["filter-ids"] == tp_threshold.filter_ids
assert data["attributes"]["activation-interval"] == tp_threshold.activation_interval
assert data["attributes"]["max-hits"] == tp_threshold.max_hits
assert data["attributes"]["min-hits"] == tp_threshold.min_hits
assert data["attributes"]["action-ids"] == tp_threshold.action_ids
assert data["attributes"]["async"] == tp_threshold.async
assert data["attributes"]["blocker"] == tp_threshold.blocker
assert data["attributes"]["weight"] == "10.00"
end
test "does not show resource and instead throw error when id is nonexistent", %{conn: conn} do
assert_error_sent 404, fn ->
get(conn, tp_threshold_path(conn, :show, -1)) |> doc
end
end
end
describe "GET export_to_csv" do
test "returns status 'ok'", %{conn: conn} do
tariff_plan = insert :tariff_plan
insert :tp_threshold, tpid: tariff_plan.alias, blocker: true, tenant: "t1"
insert :tp_threshold, tpid: tariff_plan.alias, blocker: false
conn = conn
|> get(tp_threshold_path(conn, :export_to_csv), %{tpid: tariff_plan.alias, filter: %{blocker: true, tenant: "t1"}})
|> doc()
assert conn.status == 200
end
end
describe "POST create" do
test "creates and renders resource when data is valid", %{conn: conn} do
tariff_plan = insert :tariff_plan
params = Map.merge params_for(:tp_threshold), %{tpid: tariff_plan.alias}
conn = post(conn, tp_threshold_path(conn, :create), %{
"meta" => %{},
"data" => %{
"type" => "tp_threshold",
"attributes" => params,
}
}) |> doc
assert json_response(conn, 201)["data"]["id"]
assert Repo.get_by(TpThreshold, params)
end
test "does not create resource and renders errors when data is invalid", %{conn: conn} do
conn = post(conn, tp_threshold_path(conn, :create), %{
"meta" => %{},
"data" => %{
"type" => "tp_threshold",
"attributes" => %{min_sleep: nil},
}
}) |> doc
assert json_response(conn, 422)["errors"] != %{}
end
end
describe "PATCH/PUT update" do
test "updates and renders chosen resource when data is valid", %{conn: conn} do
tariff_plan = insert :tariff_plan
tp_threshold = insert :tp_threshold, tpid: tariff_plan.alias
params = params_for(:tp_threshold)
conn = put(conn, tp_threshold_path(conn, :update, tp_threshold), %{
"meta" => %{},
"data" => %{
"type" => "tp_threshold",
"id" => tp_threshold.pk,
"attributes" => params,
}
}) |> doc
assert json_response(conn, 200)["data"]["id"]
assert Repo.get_by(TpThreshold, params)
end
test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do
tariff_plan = insert :tariff_plan
tp_threshold = insert :tp_threshold, tpid: tariff_plan.alias
conn = put(conn, tp_threshold_path(conn, :update, tp_threshold), %{
"meta" => %{},
"data" => %{
"type" => "tp_threshold",
"id" => tp_threshold.pk,
"attributes" => %{min_sleep: nil},
}
}) |> doc
assert json_response(conn, 422)["errors"] != %{}
end
end
describe "DELETE destroy" do
test "deletes chosen resource", %{conn: conn} do
tariff_plan = insert :tariff_plan
tp_threshold = insert :tp_threshold, tpid: tariff_plan.alias
conn = delete(conn, tp_threshold_path(conn, :delete, tp_threshold)) |> doc
assert response(conn, 204)
refute Repo.get(TpThreshold, tp_threshold.pk)
end
end
describe "DELETE delete_all" do
test "deletes all records by filter", %{conn: conn} do
tariff_plan = insert :tariff_plan
tp_threshold1 = insert :tp_threshold, tpid: tariff_plan.alias, blocker: true, tenant: "tenant1"
tp_threshold2 = insert :tp_threshold, tpid: tariff_plan.alias, blocker: false
conn = conn
|> post(tp_threshold_path(conn, :delete_all), %{tpid: tariff_plan.alias, filter: %{blocker: false}})
assert Repo.get(TpThreshold, tp_threshold1.pk)
refute Repo.get(TpThreshold, tp_threshold2.pk)
end
end
end
| 35.924138 | 136 | 0.646669 |
1cee76170381b03b9c31e6cf770aeada79c56031 | 240 | exs | Elixir | priv/repo/migrations/20160912135432_add_featured_to_products.exs | anndream/phoenix-commerce | 5e4471fa8fd1ac402d4df68fe7ccbcb0f7a53296 | [
"MIT"
] | 229 | 2016-09-21T09:24:46.000Z | 2020-05-16T22:41:31.000Z | priv/repo/migrations/20160912135432_add_featured_to_products.exs | sadiqmmm/ex-shop | 5e4471fa8fd1ac402d4df68fe7ccbcb0f7a53296 | [
"MIT"
] | 3 | 2016-09-21T10:26:50.000Z | 2016-10-19T07:25:12.000Z | priv/repo/migrations/20160912135432_add_featured_to_products.exs | sadiqmmm/ex-shop | 5e4471fa8fd1ac402d4df68fe7ccbcb0f7a53296 | [
"MIT"
] | 32 | 2016-09-22T05:19:05.000Z | 2019-11-01T04:07:13.000Z | defmodule Ap.Repo.Migrations.AddFeaturedToProducts do
use Ecto.Migration
def change do
alter table(:products) do
add :featured, :boolean, default: true, null: false
end
create index(:products, [:featured])
end
end
| 20 | 57 | 0.704167 |
1cee83c82502c2d8b29b7b6b44c9f192454efed9 | 1,255 | ex | Elixir | netaxs_sniff/suckmisic/test/support/conn_case.ex | TomasMadeja/santomet-playground | f4467233401756e276612b8a94421e7820ad67fc | [
"WTFPL"
] | null | null | null | netaxs_sniff/suckmisic/test/support/conn_case.ex | TomasMadeja/santomet-playground | f4467233401756e276612b8a94421e7820ad67fc | [
"WTFPL"
] | null | null | null | netaxs_sniff/suckmisic/test/support/conn_case.ex | TomasMadeja/santomet-playground | f4467233401756e276612b8a94421e7820ad67fc | [
"WTFPL"
] | null | null | null | defmodule SuckmisicWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use SuckmisicWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import SuckmisicWeb.ConnCase
alias SuckmisicWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint SuckmisicWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Suckmisic.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Suckmisic.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 28.522727 | 71 | 0.72749 |
1ceea908a0a7051174f40e7d1f035d1111163654 | 5,443 | exs | Elixir | .credo.exs | sztosz/sentry-elixir | 3a2cf14eb4a4778d7e77e3b851897a2575b08052 | [
"MIT"
] | null | null | null | .credo.exs | sztosz/sentry-elixir | 3a2cf14eb4a4778d7e77e3b851897a2575b08052 | [
"MIT"
] | null | null | null | .credo.exs | sztosz/sentry-elixir | 3a2cf14eb4a4778d7e77e3b851897a2575b08052 | [
"MIT"
] | null | null | null | # This file contains the configuration for Credo and you are probably reading
# this after creating it with `mix credo.gen.config`.
#
# If you find anything wrong or unclear in this file, please report an
# issue on GitHub: https://github.com/rrrene/credo/issues
#
%{
#
# You can have as many configs as you like in the `configs:` field.
configs: [
%{
#
# Run any config using `mix credo -C <name>`. If no config name is given
# "default" is used.
name: "default",
#
# These are the files included in the analysis:
files: %{
#
# You can give explicit globs or simply directories.
# In the latter case `**/*.{ex,exs}` will be used.
included: ["lib/", "src/", "web/", "apps/"],
excluded: [~r"/_build/", ~r"/deps/"]
},
#
# If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis.
requires: [],
#
# Credo automatically checks for updates, like e.g. Hex does.
# You can disable this behaviour below:
check_for_updates: true,
#
# If you want to enforce a style guide and need a more traditional linting
# experience, you can change `strict` to `true` below:
strict: false,
#
# If you want to use uncolored output by default, you can change `color`
# to `false` below:
color: true,
#
# You can customize the parameters of any check by adding a second element
# to the tuple.
#
# To disable a check put `false` as second element:
#
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: [
{Credo.Check.Consistency.ExceptionNames},
{Credo.Check.Consistency.LineEndings},
{Credo.Check.Consistency.MultiAliasImportRequireUse},
{Credo.Check.Consistency.ParameterPatternMatching},
{Credo.Check.Consistency.SpaceAroundOperators},
{Credo.Check.Consistency.SpaceInParentheses},
{Credo.Check.Consistency.TabsOrSpaces},
# For some checks, like AliasUsage, you can only customize the priority
# Priority values are: `low, normal, high, higher`
{Credo.Check.Design.AliasUsage, priority: :low},
# For others you can set parameters
# If you don't want the `setup` and `test` macro calls in ExUnit tests
# or the `schema` macro in Ecto schemas to trigger DuplicatedCode, just
# set the `excluded_macros` parameter to `[:schema, :setup, :test]`.
{Credo.Check.Design.DuplicatedCode, excluded_macros: []},
# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
{Credo.Check.Design.TagTODO, exit_status: 0},
{Credo.Check.Design.TagFIXME},
{Credo.Check.Readability.FunctionNames},
{Credo.Check.Readability.LargeNumbers},
{Credo.Check.Readability.MaxLineLength, priority: :low, max_length: 80},
{Credo.Check.Readability.ModuleAttributeNames},
{Credo.Check.Readability.ModuleDoc},
{Credo.Check.Readability.ModuleNames},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs},
{Credo.Check.Readability.ParenthesesInCondition, false},
{Credo.Check.Readability.PredicateFunctionNames},
{Credo.Check.Readability.PreferImplicitTry},
{Credo.Check.Readability.RedundantBlankLines},
{Credo.Check.Readability.Specs, false},
{Credo.Check.Readability.StringSigils},
{Credo.Check.Readability.TrailingBlankLine},
{Credo.Check.Readability.TrailingWhiteSpace},
{Credo.Check.Readability.VariableNames},
{Credo.Check.Refactor.DoubleBooleanNegation},
# {Credo.Check.Refactor.CaseTrivialMatches}, # deprecated in 0.4.0
{Credo.Check.Refactor.ABCSize},
{Credo.Check.Refactor.CondStatements},
{Credo.Check.Refactor.CyclomaticComplexity},
{Credo.Check.Refactor.FunctionArity},
{Credo.Check.Refactor.MatchInCondition},
{Credo.Check.Refactor.NegatedConditionsInUnless},
{Credo.Check.Refactor.NegatedConditionsWithElse},
{Credo.Check.Refactor.Nesting},
{Credo.Check.Refactor.PipeChainStart, false},
{Credo.Check.Refactor.UnlessWithElse},
{Credo.Check.Refactor.VariableRebinding},
{Credo.Check.Warning.BoolOperationOnSameValues},
{Credo.Check.Warning.IExPry},
{Credo.Check.Warning.IoInspect},
{Credo.Check.Warning.NameRedeclarationByAssignment},
{Credo.Check.Warning.NameRedeclarationByCase},
{Credo.Check.Warning.NameRedeclarationByDef},
{Credo.Check.Warning.NameRedeclarationByFn},
{Credo.Check.Warning.OperationOnSameValues},
{Credo.Check.Warning.OperationWithConstantResult},
{Credo.Check.Warning.UnusedEnumOperation},
{Credo.Check.Warning.UnusedFileOperation},
{Credo.Check.Warning.UnusedKeywordOperation},
{Credo.Check.Warning.UnusedListOperation},
{Credo.Check.Warning.UnusedPathOperation},
{Credo.Check.Warning.UnusedRegexOperation},
{Credo.Check.Warning.UnusedStringOperation},
{Credo.Check.Warning.UnusedTupleOperation},
# Custom checks can be created using `mix credo.gen.check`.
#
]
}
]
}
| 41.869231 | 80 | 0.661584 |
1ceecc07e579c4727e19cd7b6cb8beb8f1c36894 | 473 | exs | Elixir | config/test.exs | nullpilot/pawmon | 00623bf1cd2ca126af385bf0c81e5fe3afca11a3 | [
"MIT"
] | null | null | null | config/test.exs | nullpilot/pawmon | 00623bf1cd2ca126af385bf0c81e5fe3afca11a3 | [
"MIT"
] | null | null | null | config/test.exs | nullpilot/pawmon | 00623bf1cd2ca126af385bf0c81e5fe3afca11a3 | [
"MIT"
] | null | null | null | import Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :paw_mon, PawMonWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "datvNyHnrOZD5UUISOL1dE69JUiWvzBVfjXXgXeaJe1100sTEG9Mlka385HCZQ+l",
server: false
# Print only warnings and errors during test
config :logger, level: :warn
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime
| 31.533333 | 86 | 0.767442 |
1cef333b68b20edb15316428de6cf354ad3518f4 | 73 | exs | Elixir | v02/ch02/struct2.edit0.exs | oiax/elixir-primer | c8b89a29f108cc335b8e1341b7a1e90ec12adc66 | [
"MIT"
] | null | null | null | v02/ch02/struct2.edit0.exs | oiax/elixir-primer | c8b89a29f108cc335b8e1341b7a1e90ec12adc66 | [
"MIT"
] | null | null | null | v02/ch02/struct2.edit0.exs | oiax/elixir-primer | c8b89a29f108cc335b8e1341b7a1e90ec12adc66 | [
"MIT"
] | null | null | null | u = %User{email: "foo@example.com"}
IO.inspect u.name
IO.inspect u.email
| 18.25 | 35 | 0.712329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.