hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
032ee48b21172b46a60a3cddba2738ea9f1bbd24 | 522 | ex | Elixir | lib/parameters/params_node.ex | imranismail/parameters | 9de14c32a007d8ddd01685678ba81e0fdb1f7fb9 | [
"MIT"
] | 13 | 2019-04-23T04:22:49.000Z | 2021-12-17T10:38:12.000Z | lib/parameters/params_node.ex | imranismail/parameters | 9de14c32a007d8ddd01685678ba81e0fdb1f7fb9 | [
"MIT"
] | 2 | 2019-07-07T13:59:45.000Z | 2019-07-07T14:02:34.000Z | lib/parameters/params_node.ex | imranismail/parameters | 9de14c32a007d8ddd01685678ba81e0fdb1f7fb9 | [
"MIT"
] | null | null | null | defmodule Parameters.ParamsNode do
defstruct [
:id,
fields: []
]
def parse(name, {:__block__, _metadata, ast}), do: parse(name, ast)
def parse(name, ast) when is_tuple(ast), do: parse(name, [ast])
def parse(name, ast) when is_list(ast) do
Enum.reduce(ast, struct(__MODULE__), fn field, schema ->
Map.update!(schema, :fields, fn fields ->
[Parameters.FieldNode.parse(field) | fields]
end)
end)
|> Map.put(:id, name)
|> Map.update!(:fields, &Enum.reverse/1)
end
end
| 26.1 | 69 | 0.626437 |
032f178d247f8341129ad9725464893268376c5f | 1,417 | exs | Elixir | test/sealax_web/controllers/workspace_controller_test.exs | sealas/sealax | 3f11b7f649972a43f4812ea959bd2be2e0151baa | [
"MIT"
] | null | null | null | test/sealax_web/controllers/workspace_controller_test.exs | sealas/sealax | 3f11b7f649972a43f4812ea959bd2be2e0151baa | [
"MIT"
] | 9 | 2021-08-19T01:09:55.000Z | 2022-03-08T01:18:45.000Z | test/sealax_web/controllers/workspace_controller_test.exs | sealas/sealax | 3f11b7f649972a43f4812ea959bd2be2e0151baa | [
"MIT"
] | null | null | null | defmodule Sealax.WorkspaceControllerTest do
use SealaxWeb.ConnCase
alias Sealax.Accounts.Workspace
alias Sealax.Accounts.UserWorkspace
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
describe "workspace actions" do
@describetag setup: true, create_user: true, auth_user: true
test "workspace flow", %{conn: conn} do
conn = post conn, Routes.workspace_path(conn, :create), %{name: "Encrypted Workspace Name Goes Here", appkey: "encrypted_appkey", appkey_salt: "salty_salt"}
assert auth = json_response(conn, 201)
conn = get conn, Routes.workspace_path(conn, :index)
assert %{"workspaces" => workspaces} = json_response(conn, 200)
assert length(workspaces) == 1
end
test "updating workspaces", %{conn: conn, user: user} do
{:ok, %{user: other_user}} = TestData.create_user({:ok, %{}}, %{:create_user => true}, %{email: "[email protected]", password: "pewpew"})
{:ok, workspace} = Workspace.create(%{name: "Pew", owner_id: other_user.id})
conn = put conn, Routes.workspace_path(conn, :update, workspace.id), %{name: "new name"}
assert json_response(conn, 400)
{:ok, workspace} = Workspace.create(%{name: "Pew", owner_id: user.id})
conn = put conn, Routes.workspace_path(conn, :update, workspace.id), %{name: "new name"}
assert json_response(conn, 200)
end
end
end
| 38.297297 | 162 | 0.671842 |
032f4a14b31c0cb4ec9086ee52903c8fa72c846e | 570 | exs | Elixir | test/concentrate/health_test.exs | paulswartz/concentrate | a69aa51c16071f2669932005be810da198f622c8 | [
"MIT"
] | 19 | 2018-01-22T18:39:20.000Z | 2022-02-22T16:15:30.000Z | test/concentrate/health_test.exs | mbta/concentrate | bae6e05713ed079b7da53867a01dd007861fb656 | [
"MIT"
] | 216 | 2018-01-22T14:22:39.000Z | 2022-03-31T10:30:31.000Z | test/concentrate/health_test.exs | paulswartz/concentrate | a69aa51c16071f2669932005be810da198f622c8 | [
"MIT"
] | 5 | 2018-01-22T14:18:15.000Z | 2021-04-26T18:34:19.000Z | defmodule Concentrate.HealthTest do
use ExUnit.Case
import ExUnit.CaptureLog
import Concentrate.Health
describe "healthy?" do
test "crashes by default" do
healthy?(:health_false)
assert false
catch
:exit, _ ->
true
end
test "true when the server is running" do
{:ok, pid} = start_link([])
assert healthy?(pid)
end
test "logs a message" do
{:ok, pid} = start_link([])
log =
capture_log(fn ->
healthy?(pid)
end)
assert log =~ "Health"
end
end
end
| 17.8125 | 45 | 0.575439 |
032f4d328971ad0447c29144df2f5d68fc039ca7 | 3,153 | ex | Elixir | lib/grizzly/command_class/association/set.ex | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | lib/grizzly/command_class/association/set.ex | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | lib/grizzly/command_class/association/set.ex | pragdave/grizzly | bcd7b46ab2cff1797dac04bc3cd12a36209dd579 | [
"Apache-2.0"
] | null | null | null | defmodule Grizzly.CommandClass.Association.Set do
@moduledoc """
Command for working with Association command class SET command
Command Options:
* `:group` - The association group
* `:nodes` - List of node ids to receive messages about node events
* `:seq_number` - The sequence number used in the Z/IP packet
* `:retries` - The number of attempts to send the command (default 2)
"""
@behaviour Grizzly.Command
alias Grizzly.{Node, Packet}
alias Grizzly.Command.{EncodeError, Encoding}
alias Grizzly.Network.State, as: NetworkState
@type t :: %__MODULE__{
group: byte,
nodes: associated_nodes,
seq_number: Grizzly.seq_number(),
retries: non_neg_integer(),
exec_state: NetworkState.state() | nil,
pre_states: [NetworkState.state()]
}
@type associated_nodes :: [Node.node_id()]
@type opts ::
{:group, byte}
| {:nodes, associated_nodes}
| {:seq_number, Grizzly.seq_number()}
| {:retries, non_neg_integer()}
| {:pre_states, [NetworkState.state()]}
| {:exec_state, NetworkState.state()}
defstruct group: nil,
nodes: nil,
seq_number: nil,
retries: 2,
exec_state: nil,
pre_states: [:not_ready, :idle]
@spec init([opts]) :: {:ok, t}
def init(opts) do
{:ok, struct(__MODULE__, opts)}
end
@spec encode(t) :: {:ok, binary} | {:error, EncodeError.t()}
def encode(%__MODULE__{group: group, nodes: nodes, seq_number: seq_number} = command) do
with {:ok, _} <- Encoding.encode_and_validate_args(command, %{group: :byte, nodes: [:byte]}) do
binary = Packet.header(seq_number) <> <<0x85, 0x01, group>> <> :erlang.list_to_binary(nodes)
{:ok, binary}
end
end
@spec handle_response(t, Packet.t()) ::
{:continue, t()}
| {:done, {:error, :nack_response}}
| {:done, :ok}
| {:retry, t()}
| {:queued, t()}
def handle_response(
%__MODULE__{seq_number: seq_number},
%Packet{
seq_number: seq_number,
types: [:ack_response]
}
) do
{:done, :ok}
end
def handle_response(
%__MODULE__{seq_number: seq_number, retries: 0},
%Packet{
seq_number: seq_number,
types: [:nack_response]
}
) do
{:done, {:error, :nack_response}}
end
def handle_response(
%__MODULE__{seq_number: seq_number, retries: n} = command,
%Packet{
seq_number: seq_number,
types: [:nack_response]
}
) do
{:retry, %{command | retries: n - 1}}
end
def handle_response(
%__MODULE__{seq_number: seq_number} = command,
%Packet{
seq_number: seq_number,
types: [:nack_response, :nack_waiting]
} = packet
) do
netstate = Grizzly.Network.get_state()
if Packet.sleeping_delay?(packet) && netstate != :configurating_new_node do
{:queued, command}
else
{:continue, command}
end
end
def handle_response(command, _), do: {:continue, command}
end
| 28.151786 | 99 | 0.587377 |
032f5adfc56f12e4f2d8128a47a4d44da0eb8b4d | 2,308 | ex | Elixir | clients/cloud_support/lib/google_api/cloud_support/v2beta/model/actor.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/cloud_support/lib/google_api/cloud_support/v2beta/model/actor.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/cloud_support/lib/google_api/cloud_support/v2beta/model/actor.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudSupport.V2beta.Model.Actor do
@moduledoc """
An object containing information about the effective user and authenticated principal responsible for an action.
## Attributes
* `displayName` (*type:* `String.t`, *default:* `nil`) - The name to display for the actor. If not provided, it is inferred from credentials supplied during case creation. When an email is provided, a display name must also be provided. This will be obfuscated if the user is a Google Support agent.
* `email` (*type:* `String.t`, *default:* `nil`) - The email address of the actor. If not provided, it is inferred from credentials supplied during case creation. If the authenticated principal does not have an email address, one must be provided. When a name is provided, an email must also be provided. This will be obfuscated if the user is a Google Support agent.
* `googleSupport` (*type:* `boolean()`, *default:* `nil`) - Output only. Whether the actor is a Google support actor.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:displayName => String.t() | nil,
:email => String.t() | nil,
:googleSupport => boolean() | nil
}
field(:displayName)
field(:email)
field(:googleSupport)
end
defimpl Poison.Decoder, for: GoogleApi.CloudSupport.V2beta.Model.Actor do
def decode(value, options) do
GoogleApi.CloudSupport.V2beta.Model.Actor.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudSupport.V2beta.Model.Actor do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.54717 | 371 | 0.733102 |
032f605461c638d31161a5ae4e1f5353123e5d68 | 1,931 | ex | Elixir | clients/gmail/lib/google_api/gmail/v1/model/filter.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/gmail/lib/google_api/gmail/v1/model/filter.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/gmail/lib/google_api/gmail/v1/model/filter.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.Gmail.V1.Model.Filter do
@moduledoc """
Resource definition for Gmail filters. Filters apply to specific messages instead of an entire email thread.
## Attributes
* `action` (*type:* `GoogleApi.Gmail.V1.Model.FilterAction.t`, *default:* `nil`) - Action that the filter performs.
* `criteria` (*type:* `GoogleApi.Gmail.V1.Model.FilterCriteria.t`, *default:* `nil`) - Matching criteria for the filter.
* `id` (*type:* `String.t`, *default:* `nil`) - The server assigned ID of the filter.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:action => GoogleApi.Gmail.V1.Model.FilterAction.t(),
:criteria => GoogleApi.Gmail.V1.Model.FilterCriteria.t(),
:id => String.t()
}
field(:action, as: GoogleApi.Gmail.V1.Model.FilterAction)
field(:criteria, as: GoogleApi.Gmail.V1.Model.FilterCriteria)
field(:id)
end
defimpl Poison.Decoder, for: GoogleApi.Gmail.V1.Model.Filter do
def decode(value, options) do
GoogleApi.Gmail.V1.Model.Filter.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Gmail.V1.Model.Filter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.433962 | 124 | 0.719834 |
032f685406a30d9dee51c1b9b5512b7f3ac5397f | 2,250 | ex | Elixir | lib/cforum_web/controllers/messages/accept_controller.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 16 | 2019-04-04T06:33:33.000Z | 2021-08-16T19:34:31.000Z | lib/cforum_web/controllers/messages/accept_controller.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 294 | 2019-02-10T11:10:27.000Z | 2022-03-30T04:52:53.000Z | lib/cforum_web/controllers/messages/accept_controller.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 10 | 2019-02-10T10:39:24.000Z | 2021-07-06T11:46:05.000Z | defmodule CforumWeb.Messages.AcceptController do
use CforumWeb, :controller
alias Cforum.Abilities
alias Cforum.Threads
alias Cforum.Threads.ThreadHelpers
alias Cforum.Messages
alias Cforum.Messages.MessageHelpers
alias Cforum.ConfigManager
alias Cforum.Helpers
alias CforumWeb.Views.ViewHelpers.ReturnUrl
def accept(conn, params) do
accept_value = ConfigManager.conf(conn, "accept_value", :int)
Messages.accept_message(conn.assigns.message, conn.assigns.current_user, accept_value)
conn
|> put_flash(:info, gettext("Message has successfully been accepted as a solving answer"))
|> redirect(to: ReturnUrl.return_path(conn, params, conn.assigns.thread, conn.assigns.message))
end
def unaccept(conn, params) do
Messages.unaccept_message(conn.assigns.message, conn.assigns.current_user)
conn
|> put_flash(:info, gettext("Message has successfully been unaccepted as a solving answer"))
|> redirect(to: ReturnUrl.return_path(conn, params, conn.assigns.thread, conn.assigns.message))
end
def load_resource(conn) do
thread =
conn.assigns[:current_forum]
|> Threads.get_thread_by_slug!(nil, ThreadHelpers.slug_from_params(conn.params))
|> Threads.reject_deleted_threads(conn.assigns[:view_all])
|> Threads.build_message_tree(ConfigManager.uconf(conn, "sort_messages"))
message = Messages.get_message_from_mid!(thread, conn.params["mid"])
conn
|> Plug.Conn.assign(:thread, thread)
|> Plug.Conn.assign(:message, message)
end
def allowed?(conn, :accept, resource) do
{thread, message} =
case resource do
{thread, message} -> {thread, message}
_ -> {conn.assigns.thread, conn.assigns.message}
end
Helpers.present?(message.parent_id) && Abilities.accept?(conn, thread.message) && !MessageHelpers.accepted?(message) &&
!thread.archived
end
def allowed?(conn, :unaccept, resource) do
{thread, message} =
case resource do
{thread, message} -> {thread, message}
_ -> {conn.assigns.thread, conn.assigns.message}
end
Abilities.accept?(conn, thread.message) && MessageHelpers.accepted?(message) && !thread.archived
end
def allowed?(_, _, _), do: false
end
| 32.142857 | 123 | 0.712444 |
032f68e90127e13028784da4476429c78d2a3c0c | 1,081 | ex | Elixir | lib/geometry/wkt.ex | hrzndhrn/geometry | bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60 | [
"MIT"
] | null | null | null | lib/geometry/wkt.ex | hrzndhrn/geometry | bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60 | [
"MIT"
] | 2 | 2020-10-25T10:06:07.000Z | 2020-10-26T18:15:20.000Z | lib/geometry/wkt.ex | hrzndhrn/geometry | bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60 | [
"MIT"
] | null | null | null | defmodule Geometry.WKT do
@moduledoc false
alias Geometry.WKT.Parser
@spec to_ewkt(String.t(), keyword()) :: String.t()
def to_ewkt(wkt, []), do: wkt
def to_ewkt(wkt, opts) when is_list(opts) do
opts
|> Keyword.get(:srid)
|> ewkt(wkt)
end
@spec to_geometry(Geometry.wkt(), module()) ::
{:ok, Geometry.t()} | {Geometry.t(), Geometry.srid()} | Geometry.wkt_error()
def to_geometry(wkt, module) do
case to_geometry(wkt) do
{:ok, {geometry, _srid}} = result ->
with :ok <- check_geometry(geometry, module), do: result
{:ok, geometry} = result ->
with :ok <- check_geometry(geometry, module), do: result
error ->
error
end
end
defdelegate to_geometry(wkt), to: Parser, as: :parse
defp ewkt(nil, wkt), do: wkt
defp ewkt(srid, wkt) when is_integer(srid),
do: <<"SRID=", to_string(srid)::binary(), ";", wkt::binary>>
defp check_geometry(%geometry{}, geometry), do: :ok
defp check_geometry(%{__struct__: got}, expected),
do: {:error, %{expected: expected, got: got}}
end
| 25.738095 | 86 | 0.617946 |
032f7b47040355b47bbc6c8800b2795220cc1306 | 466 | ex | Elixir | lib/page_object.ex | hidnasio/page_object | 57548eeb69405d56cc32d8a416fca1743b1b4f16 | [
"MIT"
] | null | null | null | lib/page_object.ex | hidnasio/page_object | 57548eeb69405d56cc32d8a416fca1743b1b4f16 | [
"MIT"
] | null | null | null | lib/page_object.ex | hidnasio/page_object | 57548eeb69405d56cc32d8a416fca1743b1b4f16 | [
"MIT"
] | null | null | null | defmodule PageObject do
@moduledoc """
PageObject wraps all the available macros and is the target module you should `use` in your PageObject module.
"""
defmacro __using__(_opts) do
quote do
use Hound.Helpers
import PageObject
import PageObject.Collections.Collection
import PageObject.Actions.{Visitable, Clickable, Fillable, Selectable}
import PageObject.Queries.{Attribute, IsPresent, Text, Value}
end
end
end
| 27.411765 | 114 | 0.723176 |
032f7e66346f672fbee5c142b60de5cc90fd1d8b | 1,456 | exs | Elixir | server/test/realtime_web/channels/user_socket_test.exs | gustavoarmoa/realtime | e8075779ed19bfb8c22541dc1e5e8ea032d5b823 | [
"Apache-2.0"
] | 4,609 | 2019-10-25T12:28:35.000Z | 2022-03-31T23:05:06.000Z | server/test/realtime_web/channels/user_socket_test.exs | gustavoarmoa/realtime | e8075779ed19bfb8c22541dc1e5e8ea032d5b823 | [
"Apache-2.0"
] | 223 | 2019-09-27T03:21:45.000Z | 2022-03-29T23:04:03.000Z | server/test/realtime_web/channels/user_socket_test.exs | gustavoarmoa/realtime | e8075779ed19bfb8c22541dc1e5e8ea032d5b823 | [
"Apache-2.0"
] | 187 | 2019-10-27T07:44:15.000Z | 2022-03-29T19:34:52.000Z | defmodule RealtimeWeb.UserSocketTest do
use RealtimeWeb.ChannelCase
import Mock
alias Phoenix.Socket
alias RealtimeWeb.{UserSocket, ChannelsAuthorization}
test "connect/2 when :secure_channels config is false" do
Application.put_env(:realtime, :secure_channels, false)
assert {:ok, %Socket{}} = UserSocket.connect(%{}, socket(UserSocket))
end
test "connect/2 when :secure_channels config is true and token is authorized" do
with_mock ChannelsAuthorization, authorize: fn _token -> {:ok, %{}} end do
Application.put_env(:realtime, :secure_channels, true)
# WARNING: "token" param key will be deprecated.
assert {:ok, %Socket{}} =
UserSocket.connect(%{"token" => "auth_token123"}, socket(UserSocket))
assert {:ok, %Socket{}} =
UserSocket.connect(%{"apikey" => "auth_token123"}, socket(UserSocket))
end
end
test "connect/2 when :secure_channels config is true and token is unauthorized" do
with_mock ChannelsAuthorization, authorize: fn _token -> {:error, "unauthorized"} end do
Application.put_env(:realtime, :secure_channels, true)
assert :error = UserSocket.connect(%{"token" => "bad_token9"}, socket(UserSocket))
end
end
test "connect/2 when :secure_channels config is true and token is missing" do
Application.put_env(:realtime, :secure_channels, true)
assert :error = UserSocket.connect(%{}, socket(UserSocket))
end
end
| 34.666667 | 92 | 0.699176 |
032f84582884b5152b796f79d390073f65168242 | 1,080 | ex | Elixir | lib/room/room.ex | henriquetorquato/hermes | 6d98ecdffd6486c1f64e8e0c5827fd512c719296 | [
"MIT"
] | null | null | null | lib/room/room.ex | henriquetorquato/hermes | 6d98ecdffd6486c1f64e8e0c5827fd512c719296 | [
"MIT"
] | null | null | null | lib/room/room.ex | henriquetorquato/hermes | 6d98ecdffd6486c1f64e8e0c5827fd512c719296 | [
"MIT"
] | null | null | null | defmodule Room do
use Agent
def init(_args) do
[]
end
def start_link(name) do
Agent.start_link __MODULE__, :init, [name], name: String.to_atom name
end
def join(pid, node, username) do
Node.connect node
Agent.update pid, fn users -> [{username, node} | users] end
broadcast pid, %Message{
type: "info",
content: "User '#{username}' joined!",
originator: username
}
end
def broadcast(pid, message) do
users = not_user message.originator, get_users pid
case message.type do
"message" ->
broadcast pid, message, users
"info" ->
broadcast pid, message, users
end
end
def broadcast(_pid, message, users) do
Enum.each users, fn {_username, node} ->
send_message node, message
end
end
defp get_users(pid) do
Agent.get pid, fn users -> users end
end
defp not_user(username, users) do
Enum.filter users, fn {name, _node} -> username != name end
end
defp send_message(node, message) do
send {:receiver, node}, {:message, message}
end
end
| 20.769231 | 73 | 0.636111 |
032fad94247b616bbbd4c26ae99130972eb9d7e8 | 1,027 | exs | Elixir | elixir-generate-dockerfile/src/test/app_config/phoenix_1_2/mix.exs | kayodeosagbemi/elixir-runtime | 1746adf362444e3e0cc2daa5e461be24f1cb624a | [
"Apache-2.0"
] | 170 | 2017-08-25T06:40:14.000Z | 2022-01-10T22:18:51.000Z | elixir-generate-dockerfile/src/test/app_config/phoenix_1_2/mix.exs | kayodeosagbemi/elixir-runtime | 1746adf362444e3e0cc2daa5e461be24f1cb624a | [
"Apache-2.0"
] | 27 | 2017-09-07T05:57:37.000Z | 2022-03-22T13:40:47.000Z | elixir-generate-dockerfile/src/test/app_config/phoenix_1_2/mix.exs | kayodeosagbemi/elixir-runtime | 1746adf362444e3e0cc2daa5e461be24f1cb624a | [
"Apache-2.0"
] | 16 | 2017-11-14T01:45:00.000Z | 2021-10-09T03:26:39.000Z | defmodule Blog.Mixfile do
use Mix.Project
def project do
[
app: :blog,
version: "0.0.1",
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Blog.Application, []},
extra_applications: [: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
[
{:phoenix, "1.2.5"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"}
]
end
end
| 23.340909 | 57 | 0.578384 |
032fbb3bf47df877dcd5536ca25e1f04228ea841 | 489 | exs | Elixir | test/functional/parser/whitespace_test.exs | RobertDober/earmark | 6f20bd06f40e4333294d19eb38031ea480f3d3ba | [
"Apache-2.0"
] | null | null | null | test/functional/parser/whitespace_test.exs | RobertDober/earmark | 6f20bd06f40e4333294d19eb38031ea480f3d3ba | [
"Apache-2.0"
] | null | null | null | test/functional/parser/whitespace_test.exs | RobertDober/earmark | 6f20bd06f40e4333294d19eb38031ea480f3d3ba | [
"Apache-2.0"
] | 1 | 2020-09-15T17:47:35.000Z | 2020-09-15T17:47:35.000Z | defmodule Parser.WhitespaceTest do
use ExUnit.Case
alias Earmark.Parser
alias Earmark.Block
test "Whitespace before and after code is ignored" do
{result, _, _} = Parser.parse(["",
" line 1",
" line 2",
"",
"",
"para"])
expected = [
%Block.Code{lnb: 2, attrs: nil,
language: nil,
lines: ["line 1", "line 2"]},
%Block.Para{lnb: 6, attrs: nil, lines: ["para"]}
]
assert result == expected
end
end
| 19.56 | 55 | 0.543967 |
032fd5856d116a6c967f65a330e85e0576da87be | 1,995 | exs | Elixir | test/changelog/schema/news/news_item_comment_test.exs | d-m-u/changelog.com | bb0d6ac6d29a3d64dbeb44892f9a8a1ff3ba6325 | [
"MIT"
] | null | null | null | test/changelog/schema/news/news_item_comment_test.exs | d-m-u/changelog.com | bb0d6ac6d29a3d64dbeb44892f9a8a1ff3ba6325 | [
"MIT"
] | null | null | null | test/changelog/schema/news/news_item_comment_test.exs | d-m-u/changelog.com | bb0d6ac6d29a3d64dbeb44892f9a8a1ff3ba6325 | [
"MIT"
] | null | null | null | defmodule Changelog.NewsItemCommentTest do
use Changelog.SchemaCase
alias Changelog.NewsItemComment
describe "insert_changeset" do
test "with valid attributes" do
changeset =
NewsItemComment.insert_changeset(%NewsItemComment{}, %{
content: "ohai",
item_id: 1,
author_id: 2
})
assert changeset.valid?
end
test "with invalid attributes" do
changeset = NewsItemComment.insert_changeset(%NewsItemComment{}, %{content: "ohnoes"})
refute changeset.valid?
end
end
describe "mentioned_people/1" do
test "returns an empty list when there aren't any mentions" do
comment = build(:news_item_comment, content: "zomg this is rad")
assert NewsItemComment.mentioned_people(comment) == []
end
test "also works directly with comment content" do
assert NewsItemComment.mentioned_people("zomg this is rad") == []
end
test "returns one person when they are mentioned" do
person = insert(:person, handle: "joedev")
comment = build(:news_item_comment, content: "zomg @joedev this is rad")
assert NewsItemComment.mentioned_people(comment) == [person]
end
test "returns many people when they are mentioned" do
p1 = insert(:person, handle: "joedev")
p2 = insert(:person, handle: "janedev")
p3 = insert(:person, handle: "alicedev")
comment =
build(:news_item_comment, content: "zomg @joedev & @janedev this is rad @alicedev!")
assert NewsItemComment.mentioned_people(comment) == [p1, p2, p3]
end
end
describe "nested/1" do
test "nests comments appropriately" do
parent = %NewsItemComment{id: 1, parent_id: nil, content: "ohai", approved: true}
reply = %NewsItemComment{id: 2, parent_id: 1, content: "bai now", approved: true}
nested = NewsItemComment.nested([reply, parent])
assert length(nested) == 1
assert length(List.first(nested).children) == 1
end
end
end
| 31.171875 | 92 | 0.66817 |
032fe3a2d8bab7b9463624827b2d351ee0578d63 | 2,210 | ex | Elixir | clients/recommendation_engine/lib/google_api/recommendation_engine/v1beta1/model/google_cloud_recommendationengine_v1beta1_create_prediction_api_key_registration_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/recommendation_engine/lib/google_api/recommendation_engine/v1beta1/model/google_cloud_recommendationengine_v1beta1_create_prediction_api_key_registration_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/recommendation_engine/lib/google_api/recommendation_engine/v1beta1/model/google_cloud_recommendationengine_v1beta1_create_prediction_api_key_registration_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.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest do
@moduledoc """
Request message for the `CreatePredictionApiKeyRegistration` method.
## Attributes
* `predictionApiKeyRegistration` (*type:* `GoogleApi.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration.t`, *default:* `nil`) - Required. The prediction API key registration.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:predictionApiKeyRegistration =>
GoogleApi.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration.t()
}
field(:predictionApiKeyRegistration,
as:
GoogleApi.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1PredictionApiKeyRegistration
)
end
defimpl Poison.Decoder,
for:
GoogleApi.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest do
def decode(value, options) do
GoogleApi.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.RecommendationEngine.V1beta1.Model.GoogleCloudRecommendationengineV1beta1CreatePredictionApiKeyRegistrationRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.103448 | 229 | 0.798643 |
032ff23955d2f143fa9629dc2794847a24e5e9dc | 965 | ex | Elixir | lib/ex/application.ex | ykurtbas/kitchensink | 01603ede591a72d0eeb1b8d7091eb4520bd666f6 | [
"BSD-3-Clause"
] | 4 | 2021-03-22T17:31:03.000Z | 2021-04-09T07:03:25.000Z | lib/ex/application.ex | ykurtbas/kitchensink | 01603ede591a72d0eeb1b8d7091eb4520bd666f6 | [
"BSD-3-Clause"
] | null | null | null | lib/ex/application.ex | ykurtbas/kitchensink | 01603ede591a72d0eeb1b8d7091eb4520bd666f6 | [
"BSD-3-Clause"
] | 1 | 2021-04-19T01:52:47.000Z | 2021-04-19T01:52:47.000Z | defmodule Ex.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
children = [
# Start the Ecto repository
Ex.Repo,
# Start the Telemetry supervisor
ExWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: Ex.PubSub},
# Start the Endpoint (http/https)
ExWeb.Endpoint
# Start a worker by calling: Ex.Worker.start_link(arg)
# {Ex.Worker, arg}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Ex.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
ExWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 27.571429 | 60 | 0.688083 |
033026ed1a659a80fb52d29ffe31c4dfeaf8f514 | 4,966 | ex | Elixir | lib/jaxon/decoder.ex | suexcxine/jaxon | fb638f76945236822e8e015ee4b4d79b8255b71e | [
"Apache-2.0"
] | null | null | null | lib/jaxon/decoder.ex | suexcxine/jaxon | fb638f76945236822e8e015ee4b4d79b8255b71e | [
"Apache-2.0"
] | null | null | null | lib/jaxon/decoder.ex | suexcxine/jaxon | fb638f76945236822e8e015ee4b4d79b8255b71e | [
"Apache-2.0"
] | 1 | 2020-01-29T01:50:12.000Z | 2020-01-29T01:50:12.000Z | defmodule Jaxon.Decoder do
alias Jaxon.{ParseError}
@moduledoc false
@type json_term() ::
nil
| true
| false
| list
| float
| integer
| String.t()
| map
| [json_term()]
@doc """
Takes a list of events and decodes them into a term.
"""
@spec events_to_term([Jaxon.Event.t()]) :: json_term()
def events_to_term(events) do
events
|> events_to_value()
|> do_events_to_term()
end
defp do_events_to_term(result) do
case result do
{:ok, term, [:end_stream]} ->
{:ok, term}
{:ok, term, []} ->
{:ok, term}
{:ok, _, [event | _]} ->
parse_error(event, [:end_stream])
{:yield, tail, fun} ->
{:yield, tail,
fn next ->
do_events_to_term(fun.(next))
end}
{:error, err} ->
{:error, err}
end
end
def events_to_value([:start_object | events]) do
events_to_object(events, %{})
end
def events_to_value([:start_array | events]) do
events_to_array(events, [])
end
def events_to_value([{event, value} | events])
when event in [:string, :decimal, :integer, :boolean] do
{:ok, value, events}
end
def events_to_value([nil | events]) do
{:ok, nil, events}
end
def events_to_value([{:incomplete, {:decimal, value}, _}, :end_stream]) do
{:ok, value, [:end_stream]}
end
def events_to_value([{:incomplete, {:integer, value}, _}, :end_stream]) do
{:ok, value, [:end_stream]}
end
def events_to_value([{:incomplete, {:decimal, _}, tail}]) do
{:yield, tail, &events_to_value(&1)}
end
def events_to_value([{:incomplete, {:integer, _}, tail}]) do
{:yield, tail, &events_to_value(&1)}
end
def events_to_value([{:incomplete, tail}]) do
{:yield, tail, &events_to_value(&1)}
end
def events_to_value([]) do
{:yield, "", &events_to_value(&1)}
end
def events_to_value([{:incomplete, _}, :end_stream]) do
parse_error(:end_stream, [:value])
end
def events_to_value([event | _]) do
parse_error(event, [:value])
end
defp parse_error(got, expected) do
{:error,
%ParseError{
unexpected: got,
expected: expected
}}
end
def events_expect([event | events], event, state) do
{:ok, events, state}
end
def events_expect([{event, _} | _], expected, _) do
parse_error(event, [expected])
end
def events_expect([event | _], expected, _) do
parse_error(event, [expected])
end
defp events_to_array([:end_array | events], array) do
{:ok, array, events}
end
defp events_to_array([:comma | events], array = [_ | _]) do
events_to_value(events)
|> add_value_to_array(array)
end
defp events_to_array([], array) do
{:yield, "", &events_to_array(&1, array)}
end
defp events_to_array(events, array = []) do
events_to_value(events)
|> add_value_to_array(array)
end
defp events_to_array([event | _], _) do
parse_error(event, [:comma, :end_array])
end
defp add_value_to_array({:ok, value, rest}, array) do
events_to_array(rest, array ++ [value])
end
defp add_value_to_array(t = {:yield, _, inner}, array) do
:erlang.setelement(3, t, fn next ->
add_value_to_array(inner.(next), array)
end)
end
defp add_value_to_array(result, _) do
result
end
defp add_value_to_object({:ok, value, rest}, key, object) do
events_to_object(rest, Map.put(object, key, value))
end
defp add_value_to_object(t = {:yield, _, inner}, key, object) do
:erlang.setelement(3, t, fn next ->
add_value_to_object(inner.(next), key, object)
end)
end
defp add_value_to_object(result, _, _) do
result
end
defp events_to_object_key_value([{:incomplete, tail}], object) do
{:yield, tail, &events_to_object_key_value(&1, object)}
end
defp events_to_object_key_value([{:string, key}], object) do
{:yield, "", &events_to_object_key_value([{:string, key} | &1], object)}
end
defp events_to_object_key_value([{:string, key} | rest], object) do
with {:ok, rest, object} <- events_expect(rest, :colon, object) do
add_value_to_object(events_to_value(rest), key, object)
end
end
defp events_to_object_key_value([], object) do
{:yield, "", &events_to_object_key_value(&1, object)}
end
defp events_to_object_key_value([event | _], _) do
parse_error(event, [:key])
end
defp events_to_object([:comma | events], object) when map_size(object) > 0 do
events_to_object_key_value(events, object)
end
defp events_to_object([:end_object | events], object) do
{:ok, object, events}
end
defp events_to_object([], object) do
{:yield, "", &events_to_object(&1, object)}
end
defp events_to_object(events, object = %{}) do
events_to_object_key_value(events, object)
end
defp events_to_object([event | _], _) do
parse_error(event, [:key, :end_object, :comma])
end
end
| 23.990338 | 79 | 0.627064 |
03302e619d49b5880523e59a8ba39bd611855798 | 21,500 | ex | Elixir | lib/aws/generated/app_stream.ex | andrewhr/aws-elixir | 861dc2fafca50a2b2f83badba4cdcb44b5b0c171 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/app_stream.ex | andrewhr/aws-elixir | 861dc2fafca50a2b2f83badba4cdcb44b5b0c171 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/app_stream.ex | andrewhr/aws-elixir | 861dc2fafca50a2b2f83badba4cdcb44b5b0c171 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.AppStream do
@moduledoc """
Amazon AppStream 2.0
This is the *Amazon AppStream 2.0 API Reference*.
This documentation provides descriptions and syntax for each of the actions and
data types in AppStream 2.0. AppStream 2.0 is a fully managed, secure
application streaming service that lets you stream desktop applications to users
without rewriting applications. AppStream 2.0 manages the AWS resources that are
required to host and run your applications, scales automatically, and provides
access to your users on demand.
You can call the AppStream 2.0 API operations by using an interface VPC endpoint
(interface endpoint). For more information, see [Access AppStream 2.0 API Operations and CLI Commands Through an Interface VPC
Endpoint](https://docs.aws.amazon.com/appstream2/latest/developerguide/access-api-cli-through-interface-vpc-endpoint.html)
in the *Amazon AppStream 2.0 Administration Guide*.
To learn more about AppStream 2.0, see the following resources:
* [Amazon AppStream 2.0 product page](http://aws.amazon.com/appstream2)
* [Amazon AppStream 2.0 documentation](http://aws.amazon.com/documentation/appstream2)
"""
alias AWS.Client
alias AWS.Request
def metadata do
%AWS.ServiceMetadata{
abbreviation: nil,
api_version: "2016-12-01",
content_type: "application/x-amz-json-1.1",
credential_scope: nil,
endpoint_prefix: "appstream2",
global?: false,
protocol: "json",
service_id: "AppStream",
signature_version: "v4",
signing_name: "appstream",
target_prefix: "PhotonAdminProxyService"
}
end
@doc """
Associates the specified application with the specified fleet.
This is only supported for Elastic fleets.
"""
def associate_application_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "AssociateApplicationFleet", input, options)
end
@doc """
Associates the specified fleet with the specified stack.
"""
def associate_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "AssociateFleet", input, options)
end
@doc """
Associates the specified users with the specified stacks.
Users in a user pool cannot be assigned to stacks with fleets that are joined to
an Active Directory domain.
"""
def batch_associate_user_stack(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "BatchAssociateUserStack", input, options)
end
@doc """
Disassociates the specified users from the specified stacks.
"""
def batch_disassociate_user_stack(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "BatchDisassociateUserStack", input, options)
end
@doc """
Copies the image within the same region or to a new region within the same AWS
account.
Note that any tags you added to the image will not be copied.
"""
def copy_image(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CopyImage", input, options)
end
@doc """
Creates an app block.
App blocks are an Amazon AppStream 2.0 resource that stores the details about
the virtual hard disk in an S3 bucket. It also stores the setup script with
details about how to mount the virtual hard disk. The virtual hard disk includes
the application binaries and other files necessary to launch your applications.
Multiple applications can be assigned to a single app block.
This is only supported for Elastic fleets.
"""
def create_app_block(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateAppBlock", input, options)
end
@doc """
Creates an application.
Applications are an Amazon AppStream 2.0 resource that stores the details about
how to launch applications on Elastic fleet streaming instances. An application
consists of the launch details, icon, and display name. Applications are
associated with an app block that contains the application binaries and other
files. The applications assigned to an Elastic fleet are the applications users
can launch.
This is only supported for Elastic fleets.
"""
def create_application(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateApplication", input, options)
end
@doc """
Creates a Directory Config object in AppStream 2.0.
This object includes the configuration information required to join fleets and
image builders to Microsoft Active Directory domains.
"""
def create_directory_config(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateDirectoryConfig", input, options)
end
@doc """
Creates a fleet.
A fleet consists of streaming instances that run a specified image when using
Always-On or On-Demand.
"""
def create_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateFleet", input, options)
end
@doc """
Creates an image builder.
An image builder is a virtual machine that is used to create an image.
The initial state of the builder is `PENDING`. When it is ready, the state is
`RUNNING`.
"""
def create_image_builder(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateImageBuilder", input, options)
end
@doc """
Creates a URL to start an image builder streaming session.
"""
def create_image_builder_streaming_url(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateImageBuilderStreamingURL", input, options)
end
@doc """
Creates a stack to start streaming applications to users.
A stack consists of an associated fleet, user access policies, and storage
configurations.
"""
def create_stack(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateStack", input, options)
end
@doc """
Creates a temporary URL to start an AppStream 2.0 streaming session for the
specified user.
A streaming URL enables application streaming to be tested without user setup.
"""
def create_streaming_url(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateStreamingURL", input, options)
end
@doc """
Creates a new image with the latest Windows operating system updates, driver
updates, and AppStream 2.0 agent software.
For more information, see the "Update an Image by Using Managed AppStream 2.0
Image Updates" section in [Administer Your AppStream 2.0 Images](https://docs.aws.amazon.com/appstream2/latest/developerguide/administer-images.html),
in the *Amazon AppStream 2.0 Administration Guide*.
"""
def create_updated_image(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateUpdatedImage", input, options)
end
@doc """
Creates a usage report subscription.
Usage reports are generated daily.
"""
def create_usage_report_subscription(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateUsageReportSubscription", input, options)
end
@doc """
Creates a new user in the user pool.
"""
def create_user(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateUser", input, options)
end
@doc """
Deletes an app block.
"""
def delete_app_block(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteAppBlock", input, options)
end
@doc """
Deletes an application.
"""
def delete_application(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteApplication", input, options)
end
@doc """
Deletes the specified Directory Config object from AppStream 2.0.
This object includes the information required to join streaming instances to an
Active Directory domain.
"""
def delete_directory_config(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteDirectoryConfig", input, options)
end
@doc """
Deletes the specified fleet.
"""
def delete_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteFleet", input, options)
end
@doc """
Deletes the specified image.
You cannot delete an image when it is in use. After you delete an image, you
cannot provision new capacity using the image.
"""
def delete_image(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteImage", input, options)
end
@doc """
Deletes the specified image builder and releases the capacity.
"""
def delete_image_builder(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteImageBuilder", input, options)
end
@doc """
Deletes permissions for the specified private image.
After you delete permissions for an image, AWS accounts to which you previously
granted these permissions can no longer use the image.
"""
def delete_image_permissions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteImagePermissions", input, options)
end
@doc """
Deletes the specified stack.
After the stack is deleted, the application streaming environment provided by
the stack is no longer available to users. Also, any reservations made for
application streaming sessions for the stack are released.
"""
def delete_stack(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteStack", input, options)
end
@doc """
Disables usage report generation.
"""
def delete_usage_report_subscription(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteUsageReportSubscription", input, options)
end
@doc """
Deletes a user from the user pool.
"""
def delete_user(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteUser", input, options)
end
@doc """
Retrieves a list that describes one or more app blocks.
"""
def describe_app_blocks(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeAppBlocks", input, options)
end
@doc """
Retrieves a list that describes one or more application fleet associations.
Either ApplicationArn or FleetName must be specified.
"""
def describe_application_fleet_associations(%Client{} = client, input, options \\ []) do
Request.request_post(
client,
metadata(),
"DescribeApplicationFleetAssociations",
input,
options
)
end
@doc """
Retrieves a list that describes one or more applications.
"""
def describe_applications(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeApplications", input, options)
end
@doc """
Retrieves a list that describes one or more specified Directory Config objects
for AppStream 2.0, if the names for these objects are provided.
Otherwise, all Directory Config objects in the account are described. These
objects include the configuration information required to join fleets and image
builders to Microsoft Active Directory domains.
Although the response syntax in this topic includes the account password, this
password is not returned in the actual response.
"""
def describe_directory_configs(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDirectoryConfigs", input, options)
end
@doc """
Retrieves a list that describes one or more specified fleets, if the fleet names
are provided.
Otherwise, all fleets in the account are described.
"""
def describe_fleets(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeFleets", input, options)
end
@doc """
Retrieves a list that describes one or more specified image builders, if the
image builder names are provided.
Otherwise, all image builders in the account are described.
"""
def describe_image_builders(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeImageBuilders", input, options)
end
@doc """
Retrieves a list that describes the permissions for shared AWS account IDs on a
private image that you own.
"""
def describe_image_permissions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeImagePermissions", input, options)
end
@doc """
Retrieves a list that describes one or more specified images, if the image names
or image ARNs are provided.
Otherwise, all images in the account are described.
"""
def describe_images(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeImages", input, options)
end
@doc """
Retrieves a list that describes the streaming sessions for a specified stack and
fleet.
If a UserId is provided for the stack and fleet, only streaming sessions for
that user are described. If an authentication type is not provided, the default
is to authenticate users using a streaming URL.
"""
def describe_sessions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeSessions", input, options)
end
@doc """
Retrieves a list that describes one or more specified stacks, if the stack names
are provided.
Otherwise, all stacks in the account are described.
"""
def describe_stacks(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeStacks", input, options)
end
@doc """
Retrieves a list that describes one or more usage report subscriptions.
"""
def describe_usage_report_subscriptions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeUsageReportSubscriptions", input, options)
end
@doc """
Retrieves a list that describes the UserStackAssociation objects.
You must specify either or both of the following:
* The stack name
* The user name (email address of the user associated with the
stack) and the authentication type for the user
"""
def describe_user_stack_associations(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeUserStackAssociations", input, options)
end
@doc """
Retrieves a list that describes one or more specified users in the user pool.
"""
def describe_users(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeUsers", input, options)
end
@doc """
Disables the specified user in the user pool.
Users can't sign in to AppStream 2.0 until they are re-enabled. This action does
not delete the user.
"""
def disable_user(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DisableUser", input, options)
end
@doc """
Disassociates the specified application from the fleet.
"""
def disassociate_application_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DisassociateApplicationFleet", input, options)
end
@doc """
Disassociates the specified fleet from the specified stack.
"""
def disassociate_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DisassociateFleet", input, options)
end
@doc """
Enables a user in the user pool.
After being enabled, users can sign in to AppStream 2.0 and open applications
from the stacks to which they are assigned.
"""
def enable_user(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "EnableUser", input, options)
end
@doc """
Immediately stops the specified streaming session.
"""
def expire_session(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ExpireSession", input, options)
end
@doc """
Retrieves the name of the fleet that is associated with the specified stack.
"""
def list_associated_fleets(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListAssociatedFleets", input, options)
end
@doc """
Retrieves the name of the stack with which the specified fleet is associated.
"""
def list_associated_stacks(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListAssociatedStacks", input, options)
end
@doc """
Retrieves a list of all tags for the specified AppStream 2.0 resource.
You can tag AppStream 2.0 image builders, images, fleets, and stacks.
For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html)
in the *Amazon AppStream 2.0 Administration Guide*.
"""
def list_tags_for_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListTagsForResource", input, options)
end
@doc """
Starts the specified fleet.
"""
def start_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "StartFleet", input, options)
end
@doc """
Starts the specified image builder.
"""
def start_image_builder(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "StartImageBuilder", input, options)
end
@doc """
Stops the specified fleet.
"""
def stop_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "StopFleet", input, options)
end
@doc """
Stops the specified image builder.
"""
def stop_image_builder(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "StopImageBuilder", input, options)
end
@doc """
Adds or overwrites one or more tags for the specified AppStream 2.0 resource.
You can tag AppStream 2.0 image builders, images, fleets, and stacks.
Each tag consists of a key and an optional value. If a resource already has a
tag with the same key, this operation updates its value.
To list the current tags for your resources, use `ListTagsForResource`. To
disassociate tags from your resources, use `UntagResource`.
For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html)
in the *Amazon AppStream 2.0 Administration Guide*.
"""
def tag_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "TagResource", input, options)
end
@doc """
Disassociates one or more specified tags from the specified AppStream 2.0
resource.
To list the current tags for your resources, use `ListTagsForResource`.
For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html)
in the *Amazon AppStream 2.0 Administration Guide*.
"""
def untag_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UntagResource", input, options)
end
@doc """
Updates the specified application.
"""
def update_application(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateApplication", input, options)
end
@doc """
Updates the specified Directory Config object in AppStream 2.0.
This object includes the configuration information required to join fleets and
image builders to Microsoft Active Directory domains.
"""
def update_directory_config(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateDirectoryConfig", input, options)
end
@doc """
Updates the specified fleet.
If the fleet is in the `STOPPED` state, you can update any attribute except the
fleet name.
If the fleet is in the `RUNNING` state, you can update the following based on
the fleet type:
* Always-On and On-Demand fleet types
You can update the `DisplayName`, `ComputeCapacity`, `ImageARN`, `ImageName`,
`IdleDisconnectTimeoutInSeconds`, and `DisconnectTimeoutInSeconds` attributes.
* Elastic fleet type
You can update the `DisplayName`, `IdleDisconnectTimeoutInSeconds`,
`DisconnectTimeoutInSeconds`, `MaxConcurrentSessions`, and
`UsbDeviceFilterStrings` attributes.
If the fleet is in the `STARTING` or `STOPPED` state, you can't update it.
"""
def update_fleet(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateFleet", input, options)
end
@doc """
Adds or updates permissions for the specified private image.
"""
def update_image_permissions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateImagePermissions", input, options)
end
@doc """
Updates the specified fields for the specified stack.
"""
def update_stack(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "UpdateStack", input, options)
end
end
| 35.420099 | 152 | 0.717953 |
0330330673c1250b1eb9ed0a853d1acacfa74fd5 | 1,829 | exs | Elixir | play_ui/config/config.exs | axelson/scenic_asteroids | 20fb22af441028b0837016337c5e418c033ded29 | [
"BSD-3-Clause"
] | 31 | 2018-12-25T19:52:35.000Z | 2022-03-20T01:06:46.000Z | play_ui/config/config.exs | axelson/scenic_asteroids | 20fb22af441028b0837016337c5e418c033ded29 | [
"BSD-3-Clause"
] | 4 | 2018-12-23T18:34:20.000Z | 2021-05-10T04:05:45.000Z | play_ui/config/config.exs | axelson/scenic_asteroids | 20fb22af441028b0837016337c5e418c033ded29 | [
"BSD-3-Clause"
] | 2 | 2019-04-09T18:35:51.000Z | 2020-12-22T15:19:18.000Z | use Mix.Config
# Configure the main viewport for the Scenic application
config :play, :viewport, %{
name: :main_viewport,
size: {500, 500},
# default_scene: {Play.Scene.Asteroids, nil},
default_scene: {Play.Scene.Splash, Play.Scene.Asteroids},
drivers: [
%{
module: Scenic.Driver.Glfw,
name: :glfw,
opts: [resizeable: false, title: "play"]
}
]
}
config :play_web, PlayWeb.Endpoint,
url: [host: "localhost"],
server: true,
secret_key_base: "4m4EdLqbm138oXxQyvWMUy8CEiksqoNBPjoHZEwvhnGVML9SrFNCXtE57z6x8EV1",
render_errors: [view: PlayWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: PlayWeb.PubSub, adapter: Phoenix.PubSub.PG2]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Disable tzdata automatic updates
config :tzdata, :autoupdate, :disabled
case Mix.env() do
:dev ->
config :exsync,
reload_timeout: 75,
reload_callback: {GenServer, :call, [ScenicLiveReload, :reload_current_scene]}
_ ->
nil
end
case Mix.env() do
:dev ->
config :play_web, PlayWeb.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("../../play_web/assets", __DIR__)
]
]
config :play_web, PlayWeb.Endpoint,
live_reload: [
patterns: [
# TODO: Update these paths
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/play_web/{live,views}/.*(ex)$",
~r"lib/play_web/templates/.*(eex)$"
]
]
config :phoenix_live_reload, dirs: ["../play_web"]
_ ->
nil
end
| 24.716216 | 86 | 0.614543 |
0330725f9716b3c9b52232c1664fd4d2cd7b9aac | 2,608 | ex | Elixir | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/asymmetric_sign_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/asymmetric_sign_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/asymmetric_sign_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.CloudKMS.V1.Model.AsymmetricSignRequest do
@moduledoc """
Request message for KeyManagementService.AsymmetricSign.
## Attributes
* `digest` (*type:* `GoogleApi.CloudKMS.V1.Model.Digest.t`, *default:* `nil`) - Required. The digest of the data to sign. The digest must be produced with the same digest algorithm as specified by the key version's algorithm.
* `digestCrc32c` (*type:* `String.t`, *default:* `nil`) - Optional. An optional CRC32C checksum of the AsymmetricSignRequest.digest. If specified, KeyManagementService will verify the integrity of the received AsymmetricSignRequest.digest using this checksum. KeyManagementService will report an error if the checksum verification fails. If you receive a checksum error, your client should verify that CRC32C(AsymmetricSignRequest.digest) is equal to AsymmetricSignRequest.digest_crc32c, and if so, perform a limited number of retries. A persistent mismatch may indicate an issue in your computation of the CRC32C checksum. Note: This field is defined as int64 for reasons of compatibility across different languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be safely downconverted to uint32 in languages that support this type. NOTE: This field is in Beta.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:digest => GoogleApi.CloudKMS.V1.Model.Digest.t(),
:digestCrc32c => String.t()
}
field(:digest, as: GoogleApi.CloudKMS.V1.Model.Digest)
field(:digestCrc32c)
end
defimpl Poison.Decoder, for: GoogleApi.CloudKMS.V1.Model.AsymmetricSignRequest do
def decode(value, options) do
GoogleApi.CloudKMS.V1.Model.AsymmetricSignRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudKMS.V1.Model.AsymmetricSignRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 52.16 | 900 | 0.768021 |
03307a9e32630050fb2fc861ffee2f07e052dedc | 2,978 | ex | Elixir | lib/surface/directive/events.ex | bonfire-networks/surface | fed7b81b8d12a8cba49bf3ffe505d18033157e0d | [
"MIT"
] | 1 | 2021-04-30T14:28:08.000Z | 2021-04-30T14:28:08.000Z | lib/surface/directive/events.ex | bonfire-networks/surface | fed7b81b8d12a8cba49bf3ffe505d18033157e0d | [
"MIT"
] | null | null | null | lib/surface/directive/events.ex | bonfire-networks/surface | fed7b81b8d12a8cba49bf3ffe505d18033157e0d | [
"MIT"
] | null | null | null | defmodule Surface.Directive.Events do
use Surface.Directive
@events [
"click",
"capture-click",
"blur",
"focus",
"change",
"submit",
"keydown",
"keyup",
"window-focus",
"window-blur",
"window-keydown",
"window-keyup"
]
@phx_events Enum.map(@events, &"phx-#{&1}")
def phx_events(), do: @phx_events
def extract({":on-" <> event_name, value, attr_meta}, meta)
when event_name in @events do
name = String.to_atom(event_name)
%AST.Directive{
module: __MODULE__,
name: name,
value: to_quoted_expr(name, value, meta),
meta: Helpers.to_meta(attr_meta, meta)
}
end
def extract(_, _), do: []
def process(
%AST.Directive{
name: event_name,
value: %AST.AttributeExpr{value: value} = expr,
meta: meta
},
%type{attributes: attributes} = node
)
when type in [AST.Tag, AST.VoidTag] do
cid = AST.Meta.quoted_caller_cid(meta)
value =
quote generated: true do
[
{unquote("phx-#{event_name}"),
{:string, unquote(__MODULE__).event_name(unquote(value))}},
"phx-target": {:string, unquote(__MODULE__).event_target(unquote(value), unquote(cid))}
]
end
%{
node
| attributes: [
%AST.DynamicAttribute{name: event_name, meta: meta, expr: %{expr | value: value}}
| attributes
]
}
end
defp to_quoted_expr(_name, [], meta) do
%AST.AttributeExpr{
original: "",
value: nil,
meta: meta
}
end
defp to_quoted_expr(name, [{:attribute_expr, original, expr_meta} = value], meta) do
to_quoted_expr(name, value, meta)
end
defp to_quoted_expr(name, value, meta) when is_list(value) do
to_quoted_expr(name, to_string(value), meta)
end
defp to_quoted_expr(name, event, meta) when is_binary(event) or is_bitstring(event) do
%AST.AttributeExpr{
original: event,
value: Surface.TypeHandler.expr_to_quoted!(Macro.to_string(event), name, :event, meta),
meta: meta
}
end
defp to_quoted_expr(name, {:attribute_expr, original, expr_meta}, meta) do
expr_meta = Helpers.to_meta(expr_meta, meta)
value =
original
|> Surface.TypeHandler.expr_to_quoted!(name, :event, expr_meta)
|> case do
[name, opts] when is_binary(name) and is_list(opts) -> Keyword.put(opts, :name, name)
[name | opts] when is_binary(name) and is_list(opts) -> Keyword.put(opts, :name, name)
value -> value
end
%AST.AttributeExpr{
original: original,
value: value,
meta: expr_meta
}
end
def event_name(%{name: name}) do
name
end
def event_name(_) do
""
end
def event_target(%{target: nil}, cid) do
to_string(cid)
end
def event_target(%{target: target}, _cid) when target != :live_view do
to_string(target)
end
def event_target(_, _cid) do
""
end
end
| 23.085271 | 97 | 0.605776 |
03308c0171b953cf2435c32b296406268c4ef176 | 315 | ex | Elixir | web/views/tp_resource_view.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/views/tp_resource_view.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/views/tp_resource_view.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | defmodule CgratesWebJsonapi.TpResourceView do
use CgratesWebJsonapi.Web, :view
use JaSerializer.PhoenixView
attributes ~w[id tpid tenant custom_id filter_ids usage_ttl activation_interval
threshold_ids stored allocation_message blocker weight limit]a
def id(resource), do: resource.pk
end
| 31.5 | 81 | 0.790476 |
03309065f047280431bcab30e895398663aff238 | 46,569 | exs | Elixir | lib/elixir/test/elixir/kernel/warning_test.exs | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | 1 | 2018-02-24T19:48:35.000Z | 2018-02-24T19:48:35.000Z | lib/elixir/test/elixir/kernel/warning_test.exs | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/kernel/warning_test.exs | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | null | null | null | Code.require_file("../test_helper.exs", __DIR__)
defmodule Kernel.WarningTest do
use ExUnit.Case
import ExUnit.CaptureIO
defp capture_err(fun) do
capture_io(:stderr, fun)
end
test "outdented heredoc" do
output =
capture_err(fn ->
Code.eval_string("""
'''
outdented
'''
""")
end)
assert output =~ "outdented heredoc line"
assert output =~ "nofile:2"
end
test "operators formed by many of the same character followed by that character" do
output =
capture_err(fn ->
Code.eval_string("quote do: ....()")
end)
assert output =~ "found \"...\" followed by \".\", please use parens around \"...\" instead"
end
test "identifier that ends in ! followed by the = operator without a space in between" do
output = capture_err(fn -> Code.eval_string("foo!= 1") end)
assert output =~ "found identifier \"foo!\", ending with \"!\""
output = capture_err(fn -> Code.eval_string(":foo!= :foo!") end)
assert output =~ "found atom \":foo!\", ending with \"!\""
end
describe "unnecessary quotes" do
test "does not warn for unnecessary quotes in uppercase atoms/keywords" do
assert capture_err(fn -> Code.eval_string(~s/:"Foo"/) end) == ""
assert capture_err(fn -> Code.eval_string(~s/["Foo": :bar]/) end) == ""
end
test "warns for unnecessary quotes" do
assert capture_err(fn -> Code.eval_string(~s/:"foo"/) end) =~
"found quoted atom \"foo\" but the quotes are not required"
assert capture_err(fn -> Code.eval_string(~s/["foo": :bar]/) end) =~
"found quoted keyword \"foo\" but the quotes are not required"
assert capture_err(fn -> Code.eval_string(~s/[Kernel."length"([])]/) end) =~
"found quoted call \"length\" but the quotes are not required"
end
end
test "unused variable" do
output =
capture_err(fn ->
# Note we use compile_string because eval_string does not emit unused vars warning
Code.compile_string("""
defmodule Sample do
module = 1
def hello(arg), do: nil
end
file = 2
file = 3
file
""")
end)
assert output =~ "variable \"arg\" is unused"
assert output =~ "variable \"module\" is unused"
assert output =~ "variable \"file\" is unused"
after
purge(Sample)
end
test "nested unused variable" do
message = "variable \"x\" is unused"
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
case false do
true -> x = 1
_ -> 1
end
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
false and (x = 1)
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
true or (x = 1)
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
if false do
x = 1
end
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
cond do
false -> x = 1
true -> 1
end
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
receive do
:foo -> x = 1
after
0 -> 1
end
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
false && (x = 1)
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
true || (x = 1)
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
with true <- true do
x = false
end
x
""")
end
end) =~ message
assert capture_err(fn ->
assert_raise CompileError, ~r/undefined function x/, fn ->
Code.eval_string("""
fn ->
x = true
end
x
""")
end
end) =~ message
end
test "unused variable in redefined function in different file" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defmacro __using__(_) do
quote location: :keep do
def function(arg)
end
end
end
""")
code = """
defmodule RedefineSample do
use Sample
def function(var123), do: nil
end
"""
Code.eval_string(code, [], file: "redefine_sample.ex")
end)
assert output =~ "redefine_sample.ex:3"
assert output =~ "variable \"var123\" is unused"
after
purge(Sample)
purge(RedefineSample)
end
test "useless literal" do
message = "code block contains unused literal \"oops\""
assert capture_err(fn ->
Code.eval_string("""
"oops"
:ok
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string("""
fn ->
"oops"
:ok
end
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string("""
try do
"oops"
:ok
after
:ok
end
""")
end) =~ message
end
test "useless attr" do
message =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@foo 1
@bar 1
@foo
def bar do
@bar
:ok
end
end
""")
end)
assert message =~ "module attribute @foo in code block has no effect as it is never returned "
assert message =~ "module attribute @bar in code block has no effect as it is never returned "
after
purge(Sample)
end
test "useless var" do
message = "variable foo in code block has no effect as it is never returned "
assert capture_err(fn ->
Code.eval_string("""
foo = 1
foo
:ok
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string("""
fn ->
foo = 1
foo
:ok
end
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string("""
try do
foo = 1
foo
:ok
after
:ok
end
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string("""
node()
:ok
""")
end) == ""
end
test "underscored variable on match" do
assert capture_err(fn ->
Code.eval_string("""
{_arg, _arg} = {1, 1}
""")
end) =~ "the underscored variable \"_arg\" appears more than once in a match"
end
test "underscored variable on use" do
assert capture_err(fn ->
Code.eval_string("""
fn _var -> _var + 1 end
""")
end) =~ "the underscored variable \"_var\" is used after being set"
assert capture_err(fn ->
Code.eval_string("""
fn var!(_var, Foo) -> var!(_var, Foo) + 1 end
""")
end) =~ ""
end
test "unused function" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
defp hello, do: nil
end
""")
end) =~ "function hello/0 is unused\n nofile:2"
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample2 do
defp hello(0), do: hello(1)
defp hello(1), do: :ok
end
""")
end) =~ "function hello/1 is unused\n nofile:2"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample3 do
def a, do: nil
def b, do: d(10)
defp c(x, y \\ 1), do: [x, y]
defp d(x), do: x
end
""")
end) =~ "function c/2 is unused\n nofile:4"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample4 do
def a, do: nil
defp b(x \\ 1, y \\ 1)
defp b(x, y), do: [x, y]
end
""")
end) =~ "function b/2 is unused\n nofile:3"
after
purge([Sample1, Sample2, Sample3, Sample4])
end
test "unused cyclic functions" do
message =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defp a, do: b()
defp b, do: a()
end
""")
end)
assert message =~ "function a/0 is unused\n nofile:2"
assert message =~ "function b/0 is unused\n nofile:3"
after
purge(Sample)
end
test "unused macro" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defmacrop hello, do: nil
end
""")
end) =~ "macro hello/0 is unused"
after
purge(Sample)
end
test "shadowing" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def test(x) do
case x do
{:file, fid} -> fid
{:path, _} -> fn(fid) -> fid end
end
end
end
""")
end) == ""
after
purge(Sample)
end
test "unused default args" do
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample1 do
def a, do: b(1, 2, 3)
defp b(arg1 \\ 1, arg2 \\ 2, arg3 \\ 3), do: [arg1, arg2, arg3]
end
""")
end) =~ "default arguments in b/3 are never used\n nofile:3"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample2 do
def a, do: b(1, 2)
defp b(arg1 \\ 1, arg2 \\ 2, arg3 \\ 3), do: [arg1, arg2, arg3]
end
""")
end) =~ "the first 2 default arguments in b/3 are never used\n nofile:3"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample3 do
def a, do: b(1)
defp b(arg1 \\ 1, arg2 \\ 2, arg3 \\ 3), do: [arg1, arg2, arg3]
end
""")
end) =~ "the first default argument in b/3 is never used\n nofile:3"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample4 do
def a, do: b(1)
defp b(arg1 \\ 1, arg2, arg3 \\ 3), do: [arg1, arg2, arg3]
end
""")
end) == ""
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample5 do
def a, do: b(1, 2, 3)
defp b(arg1 \\ 1, arg2 \\ 2, arg3 \\ 3)
defp b(arg1, arg2, arg3), do: [arg1, arg2, arg3]
end
""")
end) =~ "default arguments in b/3 are never used\n nofile:3"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample6 do
def a, do: b(1, 2)
defp b(arg1 \\ 1, arg2 \\ 2, arg3 \\ 3)
defp b(arg1, arg2, arg3), do: [arg1, arg2, arg3]
end
""")
end) =~ "the first 2 default arguments in b/3 are never used\n nofile:3"
after
purge([Sample1, Sample2, Sample3, Sample4, Sample5, Sample6])
end
test "unused import" do
assert capture_err(fn ->
Code.compile_string("""
defmodule Sample do
import :lists
def a, do: nil
end
""")
end) =~ "unused import :lists\n"
assert capture_err(fn ->
Code.compile_string("""
import :lists
""")
end) =~ "unused import :lists\n"
after
purge(Sample)
end
test "unused import of one of the functions in :only" do
output =
capture_err(fn ->
Code.compile_string("""
defmodule Sample do
import String, only: [upcase: 1, downcase: 1, trim: 1]
def a, do: upcase("hello")
end
""")
end)
assert output =~ "unused import String.downcase/1"
assert output =~ "unused import String.trim/1"
after
purge(Sample)
end
test "unused import of any of the functions in :only" do
assert capture_err(fn ->
Code.compile_string("""
defmodule Sample do
import String, only: [upcase: 1, downcase: 1]
def a, do: nil
end
""")
end) =~ "unused import String\n"
after
purge(Sample)
end
test "unused alias" do
assert capture_err(fn ->
Code.compile_string("""
defmodule Sample do
alias :lists, as: List
def a, do: nil
end
""")
end) =~ "unused alias List"
after
purge(Sample)
end
test "unused alias when also import" do
assert capture_err(fn ->
Code.compile_string("""
defmodule Sample do
alias :lists, as: List
import MapSet
new()
end
""")
end) =~ "unused alias List"
after
purge(Sample)
end
test "unused inside dynamic module" do
import List, only: [flatten: 1], warn: false
assert capture_err(fn ->
defmodule Sample do
import String, only: [downcase: 1]
def world do
flatten([1, 2, 3])
end
end
end) =~ "unused import String"
after
purge(Sample)
end
test "duplicate map keys" do
output =
capture_err(fn ->
defmodule DuplicateMapKeys do
assert %{a: :b, a: :c} == %{a: :c}
assert %{m: :n, m: :o, m: :p} == %{m: :p}
assert %{1 => 2, 1 => 3} == %{1 => 3}
end
end)
assert output =~ "key :a will be overridden in map"
assert output =~ "key :m will be overridden in map"
assert output =~ "key 1 will be overridden in map"
assert map_size(%{System.unique_integer() => 1, System.unique_integer() => 2}) == 2
end
test "unused guard" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def atom_case do
v = "bc"
case v do
_ when is_atom(v) -> :ok
_ -> :fail
end
end
end
""")
end) =~ "this check/guard will always yield the same result"
after
purge(Sample)
end
test "length(list) == 0 in guard" do
error_message =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def list_case do
v = []
case v do
_ when length(v) == 0 -> :ok
_ -> :fail
end
end
end
""")
end)
assert error_message =~ "do not use \"length(v) == 0\" to check if a list is empty"
assert error_message =~
"Prefer to pattern match on an empty list or use \"v == []\" as a guard"
after
purge(Sample)
end
test "length(list) > 0 in guard" do
error_message =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def list_case do
v = []
case v do
_ when length(v) > 0 -> :ok
_ -> :fail
end
end
end
""")
end)
assert error_message =~ "do not use \"length(v) > 0\" to check if a list is not empty"
assert error_message =~
"Prefer to pattern match on a non-empty list, such as [_ | _], or use \"v != []\" as a guard"
after
purge(Sample)
end
test "previous clause always matches" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def binary_cond do
v = "bc"
cond do
is_binary(v) -> :bin
true -> :ok
end
end
end
""")
end) =~ "this clause cannot match because a previous clause at line 5 always matches"
after
purge(Sample)
end
test "empty clause" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
def hello
end
""")
end) =~ "implementation not provided for predefined def hello/0"
after
purge(Sample1)
end
test "used import via alias" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
import List, only: [flatten: 1]
defmacro generate do
List.duplicate(quote(do: flatten([1, 2, 3])), 100)
end
end
defmodule Sample2 do
import Sample1
generate()
end
""")
end) == ""
after
purge([Sample1, Sample2])
end
test "clause not match" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def hello, do: nil
def hello, do: nil
end
""")
end) =~ "this clause cannot match because a previous clause at line 2 always matches"
after
purge(Sample)
end
test "generated clause not match" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defmacro __using__(_) do
quote do
def hello, do: nil
def hello, do: nil
end
end
end
defmodule UseSample do
use Sample
end
""")
end) =~ "this clause cannot match because a previous clause at line 10 always matches"
after
purge(Sample)
purge(UseSample)
end
test "deprecated not left in right" do
assert capture_err(fn ->
Code.eval_string("not 1 in [1, 2, 3]")
end) =~ "deprecated"
end
test "clause with defaults should be first" do
message = "def hello/1 has multiple clauses and also declares default values"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample1 do
def hello(arg), do: arg
def hello(arg \\ 0), do: arg
end
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample2 do
def hello(_arg)
def hello(arg \\ 0), do: arg
end
""")
end) =~ message
after
purge([Sample1, Sample2])
end
test "clauses with default should use header" do
message = "def hello/1 has multiple clauses and also declares default values"
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample1 do
def hello(arg \\ 0), do: arg
def hello(arg), do: arg
end
""")
end) =~ message
assert capture_err(fn ->
Code.eval_string(~S"""
defmodule Sample2 do
def hello(arg \\ 0), do: arg
def hello(_arg)
end
""")
end) == ""
after
purge([Sample1, Sample2])
end
test "unused with local with overridable" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def hello, do: world()
defp world, do: :ok
defoverridable [hello: 0]
def hello, do: :ok
end
""")
end) =~ "function world/0 is unused"
after
purge(Sample)
end
test "undefined module attribute" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@foo
end
""")
end) =~
"undefined module attribute @foo, please remove access to @foo or explicitly set it before access"
after
purge(Sample)
end
test "undefined module attribute in function" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def hello do
@foo
end
end
""")
end) =~
"undefined module attribute @foo, please remove access to @foo or explicitly set it before access"
after
purge(Sample)
end
test "undefined module attribute with file" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@foo
end
""")
end) =~
"undefined module attribute @foo, please remove access to @foo or explicitly set it before access"
after
purge(Sample)
end
test "parse transform" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@compile {:parse_transform, :ms_transform}
end
""")
end) =~ "@compile {:parse_transform, :ms_transform} is deprecated"
after
purge(Sample)
end
test "@compile inline no warning for unreachable function" do
refute capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@compile {:inline, foo: 1}
defp foo(_), do: :ok
end
""")
end) =~ "inlined function foo/1 undefined"
after
purge(Sample)
end
test "in guard empty list" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def a(x) when x in [], do: x
end
""")
end) =~ "this check/guard will always yield the same result"
after
purge(Sample)
end
test "no effect operator" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def a(x) do
x != :foo
:ok
end
end
""")
end) =~ "use of operator != has no effect"
after
purge(Sample)
end
test "badarg warning" do
assert capture_err(fn ->
assert_raise ArgumentError, fn ->
Code.eval_string("""
defmodule Sample do
Atom.to_string "abc"
end
""")
end
end) =~ "this expression will fail with ArgumentError"
after
purge([Sample])
end
test "undefined function for behaviour" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
@callback foo :: term
end
defmodule Sample2 do
@behaviour Sample1
end
""")
end) =~
"function foo/0 required by behaviour Sample1 is not implemented (in module Sample2)"
after
purge([Sample1, Sample2])
end
test "undefined macro for behaviour" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
@macrocallback foo :: Macro.t
end
defmodule Sample2 do
@behaviour Sample1
end
""")
end) =~
"macro foo/0 required by behaviour Sample1 is not implemented (in module Sample2)"
after
purge([Sample1, Sample2])
end
test "wrong kind for behaviour" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
@callback foo :: term
end
defmodule Sample2 do
@behaviour Sample1
defmacro foo, do: :ok
end
""")
end) =~
"function foo/0 required by behaviour Sample1 was implemented as \"defmacro\" but should have been \"def\""
after
purge([Sample1, Sample2])
end
test "conflicting behaviour" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
@callback foo :: term
end
defmodule Sample2 do
@callback foo :: term
end
defmodule Sample3 do
@behaviour Sample1
@behaviour Sample2
end
""")
end) =~
"conflicting behaviours found. function foo/0 is required by Sample1 and Sample2 (in module Sample3)"
after
purge([Sample1, Sample2, Sample3])
end
test "duplicate behaviour" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample1 do
@callback foo :: term
end
defmodule Sample2 do
@behaviour Sample1
@behaviour Sample1
end
""")
end) =~
"the behavior Sample1 has been declared twice (conflict in function foo/0 in module Sample2)"
after
purge([Sample1, Sample2])
end
test "undefined behaviour" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@behaviour UndefinedBehaviour
end
""")
end) =~ "@behaviour UndefinedBehaviour does not exist (in module Sample)"
after
purge(Sample)
end
test "empty behaviours" do
assert capture_err(fn ->
Code.eval_string("""
defmodule EmptyBehaviour do
end
defmodule Sample do
@behaviour EmptyBehaviour
end
""")
end) =~ "module EmptyBehaviour is not a behaviour (in module Sample)"
after
purge(Sample)
purge(EmptyBehaviour)
end
test "undefined behavior" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@behavior Hello
end
""")
end) =~ "@behavior attribute is not supported, please use @behaviour instead"
after
purge(Sample)
end
test "undefined function for protocol" do
assert capture_err(fn ->
Code.eval_string("""
defprotocol Sample1 do
def foo(subject)
end
defimpl Sample1, for: Atom do
end
""")
end) =~
"function foo/1 required by protocol Sample1 is not implemented (in module Sample1.Atom)"
after
purge([Sample1, Sample1.Atom])
end
test "overridden def name" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def foo(x, 1), do: x + 1
def foo(), do: nil
def foo(x, 2), do: x * 2
end
""")
end) =~
"clauses with the same name should be grouped together, \"def foo/2\" was previously defined (nofile:2)"
after
purge(Sample)
end
test "overridden def name and arity" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def foo(x, 1), do: x + 1
def bar(), do: nil
def foo(x, 2), do: x * 2
end
""")
end) =~
"clauses with the same name and arity (number of arguments) should be grouped together, \"def foo/2\" was previously defined (nofile:2)"
after
purge(Sample)
end
test "warning with overridden file" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@file "sample"
def foo(x), do: :ok
end
""")
end)
assert output =~ "variable \"x\" is unused"
assert output =~ "sample:3"
after
purge(Sample)
end
test "with and do clauses emit errors, else clauses do not" do
assert capture_err(fn ->
Code.compile_string("""
with {:first, int} when is_integer(int) <- {:second, Integer.gcd(2, 4)} do
int
end
""")
end) =~ "this clause cannot match"
assert capture_err(fn ->
Code.compile_string("""
with {:first, int1} when is_integer(int1) <- {:first, Integer.gcd(2, 4)},
{:second, int2} when is_integer(int2) <- {:second, Integer.gcd(2, 4)} do
{:ok, int1 + int2}
else
{:first, nil} -> {:error, "first number is not integer"}
{:second, nil} -> {:error, "second number is not integer"}
end
""")
end) == ""
after
purge(Sample1)
purge(Sample2)
end
test "warning on code point escape" do
assert capture_err(fn ->
Code.eval_string("? ")
end) =~ "found ? followed by code point 0x20 (space), please use ?\\s instead"
end
test "duplicated docs in the same clause" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@doc "Something"
@doc "Another"
def foo, do: :ok
Module.eval_quoted(__MODULE__, quote(do: @doc false))
@doc "Doc"
def bar, do: :ok
end
""")
end)
assert output =~ "redefining @doc attribute previously set at line 2"
assert output =~ "nofile:3: Sample (module)"
refute output =~ "nofile:7"
after
purge(Sample)
end
test "reserved doc metadata keys" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@typedoc opaque: false
@type t :: binary
@doc defaults: 3, since: "1.2.3"
def foo(a), do: a
end
""")
end)
assert output =~ "ignoring reserved documentation metadata key: :opaque"
assert output =~ "ignoring reserved documentation metadata key: :defaults"
refute output =~ ":since"
after
purge(Sample)
end
describe "typespecs" do
test "unused types" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type pub :: any
@opaque op :: any
@typep priv :: any
@typep priv_args(var1, var2) :: {var1, var2}
@typep priv2 :: any
@typep priv3 :: priv2 | atom
@spec my_fun(priv3) :: pub
def my_fun(var), do: var
end
""")
end)
assert output =~ "nofile:4"
assert output =~ "type priv/0 is unused"
assert output =~ "nofile:5"
assert output =~ "type priv_args/2 is unused"
refute output =~ "type pub/0 is unused"
refute output =~ "type op/0 is unused"
refute output =~ "type priv2/0 is unused"
refute output =~ "type priv3/0 is unused"
after
purge(Sample)
end
test "underspecified opaque types" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@opaque op1 :: term
@opaque op2 :: any
@opaque op3 :: atom
end
""")
end)
assert output =~ "nofile:2"
assert output =~ "@opaque type op1/0 is underspecified and therefore meaningless"
assert output =~ "nofile:3"
assert output =~ "@opaque type op2/0 is underspecified and therefore meaningless"
refute output =~ "nofile:4"
refute output =~ "op3"
after
purge(Sample)
end
test "underscored types variables" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type in_typespec_vars(_var1, _var1) :: atom
@type in_typespec(_var2) :: {atom, _var2}
@spec in_spec(_var3) :: {atom, _var3} when _var3: var
def in_spec(a), do: {:ok, a}
end
""")
end)
assert output =~ "nofile:2"
assert output =~ ~r/the underscored type variable "_var1" is used more than once/
assert output =~ "nofile:3"
assert output =~ ~r/the underscored type variable "_var2" is used more than once/
assert output =~ "nofile:5"
assert output =~ ~r/the underscored type variable "_var3" is used more than once/
after
purge(Sample)
end
test "typedoc on typep" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@typedoc "Something"
@typep priv :: any
@spec foo() :: priv
def foo(), do: nil
end
""")
end) =~ "type priv/0 is private, @typedoc's are always discarded for private types"
after
purge(Sample)
end
test "discouraged types" do
message =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type foo :: string()
@type bar :: nonempty_string()
end
""")
end)
string_discouraged =
"string() type use is discouraged. " <>
"For character lists, use charlist() type, for strings, String.t()\n"
nonempty_string_discouraged =
"nonempty_string() type use is discouraged. " <>
"For non-empty character lists, use nonempty_charlist() type, for strings, String.t()\n"
assert message =~ string_discouraged
assert message =~ nonempty_string_discouraged
after
purge(Sample)
end
test "unreachable specs" do
message =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defp my_fun(x), do: x
@spec my_fun(integer) :: integer
end
""")
end)
assert message != ""
after
purge(Sample)
end
test "nested type annotations" do
message = "invalid type annotation. Type annotations cannot be nested"
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type my_type :: ann_type :: nested_ann_type :: atom
end
""")
end) =~ message
purge(Sample)
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type my_type :: ann_type :: nested_ann_type :: atom | port
end
""")
end) =~ message
purge(Sample)
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@spec foo :: {pid, ann_type :: nested_ann_type :: atom}
def foo, do: nil
end
""")
end) =~ message
after
purge(Sample)
end
test "invalid type annotations" do
message =
"invalid type annotation. When using the | operator to represent the union of types, " <>
"make sure to wrap type annotations in parentheses"
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type my_type :: pid | ann_type :: atom
end
""")
end) =~ message
purge(Sample)
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type my_type :: pid | ann_type :: atom | port
end
""")
end) =~ message
purge(Sample)
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@type my_type :: {port, pid | ann_type :: atom | port}
end
""")
end) =~ message
after
purge(Sample)
end
end
test "attribute with no use" do
content =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@at "Something"
end
""")
end)
assert content =~ "module attribute @at was set but never used"
assert content =~ "nofile:2"
after
purge(Sample)
end
test "typedoc with no type" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@typedoc "Something"
end
""")
end) =~ "module attribute @typedoc was set but no type follows it"
after
purge(Sample)
end
test "doc with no function" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
@doc "Something"
end
""")
end) =~ "module attribute @doc was set but no definition follows it"
after
purge(Sample)
end
test "pipe without explicit parentheses" do
assert capture_err(fn ->
Code.eval_string("""
[5, 6, 7, 3]
|> Enum.map_join "", &(Integer.to_string(&1))
|> String.to_integer
""")
end) =~ "parentheses are required when piping into a function call"
end
test "variable is being expanded to function call" do
output =
capture_err(fn ->
Code.eval_string("""
self
defmodule Sample do
def my_node(), do: node
end
""")
end)
assert output =~ "variable \"self\" does not exist and is being expanded to \"self()\""
assert output =~ "variable \"node\" does not exist and is being expanded to \"node()\""
after
purge(Sample)
end
defmodule User do
defstruct [:name]
end
test ":__struct__ is ignored when using structs" do
assert capture_err(fn ->
code = """
assert %Kernel.WarningTest.User{__struct__: Ignored, name: "joe"} ==
%Kernel.WarningTest.User{name: "joe"}
"""
Code.eval_string(code, [], __ENV__)
end) =~ "key :__struct__ is ignored when using structs"
assert capture_err(fn ->
code = """
user = %Kernel.WarningTest.User{name: "meg"}
assert %Kernel.WarningTest.User{user | __struct__: Ignored, name: "joe"} ==
%Kernel.WarningTest.User{__struct__: Kernel.WarningTest.User, name: "joe"}
"""
Code.eval_string(code, [], __ENV__)
end) =~ "key :__struct__ is ignored when using structs"
end
test "catch comes before rescue in try block" do
output =
capture_err(fn ->
Code.eval_string("""
try do
:trying
catch
_ -> :caught
rescue
_ -> :error
end
""")
end)
assert output =~ ~s("catch" should always come after "rescue" in try)
end
test "catch comes before rescue in def" do
output =
capture_err(fn ->
Code.eval_string("""
defmodule Sample do
def foo do
:trying
catch
_, _ -> :caught
rescue
_ -> :error
end
end
""")
end)
assert output =~ ~s("catch" should always come after "rescue" in def)
after
purge(Sample)
end
test "System.stacktrace is deprecated outside catch/rescue" do
output = capture_err(fn -> Code.eval_string("System.stacktrace()") end)
assert output =~ "System.stacktrace/0 outside of rescue/catch clauses is deprecated"
output =
capture_err(fn ->
Code.eval_string("""
try do
:trying
rescue
_ -> System.stacktrace()
catch
_ -> System.stacktrace()
end
""")
end)
assert output == ""
end
test "unused variable in defguard" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defguard foo(bar, baz) when bar
end
""")
end) =~ "variable \"baz\" is unused"
after
purge(Sample)
end
test "unused import in defguard" do
assert capture_err(fn ->
Code.compile_string("""
defmodule Sample do
import Record
defguard is_record(baz) when baz
end
""")
end) =~ "unused import Record\n"
after
purge(Sample)
end
test "unused private guard" do
assert capture_err(fn ->
Code.compile_string("""
defmodule Sample do
defguardp foo(bar, baz) when bar + baz
end
""")
end) =~ "macro foo/2 is unused\n"
after
purge(Sample)
end
test "defguard overriding defmacro" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defmacro foo(bar), do: bar == :bar
defguard foo(baz) when baz == :baz
end
""")
end) =~ "this clause cannot match because a previous clause at line 2 always matches"
after
purge(Sample)
end
test "defmacro overriding defguard" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defguard foo(baz) when baz == :baz
defmacro foo(bar), do: bar == :bar
end
""")
end) =~ "this clause cannot match because a previous clause at line 2 always matches"
after
purge(Sample)
end
test "defguard needs an implementation" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
defguard foo(bar)
end
""")
end) =~ "implementation not provided for predefined defmacro foo/1"
after
purge(Sample)
end
test "struct comparisons" do
expressions = [
~s(~N"2018-01-28 12:00:00"),
~s(~T"12:00:00"),
~s(~D"2018-01-28"),
"%File.Stat{}"
]
for op <- [:<, :>, :<=, :>=],
expression <- expressions do
assert capture_err(fn ->
Code.eval_string("x #{op} #{expression}", x: 1)
end) =~ "invalid comparison with struct literal #{expression}"
assert capture_err(fn ->
Code.eval_string("#{expression} #{op} x", x: 1)
end) =~ "invalid comparison with struct literal #{expression}"
end
end
test "deprecated GenServer super" do
assert capture_err(fn ->
Code.eval_string("""
defmodule Sample do
use GenServer
def handle_call(a, b, c) do
super(a, b, c)
end
end
""")
end) =~ "calling super for GenServer callback handle_call/3 is deprecated"
after
purge(Sample)
end
test "nested comparison operators" do
message =
capture_err(fn ->
Code.compile_string("""
1 < 3 < 5
""")
end)
assert message =~ "Elixir does not support nested comparisons"
assert message =~ "1 < 3 < 5"
message =
capture_err(fn ->
Code.compile_string("""
x = 5
y = 7
1 < x < y < 10
""")
end)
assert message =~ "Elixir does not support nested comparisons"
assert message =~ "1 < x < y < 10"
end
test "def warns if only clause is else" do
message =
capture_err(fn ->
Code.compile_string("""
defmodule Sample do
def foo do
:bar
else
_other -> :ok
end
end
""")
end)
assert message =~ "\"else\" shouldn't be used as the only clause in \"def\""
after
purge(Sample)
end
test "try warns if only clause is else" do
message =
capture_err(fn ->
Code.compile_string("""
try do
:ok
else
other -> other
end
""")
end)
assert message =~ "\"else\" shouldn't be used as the only clause in \"try\""
end
test "warns on bad record update input" do
assert capture_err(fn ->
defmodule Sample do
require Record
Record.defrecord(:user, __MODULE__, name: "john", age: 25)
def fun do
user(user(), _: :_, name: "meg")
end
end
end) =~ "updating a record with a default (:_) is equivalent to creating a new record"
after
purge([Sample])
end
defp purge(list) when is_list(list) do
Enum.each(list, &purge/1)
end
defp purge(module) when is_atom(module) do
:code.delete(module)
:code.purge(module)
end
end
| 26.717728 | 149 | 0.494449 |
0330abcdd555f8a249d7c2cb82668368ecdf5dad | 2,163 | ex | Elixir | clients/game_services/lib/google_api/game_services/v1beta/model/list_game_server_configs_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/game_services/lib/google_api/game_services/v1beta/model/list_game_server_configs_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/game_services/lib/google_api/game_services/v1beta/model/list_game_server_configs_response.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.GameServices.V1beta.Model.ListGameServerConfigsResponse do
@moduledoc """
Response message for GameServerConfigsService.ListGameServerConfigs.
## Attributes
* `gameServerConfigs` (*type:* `list(GoogleApi.GameServices.V1beta.Model.GameServerConfig.t)`, *default:* `nil`) - The list of game server configs.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Token to retrieve the next page of results, or empty if there are no more results in the list.
* `unreachable` (*type:* `list(String.t)`, *default:* `nil`) - List of locations that could not be reached.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:gameServerConfigs =>
list(GoogleApi.GameServices.V1beta.Model.GameServerConfig.t()) | nil,
:nextPageToken => String.t() | nil,
:unreachable => list(String.t()) | nil
}
field(:gameServerConfigs, as: GoogleApi.GameServices.V1beta.Model.GameServerConfig, type: :list)
field(:nextPageToken)
field(:unreachable, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.GameServices.V1beta.Model.ListGameServerConfigsResponse do
def decode(value, options) do
GoogleApi.GameServices.V1beta.Model.ListGameServerConfigsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.GameServices.V1beta.Model.ListGameServerConfigsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.055556 | 157 | 0.738789 |
0330b976274281a585a0afa23dd8188516631d84 | 365 | ex | Elixir | lib/readtome_web/auth/guardian.ex | zephraph/readtome | 64a5f773bdc3c19d9c5ac50a04aa14e446e36c55 | [
"MIT"
] | 1 | 2021-09-05T20:54:57.000Z | 2021-09-05T20:54:57.000Z | lib/readtome_web/auth/guardian.ex | zephraph/readtome | 64a5f773bdc3c19d9c5ac50a04aa14e446e36c55 | [
"MIT"
] | 17 | 2019-07-06T17:31:56.000Z | 2021-06-22T15:31:06.000Z | lib/readtome_web/auth/guardian.ex | zephraph/readtome | 64a5f773bdc3c19d9c5ac50a04aa14e446e36c55 | [
"MIT"
] | 1 | 2021-03-15T20:50:27.000Z | 2021-03-15T20:50:27.000Z | defmodule ReadtomeWeb.Auth.Guardian do
use Guardian, otp_app: :readtome
alias Readtome.Accounts
def subject_for_token(user, _claims) do
{:ok, to_string(user.id)}
end
def resource_from_claims(claims) do
user =
claims["sub"]
|> Accounts.get_user!()
{:ok, user}
# If something goes wrong here return {:error, reason}
end
end
| 20.277778 | 58 | 0.676712 |
0330be2394cea62de182640d4b75c5b608413699 | 42,505 | ex | Elixir | lib/phoenix/endpoint.ex | tomsharratt/phoenix | 2ea5db50f60ce9a783a12dc0f3a30ab8851f937e | [
"MIT"
] | null | null | null | lib/phoenix/endpoint.ex | tomsharratt/phoenix | 2ea5db50f60ce9a783a12dc0f3a30ab8851f937e | [
"MIT"
] | null | null | null | lib/phoenix/endpoint.ex | tomsharratt/phoenix | 2ea5db50f60ce9a783a12dc0f3a30ab8851f937e | [
"MIT"
] | null | null | null | defmodule Phoenix.Endpoint do
@moduledoc ~S"""
Defines a Phoenix endpoint.
The endpoint is the boundary where all requests to your
web application start. It is also the interface your
application provides to the underlying web servers.
Overall, an endpoint has three responsibilities:
* to provide a wrapper for starting and stopping the
endpoint as part of a supervision tree
* to define an initial plug pipeline for requests
to pass through
* to host web specific configuration for your
application
## Endpoints
An endpoint is simply a module defined with the help
of `Phoenix.Endpoint`. If you have used the `mix phx.new`
generator, an endpoint was automatically generated as
part of your application:
defmodule YourAppWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :your_app
# plug ...
# plug ...
plug YourApp.Router
end
Endpoints must be explicitly started as part of your application
supervision tree. Endpoints are added by default
to the supervision tree in generated applications. Endpoints can be
added to the supervision tree as follows:
children = [
YourAppWeb.Endpoint
]
## Endpoint configuration
All endpoints are configured in your application environment.
For example:
config :your_app, YourAppWeb.Endpoint,
secret_key_base: "kjoy3o1zeidquwy1398juxzldjlksahdk3"
Endpoint configuration is split into two categories. Compile-time
configuration means the configuration is read during compilation
and changing it at runtime has no effect. The compile-time
configuration is mostly related to error handling.
Runtime configuration, instead, is accessed during or
after your application is started and can be read through the
`c:config/2` function:
YourAppWeb.Endpoint.config(:port)
YourAppWeb.Endpoint.config(:some_config, :default_value)
### Dynamic configuration
For dynamically configuring the endpoint, such as loading data
from environment variables or configuration files, Phoenix invokes
the `c:init/2` callback on the endpoint, passing the atom `:supervisor`
as the first argument and the endpoint configuration as second.
All of Phoenix configuration, except the Compile-time configuration
below can be set dynamically from the `c:init/2` callback.
### Compile-time configuration
* `:code_reloader` - when `true`, enables code reloading functionality.
For the list of code reloader configuration options see
`Phoenix.CodeReloader.reload/1`. Keep in mind code reloading is
based on the file-system, therefore it is not possible to run two
instances of the same app at the same time with code reloading in
development, as they will race each other and only one will effectively
recompile the files. In such cases, tweak your config files so code
reloading is enabled in only one of the apps or set the MIX_BUILD
environment variable to give them distinct build directories
* `:debug_errors` - when `true`, uses `Plug.Debugger` functionality for
debugging failures in the application. Recommended to be set to `true`
only in development as it allows listing of the application source
code during debugging. Defaults to `false`
* `:force_ssl` - ensures no data is ever sent via HTTP, always redirecting
to HTTPS. It expects a list of options which are forwarded to `Plug.SSL`.
By default it sets the "strict-transport-security" header in HTTPS requests,
forcing browsers to always use HTTPS. If an unsafe request (HTTP) is sent,
it redirects to the HTTPS version using the `:host` specified in the `:url`
configuration. To dynamically redirect to the `host` of the current request,
set `:host` in the `:force_ssl` configuration to `nil`
### Runtime configuration
* `:adapter` - which webserver adapter to use for serving web requests.
See the "Adapter configuration" section below
* `:cache_static_manifest` - a path to a json manifest file that contains
static files and their digested version. This is typically set to
"priv/static/cache_manifest.json" which is the file automatically generated
by `mix phx.digest`. It can be either: a string containing a file system path
or a tuple containing the application name and the path within that application.
* `:cache_static_manifest_latest` - a map of the static files pointing to their
digest version. This is automatically loaded from `cache_static_manifest` on
boot. However, if you have your own static handling mechanism, you may want to
set this value explicitly. This is used by projects such as `LiveView` to
detect if the client is running on the latest version of all assets.
* `:cache_manifest_skip_vsn` - when true, skips the appended query string
"?vsn=d" when generatic paths to static assets. This query string is used
by `Plug.Static` to set long expiry dates, therefore, you should set this
option to true only if you are not using `Plug.Static` to serve assets,
for example, if you are using a CDN. If you are setting this option, you
should also consider passing `--no-vsn` to `mix phx.digest`. Defaults to
`false`.
* `:check_origin` - configure the default `:check_origin` setting for
transports. See `socket/3` for options. Defaults to `true`.
* `:secret_key_base` - a secret key used as a base to generate secrets
for encrypting and signing data. For example, cookies and tokens
are signed by default, but they may also be encrypted if desired.
Defaults to `nil` as it must be set per application
* `:server` - when `true`, starts the web server when the endpoint
supervision tree starts. Defaults to `false`. The `mix phx.server`
task automatically sets this to `true`
* `:url` - configuration for generating URLs throughout the app.
Accepts the `:host`, `:scheme`, `:path` and `:port` options. All
keys except `:path` can be changed at runtime. Defaults to:
[host: "localhost", path: "/"]
The `:port` option requires either an integer or string. The `:host`
option requires a string.
The `:scheme` option accepts `"http"` and `"https"` values. Default value
is inferred from top level `:http` or `:https` option. It is useful
when hosting Phoenix behind a load balancer or reverse proxy and
terminating SSL there.
The `:path` option can be used to override root path. Useful when hosting
Phoenix behind a reverse proxy with URL rewrite rules
* `:static_url` - configuration for generating URLs for static files.
It will fallback to `url` if no option is provided. Accepts the same
options as `url`
* `:watchers` - a set of watchers to run alongside your server. It
expects a list of tuples containing the executable and its arguments.
Watchers are guaranteed to run in the application directory, but only
when the server is enabled (unless `:force_watchers` configuration is
set to `true`). For example, the watcher below will run the "watch" mode
of the webpack build tool when the server starts. You can configure it
to whatever build tool or command you want:
[
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch",
"--watch-options-stdin"
]
]
The `:cd` and `:env` options can be given at the end of the list to customize
the watcher:
[node: [..., cd: "assets", env: [{"TAILWIND_MODE", "watch"}]]]
A watcher can also be a module-function-args tuple that will be invoked accordingly:
[another: {Mod, :fun, [arg1, arg2]}]
* `:force_watchers` - when `true`, forces your watchers to start
even when the `:server` option is set to `false`.
* `:live_reload` - configuration for the live reload option.
Configuration requires a `:patterns` option which should be a list of
file patterns to watch. When these files change, it will trigger a reload.
If you are using a tool like [pow](http://pow.cx) in development,
you may need to set the `:url` option appropriately.
live_reload: [
url: "ws://localhost:4000",
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex)$}
]
]
* `:pubsub_server` - the name of the pubsub server to use in channels
and via the Endpoint broadcast functions. The PubSub server is typically
started in your supervision tree.
* `:render_errors` - responsible for rendering templates whenever there
is a failure in the application. For example, if the application crashes
with a 500 error during a HTML request, `render("500.html", assigns)`
will be called in the view given to `:render_errors`. Defaults to:
[view: MyApp.ErrorView, accepts: ~w(html), layout: false, log: :debug]
The default format is used when none is set in the connection
* `:log_access_url` - log the access url once the server boots
### Adapter configuration
Phoenix allows you to choose which webserver adapter to use. The default
is `Phoenix.Endpoint.Cowboy2Adapter` which can be configured via the
following top-level options.
* `:http` - the configuration for the HTTP server. It accepts all options
as defined by [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/). Defaults
to `false`
* `:https` - the configuration for the HTTPS server. It accepts all options
as defined by [`Plug.Cowboy`](https://hexdocs.pm/plug_cowboy/). Defaults
to `false`
* `:drainer` - a drainer process that triggers when your application is
shutting down to wait for any on-going request to finish. It accepts all
options as defined by [`Plug.Cowboy.Drainer`](https://hexdocs.pm/plug_cowboy/Plug.Cowboy.Drainer.html).
Defaults to `[]`, which will start a drainer process for each configured endpoint,
but can be disabled by setting it to `false`.
## Endpoint API
In the previous section, we have used the `c:config/2` function that is
automatically generated in your endpoint. Here's a list of all the functions
that are automatically defined in your endpoint:
* for handling paths and URLs: `c:struct_url/0`, `c:url/0`, `c:path/1`,
`c:static_url/0`,`c:static_path/1`, and `c:static_integrity/1`
* for broadcasting to channels: `c:broadcast/3`, `c:broadcast!/3`,
`c:broadcast_from/4`, `c:broadcast_from!/4`, `c:local_broadcast/3`,
and `c:local_broadcast_from/4`
* for configuration: `c:start_link/1`, `c:config/2`, and `c:config_change/2`
* as required by the `Plug` behaviour: `c:Plug.init/1` and `c:Plug.call/2`
"""
@type topic :: String.t
@type event :: String.t
@type msg :: map | {:binary, binary}
require Logger
# Configuration
@doc """
Starts the endpoint supervision tree.
Starts endpoint's configuration cache and possibly the servers for
handling requests.
"""
@callback start_link(keyword) :: Supervisor.on_start
@doc """
Access the endpoint configuration given by key.
"""
@callback config(key :: atom, default :: term) :: term
@doc """
Reload the endpoint configuration on application upgrades.
"""
@callback config_change(changed :: term, removed :: term) :: term
@doc """
Initialize the endpoint configuration.
Invoked when the endpoint supervisor starts, allows dynamically
configuring the endpoint from system environment or other runtime sources.
"""
@callback init(:supervisor, config :: Keyword.t) :: {:ok, Keyword.t}
# Paths and URLs
@doc """
Generates the endpoint base URL, but as a `URI` struct.
"""
@callback struct_url() :: URI.t
@doc """
Generates the endpoint base URL without any path information.
"""
@callback url() :: String.t
@doc """
Generates the path information when routing to this endpoint.
"""
@callback path(path :: String.t) :: String.t
@doc """
Generates the static URL without any path information.
"""
@callback static_url() :: String.t
@doc """
Generates a route to a static file in `priv/static`.
"""
@callback static_path(path :: String.t) :: String.t
@doc """
Generates an integrity hash to a static file in `priv/static`.
"""
@callback static_integrity(path :: String.t) :: String.t | nil
@doc """
Generates a two item tuple containing the `static_path` and `static_integrity`.
"""
@callback static_lookup(path :: String.t) :: {String.t, String.t} | {String.t, nil}
@doc """
Returns the script name from the :url configuration.
"""
@callback script_name() :: [String.t]
@doc """
Returns the host from the :url configuration.
"""
@callback host() :: String.t
# Channels
@doc """
Subscribes the caller to the given topic.
See `Phoenix.PubSub.subscribe/3` for options.
"""
@callback subscribe(topic, opts :: Keyword.t) :: :ok | {:error, term}
@doc """
Unsubscribes the caller from the given topic.
"""
@callback unsubscribe(topic) :: :ok | {:error, term}
@doc """
Broadcasts a `msg` as `event` in the given `topic` to all nodes.
"""
@callback broadcast(topic, event, msg) :: :ok | {:error, term}
@doc """
Broadcasts a `msg` as `event` in the given `topic` to all nodes.
Raises in case of failures.
"""
@callback broadcast!(topic, event, msg) :: :ok | no_return
@doc """
Broadcasts a `msg` from the given `from` as `event` in the given `topic` to all nodes.
"""
@callback broadcast_from(from :: pid, topic, event, msg) :: :ok | {:error, term}
@doc """
Broadcasts a `msg` from the given `from` as `event` in the given `topic` to all nodes.
Raises in case of failures.
"""
@callback broadcast_from!(from :: pid, topic, event, msg) :: :ok | no_return
@doc """
Broadcasts a `msg` as `event` in the given `topic` within the current node.
"""
@callback local_broadcast(topic, event, msg) :: :ok
@doc """
Broadcasts a `msg` from the given `from` as `event` in the given `topic` within the current node.
"""
@callback local_broadcast_from(from :: pid, topic, event, msg) :: :ok
@doc false
defmacro __using__(opts) do
quote do
@behaviour Phoenix.Endpoint
unquote(config(opts))
unquote(pubsub())
unquote(plug())
unquote(server())
end
end
defp config(opts) do
quote do
@otp_app unquote(opts)[:otp_app] || raise "endpoint expects :otp_app to be given"
var!(config) = Phoenix.Endpoint.Supervisor.config(@otp_app, __MODULE__)
var!(code_reloading?) = var!(config)[:code_reloader]
@compile_config Keyword.take(var!(config), Phoenix.Endpoint.Supervisor.compile_config_keys())
@doc false
def __compile_config__ do
@compile_config
end
# Avoid unused variable warnings
_ = var!(code_reloading?)
@doc false
def init(_key, config) do
{:ok, config}
end
defoverridable init: 2
end
end
defp pubsub() do
quote do
def subscribe(topic, opts \\ []) when is_binary(topic) do
Phoenix.PubSub.subscribe(pubsub_server!(), topic, opts)
end
def unsubscribe(topic) do
Phoenix.PubSub.unsubscribe(pubsub_server!(), topic)
end
def broadcast_from(from, topic, event, msg) do
Phoenix.Channel.Server.broadcast_from(pubsub_server!(), from, topic, event, msg)
end
def broadcast_from!(from, topic, event, msg) do
Phoenix.Channel.Server.broadcast_from!(pubsub_server!(), from, topic, event, msg)
end
def broadcast(topic, event, msg) do
Phoenix.Channel.Server.broadcast(pubsub_server!(), topic, event, msg)
end
def broadcast!(topic, event, msg) do
Phoenix.Channel.Server.broadcast!(pubsub_server!(), topic, event, msg)
end
def local_broadcast(topic, event, msg) do
Phoenix.Channel.Server.local_broadcast(pubsub_server!(), topic, event, msg)
end
def local_broadcast_from(from, topic, event, msg) do
Phoenix.Channel.Server.local_broadcast_from(pubsub_server!(), from, topic, event, msg)
end
defp pubsub_server! do
config(:pubsub_server) ||
raise ArgumentError, "no :pubsub_server configured for #{inspect(__MODULE__)}"
end
end
end
defp plug() do
quote location: :keep do
use Plug.Builder, init_mode: Phoenix.plug_init_mode()
import Phoenix.Endpoint
Module.register_attribute(__MODULE__, :phoenix_sockets, accumulate: true)
if force_ssl = Phoenix.Endpoint.__force_ssl__(__MODULE__, var!(config)) do
plug Plug.SSL, force_ssl
end
if var!(config)[:debug_errors] do
use Plug.Debugger,
otp_app: @otp_app,
banner: {Phoenix.Endpoint.RenderErrors, :__debugger_banner__, []},
style: [
primary: "#EB532D",
logo: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJEAAABjCAYAAACbguIxAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAHThJREFUeAHtPWlgVOW197vbLNkTFoFQlixAwpIVQZ8ooE+tRaBWdoK4VF5tfe2r1tb2ta611r6n9b1Xd4GETRGxIuJSoKACAlkIkD0hsiRoIHtmues7J3LpOJ2Z3Jm5yUxi5s+991vOOd+5Z777fWf7CGXA79Ct46ZGmyPnshw9WaX5qTSlJBCKjqU51aoohKVUivaIRqUUmlactEK3iCp1gablTztsnZ9kbK16w2P7wcKw5AAJhKqiBWlzIyIjVrKsnKtQ7HiiqiaGZQOC5Qm/JAkiUekqSha2X7/x2JP1FOXw1G6wLDw4oPvFl94+ZVmkib9HJnQuy7MRfUW+qoqSLMtHWi60PzB9Z+2BvsI7iEc/B3wK0d8Wjk8dHRX7B5hjbqBZU6R+sMa3VBWFUiSxqLmhdc303XVHjMcwCDFQDngUosO3JF0VPzz2eSKRLJrjPLbxhVARYYXDUCKlKAJFMV00yw731d6fOlWVKadT/mjSxsIb/ek32Lb3OPANAdl/c3La8CExmziGnUYYz2thd1JwhpBk5RDDyBccTuWgKNpqWxzCsdk76iuwbdXiyd/nIqO2ufcL9lmVBZvgcP5k4pYTrwcLa7B/cBy4LESVeVlvsxS9wN+ZR1Jkioi2B5M3nPiTJ1LqVuXaCcuaPdUZUSbJjg9T1hXfZASsQRiBcYDULJ/2OM1zDxOa0zf1eMFDROmcQ5Jeam7peE+iKOfQ+IjFHM//gqF7T4A0UhD3dflHkusHd3EaS/r0SupWZO+lCHWFwislio2Kpi30cKKQZEKYGEL7L1e4ZqFkRSWs/2upYEauSpKjpblldvaOmkPBwBns6z8HLn/O3Lsenjs+N2pU7G94hr6JpjnevT4cn0GQ1HZb29JBZWXfvh2vQuRCBg2z1W5i4q9zKQvfW1mmOrrsy6duPb4pfIkcWJTp+V4p4zcUzrY72h9SJCX8R88wVGSEdWPZkskrw5/YgUGhnpno8khLbk9dHBMZu4Wimctl4XqjKCrV4ehcmbH5xAZXGsuWTLpFdSpylyC1t3RIjQfLv2h6pInqdG0zeO8fB/wSIgR9clnGw1aL5Un/0ISmtSorVJe97cYpb1R8pFFQtSzzBc5iXoPPMqyhCKOqlEycKqW2gHL0vCqRvR1S146srRX7tD6DV98c8FuIEFxlXnYxz/EZvkGHR60kSUrjVy1TZu2qKdMoqr4j8wOWMXvVeOMsJqlyB0vkfRdPtz42aGbROOf5GpAQIai61Tlgiw1Ot+SZJONLFUUU5q49GlPvokequStzM0OZl/SEDWczmLIq2mwdv8rcVvVOT+2/jfV6FtYe+SJQ9CseK8KwEFUUu1flNLqSlvxa8VKH0/msa5mnezT/EJ6fGBubsL1qdfahVxOj4z21+zaXBTwTIdNq7siVGIYN/1X2pTcsCY6alILiFNcXfmxR+qrICMsrIGica7m3e0WWRFWyP+zNzOOt30AuD3gmQqbAwnRPf2IOy5uTa1dlfuxK87Q3T64/V9o0RhLFBtdyb/c0w3KMKeqZyhVZu721+baVByVELS3tv+pvDANT3vUVt019xpXuWYVfNKbkHx0liM7tuKjW8+NNpjk1q6af/9vkcYa5uejBG45tgvqc4YCq83I6WY7rM09Ho5jY1n5xiSfzCOqRLBbrWormh+rBBYt20emw/yht88lX9bQfiG2CmomQIYqifN4fGRMZGb1p46QRY9xpT9tSvnPc2sJhotjxgiLLTvd692dcS1ms0a9U5uW85173bXkOWohssrSjPzKLAfXEjNzEclfa86cOH4aRK1iWmn/iR0nrDpslQdiqqKLo2s7TPc9xt1Tm5bafXDL1fk/1A7ks6M/Z7mmJo8ZmjDpLs0HLY0j4jAtqXA8hclzfjM+M/7ugCqUTNxxf7EIQe3LFlGdZYlrC89wQl3KPt7IoXJAVeqfU1b4lfXvlB66Ntt88OmnikJhFxEbH7zt+4el7qxouuNb3x/ughQgHXZU3vZPjmH63LtJemCRIx1IKjnRr4E8unHCTJTZ2l6jIdRPWH03S2mjX0vmp3zVbI+6jeeYqQjGxPf15upWVYFNBPytCE4jAU0WiKC2CxHz44aHa+++vaW7XYPfXqzFCtHz6Kc7MjO2vTEC6FcX5XtLaonl4j4JkjY/fJUO0UofofCBzc+lzWO7+++yWpMnDYyMXixQ7nefIBAjFjCZEtUA7FvTcDAM7PZUhqqLS4OyptqhELBEd4sa0LScK3GH152dDhKhmedZ+xmy6pj8zAmmXFfHl5LVH78X76vkTfsAOid+K9+h+2253/EKvj9IPR1LW5fEjEzY2N1x8uYGyIYxgfwe/m3JldBSXwUhsMmdhR6gmlVFE9UvJQVU7VMeJUBqMDRGiyhW563gTuypYRoVD/06b8NSUzYUPIy0YqcKazW9prr4oTJIsrE3eeOw/e5tWnOVi46z3WhjTXIUm42iKNnt1V4ZgCZjuHLIqldrt0p/1CrtRYzBEiMpXZDxiNll+ZxRRoYYjO2xPaIKCbsJxo4fsZxnGrNGFBl14bcVSl1yQ9mYJ2hAhvi74H35G+cjIOxWKzOYYZojesC13zIIk1rWdbV7SV94HhggR2p+io6LXuQ+mPz/bHfYn0zaW/AbH8MhQKnLZTbnlHM8muo+JyJIsqmoDuCaVU4rzI8Uhnjxc/OWh1fWtre5tXZ9xVzs0Ne5as4WZrlDMbI6iU2iOxfWUIT8VTHyCKP9u4qbixw0B6AOIIUKkLUR94OmXVXab49W0zcX3aMR3x+Yx/EKa9s02FCxYU4sQ8yIwtGSTZGJHGDRLWWSFtcLim4f9Gs+yva8XcQqdz00sOP4zbQy9cfXNDZ0YcdE3fHj8Ia/fbJ1wwrGZ6LTtSN1w7FaNtuOLJ/5rpDVig16ziNYvlFdvJh6jaOqfGkKjRq8DDmeyzqtbmX1Zs42utmgWcbZ2/QnSlTh0gAh5k8iImI29SYQhQoQ2SAr0aAP1h05paGg+sWhitx4JxzlxW+mDKesOW9DGJshSR6jHjv7i3mhAn6+qpZk7vdUHW27I5wxtTtdkjWkA9VrYOqih5lhQpFJVkbfbZaUyyuYUO62mRCvDzuNYMoMwvLUnZn6dvEJ6KzW/8Hb3tjUrJj8AMNaAFns85B4whK/uOLRnRQTHcVWqVwh3UHYIn6uivbZVkM7yFjbJyloywI63EN7EFML8Y82F4V7791XG9bTg13D4czVksOEuROiN2NLWNidne9Wn3phTtiLzVRPN3KknoQVkzGlz2OwPpb9R9pI7vP3ZY0YMGR/zM85ims8Q6jtGJbNAtQJYTqpE1bFpUsGJpwGvzyBAtAOOzorfBgEVV2s0uipTtTIjroYIUbcRNvuK0zQJP8d9zFrS0dl+nR6NLuqEYkYl7OY5NkoPc0X498s222OTtp1EXZHH3/GFk25gIyw3w7phGsXQYymVDCUU7MwYiqMU0s1/lIbudQUDzwqoDVFHrqgCTOunZUqusovC2+7xcx6ReSgsWzTlZ+ZIy39DbgUK0vE0jV9XOMxDs6CKDBGitWNjY6+ZlXKB4cLP3xomoYbk9V9b6fVyqvaOnHqa4cbobY8vxympG/YfPv97vVZ5nL2ThltGMhZyeUZRRIYRz9guXHui4Yxe3HradQedRidswU96/s7Po4wO1jREiHAgdXfmOAjhTHoG1Zdt0OV1Qn7R9/3FWbUyq4jjTZn+9MMYN0LJpwVZ3c112D5I+WvlW/707822WtCmvbP1vrQ3yv9iJC7DhKhq1ZVtHEtHG0mcEbCCUbZVrZy6jeMj/BZAjW70AiCM0qnI9JegYHTSKjFJolSTurl4IbQxxFSi4dJzxYRjsIcrSc0/MlNPe71tDNnidyNTlLD0i6EJ/0+mCr3MSS0ovc3W2bYGdkPdGme9/bR2+HmnaT6G5dhUCBKZAnvw0QorVUE9uIb0/U9S7WtZosYYjZk1CiCjyhAc+M+2JaPgBwqHZugZgfbFfpd2YC/V5GW9D9v3G8C+5RfPcDsuU9RRsaP9UXcvx2DoCqRvU2PnywmJVuMmjktEGPY5q1s1rYCw1hWBDK43+2Am250H6mKN8CAcS1HmD1ZOeYol3DzwaExUVdbkyY4GubedlKie6pKo7fM2Fz5W7xK+3Ztj1QkbhejyYl5nH5/NDBOiikVpa0xRMS/4xBaiStQqo+O90egP35oyK9JqGqPS7GgTeDR2KOpFkypWY8SI0bjCGZ5hQoRKtsSpVzSEoxEWbVxoogjnF9GfaTNMiJAJvb1DU2UJwtxAXQfmFU+fEV8vwuG0PzppQ8kjvtqEYx266UrRXApR2RRCkUTw9rfAuToyHMDDKERtpmS5pNPpKMp9q/KvoaLfUCGqzMvYx3OWWUYORpLEM6oqvS122D+4UN1xsq7T1pGenpAWHRN5K01Mi/UGCOACNyn/iK6kDUbS7y8sNPJyZutqnqZmKoRO0JtoApSqqDKoVFXnxpT842gW6bOfoUJkpIcjWqVFxf5rsBM95YsbR34wYX6cNfJVhuN7jAdzCo59EwuKr/MFLxR1Y2HB/uGK3BdZTlmAKoFgacBgS0mit0zIP5wXLCw9/Q0VIkRYuypXhLM8/NoGeyLU2dVxlz9HLmC2D0zW4AmWa1lHe2fYZJZFc9Gs2eMLCKFvAm2/XzzDODb4qAk0kbp1TiohrAofejjiC/LPX9rFC6Iqs9QrEMFyH/Cg13RThgtR9cqsz1jedJXri/P3Xpac9cnri8b52w8t8RaT+S5f/XBddfb4V4mYCcRXu96uQ1rNPLPKH+FR0K6iSkWdorwZ/mR7Zrx7qtSFThoScMWOHh8XMzLBmsxwplQ+klkNm/mhXTbHbzGFjktbQ28NFyI8oWjoFcM+C4ZKm93+6/RNJb8PBEb58mmPms3W3/rqK4pyV2r+4ZAcvYWpkU1m8/+AgVf3Z0sGn20wnr696+CpuwPRd2F2t7vPtjf74kkwdYYLERKDeXvAmW54oIS12ZvnZGyq3Btof83Y6Ks/+Oc0J609muCrjZF16N8zNjPufYY3ZfkDV1aFwvrDzbdcf+LUl/7068u2fn2H9RLW0tV275CY+ICTZEp2VdSLy1O71E3F/1a1Ytoo9I/2VI9lsOuJr12dc3H/3pqk3vD2c8VbtjTzFRPP3uHPWhHdSzpsjgf9+Qx1H6URa8kgVjqNU7mhAk1FgXdSE22XWxy8cszW6jh51a6aYlfajLjvlZkICTuVl9NAcdyIQIhsbb240IhMrTV5OccZjpvsiwZURDrs7fNdc137ao8OeFFjLEnT363e76sdfkKuuibpaTPPrvDHu1EW5Xan0/mX9DeO/coXfK2uaOnUpVaWuZejSTZk843sSdkrgj88ZJeoUJ32Fye+WfaiBieYa68J0Wc3jM0Y+Z0RAUm9e7xXMAOsyZvexnCMTxeV7qNBKflyHL4vfHiw4BVD416jCRmnggZQkZWzhBJr4R/vlAlrg8wfQ3mangauiqP1enriwTaCSmpkwfG/6VtKn/eFX6srvy39Hi4y4vFglg2YxEsUxCcgwPEJDW4g114TIiSmdnXWDpo2fc9fwsCH+XzS2sKAZjF3XC+ljhxy/b+M/FLPC0UvyPY2W17WO2U9JfVkIe/jU6yVW6TSdKK/QYiqgnGNik0SmQrZ4dxbfKLp/5aXN37hTrunZ5wJvzNtxB50L/FU76kM13+gbH2v1WF/W7VLTSxnspis/JUmhr5NUdh40tn2YDAOdL0qRDggzB6m12dZYwDODAcPnR6rl7FaP29X1AJHRMW9663etRxxy7JwuLGpY7VrFn7XNu73JcsmzDbRlmsZmeSqHD2SAidprQ3ogOw0JbfQRL5oF0m5U1VONR/v2BPIQrlsefoveM76e3/SPjud9rUTN5TcqdHj6YqCOffY2XOe6vSUXR6snsaBtMETrcdHJ1T4G0YD/9BPkjcWGWZCqcrLeA6yK/673jHIqKijSKHN1vakEeszvXi9tatcPmUTb45c6q3evRz/DA5H5z19kZC014UIB1e2NP1uTI7pPlCfz3Bu2UcHzg7V6/juE9alyupVmQfgONqZetq6tsHPgSyre5wdtpenbC//2LXOqHuczd75uPKIJyf6QOh2tLb/0FcUyt55YycOi7TOZNSvEwtA7s1aPRExnsbbJ0KEiDF3tCk24gFPRHgrc4py9cT8w7q//d7guJYHs2tEOKiohN1NOVGEUggCeOfcefuJG/d/ccoVh5573L3NzB0x3RJtXi6ppoWQ+OGLgp1FV7oLUc3KrEJ/dUvePBZQBRA7LOYRxkxfDUe0Rmt5l7rpxRxHRHGCD1+F0yH80Z8cR30mREho1fLM5zmz+Sd6mKy1sXd0/kfam8ef1Z6NuNbdkd2lJ+JVDy70nKSI0gX/505RZZqJIrdCfqEmVRWcsIPr1sMRlhcVSTXD+mg47OiGQXhZDFTEqpeOtMBt95Ej5ya4rwErV+Ye4Xk2Rw8dWhvB0bl5wsbjy7RnvKIVIT5h6HaGI7pjzmCTcRxCrVAx2qPNrU+FCAd0cknG73gL/wir8+A9zLNTfaopKZB/O+Lz9EMHulGTh532R/nnCY4RZbLorE3OL0p2hxWIW43qFP6Op2S6w8IASlOk5WmQdhqickeBX1KCnkhfUHjaGptar7x6Z+0Jd5iuz30uRIgc09hRJvMmjtMXp4YnTc9ZfySu3kBf5cJ5yTPihsR+FsrjtgSnc8+EDUVzXV8I3mNQABhQb3Yv9/UsCNLRCQVHcn210epwszM6KvYPNGHm96SewLCnpgutV898v/pzrb/7NSRChERgcsxfzs0uxIwb7kR5eobptXXD+0dHu68ZPLXVW4bTfNyQ+E96YqReeHrboSeB3SE+lr6l5FH3PoEEPHibgdxhuz/vuCExZdLIkZ/0pLBEA/AXxY1jvKkBQiZE2oDQ6s6x3C8hLovXyrxdMf6rtaVlTvaOmkPe2vhbjovN+MT4T/Xg9xe2p/b4+Spv/OrmeR+frXavDySBqt3peC1tQ/Hd7rD8edZjHkLtdlNz03Q395NuNCEXokuDZcvzsraxhPleT7OCih41qvP51PySn/rDKF9tUdkGQQYlerLl+4Ljq04QpQ74LP/Rm4mhekXGetZk0e2JCCcBdHXZ2+/ydMiNLzq81ek5khXTCNrsnfe7h2GHRIhqV2RtQAvzpPyi+a6DwgNbcrOHga+N+UZIreNzZsKMHJJof9jIxOIVKzP/buLN17rSFOw9mNQ6HYK4Ln3Dca+7UvgD/dXMmS6n9POJE5SgDqLscOedax+c0RhemSyLlB08IKsdsrTHwvHfx5wExbdm326NoZZPKChc4NoH74GOg0BHj8GeuHMTnI5nzjR0fFp/XuwIiRBholBzbNwuyBvU0FDUMMNTFoyy5RlP8DSzElKRj2YgXb37gC8/y87zTkFef7a0/dlATAmX4Vy6wQwaUdaYP8POLWB/qG4HREWt7pKEF71l49fwYio/PetCXJfIinKoqvHL1Z4+hRo8vKJ2Hs4huZ+wNLG3dz3DmLlUnufnj3vtIKlZlXMOPt0j8d61j3ZftXzaa6CQXY19tTJvV/DlVhw26bEeG3oDEGw5OtijzxEkXgJ7q7gudeMxj26t3ZrVmKj7TLTpOkJIErg6WLy5O6AbBbgAnmJU54Zgj9fEvD6syXQv6HrA1dR3yhxcKKu0bANdUBmRlY++OHHxRW+LUI1v5Usn/5znLY+DsFq0MvcrWvchQqoRkhZt37u75rf+eCeiioBWuWw4sySyenXOFpbmFquCUAG+2BPgEHfq+oKj1novu11MxD4kPvYFjqZzwPHqG0nYUS8G1mMbZD+pFBTnG3/7vPHFkAkRMszVlRU1wZCt/jktd7Q7Q7Vn3JrTkdYZVsaUQdFyNOg8INQd5is4RoMGDZ9EMZLd2bbLqLUC5rBePCt9KYmOyIY1wTCwwIugFuBoRemQiFThlKgzpSebPsor/fIrjUYvVxr0NXMjovk8WeUWuh80iMm4OPj2SApzUaSEOiKp75e3XNi0cNeZWi/wfBZXrcypAKVmEoZJVa7M/oTlyFXdngzwOVRoqu1Ue/OV12+vw+QSPn/IbytvmiIR1gwa7YtfSV1H3fuFVIiQend3EVUWbaJEth74tPqnRnscfjhrzLjEkXF5LA/+PpSSAAkavoLPRNn59rbNs3fUV/jkZpCVOKOOiI170cTAQTLwg7nrNBw5dBoOFGnsghONlE7bodt21JTUe5kd/EWP6xueIZPApSYWTSegKQfNs/Q2CKmFZbkft7W1LfCVftAffCEXIiQW/imwM+Lhxf7jh2sAilZKhC7b6+67gX+06vkO/YnmZI/4JTHTi2mFHuXtW48KTYck/ldPM2HPGL22wI0CBhj2yQ/HnWyhTfhZ3Td55Ojq1s4u7XOIBwO+fvRUjVGH14SFECFXcfrleK77X+rOZZjjBULEGkhk+LkiObcVH2s94W5n0vog865Kj8lkIsyLzTR7DXgaJvnKagvCI6m0coHIdLtDFrf2ohBpJA64a9gIEXJW704FF3eEhu0roRzgCGbHvuA4bGJpxQzJNa16vBhReOwO4U96fZkRx+DPMwfCSoiQRNiClsIWdIpncg0qlWW5tu1CmvsC0SDo3zowl+Jtw2fc4H4wFQ2TvUmRCruTQQEyjsNhJ0Q4NLRsi6L9zzpcWQLiBCT9jUdvy4A6D3b6Jw6E3efMlcLi21IXREbFbnY9sM61Pph79EEWRNubX5W3/zTUcfnBjCMc+oa1EF1iEF+Tl1sEWuP03mAYqu7BqHsKZqdDHc7OHbZOpWrZrpryeoP0Nb1Bc7jB7A9C1M0z9Ig0W9iHIfzZp2E2WAbjDKVSYECRaYEBtbGsgm8Bo0CkDy3CQXcXVFUpkxSpvKK5OT9QbXKwNIZb/34jRJcYx4JNaDdP87NA9xNSXqJdC+wsLaD5PnDxq7anpu+sPRBSgkKIvL8JUTer0CMRDISvEZaZCKkLQ8i+r1Hj7KXIYm2LrevnocydGCpG9Esh0piFsVoRTMQTkAcUzivT0oNptaG5gvXkYMr64qCSfIWG8sCx9msh0oaNJ/bMmHLFU7BcgjPGSEJvzU5oaWcUOEtKwUOBARPtWUOCRuTGppYeoyQ0+vv7dUAIketLQNeFyLj4H0Es2NUwNyX6sxDH0GnI5iECU2yQ//AcIVKjSHO1YofzJMU4K+0XhJb2aKoN8VkddERUNDuUoUgyy/LZkBA9FRIjTwJfnTjNxbe1SViU+W7hVlf6BuL9gBMi95eEXpR8FD+NIfRkQaFHw0vvTkNM06pNoZmLquxophWqrl2mz3W22o7pTeLgjkd7xoxoIybHrDHxzI8hiDGq9VzzNdN31x3R6gfidcALkZEv7cDNyZmxUZbrBNXZ8Pmxzt095QlAAcazWXsK/jOSxlDAGhQiP7iOkaSWePOdRGZmghfBKAJZrWSacmBKOzgbsxFcaY/YHLZ39WZd8wN1WDcdFKIAX0/Zooz7OAv7EHgJjnYHAX5P7USRPty3t3qN5gjm3mYgPQ8KUZBvs2hB2tzouIh1kIE80R0UhiBDvNnatM3F97jXDaTnQSEy6G1WrMh43WSyrPYEDqMsxhcUTvJUNxDKBoXIwLdYsnTyimizeb2nJBGSIJxKKSgcbyC6sAE1KEQGvwp0gh86JOEouOh2qxJcwQuiUDIhvzDTtWwg3HtWuQ6EkYVoDJjw4PyZC9PRQOtOAs/xGRXLpv3Bvby/Pw8KUS+8was/ri+52NW+UJHAPuL2482mhzAixa24Xz8OClEvvT605jd3tS6ApKHfOGKCEIaaM3NkUS+hDQnYQSHqRbajIH1WeCZRFaVvhCujbqlmdc5LvYi6T0EPLqz7iN14Wjdtivg1C0eha9Z/OB/x0P49lbf0d4XkoBD1kRBpaNChLiYhYY2JUufIrDpCEkkR5FrE3No9ZmnVYITb9f8BhSZnYemqCy4AAAAASUVORK5CYII="
]
end
# Compile after the debugger so we properly wrap it.
@before_compile Phoenix.Endpoint
end
end
defp server() do
quote location: :keep, unquote: false do
@doc """
Returns the child specification to start the endpoint
under a supervision tree.
"""
def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [opts]},
type: :supervisor
}
end
@doc """
Starts the endpoint supervision tree.
All other options are merged into the endpoint configuration.
"""
def start_link(opts \\ []) do
Phoenix.Endpoint.Supervisor.start_link(@otp_app, __MODULE__, opts)
end
@doc """
Returns the endpoint configuration for `key`
Returns `default` if the key does not exist.
"""
def config(key, default \\ nil) do
case :ets.lookup(__MODULE__, key) do
[{^key, val}] -> val
[] -> default
end
end
@doc """
Reloads the configuration given the application environment changes.
"""
def config_change(changed, removed) do
Phoenix.Endpoint.Supervisor.config_change(__MODULE__, changed, removed)
end
@doc """
Generates the endpoint base URL without any path information.
It uses the configuration under `:url` to generate such.
"""
def url do
Phoenix.Config.cache(__MODULE__,
:__phoenix_url__,
&Phoenix.Endpoint.Supervisor.url/1)
end
@doc """
Generates the static URL without any path information.
It uses the configuration under `:static_url` to generate
such. It falls back to `:url` if `:static_url` is not set.
"""
def static_url do
Phoenix.Config.cache(__MODULE__,
:__phoenix_static_url__,
&Phoenix.Endpoint.Supervisor.static_url/1)
end
@doc """
Generates the endpoint base URL but as a `URI` struct.
It uses the configuration under `:url` to generate such.
Useful for manipulating the URL data and passing it to
URL helpers.
"""
def struct_url do
Phoenix.Config.cache(__MODULE__,
:__phoenix_struct_url__,
&Phoenix.Endpoint.Supervisor.struct_url/1)
end
@doc """
Returns the host for the given endpoint.
"""
def host do
Phoenix.Config.cache(__MODULE__,
:__phoenix_host__,
&Phoenix.Endpoint.Supervisor.host/1)
end
@doc """
Generates the path information when routing to this endpoint.
"""
def path(path) do
Phoenix.Config.cache(__MODULE__,
:__phoenix_path__,
&Phoenix.Endpoint.Supervisor.path/1) <> path
end
@doc """
Generates the script name.
"""
def script_name do
Phoenix.Config.cache(__MODULE__,
:__phoenix_script_name__,
&Phoenix.Endpoint.Supervisor.script_name/1)
end
@doc """
Generates a route to a static file in `priv/static`.
"""
def static_path(path) do
Phoenix.Config.cache(__MODULE__, :__phoenix_static__,
&Phoenix.Endpoint.Supervisor.static_path/1) <>
elem(static_lookup(path), 0)
end
@doc """
Generates a base64-encoded cryptographic hash (sha512) to a static file
in `priv/static`. Meant to be used for Subresource Integrity with CDNs.
"""
def static_integrity(path) do
elem(static_lookup(path), 1)
end
@doc """
Returns a two item tuple with the first item being the `static_path`
and the second item being the `static_integrity`.
"""
def static_lookup(path) do
Phoenix.Config.cache(__MODULE__, {:__phoenix_static__, path},
&Phoenix.Endpoint.Supervisor.static_lookup(&1, path))
end
end
end
@doc false
def __force_ssl__(module, config) do
if force_ssl = config[:force_ssl] do
Keyword.put_new(force_ssl, :host, {module, :host, []})
end
end
@doc false
defmacro __before_compile__(%{module: module}) do
sockets = Module.get_attribute(module, :phoenix_sockets)
dispatches =
for {path, socket, socket_opts} <- sockets,
{path, type, conn_ast, socket, opts} <- socket_paths(module, path, socket, socket_opts) do
quote do
defp do_handler(unquote(path), conn, _opts) do
{unquote(type), unquote(conn_ast), unquote(socket), unquote(Macro.escape(opts))}
end
end
end
quote do
defoverridable [call: 2]
# Inline render errors so we set the endpoint before calling it.
def call(conn, opts) do
conn = %{conn | script_name: script_name(), secret_key_base: config(:secret_key_base)}
conn = Plug.Conn.put_private(conn, :phoenix_endpoint, __MODULE__)
try do
super(conn, opts)
rescue
e in Plug.Conn.WrapperError ->
%{conn: conn, kind: kind, reason: reason, stack: stack} = e
Phoenix.Endpoint.RenderErrors.__catch__(conn, kind, reason, stack, config(:render_errors))
catch
kind, reason ->
stack = __STACKTRACE__
Phoenix.Endpoint.RenderErrors.__catch__(conn, kind, reason, stack, config(:render_errors))
end
end
@doc false
def __sockets__, do: unquote(Macro.escape(sockets))
@doc false
def __handler__(%{path_info: path} = conn, opts), do: do_handler(path, conn, opts)
unquote(dispatches)
defp do_handler(_path, conn, opts), do: {:plug, conn, __MODULE__, opts}
end
end
defp socket_paths(endpoint, path, socket, opts) do
paths = []
websocket = Keyword.get(opts, :websocket, true)
longpoll = Keyword.get(opts, :longpoll, false)
paths =
if websocket do
config = Phoenix.Socket.Transport.load_config(websocket, Phoenix.Transports.WebSocket)
{conn_ast, match_path} = socket_path(path, config)
[{match_path, :websocket, conn_ast, socket, config} | paths]
else
paths
end
paths =
if longpoll do
config = Phoenix.Socket.Transport.load_config(longpoll, Phoenix.Transports.LongPoll)
plug_init = {endpoint, socket, config}
{conn_ast, match_path} = socket_path(path, config)
[{match_path, :plug, conn_ast, Phoenix.Transports.LongPoll, plug_init} | paths]
else
paths
end
paths
end
defp socket_path(path, config) do
end_path_fragment = Keyword.fetch!(config, :path)
{vars, path} =
String.split(path <> "/" <> end_path_fragment, "/", trim: true)
|> Enum.join("/")
|> Plug.Router.Utils.build_path_match()
conn_ast =
if vars == [] do
quote do
conn
end
else
params =
for var <- vars,
param = Atom.to_string(var),
not match?("_" <> _, param),
do: {param, Macro.var(var, nil)}
quote do
params = %{unquote_splicing(params)}
%Plug.Conn{conn | path_params: params, params: params}
end
end
{conn_ast, path}
end
## API
@doc """
Defines a websocket/longpoll mount-point for a socket.
## Options
* `:websocket` - controls the websocket configuration.
Defaults to `true`. May be false or a keyword list
of options. See "Common configuration" and
"WebSocket configuration" for the whole list
* `:longpoll` - controls the longpoll configuration.
Defaults to `false`. May be true or a keyword list
of options. See "Common configuration" and
"Longpoll configuration" for the whole list
If your socket is implemented using `Phoenix.Socket`,
you can also pass to each transport above all options
accepted on `use Phoenix.Socket`. An option given here
will override the value in `use Phoenix.Socket`.
## Examples
socket "/ws", MyApp.UserSocket
socket "/ws/admin", MyApp.AdminUserSocket,
longpoll: true,
websocket: [compress: true]
## Path params
It is possible to include variables in the path, these will be
available in the `params` that are passed to the socket.
socket "/ws/:user_id", MyApp.UserSocket,
websocket: [path: "/project/:project_id"]
## Common configuration
The configuration below can be given to both `:websocket` and
`:longpoll` keys:
* `:path` - the path to use for the transport. Will default
to the transport name ("/websocket" or "/longpoll")
* `:serializer` - a list of serializers for messages. See
`Phoenix.Socket` for more information
* `:transport_log` - if the transport layer itself should log and,
if so, the level
* `:check_origin` - if the transport should check the origin of requests when
the `origin` header is present. May be `true`, `false`, a list of hosts that
are allowed, or a function provided as MFA tuple. Defaults to `:check_origin`
setting at endpoint configuration.
If `true`, the header is checked against `:host` in `YourAppWeb.Endpoint.config(:url)[:host]`.
If `false`, your app is vulnerable to Cross-Site WebSocket Hijacking (CSWSH)
attacks. Only use in development, when the host is truly unknown or when
serving clients that do not send the `origin` header, such as mobile apps.
You can also specify a list of explicitly allowed origins. Wildcards are
supported.
check_origin: [
"https://example.com",
"//another.com:888",
"//*.other.com"
]
Or to accept any origin matching the request connection's host, port, and scheme:
check_origin: :conn
Or a custom MFA function:
check_origin: {MyAppWeb.Auth, :my_check_origin?, []}
The MFA is invoked with the request `%URI{}` as the first argument,
followed by arguments in the MFA list, and must return a boolean.
* `:code_reloader` - enable or disable the code reloader. Defaults to your
endpoint configuration
* `:connect_info` - a list of keys that represent data to be copied from
the transport to be made available in the user socket `connect/3` callback
The valid keys are:
* `:peer_data` - the result of `Plug.Conn.get_peer_data/1`
* `:trace_context_headers` - a list of all trace context headers. Supported
headers are defined by the [W3C Trace Context Specification](https://www.w3.org/TR/trace-context-1/).
These headers are necessary for libraries such as [OpenTelemetry](https://opentelemetry.io/) to extract
trace propagation information to know this request is part of a larger trace
in progress.
* `:x_headers` - all request headers that have an "x-" prefix
* `:uri` - a `%URI{}` with information from the conn
* `:user_agent` - the value of the "user-agent" request header
* `{:session, session_config}` - the session information from `Plug.Conn`.
The `session_config` is an exact copy of the arguments given to `Plug.Session`.
This requires the "_csrf_token" to be given as request parameter with
the value of `URI.encode_www_form(Plug.CSRFProtection.get_csrf_token())`
when connecting to the socket. It can also be a MFA to allow loading
config in runtime `{MyAppWeb.Auth, :get_session_config, []}`. Otherwise
the session will be `nil`.
Arbitrary keywords may also appear following the above valid keys, which
is useful for passing custom connection information to the socket.
For example:
```
socket "/socket", AppWeb.UserSocket,
websocket: [
connect_info: [:peer_data, :trace_context_headers, :x_headers, :uri, session: [store: :cookie]]
]
```
With arbitrary keywords:
```
socket "/socket", AppWeb.UserSocket,
websocket: [
connect_info: [:uri, custom_value: "abcdef"]
]
```
## Websocket configuration
The following configuration applies only to `:websocket`.
* `:timeout` - the timeout for keeping websocket connections
open after it last received data, defaults to 60_000ms
* `:max_frame_size` - the maximum allowed frame size in bytes,
defaults to "infinity"
* `:fullsweep_after` - the maximum number of garbage collections
before forcing a fullsweep for the socket process. You can set
it to `0` to force more frequent cleanups of your websocket
transport processes. Setting this option requires Erlang/OTP 24
* `:compress` - whether to enable per message compression on
all data frames, defaults to false
* `:subprotocols` - a list of supported websocket subprotocols.
Used for handshake `Sec-WebSocket-Protocol` response header, defaults to nil.
For example:
subprotocols: ["sip", "mqtt"]
* `:error_handler` - custom error handler for connection errors.
If `c:Phoenix.Socket.connect/3` returns an `{:error, reason}` tuple,
the error handler will be called with the error reason. For WebSockets,
the error handler must be a MFA tuple that receives a `Plug.Conn`, the
error reason, and returns a `Plug.Conn` with a response. For example:
error_handler: {MySocket, :handle_error, []}
and a `{:error, :rate_limit}` return may be handled on `MySocket` as:
def handle_error(conn, :rate_limit), do: Plug.Conn.send_resp(conn, 429, "Too many requests")
## Longpoll configuration
The following configuration applies only to `:longpoll`:
* `:window_ms` - how long the client can wait for new messages
in its poll request, defaults to 10_000ms.
* `:pubsub_timeout_ms` - how long a request can wait for the
pubsub layer to respond, defaults to 2000ms.
* `:crypto` - options for verifying and signing the token, accepted
by `Phoenix.Token`. By default tokens are valid for 2 weeks
"""
defmacro socket(path, module, opts \\ []) do
module = Macro.expand(module, %{__CALLER__ | function: {:__handler__, 2}})
quote do
@phoenix_sockets {unquote(path), unquote(module), unquote(opts)}
end
end
@doc false
@deprecated "Phoenix.Endpoint.instrument/4 is deprecated and has no effect. Use :telemetry instead"
defmacro instrument(_endpoint_or_conn_or_socket, _event, _runtime, _fun) do
:ok
end
@doc """
Checks if Endpoint's web server has been configured to start.
* `otp_app` - The OTP app running the endpoint, for example `:my_app`
* `endpoint` - The endpoint module, for example `MyAppWeb.Endpoint`
## Examples
iex> Phoenix.Endpoint.server?(:my_app, MyAppWeb.Endpoint)
true
"""
def server?(otp_app, endpoint) when is_atom(otp_app) and is_atom(endpoint) do
Phoenix.Endpoint.Supervisor.server?(otp_app, endpoint)
end
end
| 44.978836 | 10,138 | 0.732643 |
03310fcaf91610b63b0b41324fdddd442a4460f5 | 1,213 | ex | Elixir | lib/cloak/crypto/interface.ex | predrag-rakic/cloak | dd91e941936cf93cbc7ca83941944a3501adde62 | [
"MIT"
] | 475 | 2015-09-19T14:09:11.000Z | 2022-03-28T14:53:27.000Z | lib/cloak/crypto/interface.ex | predrag-rakic/cloak | dd91e941936cf93cbc7ca83941944a3501adde62 | [
"MIT"
] | 98 | 2015-12-16T03:53:48.000Z | 2022-03-24T22:34:56.000Z | lib/cloak/crypto/interface.ex | predrag-rakic/cloak | dd91e941936cf93cbc7ca83941944a3501adde62 | [
"MIT"
] | 67 | 2015-10-21T11:56:38.000Z | 2022-03-18T13:51:16.000Z | defmodule Cloak.Crypto.Interface do
@moduledoc false
@type cipher :: atom
@type key :: iodata
@type iv :: iodata
@type aad :: iodata
@type plaintext :: iodata
@type ciphertext :: iodata
@type ciphertag :: iodata
@doc """
Alias for `:crypto.strong_rand_bytes/1`.
"""
@callback strong_rand_bytes(non_neg_integer()) :: binary()
@doc """
Alias for `:crypto.crypto_one_time/5` with `opts[:encrypt]` set to `true`.
"""
@callback encrypt_one_time(cipher, key, iv, plaintext) :: binary()
@doc """
Alias for `:crypto.crypto_one_time/5` with `opts[:encrypt]` set to `false`.
"""
@callback decrypt_one_time(cipher, key, iv, ciphertext) :: binary()
@doc """
Alias for `:crypto.crypto_one_time_aead/7` with `encFlag` set to `true`.
"""
@callback encrypt_one_time_aead(cipher, key, iv, aad, plaintext) :: {binary(), binary()}
@doc """
Alias for `:crypto.crypto_one_time_aead/7` with `encFlag` set to `false`.
"""
@callback decrypt_one_time_aead(cipher, key, iv, aad, ciphertext, ciphertag) ::
binary()
@doc """
Converts a cipher name to a supported cipher name, depending on the crypto library.
"""
@callback map_cipher(atom()) :: cipher
end
| 28.209302 | 90 | 0.661995 |
033161dcb0713e60502d918dc0ecc9cabd576e40 | 2,589 | exs | Elixir | test/callisto/properties_test.exs | mkompanets/callisto | a6dd6eabdd561feb7a8d727cc4890ba891ae5b62 | [
"Apache-2.0"
] | null | null | null | test/callisto/properties_test.exs | mkompanets/callisto | a6dd6eabdd561feb7a8d727cc4890ba891ae5b62 | [
"Apache-2.0"
] | null | null | null | test/callisto/properties_test.exs | mkompanets/callisto | a6dd6eabdd561feb7a8d727cc4890ba891ae5b62 | [
"Apache-2.0"
] | null | null | null | defmodule Callisto.PropertiesTest do
use ExUnit.Case
alias Callisto.{Properties, Type, Vertex}
doctest Type
doctest Properties
test "defines properties on label struct" do
med = %Medicine{}
field_names = Map.keys(med)
assert field_names == [:__struct__, :dose, :efficacy, :id, :is_bitter, :name]
assert Medicine.__callisto_properties.name == "Medicine"
assert Properties.__callisto_properties(med).name == "Medicine"
assert med.dose == 100
end
test "defines properties on relationship struct" do
relationship = struct(HasMedicine)
field_names = Map.keys(relationship)
assert field_names == [:__struct__, :amount]
assert HasMedicine.__callisto_properties.name == "has_medicine"
assert Properties.__callisto_properties(relationship).name == "has_medicine"
end
test "can verify field config" do
assert Medicine.__callisto_field(:dose) == [type: :integer, default: 100]
assert Medicine.__callisto_field(:name) == [type: :string, required: true]
end
test "defaults id type to :string" do
assert Medicine.__callisto_properties.id == :string
end
test "can pass ID config as parameter" do
defmodule PropertyTestFoo do
use Callisto.Properties
properties [id: nil] do
field :foo, :string
end
end
assert is_nil(PropertyTestFoo.__callisto_properties.id)
assert Map.keys(struct(PropertyTestFoo)) == [:__struct__, :foo]
end
test "can work without ID config parameter" do
defmodule PropertyTestBar do
use Callisto.Properties
properties do
field :foo, :string
end
end
assert PropertyTestBar.__callisto_properties.id == :uuid
assert Map.keys(struct(PropertyTestBar)) == [:__struct__, :foo, :id]
end
test "ID config 'false' doesn't set id in struct" do
defmodule PropertyTestBiff do
use Callisto.Properties
properties id: false do
field :foo, :string
end
end
assert PropertyTestBiff.__callisto_properties.id == false
assert Map.keys(struct(PropertyTestBiff)) == [:__struct__, :foo]
end
test "can pass a function as a default" do
defmodule PropertyTestFuncDefault do
use Callisto.Properties
properties id: false do
field :foo, :string
field :lower, :string,
default: &PropertyTestFuncDefault.default_lower/1
end
def default_lower(data) do
String.downcase(to_string(data[:foo]))
end
end
x = Vertex.new(PropertyTestFuncDefault, foo: "UPCASE")
assert x.props.lower == "upcase"
end
end
| 30.104651 | 81 | 0.690614 |
03317fc64b4db4c210c6becb59f91cf51178a657 | 1,676 | ex | Elixir | web/web.ex | erickgnavarro/phoenix_demo_chat | 71749db3fb4e8012047e8d857b0a096a36dbe375 | [
"MIT"
] | 2 | 2015-05-12T04:00:03.000Z | 2016-05-02T06:05:25.000Z | web/web.ex | erickgnavarro/phoenix_demo_chat | 71749db3fb4e8012047e8d857b0a096a36dbe375 | [
"MIT"
] | null | null | null | web/web.ex | erickgnavarro/phoenix_demo_chat | 71749db3fb4e8012047e8d857b0a096a36dbe375 | [
"MIT"
] | null | null | null | defmodule DemoChat.Web do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use DemoChat.Web, :controller
use DemoChat.Web, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below.
"""
def model do
quote do
use Ecto.Model
end
end
def controller do
quote do
use Phoenix.Controller
# Alias the data repository and import query/model functions
alias DemoChat.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
# Import URL helpers from the router
import DemoChat.Router.Helpers
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
# Import URL helpers from the router
import DemoChat.Router.Helpers
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
# Alias the data repository and import query/model functions
alias DemoChat.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 21.21519 | 69 | 0.670048 |
03319a2f47960861a9607f92f7c94fdcc741d767 | 840 | ex | Elixir | lib/noted_web/controllers/file_controller.ex | lawik/noted | a51b5d79cf44abfc2463560f83f1a8d65e6af85e | [
"BSD-3-Clause"
] | 28 | 2021-02-20T22:22:49.000Z | 2022-03-24T21:07:39.000Z | lib/noted_web/controllers/file_controller.ex | gerhard/noted | c83bfd2e8e2950187268a2e3ba0904ae8a9773e5 | [
"BSD-3-Clause"
] | 5 | 2021-05-06T11:37:11.000Z | 2021-08-31T11:38:14.000Z | lib/noted_web/controllers/file_controller.ex | gerhard/noted | c83bfd2e8e2950187268a2e3ba0904ae8a9773e5 | [
"BSD-3-Clause"
] | 7 | 2021-02-24T19:18:28.000Z | 2021-09-13T16:07:08.000Z | defmodule NotedWeb.FileController do
use NotedWeb, :controller
def serve(conn, %{"id" => id}) do
user_id = get_session(conn, "user_id")
file = Noted.Notes.get_file!(id)
note = Noted.Notes.get_note!(file.note_id)
# Check user owns the file
if note.user_id == user_id do
filename = file.filename || Path.basename(file.path)
send_download(conn, {:file, file.path}, filename: filename)
else
put_status(conn, :not_found)
end
end
def serve_user(conn, %{"id" => user_id}) do
auth_user_id = get_session(conn, "user_id")
user = Noted.Accounts.get_user!(user_id)
# Check user owns the file
if auth_user_id == user.id do
send_download(conn, {:file, user.photo_path}, filename: Path.basename(user.photo_path))
else
put_status(conn, :not_found)
end
end
end
| 28 | 93 | 0.665476 |
0331e9283d7c18c8e17c9842025a9b23641f1312 | 85 | ex | Elixir | lib/stream/proto/pub_ack.ex | UA3MQJ/nats.ex | 549ac3180fe08d3a06cf3b085cf5a40759cc090b | [
"MIT"
] | null | null | null | lib/stream/proto/pub_ack.ex | UA3MQJ/nats.ex | 549ac3180fe08d3a06cf3b085cf5a40759cc090b | [
"MIT"
] | null | null | null | lib/stream/proto/pub_ack.ex | UA3MQJ/nats.ex | 549ac3180fe08d3a06cf3b085cf5a40759cc090b | [
"MIT"
] | null | null | null | defmodule Gnat.Stream.Proto.PubAck do
@moduledoc false
use Gnat.Stream.Proto
end
| 17 | 37 | 0.788235 |
0331fdcdcc31d8e2ead5b672d457dabbe6281c9d | 850 | ex | Elixir | test/fixtures/compiled_with_docs.ex | kelvinst/ex_doc | 609d9765dd6f098dc298e5d6db6430859ee934ec | [
"Apache-2.0",
"CC-BY-4.0"
] | 1,206 | 2015-01-02T02:05:12.000Z | 2022-03-29T17:18:10.000Z | test/fixtures/compiled_with_docs.ex | kelvinst/ex_doc | 609d9765dd6f098dc298e5d6db6430859ee934ec | [
"Apache-2.0",
"CC-BY-4.0"
] | 1,266 | 2015-01-03T03:26:04.000Z | 2022-03-31T09:43:53.000Z | test/fixtures/compiled_with_docs.ex | kelvinst/ex_doc | 609d9765dd6f098dc298e5d6db6430859ee934ec | [
"Apache-2.0",
"CC-BY-4.0"
] | 300 | 2015-01-03T04:07:24.000Z | 2022-03-29T08:10:56.000Z | defmodule CompiledWithDocs do
@moduledoc """
moduledoc
## Example ☃ Unicode > escaping
CompiledWithDocs.example
### Example H3 heading
example
"""
@doc "Some struct"
defstruct [:field]
@doc "Some example"
@doc purpose: :example
@deprecated "Use something else instead"
def example(foo, bar \\ Baz), do: bar.baz(foo)
@doc "Another example"
@doc since: "1.3.0"
defmacro example_1, do: 1
@doc "A simple guard"
defguard is_zero(number) when number == 0
@doc """
Does example action.
### Examples
"""
@doc purpose: :example
def example_with_h3, do: 1
@deprecated "Use something else instead"
def example_without_docs, do: nil
# Check that delegate autogenerate docs
defdelegate flatten(hello), to: List
def unquote(:"name/with/slashes")(), do: :ok
defmodule Nested do
end
end
| 18.085106 | 48 | 0.670588 |
03325ecc00f6b54e1261b4eadda2b05d53960552 | 1,684 | ex | Elixir | lib/ecto/query/builder/limit_offset.ex | tcrossland/ecto | e028a90920fed27865075787d33c2ad61f45fd24 | [
"Apache-2.0"
] | 3,931 | 2016-06-16T11:38:48.000Z | 2022-03-31T21:24:19.000Z | lib/ecto/query/builder/limit_offset.ex | tcrossland/ecto | e028a90920fed27865075787d33c2ad61f45fd24 | [
"Apache-2.0"
] | 2,343 | 2016-06-16T11:18:09.000Z | 2022-03-27T23:44:43.000Z | deps/ecto/lib/ecto/query/builder/limit_offset.ex | adrianomota/blog | ef3b2d2ed54f038368ead8234d76c18983caa75b | [
"MIT"
] | 1,300 | 2016-06-17T13:56:59.000Z | 2022-03-31T01:46:20.000Z | import Kernel, except: [apply: 3]
defmodule Ecto.Query.Builder.LimitOffset do
@moduledoc false
alias Ecto.Query.Builder
@doc """
Builds a quoted expression.
The quoted expression should evaluate to a query at runtime.
If possible, it does all calculations at compile time to avoid
runtime work.
"""
@spec build(:limit | :offset, Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
def build(type, query, binding, expr, env) do
{query, binding} = Builder.escape_binding(query, binding, env)
{expr, {params, :acc}} = Builder.escape(expr, :integer, {[], :acc}, binding, env)
params = Builder.escape_params(params)
if contains_variable?(expr) do
Builder.error! "query variables are not allowed in #{type} expression"
end
limoff = quote do: %Ecto.Query.QueryExpr{
expr: unquote(expr),
params: unquote(params),
file: unquote(env.file),
line: unquote(env.line)}
Builder.apply_query(query, __MODULE__, [type, limoff], env)
end
defp contains_variable?(ast) do
ast
|> Macro.prewalk(false, fn
{:&, _, [_]} = expr, _ -> {expr, true}
expr, acc -> {expr, acc}
end)
|> elem(1)
end
@doc """
The callback applied by `build/4` to build the query.
"""
@spec apply(Ecto.Queryable.t, :limit | :offset, term) :: Ecto.Query.t
def apply(%Ecto.Query{} = query, :limit, expr) do
%{query | limit: expr}
end
def apply(%Ecto.Query{} = query, :offset, expr) do
%{query | offset: expr}
end
def apply(query, kind, expr) do
apply(Ecto.Queryable.to_query(query), kind, expr)
end
end
| 29.54386 | 85 | 0.614014 |
03327599f2d950d8ca9957449126ade6f3cbd943 | 134 | ex | Elixir | lib/protocols/inspect.ex | lmarlow/yaq | d303b6b23543e46b5cd2a9b7bb1bc2e35a3e7306 | [
"Apache-2.0"
] | 5 | 2020-05-21T21:34:38.000Z | 2021-06-15T15:57:38.000Z | lib/protocols/inspect.ex | lmarlow/yaq | d303b6b23543e46b5cd2a9b7bb1bc2e35a3e7306 | [
"Apache-2.0"
] | 1 | 2020-08-18T14:15:49.000Z | 2020-08-18T14:15:49.000Z | lib/protocols/inspect.ex | lmarlow/yaq | d303b6b23543e46b5cd2a9b7bb1bc2e35a3e7306 | [
"Apache-2.0"
] | 1 | 2020-05-26T20:07:44.000Z | 2020-05-26T20:07:44.000Z | defimpl Inspect, for: Yaq do
@impl true
def inspect(queue, _opts) do
"#Yaq<length: #{queue.l_size + queue.r_size}>"
end
end
| 19.142857 | 50 | 0.664179 |
03328dec15900476987680bc46f61530fc54e1b7 | 945 | exs | Elixir | test/failback_test.exs | terianil/geetest3 | 8a6edaf3d893b1ef57fe140bfe807f5074686a24 | [
"MIT"
] | 1 | 2020-04-29T09:40:11.000Z | 2020-04-29T09:40:11.000Z | test/failback_test.exs | terianil/geetest3 | 8a6edaf3d893b1ef57fe140bfe807f5074686a24 | [
"MIT"
] | null | null | null | test/failback_test.exs | terianil/geetest3 | 8a6edaf3d893b1ef57fe140bfe807f5074686a24 | [
"MIT"
] | null | null | null | defmodule Geetest3.FailbackTest do
use ExUnit.Case
import Tesla.Mock
setup do
mock(fn
%{method: :get, url: "https://api.geetest.com/register.php?gt=test_id&json_format=1"} ->
%Tesla.Env{status: 403, body: "403 Forbidden"}
end)
:ok
end
@tag :capture_log
test "register failback" do
assert %{
challenge: challenge,
gt: "test_id",
new_captcha: true,
offline: true
} = Geetest3.register()
assert is_binary(challenge)
assert String.length(challenge) == 34
end
test "validate failback success" do
assert {:ok, true} =
Geetest3.validate_failback(
"challenge",
"b04ec0ade3d49b4a079f0e207d5e2821",
"seccode"
)
end
test "validate failback fail" do
assert {:ok, false} = Geetest3.validate_failback("challenge", "wrong_validate", "seccode")
end
end
| 23.625 | 94 | 0.591534 |
0332a87c785b7123c4480e554c60f2aafbd55efe | 111 | exs | Elixir | priv/templates/phx.gen.controller/controller_test.exs | nyrf/phoenix_extra_generators | 730696c6ad8f055cf9af8b8bf0cf3de0a74bd773 | [
"MIT"
] | 11 | 2017-11-03T11:14:17.000Z | 2019-05-24T13:45:06.000Z | priv/templates/phx.gen.controller/controller_test.exs | nyrf/phoenix_extra_generators | 730696c6ad8f055cf9af8b8bf0cf3de0a74bd773 | [
"MIT"
] | 1 | 2017-11-03T09:52:40.000Z | 2017-11-03T09:52:40.000Z | priv/templates/phx.gen.controller/controller_test.exs | nyrf/phoenix_extra_generators | 730696c6ad8f055cf9af8b8bf0cf3de0a74bd773 | [
"MIT"
] | 1 | 2018-11-03T17:40:49.000Z | 2018-11-03T17:40:49.000Z | defmodule <%= module %>ControllerTest do
use <%= web_module %>.ConnCase
alias <%= module %>Controller
end
| 18.5 | 40 | 0.684685 |
0332b02d12cf7e4d01877647d95bb0bb360d1d03 | 1,017 | exs | Elixir | mix.exs | SimpleBet/opentelemetry_commanded | 31b2b3e72d84b555263a4eccdaa3200c1c0c96fa | [
"Apache-2.0"
] | 10 | 2020-11-03T21:22:03.000Z | 2022-01-23T16:24:02.000Z | mix.exs | SimpleBet/opentelemetry_commanded | 31b2b3e72d84b555263a4eccdaa3200c1c0c96fa | [
"Apache-2.0"
] | 7 | 2020-11-06T21:36:00.000Z | 2022-03-16T17:10:23.000Z | mix.exs | SimpleBet/opentelemetry_commanded | 31b2b3e72d84b555263a4eccdaa3200c1c0c96fa | [
"Apache-2.0"
] | null | null | null | defmodule OpentelemetryCommanded.MixProject do
use Mix.Project
def project do
[
app: :opentelemetry_commanded,
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
package: package(),
deps: deps(),
description: "Trace Commanded CRQS operations with OpenTelemetry",
source_url: "https://github.com/SimpleBet/opentelemetry_commanded",
homepage_url: "https://github.com/SimpleBet/opentelemetry_commanded"
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[]
end
defp package do
[
licenses: ["Apache-2"],
links: %{"GitHub" => "https://github.com/SimpleBet/opentelemetry_commanded"}
]
end
defp deps do
[
{:commanded,
github: "davydog187/commanded", ref: "115eda528b19a213a53ad6501b96acb0f61ee2a4"},
{:telemetry, "~> 0.4.0"},
{:opentelemetry, "~> 1.0-rc"},
{:ex_doc, "~> 0.23.0", only: [:dev], runtime: false}
]
end
end
| 25.425 | 88 | 0.624385 |
0332ef791da5efb6c0147d431c89ecf22df2d9a0 | 1,559 | ex | Elixir | clients/cloud_identity/lib/google_api/cloud_identity/v1/model/transitive_membership_role.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/cloud_identity/lib/google_api/cloud_identity/v1/model/transitive_membership_role.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_identity/lib/google_api/cloud_identity/v1/model/transitive_membership_role.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.CloudIdentity.V1.Model.TransitiveMembershipRole do
@moduledoc """
Message representing the role of a TransitiveMembership.
## Attributes
* `role` (*type:* `String.t`, *default:* `nil`) - TransitiveMembershipRole in string format. Currently supported TransitiveMembershipRoles: `"MEMBER"`, `"OWNER"`, and `"MANAGER"`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:role => String.t()
}
field(:role)
end
defimpl Poison.Decoder, for: GoogleApi.CloudIdentity.V1.Model.TransitiveMembershipRole do
def decode(value, options) do
GoogleApi.CloudIdentity.V1.Model.TransitiveMembershipRole.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudIdentity.V1.Model.TransitiveMembershipRole do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.170213 | 183 | 0.747915 |
0332fb7f21ac736684c2c6955212627d152e0e9b | 710 | exs | Elixir | test/furlex/fetcher_test.exs | XukuLLC/furlex | 8ccd3e09be4f7f5ff16520022287d9282d9c494f | [
"Apache-2.0"
] | null | null | null | test/furlex/fetcher_test.exs | XukuLLC/furlex | 8ccd3e09be4f7f5ff16520022287d9282d9c494f | [
"Apache-2.0"
] | null | null | null | test/furlex/fetcher_test.exs | XukuLLC/furlex | 8ccd3e09be4f7f5ff16520022287d9282d9c494f | [
"Apache-2.0"
] | 1 | 2019-12-12T07:21:31.000Z | 2019-12-12T07:21:31.000Z | defmodule Furlex.FetcherTest do
use ExUnit.Case
alias Furlex.Fetcher
doctest Fetcher
setup do
bypass = Bypass.open()
url = "http://localhost:#{bypass.port}"
{:ok, bypass: bypass, url: url}
end
test "fetches url", %{bypass: bypass, url: url} do
Bypass.expect_once(bypass, &handle/1)
assert {:ok, body, 200} = Fetcher.fetch(url)
assert body =~ "<title>Test HTML</title>"
end
test "fetches url with options", %{url: url} do
assert {:error, :econnrefused} = Fetcher.fetch(url, timeout: 0)
end
def handle(conn) do
body =
[__DIR__ | ~w(.. fixtures test.html)]
|> Path.join()
|> File.read!()
Plug.Conn.resp(conn, 200, body)
end
end
| 20.285714 | 67 | 0.619718 |
0332fde03eb47746307fd205f766d31bed2c1cac | 206 | ex | Elixir | serverless/lib/serverless.ex | rob-brown/ElixirTraining2018 | 9724cc4961d767a1ba2450240e026b46ad5a0f1b | [
"MIT"
] | 2 | 2018-02-01T22:56:09.000Z | 2020-01-20T19:57:48.000Z | serverless/lib/serverless.ex | rob-brown/ElixirTraining2018 | 9724cc4961d767a1ba2450240e026b46ad5a0f1b | [
"MIT"
] | null | null | null | serverless/lib/serverless.ex | rob-brown/ElixirTraining2018 | 9724cc4961d767a1ba2450240e026b46ad5a0f1b | [
"MIT"
] | null | null | null | defmodule Serverless do
@moduledoc """
Documentation for Serverless.
"""
@doc """
Hello world.
## Examples
iex> Serverless.hello
:world
"""
def hello do
:world
end
end
| 10.842105 | 31 | 0.587379 |
033335d190a79169481c4f9366aa83271b9cd848 | 3,848 | ex | Elixir | lib/sneeze.ex | egillet/sneeze | 066602b3da5cadde5a209515ae984417f4668b01 | [
"MIT"
] | 4 | 2021-11-16T10:28:35.000Z | 2022-02-23T16:15:34.000Z | lib/sneeze.ex | egillet/sneeze | 066602b3da5cadde5a209515ae984417f4668b01 | [
"MIT"
] | 1 | 2021-12-23T13:07:37.000Z | 2021-12-23T13:07:37.000Z | lib/sneeze.ex | egillet/sneeze | 066602b3da5cadde5a209515ae984417f4668b01 | [
"MIT"
] | 2 | 2021-09-01T15:41:44.000Z | 2022-01-30T14:18:49.000Z | defmodule Sneeze do
alias Sneeze.Internal
@doc ~s"""
Render a data-structure, containing 'elements' to html.
An element is either:
- [tag, attribute_map | body]
- [tag, attribute_map]
- [tag | body]
- [tag]
- [:@__raw_html, html_string]
- [:script, attribute_map, script_text]
- [:script, script_text]
- [:style, attribute_map, style_text]
- [:style, style_text]
- A bare, stringable value (such as a string or number)
- A list of elements
The content of `:__@raw_html`, `:style` and `:script` elements will not be escaped.
All other elements content will be html-escaped.
Examples:
```
render([:p, %{class: "outlined"}, "hello"])
render([:br])
render([[:span, "one"], [:span, %{class: "highlight"}, "two"]])
render([:ul, %{id: "some-list"},
[:li, [:a, %{href: "/"}, "Home"]],
[:li, [:a, %{href: "/about"}, "About"]]])
render([:__@raw_html, "<!DOCTYPE html>"])
render([:script, "console.log(42 < 9);"])
```
"""
def render(data) do
# _render(data)
IO.iodata_to_binary(_render(data))
end
defp _render(data) do
case data do
[] ->
[]
# list with tag
[tag] when is_atom(tag) ->
if Internal.is_void_tag?(tag) do
[Internal.render_void_tag(tag)]
else
[Internal.render_tag(tag)]
end
# script tags
[:script, attributes, script_body] when is_map(attributes) ->
[
Internal.render_opening_tag(:script, attributes),
script_body,
Internal.render_closing_tag(:script)
]
[:script, script_body] ->
[Internal.render_opening_tag(:script), script_body, Internal.render_closing_tag(:script)]
# style tags
[:style, attributes, style_body] when is_map(attributes) ->
[
Internal.render_opening_tag(:style, attributes),
style_body,
Internal.render_closing_tag(:style)
]
[:style, style_body] ->
[Internal.render_opening_tag(:style), style_body, Internal.render_closing_tag(:style)]
# list with tag and attribute map
[tag, attributes] when is_atom(tag) and is_map(attributes) ->
if Internal.is_void_tag?(tag) do
[Internal.render_void_tag(tag, attributes)]
else
[Internal.render_tag(tag, attributes)]
end
[:__@raw_html, html_string] ->
[html_string]
# list with tag, attribute map and child nodes
[tag, attributes | body] when is_map(attributes) ->
if Internal.is_void_tag?(tag) do
[
Internal.render_void_tag(tag, attributes),
# not actually body, next elements
_render(body)
]
else
[
Internal.render_opening_tag(tag, attributes),
_render_body(body),
Internal.render_closing_tag(tag)
]
end
# list with tag and child nodes
[tag | body] when is_atom(tag) ->
if Internal.is_void_tag?(tag) do
[
Internal.render_void_tag(tag),
# not actually body, next elements
_render_body(body)
]
else
[Internal.render_opening_tag(tag), _render_body(body), Internal.render_closing_tag(tag)]
end
# list with list of child nodes
[node] when is_list(node) ->
[_render(node)]
# list with sub-list as first element
[node | rest] when is_list(node) ->
[_render(node), _render(rest)]
# list with single, stringible member
[something] ->
[to_string(something) |> HtmlEntities.encode()]
# any non-list node
bare_node ->
[to_string(bare_node) |> HtmlEntities.encode()]
end
end
defp _render_body(body_elements) do
body_elements
|> Enum.map(&_render/1)
end
end
| 28.294118 | 98 | 0.587058 |
03333957a58bb65b43b4fb71fbb44569d0901c74 | 827 | ex | Elixir | lib/snowflake.ex | g-ken/snowflake | 5414037b8a15bb9cc596661079e438a9a7cf1972 | [
"MIT"
] | null | null | null | lib/snowflake.ex | g-ken/snowflake | 5414037b8a15bb9cc596661079e438a9a7cf1972 | [
"MIT"
] | null | null | null | lib/snowflake.ex | g-ken/snowflake | 5414037b8a15bb9cc596661079e438a9a7cf1972 | [
"MIT"
] | 1 | 2021-09-28T12:24:51.000Z | 2021-09-28T12:24:51.000Z | defmodule Snowflake do
@moduledoc """
Generates Snowflake IDs
"""
use Application
def start(_type, _args) do
import Supervisor.Spec
children = [
worker(Snowflake.Generator, [Snowflake.Helper.epoch(), Snowflake.Helper.machine_id()])
]
Supervisor.start_link(children, strategy: :one_for_one)
end
@doc """
Generates a snowflake ID, each call is guaranteed to return a different ID
that is sequantially larger than the previous ID.
"""
@spec next_id() :: {:ok, integer} |
{:error, :backwards_clock}
def next_id() do
GenServer.call(Snowflake.Generator, :next_id)
end
@doc """
Returns the machine id of the current node.
"""
@spec machine_id() :: {:ok, integer}
def machine_id() do
GenServer.call(Snowflake.Generator, :machine_id)
end
end
| 23.628571 | 92 | 0.667473 |
0333b76f78f273fa7b09a7fb1d5432d795ee9b8d | 2,699 | ex | Elixir | lib/tarearbol/application.ex | am-kantox/tarearbol | 37bac59178940df4c72bf942dd08d8acca505130 | [
"MIT"
] | 49 | 2017-07-22T12:25:46.000Z | 2022-02-12T20:29:36.000Z | lib/tarearbol/application.ex | am-kantox/tarearbol | 37bac59178940df4c72bf942dd08d8acca505130 | [
"MIT"
] | 15 | 2017-07-21T13:17:32.000Z | 2021-02-25T05:40:11.000Z | lib/tarearbol/application.ex | am-kantox/tarearbol | 37bac59178940df4c72bf942dd08d8acca505130 | [
"MIT"
] | 4 | 2017-10-26T10:28:00.000Z | 2019-09-13T08:04:01.000Z | defmodule Tarearbol.Application do
@moduledoc false
use Boundary, deps: [Tarearbol.Scheduler, Tarearbol.DynamicManager]
use Application
@spec start(Application.app(), Application.restart_type()) ::
{:error, any()} | {:ok, pid()} | {:ok, pid(), any()}
def start(_type, _args) do
optional =
if Application.get_env(:tarearbol, :scheduler, false), do: [Tarearbol.Scheduler], else: []
children = [
{Task.Supervisor, [name: Tarearbol.Application]} | optional
]
opts = [strategy: :one_for_one, name: Tarearbol.Supervisor]
Supervisor.start_link(children, opts)
end
##############################################################################
@spec children :: [{:local | :external, Process.dest(), Tarearbol.Scheduler.Job.t(), keyword()}]
def children, do: children(:local) ++ children(:external)
@spec children(:local | :external) :: [
{:local | :external, Process.dest(), Tarearbol.Scheduler.Job.t(), keyword()}
]
def children(:local) do
Tarearbol.Application
|> Task.Supervisor.children()
|> Enum.map(&{:local, &1, Process.info(&1, :dictionary)})
|> Enum.map(fn {:local, pid, {:dictionary, dict}} -> {:local, pid, dict[:job]} end)
|> Enum.map(fn
{:local, pid, {job, interval, opts}} ->
{:local, pid, job, Keyword.put(opts, :timeout, interval)}
_ ->
nil
end)
|> Enum.reject(&is_nil/1)
end
def children(:external) do
for {name, %Tarearbol.DynamicManager.Child{} = child} <-
Tarearbol.Scheduler.State.state().children do
{:external, child.pid, child.opts.payload.job,
[__name__: name, timeout: child.opts.timeout]}
end
end
def jobs, do: Enum.map(children(), &elem(&1, 2))
@spec kill :: [:ok | {:error, :not_found | :dead}]
def kill, do: for(child <- children(), do: kill(child))
@spec kill(Process.dest()) :: :ok | {:error, :not_found | :dead}
def kill(child) when is_pid(child) or is_port(child) or is_atom(child) or is_tuple(child) do
child =
case child do
{_, pid, _, _} -> pid
pid -> pid
end
case Enum.find(children(), &match?({_, ^child, _, _}, &1)) do
nil -> {:error, :not_found}
{:local, victim, _, _} -> Task.Supervisor.terminate_child(Tarearbol.Application, victim)
{:external, _, _, opts} -> Tarearbol.Scheduler.del(opts[:__name__])
end
end
@spec task!((() -> any()) | {module(), atom(), list()}) :: Task.t()
def task!(job) when is_function(job, 0),
do: Task.Supervisor.async_nolink(Tarearbol.Application, job)
def task!({mod, fun, params}),
do: Task.Supervisor.async_nolink(Tarearbol.Application, mod, fun, params)
end
| 33.7375 | 98 | 0.600222 |
0333badaa0723b56d9c9fda93468e46337fea4af | 732 | ex | Elixir | lib/docusign/model/e_note_configurations.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 4 | 2020-12-21T12:50:13.000Z | 2022-01-12T16:50:43.000Z | lib/docusign/model/e_note_configurations.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 12 | 2018-09-18T15:26:34.000Z | 2019-09-28T15:29:39.000Z | lib/docusign/model/e_note_configurations.ex | gaslight/docusign_elixir | d9d88d53dd85d32a39d537bade9db28d779414e6 | [
"MIT"
] | 15 | 2020-04-29T21:50:16.000Z | 2022-02-11T18:01:51.000Z | # 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 DocuSign.Model.ENoteConfigurations do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:connectConfigured,
:eNoteConfigured,
:organization,
:password,
:userName
]
@type t :: %__MODULE__{
:connectConfigured => String.t(),
:eNoteConfigured => String.t(),
:organization => String.t(),
:password => String.t(),
:userName => String.t()
}
end
defimpl Poison.Decoder, for: DocuSign.Model.ENoteConfigurations do
def decode(value, _options) do
value
end
end
| 22.181818 | 75 | 0.643443 |
0333bca49cbca97ee5fdc2057153e7ad1c56e75f | 177 | exs | Elixir | priv/repo/migrations/20201229174200_add_timestamps_to_card_refills.exs | jfcloutier/freegiving | 2ab3821595996fc295c5b55515d6f60cbce05181 | [
"Unlicense"
] | null | null | null | priv/repo/migrations/20201229174200_add_timestamps_to_card_refills.exs | jfcloutier/freegiving | 2ab3821595996fc295c5b55515d6f60cbce05181 | [
"Unlicense"
] | null | null | null | priv/repo/migrations/20201229174200_add_timestamps_to_card_refills.exs | jfcloutier/freegiving | 2ab3821595996fc295c5b55515d6f60cbce05181 | [
"Unlicense"
] | null | null | null | defmodule Freegiving.Repo.Migrations.AddTimestampsToCardRefills do
use Ecto.Migration
def change do
alter table("card_refills") do
timestamps()
end
end
end
| 17.7 | 66 | 0.740113 |
033419f210ef57c8ad4b1afaaf891c27acb4042c | 1,720 | exs | Elixir | test/earmark_wrapper/options_test.exs | RobertDober/EarmarkWrapper | c62ff01d11cb32c20fdd6a10b529315bd8ea2874 | [
"Apache-2.0"
] | null | null | null | test/earmark_wrapper/options_test.exs | RobertDober/EarmarkWrapper | c62ff01d11cb32c20fdd6a10b529315bd8ea2874 | [
"Apache-2.0"
] | null | null | null | test/earmark_wrapper/options_test.exs | RobertDober/EarmarkWrapper | c62ff01d11cb32c20fdd6a10b529315bd8ea2874 | [
"Apache-2.0"
] | null | null | null | defmodule EarmarkWrapper.OptionsTest do
use ExUnit.Case
alias Earmark.Options, as: EO
alias EarmarkWrapper.Options
describe "empty" do
test "empty input -> default values" do
assert Options.parse([]) == %Options{}
end
end
runner = fn( {options, args}) ->
args1 = if is_binary(args), do: [args], else: args
test(Enum.join(args1," ")) do
expected = struct(Options, unquote(Macro.escape options))
actual = Options.parse(unquote(Macro.escape args1))
assert actual == expected
end
end
describe "parameters" do
[
{ %{help: true, earmark_options: %EO{}}, "--help"},
{ %{help: true}, "-h"},
{ %{version: true}, "--version"},
{ %{version: true}, "-v"},
{ %{input: ~w{xxx yyy}, javascript: "jsfile", lang: "fr", title: "Mr."},
~w{--lang fr -t=Mr. --javascript jsfile xxx yyy}},
{ %{errors: [{"--xxx", nil}]}, ~w{--xxx}}
] |> Enum.each(runner)
end
describe "Earmark parameters" do
[
{%{earmark_options: %EO{footnotes: true, footnote_offset: 0}}, ~w{--earmark-options footnotes,footnote_offset=0}},
{%{earmark_options: %EO{footnotes: true, footnote_offset: 0}}, ~w{-e footnotes=true,footnote_offset=0}},
{%{earmark_options: %EO{timeout: 200, gfm: false}}, ~w{--earmark-options timeout=200,gfm=false}},
{%{earmark_options: %EO{}, errors: ["illegal is not a legal Earmark option"]}, ~w{-e illegal}},
] |> Enum.each(runner)
end
describe "mixed" do
[
{ %{earmark_options: %EO{pedantic: true}, input: ~w{alpha}, stylesheet: "stylesheet", title: "Ms."},
~w{-e pedantic -s stylesheet --title Ms. alpha}}
] |> Enum.each(runner)
end
end
| 31.272727 | 120 | 0.59593 |
03342ad9be2225b541aba99e6bab547123f1089a | 5,924 | exs | Elixir | test/inertia_phoenix/controller_test.exs | szTheory/inertia_phoenix | e402057ced14bdd020d4b1c4354b089aee773a75 | [
"MIT"
] | null | null | null | test/inertia_phoenix/controller_test.exs | szTheory/inertia_phoenix | e402057ced14bdd020d4b1c4354b089aee773a75 | [
"MIT"
] | null | null | null | test/inertia_phoenix/controller_test.exs | szTheory/inertia_phoenix | e402057ced14bdd020d4b1c4354b089aee773a75 | [
"MIT"
] | null | null | null | defmodule InertiaPhoenix.ControllerTest do
use InertiaPhoenix.Test.ConnCase
alias Plug.Conn
alias Phoenix.HTML.Tag
test "render_inertia/2 no props", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "false")
|> Conn.put_req_header("x-inertia-version", "1")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Controller.render_inertia("Home")
page_json =
Jason.encode!(%{
component: "Home",
props: %{},
url: "/",
version: "1"
})
expected =
Tag.content_tag(:div, "", [
{:id, "app"},
{:data, [page: page_json]}
])
assert html = html_response(conn, 200)
assert html == Phoenix.HTML.safe_to_string(expected)
end
test "render_inertia/3 regular", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "false")
|> Conn.put_req_header("x-inertia-version", "1")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Controller.render_inertia("Home", props: %{hello: "world"})
page_json =
Jason.encode!(%{
component: "Home",
props: %{hello: "world"},
url: "/",
version: "1"
})
expected =
Tag.content_tag(:div, "", [
{:id, "app"},
{:data, [page: page_json]}
])
assert html = html_response(conn, 200)
assert html == Phoenix.HTML.safe_to_string(expected)
end
test "render_inertia/3 with x-inertia header", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "1")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Plug.call([])
|> InertiaPhoenix.Controller.render_inertia("Home", props: %{hello: "world"})
page_map = %{
"component" => "Home",
"props" => %{"hello" => "world"},
"url" => "/",
"version" => "1"
}
assert json = json_response(conn, 200)
assert json == page_map
end
test "render_inertia/3 with x-inertia-version mismatch", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "123")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Plug.call([])
# |> InertiaPhoenix.Controller.render_inertia("Home", props: %{hello: "world"})
assert html = html_response(conn, 409)
end
test "render_inertia/3 PUT request with 301", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "1")
|> fetch_session
|> fetch_flash
|> put_status(301)
|> Map.put(:method, "PUT")
|> InertiaPhoenix.Plug.call([])
|> InertiaPhoenix.Controller.render_inertia("Home")
assert json = json_response(conn, 303)
end
test "render_inertia/3 with x-inertia-partial-data", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "1")
|> Conn.put_req_header("x-inertia-partial-component", "Home")
|> Conn.put_req_header("x-inertia-partial-data", "hello,foo")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Plug.call([])
|> InertiaPhoenix.Controller.render_inertia("Home",
props: %{hello: "world", world: "hello", foo: "bar"}
)
page_map = %{
"component" => "Home",
"props" => %{"hello" => "world", "foo" => "bar"},
"url" => "/",
"version" => "1"
}
assert json = json_response(conn, 200)
assert json == page_map
end
test "render_inertia/3 with x-inertia-partial-data and mismatched x-inertia-partial-component",
%{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "1")
|> Conn.put_req_header("x-inertia-partial-component", "Dashboard")
|> Conn.put_req_header("x-inertia-partial-data", "hello,foo")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Plug.call([])
|> InertiaPhoenix.Controller.render_inertia("Home",
props: %{hello: "world", world: "hello", foo: "bar"}
)
page_map = %{
"component" => "Home",
"props" => %{"hello" => "world", "world" => "hello", "foo" => "bar"},
"url" => "/",
"version" => "1"
}
assert json = json_response(conn, 200)
assert json == page_map
end
test "render_inertia/3 with lazy loaded prop", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "1")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.Plug.call([])
|> InertiaPhoenix.Controller.render_inertia("Home",
props: %{hello: fn -> "world" end, foo: "bar"}
)
page_map = %{
"component" => "Home",
"props" => %{"hello" => "world", "foo" => "bar"},
"url" => "/",
"version" => "1"
}
assert json = json_response(conn, 200)
assert json == page_map
end
test "render_inertia/3 with shared props", %{conn: conn} do
conn =
conn
|> Conn.put_req_header("x-inertia", "true")
|> Conn.put_req_header("x-inertia-version", "1")
|> fetch_session
|> fetch_flash
|> InertiaPhoenix.share(:hello, fn -> :world end)
|> InertiaPhoenix.share(:foo, :baz)
|> InertiaPhoenix.share("user", %{name: "José"})
|> InertiaPhoenix.Plug.call([])
|> InertiaPhoenix.Controller.render_inertia("Home",
props: %{foo: "bar"}
)
page_map = %{
"component" => "Home",
"props" => %{"hello" => "world", "foo" => "bar", "user" => %{"name" => "José"}},
"url" => "/",
"version" => "1"
}
assert json = json_response(conn, 200)
assert json == page_map
end
end
| 28.209524 | 97 | 0.567353 |
03342e0fbb8b2d7c707962600b934aa63f6f1eb3 | 590 | ex | Elixir | lib/genex/tools/evaluation/indicator.ex | seanmor5/genex | d1be8b030019f24180ddd0b1a9a91bd3039da076 | [
"Apache-2.0"
] | 114 | 2019-08-04T04:36:05.000Z | 2022-02-11T03:09:15.000Z | lib/genex/tools/evaluation/indicator.ex | seanmor5/genex | d1be8b030019f24180ddd0b1a9a91bd3039da076 | [
"Apache-2.0"
] | 18 | 2019-08-03T23:59:45.000Z | 2019-08-15T18:21:44.000Z | lib/genex/tools/evaluation/indicator.ex | seanmor5/genex | d1be8b030019f24180ddd0b1a9a91bd3039da076 | [
"Apache-2.0"
] | 8 | 2019-08-12T22:52:54.000Z | 2022-02-28T11:33:54.000Z | defmodule Genex.Tools.Evaluation.Indicator do
@moduledoc """
Convenience functions for Multi-Objective Optimization.
Most of these functions aren't tested yet.
"""
@doc false
def hypervolume, do: :ok
@doc false
def additive_epsilon, do: :ok
@doc false
def multiplicative_epsilon, do: :ok
@doc """
Determines if `c1` dominates `c2`.
"""
def dominates?(c1, c2) do
objectives =
c1.genes
|> Enum.zip(c2.genes)
|> Enum.map(fn {g1, g2} -> g1 - g2 end)
Enum.any?(objectives, &(&1 > 0)) and not Enum.any?(objectives, &(&1 < 0))
end
end
| 20.344828 | 77 | 0.632203 |
033448fde533c77d400d1c414c99f04598e56f47 | 3,249 | ex | Elixir | apps/deployment_scope/lib/deployment_scope/stack/config_loader.ex | vapordao/staxx | 5110167573e67a91c0865c3265896642ebe4012e | [
"Apache-2.0"
] | null | null | null | apps/deployment_scope/lib/deployment_scope/stack/config_loader.ex | vapordao/staxx | 5110167573e67a91c0865c3265896642ebe4012e | [
"Apache-2.0"
] | null | null | null | apps/deployment_scope/lib/deployment_scope/stack/config_loader.ex | vapordao/staxx | 5110167573e67a91c0865c3265896642ebe4012e | [
"Apache-2.0"
] | null | null | null | defmodule Staxx.DeploymentScope.Stack.ConfigLoader do
@moduledoc """
Module will load list of stack configs form folder (see: `Application.get_env(:deployment_scope, :stacks_dir)`)
State for config loader will consist of map in format:
```elixir
%{
"stack_name" => %Staxx.DeploymentScope.Stack.Config{},
"another_stack_name" => %Staxx.DeploymentScope.Stack.Config{},
}
```
"""
use GenServer
require Logger
alias Staxx.DeploymentScope.Stack.Config
@stack_config_filename "stack.json"
@doc false
def start_link(_) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@doc false
def init(:ok) do
# Check configuration correctness
if is_nil(config_folder()) do
raise "Stack config folder was not configured !"
end
# Validate that stack config folder exist
unless File.exists?(config_folder()) do
File.mkdir!(config_folder())
end
state = read()
Logger.debug(fn ->
"""
#{__MODULE__}: Loaded list of staks configs
#{inspect(state, pretty: true)}
"""
end)
{:ok, state}
end
@doc false
def handle_call(:get, _from, state),
do: {:reply, state, state}
@doc false
def handle_call({:get, stack}, _from, state),
do: {:reply, Map.get(state, stack), state}
@doc false
def handle_call({:has_image, stack, image}, _from, state) do
case Map.get(state, stack) do
nil ->
{:reply, false, state}
%Config{} = config ->
{:reply, Config.has_image?(config, image), state}
end
end
@doc false
def handle_cast(:reload, _state) do
updated = read()
Logger.debug("#{__MODULE__}: Reloaded list of available stacks")
{:noreply, updated}
end
@doc """
Get list of available (registered in system) stacks
"""
@spec get() :: map()
def get(),
do: GenServer.call(__MODULE__, :get)
@doc """
Get exact stack details
"""
@spec get(binary) :: map() | nil
def get(stack_name),
do: GenServer.call(__MODULE__, {:get, stack_name})
@doc """
Check if stack has image in it's config.
If there is no such docker image in config listed, we couldn't start image
"""
@spec has_image?(binary, binary) :: boolean
def has_image?(stack_name, image),
do: GenServer.call(__MODULE__, {:has_image, stack_name, image})
@doc """
Reload stack configuration from disc.
"""
@spec reload() :: :ok
def reload(),
do: GenServer.cast(__MODULE__, :reload)
@doc """
Read list of details from stacks into configured path
"""
@spec read() :: map()
def read() do
config_folder()
|> File.ls!()
|> Enum.map(&scan_stack_config/1)
|> Map.new()
end
#
# Private functions
#
defp scan_stack_config(dir) do
dir
|> Path.expand(config_folder())
|> Path.join(@stack_config_filename)
|> parse_config_file()
end
defp parse_config_file(nil), do: nil
defp parse_config_file(""), do: nil
defp parse_config_file(path) do
config =
path
|> File.read!()
|> Poison.decode!(as: %Config{}, keys: :atoms)
{Map.get(config, :name), config}
end
# Get folder with stacks configuration
defp config_folder(),
do: Application.get_env(:deployment_scope, :stacks_dir)
end
| 22.72028 | 113 | 0.642044 |
033462a36c374d5acb35d86e1a0368680f31a6c1 | 1,536 | ex | Elixir | lib/core/adapters/commands/worker.ex | giusdp/funless-core | d64570549ef0bd4376b1d16096033aca90042bef | [
"Apache-2.0"
] | null | null | null | lib/core/adapters/commands/worker.ex | giusdp/funless-core | d64570549ef0bd4376b1d16096033aca90042bef | [
"Apache-2.0"
] | null | null | null | lib/core/adapters/commands/worker.ex | giusdp/funless-core | d64570549ef0bd4376b1d16096033aca90042bef | [
"Apache-2.0"
] | 1 | 2022-03-24T12:05:11.000Z | 2022-03-24T12:05:11.000Z | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
defmodule Core.Adapters.Commands.Worker do
@moduledoc """
Adapter to send commands to a worker actor.
Currently implemented commands: invocation.
"""
require Elixir.Logger
@behaviour Core.Domain.Ports.Commands
@impl true
def send_invocation_command(worker, ivk_params) do
f_name = ivk_params["name"]
Elixir.Logger.info("Sending invocation request to worker #{worker} for function #{f_name}")
reply =
GenServer.call(
{:worker, worker},
{:invoke,
%{
name: f_name,
image: "node:lts-alpine",
main_file: "/opt/index.js",
archive: "js/hello.tar.gz"
}}
)
Elixir.Logger.debug(reply)
{:ok, name: ivk_params["name"]}
end
end
| 30.72 | 95 | 0.696615 |
0334763d4abdc4ed10337dc70a4040d7b716793d | 6,499 | ex | Elixir | deps/phoenix/lib/mix/tasks/phx.gen.schema.ex | rpillar/Top5_Elixir | 9c450d2e9b291108ff1465dc066dfe442dbca822 | [
"MIT"
] | null | null | null | deps/phoenix/lib/mix/tasks/phx.gen.schema.ex | rpillar/Top5_Elixir | 9c450d2e9b291108ff1465dc066dfe442dbca822 | [
"MIT"
] | null | null | null | deps/phoenix/lib/mix/tasks/phx.gen.schema.ex | rpillar/Top5_Elixir | 9c450d2e9b291108ff1465dc066dfe442dbca822 | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Phx.Gen.Schema do
@shortdoc "Generates an Ecto schema and migration file"
@moduledoc """
Generates an Ecto schema and migration.
mix phx.gen.schema Blog.Post blog_posts title:string views:integer
The first argument is the schema module followed by its plural
name (used as the table name).
The generated schema above will contain:
* a schema file in `lib/my_app/blog/post.ex`, with a `blog_posts` table
* a migration file for the repository
The generated migration can be skipped with `--no-migration`.
## Contexts
Your schemas can be generated and added to a separate OTP app.
Make sure your configuration is properly setup or manually
specify the context app with the `--context-app` option with
the CLI.
# Via config
config :marketing_web, :generators, context_app: :marketing
# Via CLI
mix phx.gen.schema Blog.Post blog_posts title:string views:integer --context-app marketing
## Attributes
The resource fields are given using `name:type` syntax
where type are the types supported by Ecto. Omitting
the type makes it default to `:string`:
mix phx.gen.schema Blog.Post blog_posts title views:integer
The following types are supported:
#{for attr <- Mix.Phoenix.Schema.valid_types(), do: " * `#{inspect attr}`\n"}
* `:datetime` - An alias for `:naive_datetime`
The generator also supports references, which we will properly
associate the given column to the primary key column of the
referenced table:
mix phx.gen.schema Blog.Post blog_posts title user_id:references:users
This will result in a migration with an `:integer` column
of `:user_id` and create an index.
Furthermore an array type can also be given if it is
supported by your database, although it requires the
type of the underlying array element to be given too:
mix phx.gen.schema Blog.Post blog_posts tags:array:string
Unique columns can be automatically generated by using:
mix phx.gen.schema Blog.Post blog_posts title:unique unique_int:integer:unique
If no data type is given, it defaults to a string.
## table
By default, the table name for the migration and schema will be
the plural name provided for the resource. To customize this value,
a `--table` option may be provided. For example:
mix phx.gen.schema Blog.Post posts --table cms_posts
## binary_id
Generated migration can use `binary_id` for schema's primary key
and its references with option `--binary-id`.
## Default options
This generator uses default options provided in the `:generators`
configuration of your application. These are the defaults:
config :your_app, :generators,
migration: true,
binary_id: false,
sample_binary_id: "11111111-1111-1111-1111-111111111111"
You can override those options per invocation by providing corresponding
switches, e.g. `--no-binary-id` to use normal ids despite the default
configuration or `--migration` to force generation of the migration.
"""
use Mix.Task
alias Mix.Phoenix.Schema
@switches [migration: :boolean, binary_id: :boolean, table: :string,
web: :string, context_app: :string]
@doc false
def run(args) do
if Mix.Project.umbrella?() do
Mix.raise "mix phx.gen.schema can only be run inside an application directory"
end
schema = build(args, [])
paths = Mix.Phoenix.generator_paths()
prompt_for_conflicts(schema)
schema
|> copy_new_files(paths, schema: schema)
|> print_shell_instructions()
end
defp prompt_for_conflicts(schema) do
schema
|> files_to_be_generated()
|> Mix.Phoenix.prompt_for_conflicts()
end
@doc false
def build(args, parent_opts, help \\ __MODULE__) do
{schema_opts, parsed, _} = OptionParser.parse(args, switches: @switches)
[schema_name, plural | attrs] = validate_args!(parsed, help)
opts =
parent_opts
|> Keyword.merge(schema_opts)
|> put_context_app(schema_opts[:context_app])
schema = Schema.new(schema_name, plural, attrs, opts)
schema
end
defp put_context_app(opts, nil), do: opts
defp put_context_app(opts, string) do
Keyword.put(opts, :context_app, String.to_atom(string))
end
@doc false
def files_to_be_generated(%Schema{} = schema) do
[{:eex, "schema.ex", schema.file}]
end
@doc false
def copy_new_files(%Schema{context_app: ctx_app} = schema, paths, binding) do
files = files_to_be_generated(schema)
Mix.Phoenix.copy_from(paths, "priv/templates/phx.gen.schema", binding, files)
if schema.migration? do
migration_path = Mix.Phoenix.context_app_path(ctx_app, "priv/repo/migrations/#{timestamp()}_create_#{schema.table}.exs")
Mix.Phoenix.copy_from paths, "priv/templates/phx.gen.schema", binding, [
{:eex, "migration.exs", migration_path},
]
end
schema
end
@doc false
def print_shell_instructions(%Schema{} = schema) do
if schema.migration? do
Mix.shell.info """
Remember to update your repository by running migrations:
$ mix ecto.migrate
"""
end
end
@doc false
def validate_args!([schema, plural | _] = args, help) do
cond do
not Schema.valid?(schema) ->
help.raise_with_help "Expected the schema argument, #{inspect schema}, to be a valid module name"
String.contains?(plural, ":") or plural != Phoenix.Naming.underscore(plural) ->
help.raise_with_help "Expected the plural argument, #{inspect plural}, to be all lowercase using snake_case convention"
true ->
args
end
end
def validate_args!(_, help) do
help.raise_with_help "Invalid arguments"
end
@doc false
@spec raise_with_help(String.t) :: no_return()
def raise_with_help(msg) do
Mix.raise """
#{msg}
mix phx.gen.schema expects both a module name and
the plural of the generated resource followed by
any number of attributes:
mix phx.gen.schema Blog.Post blog_posts title:string
"""
end
defp timestamp do
{{y, m, d}, {hh, mm, ss}} = :calendar.universal_time()
"#{y}#{pad(m)}#{pad(d)}#{pad(hh)}#{pad(mm)}#{pad(ss)}"
end
defp pad(i) when i < 10, do: << ?0, ?0 + i >>
defp pad(i), do: to_string(i)
end
| 30.947619 | 128 | 0.674258 |
03348172d954d0be05858baf27cb2ee9653fbbf6 | 715 | ex | Elixir | lib/strava/model/activity_zone.ex | rkorzeniec/strava | aa99040355f72ff2766c080d5a919c66a53ac44b | [
"MIT"
] | 39 | 2016-04-09T21:50:34.000Z | 2022-03-04T09:16:25.000Z | lib/strava/model/activity_zone.ex | rkorzeniec/strava | aa99040355f72ff2766c080d5a919c66a53ac44b | [
"MIT"
] | 24 | 2016-05-29T15:49:07.000Z | 2022-01-17T11:57:05.000Z | lib/strava/model/activity_zone.ex | rkorzeniec/strava | aa99040355f72ff2766c080d5a919c66a53ac44b | [
"MIT"
] | 21 | 2016-02-02T01:19:23.000Z | 2022-02-06T23:29:32.000Z | defmodule Strava.ActivityZone do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:score,
:distribution_buckets,
:type,
:sensor_based,
:points,
:custom_zones,
:max
]
@type t :: %__MODULE__{
score: integer(),
distribution_buckets: list(Strava.TimedZoneRange.t()),
type: String.t(),
sensor_based: boolean(),
points: integer(),
custom_zones: boolean(),
max: integer()
}
end
defimpl Poison.Decoder, for: Strava.ActivityZone do
import Strava.Deserializer
def decode(value, options) do
value
|> deserialize(:distribution_buckets, :list, Strava.TimedZoneRange, options)
end
end
| 19.861111 | 80 | 0.612587 |
0334d196279419d11eb4d53e7cc03f06116367f3 | 506 | exs | Elixir | priv/repo/migrations/20210427223600_add_multibuy_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 83 | 2018-05-31T14:49:10.000Z | 2022-03-27T16:49:49.000Z | priv/repo/migrations/20210427223600_add_multibuy_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 267 | 2018-05-22T23:19:02.000Z | 2022-03-31T04:31:06.000Z | priv/repo/migrations/20210427223600_add_multibuy_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 18 | 2018-11-20T05:15:54.000Z | 2022-03-28T08:20:13.000Z | defmodule Console.Repo.Migrations.AddMultibuyTable do
use Ecto.Migration
def change do
create table(:multi_buys, primary_key: false) do
add :id, :binary_id, primary_key: true, null: false
add :name, :string, null: false
add :value, :integer, null: false, default: 1
add :organization_id, references(:organizations, on_delete: :delete_all, type: :binary_id, null: false)
timestamps()
end
create unique_index(:multi_buys, [:name, :organization_id])
end
end
| 29.764706 | 109 | 0.699605 |
03355e7a0dd1ca487493a1333cdc0429aafa29c9 | 1,862 | ex | Elixir | test/support/fixtures/payments_fixtures.ex | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | null | null | null | test/support/fixtures/payments_fixtures.ex | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | null | null | null | test/support/fixtures/payments_fixtures.ex | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | null | null | null | defmodule Glimesh.PaymentsFixtures do
@moduledoc """
This module defines test helpers for creating
entities via the `Glimesh.Payments` context.
"""
def platform_founder_subscription_fixture(user) do
Glimesh.Payments.create_subscription(%{
user: user,
stripe_subscription_id: "random_id",
stripe_product_id: Glimesh.Payments.get_platform_sub_founder_product_id(),
stripe_price_id: Glimesh.Payments.get_platform_sub_founder_price_id(),
stripe_current_period_end: 1234,
price: 100,
fee: 10,
payout: 90,
product_name: "some name",
is_active: true,
started_at: NaiveDateTime.utc_now(),
ended_at: NaiveDateTime.utc_now()
})
end
def platform_supporter_subscription_fixture(user) do
Glimesh.Payments.create_subscription(%{
user: user,
stripe_subscription_id: "random_id",
stripe_product_id: Glimesh.Payments.get_platform_sub_supporter_product_id(),
stripe_price_id: Glimesh.Payments.get_platform_sub_supporter_price_id(),
stripe_current_period_end: 1234,
price: 100,
fee: 10,
payout: 90,
product_name: "some name",
is_active: true,
started_at: NaiveDateTime.utc_now(),
ended_at: NaiveDateTime.utc_now()
})
end
def channel_subscription_fixture(streamer, user) do
Glimesh.Payments.create_subscription(%{
user: user,
streamer: streamer,
stripe_subscription_id: "random_id",
stripe_product_id: Glimesh.Payments.get_channel_sub_base_product_id(),
stripe_price_id: Glimesh.Payments.get_channel_sub_base_price_id(),
stripe_current_period_end: 1234,
price: 100,
fee: 10,
payout: 90,
product_name: "some name",
is_active: true,
started_at: NaiveDateTime.utc_now(),
ended_at: NaiveDateTime.utc_now()
})
end
end
| 31.559322 | 82 | 0.705156 |
03357289fcbfd1a74db7775c8ae47bd4326862fd | 4,073 | ex | Elixir | fisherman_server/lib/fisherman_server/sorts.ex | henrysdev/Fisherman | 57bc51730cedb84a47807e2d617061f2cfe54ffd | [
"MIT"
] | 1 | 2020-05-14T06:07:21.000Z | 2020-05-14T06:07:21.000Z | fisherman_server/lib/fisherman_server/sorts.ex | henrysdev/Fisherman | 57bc51730cedb84a47807e2d617061f2cfe54ffd | [
"MIT"
] | 19 | 2020-05-04T17:29:44.000Z | 2020-07-05T18:15:10.000Z | fisherman_server/lib/fisherman_server/sorts.ex | henrysdev/Fisherman | 57bc51730cedb84a47807e2d617061f2cfe54ffd | [
"MIT"
] | null | null | null | defmodule FishermanServer.Sorts do
@moduledoc """
Provides handy algorithm helpers
"""
@doc """
Sort shell records by relative time interval. This is accomplished
by the following process:
1. Separate each shell record into two bounds (start and end)
2. Sort all bounds by timestamp and record their sorted order
3. Split up the processed bounds into two data structures:
- A list of start-boundaries
- A map consisting of command_id -> end-boundary order lookups
4. Iterate over each start-boundary and lookup its corresponding
end boundary by shared id.
5. Merge each corresponding boundary into a structure %{id, start, end}
- id = string identifier for shell record
- start = integer denoting start boundary's relative order to
other boundaries.
- end = integer denoting end boundary's relative order to
other boundaries.
6. Build a lookup by order index map to return with the list
"""
def interval_sort(intervals) do
%{
starts: starts,
ends: ends
} =
intervals
|> Enum.reduce([], fn %FishermanServer.ShellRecord{
uuid: id,
command_timestamp: sm,
error_timestamp: em
},
acc ->
[
%{ts: DateTime.to_unix(sm, :millisecond), id: id, bound: 0},
%{ts: DateTime.to_unix(em, :millisecond), id: id, bound: 1}
| acc
]
end)
|> Enum.sort(&(&1.ts <= &2.ts))
|> Enum.with_index()
|> Enum.reduce(%{starts: [], ends: %{}}, &split_bounds(&1, &2))
results =
starts
|> Enum.reverse()
|> Enum.map(fn {%{id: id}, idx} ->
%{id: id, start: idx, end: Map.get(ends, id)}
end)
results
end
# Bucket the bound into its appropriate container
defp split_bounds({%{bound: 0}, _rel_order} = boundary, acc) do
Map.update!(acc, :starts, &[boundary | &1])
end
defp split_bounds({%{bound: 1, id: id}, rel_order} = _boundary, %{ends: ends} = acc) do
Map.put(acc, :ends, Map.put(ends, id, rel_order))
end
@doc """
Build a 2D map of content by row for UI table
"""
def build_table_matrix(records, pids) do
# Build lookup of record uuid -> record
record_lookup = Enum.reduce(records, %{}, &Map.put(&2, &1.uuid, &1))
# Maintain a set of occupied bounds for each pid
pids_map =
pids
|> Enum.reduce(%{}, &Map.put(&2, &1, %{}))
# Populate occupied bounds for each pid
sorted_intervals = records
matrix =
records
|> interval_sort()
|> Enum.reduce(pids_map, &add_cell_info(&1, &2, record_lookup))
{matrix, record_lookup}
end
defp add_cell_info(
%{id: id, start: start_idx, end: end_idx},
pids_map,
record_lookup
) do
# Fetch whole shell record object from lookup map
%{
pid: pid,
uuid: record_id
} = Map.get(record_lookup, id)
# Place in map with identifier to denote the start of a block
# as well as how many spaces it will take up
fill_size = abs(end_idx - start_idx)
cell_info = %{
fill_size: fill_size,
record_id: record_id
}
# rel_order_idx maps to cell info
idx_map_for_pid = Map.get(pids_map, pid, %{})
pid_map = Map.put(idx_map_for_pid, start_idx, {:start, cell_info})
# Generate :fill records for cells that should be skipped akin
# to how <td> cells are skipped by rowspan/colspan
pid_map =
if fill_size > 1 do
(start_idx + 1)..(end_idx - 1)
|> Enum.reduce(pid_map, &Map.put(&2, &1, :fill))
else
pid_map
end
Map.put(pids_map, pid, pid_map)
end
# Builds a mapping from rel_order_idx -> record_id for interval bounds
# NOTE Not used currently
defp build_order_idx_lookup(intervals) do
lookup_by_order_idx =
Enum.reduce(intervals, %{}, fn item, acc ->
acc
|> Map.put(item.start, item.id)
|> Map.put(item.end, item.id)
end)
end
end
| 29.729927 | 89 | 0.603486 |
03359f269d9b8c05728cd2bdc68a3f93d292f3fa | 4,871 | ex | Elixir | clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_command_task_inputs.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_command_task_inputs.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_command_task_inputs.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.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputs do
@moduledoc """
Describes the inputs to a shell-style task.
## Attributes
* `arguments` (*type:* `list(String.t)`, *default:* `nil`) - The command itself to run (e.g., argv).
This field should be passed directly to the underlying operating system,
and so it must be sensible to that operating system. For example, on
Windows, the first argument might be "C:\\Windows\\System32\\ping.exe" -
that is, using drive letters and backslashes. A command for a *nix
system, on the other hand, would use forward slashes.
All other fields in the RWAPI must consistently use forward slashes,
since those fields may be interpretted by both the service and the bot.
* `environmentVariables` (*type:* `list(GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputsEnvironmentVariable.t)`, *default:* `nil`) - All environment variables required by the task.
* `files` (*type:* `list(GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest.t)`, *default:* `nil`) - The input filesystem to be set up prior to the task beginning. The
contents should be a repeated set of FileMetadata messages though other
formats are allowed if better for the implementation (eg, a LUCI-style
.isolated file).
This field is repeated since implementations might want to cache the
metadata, in which case it may be useful to break up portions of the
filesystem that change frequently (eg, specific input files) from those
that don't (eg, standard header files).
* `inlineBlobs` (*type:* `list(GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Blob.t)`, *default:* `nil`) - Inline contents for blobs expected to be needed by the bot to execute the
task. For example, contents of entries in `files` or blobs that are
indirectly referenced by an entry there.
The bot should check against this list before downloading required task
inputs to reduce the number of communications between itself and the
remote CAS server.
* `workingDirectory` (*type:* `String.t`, *default:* `nil`) - Directory from which a command is executed. It is a relative directory
with respect to the bot's working directory (i.e., "./"). If it is
non-empty, then it must exist under "./". Otherwise, "./" will be used.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:arguments => list(String.t()),
:environmentVariables =>
list(
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputsEnvironmentVariable.t()
),
:files =>
list(
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest.t()
),
:inlineBlobs =>
list(
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Blob.t()
),
:workingDirectory => String.t()
}
field(:arguments, type: :list)
field(:environmentVariables,
as:
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputsEnvironmentVariable,
type: :list
)
field(:files,
as: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest,
type: :list
)
field(:inlineBlobs,
as: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Blob,
type: :list
)
field(:workingDirectory)
end
defimpl Poison.Decoder,
for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputs do
def decode(value, options) do
GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputs.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2CommandTaskInputs do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.491071 | 227 | 0.728187 |
0335a2b684084d544e1e40dc235bb6b0851c7c9b | 116 | ex | Elixir | lib/db/repo.ex | aslakjohansen/dde-iotserver-liveview | eaf063c366105da7ca30b55c6a7a7dd4505b0916 | [
"BSD-3-Clause"
] | null | null | null | lib/db/repo.ex | aslakjohansen/dde-iotserver-liveview | eaf063c366105da7ca30b55c6a7a7dd4505b0916 | [
"BSD-3-Clause"
] | null | null | null | lib/db/repo.ex | aslakjohansen/dde-iotserver-liveview | eaf063c366105da7ca30b55c6a7a7dd4505b0916 | [
"BSD-3-Clause"
] | null | null | null | defmodule DB.Repo do
use Ecto.Repo,
otp_app: :dde_iotserver_liveview,
adapter: Ecto.Adapters.Postgres
end
| 19.333333 | 37 | 0.75 |
0335d191bc6bb552bb79cd8ce9f787ea0051a58c | 167 | exs | Elixir | test/castore_test.exs | YosephHaryanto/castore | 41f8ad333679f7b79c178a708f48bd575314a159 | [
"Apache-2.0"
] | 66 | 2019-10-29T02:50:03.000Z | 2022-03-31T06:13:26.000Z | test/castore_test.exs | YosephHaryanto/castore | 41f8ad333679f7b79c178a708f48bd575314a159 | [
"Apache-2.0"
] | 16 | 2020-05-30T14:51:12.000Z | 2022-03-29T13:26:32.000Z | test/castore_test.exs | YosephHaryanto/castore | 41f8ad333679f7b79c178a708f48bd575314a159 | [
"Apache-2.0"
] | 14 | 2020-03-30T06:17:57.000Z | 2021-08-07T07:00:23.000Z | defmodule CAStoreTest do
use ExUnit.Case
doctest CAStore
test "file_path/0" do
assert String.ends_with?(CAStore.file_path(), "/priv/cacerts.pem")
end
end
| 18.555556 | 70 | 0.730539 |
0335fdcb4205638bca5d08cf35cec3dd86fc9c42 | 1,788 | exs | Elixir | config/dev.exs | synion/tilex | ea29646830efaa89fc47fad347f6e495ff7ce48b | [
"MIT"
] | 1 | 2019-05-28T20:43:28.000Z | 2019-05-28T20:43:28.000Z | config/dev.exs | synion/tilex | ea29646830efaa89fc47fad347f6e495ff7ce48b | [
"MIT"
] | 1 | 2019-02-11T23:14:15.000Z | 2019-02-11T23:14:15.000Z | config/dev.exs | synion/tilex | ea29646830efaa89fc47fad347f6e495ff7ce48b | [
"MIT"
] | 1 | 2019-12-02T08:59:45.000Z | 2019-12-02T08:59:45.000Z | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :tilex, TilexWeb.Endpoint,
http: [port: 4000, protocol_options: [max_request_line_length: 8192, max_header_value_length: 8192]],
url: [scheme: "https", host: "localdev.selleo.com", path: "/til"],
secret_key_base: "mdTtrt4Y4JrtiTv63NepUe4fs1iSt23VfzKpnXm6mawKl6wN8jEfLfIf2HbyMeKe",
render_errors: [view: TilexWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: Tilex.PubSub, adapter: Phoenix.PubSub.PG2],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/brunch/bin/brunch",
"watch",
"--stdin",
cd: Path.expand("../assets", __DIR__)
]
]
# Watch static and templates for browser reloading.
config :tilex, TilexWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/tilex/web/views/.*(ex)$},
~r{lib/tilex/web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :tilex, Tilex.Repo,
adapter: Ecto.Adapters.Postgres,
database: "tilex_dev",
hostname: "localhost",
pool_size: 10
config :tilex, :page_size, 50
config :tilex, :cors_origin, "http://localhost:3000"
config :tilex, :default_twitter_handle, "selleo"
| 32.509091 | 103 | 0.709732 |
033602a529d1ac0e2070aece77f85382d0c2b0b1 | 1,415 | exs | Elixir | mix.exs | capitalist/surface | f1c75f92513b607c98ba578030a647e0f5d6d11c | [
"MIT"
] | null | null | null | mix.exs | capitalist/surface | f1c75f92513b607c98ba578030a647e0f5d6d11c | [
"MIT"
] | null | null | null | mix.exs | capitalist/surface | f1c75f92513b607c98ba578030a647e0f5d6d11c | [
"MIT"
] | null | null | null | defmodule Surface.MixProject do
use Mix.Project
@version "0.1.0-rc.0"
def project do
[
app: :surface,
version: @version,
elixir: "~> 1.8",
description: "A component based library for Phoenix LiveView",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
deps: deps(),
docs: docs(),
package: package()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:nimble_parsec, "~> 0.5.0"},
{:jason, "~> 1.0"},
{:phoenix_live_view,
git: "https://github.com/phoenixframework/phoenix_live_view.git",
tag: "0f592a4b249858590a6b96c4e26e48fd7a46833b"},
{:earmark, "~> 1.3"},
{:floki, "~> 0.25.0", only: :test},
{:phoenix_ecto, "~> 4.0", only: :test},
{:ecto, "~> 3.4.2", only: :test},
{:ex_doc, ">= 0.19.0", only: :docs}
]
end
defp docs do
[
main: "Surface",
source_ref: "v#{@version}",
source_url: "https://github.com/msaraiva/surface"
]
end
defp package do
%{
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/msaraiva/surface"}
}
end
end
| 23.196721 | 72 | 0.561837 |
03360f1fda7d589777c077893460ca4b3b283b41 | 3,091 | ex | Elixir | clients/slides/lib/google_api/slides/v1/model/replace_all_shapes_with_sheets_chart_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/slides/lib/google_api/slides/v1/model/replace_all_shapes_with_sheets_chart_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/slides/lib/google_api/slides/v1/model/replace_all_shapes_with_sheets_chart_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "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.Slides.V1.Model.ReplaceAllShapesWithSheetsChartRequest do
@moduledoc """
Replaces all shapes that match the given criteria with the provided Google
Sheets chart. The chart will be scaled and centered to fit within the bounds
of the original shape.
NOTE: Replacing shapes with a chart requires at least one of the
spreadsheets.readonly, spreadsheets, drive.readonly, or drive OAuth scopes.
## Attributes
* `chartId` (*type:* `integer()`, *default:* `nil`) - The ID of the specific chart in the Google Sheets spreadsheet.
* `containsText` (*type:* `GoogleApi.Slides.V1.Model.SubstringMatchCriteria.t`, *default:* `nil`) - The criteria that the shapes must match in order to be replaced. The
request will replace all of the shapes that contain the given text.
* `linkingMode` (*type:* `String.t`, *default:* `nil`) - The mode with which the chart is linked to the source spreadsheet. When
not specified, the chart will be an image that is not linked.
* `pageObjectIds` (*type:* `list(String.t)`, *default:* `nil`) - If non-empty, limits the matches to page elements only on the given pages.
Returns a 400 bad request error if given the page object ID of a
notes page or a
notes master, or if a
page with that object ID doesn't exist in the presentation.
* `spreadsheetId` (*type:* `String.t`, *default:* `nil`) - The ID of the Google Sheets spreadsheet that contains the chart.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:chartId => integer(),
:containsText => GoogleApi.Slides.V1.Model.SubstringMatchCriteria.t(),
:linkingMode => String.t(),
:pageObjectIds => list(String.t()),
:spreadsheetId => String.t()
}
field(:chartId)
field(:containsText, as: GoogleApi.Slides.V1.Model.SubstringMatchCriteria)
field(:linkingMode)
field(:pageObjectIds, type: :list)
field(:spreadsheetId)
end
defimpl Poison.Decoder, for: GoogleApi.Slides.V1.Model.ReplaceAllShapesWithSheetsChartRequest do
def decode(value, options) do
GoogleApi.Slides.V1.Model.ReplaceAllShapesWithSheetsChartRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Slides.V1.Model.ReplaceAllShapesWithSheetsChartRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.535211 | 172 | 0.72792 |
0336291b8f43dc53af31b8d3edf08bc4cff143cb | 635 | ex | Elixir | lib/type/timestamp.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 144 | 2018-04-27T07:24:49.000Z | 2022-03-15T05:19:37.000Z | lib/type/timestamp.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 123 | 2018-05-01T02:54:43.000Z | 2022-01-28T01:30:52.000Z | lib/type/timestamp.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 14 | 2018-05-01T02:30:47.000Z | 2022-02-21T04:38:56.000Z | # Copyright(c) 2015-2021 ACCESS CO., LTD. All rights reserved.
use Croma
alias Croma.Result, as: R
alias Antikythera.Time
defmodule Antikythera.IsoTimestamp do
@moduledoc """
A strict subset of ISO8601 format of timestamp.
"""
@type t :: String.t()
defun valid?(v :: term) :: boolean do
t when is_binary(t) -> Time.from_iso_timestamp(t) |> R.ok?()
_ -> false
end
end
defmodule Antikythera.IsoTimestamp.Basic do
@moduledoc """
ISO8601 basic format.
"""
@type t :: String.t()
defun valid?(v :: term) :: boolean do
t when is_binary(t) -> Time.from_iso_basic(t) |> R.ok?()
_ -> false
end
end
| 19.84375 | 64 | 0.653543 |
03364fa35685aa7921872612319021566752ae0a | 24 | ex | Elixir | lib/explay.ex | sheharyarn/explay | 72a5d1ae131cbbcb277cb47a2e6b5e7cb65d7a75 | [
"MIT"
] | 16 | 2016-10-17T19:58:32.000Z | 2020-04-22T10:33:22.000Z | lib/explay.ex | sheharyarn/explay | 72a5d1ae131cbbcb277cb47a2e6b5e7cb65d7a75 | [
"MIT"
] | 2 | 2017-04-12T13:24:09.000Z | 2021-08-29T15:17:14.000Z | lib/explay.ex | sheharyarn/explay | 72a5d1ae131cbbcb277cb47a2e6b5e7cb65d7a75 | [
"MIT"
] | 1 | 2017-04-06T15:02:55.000Z | 2017-04-06T15:02:55.000Z | defmodule ExPlay do
end
| 8 | 19 | 0.833333 |
033677cb82dd31467281782713b7c213703892bd | 607 | ex | Elixir | lib/drunkard/recipes/recipe_ingredient.ex | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 2 | 2020-07-05T21:27:33.000Z | 2021-12-12T22:56:00.000Z | lib/drunkard/recipes/recipe_ingredient.ex | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 1 | 2021-05-11T08:14:48.000Z | 2021-05-11T08:14:48.000Z | lib/drunkard/recipes/recipe_ingredient.ex | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 1 | 2020-07-05T21:27:46.000Z | 2020-07-05T21:27:46.000Z | defmodule Drunkard.Recipes.RecipeIngredient do
use Drunkard, :schema
embedded_schema do
field :amount, :decimal
field :is_garnish, :boolean, default: false
field :is_optional, :boolean, default: false
field :unit, :string
field :alternatives, {:array, :binary_id}
field :ingredient, :binary_id
timestamps()
end
@doc false
def changeset(recipe_ingredient, attrs) do
recipe_ingredient
|> cast(attrs, [:amount, :unit, :is_optional, :is_garnish, :unit, :ingredient, :alternatives])
|> validate_required([:amount, :unit, :is_optional, :is_garnish])
end
end
| 27.590909 | 98 | 0.70346 |
03367b473755cdc5ff70b9a535021a9e6a534e48 | 3,964 | ex | Elixir | lib/crew_web/live/live_helpers.ex | anamba/crew | c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1 | [
"BSL-1.0"
] | null | null | null | lib/crew_web/live/live_helpers.ex | anamba/crew | c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1 | [
"BSL-1.0"
] | 5 | 2020-07-20T01:49:01.000Z | 2021-09-08T00:17:04.000Z | lib/crew_web/live/live_helpers.ex | anamba/crew | c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1 | [
"BSL-1.0"
] | null | null | null | defmodule CrewWeb.LiveHelpers do
import Phoenix.LiveView
import Phoenix.LiveView.Helpers
import Phoenix.HTML.Link
alias CrewWeb.Router.Helpers, as: Routes
@doc """
Renders a component inside the `CrewWeb.ModalComponent` component.
The rendered modal receives a `:return_to` option to properly update
the URL when the modal is closed.
## Examples
<%= live_modal @socket, CrewWeb.OrganizationLive.FormComponent,
id: @organization.id || :new,
action: @live_action,
organization: @organization,
return_to: Routes.organization_index_path(@socket, :index) %>
"""
def live_modal(_socket, component, opts) do
path = Keyword.fetch!(opts, :return_to)
modal_opts = [id: :modal, return_to: path, component: component, opts: opts]
live_component(_socket, CrewWeb.ModalComponent, modal_opts)
end
def assign_from_session_with_person(socket, %{"person_id" => person_id} = params) do
socket =
socket
|> assign_from_session(params)
|> assign_new(:current_person, fn -> Crew.Persons.get_person(person_id) end)
if socket.assigns.current_person && socket.assigns.current_person.email_confirmed_at,
do: socket,
else: redirect(socket, to: Routes.public_signup_index_path(socket, :index))
end
def assign_from_session_with_person(socket, params) do
socket
|> assign_from_session(params)
|> redirect(to: Routes.public_signup_index_path(socket, :index))
end
def assign_from_session(socket, %{"site_id" => site_id}) do
socket =
socket
|> assign(:site_id, site_id)
|> assign_new(:current_site, fn -> Crew.Sites.get_site!(site_id) end)
socket
|> assign(:time_zone, socket.assigns.current_site.default_time_zone)
end
def assign_from_session(socket, _params) do
socket
end
def time_range_to_str(start_time, end_time) do
start_time_format =
if Timex.format!(start_time, "%p", :strftime) ==
Timex.format!(end_time, "%p", :strftime),
do: "%a %Y-%m-%d %-I:%M",
else: "%a %Y-%m-%d %-I:%M%P"
end_time_format =
if NaiveDateTime.to_date(start_time) == NaiveDateTime.to_date(end_time),
do: "%-I:%M%P",
else: "%a %Y-%m-%d %-I:%M%P"
Timex.format!(start_time, start_time_format, :strftime) <>
" – " <>
Timex.format!(end_time, end_time_format, :strftime)
end
def format_timestamp(timestamp, time_zone) do
Timex.Timezone.convert(timestamp, time_zone)
|> Timex.format!("%Y-%m-%d %I:%M%P", :strftime)
end
def last_page(count, per_page) do
ceil(count / per_page)
end
def paginator(page, per_page, count) do
assigns = []
~L"""
<%= if count > 0 do %>
<div class="my-4 text-center">
<%= if last_page(count, per_page) > 1 do %>
<div class="mb-2">
<div class="inline-block px-2 py-1 rounded-lg">
<%= if page > 1 do %>
<%= link "‹ Prev", to: "#", phx_click: "set_page", phx_value_page: page - 1 %>
<% else %>
‹ Prev
<% end %>
</div>
<%= for pg <- 1..last_page(count, per_page) do %>
<div class="inline-block px-2 py-1 <%= if page == pg, do: "bg-gray-100" %> rounded-lg">
<%= if page == pg, do: pg, else: link pg, to: "#", phx_click: "set_page", phx_value_page: pg %>
</div>
<% end %>
<div class="inline-block px-2 py-1 rounded-lg">
<%= if page < last_page(count, per_page) do %>
<%= link "Next ›", to: "#", phx_click: "set_page", phx_value_page: page + 1 %>
<% else %>
Next ›
<% end %>
</div>
</div>
<% end %>
<div class="text-sm">
Displaying <%= (page - 1) * per_page + 1 %>-<%= [page * per_page, count] |> Enum.min %> out of <%= count %>
</div>
</div>
<% end %>
"""
end
end
| 32.491803 | 117 | 0.590565 |
0336c22190f0e63f403421e9503b7b8bd0c8f385 | 1,667 | ex | Elixir | clients/sql_admin/lib/google_api/sql_admin/v1/model/failover_context.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1/model/failover_context.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1/model/failover_context.ex | MMore/elixir-google-api | 0574ec1439d9bbfe22d63965be1681b0f45a94c9 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SQLAdmin.V1.Model.FailoverContext do
@moduledoc """
Database instance failover context.
## Attributes
* `kind` (*type:* `String.t`, *default:* `nil`) - This is always `sql#failoverContext`.
* `settingsVersion` (*type:* `String.t`, *default:* `nil`) - The current settings version of this instance. Request will be rejected if this version doesn't match the current settings version.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t() | nil,
:settingsVersion => String.t() | nil
}
field(:kind)
field(:settingsVersion)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1.Model.FailoverContext do
def decode(value, options) do
GoogleApi.SQLAdmin.V1.Model.FailoverContext.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1.Model.FailoverContext do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.34 | 196 | 0.727654 |
0336e63b49a8683f8ae1b3017791bc7f9ebf3337 | 1,924 | ex | Elixir | clients/ad_sense_host/lib/google_api/ad_sense_host/v41/model/custom_channels.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/ad_sense_host/lib/google_api/ad_sense_host/v41/model/custom_channels.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/ad_sense_host/lib/google_api/ad_sense_host/v41/model/custom_channels.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.AdSenseHost.V41.Model.CustomChannels do
@moduledoc """
## Attributes
- etag (String): ETag of this response for caching purposes. Defaults to: `null`.
- items (List[CustomChannel]): The custom channels returned in this list response. Defaults to: `null`.
- kind (String): Kind of list this is, in this case adsensehost#customChannels. Defaults to: `null`.
- nextPageToken (String): Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's \"pageToken\" value to this. Defaults to: `null`.
"""
defstruct [
:"etag",
:"items",
:"kind",
:"nextPageToken"
]
end
defimpl Poison.Decoder, for: GoogleApi.AdSenseHost.V41.Model.CustomChannels do
import GoogleApi.AdSenseHost.V41.Deserializer
def decode(value, options) do
value
|> deserialize(:"items", :list, GoogleApi.AdSenseHost.V41.Model.CustomChannel, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdSenseHost.V41.Model.CustomChannels do
def encode(value, options) do
GoogleApi.AdSenseHost.V41.Deserializer.serialize_non_nil(value, options)
end
end
| 35.62963 | 209 | 0.744802 |
0336f496867277be616e0db527145e88350f8c45 | 991 | ex | Elixir | lib/surface_bootstrap/tab.ex | joerichsen/surface_bootstrap | 14a8b57126ead9a6593d628b9962e167fc01030d | [
"MIT"
] | null | null | null | lib/surface_bootstrap/tab.ex | joerichsen/surface_bootstrap | 14a8b57126ead9a6593d628b9962e167fc01030d | [
"MIT"
] | null | null | null | lib/surface_bootstrap/tab.ex | joerichsen/surface_bootstrap | 14a8b57126ead9a6593d628b9962e167fc01030d | [
"MIT"
] | null | null | null | defmodule SurfaceBootstrap.Tab do
@moduledoc """
Tab component.
This version does not support the full permutation of flexbox, if you
require that, it is probably better to make your own tab component.
This component only renders Tab.Item components and has no default slot.
https://getbootstrap.com/docs/5.0/components/navs-tabs/#tabs
"""
use Surface.Component
@doc "Render as pills"
prop pills, :boolean
@doc "Equal width nav items"
prop justified, :boolean
@doc "Fill width of container"
prop fill, :boolean
@doc "Any classes to put on the nav"
prop class, :css_class, default: []
slot static_tab_items
def render(assigns) do
~H"""
<nav class={{["nav", "nav-tabs": !@pills, "nav-pills": @pills, "nav-fill": @fill, "nav-justified": @justified] ++
@class}}>
<For each={{ {_tab_item, i} <- Enum.with_index(@static_tab_items) }}>
<slot name="static_tab_items" index={{ i }} />
</For>
</nav>
"""
end
end
| 25.410256 | 117 | 0.657921 |
0336f7343a7ab4142d401ef64ef6fe40bf759922 | 1,317 | ex | Elixir | clients/blogger/lib/google_api/blogger/v3/model/page_author_image.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/blogger/lib/google_api/blogger/v3/model/page_author_image.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/blogger/lib/google_api/blogger/v3/model/page_author_image.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.Blogger.V3.Model.PageAuthorImage do
@moduledoc """
The page author's avatar.
## Attributes
- url (String): The page author's avatar URL. Defaults to: `null`.
"""
defstruct [
:"url"
]
end
defimpl Poison.Decoder, for: GoogleApi.Blogger.V3.Model.PageAuthorImage do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Blogger.V3.Model.PageAuthorImage do
def encode(value, options) do
GoogleApi.Blogger.V3.Deserializer.serialize_non_nil(value, options)
end
end
| 28.630435 | 77 | 0.745634 |
03370dda04d4eaf6831868d0a55d4cedf064cd6f | 18,592 | ex | Elixir | lib/phoenix/channel.ex | arkgil/phoenix | b5d82814154b5fb87c0870e25c1c2243c9384d9e | [
"MIT"
] | null | null | null | lib/phoenix/channel.ex | arkgil/phoenix | b5d82814154b5fb87c0870e25c1c2243c9384d9e | [
"MIT"
] | null | null | null | lib/phoenix/channel.ex | arkgil/phoenix | b5d82814154b5fb87c0870e25c1c2243c9384d9e | [
"MIT"
] | null | null | null | defmodule Phoenix.Channel do
@moduledoc ~S"""
Defines a Phoenix Channel.
Channels provide a means for bidirectional communication from clients that
integrate with the `Phoenix.PubSub` layer for soft-realtime functionality.
## Topics & Callbacks
Every time you join a channel, you need to choose which particular topic you
want to listen to. The topic is just an identifier, but by convention it is
often made of two parts: `"topic:subtopic"`. Using the `"topic:subtopic"`
approach pairs nicely with the `Phoenix.Socket.channel/2` allowing you to
match on all topics starting with a given prefix:
channel "room:*", MyApp.RoomChannel
Any topic coming into the router with the `"room:"` prefix would dispatch
to `MyApp.RoomChannel` in the above example. Topics can also be pattern
matched in your channels' `join/3` callback to pluck out the scoped pattern:
# handles the special `"lobby"` subtopic
def join("room:lobby", _auth_message, socket) do
{:ok, socket}
end
# handles any other subtopic as the room ID, for example `"room:12"`, `"room:34"`
def join("room:" <> room_id, auth_message, socket) do
{:ok, socket}
end
## Authorization
Clients must join a channel to send and receive PubSub events on that channel.
Your channels must implement a `join/3` callback that authorizes the socket
for the given topic. For example, you could check if the user is allowed to
join that particular room.
To authorize a socket in `join/3`, return `{:ok, socket}`.
To refuse authorization in `join/3`, return `{:error, reply}`.
## Incoming Events
After a client has successfully joined a channel, incoming events from the
client are routed through the channel's `handle_in/3` callbacks. Within these
callbacks, you can perform any action. Typically you'll either forward a
message to all listeners with `broadcast!/3`, or push a message directly down
the socket with `push/3`. Incoming callbacks must return the `socket` to
maintain ephemeral state.
Here's an example of receiving an incoming `"new_msg"` event from one client,
and broadcasting the message to all topic subscribers for this socket.
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
broadcast!(socket, "new_msg", %{uid: uid, body: body})
{:noreply, socket}
end
You can also push a message directly down the socket:
# client asks for their current rank, push sent directly as a new event.
def handle_in("current_rank", socket) do
push(socket, "current_rank", %{val: Game.get_rank(socket.assigns[:user])})
{:noreply, socket}
end
## Replies
In addition to pushing messages out when you receive a `handle_in` event,
you can also reply directly to a client event for request/response style
messaging. This is useful when a client must know the result of an operation
or to simply ack messages.
For example, imagine creating a resource and replying with the created record:
def handle_in("create:post", attrs, socket) do
changeset = Post.changeset(%Post{}, attrs)
if changeset.valid? do
post = Repo.insert!(changeset)
response = MyApp.PostView.render("show.json", %{post: post})
{:reply, {:ok, response}, socket}
else
response = MyApp.ChangesetView.render("errors.json", %{changeset: changeset})
{:reply, {:error, response}, socket}
end
end
Alternatively, you may just want to ack the status of the operation:
def handle_in("create:post", attrs, socket) do
changeset = Post.changeset(%Post{}, attrs)
if changeset.valid? do
Repo.insert!(changeset)
{:reply, :ok, socket}
else
{:reply, :error, socket}
end
end
## Intercepting Outgoing Events
When an event is broadcasted with `broadcast/3`, each channel subscriber can
choose to intercept the event and have their `handle_out/3` callback triggered.
This allows the event's payload to be customized on a socket by socket basis
to append extra information, or conditionally filter the message from being
delivered. If the event is not intercepted with `Phoenix.Channel.intercept/1`,
then the message is pushed directly to the client:
intercept ["new_msg", "user_joined"]
# for every socket subscribing to this topic, append an `is_editable`
# value for client metadata.
def handle_out("new_msg", msg, socket) do
push(socket, "new_msg", Map.merge(msg,
%{is_editable: User.can_edit_message?(socket.assigns[:user], msg)}
))
{:noreply, socket}
end
# do not send broadcasted `"user_joined"` events if this socket's user
# is ignoring the user who joined.
def handle_out("user_joined", msg, socket) do
unless User.ignoring?(socket.assigns[:user], msg.user_id) do
push(socket, "user_joined", msg)
end
{:noreply, socket}
end
## Broadcasting to an external topic
In some cases, you will want to broadcast messages without the context of
a `socket`. This could be for broadcasting from within your channel to an
external topic, or broadcasting from elsewhere in your application like a
controller or another process. Such can be done via your endpoint:
# within channel
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
...
broadcast_from!(socket, "new_msg", %{uid: uid, body: body})
MyApp.Endpoint.broadcast_from!(self(), "room:superadmin",
"new_msg", %{uid: uid, body: body})
{:noreply, socket}
end
# within controller
def create(conn, params) do
...
MyApp.Endpoint.broadcast!("room:" <> rid, "new_msg", %{uid: uid, body: body})
MyApp.Endpoint.broadcast!("room:superadmin", "new_msg", %{uid: uid, body: body})
redirect(conn, to: "/")
end
## Terminate
On termination, the channel callback `terminate/2` will be invoked with
the error reason and the socket.
If we are terminating because the client left, the reason will be
`{:shutdown, :left}`. Similarly, if we are terminating because the
client connection was closed, the reason will be `{:shutdown, :closed}`.
If any of the callbacks return a `:stop` tuple, it will also
trigger terminate with the reason given in the tuple.
`terminate/2`, however, won't be invoked in case of errors nor in
case of exits. This is the same behaviour as you find in Elixir
abstractions like `GenServer` and others. Typically speaking, if you
want to clean something up, it is better to monitor your channel
process and do the clean up from another process. Similar to GenServer,
it would also be possible `:trap_exit` to guarantee that `terminate/2`
is invoked. This practice is not encouraged though.
## Exit reasons when stopping a channel
When the channel callbacks return a `:stop` tuple, such as:
{:stop, :shutdown, socket}
{:stop, {:error, :enoent}, socket}
the second argument is the exit reason, which follows the same behaviour as
standard `GenServer` exits.
You have three options to choose from when shutting down a channel:
* `:normal` - in such cases, the exit won't be logged, there is no restart
in transient mode, and linked processes do not exit
* `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be
logged, there is no restart in transient mode, and linked processes exit
with the same reason unless they're trapping exits
* any other term - in such cases, the exit will be logged, there are
restarts in transient mode, and linked processes exit with the same reason
unless they're trapping exits
## Subscribing to external topics
Sometimes you may need to programmatically subscribe a socket to external
topics in addition to the the internal `socket.topic`. For example,
imagine you have a bidding system where a remote client dynamically sets
preferences on products they want to receive bidding notifications on.
Instead of requiring a unique channel process and topic per
preference, a more efficient and simple approach would be to subscribe a
single channel to relevant notifications via your endpoint. For example:
defmodule MyApp.Endpoint.NotificationChannel do
use Phoenix.Channel
def join("notification:" <> user_id, %{"ids" => ids}, socket) do
topics = for product_id <- ids, do: "product:#{product_id}"
{:ok, socket
|> assign(:topics, [])
|> put_new_topics(topics)}
end
def handle_in("watch", %{"product_id" => id}, socket) do
{:reply, :ok, put_new_topics(socket, ["product:#{id}"])}
end
def handle_in("unwatch", %{"product_id" => id}, socket) do
{:reply, :ok, MyApp.Endpoint.unsubscribe("product:#{id}")}
end
defp put_new_topics(socket, topics) do
Enum.reduce(topics, socket, fn topic, acc ->
topics = acc.assigns.topics
if topic in topics do
acc
else
:ok = MyApp.Endpoint.subscribe(topic)
assign(acc, :topics, [topic | topics])
end
end)
end
end
Note: the caller must be responsible for preventing duplicate subscriptions.
After calling `subscribe/1` from your endpoint, the same flow applies to
handling regular Elixir messages within your channel. Most often, you'll
simply relay the `%Phoenix.Socket.Broadcast{}` event and payload:
alias Phoenix.Socket.Broadcast
def handle_info(%Broadcast{topic: _, event: ev, payload: payload}, socket) do
push(socket, ev, payload)
{:noreply, socket}
end
## Logging
By default, channel `"join"` and `"handle_in"` events are logged, using
the level `:info` and `:debug`, respectively. Logs can be customized per
event type or disabled by setting the `:log_join` and `:log_handle_in`
options when using `Phoenix.Channel`. For example, the following
configuration logs join events as `:info`, but disables logging for
incoming events:
use Phoenix.Channel, log_join: :info, log_handle_in: false
"""
alias Phoenix.Socket
alias Phoenix.Channel.Server
@type reply :: status :: atom | {status :: atom, response :: map}
@type socket_ref ::
{transport_pid :: Pid, serializer :: module, topic :: binary, ref :: binary,
join_ref :: binary}
@callback join(topic :: binary, auth_msg :: map, Socket.t()) ::
{:ok, Socket.t()}
| {:ok, map, Socket.t()}
| {:error, map}
@callback handle_in(event :: String.t(), msg :: map, Socket.t()) ::
{:noreply, Socket.t()}
| {:noreply, Socket.t(), timeout | :hibernate}
| {:reply, reply, Socket.t()}
| {:stop, reason :: term, Socket.t()}
| {:stop, reason :: term, reply, Socket.t()}
@callback handle_out(event :: String.t(), msg :: map, Socket.t()) ::
{:noreply, Socket.t()}
| {:noreply, Socket.t(), timeout | :hibernate}
| {:stop, reason :: term, Socket.t()}
@callback handle_info(term, Socket.t()) ::
{:noreply, Socket.t()}
| {:stop, reason :: term, Socket.t()}
@callback code_change(old_vsn, Socket.t(), extra :: term) ::
{:ok, Socket.t()}
| {:error, reason :: term}
when old_vsn: term | {:down, term}
@callback terminate(
reason :: :normal | :shutdown | {:shutdown, :left | :closed | term},
Socket.t()
) :: term
@optional_callbacks handle_in: 3, handle_out: 3, handle_info: 2, code_change: 3, terminate: 2
defmacro __using__(opts \\ []) do
quote do
opts = unquote(opts)
@behaviour unquote(__MODULE__)
@on_definition unquote(__MODULE__)
@before_compile unquote(__MODULE__)
@phoenix_intercepts []
@phoenix_log_join Keyword.get(opts, :log_join, :info)
@phoenix_log_handle_in Keyword.get(opts, :log_handle_in, :debug)
import unquote(__MODULE__)
import Phoenix.Socket, only: [assign: 3]
def __socket__(:private) do
%{log_join: @phoenix_log_join, log_handle_in: @phoenix_log_handle_in}
end
end
end
defmacro __before_compile__(_) do
quote do
def __intercepts__, do: @phoenix_intercepts
end
end
@doc """
Defines which Channel events to intercept for `handle_out/3` callbacks.
By default, broadcasted events are pushed directly to the client, but
intercepting events gives your channel a chance to customize the event
for the client to append extra information or filter the message from being
delivered.
*Note*: intercepting events can introduce significantly more overhead if a
large number of subscribers must customize a message since the broadcast will
be encoded N times instead of a single shared encoding across all subscribers.
## Examples
intercept ["new_msg"]
def handle_out("new_msg", payload, socket) do
push(socket, "new_msg", Map.merge(payload,
is_editable: User.can_edit_message?(socket.assigns[:user], payload)
))
{:noreply, socket}
end
`handle_out/3` callbacks must return one of:
{:noreply, Socket.t} |
{:stop, reason :: term, Socket.t}
"""
defmacro intercept(events) do
quote do
@phoenix_intercepts unquote(events)
end
end
@doc false
def __on_definition__(env, :def, :handle_out, [event, _payload, _socket], _, _)
when is_binary(event) do
unless event in Module.get_attribute(env.module, :phoenix_intercepts) do
IO.write(
"#{Path.relative_to(env.file, File.cwd!())}:#{env.line}: [warning] " <>
"An intercept for event \"#{event}\" has not yet been defined in #{env.module}.handle_out/3. " <>
"Add \"#{event}\" to your list of intercepted events with intercept/1"
)
end
end
def __on_definition__(_env, _kind, _name, _args, _guards, _body) do
:ok
end
@doc """
Broadcast an event to all subscribers of the socket topic.
The event's message must be a serializable map.
## Examples
iex> broadcast(socket, "new_message", %{id: 1, content: "hello"})
:ok
"""
def broadcast(socket, event, message) do
%{pubsub_server: pubsub_server, topic: topic} = assert_joined!(socket)
Server.broadcast(pubsub_server, topic, event, message)
end
@doc """
Same as `broadcast/3`, but raises if broadcast fails.
"""
def broadcast!(socket, event, message) do
%{pubsub_server: pubsub_server, topic: topic} = assert_joined!(socket)
Server.broadcast!(pubsub_server, topic, event, message)
end
@doc """
Broadcast event from pid to all subscribers of the socket topic.
The channel that owns the socket will not receive the published
message. The event's message must be a serializable map.
## Examples
iex> broadcast_from(socket, "new_message", %{id: 1, content: "hello"})
:ok
"""
def broadcast_from(socket, event, message) do
%{pubsub_server: pubsub_server, topic: topic, channel_pid: channel_pid} =
assert_joined!(socket)
Server.broadcast_from(pubsub_server, channel_pid, topic, event, message)
end
@doc """
Same as `broadcast_from/3`, but raises if broadcast fails.
"""
def broadcast_from!(socket, event, message) do
%{pubsub_server: pubsub_server, topic: topic, channel_pid: channel_pid} =
assert_joined!(socket)
Server.broadcast_from!(pubsub_server, channel_pid, topic, event, message)
end
@doc """
Sends event to the socket.
The event's message must be a serializable map.
## Examples
iex> push(socket, "new_message", %{id: 1, content: "hello"})
:ok
"""
def push(socket, event, message) do
%{transport_pid: transport_pid, topic: topic} = assert_joined!(socket)
Server.push(transport_pid, topic, event, message, socket.serializer)
end
@doc """
Replies asynchronously to a socket push.
Useful when you need to reply to a push that can't otherwise be handled using
the `{:reply, {status, payload}, socket}` return from your `handle_in`
callbacks. `reply/2` will be used in the rare cases you need to perform work in
another process and reply when finished by generating a reference to the push
with `socket_ref/1`.
*Note*: In such cases, a `socket_ref` should be generated and
passed to the external process, so the `socket` itself is not leaked outside
the channel. The `socket` holds information such as assigns and transport
configuration, so it's important to not copy this information outside of the
channel that owns it.
## Examples
def handle_in("work", payload, socket) do
Worker.perform(payload, socket_ref(socket))
{:noreply, socket}
end
def handle_info({:work_complete, result, ref}, socket) do
reply(ref, {:ok, result})
{:noreply, socket}
end
"""
@spec reply(socket_ref, reply) :: :ok
def reply(socket_ref, status) when is_atom(status) do
reply(socket_ref, {status, %{}})
end
def reply({transport_pid, serializer, topic, ref, join_ref}, {status, payload}) do
Server.reply(transport_pid, join_ref, ref, topic, {status, payload}, serializer)
end
@doc """
Generates a `socket_ref` for an async reply.
See `reply/2` for example usage.
"""
@spec socket_ref(Socket.t()) :: socket_ref
def socket_ref(%Socket{joined: true, ref: ref} = socket) when not is_nil(ref) do
{socket.transport_pid, socket.serializer, socket.topic, ref, socket.join_ref}
end
def socket_ref(_socket) do
raise ArgumentError, """
Socket refs can only be generated for a socket that has joined with a push ref
"""
end
defp assert_joined!(%Socket{joined: true} = socket) do
socket
end
defp assert_joined!(%Socket{joined: false}) do
raise """
`push`, `reply`, and `broadcast` can only be called after the socket has finished joining.
To push a message on join, send to self and handle in handle_info/2, ie:
def join(topic, auth_msg, socket) do
...
send(self, :after_join)
{:ok, socket}
end
def handle_info(:after_join, socket) do
push(socket, "feed", %{list: feed_items(socket)})
{:noreply, socket}
end
"""
end
end
| 35.413333 | 107 | 0.664372 |
03372be9b96b2bc70d01d780ed9a664578262e79 | 646 | ex | Elixir | apps/customer/lib/customer/web/views/api/v1/favorite_job_view.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 102 | 2017-05-21T18:24:04.000Z | 2022-03-10T12:53:20.000Z | apps/customer/lib/customer/web/views/api/v1/favorite_job_view.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 2 | 2017-05-21T01:53:30.000Z | 2017-12-01T00:27:06.000Z | apps/customer/lib/customer/web/views/api/v1/favorite_job_view.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 18 | 2017-05-22T09:51:36.000Z | 2021-09-24T00:57:01.000Z | defmodule Customer.Web.Api.V1.FavoriteJobView do
use Customer.Web, :view
def render("index.json", %{favorite_jobs: favorite_jobs}) do
%{favoriteJobs: Enum.map(favorite_jobs, &(parse(&1)))}
end
def render("show.json", %{favorite_job_id: favorite_job_id} = param) do
%{favoriteJobId: favorite_job_id}
end
defp parse(%FavoriteJob{interest: interest, job_id: job_id, job: job, status: status, remarks: remarks}) do
%{
interest: interest,
jobId: job_id,
jobTitle: job.title["value"],
area: job.area.name,
status: status,
company: job.company.name,
remarks: remarks
}
end
end
| 25.84 | 109 | 0.665635 |
03374eab220bd071b7d1123caf970ec7add4221e | 430 | ex | Elixir | lib/pugme/pugfinder.ex | KevinGreene/Tinc | 4101e4bd24ba81f84e51e9a85be3609515087e6e | [
"MIT"
] | null | null | null | lib/pugme/pugfinder.ex | KevinGreene/Tinc | 4101e4bd24ba81f84e51e9a85be3609515087e6e | [
"MIT"
] | null | null | null | lib/pugme/pugfinder.ex | KevinGreene/Tinc | 4101e4bd24ba81f84e51e9a85be3609515087e6e | [
"MIT"
] | null | null | null | defmodule Pugme.PugFinder do
@url "http://pugme.herokuapp.com/random"
def get_pug() do
case HTTPoison.get(@url) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
Poison.decode!(body)
|> Dict.get("pug")
{:ok, %HTTPoison.Response{status_code: 404}} ->
IO.puts "Not found :("
{:error, %HTTPoison.Error{reason: reason}} ->
IO.inspect reason
end
end
end
| 25.294118 | 65 | 0.597674 |
033788e417c75e1aeba56ca5db5407ce8f03867c | 1,768 | exs | Elixir | test/git_hub_actions_case.exs | kianmeng/git_hub_actions | f60cc151d6dc13983132fbf773f3233ca381406d | [
"MIT"
] | 6 | 2021-08-22T22:23:54.000Z | 2021-08-29T12:25:53.000Z | test/git_hub_actions_case.exs | kianmeng/git_hub_actions | f60cc151d6dc13983132fbf773f3233ca381406d | [
"MIT"
] | 2 | 2022-02-15T16:36:41.000Z | 2022-02-18T17:32:07.000Z | test/git_hub_actions_case.exs | hrzndhrn/git_hub_actions | 5d96718cf5aacb017c0b1114ca3283fe75c8913e | [
"MIT"
] | null | null | null | defmodule GitHubActionsCase do
use ExUnit.CaseTemplate
import ExUnit.CaptureIO
import Mock
@dir ".gha"
@fixtures "test/fixtures"
@tmp "test/tmp"
@home Path.join(@tmp, "home")
@config "config.exs"
@defaults [workflow: :default, config: :default, output: :default]
using do
{module, default} =
case __CALLER__.module do
Mix.Tasks.GhaTest -> {Mix.Tasks.Gha, []}
_else -> {GitHubActions, @defaults}
end
quote do
import GitHubActionsCase
def assert_run(file, opts \\ unquote(default)) do
assert capture_io(fn -> unquote(module).run(opts) end) =~
~r|creating.+test/tmp/#{file}|
assert file |> tmp() |> File.read!() == file |> fixture() |> File.read!()
end
end
end
setup_with_mocks([
{System, [:passthrough], [user_home!: fn -> @home end]}
]) do
# Create local .gha dir for config.
File.mkdir(@dir)
File.mkdir_p(Path.join(@home, @dir))
on_exit(fn ->
File.rm_rf!(@dir)
File.rm_rf!(@home)
@tmp
|> File.ls!()
|> Enum.each(fn
".keep" -> :ok
file -> @tmp |> Path.join(file) |> File.rm!()
end)
end)
:ok
end
def tmp, do: @tmp
def tmp(file), do: Path.join(@tmp, file)
def fixture(file), do: Path.join(@fixtures, file)
def local(file), do: Path.join(@dir, file)
def local_config(term) do
write_config(Path.join(@dir, @config), term)
end
def global_config(term) do
write_config(Path.join([@home, @dir, @config]), term)
end
defp write_config(path, term) do
File.write!(path, """
import GitHubActions.Config
config(#{inspect(term)})
""")
end
def opts, do: @defaults
def opts(opts), do: Keyword.merge(@defaults, opts)
end
| 21.560976 | 81 | 0.59276 |
0337a89b050d378fa9212f31e74630bf71e3ee0a | 77 | ex | Elixir | extended_example/lib/demo/events/shipment_registered.ex | PJUllrich/event-sourcing-with-elixir | 7f70e6bc49d9d93f1d86513a1f358e41e07b8304 | [
"MIT"
] | 19 | 2020-10-08T14:05:30.000Z | 2022-03-18T08:43:11.000Z | extended_example/lib/demo/events/shipment_registered.ex | PJUllrich/event-sourcing-with-elixir | 7f70e6bc49d9d93f1d86513a1f358e41e07b8304 | [
"MIT"
] | null | null | null | extended_example/lib/demo/events/shipment_registered.ex | PJUllrich/event-sourcing-with-elixir | 7f70e6bc49d9d93f1d86513a1f358e41e07b8304 | [
"MIT"
] | 3 | 2021-02-19T08:31:58.000Z | 2021-12-09T05:28:55.000Z | defmodule ShipmentRegistered do
defstruct [:shipment_id, :destination]
end
| 19.25 | 40 | 0.818182 |
0337dfdb695858ba5155faa63c630659adf3aa3a | 6,200 | ex | Elixir | lib/bluex/dbus_discovery.ex | highmobility/bluex | 2ad4b713445734a235fd997fce0f8f4c934179fc | [
"MIT"
] | 18 | 2016-09-28T20:23:41.000Z | 2021-03-17T03:36:27.000Z | lib/bluex/dbus_discovery.ex | highmobility/bluex | 2ad4b713445734a235fd997fce0f8f4c934179fc | [
"MIT"
] | 1 | 2016-10-27T08:40:10.000Z | 2016-10-27T08:40:10.000Z | lib/bluex/dbus_discovery.ex | highmobility/bluex | 2ad4b713445734a235fd997fce0f8f4c934179fc | [
"MIT"
] | 6 | 2017-09-02T08:03:56.000Z | 2020-07-07T19:03:40.000Z | defmodule Bluex.DBusDiscovery do
@dbus_name Application.get_env(:bluex, :dbus_name) || "org.bluez"
@iface_dbus_name Application.get_env(:bluex, :iface_dbus_name) || "org.bluez.Adapter1"
@device_dbus_name Application.get_env(:bluex, :device_dbus_name) || "org.bluez.Device1"
@dbus_bluez_path Application.get_env(:bluex, :dbus_bluez_path) || "/org/bluez"
@dbus_type Application.get_env(:bluex, :bus_type) || :system
use GenServer
alias Bluex.DiscoveryFilter
@doc """
Gets list of adapters
"""
@spec get_adapters(pid) :: list(String.t)
def get_adapters(pid) do
GenServer.call(pid, :get_adapters)
end
@doc """
Gets list of devices
"""
@spec get_devices(pid) :: list(%Bluex.Device{})
def get_devices(pid) do
GenServer.call(pid, :get_devices)
end
@doc false
@spec device_found(pid, %Bluex.Device{}) :: :ok
def device_found(pid, device) do
GenServer.cast(pid, {:device_found, device})
end
def start_link(module, opts \\ []) do
GenServer.start_link(__MODULE__, [module, opts], name: module)
end
@doc """
Starts Bluetooth discovery
"""
@spec start_discovery(pid) :: :ok
def start_discovery(pid) do
GenServer.cast(pid, {:start_discovery, %DiscoveryFilter{}})
end
@doc """
Starts Bluetooth discovery and sets the device discovery filter.
Filter is `Bluex.DiscoveryFilter` struct.
"""
@spec start_discovery(pid, %DiscoveryFilter{}) :: :ok
def start_discovery(pid, filter) do
GenServer.cast(pid, {:start_discovery, filter})
end
@doc """
Starts Bluetooth discovery
"""
@spec stop_discovery(pid) :: :ok
def stop_discovery(pid) do
GenServer.cast(pid, :stop_discovery)
end
@doc false
def init([module, _opts]) do
{:ok, bus} = :dbus_bus_connection.connect(@dbus_type)
{:ok, adapter_manager} = :dbus_proxy.start_link(bus, @dbus_name, @dbus_bluez_path)
{:ok, bluez_manager} = :dbus_proxy.start_link(bus, @dbus_name, "/")
{:ok, %{bus: bus, adapter_manager: adapter_manager, devices: [], adapters: [], bluez_manager: bluez_manager, module: module}}
end
@doc false
def handle_call(:get_adapters, _, state) do
{:reply, state[:adapters], state}
end
@doc false
def handle_call(:get_devices, _, state) do
{:reply, state[:devices], state}
end
@doc false
def handle_info({:dbus_signal, _}, state) do
GenServer.cast(state[:module], :get_adapters)
{:noreply, state}
end
@doc false
def handle_cast(:get_adapters, state) do
adapters = :dbus_proxy.children(state[:adapter_manager])
|> Stream.map(&Path.basename/1)
|> Stream.map(fn (adapter) ->
bluez_path = "#{@dbus_bluez_path}/#{adapter}"
{:ok, adapter_proxy} = :dbus_proxy.start_link(state[:bus], @dbus_name, bluez_path)
:dbus_proxy.has_interface(adapter_proxy, @iface_dbus_name)
{adapter, %{path: bluez_path, proxy: adapter_proxy}}
end)
|> Stream.filter(fn ({_, %{proxy: adapter_proxy}}) ->
#TODO close invalid adapter
:dbus_proxy.has_interface(adapter_proxy, @iface_dbus_name)
end)
|> Enum.into(%{})
state = Map.put(state, :adapters, adapters)
{:noreply, state}
end
@doc false
def handle_cast(:stop_discovery, state) do
state[:adapters]
|> Enum.each(fn ({_, %{proxy: adapter_proxy}}) ->
:dbus_proxy.call(adapter_proxy, @iface_dbus_name, "StopDiscovery", [])
end)
{:noreply, state}
end
@doc false
def handle_cast({:start_discovery, filter}, state) do
#TODO: ???get list of devices now and call the device_found callback before leaving this function
add_interface = fn(_sender, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded", _path, args, pid) ->
case args do
{_interface_bluez_path, %{@device_dbus_name => device_details}} ->
device = %Bluex.Device{}
|> Map.put(:mac_address, device_details["Address"])
|> Map.put(:manufacturer_data, device_details["ManufacturerData"])
|> Map.put(:rssi, device_details["RSSI"])
|> Map.put(:uuids, device_details["UUIDs"])
|> Map.put(:adapter, Path.basename(device_details["Adapter"]))
Bluex.DBusDiscovery.device_found(pid, device)
_ -> :ok
end
end
:dbus_proxy.connect_signal(state[:bluez_manager],
"org.freedesktop.DBus.ObjectManager",
"InterfacesAdded",
{add_interface, self})
:dbus_proxy.children(state[:bluez_manager])
state[:adapters]
|> Enum.filter(&(match_adapter(&1, filter)))
|> Enum.map(fn ({_, %{proxy: adapter_proxy}}) ->
:ok = :dbus_proxy.call(adapter_proxy, @iface_dbus_name, "SetDiscoveryFilter", [filter_to_dbus_array(filter)])
:ok = :dbus_proxy.call(adapter_proxy, @iface_dbus_name, "StartDiscovery", [])
end)
|> Kernel."=="([])
|> if(do: throw {:stop, {:adapter_not_found, filter.adapters}, state})
{:noreply, state}
end
@doc false
def handle_cast({:device_found, device}, state) do
state = case apply(state[:module], :device_found, [device]) do
:ok ->
Map.put(state, :devices, [device])
_ ->
state
end
{:noreply, state}
end
defp filter_to_dbus_array(filter) do
%{
"Transport" => {:dbus_variant, :string, Atom.to_string(filter.transport)},
"UUIDs" => {:dbus_variant, {:array, :string}, filter.uuids}
}
end
defp match_adapter({adapter_name, _}, filter) do
case filter.adapters do
[] -> true
adapters -> Enum.member?(adapters, adapter_name)
end
end
defmacro __using__(_opts) do
quote [unquote: false, location: :keep] do
@behaviour Bluex.Discovery
import Bluex.DBusDiscovery
use GenServer
@doc false
def start_link do
Bluex.DBusDiscovery.start_link(__MODULE__, [])
end
@doc """
Starts Bluetooth discovery
"""
def start_discovery(filter \\ %DiscoveryFilter{}) do
Bluex.DBusDiscovery.start_discovery(__MODULE__, filter)
end
def stop_discovery do
Bluex.DBusDiscovery.stop_discovery(__MODULE__)
end
end
end
end
| 30.845771 | 129 | 0.647903 |
0337e9cc7c84dda7225062eb4d5cc694a255a47b | 724 | exs | Elixir | apps/api/test/api/error_enhancer_test.exs | omgnetwork/omg-childchain-v2 | 31cc9cf9e42718fc3b9bd6668f24a627cac80b4f | [
"Apache-2.0"
] | 4 | 2020-11-30T17:38:57.000Z | 2021-01-23T21:29:41.000Z | apps/api/test/api/error_enhancer_test.exs | omgnetwork/omg-childchain-v2 | 31cc9cf9e42718fc3b9bd6668f24a627cac80b4f | [
"Apache-2.0"
] | 24 | 2020-11-30T17:32:48.000Z | 2021-02-22T06:25:22.000Z | apps/api/test/api/error_enhancer_test.exs | omgnetwork/omg-childchain-v2 | 31cc9cf9e42718fc3b9bd6668f24a627cac80b4f | [
"Apache-2.0"
] | null | null | null | defmodule API.ErrorEnhancerTest do
use ExUnit.Case, async: true
alias API.ErrorEnhancer
describe "enhance/1" do
test "enhance a changeset error" do
changeset = Ecto.Changeset.add_error(%Ecto.Changeset{}, :some_key, "some_error")
assert ErrorEnhancer.enhance({:error, changeset}) == {:error, :validation_error, "some_key: some_error"}
end
test "enhance a tuple of errors with a known error" do
assert ErrorEnhancer.enhance({:error, :decoding_error}) == {:error, :decoding_error, "Invalid hex encoded binary"}
end
test "enhance a tuple of errors with a unknown error" do
assert ErrorEnhancer.enhance({:error, :unknown_key}) == {:error, :unknown_key, ""}
end
end
end
| 34.47619 | 120 | 0.700276 |
0337fd41d3f120fbdcccf3af6522939a1cfc7bae | 1,601 | exs | Elixir | test/services/coto_search_service_test.exs | pamf/cotoami | 4b69b0e2668e80e12ea98e248ad461cb32ec6651 | [
"Apache-2.0"
] | 337 | 2016-11-28T15:46:58.000Z | 2022-03-01T06:21:25.000Z | test/services/coto_search_service_test.exs | kroschu/cotoami | ae02a9e9982060977a565ed8137334258ff4faf0 | [
"Apache-2.0"
] | 79 | 2017-02-27T05:44:36.000Z | 2021-12-09T00:28:11.000Z | test/services/coto_search_service_test.exs | kroschu/cotoami | ae02a9e9982060977a565ed8137334258ff4faf0 | [
"Apache-2.0"
] | 47 | 2018-02-03T01:32:13.000Z | 2021-11-08T07:54:43.000Z | defmodule Cotoami.CotoSearchServiceTest do
use Cotoami.DataCase
import ShorterMaps
alias Cotoami.{
Fixtures,
Repo,
EmailUser,
Coto,
AmishiService,
CotoSearchService
}
setup do
amishi_a = AmishiService.insert_or_update!(%EmailUser{email: "[email protected]"})
amishi_b = AmishiService.insert_or_update!(%EmailUser{email: "[email protected]"})
cotonoma_a = Fixtures.create_cotonoma!("cotonoma a", false, amishi_a)
~M{amishi_a, amishi_b, cotonoma_a}
end
describe "when there are private cotos by amishi_a" do
setup ~M{amishi_a, cotonoma_a} do
coto1 = Fixtures.create_coto!("Search has become an important feature.", amishi_a)
coto2 = Fixtures.create_coto!("You are often asked to add search.", amishi_a, cotonoma_a)
~M{coto1, coto2}
end
test "amishi_a searches the cotos and finds a single result", ~M{amishi_a} do
assert search(amishi_a, "important") == [
"Search has become an important feature."
]
end
test "multiple results should be sorted in ascending order of date", ~M{amishi_a} do
assert search(amishi_a, "search") == [
"You are often asked to add search.",
"Search has become an important feature."
]
end
test "amishi_b shouldn't be able to search the cotos", ~M{amishi_b} do
assert search(amishi_b, "search") == []
end
end
defp search(amishi, search_string) do
Coto
|> CotoSearchService.search(amishi, search_string)
|> Repo.all()
|> Enum.map(& &1.content)
end
end
| 30.207547 | 95 | 0.661462 |
033845f6a3968352fe610d9440ec21db59afba81 | 255 | ex | Elixir | lib/the_end/listener_gatherer/plug.ex | MozillaReality/the_end | 51e9b0860b96ec5e0cbfc9e84f8fb120387ca4de | [
"MIT"
] | 13 | 2017-10-31T12:20:30.000Z | 2020-05-08T21:10:28.000Z | lib/the_end/listener_gatherer/plug.ex | MozillaReality/the_end | 51e9b0860b96ec5e0cbfc9e84f8fb120387ca4de | [
"MIT"
] | 1 | 2018-11-09T18:42:28.000Z | 2020-06-30T18:46:52.000Z | lib/the_end/listener_gatherer/plug.ex | MozillaReality/the_end | 51e9b0860b96ec5e0cbfc9e84f8fb120387ca4de | [
"MIT"
] | 2 | 2018-08-08T04:47:41.000Z | 2020-04-20T01:01:21.000Z | defmodule TheEnd.ListenerGatherer.Plug do
@behaviour TheEnd.ListenerGatherer
import Supervisor, only: [which_children: 1]
def gather(endpoint) do
for {{:ranch_listener_sup, _}, pid, _, _} <- which_children(endpoint),
do: pid
end
end
| 19.615385 | 74 | 0.713725 |
0338491963d681d36e0caa584937eabb9a00da9b | 2,043 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/gradient_rule.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/gradient_rule.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sheets/lib/google_api/sheets/v4/model/gradient_rule.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.Sheets.V4.Model.GradientRule do
@moduledoc """
A rule that applies a gradient color scale format, based on the interpolation points listed. The format of a cell will vary based on its contents as compared to the values of the interpolation points.
## Attributes
- maxpoint (InterpolationPoint): The final interpolation point. Defaults to: `null`.
- midpoint (InterpolationPoint): An optional midway interpolation point. Defaults to: `null`.
- minpoint (InterpolationPoint): The starting interpolation point. Defaults to: `null`.
"""
defstruct [
:"maxpoint",
:"midpoint",
:"minpoint"
]
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.GradientRule do
import GoogleApi.Sheets.V4.Deserializer
def decode(value, options) do
value
|> deserialize(:"maxpoint", :struct, GoogleApi.Sheets.V4.Model.InterpolationPoint, options)
|> deserialize(:"midpoint", :struct, GoogleApi.Sheets.V4.Model.InterpolationPoint, options)
|> deserialize(:"minpoint", :struct, GoogleApi.Sheets.V4.Model.InterpolationPoint, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.GradientRule do
def encode(value, options) do
GoogleApi.Sheets.V4.Deserializer.serialize_non_nil(value, options)
end
end
| 37.833333 | 202 | 0.754772 |
0338658ae83864c60790448483e9646708967817 | 953 | exs | Elixir | sparkline_idea.exs | pmarreck/elixir-snippets | 5f5ee26087bc2ded4e71c4c3eeff1231310ff358 | [
"BSD-3-Clause"
] | 34 | 2015-02-27T14:41:12.000Z | 2021-09-26T06:06:18.000Z | sparkline_idea.exs | pmarreck/elixir-snippets | 5f5ee26087bc2ded4e71c4c3eeff1231310ff358 | [
"BSD-3-Clause"
] | null | null | null | sparkline_idea.exs | pmarreck/elixir-snippets | 5f5ee26087bc2ded4e71c4c3eeff1231310ff358 | [
"BSD-3-Clause"
] | 3 | 2016-02-05T16:09:41.000Z | 2017-10-21T15:47:04.000Z | defmodule Sparkline do
@zombie %{
draw: %{
"1 2.5 3 5, 3 1" => '▁▄▅█▅▁',
"1 2 3, 5 2 1" => '▁▃▅█▃▁'
}
}
# hypothetical inline spec/stub API
# spec draw(str) do
# case str do
# "1 2.5 3 5, 3 1" -> '▁▄▅█▅▁'
# "1 2 3, 5 2 1" -> '▁▃▅█▃▁'
# end
# end
def draw(str) do
values = str |> String.split(~r/[, ]+/)
|> Enum.map(&(elem(Float.parse(&1), 0)))
{min, max} = {Enum.min(values), Enum.max(values)}
values |> Enum.map(&(round((&1 - min) / (max - min) * 7 + 0x2581)))
end
# should be the last function
def zombie do
@zombie
end
end
# run this inline suite with "elixir #{__ENV__.file} test"
if System.argv |> List.first == "test" do
ExUnit.start
defmodule SparklineTest do
use ExUnit.Case, async: true
test "sparkline" do
Sparkline.zombie[:draw] |> Enum.each(
fn {x, y} -> assert Sparkline.draw(x) == y end
)
end
end
end
| 22.162791 | 71 | 0.515215 |
03387c03dfacf0fe4790392195f0fe7fff9b5493 | 1,747 | exs | Elixir | test/atecc508a/data_zone_test.exs | bcdevices/atecc508a | 934652947ac1de2022f1da556adffa3e8cba31e3 | [
"Apache-2.0"
] | 6 | 2018-12-13T16:33:09.000Z | 2022-03-02T08:57:20.000Z | test/atecc508a/data_zone_test.exs | bcdevices/atecc508a | 934652947ac1de2022f1da556adffa3e8cba31e3 | [
"Apache-2.0"
] | 10 | 2019-01-30T19:33:48.000Z | 2022-03-03T21:07:37.000Z | test/atecc508a/data_zone_test.exs | bcdevices/atecc508a | 934652947ac1de2022f1da556adffa3e8cba31e3 | [
"Apache-2.0"
] | 9 | 2019-08-22T06:26:45.000Z | 2022-03-01T18:05:01.000Z | defmodule ATECC508A.DataZoneTest do
use ExUnit.Case
alias ATECC508A.DataZone
test "pad to slot size" do
assert DataZone.pad_to_slot_size(0, <<>>) == <<0::size(36)-unit(8)>>
assert DataZone.pad_to_slot_size(1, <<1>>) == <<1, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(2, <<2>>) == <<2, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(3, <<3>>) == <<3, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(4, <<4>>) == <<4, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(5, <<5>>) == <<5, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(6, <<6>>) == <<6, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(7, <<7>>) == <<7, 0::size(35)-unit(8)>>
assert DataZone.pad_to_slot_size(8, <<8>>) == <<8, 0::size(415)-unit(8)>>
assert DataZone.pad_to_slot_size(9, <<9>>) == <<9, 0::size(71)-unit(8)>>
assert DataZone.pad_to_slot_size(10, <<10>>) == <<10, 0::size(71)-unit(8)>>
assert DataZone.pad_to_slot_size(11, <<11>>) == <<11, 0::size(71)-unit(8)>>
assert DataZone.pad_to_slot_size(12, <<12>>) == <<12, 0::size(71)-unit(8)>>
assert DataZone.pad_to_slot_size(13, <<13>>) == <<13, 0::size(71)-unit(8)>>
assert DataZone.pad_to_slot_size(14, <<14>>) == <<14, 0::size(71)-unit(8)>>
assert DataZone.pad_to_slot_size(15, <<15>>) == <<15, 0::size(71)-unit(8)>>
end
test "no padding when the exact slot size" do
data = :crypto.strong_rand_bytes(36)
assert DataZone.pad_to_slot_size(1, data) == data
end
test "pad to 32-bytes" do
assert DataZone.pad_to_32(<<>>) == <<>>
assert DataZone.pad_to_32(<<1>>) == <<1, 0::size(31)-unit(8)>>
assert DataZone.pad_to_32(<<0::size(32)-unit(8)>>) == <<0::size(32)-unit(8)>>
end
end
| 48.527778 | 81 | 0.608472 |
03388484622dfdb913a3d02247e8da5ebd7c019a | 332 | exs | Elixir | spec/spec_helper.exs | CraigCottingham/advent-of-code-2019 | 76a1545e4cca14fe1e9e0de475de253170da1645 | [
"Apache-2.0"
] | null | null | null | spec/spec_helper.exs | CraigCottingham/advent-of-code-2019 | 76a1545e4cca14fe1e9e0de475de253170da1645 | [
"Apache-2.0"
] | null | null | null | spec/spec_helper.exs | CraigCottingham/advent-of-code-2019 | 76a1545e4cca14fe1e9e0de475de253170da1645 | [
"Apache-2.0"
] | null | null | null | ESpec.configure(fn config ->
config.before(fn tags ->
{:shared, solutions: AoC.SpecHelper.load_solutions(), tags: tags}
end)
config.finally(fn _shared ->
:ok
end)
end)
defmodule AoC.SpecHelper do
@moduledoc false
def load_solutions do
"solutions.json"
|> File.read!()
|> Jason.decode!()
end
end
| 16.6 | 69 | 0.656627 |
0338ba88d915c483195e117fda5cf3d1f9da28c4 | 1,719 | ex | Elixir | clients/discovery/lib/google_api/discovery/v1/model/rest_resource.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/discovery/lib/google_api/discovery/v1/model/rest_resource.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/discovery/lib/google_api/discovery/v1/model/rest_resource.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2018 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.Discovery.V1.Model.RestResource do
@moduledoc """
## Attributes
- methods (%{optional(String.t) => RestMethod}): Methods on this resource. Defaults to: `null`.
- resources (%{optional(String.t) => RestResource}): Sub-resources on this resource. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:methods => map(),
:resources => map()
}
field(:methods, as: GoogleApi.Discovery.V1.Model.RestMethod, type: :map)
field(:resources, as: GoogleApi.Discovery.V1.Model.RestResource, type: :map)
end
defimpl Poison.Decoder, for: GoogleApi.Discovery.V1.Model.RestResource do
def decode(value, options) do
GoogleApi.Discovery.V1.Model.RestResource.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Discovery.V1.Model.RestResource do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.705882 | 115 | 0.730657 |
0338f4ded4269ef4b9e09c07af8ca3eece23ffb6 | 1,318 | ex | Elixir | lib/rtl/emails.ex | topherhunt/reassembling-the-line | c6823b3394ee98d9b0149fa3d09448928ac5c0db | [
"MIT"
] | 1 | 2019-04-27T15:39:20.000Z | 2019-04-27T15:39:20.000Z | lib/rtl/emails.ex | topherhunt/reassembling-the-line | c6823b3394ee98d9b0149fa3d09448928ac5c0db | [
"MIT"
] | 11 | 2020-07-16T11:40:53.000Z | 2021-08-16T07:03:33.000Z | lib/rtl/emails.ex | topherhunt/reassembling-the-line | c6823b3394ee98d9b0149fa3d09448928ac5c0db | [
"MIT"
] | null | null | null | defmodule RTL.Emails do
require Logger
use Bamboo.Phoenix, view: RTLWeb.EmailsView
import Bamboo.Email
import RTLWeb.Gettext
alias RTL.Accounts
alias RTL.Accounts.User
alias RTLWeb.Router.Helpers, as: Routes
@endpoint RTLWeb.Endpoint
def confirm_address(%User{} = user, email) do
token = Accounts.create_token!({:confirm_email, user.id, email})
url = Routes.auth_url(@endpoint, :confirm_email, token: token)
if Mix.env == :dev, do: Logger.info "Email confirmation link sent to #{email}: #{url}"
standard_email()
|> to(email)
|> subject("RTL: #{gettext "Please confirm your address"}")
|> render("confirm_address.html", url: url)
end
def reset_password(%User{} = user) do
token = Accounts.create_token!({:reset_password, user.id})
url = Routes.auth_url(@endpoint, :reset_password, token: token)
if Mix.env == :dev, do: Logger.info "PW reset link sent to #{user.email}: #{url}"
standard_email()
|> to(user.email)
|> subject("RTL: #{gettext "Use this link to reset your password"}")
|> render("reset_password.html", url: url)
end
#
# Internal
#
defp standard_email do
new_email()
|> from({"Reassembling the Line", "[email protected]"})
|> put_html_layout({RTLWeb.LayoutView, "email.html"})
end
end
| 29.954545 | 90 | 0.676783 |
0339194c742a377ebf9f71ce3d3b2fe3577c61f1 | 1,098 | ex | Elixir | lib/types/entry.ex | imeraj/elixir_git | 27792b6aa9f8b14c946543cd81b253977d8686f8 | [
"MIT"
] | 22 | 2021-03-07T17:00:42.000Z | 2022-03-21T07:16:11.000Z | lib/types/entry.ex | imeraj/elixir_git | 27792b6aa9f8b14c946543cd81b253977d8686f8 | [
"MIT"
] | null | null | null | lib/types/entry.ex | imeraj/elixir_git | 27792b6aa9f8b14c946543cd81b253977d8686f8 | [
"MIT"
] | 2 | 2021-03-10T21:16:51.000Z | 2021-05-06T10:49:13.000Z | defmodule Egit.Types.Entry do
@moduledoc """
An Elixir implementation of Git version control system
"""
use Bitwise
@regular_mode "100644"
@executable_mode "100755"
@directory_mode "40000"
defstruct name: nil, oid: nil, content: nil, stat: nil
def parent_dirs(entry) do
descend(entry.name)
|> Enum.drop(-1)
end
def dir_mode do
@directory_mode
end
def mode(entry) do
if executable?(entry.stat.mode), do: @executable_mode, else: @regular_mode
end
defp executable?(mode) do
<<_::1, _::1, o_exec::1, _::1, _::1, g_exec::1, _::1, _::1, a_exec::1>> = <<mode::9>>
case bor(bor(o_exec, g_exec), a_exec) do
1 -> true
0 -> false
end
end
def basename(name) do
Path.basename(name)
end
defp descend(path) do
Path.split(path)
|> Enum.reduce([], fn dir, results ->
case List.last(results) do
nil ->
[dir]
root ->
if root == "/" do
results ++ [root <> dir]
else
results ++ [root <> "/" <> dir]
end
end
end)
end
end
| 19.263158 | 89 | 0.565574 |
033940840de88311140716cc24442530fe1acc3e | 1,784 | exs | Elixir | test/ex_aws_code_deploy_test.exs | fmcgeough/ex_aws_code_deploy | 0d8c8ed828fc3784d8eb5b898e41e5be5098f16c | [
"MIT"
] | 1 | 2020-01-12T03:30:38.000Z | 2020-01-12T03:30:38.000Z | test/ex_aws_code_deploy_test.exs | fmcgeough/ex_aws_code_deploy | 0d8c8ed828fc3784d8eb5b898e41e5be5098f16c | [
"MIT"
] | null | null | null | test/ex_aws_code_deploy_test.exs | fmcgeough/ex_aws_code_deploy | 0d8c8ed828fc3784d8eb5b898e41e5be5098f16c | [
"MIT"
] | null | null | null | defmodule ExAwsCodeDeployTest do
use ExUnit.Case
doctest ExAws.CodeDeploy
alias ExAws.CodeDeploy
test "get application revision from S3" do
revision = %{
"revision" => %{
"revisionType" => "S3",
"s3Location" => %{
"bundleType" => "zip",
"eTag" => "fff9102ckv48b652bf903700453f7408",
"bucket" => "project-1234",
"key" => "North-App.zip"
}
}
}
op = CodeDeploy.get_application_revision("Test", revision)
assert op.data == %{
"applicationName" => "Test",
"revision" => %{
"revisionType" => "S3",
"s3Location" => %{
"bucket" => "project-1234",
"bundleType" => "zip",
"eTag" => "fff9102ckv48b652bf903700453f7408",
"key" => "North-App.zip"
}
}
}
end
test "create deployment with caller defined deployment details" do
deployment_details = %{
"autoRollbackConfiguration" => %{
"enabled" => true,
"events" => [
"DEPLOYMENT_FAILURE"
]
},
"deploymentGroupName" => "dep-group-ghi-789",
"description" => "Deployment for Project 1234",
"deploymentConfigName" => "CodeDeployDefault.OneAtATime",
"ignoreApplicationStopFailures" => true,
"revision" => %{
"revisionType" => "S3",
"s3Location" => %{
"bundleType" => "zip",
"bucket" => "project-1234",
"key" => "East-App.zip"
},
"updateOutdatedInstancesOnly" => true
}
}
op = CodeDeploy.create_deployment("Test", deployment_details)
assert op.data == Map.merge(deployment_details, %{"applicationName" => "Test"})
end
end
| 28.774194 | 83 | 0.524103 |
0339606ed6f251da3ac69e244ee335806346a82c | 2,245 | ex | Elixir | clients/dlp/lib/google_api/dlp/v2beta1/model/google_privacy_dlp_v2beta1_datastore_options.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dlp/lib/google_api/dlp/v2beta1/model/google_privacy_dlp_v2beta1_datastore_options.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dlp/lib/google_api/dlp/v2beta1/model/google_privacy_dlp_v2beta1_datastore_options.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1DatastoreOptions do
@moduledoc """
Options defining a data set within Google Cloud Datastore.
## Attributes
- kind (GooglePrivacyDlpV2beta1KindExpression): The kind to process. Defaults to: `null`.
- partitionId (GooglePrivacyDlpV2beta1PartitionId): A partition ID identifies a grouping of entities. The grouping is always by project and namespace, however the namespace ID may be empty. Defaults to: `null`.
- projection (List[GooglePrivacyDlpV2beta1Projection]): Properties to scan. If none are specified, all properties will be scanned by default. Defaults to: `null`.
"""
defstruct [
:"kind",
:"partitionId",
:"projection"
]
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1DatastoreOptions do
import GoogleApi.DLP.V2beta1.Deserializer
def decode(value, options) do
value
|> deserialize(:"kind", :struct, GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1KindExpression, options)
|> deserialize(:"partitionId", :struct, GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1PartitionId, options)
|> deserialize(:"projection", :list, GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1Projection, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2beta1.Model.GooglePrivacyDlpV2beta1DatastoreOptions do
def encode(value, options) do
GoogleApi.DLP.V2beta1.Deserializer.serialize_non_nil(value, options)
end
end
| 41.574074 | 212 | 0.774165 |
0339720b338b83ed3d5944b75e3c8c2b244ca540 | 682 | exs | Elixir | priv/repo/migrations/20170914141603_create_account_users.exs | vahidabdi/escala_api | 84a4a3ef832180f12c6197683933d8cd0ab35ef4 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170914141603_create_account_users.exs | vahidabdi/escala_api | 84a4a3ef832180f12c6197683933d8cd0ab35ef4 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170914141603_create_account_users.exs | vahidabdi/escala_api | 84a4a3ef832180f12c6197683933d8cd0ab35ef4 | [
"MIT"
] | null | null | null | defmodule Escala.Repo.Migrations.CreateAccountUsers do
use Ecto.Migration
def up do
execute "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\""
create table(:account_users, primary_key: false) do
add :id, :uuid, primary_key: true, default: fragment("uuid_generate_v4()")
add :email, :text, null: false
add :username, :text
add :first_name, :text
add :last_name, :text
add :picture, :text
add :providers, {:array, :text}
timestamps(type: :timestamptz)
end
create unique_index(:account_users, [:email])
create unique_index(:account_users, [:username])
end
def down do
drop table(:account_users)
end
end
| 26.230769 | 80 | 0.670088 |
0339773310e8cff3c2d2f3f7dae1d7a5644d4b04 | 357 | ex | Elixir | lib/ex_gpgme/notation/signature_notation.ex | jshmrtn/ex-gpgme | 0a465254d24d192c2311acf640258fe016b9195a | [
"MIT"
] | 3 | 2017-11-30T16:47:13.000Z | 2019-02-20T20:43:05.000Z | lib/ex_gpgme/notation/signature_notation.ex | jshmrtn/ex-gpgme | 0a465254d24d192c2311acf640258fe016b9195a | [
"MIT"
] | 1 | 2020-07-08T18:33:26.000Z | 2020-07-08T18:47:09.000Z | lib/ex_gpgme/notation/signature_notation.ex | jshmrtn/ex-gpgme | 0a465254d24d192c2311acf640258fe016b9195a | [
"MIT"
] | 2 | 2018-12-31T02:03:38.000Z | 2020-07-08T17:45:14.000Z | defmodule ExGpgme.Notation.SignatureNotation do
@moduledoc """
Signature Notation
"""
@type t :: %__MODULE__{
is_human_readable: boolean,
is_critical: boolean,
# flags: any
name: String.t,
value: String.t,
}
@enforce_keys [
:is_human_readable,
:is_critical,
:name,
:value,
]
defstruct @enforce_keys
end
| 16.227273 | 47 | 0.644258 |
03398ad3876518de177805d45c9ddf1d961dae5b | 3,232 | exs | Elixir | backend/config/runtime.exs | ugbots/ggj2022 | 1c7b9f6694268951f93a11fde91fa9573c179c26 | [
"MIT"
] | null | null | null | backend/config/runtime.exs | ugbots/ggj2022 | 1c7b9f6694268951f93a11fde91fa9573c179c26 | [
"MIT"
] | null | null | null | backend/config/runtime.exs | ugbots/ggj2022 | 1c7b9f6694268951f93a11fde91fa9573c179c26 | [
"MIT"
] | null | null | null | import Config
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.
# Start the phoenix server if environment is set and running in a release
if System.get_env("PHX_SERVER") && System.get_env("RELEASE_NAME") do
config :backend, BackendWeb.Endpoint, server: true
end
if config_env() == :prod do
database_url =
System.get_env("DATABASE_URL") ||
raise """
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
"""
maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: []
config :backend, Backend.Repo,
# ssl: true,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
socket_options: maybe_ipv6
# The secret key base is used to sign/encrypt cookies and other secrets.
# A default value is used in config/dev.exs and config/test.exs but you
# want to use a different value for prod and you most likely don't want
# to check this value into version control, so we use an environment
# variable instead.
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
host = System.get_env("PHX_HOST") || "example.com"
port = String.to_integer(System.get_env("PORT") || "4000")
config :backend, BackendWeb.Endpoint,
url: [host: host, port: 443],
http: [
# Enable IPv6 and bind on all interfaces.
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
# See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0},
port: port
],
secret_key_base: secret_key_base
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start each relevant endpoint:
#
# config :backend, BackendWeb.Endpoint, server: true
#
# Then you can assemble a release by calling `mix release`.
# See `mix help release` for more information.
# ## Configuring the mailer
#
# In production you need to configure the mailer to use a different adapter.
# Also, you may need to configure the Swoosh API client of your choice if you
# are not using SMTP. Here is an example of the configuration:
#
# config :backend, Backend.Mailer,
# adapter: Swoosh.Adapters.Mailgun,
# api_key: System.get_env("MAILGUN_API_KEY"),
# domain: System.get_env("MAILGUN_DOMAIN")
#
# For this example you need include a HTTP client required by Swoosh API client.
# Swoosh supports Hackney and Finch out of the box:
#
# config :swoosh, :api_client, Swoosh.ApiClient.Hackney
#
# See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
end
| 37.581395 | 82 | 0.698639 |
03398f7228c8c5e716dd416d3a1334998934b186 | 910 | exs | Elixir | mix.exs | sean-lin/ApkInjector | 2c56954d6e756411818b0a986cc2933502b83a12 | [
"Apache-2.0"
] | 23 | 2016-09-07T03:48:58.000Z | 2021-11-17T10:24:14.000Z | mix.exs | sean-lin/ApkInjector | 2c56954d6e756411818b0a986cc2933502b83a12 | [
"Apache-2.0"
] | 1 | 2017-07-30T11:47:31.000Z | 2017-07-30T11:47:31.000Z | mix.exs | sean-lin/ApkInjector | 2c56954d6e756411818b0a986cc2933502b83a12 | [
"Apache-2.0"
] | 10 | 2016-12-22T07:33:59.000Z | 2020-05-27T10:46:43.000Z | defmodule Injector.Mixfile do
use Mix.Project
def project do
[app: :injector,
version: "0.1.0",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
escript: [main_module: Injector.Cmd],
deps: deps()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[
mod: {Injector, []},
applications: [
:logger,
:eex,
:poison,
:yaml_elixir,
]
]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[
{:poison, "~> 2.0"},
{:yaml_elixir, "~> 1.0.0"},
{:yamerl, "~> 0.4.0"},
]
end
end
| 19.782609 | 77 | 0.548352 |
03399bc13e1e37601a3419f1d8991e73a59da6ff | 273 | exs | Elixir | Elixir/elixirexamples/test/continuationpassing_test.exs | kujua/erlang-elixir-imperative-bookcompanion | 7bc9f033bacd0f8744ec6bcee3932794d594fe69 | [
"Apache-2.0"
] | 8 | 2016-08-14T12:35:16.000Z | 2021-01-26T04:05:31.000Z | Elixir/elixirexamples/test/continuationpassing_test.exs | kujua/erlang-elixir-imperative-bookcompanion | 7bc9f033bacd0f8744ec6bcee3932794d594fe69 | [
"Apache-2.0"
] | null | null | null | Elixir/elixirexamples/test/continuationpassing_test.exs | kujua/erlang-elixir-imperative-bookcompanion | 7bc9f033bacd0f8744ec6bcee3932794d594fe69 | [
"Apache-2.0"
] | 5 | 2016-08-18T22:12:19.000Z | 2020-02-17T18:52:41.000Z | defmodule ContinuationPassingTest do
use ExUnit.Case
test "initiate_ok" do
ret = ContinuationPassing.initiate {:ok,1}
assert ret == {:stopped}
end
test "initiate_error" do
ret = ContinuationPassing.initiate {:ok,2}
assert ret == :error
end
end
| 18.2 | 46 | 0.692308 |
0339bb0c3b7fe39bb132eec5ec263f1c6ca2fcdb | 560 | ex | Elixir | lib/escript_testbed/scenarios/data_set_a.ex | elvanja/escript_testbed | eb92772b6223309d727716d8a6dc1c9d316bbbb4 | [
"MIT"
] | null | null | null | lib/escript_testbed/scenarios/data_set_a.ex | elvanja/escript_testbed | eb92772b6223309d727716d8a6dc1c9d316bbbb4 | [
"MIT"
] | 2 | 2020-07-27T00:13:11.000Z | 2020-07-27T05:22:17.000Z | lib/escript_testbed/scenarios/data_set_a.ex | elvanja/escript_testbed | eb92772b6223309d727716d8a6dc1c9d316bbbb4 | [
"MIT"
] | 2 | 2020-07-26T12:32:39.000Z | 2020-07-26T23:54:13.000Z | defmodule EscriptTestbed.Scenarios.DataSetA do
@moduledoc false
alias EscriptTestbed.Repos.Destination, as: DestinationRepo
alias EscriptTestbed.Repos.Source, as: SourceRepo
alias EscriptTestbed.Scenario
@behaviour Scenario
@impl Scenario
def run do
IO.puts("""
Sync completed successfully:
- scenario: #{__MODULE__}
- source:
- #{SourceRepo.__adapter__()}
- #{inspect(SourceRepo.config())}
- destination:
- #{DestinationRepo.__adapter__()}
- #{inspect(DestinationRepo.config())}
""")
end
end
| 23.333333 | 61 | 0.685714 |
033a2b68636a0925613e0552f6b55ce92f1ba08f | 1,501 | exs | Elixir | test/data/mutate_rows_test.exs | bzzt/bigtable | 215b104a60596dde6cd459efb73baf8bccdb6b50 | [
"MIT"
] | 17 | 2019-01-22T12:59:38.000Z | 2021-12-13T10:41:52.000Z | test/data/mutate_rows_test.exs | bzzt/bigtable | 215b104a60596dde6cd459efb73baf8bccdb6b50 | [
"MIT"
] | 17 | 2019-01-27T18:11:33.000Z | 2020-02-24T10:16:08.000Z | test/data/mutate_rows_test.exs | bzzt/bigtable | 215b104a60596dde6cd459efb73baf8bccdb6b50 | [
"MIT"
] | 3 | 2019-02-04T17:08:09.000Z | 2021-04-07T07:13:53.000Z | defmodule MutateRowsTest do
@moduledoc false
alias Bigtable.{MutateRows, Mutations}
use ExUnit.Case
setup do
[
entries: [Mutations.build("Test#123"), Mutations.build("Test#124")]
]
end
describe "MutateRow.build() " do
test "should build a MutateRowsRequest with configured table", context do
expected = %Google.Bigtable.V2.MutateRowsRequest{
app_profile_id: "",
entries: [
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#123"
},
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#124"
}
],
table_name: Bigtable.Utils.configured_table_name()
}
result = context.entries |> MutateRows.build()
assert result == expected
end
test "should build a MutateRowsRequest with custom table", context do
table_name = "custom-table"
expected = %Google.Bigtable.V2.MutateRowsRequest{
app_profile_id: "",
entries: [
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#123"
},
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#124"
}
],
table_name: table_name
}
result =
context.entries
|> MutateRows.build(table_name)
assert result == expected
end
end
end
| 24.606557 | 77 | 0.579614 |
033a2c6201ba091707499ccf9472a16d931587b0 | 760 | ex | Elixir | lib/tinybeam/router.ex | niklaslong/tinybeam | fa69e985cfe8c5145cd9238dd01ff8804613e107 | [
"MIT"
] | null | null | null | lib/tinybeam/router.ex | niklaslong/tinybeam | fa69e985cfe8c5145cd9238dd01ff8804613e107 | [
"MIT"
] | 9 | 2020-06-16T10:41:57.000Z | 2020-06-16T10:44:04.000Z | lib/tinybeam/router.ex | niklaslong/tinybeam | fa69e985cfe8c5145cd9238dd01ff8804613e107 | [
"MIT"
] | null | null | null | defmodule Tinybeam.Router do
alias Tinybeam.Server.Response
defmacro __using__(_options) do
quote do
import Tinybeam.Router
alias Tinybeam.Server.Response
def match(type, route, request) do
do_match(type, route, request)
end
end
end
defmacro get(route, body) do
quote do
defp do_match(:get, unquote(route), var!(request)) do
unquote(body[:do])
end
end
end
defmacro post(route, body) do
quote do
defp do_match(:post, unquote(route), var!(request)) do
unquote(body[:do])
end
end
end
def match(:get, "/", request),
do:
Response.new(request.req_ref, 200, "Hi, welcome to tinybeam!", [
{"Content-Type", "text/plain"}
])
end
| 20.540541 | 70 | 0.610526 |
033a629ccdb5ed900874171ee43668f497278b4e | 1,206 | exs | Elixir | mix.exs | PRX/redix-clustered | 46d5826fdcd877ba9794e083260b5bcc784b8a9e | [
"MIT"
] | null | null | null | mix.exs | PRX/redix-clustered | 46d5826fdcd877ba9794e083260b5bcc784b8a9e | [
"MIT"
] | null | null | null | mix.exs | PRX/redix-clustered | 46d5826fdcd877ba9794e083260b5bcc784b8a9e | [
"MIT"
] | null | null | null | defmodule RedixClustered.MixProject do
use Mix.Project
def project do
[
app: :redix_clustered,
version: "1.1.0",
elixir: "~> 1.12",
name: "RedixClustered",
source_url: "https://github.com/PRX/redix-clustered",
homepage_url: "https://github.com/PRX/redix-clustered",
description: description(),
package: package(),
docs: docs(),
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[
{:redix, "~> 1.1"},
{:castore, ">= 0.0.0"},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:mix_test_watch, "~> 1.0", only: :dev, runtime: false},
{:dotenv, "~> 3.0.0", only: [:dev, :test]}
]
end
defp description do
"Hex package to run redix with cluster support and more"
end
defp package do
[
contributors: ["Ryan Cavis"],
maintainers: ["Ryan Cavis"],
licenses: ["MIT"],
links: %{github: "https://github.com/PRX/redix-clustered"},
files: ~w(lib LICENSE mix.exs README.md)
]
end
defp docs do
[main: "readme", extras: ["README.md"]]
end
end
| 22.333333 | 65 | 0.563847 |
033a6c13e1fcd347ec796a3962510e05ad4d72a3 | 2,160 | exs | Elixir | test/zanox/products_test.exs | rafaelss/zanox | 4f9849252dc96a644d974939ce9437d5e538300a | [
"MIT"
] | 1 | 2016-10-08T15:45:34.000Z | 2016-10-08T15:45:34.000Z | test/zanox/products_test.exs | rafaelss/zanox | 4f9849252dc96a644d974939ce9437d5e538300a | [
"MIT"
] | null | null | null | test/zanox/products_test.exs | rafaelss/zanox | 4f9849252dc96a644d974939ce9437d5e538300a | [
"MIT"
] | null | null | null | defmodule Zanox.ProductsTest do
use ExUnit.Case
use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney
doctest Zanox
setup_all do
Application.put_env(:zanox, :connectid, "foobar")
ExVCR.Config.cassette_library_dir("test/fixtures/cassettes")
:ok
end
test "load products" do
use_cassette "load-products" do
Zanox.Products.start
products = Zanox.Products.search("tv led 32", %{programs: 13212, items: 1})
assert Enum.count(products) == 1
product = products |> List.first
assert product.id == "8da9d468080fb24227b141cbd5d48c57"
assert product.name == "Suporte Fixo Multivisão para TVs LCD/LED/Plasma e 3D de 32\" à 84\" Pronto para Instalar -STPF63"
assert product.modified == "2015-12-04T15:05:59Z"
assert product.program.name == "Ricardo Eletro BR"
assert product.program.id == "13212"
assert product.price == 66.4
assert product.currency == "BRL"
assert product.description == ""
assert product.manufacturer == "Multivisão"
assert product.ean == 7896643408005
assert product.images.large == "http://parceiroimg.maquinadevendas.com.br/produto/491_12778_20091030145930.jpg"
assert product.merchant_category == "Acessórios para TV"
assert product.merchant_product_id == 491
assert Enum.count(product.tracking_links) == 1
Enum.each(product.tracking_links, fn(link) ->
assert link.adspace_id == "2034022"
assert link.ppc == "http://ad.zanox.com/ppc/?30343243C59505925&ULP=[[Suporte-Fixo-Multivisao-para-TVs-LCDLEDPlasma-e-3D-de-32-a-84-Pronto-para-Instalar-STPF63/108-3260-3979-4657/?utm_source=Zanox&prc=8803&utm_medium=CPC_TV_e_Video_Zanox&utm_campaign=Acessorios_para_TV&utm_content=Suportes&cda=3EAC-1BE0-DA57-40AD]]&zpar9=[[foobar]]"
assert link.ppv == "http://ad.zanox.com/ppv/?30343243C59505925&ULP=[[Suporte-Fixo-Multivisao-para-TVs-LCDLEDPlasma-e-3D-de-32-a-84-Pronto-para-Instalar-STPF63/108-3260-3979-4657/?utm_source=Zanox&prc=8803&utm_medium=CPC_TV_e_Video_Zanox&utm_campaign=Acessorios_para_TV&utm_content=Suportes&cda=3EAC-1BE0-DA57-40AD]]&zpar9=[[foobar]]"
end)
end
end
end
| 49.090909 | 341 | 0.721759 |
033a800b0aeb424840e99154c877ff308d55a3fa | 13,418 | ex | Elixir | lib/demo_web/live/snake_live.ex | cadebward/phoenix_live_view | bd4903ed649a4efc1bdb6142810aa82e1e02573a | [
"MIT"
] | null | null | null | lib/demo_web/live/snake_live.ex | cadebward/phoenix_live_view | bd4903ed649a4efc1bdb6142810aa82e1e02573a | [
"MIT"
] | null | null | null | lib/demo_web/live/snake_live.ex | cadebward/phoenix_live_view | bd4903ed649a4efc1bdb6142810aa82e1e02573a | [
"MIT"
] | null | null | null | defmodule DemoWeb.SnakeLive do
use Phoenix.LiveView
@tick 100
@width 16
@snake_length 5
@board [
~w(X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 X X X X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X),
~w(X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X)
]
@board_rows length(@board)
@board_cols length(hd(@board))
def render(%{game_state: :over} = assigns) do
~L"""
<div class="snake-container">
<div class="game-over">
<h1>GAME OVER <small>SCORE: <%= @score %></h1>
<button phx-click="new_game">NEW GAME</button>
</div>
</div>
"""
end
def render(%{game_state: :playing} = assigns) do
~L"""
<div class="snake-controls">
<form phx-change="update_settings">
<select name="tick" onchange="this.blur()">
<option value="50" <%= if @tick == 50, do: "selected" %>>50</option>
<option value="100" <%= if @tick == 100, do: "selected" %>>100</option>
<option value="200" <%= if @tick == 200, do: "selected" %>>200</option>
<option value="500" <%= if @tick == 500, do: "selected" %>>500</option>
</select>
<input type="range" min="5" max="50" name="width" value="<%= @width %>" />
<%= @width %>px
</form>
</div>
<div class="snake-container" phx-keydown="keydown" phx-target="window">
<h3 class="score" style="font-size: <%= @width %>px;">SCORE: <%= @score %></h3>
<%= for block <- @compacted_tail do %>
<div class="block tail"
style="left: <%= block.x %>px;
top: <%= block.y %>px;
width: <%= block.width %>px;
height: <%= block.height %>px;
"></div>
<% end %>
<%= for {row, col} <- @cherries do %>
<div class="block cherry"
style="left: <%= x(col, @width) %>px;
top: <%= y(row, @width) %>px;
width: <%= @width %>px;
height: <%= @width %>px;
"></div>
<% end %>
<%= for {_, block} <- @blocks, block.type !== :empty do %>
<div class="block <%= block.type %>"
style="left: <%= block.x %>px;
top: <%= block.y %>px;
width: <%= block.width %>px;
height: <%= block.width %>px;
"></div>
<% end %>
</div>
"""
end
def mount(_session, socket) do
{:ok, socket |> new_game() |> schedule_tick()}
end
defp new_game(socket) do
defaults = %{
score: 0,
game_state: :playing,
heading: :stationary,
pending_headings: {:stationary, []},
width: @width,
compacted_tail: [],
tick: @tick,
row: 1,
col: 6,
max_length: @snake_length,
tail: [{1, 6}],
cherries: []
}
new_socket =
socket
|> assign(defaults)
|> build_board()
|> compact_tail()
if connected?(new_socket) do
place_cherries(new_socket, 10)
else
new_socket
end
end
def handle_event("update_settings", %{"width" => width, "tick" => tick}, socket) do
{width, ""} = Integer.parse(width)
{tick, ""} = Integer.parse(tick)
new_socket =
socket
|> update_size(width)
|> update_tick(tick)
{:noreply, new_socket}
end
def handle_event("new_game", _, socket) do
{:noreply, new_game(socket)}
end
def handle_event("keydown", %{"key" => key}, socket) do
{:noreply, turn(socket, key)}
end
def handle_info(:tick, socket) do
new_socket =
socket
|> game_loop()
|> compact_tail()
|> schedule_tick()
{:noreply, new_socket}
end
defp update_tick(socket, tick) when tick <= 1000 and tick >= 50 do
assign(socket, :tick, tick)
end
defp schedule_tick(socket) do
Process.send_after(self(), :tick, socket.assigns.tick)
socket
end
defp update_size(socket, width) do
socket
|> assign(width: width)
|> build_board()
|> compact_tail()
end
defp turn(socket, "ArrowLeft"), do: go(socket, :left)
defp turn(socket, "ArrowDown"), do: go(socket, :down)
defp turn(socket, "ArrowUp"), do: go(socket, :up)
defp turn(socket, "ArrowRight"), do: go(socket, :right)
defp turn(socket, _), do: socket
defp go(socket, heading) do
update(socket, :pending_headings, fn
{^heading, prev} -> {heading, prev}
{_, prev} -> {heading, prev ++ [heading]}
end)
end
defp next_heading(socket) do
{next, pending} =
case {socket.assigns.heading, socket.assigns.pending_headings} do
{current, {_, []}} -> {current, []}
{:left, {_, [:right | rest]}} -> {:left, rest}
{:right, {_, [:left | rest]}} -> {:right, rest}
{:up, {_, [:down | rest]}} -> {:up, rest}
{:down, {_, [:up | rest]}} -> {:down, rest}
{_current, {_, [new | rest]}} -> {new, rest}
end
{next, {next, pending}}
end
defp game_loop(%{assigns: %{pending_headings: {:stationary, []}}} = socket), do: socket
defp game_loop(socket) do
{heading, new_pending} = next_heading(socket)
{row_before, col_before} = coord(socket)
maybe_row = row(row_before, heading)
maybe_col = col(col_before, heading)
{row, col, collision} =
case block(socket, maybe_row, maybe_col) do
:wall -> {maybe_row, maybe_col, :wall}
:tail -> {maybe_row, maybe_col, :tail}
:empty -> {maybe_row, maybe_col, :empty}
:cherry -> {maybe_row, maybe_col, :cherry}
end
socket
|> advance_tail({row_before, row}, {col_before, col})
|> update(:row, fn _ -> row end)
|> update(:col, fn _ -> col end)
|> update(:heading, fn _ -> heading end)
|> update(:pending_headings, fn _ -> new_pending end)
|> handle_collision(collision)
end
defp advance_tail(socket, {row, row}, {col, col}), do: socket
defp advance_tail(socket, {row, _}, {col, _}) do
tail = [{row, col} | socket.assigns.tail]
if length(tail) < socket.assigns.max_length do
assign(socket, :tail, tail)
else
assign(socket, :tail, Enum.drop(tail, -1))
end
end
defp compact_tail(socket) do
tail = compact([coord(socket) | socket.assigns.tail], socket.assigns.width)
assign(socket, :compacted_tail, tail)
end
def handle_collision(socket, :wall), do: game_over(socket)
def handle_collision(socket, :tail), do: game_over(socket)
def handle_collision(socket, :cherry), do: level_up(socket)
def handle_collision(socket, :empty), do: socket
defp game_over(socket), do: assign(socket, :game_state, :over)
defp level_up(socket) do
new_cherries = Enum.filter(socket.assigns.cherries, &(&1 !== coord(socket)))
socket
|> assign(:score, socket.assigns.score + 10)
|> assign(:max_length, socket.assigns.max_length + 4)
|> assign(:cherries, new_cherries)
|> place_cherries(1)
end
defp col(val, :left) when val - 1 >= 0, do: val - 1
defp col(val, :right) when val + 1 < @board_cols, do: val + 1
defp col(val, _), do: val
defp row(val, :up) when val - 1 >= 0, do: val - 1
defp row(val, :down) when val + 1 < @board_rows, do: val + 1
defp row(val, _), do: val
def block(socket, row, col) do
cond do
{row, col} in socket.assigns.cherries -> :cherry
{row, col} in socket.assigns.tail -> :tail
true -> Map.fetch!(socket.assigns.blocks, {row, col}).type
end
end
defp x(x, width), do: x * width
defp y(y, width), do: y * width
defp coord(socket), do: {socket.assigns.row, socket.assigns.col}
defp build_board(socket) do
width = socket.assigns.width
{_, blocks} =
Enum.reduce(@board, {0, %{}}, fn row, {y_idx, acc} ->
{_, blocks} =
Enum.reduce(row, {0, acc}, fn
"X", {x_idx, acc} ->
{x_idx + 1, Map.put(acc, {y_idx, x_idx}, wall(x_idx, y_idx, width))}
"0", {x_idx, acc} ->
{x_idx + 1, Map.put(acc, {y_idx, x_idx}, empty(x_idx, y_idx, width))}
end)
{y_idx + 1, blocks}
end)
assign(socket, :blocks, blocks)
end
defp wall(x_idx, y_idx, width) do
%{type: :wall, x: x_idx * width, y: y_idx * width, width: width}
end
defp empty(x_idx, y_idx, width) do
%{type: :empty, x: x_idx * width, y: y_idx * width, width: width}
end
defp place_cherries(socket, count) do
Enum.reduce(0..(count - 1), socket, fn _, acc -> place_random_cherry(acc) end)
end
def place_random_cherry(socket) do
place_cherry(socket, Enum.random(0..(@board_rows - 1)), Enum.random(0..(@board_cols - 1)))
end
defp place_cherry(socket, row, col) do
case block(socket, row, col) do
:empty -> assign(socket, :cherries, [{row, col} | socket.assigns.cherries])
_ -> place_random_cherry(socket)
end
end
defp compact([{row, col} | tail], width) do
{_, _, compacted} =
Enum.reduce(tail, {row, col, [{:horizontal, row, [col]}]}, fn
{row, new_col}, {row, _prev_col, [{:horizontal, row, cols} | acc]} ->
{row, new_col, [{:horizontal, row, [new_col | cols]} | acc]}
{new_row, col}, {_prev_row, col, [{:vertical, rows, col} | acc]} ->
{new_row, col, [{:vertical, [new_row | rows], col} | acc]}
{row, new_col}, {row, _prev_col, [{:vertical, _rows, _col} | _] = acc} ->
{row, new_col, [{:horizontal, row, [new_col]} | acc]}
{new_row, col}, {_prev_row, col, [{:horizontal, _row, _cols} | _] = acc} ->
{new_row, col, [{:vertical, [new_row], col} | acc]}
end)
Enum.map(compacted, fn
{:horizontal, row, [_ | _] = cols} ->
%{
x: x(Enum.min(cols), width),
y: y(row, width),
width: length(cols) * width,
height: width
}
{:vertical, [_ | _] = rows, col} ->
%{
x: x(col, width),
y: y(Enum.min(rows), width),
height: length(rows) * width,
width: width
}
end)
end
end
| 36.661202 | 106 | 0.532568 |
033a9cf645f7dec5a537de04e4ab72670f2234a7 | 2,799 | exs | Elixir | test/plumbapius/request_test.exs | Amuhar/plumbapius | a9066512f520f2ad97e677b04d70cc62695f2def | [
"Apache-2.0"
] | null | null | null | test/plumbapius/request_test.exs | Amuhar/plumbapius | a9066512f520f2ad97e677b04d70cc62695f2def | [
"Apache-2.0"
] | null | null | null | test/plumbapius/request_test.exs | Amuhar/plumbapius | a9066512f520f2ad97e677b04d70cc62695f2def | [
"Apache-2.0"
] | null | null | null | defmodule Plumbapius.RequestTest do
use ExUnit.Case, async: true
doctest Plumbapius.Request
alias Plumbapius.Request
alias Plumbapius.Request.NotFoundSchemaForReqestBodyError
describe "#validate_body" do
test "when the body according to the schema with 1 body option" do
request_body = %{"msisdn" => 123}
assert Request.validate_body(request_schema(), request_body) == :ok
end
test "when the body does not match the schema with 1 body option" do
request_body = %{"msisdn" => "123"}
assert Request.validate_body(request_schema(), request_body) == {:error, %NotFoundSchemaForReqestBodyError{}}
end
test "when the body according one of 2 body options of the schema" do
schema = request_schema_with_two_requests()
assert Request.validate_body(schema, %{"msisdn" => 123}) == :ok
assert Request.validate_body(schema, %{"phoneNumber" => 123}) == :ok
end
test "when the body does not match any of 2 body options of the schema" do
schema = request_schema_with_two_requests()
assert Request.validate_body(schema, %{"msisdn" => "123"}) == {:error, %NotFoundSchemaForReqestBodyError{}}
assert Request.validate_body(schema, %{"phoneNumber" => "123"}) == {:error, %NotFoundSchemaForReqestBodyError{}}
end
end
describe "#match?" do
test "when schema matches with the request" do
assert Request.match?(request_schema(), "GET", "/users/1")
end
test "when request has a different method" do
refute Request.match?(request_schema(), "GET", "/users")
end
test "when request has a different path" do
refute Request.match?(request_schema(), "POST", "/users/1")
end
end
defp request_schema do
Request.Schema.new(%{
"method" => "GET",
"path" => "/users/{id}",
"content-type" => "application/json",
"request" => %{
"$schema" => "http://json-schema.org/draft-04/schema#",
"type" => "object",
"properties" => %{"msisdn" => %{"type" => "number"}},
"required" => ["msisdn"]
},
"responses" => []
})
end
defp request_schema_with_two_requests do
Request.Schema.new(%{
"method" => "GET",
"path" => "/users/{id}",
"content-type" => "application/json",
"requests" => [
%{
"$schema" => "http://json-schema.org/draft-04/schema#",
"type" => "object",
"properties" => %{"msisdn" => %{"type" => "number"}},
"required" => ["msisdn"]
},
%{
"$schema" => "http://json-schema.org/draft-04/schema#",
"type" => "object",
"properties" => %{"phoneNumber" => %{"type" => "number"}},
"required" => ["phoneNumber"]
}
],
"responses" => []
})
end
end
| 32.172414 | 118 | 0.596642 |
033ac9d383006b107df3957c0b082e4bd33c8729 | 1,894 | ex | Elixir | lib/runner.ex | flowerett/elixir-koans | 174f4610e846f59cc34b41a36b813f5d684fd510 | [
"MIT"
] | null | null | null | lib/runner.ex | flowerett/elixir-koans | 174f4610e846f59cc34b41a36b813f5d684fd510 | [
"MIT"
] | null | null | null | lib/runner.ex | flowerett/elixir-koans | 174f4610e846f59cc34b41a36b813f5d684fd510 | [
"MIT"
] | null | null | null | defmodule Runner do
use GenServer
def koan?(koan) do
Keyword.has_key?(koan.__info__(:functions), :all_koans)
end
def modules do
{:ok, modules} = :application.get_key(:elixir_koans, :modules)
modules
|> Stream.map(&(&1.module_info |> get_in([:compile, :source])))
|> Stream.map(&to_string/1) # Paths are charlists
|> Stream.zip(modules)
|> Stream.filter(fn {_path, mod} -> koan?(mod) end)
|> Stream.map(fn {path, mod} -> {path_to_number(path), mod} end)
|> Enum.sort_by(fn {number, _mod} -> number end)
|> Enum.map(fn {_number, mod} -> mod end)
end
@koan_path_pattern ~r/lib\/koans\/(\d+)_\w+.ex$/
def path_to_number(path) do
[_path, number] = Regex.run(@koan_path_pattern, path)
String.to_integer(number)
end
def modules_to_run(start_module), do: Enum.drop_while(modules(), &(&1 != start_module))
def start_link do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
def handle_cast({:run, modules}, _) do
flush()
send(self(), :run_modules)
{:noreply, modules}
end
def handle_info(:run_modules, []) do
{:noreply, []}
end
def handle_info(:run_modules, [module | rest]) do
Display.clear_screen()
case run_module(module) do
:passed ->
send(self(), :run_modules)
{:noreply, rest}
_ ->
{:noreply, []}
end
end
def run(modules) do
GenServer.cast(__MODULE__, {:run, modules})
end
defp run_module(module) do
module
|> Execute.run_module(&track/3)
|> display
end
defp track(:passed, module, koan), do: Tracker.completed(module, koan)
defp track(_, _, _), do: nil
defp display({:failed, error, module, name}) do
Display.show_failure(error, module, name)
:failed
end
defp display(_), do: :passed
defp flush do
receive do
_ -> flush()
after
0 -> :ok
end
end
end
| 22.547619 | 89 | 0.62302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.