hexsha stringlengths 40 40 | size int64 2 991k | ext stringclasses 2 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 208 | max_stars_repo_name stringlengths 6 106 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses list | max_stars_count int64 1 33.5k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 208 | max_issues_repo_name stringlengths 6 106 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses list | max_issues_count int64 1 16.3k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 208 | max_forks_repo_name stringlengths 6 106 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses list | max_forks_count int64 1 6.91k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 991k | avg_line_length float64 1 36k | max_line_length int64 1 977k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08bfca1d355b74eb840689afcdbef23a2bbda72d | 629 | ex | Elixir | lib/util/helpers.ex | aeturnum/twitch_discord_connector | b965ba1164540c92a925d2bd08e3fa299dfd457a | [
"MIT"
] | null | null | null | lib/util/helpers.ex | aeturnum/twitch_discord_connector | b965ba1164540c92a925d2bd08e3fa299dfd457a | [
"MIT"
] | null | null | null | lib/util/helpers.ex | aeturnum/twitch_discord_connector | b965ba1164540c92a925d2bd08e3fa299dfd457a | [
"MIT"
] | null | null | null | defmodule TwitchDiscordConnector.Util.H do
@moduledoc """
Random Helpers
"""
# https://stackoverflow.com/questions/32001606/how-to-generate-a-random-url-safe-string-with-elixir
def random_string(length) do
:crypto.strong_rand_bytes(length) |> Base.url_encode64() |> binary_part(0, length)
end
def now(offset \\ 0), do: DateTime.now!("Etc/UTC") |> DateTime.add(offset, :second)
def grab_keys(tgt, src, keys) do
Enum.reduce(keys, tgt, fn key, acc -> Map.put(acc, key, Map.get(src, key, nil)) end)
end
def str(o) when is_binary(o), do: o
def str(o) when is_integer(o), do: Integer.to_string(o)
end
| 31.45 | 101 | 0.693164 |
08bfd2ea4f345f6409c9a595b85ee131b8126de7 | 2,569 | ex | Elixir | lib/amazon_product_advertising_client.ex | squaretwo/elixir-amazon-product-advertising-client | e62fc4928525c72971a5427d57896bfab530d718 | [
"MIT"
] | null | null | null | lib/amazon_product_advertising_client.ex | squaretwo/elixir-amazon-product-advertising-client | e62fc4928525c72971a5427d57896bfab530d718 | [
"MIT"
] | null | null | null | lib/amazon_product_advertising_client.ex | squaretwo/elixir-amazon-product-advertising-client | e62fc4928525c72971a5427d57896bfab530d718 | [
"MIT"
] | null | null | null | defmodule AmazonProductAdvertisingClient do
@moduledoc """
An Amazon Product Advertising API client for Elixir
"""
use HTTPoison.Base
use Timex
require Logger
alias AmazonProductAdvertisingClient.Config
@scheme "http"
@host Application.get_env(:amazon_product_advertising_client, :marketplace_host, "webservices.amazon.com")
@path "/onca/xml"
@doc """
Make a call to the API with the specified request parameters.
"""
def call_api(request_params, config \\ %Config{}) do
# and this is why I don't care for HTTPoison
Process.put(:config, config)
query = [request_params, config]
|> combine_params
|> percent_encode_query
uri = %URI{scheme: @scheme, host: @host, path: @path, query: query}
Logger.info("Querying amazon api with associate tag : #{config |> Map.get(:"AssociateTag")}")
get(uri)
end
defp combine_params(params_list) do
List.foldl(params_list, Map.new, fn(params, all_params) ->
Map.merge(Map.from_struct(params), all_params)
end)
end
# `URI.encode_query/1` explicitly does not percent-encode spaces, but Amazon requires `%20`
# instead of `+` in the query, so we essentially have to rewrite `URI.encode_query/1` and
# `URI.pair/1`.
defp percent_encode_query(query_map) do
Enum.map_join(query_map, "&", &pair/1)
end
# See comment on `percent_encode_query/1`.
defp pair({k, v}) do
URI.encode(Kernel.to_string(k), &URI.char_unreserved?/1) <>
"=" <> URI.encode(Kernel.to_string(v), &URI.char_unreserved?/1)
end
def process_url(url) do
url
|> URI.parse
|> timestamp_url
|> sign_url
|> String.Chars.to_string
end
defp timestamp_url(url_parts) do
update_url(url_parts, "Timestamp", Timex.format!(Timex.local, "{ISO:Extended:Z}"))
end
defp sign_url(url_parts) do
secret_key = cond do
Process.get(:config, nil) -> Process.get(:config) |> Map.get(:"AWSSecret")
true -> Application.get_env(:amazon_product_advertising_client, :aws_secret_access_key)
end
hmac = :crypto.hmac(
:sha256,
secret_key,
Enum.join(["GET", url_parts.host, url_parts.path, url_parts.query], "\n")
)
signature = Base.encode64(hmac)
update_url(url_parts, "Signature", signature)
end
defp update_url(url_parts, key, value) do
updated_query = url_parts.query
|> URI.decode_query
|> Map.put_new(key, value)
|> percent_encode_query
Map.put(url_parts, :query, updated_query)
end
end
| 29.872093 | 111 | 0.664461 |
08bfe3452a84e1cfaa115dbabf2a00bfca62f1e1 | 1,626 | ex | Elixir | clients/health_care/lib/google_api/health_care/v1beta1/model/text_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/health_care/lib/google_api/health_care/v1beta1/model/text_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/health_care/lib/google_api/health_care/v1beta1/model/text_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.HealthCare.V1beta1.Model.TextConfig do
@moduledoc """
## Attributes
* `transformations` (*type:* `list(GoogleApi.HealthCare.V1beta1.Model.InfoTypeTransformation.t)`, *default:* `nil`) - The transformations to apply to the detected data.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:transformations =>
list(GoogleApi.HealthCare.V1beta1.Model.InfoTypeTransformation.t()) | nil
}
field(:transformations,
as: GoogleApi.HealthCare.V1beta1.Model.InfoTypeTransformation,
type: :list
)
end
defimpl Poison.Decoder, for: GoogleApi.HealthCare.V1beta1.Model.TextConfig do
def decode(value, options) do
GoogleApi.HealthCare.V1beta1.Model.TextConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.HealthCare.V1beta1.Model.TextConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.882353 | 172 | 0.744157 |
08bfea0c12253918a1d71c716b227c8a02bf5cf7 | 2,973 | exs | Elixir | mix.exs | rocketvalidator/uncharted_phoenix | 6c22c5cbbe0a430262ec87256a164191ef25f263 | [
"MIT"
] | 2 | 2021-07-16T12:17:42.000Z | 2021-08-15T22:17:28.000Z | mix.exs | rocketvalidator/uncharted_phoenix | 6c22c5cbbe0a430262ec87256a164191ef25f263 | [
"MIT"
] | null | null | null | mix.exs | rocketvalidator/uncharted_phoenix | 6c22c5cbbe0a430262ec87256a164191ef25f263 | [
"MIT"
] | 1 | 2021-08-15T22:01:51.000Z | 2021-08-15T22:01:51.000Z | defmodule UnchartedPhoenix.MixProject do
use Mix.Project
@github_organization "unchartedelixir"
@app :uncharted_phoenix
@source_url "https://github.com/#{@github_organization}/#{@app}"
@version Path.join(__DIR__, "VERSION")
|> File.read!()
|> String.trim()
def project do
[
app: @app,
version: @version,
description: description(),
package: package(),
docs: docs(),
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix] ++ Mix.compilers(),
dialyzer: [
plt_add_apps: ~w(ex_unit mix)a,
plt_add_deps: :app_tree,
plt_file: {:no_warn, "priv/plts/dialyzer.plt"},
ignore_warnings: "../.dialyzer-ignore.exs"
],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test,
credo: :test,
dialyzer: :test,
docs: :docs,
"hex.build": :docs,
"hex.publish": :docs
],
test_coverage: [tool: ExCoveralls],
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
extra_applications: [:logger]
]
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
[
{:credo, "~> 1.5", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.1", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.22", only: :docs, runtime: false},
{:excoveralls, "~> 0.14", only: :test},
{:jason, "~> 1.2"},
{:uncharted, path: "../uncharted"},
{:phoenix_live_view, "~> 0.15"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
docs: ["docs", ©_assets/1]
]
end
defp description do
"""
A LiveView Component charting package based on uncharted.
"""
end
defp docs do
[
extras: ["README.md", "CHANGELOG.md", "docs/Accessibility.md"],
main: "readme",
source_ref: "v#{@version}",
source_url: @source_url,
skip_undefined_reference_warnings_on: ["CHANGELOG.md"]
]
end
defp package do
[
files: package_files(),
licenses: ["MIT"],
links: %{"GitHub" => @source_url}
]
end
defp package_files do
~w(lib .formatter.exs mix.exs README.md LICENSE CHANGELOG.md VERSION)
end
defp copy_assets(_) do
File.cp_r("assets", "doc/assets")
end
end
| 25.410256 | 84 | 0.590313 |
08c0350489546ee0aac1a89bfd70be099da2d5f3 | 1,727 | ex | Elixir | clients/access_context_manager/lib/google_api/access_context_manager/v1/model/test_iam_permissions_request.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/access_context_manager/lib/google_api/access_context_manager/v1/model/test_iam_permissions_request.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/access_context_manager/lib/google_api/access_context_manager/v1/model/test_iam_permissions_request.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest do
@moduledoc """
Request message for `TestIamPermissions` method.
## Attributes
* `permissions` (*type:* `list(String.t)`, *default:* `nil`) - The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:permissions => list(String.t()) | nil
}
field(:permissions, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest do
def decode(value, options) do
GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.744681 | 288 | 0.751013 |
08c03e6eb075ebdc0c367f4379007ebcdfe0ee08 | 566 | exs | Elixir | elixir/day1/mix.exs | marclefrancois/advent-of-code-2018 | 75c2a088af3a6bac3fd8f86f2cb5fa21164f6ba5 | [
"MIT"
] | null | null | null | elixir/day1/mix.exs | marclefrancois/advent-of-code-2018 | 75c2a088af3a6bac3fd8f86f2cb5fa21164f6ba5 | [
"MIT"
] | null | null | null | elixir/day1/mix.exs | marclefrancois/advent-of-code-2018 | 75c2a088af3a6bac3fd8f86f2cb5fa21164f6ba5 | [
"MIT"
] | null | null | null | defmodule Day1.MixProject do
use Mix.Project
def project do
[
app: :day1,
version: "0.1.0",
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
| 19.517241 | 88 | 0.570671 |
08c07ddacb83ae003d92156d3578ea4496c2273a | 1,031 | exs | Elixir | test/nerves/env_test.exs | tverlaan/nerves | 515b9b7730a1b2934ac051b0e7075cd7987b6c4a | [
"Apache-2.0"
] | 1 | 2019-06-12T17:34:10.000Z | 2019-06-12T17:34:10.000Z | test/nerves/env_test.exs | opencollective/nerves | 81f5d30de283e77f3720a87fa1435619f0da12de | [
"Apache-2.0"
] | null | null | null | test/nerves/env_test.exs | opencollective/nerves | 81f5d30de283e77f3720a87fa1435619f0da12de | [
"Apache-2.0"
] | null | null | null | defmodule Nerves.EnvTest do
use NervesTest.Case, async: false
alias Nerves.Env
test "populate Nerves env" do
in_fixture "simple_app", fn ->
packages =
~w(system toolchain system_platform toolchain_platform)
|> Enum.sort
env_pkgs =
packages
|> load_env
|> Enum.map(& &1.app)
|> Enum.map(&Atom.to_string/1)
|> Enum.sort
assert packages == env_pkgs
end
end
test "determine host arch" do
assert Env.parse_arch("win32") == "x86_64"
assert Env.parse_arch("x86_64-apple-darwin14.1.0") == "x86_64"
assert Env.parse_arch("armv7l-unknown-linux-gnueabihf") == "arm"
assert Env.parse_arch("unknown") == "x86_64"
end
test "determine host platform" do
assert Env.parse_platform("win32") == "win"
assert Env.parse_platform("x86_64-apple-darwin14.1.0") == "darwin"
assert Env.parse_platform("x86_64-unknown-linux-gnu") == "linux"
assert_raise Mix.Error, fn ->
Env.parse_platform("unknown")
end
end
end
| 27.131579 | 70 | 0.642095 |
08c0845548adb51c4658277a78a184f9fce4396a | 248 | exs | Elixir | year_2021/test/day_12_test.exs | bschmeck/advent_of_code | cbec98019c6c00444e0f4c7e15e01b1ed9ae6145 | [
"MIT"
] | null | null | null | year_2021/test/day_12_test.exs | bschmeck/advent_of_code | cbec98019c6c00444e0f4c7e15e01b1ed9ae6145 | [
"MIT"
] | null | null | null | year_2021/test/day_12_test.exs | bschmeck/advent_of_code | cbec98019c6c00444e0f4c7e15e01b1ed9ae6145 | [
"MIT"
] | null | null | null | defmodule Day12Test do
use ExUnit.Case, async: true
test "it counts paths for part one" do
assert Day12.part_one(InputTestFile) == 10
end
test "it counts paths for part two" do
assert Day12.part_two(InputTestFile) == 36
end
end
| 20.666667 | 46 | 0.71371 |
08c0abf32221d498510555079e0de4d6dae13aca | 4,075 | ex | Elixir | lib/chat_api/slack_conversation_threads.ex | raditya3/papercups | 4657b258ee381ac0b7517e57e4d6261ce94b5871 | [
"MIT"
] | null | null | null | lib/chat_api/slack_conversation_threads.ex | raditya3/papercups | 4657b258ee381ac0b7517e57e4d6261ce94b5871 | [
"MIT"
] | null | null | null | lib/chat_api/slack_conversation_threads.ex | raditya3/papercups | 4657b258ee381ac0b7517e57e4d6261ce94b5871 | [
"MIT"
] | null | null | null | defmodule ChatApi.SlackConversationThreads do
@moduledoc """
The SlackConversationThreads context.
"""
import Ecto.Query, warn: false
alias ChatApi.Repo
alias ChatApi.SlackConversationThreads.SlackConversationThread
@spec list_slack_conversation_threads() :: [SlackConversationThread.t()]
@doc """
Returns the list of slack_conversation_threads.
## Examples
iex> list_slack_conversation_threads()
[%SlackConversationThread{}, ...]
"""
def list_slack_conversation_threads do
Repo.all(SlackConversationThread)
end
@spec get_slack_conversation_thread!(binary()) :: SlackConversationThread.t()
@doc """
Gets a single slack_conversation_thread.
Raises `Ecto.NoResultsError` if the Slack conversation thread does not exist.
## Examples
iex> get_slack_conversation_thread!(123)
%SlackConversationThread{}
iex> get_slack_conversation_thread!(456)
** (Ecto.NoResultsError)
"""
def get_slack_conversation_thread!(id), do: Repo.get!(SlackConversationThread, id)
@spec get_thread_by_conversation_id(binary()) :: SlackConversationThread.t() | nil
def get_thread_by_conversation_id(conversation_id) do
SlackConversationThread
|> where(conversation_id: ^conversation_id)
|> preload(:conversation)
|> Repo.one()
end
@spec get_by_slack_thread_ts(binary(), binary()) :: SlackConversationThread.t() | nil
def get_by_slack_thread_ts(slack_thread_ts, slack_channel) do
SlackConversationThread
|> where(slack_thread_ts: ^slack_thread_ts)
|> where(slack_channel: ^slack_channel)
|> preload(:conversation)
|> Repo.one()
end
@spec create_slack_conversation_thread(map()) ::
{:ok, SlackConversationThread.t()} | {:error, Ecto.Changeset.t()}
@doc """
Creates a slack_conversation_thread.
## Examples
iex> create_slack_conversation_thread(%{field: value})
{:ok, %SlackConversationThread{}}
iex> create_slack_conversation_thread(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_slack_conversation_thread(attrs \\ %{}) do
%SlackConversationThread{}
|> SlackConversationThread.changeset(attrs)
|> Repo.insert()
end
@spec update_slack_conversation_thread(SlackConversationThread.t(), map()) ::
{:ok, SlackConversationThread.t()} | {:error, Ecto.Changeset.t()}
@doc """
Updates a slack_conversation_thread.
## Examples
iex> update_slack_conversation_thread(slack_conversation_thread, %{field: new_value})
{:ok, %SlackConversationThread{}}
iex> update_slack_conversation_thread(slack_conversation_thread, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_slack_conversation_thread(
%SlackConversationThread{} = slack_conversation_thread,
attrs
) do
slack_conversation_thread
|> SlackConversationThread.changeset(attrs)
|> Repo.update()
end
@spec delete_slack_conversation_thread(SlackConversationThread.t()) ::
{:ok, SlackConversationThread.t()} | {:error, Ecto.Changeset.t()}
@doc """
Deletes a slack_conversation_thread.
## Examples
iex> delete_slack_conversation_thread(slack_conversation_thread)
{:ok, %SlackConversationThread{}}
iex> delete_slack_conversation_thread(slack_conversation_thread)
{:error, %Ecto.Changeset{}}
"""
def delete_slack_conversation_thread(%SlackConversationThread{} = slack_conversation_thread) do
Repo.delete(slack_conversation_thread)
end
@spec change_slack_conversation_thread(SlackConverationThread.t(), map()) :: Ecto.Changeset.t()
@doc """
Returns an `%Ecto.Changeset{}` for tracking slack_conversation_thread changes.
## Examples
iex> change_slack_conversation_thread(slack_conversation_thread)
%Ecto.Changeset{data: %SlackConversationThread{}}
"""
def change_slack_conversation_thread(
%SlackConversationThread{} = slack_conversation_thread,
attrs \\ %{}
) do
SlackConversationThread.changeset(slack_conversation_thread, attrs)
end
end
| 29.744526 | 97 | 0.723436 |
08c0af029b614edbd0087a711d59bdbb71b81306 | 5,081 | exs | Elixir | test/absinthe/phase/execution/non_null_test.exs | Rabbet/absinthe | 0764d7eb6ea9bdf9ccd957fa27bf1e6b26968f89 | [
"MIT"
] | 2 | 2021-04-22T23:45:04.000Z | 2021-05-07T01:01:15.000Z | test/absinthe/phase/execution/non_null_test.exs | Rabbet/absinthe | 0764d7eb6ea9bdf9ccd957fa27bf1e6b26968f89 | [
"MIT"
] | null | null | null | test/absinthe/phase/execution/non_null_test.exs | Rabbet/absinthe | 0764d7eb6ea9bdf9ccd957fa27bf1e6b26968f89 | [
"MIT"
] | null | null | null | defmodule Absinthe.Phase.Document.Execution.NonNullTest do
use Absinthe.Case, async: true
defmodule Schema do
use Absinthe.Schema
defp thing_resolver(_, %{make_null: make_null}, _) do
if make_null do
{:ok, nil}
else
{:ok, %{}}
end
end
defp thing_resolver(_, _, _) do
{:ok, %{}}
end
object :thing do
field :nullable, :thing do
arg :make_null, :boolean
resolve &thing_resolver/3
end
@desc """
A field declared to be non null.
It accepts an argument for testing that can be used to make it return null,
testing the null handling behaviour.
"""
field :non_null, non_null(:thing) do
arg :make_null, :boolean
resolve &thing_resolver/3
end
field :non_null_error_field, non_null(:string) do
resolve fn _, _ ->
{:error, "boom"}
end
end
end
query do
field :nullable, :thing do
arg :make_null, :boolean
resolve &thing_resolver/3
end
field :non_null_error_field, non_null(:string) do
resolve fn _, _ ->
{:error, "boom"}
end
end
field :nullable_list_of_nullable, list_of(:thing) do
resolve fn _, _ ->
{:ok, [%{}]}
end
end
field :nullable_list_of_non_null, list_of(non_null(:thing)) do
resolve fn _, _ ->
{:ok, [%{}]}
end
end
@desc """
A field declared to be non null.
It accepts an argument for testing that can be used to make it return null,
testing the null handling behaviour.
"""
field :non_null, non_null(:thing) do
arg :make_null, :boolean
resolve &thing_resolver/3
end
end
end
test "getting a null value normally works fine" do
doc = """
{
nullable { nullable(makeNull: true) { __typename }}
}
"""
assert {:ok, %{data: %{"nullable" => %{"nullable" => nil}}}} == Absinthe.run(doc, Schema)
end
test "returning nil from a non null field makes the parent nullable null" do
doc = """
{
nullable { nullable { nonNull(makeNull: true) { __typename }}}
}
"""
data = %{"nullable" => %{"nullable" => nil}}
errors = [
%{
locations: [%{column: 25, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nullable", "nullable", "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "error propogation to root field returns nil on data" do
doc = """
{
nullable { nullable { nonNullErrorField }}
}
"""
data = %{"nullable" => %{"nullable" => nil}}
errors = [
%{
locations: [%{column: 25, line: 2}],
message: "boom",
path: ["nullable", "nullable", "nonNullErrorField"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "returning an error from a non null field makes the parent nullable null" do
doc = """
{
nonNull { nonNull { nonNullErrorField }}
}
"""
result = Absinthe.run(doc, Schema)
errors = [
%{
locations: [%{column: 23, line: 2}],
message: "boom",
path: ["nonNull", "nonNull", "nonNullErrorField"]
}
]
assert {:ok, %{data: nil, errors: errors}} == result
end
test "returning an error from a non null field makes the parent nullable null at arbitrary depth" do
doc = """
{
nullable { nonNull { nonNull { nonNull { nonNull { nonNullErrorField }}}}}
}
"""
data = %{"nullable" => nil}
path = ["nullable", "nonNull", "nonNull", "nonNull", "nonNull", "nonNullErrorField"]
errors = [
%{locations: [%{column: 54, line: 2}], message: "boom", path: path}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
describe "lists" do
test "list of nullable things works when child has a null violation" do
doc = """
{
nullableListOfNullable { nonNull(makeNull: true) { __typename } }
}
"""
data = %{"nullableListOfNullable" => [nil]}
errors = [
%{
locations: [%{column: 28, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nullableListOfNullable", 0, "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "list of non null things works when child has a null violation" do
doc = """
{
nullableListOfNonNull { nonNull(makeNull: true) { __typename } }
}
"""
data = %{"nullableListOfNonNull" => nil}
errors = [
%{
locations: [%{column: 27, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nullableListOfNonNull", 0, "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
end
end
| 24.311005 | 102 | 0.554222 |
08c0b73048b5027a78c2da6bc0fc1d5d985c2a51 | 2,132 | ex | Elixir | lib/k8s/discovery.ex | rbino/k8s | fc18899344f3d153815bd59c423568d747a33ba5 | [
"MIT"
] | null | null | null | lib/k8s/discovery.ex | rbino/k8s | fc18899344f3d153815bd59c423568d747a33ba5 | [
"MIT"
] | null | null | null | lib/k8s/discovery.ex | rbino/k8s | fc18899344f3d153815bd59c423568d747a33ba5 | [
"MIT"
] | null | null | null | defmodule K8s.Discovery do
@moduledoc "Kubernetes API Discovery"
alias K8s.{Conn, Operation}
@doc """
Discovery the URL for a `K8s.Conn` and `K8s.Operation`
## Examples
iex> conn = K8s.Conn.from_file("./test/support/kube-config.yaml")
...> op = K8s.Operation.build(:get, "apps/v1", :deployments, [namespace: "default", name: "nginx"])
...> K8s.Discovery.url_for(conn, op)
{:ok, "https://localhost:6443/apis/apps/v1/namespaces/default/deployments/nginx"}
"""
@spec url_for(Conn.t(), Operation.t()) :: {:ok, String.t()} | {:error, atom(), binary()}
def url_for(%Conn{} = conn, %Operation{api_version: api_version, name: name, verb: _} = op) do
with {:ok, name} <-
K8s.Discovery.ResourceFinder.resource_name_for_kind(conn, api_version, name),
op <- Map.put(op, :name, name),
{:ok, path} <- Operation.to_path(op) do
{:ok, Path.join(conn.url, path)}
end
end
@doc """
Override the _default_ driver for discovery.
Each `K8s.Conn` can have its own driver set. If unset, this value will be used.
Defaults to `K8s.Discovery.Driver.HTTP`
## Example mix config
In the example below `dev` and `test` clusters will use the File driver, while `prod` will use the HTTP driver.
```elixir
use Mix.Config
config :k8s,
discovery_driver: K8s.Discovery.Driver.File,
discovery_opts: [config: "test/support/discovery/example.json"],
clusters: %{
test: %{
conn: "test/support/kube-config.yaml"
},
dev: %{
conn: "test/support/kube-config.yaml"
},
prod: %{
conn: "test/support/kube-config.yaml",
conn_opts: [
discovery_driver: K8s.Discovery.Driver.HTTP
]
}
}
```
"""
@spec default_driver() :: module()
def default_driver do
Application.get_env(:k8s, :discovery_driver, K8s.Discovery.Driver.HTTP)
end
@doc """
Override default opts for the discovery driver. This is also configurable per `K8s.Conn`
"""
@spec default_opts() :: Keyword.t()
def default_opts do
Application.get_env(:k8s, :discovery_opts, [])
end
end
| 30.028169 | 113 | 0.635084 |
08c0ba985e05b4ebd363ed2a6c782bc53b1cfa87 | 418 | ex | Elixir | lib/re_web/views/image_view.ex | diemesleno/backend | a55f9c846cc826b5269f3fd6ce19223f0c6a1682 | [
"MIT"
] | 1 | 2020-01-23T04:24:58.000Z | 2020-01-23T04:24:58.000Z | lib/re_web/views/image_view.ex | diemesleno/backend | a55f9c846cc826b5269f3fd6ce19223f0c6a1682 | [
"MIT"
] | null | null | null | lib/re_web/views/image_view.ex | diemesleno/backend | a55f9c846cc826b5269f3fd6ce19223f0c6a1682 | [
"MIT"
] | 1 | 2019-12-31T16:11:21.000Z | 2019-12-31T16:11:21.000Z | defmodule ReWeb.ImageView do
use ReWeb, :view
def render("index.json", %{images: images}) do
%{images: render_many(images, ReWeb.ImageView, "image.json")}
end
def render("create.json", %{image: image}) do
%{image: render_one(image, ReWeb.ImageView, "image.json")}
end
def render("image.json", %{image: image}) do
%{id: image.id, filename: image.filename, position: image.position}
end
end
| 26.125 | 71 | 0.674641 |
08c0de6cbe899669aa2a559205656ab3f15d6097 | 3,116 | exs | Elixir | priv/repo/seeds.exs | karabiner-inc/materia_chat | 6670c97e2bd6e677b4ac1234f2c9f10a7f0020b2 | [
"Apache-2.0"
] | null | null | null | priv/repo/seeds.exs | karabiner-inc/materia_chat | 6670c97e2bd6e677b4ac1234f2c9f10a7f0020b2 | [
"Apache-2.0"
] | 4 | 2019-04-01T01:35:25.000Z | 2019-06-06T05:36:31.000Z | priv/repo/seeds.exs | karabiner-inc/materia_chat | 6670c97e2bd6e677b4ac1234f2c9f10a7f0020b2 | [
"Apache-2.0"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Materia.Repo.insert!(%Materia.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
alias MateriaUtils.Test.TsvParser
alias Materia.Accounts
alias Materia.Locations
Accounts.create_grant(%{ role: "anybody", method: "ANY", request_path: "/api/ops/users" })
Accounts.create_grant(%{ role: "admin", method: "ANY", request_path: "/api/ops/grants" })
Accounts.create_grant(%{ role: "operator", method: "GET", request_path: "/api/ops/grants" })
Accounts.create_grant(%{ role: "anybody", method: "ANY", request_path: "/api/ops/organizations" })
Accounts.create_grant(%{ role: "anybody", method: "ANY", request_path: "/api/ops/mail-templates" })
{:ok, user_hogehoge} = Accounts.create_user(%{ name: "hogehoge", email: "hogehoge@example.com", password: "hogehoge", role: "admin"})
Accounts.create_user(%{ name: "fugafuga", email: "fugafuga@example.com", password: "fugafuga", role: "operator"})
Accounts.create_user(%{ name: "higehige", email: "higehige@example.com", password: "higehige", role: "operator"})
Locations.create_address(%{user_id: user_hogehoge.id, subject: "living", location: "福岡県", zip_code: "810-ZZZZ", address1: "福岡市中央区", address2: "港 x-x-xx"})
Locations.create_address(%{user_id: user_hogehoge.id, subject: "billing", location: "福岡県", zip_code: "810-ZZZZ", address1: "福岡市中央区", address2: "大名 x-x-xx"})
alias Materia.Organizations
{:ok, organization_hogehoge} = Organizations.create_organization( %{name: "hogehoge.inc", one_line_message: "let's do this.", back_ground_img_url: "https://hogehoge.com/ib_img.jpg", profile_img_url: "https://hogehoge.com/prof_img.jpg", hp_url: "https://hogehoge.inc"})
Accounts.update_user(user_hogehoge, %{organization_id: organization_hogehoge.id})
Locations.create_address(%{organization_id: organization_hogehoge.id, subject: "registry", location: "福岡県", zip_code: "810-ZZZZ", address1: "福岡市中央区", address2: "天神 x-x-xx"})
Locations.create_address(%{organization_id: organization_hogehoge.id, subject: "branch", location: "福岡県", zip_code: "812-ZZZZ", address1: "北九州市小倉北区", address2: "浅野 x-x-xx"})
{:ok, account} = Accounts.create_account(%{"external_code" => "hogehoge_code", "name" => "hogehoge account", "start_datetime" => "2019-01-10T10:03:50.293740Z", "main_user_id" => user_hogehoge.id, "organization_id" => organization_hogehoge.id})
alias MateriaChat.Rooms
rooms = "
id title access_poricy status
1 test chat room 001 private 1
2 test public chat room 001 public 1
"
jsons = TsvParser.parse_tsv_to_json(rooms, "title")
results = jsons
|> Enum.map(fn(json) ->
{:ok, result} = json
|> Rooms.create_chat_room()
end)
members = "
id chat_room_id user_id is_admin
1 1 1 1
2 1 2 2
"
jsons = TsvParser.parse_tsv_to_json(members, "id")
results = jsons
|> Enum.map(fn(json) ->
{:ok, result} = json
|> Rooms.create_chat_room_member()
end)
| 40.467532 | 268 | 0.715019 |
08c0f3371c73602d227235aa7c3a9f594f1bc5b2 | 3,216 | ex | Elixir | clients/eventarc/lib/google_api/eventarc/v1beta1/model/expr.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/eventarc/lib/google_api/eventarc/v1beta1/model/expr.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/eventarc/lib/google_api/eventarc/v1beta1/model/expr.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.Eventarc.V1beta1.Model.Expr do
@moduledoc """
Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" expression: "document.summary.size() < 100" Example (Equality): title: "Requestor is owner" description: "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly visible" expression: "document.type != 'private' && document.type != 'internal'" Example (Data Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that may be referenced within an expression are determined by the service that evaluates it. See the service documentation for additional information.
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - Optional. Description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.
* `expression` (*type:* `String.t`, *default:* `nil`) - Textual representation of an expression in Common Expression Language syntax.
* `location` (*type:* `String.t`, *default:* `nil`) - Optional. String indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
* `title` (*type:* `String.t`, *default:* `nil`) - Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t(),
:expression => String.t(),
:location => String.t(),
:title => String.t()
}
field(:description)
field(:expression)
field(:location)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.Eventarc.V1beta1.Model.Expr do
def decode(value, options) do
GoogleApi.Eventarc.V1beta1.Model.Expr.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Eventarc.V1beta1.Model.Expr do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.428571 | 1,092 | 0.736007 |
08c0fee81ef845487024fb4ad7e3261787f08dec | 4,948 | ex | Elixir | lib/automata/core/automaton_server.ex | pcmarks/automata | 2872c4ded9200e7cbf78a360517511be1375fb0b | [
"Apache-2.0"
] | null | null | null | lib/automata/core/automaton_server.ex | pcmarks/automata | 2872c4ded9200e7cbf78a360517511be1375fb0b | [
"Apache-2.0"
] | null | null | null | lib/automata/core/automaton_server.ex | pcmarks/automata | 2872c4ded9200e7cbf78a360517511be1375fb0b | [
"Apache-2.0"
] | null | null | null | defmodule Automata.AutomatonServer do
use GenServer
defmodule State do
defstruct automaton_sup: nil,
node_sup: nil,
monitors: nil,
automaton: nil,
name: nil,
mfa: nil
end
def start_link([automaton_sup, node_config]) do
GenServer.start_link(__MODULE__, [automaton_sup, node_config], name: name(node_config[:name]))
end
def status(tree_name) do
GenServer.call(name(tree_name), :status)
end
#############
# Callbacks #
#############
def init([automaton_sup, node_config]) when is_pid(automaton_sup) do
Process.flag(:trap_exit, true)
monitors = :ets.new(:monitors, [:private])
state = %State{automaton_sup: automaton_sup, monitors: monitors}
init(node_config, state)
end
def init([{:name, name} | rest], state) do
init(rest, %{state | name: name})
end
def init([{:mfa, mfa} | rest], state) do
init(rest, %{state | mfa: mfa})
end
def init([], state) do
send(self(), :start_node_supervisor)
{:ok, state}
end
def init([_ | rest], state) do
init(rest, state)
end
def handle_call(:status, _from, %{automaton: automaton, monitors: monitors} = state) do
{:reply, {state, length(automaton)}, state}
end
def handle_call(_msg, _from, state) do
{:reply, {:error, :invalid_message}, :ok, state}
end
def handle_cast({:failed, automaton}, %{monitors: monitors} = state) do
case :ets.lookup(monitors, automaton) do
[{pid, ref}] ->
true = Process.demonitor(ref)
true = :ets.delete(monitors, pid)
{:noreply, state}
[] ->
{:noreply, state}
end
end
def handle_info(
:start_node_supervisor,
state = %{automaton_sup: automaton_sup, name: name, mfa: mfa}
) do
spec = {Automaton.NodeSupervisor, [[self(), mfa, name]]}
{:ok, node_sup} = Supervisor.start_child(automaton_sup, spec)
# automaton = prepopulate(size, automaton_sup)
automaton = new_automaton(node_sup, mfa, name)
{:noreply, %{state | node_sup: node_sup, automaton: automaton}}
end
def handle_info({:DOWN, ref, _, _, _}, state = %{monitors: monitors, automaton: automaton}) do
case :ets.match(monitors, {:"$1", ref}) do
[[pid]] ->
true = :ets.delete(monitors, pid)
new_state = %{state | automaton: [pid | automaton]}
{:noreply, new_state}
[[]] ->
{:noreply, state}
end
end
def handle_info({:EXIT, node_sup, reason}, state = %{node_sup: node_sup}) do
{:stop, reason, state}
end
def handle_info(
{:EXIT, pid, _reason},
state = %{
monitors: monitors,
automaton: automaton,
node_sup: node_sup,
mfa: mfa,
name: name
}
) do
case :ets.lookup(monitors, pid) do
[{pid, ref}] ->
true = Process.demonitor(ref)
true = :ets.delete(monitors, pid)
new_state = handle_automaton_exit(pid, state)
{:noreply, new_state}
[] ->
# NOTE: Worker crashed, no monitor
case Enum.member?(automaton, pid) do
true ->
remaining_automaton = automaton |> Enum.reject(fn p -> p == pid end)
new_state = %{
state
| automaton: [new_automaton(node_sup, mfa, name) | remaining_automaton]
}
{:noreply, new_state}
false ->
{:noreply, state}
end
end
end
def handle_info(_info, state) do
{:noreply, state}
end
def terminate(_reason, _state) do
:ok
end
#####################
# Private Functions #
#####################
defp name(tree_name) do
:"#{tree_name}Server"
end
#
# defp prepopulate(size, sup) do
# prepopulate(size, sup, [])
# end
#
# defp prepopulate(size, _sup, automaton) when size < 1 do
# automaton
# end
#
# defp prepopulate(size, sup, automaton) do
# prepopulate(size - 1, sup, [new_automaton(sup) | automaton])
# end
defp new_automaton(node_sup, {m, _f, a} = mfa, name) do
# {:ok, automaton} = DynamicSupervisor.start_child(node_sup, {m, a})
spec = {m, [[node_sup, mfa, m]]}
IO.inspect(spec)
{:ok, automaton} = DynamicSupervisor.start_child(node_sup, spec)
true = Process.link(automaton)
automaton
end
# NOTE: We use this when we have to queue up the consumer
# defp new_automaton(sup, from_pid, mfa) do
# pid = new_automaton(sup, mfa, nil)
# ref = Process.monitor(from_pid)
# {pid, ref}
# end
defp dismiss_automaton(sup, pid) do
true = Process.unlink(pid)
DynamicSupervisor.terminate_child(sup, pid)
end
defp handle_automaton_exit(pid, state) do
%{
node_sup: node_sup,
automaton: automaton,
monitors: monitors
} = state
# TODO
end
def child_spec(arg) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [arg]}
}
end
end
| 24.616915 | 98 | 0.589127 |
08c0ff6f1da8014b009d3d302a2ffe753ba39073 | 949 | exs | Elixir | mix.exs | danielgrieve/ecto_gss | 4c5c82c5252fbd01be287b4e80ab7f86057ce9aa | [
"MIT"
] | null | null | null | mix.exs | danielgrieve/ecto_gss | 4c5c82c5252fbd01be287b4e80ab7f86057ce9aa | [
"MIT"
] | null | null | null | mix.exs | danielgrieve/ecto_gss | 4c5c82c5252fbd01be287b4e80ab7f86057ce9aa | [
"MIT"
] | null | null | null | defmodule EctoGss.Mixfile do
use Mix.Project
def project do
[
app: :ecto_gss,
version: "0.2.1",
elixir: "~> 1.6",
description: "Use Google Spreadsheets as storage for Ecto objects.",
docs: [extras: ["README.md"]],
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
package: package(),
deps: deps()
]
end
def package do
[
name: :ecto_gss,
files: ["lib", "mix.exs"],
maintainers: ["Vyacheslav Voronchuk"],
licenses: ["MIT"],
links: %{"Github" => "https://github.com/Voronchuk/ecto_gss"}
]
end
def application do
[
extra_applications: [
:logger,
:elixir_google_spreadsheets
]
]
end
defp deps do
[
{:elixir_google_spreadsheets, "~> 0.1.14"},
{:ecto, "~> 3.0"},
{:earmark, ">= 0.0.0", only: :dev},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
end
| 20.630435 | 74 | 0.531085 |
08c100a8d9f638ca148926bd30dde1b208bcb060 | 392 | ex | Elixir | lib/mix/tasks/tix.ex | elitau/tix | 2aa5fe4d91e7962ebcdc9b668aacf65e09ff9bb8 | [
"MIT"
] | 1 | 2021-08-16T18:52:45.000Z | 2021-08-16T18:52:45.000Z | lib/mix/tasks/tix.ex | elitau/tix | 2aa5fe4d91e7962ebcdc9b668aacf65e09ff9bb8 | [
"MIT"
] | 16 | 2021-03-09T19:39:31.000Z | 2022-03-15T15:20:24.000Z | lib/mix/tasks/tix.ex | elitau/tix | 2aa5fe4d91e7962ebcdc9b668aacf65e09ff9bb8 | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Tix do
use Mix.Task
@moduledoc """
Tix is a TDD tool that runs tests in
an iex shell upon save of a file.
This tool should be run in the root of the project directory
with the following command:
iex -S mix tix
"""
def run(_argv) do
Mix.Task.run("app.start", [])
# Tix.start()
Application.ensure_all_started(:tix, :permanent)
end
end
| 20.631579 | 62 | 0.668367 |
08c11032b2df2c9150da9f8dcc82a0469f142ff9 | 356 | ex | Elixir | lib/plumbapius/conn_helper.ex | Amuhar/plumbapius | a9066512f520f2ad97e677b04d70cc62695f2def | [
"Apache-2.0"
] | 10 | 2020-08-25T07:52:23.000Z | 2020-12-06T12:44:44.000Z | lib/plumbapius/conn_helper.ex | Amuhar/plumbapius | a9066512f520f2ad97e677b04d70cc62695f2def | [
"Apache-2.0"
] | 3 | 2020-10-13T11:49:32.000Z | 2021-05-28T08:34:41.000Z | lib/plumbapius/conn_helper.ex | Amuhar/plumbapius | a9066512f520f2ad97e677b04d70cc62695f2def | [
"Apache-2.0"
] | 2 | 2020-09-03T14:29:00.000Z | 2021-05-26T11:07:37.000Z | defmodule Plumbapius.ConnHelper do
alias Plug.Conn
@spec get_req_header(Conn.t(), String.t()) :: binary | nil
def get_req_header(conn, name), do: conn |> Conn.get_req_header(name) |> Enum.at(0)
@spec get_resp_header(Conn.t(), String.t()) :: binary | nil
def get_resp_header(conn, name), do: conn |> Conn.get_resp_header(name) |> Enum.at(0)
end
| 35.6 | 87 | 0.696629 |
08c12aaecc8d66d6a0e10fabf7192df0d4a12b0b | 2,131 | ex | Elixir | lib/worker_tracker/process_helper.ex | optoro/worker_tracker | 0a9381cbb596edd5948bbad82dcde409d5f6ab5b | [
"MIT"
] | 1 | 2020-02-06T17:15:44.000Z | 2020-02-06T17:15:44.000Z | lib/worker_tracker/process_helper.ex | optoro/worker_tracker | 0a9381cbb596edd5948bbad82dcde409d5f6ab5b | [
"MIT"
] | null | null | null | lib/worker_tracker/process_helper.ex | optoro/worker_tracker | 0a9381cbb596edd5948bbad82dcde409d5f6ab5b | [
"MIT"
] | 1 | 2021-04-01T13:29:18.000Z | 2021-04-01T13:29:18.000Z | defmodule WorkerTracker.ProcessHelper do
@moduledoc """
A module to help with processing process strings
"""
@doc ~S"""
This function populates the given `accumulator` with the contents of the `process_string` based on the provided callback `function`.
## Example
iex> "1 2 3" |> WorkerTracker.ProcessHelper.process_fields(%{}, fn({value, index}, acc) -> Map.put(acc,value,index) end)
%{"1" => 0, "2" => 1, "3" => 2}
iex> "1 2 3" |> WorkerTracker.ProcessHelper.process_fields([], fn({value, _index}, acc) -> [value | acc] end)
["3", "2", "1"]
"""
def process_fields(process_string, accumulator, function) do
process_string
|> process_fields_with_index()
|> Enum.reduce(accumulator, &function.(&1, &2))
end
@doc ~S"""
Splits a space-delimited string and returns a list with the index
## Example
iex> "deploy 1123 10" |> WorkerTracker.ProcessHelper.process_fields_with_index()
[{"deploy", 0}, {"1123", 1}, {"10", 2}]
"""
def process_fields_with_index(process_string) do
process_string
|> clean_command_string()
|> String.split(" ")
|> Enum.with_index()
end
@doc ~S"""
A function that creates a list from the given `process_string`
## Example
iex(1)> WorkerTracker.ProcessHelper.create_list_from_string("a\nb\nc\n")
["a", "b", "c"]
"""
def create_list_from_string(process_string) do
process_string
|> String.split("\n")
|> Enum.reject(&(&1 == ""))
end
@doc ~S"""
This function filters the `process_list` for the given `filter_string` and returns the result of applying the `filter_function`.
## Example
iex(1)> WorkerTracker.ProcessHelper.filter_and_transform_process_list(["a b", "c d"], "a", &String.split(&1))
[["a", "b"]]
"""
def filter_and_transform_process_list(process_list, filter_string, parser_function) do
process_list
|> Enum.filter(&String.contains?(&1, filter_string))
|> Enum.map(&parser_function.(&1))
end
defp clean_command_string(command_string) do
command_string
|> String.trim()
|> String.replace(~r/\s+/, " ")
end
end
| 30.014085 | 134 | 0.652745 |
08c135ee611d340581ffa5759f0677fc5c8600d2 | 84 | exs | Elixir | test/matchers/text_test.exs | adriankumpf/infer | a8a59683d6d8abe4be1addaa1067046509e23655 | [
"MIT"
] | 4 | 2022-01-12T10:53:47.000Z | 2022-03-15T13:55:38.000Z | test/matchers/text_test.exs | adriankumpf/infer | a8a59683d6d8abe4be1addaa1067046509e23655 | [
"MIT"
] | 4 | 2022-01-09T13:30:27.000Z | 2022-03-11T15:22:16.000Z | test/matchers/text_test.exs | adriankumpf/infer | a8a59683d6d8abe4be1addaa1067046509e23655 | [
"MIT"
] | 3 | 2022-01-09T13:16:12.000Z | 2022-03-10T11:43:10.000Z | defmodule Infer.TextTest do
use ExUnit.Case, async: true
doctest Infer.Text
end
| 16.8 | 30 | 0.77381 |
08c14fa4c72404fc394d3b62021c11a36bfbab1b | 1,713 | ex | Elixir | clients/docs/lib/google_api/docs/v1/model/delete_header_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/docs/lib/google_api/docs/v1/model/delete_header_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/docs/lib/google_api/docs/v1/model/delete_header_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.Docs.V1.Model.DeleteHeaderRequest do
@moduledoc """
Deletes a Header from the document.
## Attributes
* `headerId` (*type:* `String.t`, *default:* `nil`) - The id of the header to delete. If this header is defined on DocumentStyle, the reference to this header is removed, resulting in no header of that type for the first section of the document. If this header is defined on a SectionStyle, the reference to this header is removed and the header of that type is now continued from the previous section.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:headerId => String.t()
}
field(:headerId)
end
defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.DeleteHeaderRequest do
def decode(value, options) do
GoogleApi.Docs.V1.Model.DeleteHeaderRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.DeleteHeaderRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.446809 | 406 | 0.747227 |
08c153d1f3bf913a53a9a025da4f75f66979c774 | 18,075 | ex | Elixir | lib/ecto/migration.ex | mschae/ecto | 00f85444c4f61080617179232c0d528381de5ec3 | [
"Apache-2.0"
] | null | null | null | lib/ecto/migration.ex | mschae/ecto | 00f85444c4f61080617179232c0d528381de5ec3 | [
"Apache-2.0"
] | null | null | null | lib/ecto/migration.ex | mschae/ecto | 00f85444c4f61080617179232c0d528381de5ec3 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Migration do
@moduledoc """
Migrations are used to modify your database schema over time.
This module provides many helpers for migrating the database,
allowing developers to use Elixir to alter their storage in
a way that is database independent.
Here is an example:
defmodule MyRepo.Migrations.CreatePosts do
use Ecto.Migration
def up do
create table(:weather) do
add :city, :string, size: 40
add :temp_lo, :integer
add :temp_hi, :integer
add :prcp, :float
timestamps
end
end
def down do
drop table(:weather)
end
end
Note migrations have an `up/0` and `down/0` instructions, where
`up/0` is used to update your database and `down/0` rolls back
the prompted changes.
Ecto provides some mix tasks to help developers work with migrations:
* `mix ecto.gen.migration add_weather_table` - generates a
migration that the user can fill in with particular commands
* `mix ecto.migrate` - migrates a repository
* `mix ecto.rollback` - rolls back a particular migration
Run the `mix help COMMAND` for more information.
## Change
Migrations can also be automatically reversible by implementing
`change/0` instead of `up/0` and `down/0`. For example, the
migration above can be written as:
defmodule MyRepo.Migrations.CreatePosts do
use Ecto.Migration
def change do
create table(:weather) do
add :city, :string, size: 40
add :temp_lo, :integer
add :temp_hi, :integer
add :prcp, :float
timestamps
end
end
end
Notice not all commands are reversible though. Trying to rollback
a non-reversible command will raise an `Ecto.MigrationError`.
## Prefixes
Migrations support specifying a table prefix or index prefix which will target either a schema
if using Postgres, or a different database if using MySQL. If no prefix is
provided, the default schema or database is used.
Any reference declated in table migration refer by default table with same prefix declared for table.
The prefix is specified in the table options:
def up do
create table(:weather, prefix: :north_america) do
add :city, :string, size: 40
add :temp_lo, :integer
add :temp_hi, :integer
add :prcp, :float
add :group_id, references(:groups)
timestamps
end
create index(:weather, [:city], prefix: :north_america)
end
Note: if using MySQL with a prefixed table, you must use the same prefix for the references since
cross database references are not supported.
For both MySQL and Postgres with a prefixed table, you must use the same prefix for the index field to ensure
you index the prefix qualified table.
## Transactions
By default, Ecto runs all migrations inside a transaction. That's not always
ideal: for example, PostgreSQL allows to create/drop indexes concurrently but
only outside of any transaction (see the [PostgreSQL
docs](http://www.postgresql.org/docs/9.2/static/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY)).
Migrations can be forced to run outside a transaction by setting the
`@disable_ddl_transaction` module attribute to `true`:
defmodule MyRepo.Migrations.CreateIndexes do
use Ecto.Migration
@disable_ddl_transaction true
def change do
create index(:posts, [:slug], concurrently: true)
end
end
Since running migrations outside a transaction can be dangerous, consider
performing very few operations in such migrations.
See the `index/3` function for more information on creating/dropping indexes
concurrently.
"""
defmodule Index do
@moduledoc """
Defines an index struct used in migrations.
"""
defstruct table: nil,
prefix: nil,
name: nil,
columns: [],
unique: false,
concurrently: false,
using: nil
@type t :: %__MODULE__{
table: atom,
prefix: atom,
name: atom,
columns: [atom | String.t],
unique: boolean,
concurrently: boolean,
using: atom | String.t
}
end
defmodule Table do
@moduledoc """
Defines a table struct used in migrations.
"""
defstruct name: nil, prefix: nil, primary_key: true, engine: nil, options: nil
@type t :: %__MODULE__{name: atom, prefix: atom, primary_key: boolean, engine: atom}
end
defmodule Reference do
@moduledoc """
Defines a reference struct used in migrations.
"""
defstruct name: nil,
table: nil,
column: :id,
type: :serial,
on_delete: :nothing
@type t :: %__MODULE__{
table: atom,
column: atom,
type: atom,
on_delete: atom
}
end
alias Ecto.Migration.Runner
@doc false
defmacro __using__(_) do
quote location: :keep do
import Ecto.Migration
@disable_ddl_transaction false
@before_compile Ecto.Migration
end
end
@doc false
defmacro __before_compile__(_env) do
quote do
def __migration__,
do: [disable_ddl_transaction: @disable_ddl_transaction]
end
end
@doc """
Creates a table.
By default, the table will also include a primary_key of name `:id`
and type `:serial`. Check `table/2` docs for more information.
## Examples
create table(:posts) do
add :title, :string, default: "Untitled"
add :body, :text
timestamps
end
"""
defmacro create(object, do: block) do
do_create(object, :create, block)
end
@doc """
Creates a table if it does not exist.
Works just like `create/2` but does not raise an error when table
already exists.
"""
defmacro create_if_not_exists(object, do: block) do
do_create(object, :create_if_not_exists, block)
end
defp do_create(object, command, block) do
quote do
table = %Table{} = unquote(object)
Runner.start_command({unquote(command), table})
if table.primary_key do
add(:id, :serial, primary_key: true)
end
unquote(block)
Runner.end_command
table
end
end
@doc """
Alters a table.
## Examples
alter table(:posts) do
add :summary, :text
modify :title, :text
remove :views
end
"""
defmacro alter(object, do: block) do
quote do
table = %Table{} = unquote(object)
Runner.start_command({:alter, table})
unquote(block)
Runner.end_command
end
end
@doc """
Creates an index or a table with only `:id` field.
When reversing (in `change` running backward) indexes are only dropped if they
exist and no errors are raised. To enforce dropping an index use `drop/1`.
## Examples
create index(:posts, [:name])
create table(:version)
"""
def create(%Index{} = index) do
Runner.execute {:create, index}
end
def create(%Table{} = table) do
do_create table, :create
table
end
@doc """
Creates an index or a table with only `:id` field if one does not yet exist.
## Examples
create_if_not_exists index(:posts, [:name])
create_if_not_exists table(:version)
"""
def create_if_not_exists(%Index{} = index) do
Runner.execute {:create_if_not_exists, index}
end
def create_if_not_exists(%Table{} = table) do
do_create table, :create_if_not_exists
end
defp do_create(table, command) do
columns =
if table.primary_key do
[{:add, :id, :serial, primary_key: true}]
else
[]
end
Runner.execute {command, table, columns}
end
@doc """
Drops a table or index.
## Examples
drop index(:posts, [:name])
drop table(:posts)
"""
def drop(%{} = object) do
Runner.execute {:drop, object}
object
end
@doc """
Drops a table or index if it exists.
Does not raise an error if table or index does not exist.
## Examples
drop_if_exists index(:posts, [:name])
drop_if_exists table(:posts)
"""
def drop_if_exists(%{} = object) do
Runner.execute {:drop_if_exists, object}
end
@doc """
Returns a table struct that can be given on create, alter, etc.
## Examples
create table(:products) do
add :name, :string
add :price, :decimal
end
drop table(:products)
create table(:products, primary_key: false) do
add :name, :string
add :price, :decimal
end
## Options
* `:primary_key` - when false, does not generate primary key on table creation
* `:engine` - customizes the table storage for supported databases. For MySQL,
the default is InnoDB
* `:options` - provide custom options that will be appended after generated
statement, for example "WITH", "INHERITS" or "ON COMMIT" clauses
"""
def table(name, opts \\ []) when is_atom(name) do
struct(%Table{name: name}, opts)
end
@doc ~S"""
Returns an index struct that can be used on `create`, `drop`, etc.
Expects the table name as first argument and the index fields as
second. The field can be an atom, representing a column, or a
string representing an expression that is sent as is to the database.
Indexes are non-unique by default.
## Options
* `:name` - the name of the index. Defaults to "#{table}_#{column}_index"
* `:unique` - if the column(s) is unique or not
* `:concurrently` - if the index should be created/dropped concurrently
* `:using` - configures the index type
* `:prefix` - prefix for the index
## Adding/dropping indexes concurrently
PostgreSQL supports adding/dropping indexes concurrently (see the
[docs](http://www.postgresql.org/docs/9.4/static/sql-createindex.html)).
In order to take advantage of this, the `:concurrently` option needs to be set
to `true` when the index is created/dropped.
**Note**: in order for the `:concurrently` option to work, the migration must
not be run inside a transaction. See the `Ecto.Migration` docs for more
information on running migrations outside of a transaction.
## Index types
PostgreSQL supports several index types like B-tree, Hash or GiST. When
creating an index, the index type defaults to B-tree, but it can be specified
with the `:using` option. The `:using` option can be an atom or a string; its
value is passed to the `USING` clause as is.
More information on index types can be found in the [PostgreSQL
docs](http://www.postgresql.org/docs/9.4/static/indexes-types.html).
## Examples
# Without a name, index defaults to products_category_id_sku_index
create index(:products, [:category_id, :sku], unique: true)
# Name can be given explicitly though
drop index(:products, [:category_id, :sku], name: :my_special_name)
# Indexes can be added concurrently
create index(:products, [:category_id, :sku], concurrently: true)
# The index type can be specified
create index(:products, [:name], using: :hash)
# Create an index on custom expressions
create index(:products, ["lower(name)"], name: :products_lower_name_index)
"""
def index(table, columns, opts \\ []) when is_atom(table) and is_list(columns) do
index = struct(%Index{table: table, columns: columns}, opts)
%{index | name: index.name || default_index_name(index)}
end
@doc """
Shortcut for creating a unique index.
See `index/3` for more information.
"""
def unique_index(table, columns, opts \\ []) when is_atom(table) and is_list(columns) do
index(table, columns, [unique: true] ++ opts)
end
defp default_index_name(index) do
[index.table, index.columns, "index"]
|> List.flatten
|> Enum.join("_")
|> String.replace(~r"[^\w_]", "_")
|> String.replace("__", "_")
|> String.to_atom
end
@doc """
Executes arbitrary SQL or a keyword command in NoSQL databases.
## Examples
execute "UPDATE posts SET published_at = NULL"
execute create: "posts", capped: true, size: 1024
"""
def execute(command) when is_binary(command) or is_list(command) do
Runner.execute command
end
@doc """
Gets the migrator direction.
"""
@spec direction :: :up | :down
def direction do
Runner.migrator_direction
end
@doc """
Adds a column when creating or altering a table.
This function also accepts Ecto primitive types as column types
and they are normalized by the database adapter. For example,
`string` is converted to varchar, `datetime` to the underlying
datetime or timestamp type, `binary` to bits or blob, and so on.
However, the column type is not always the same as the type in your
model. For example, a model that has a `string` field, can be
supported by columns of types `char`, `varchar`, `text` and others.
For this reason, this function also accepts `text` and other columns,
which are sent as is to the underlying database.
To sum up, the column type may be either an Ecto primitive type,
which is normalized in cases the database does not understand it,
like `string` or `binary`, or a database type which is passed as is.
Custom Ecto types, like `Ecto.Datetime`, are not supported because
they are application level concern and may not always map to the
database.
## Examples
create table(:posts) do
add :title, :string, default: "Untitled"
end
alter table(:posts) do
add :summary, :text # Database type
add :object, :json
end
## Options
* `:primary_key` - when true, marks this field as the primary key
* `:default` - the column's default value. can be a string, number
or a fragment generated by `fragment/1`
* `:null` - when `false`, the column does not allow null values
* `:size` - the size of the type (for example the numbers of characters).
Default is no size, except for `:string` that defaults to 255.
* `:precision` - the precision for a numeric type. Default is no precision
* `:scale` - the scale of a numeric type. Default is 0 scale
"""
def add(column, type, opts \\ []) when is_atom(column) do
validate_type!(type)
Runner.subcommand {:add, column, type, opts}
end
@doc """
Renames a table.
## Examples
rename table(:posts), to: table(:new_posts)
"""
def rename(%Table{} = table_current, to: %Table{} = table_new) do
Runner.execute {:rename, table_current, table_new}
table_new
end
@doc """
Renames a column outside of the `alter` statement.
## Examples
rename table(:posts), :title, to: :summary
"""
def rename(%Table{} = table, current_column, to: new_column) when is_atom(current_column) and is_atom(new_column) do
Runner.execute {:rename, table, current_column, new_column}
table
end
@doc """
Generates a fragment to be used as default value.
## Examples
create table(:posts) do
add :inserted_at, :datetime, default: fragment("now()")
end
"""
def fragment(expr) when is_binary(expr) do
{:fragment, expr}
end
@doc """
Adds `:inserted_at` and `:updated_at` timestamps columns.
Those columns are of `:datetime` type and by default cannot
be null. `opts` can be given to customize the generated
fields.
"""
def timestamps(opts \\ []) do
opts = Keyword.put_new(opts, :null, false)
add(:inserted_at, :datetime, opts)
add(:updated_at, :datetime, opts)
end
@doc """
Modifies the type of column when altering a table.
See `add/3` for more information on supported types.
## Examples
alter table(:posts) do
modify :title, :text
end
## Options
* `:null` - sets to null or not null
* `:default` - changes the default
* `:size` - the size of the type (for example the numbers of characters). Default is no size.
* `:precision` - the precision for a numberic type. Default is no precision.
* `:scale` - the scale of a numberic type. Default is 0 scale.
"""
def modify(column, type, opts \\ []) when is_atom(column) do
Runner.subcommand {:modify, column, type, opts}
end
@doc """
Removes a column when altering a table.
## Examples
alter table(:posts) do
remove :title
end
"""
def remove(column) when is_atom(column) do
Runner.subcommand {:remove, column}
end
@doc ~S"""
Defines a foreign key.
## Examples
create table(:products) do
add :group_id, references(:groups)
end
## Options
* `:name` - The name of the underlying reference,
defaults to "#{table}_#{column}_fkey"
* `:column` - The foreign key column, default is `:id`
* `:type` - The foreign key type, default is `:serial`
* `:on_delete` - What to perform if the entry is deleted.
May be `:nothing`, `:delete_all` or `:nilify_all`.
Defaults to `:nothing`.
"""
def references(table, opts \\ []) when is_atom(table) do
reference = struct(%Reference{table: table}, opts)
unless reference.on_delete in [:nothing, :delete_all, :nilify_all] do
raise ArgumentError, "unknown :on_delete value: #{inspect reference.on_delete}"
end
reference
end
@doc """
Executes queue migration commands.
Reverses the order commands are executed when doing a rollback
on a change/0 function and resets commands queue.
"""
def flush do
Runner.flush
end
defp validate_type!(type) when is_atom(type) do
case Atom.to_string(type) do
"Elixir." <> _ ->
raise ArgumentError,
"#{inspect type} is not a valid database type, " <>
"please use an atom like :string, :text and so on"
_ ->
:ok
end
end
defp validate_type!({type, subtype}) when is_atom(type) and is_atom(subtype) do
validate_type!(subtype)
end
defp validate_type!(%Reference{} = reference) do
reference
end
end
| 27.303625 | 118 | 0.654772 |
08c17674a04ec49fb0d85de6f5cf3516f420be75 | 715 | exs | Elixir | test/models/option_value_test.exs | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 356 | 2016-03-16T12:37:28.000Z | 2021-12-18T03:22:39.000Z | test/models/option_value_test.exs | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 30 | 2016-03-16T09:19:10.000Z | 2021-01-12T08:10:52.000Z | test/models/option_value_test.exs | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 72 | 2016-03-16T13:32:14.000Z | 2021-03-23T11:27:43.000Z | defmodule Nectar.OptionValueTest do
use Nectar.ModelCase
alias Nectar.TestSetup
alias Nectar.OptionValue
describe "fields" do
has_fields OptionValue, ~w(id name presentation position option_type_id)a ++ timestamps
end
describe "associations" do
has_associations OptionValue, ~w(option_type)a
end
describe "validations" do
test "changeset with valid attributes" do
changeset = OptionValue.changeset(%OptionValue{}, TestSetup.OptionValue.valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = OptionValue.changeset(%OptionValue{}, TestSetup.OptionValue.invalid_attrs)
refute changeset.valid?
end
end
end
| 26.481481 | 92 | 0.74965 |
08c1ea41b9262def14e154a8a3fd1807708bbc55 | 2,094 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_v2_intent_message_basic_card_button.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_v2_intent_message_basic_card_button.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dialogflow/lib/google_api/dialogflow/v3/model/google_cloud_dialogflow_v2_intent_message_basic_card_button.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButton do
@moduledoc """
The button object that appears at the bottom of a card.
## Attributes
* `openUriAction` (*type:* `GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction.t`, *default:* `nil`) - Required. Action to take when a user taps on the button.
* `title` (*type:* `String.t`, *default:* `nil`) - Required. The title of the button.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:openUriAction =>
GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction.t()
| nil,
:title => String.t() | nil
}
field(:openUriAction,
as:
GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButtonOpenUriAction
)
field(:title)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButton do
def decode(value, options) do
GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButton.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V3.Model.GoogleCloudDialogflowV2IntentMessageBasicCardButton do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.327869 | 207 | 0.748329 |
08c223abb91731b75dd76fa421951273d8659256 | 1,508 | ex | Elixir | lib/surgex/refactor/refactor.ex | surgeventures/surgex | b3acdd6a9a010c26f0081b9cb23aeb072459be30 | [
"MIT"
] | 10 | 2017-09-15T08:55:48.000Z | 2021-07-08T09:26:24.000Z | lib/surgex/refactor/refactor.ex | surgeventures/surgex | b3acdd6a9a010c26f0081b9cb23aeb072459be30 | [
"MIT"
] | 17 | 2017-07-24T11:27:22.000Z | 2022-01-24T22:28:18.000Z | lib/surgex/refactor/refactor.ex | surgeventures/surgex | b3acdd6a9a010c26f0081b9cb23aeb072459be30 | [
"MIT"
] | 2 | 2018-04-12T15:01:00.000Z | 2018-05-27T12:14:34.000Z | defmodule Surgex.Refactor do
@moduledoc """
Tools for making code maintenance and refactors easier.
"""
def call(args) do
args
|> parse_args
|> call_task
end
defp parse_args(args) do
parse_result =
OptionParser.parse(
args,
switches: [fix: :boolean]
)
{opts, task, paths} =
case parse_result do
{opts, [task | paths], _} -> {opts, task, paths}
_ -> raise(ArgumentError, "No refactor task")
end
unless Keyword.get(opts, :fix, false) do
IO.puts("You're in a simulation mode, pass the --fix option to apply the action.")
IO.puts("")
end
filenames =
paths
|> expand_paths()
|> filter_elixir_files()
{task, filenames, opts}
end
defp call_task({task, filenames, opts}) do
"Elixir.Surgex.Refactor.#{Macro.camelize(task)}"
|> String.to_existing_atom()
|> apply(:call, [filenames, opts])
end
defp filter_elixir_files(paths) do
Enum.filter(paths, &String.match?(&1, ~r/\.exs?$/))
end
defp expand_paths([]), do: expand_paths(["."])
defp expand_paths(paths) when is_list(paths) do
paths
|> Enum.map(&expand_paths/1)
|> Enum.concat()
end
defp expand_paths(path) do
cond do
File.regular?(path) ->
[path]
File.dir?(path) ->
path
|> File.ls!()
|> Enum.map(&Path.join(path, &1))
|> Enum.map(&expand_paths/1)
|> Enum.concat()
true ->
[]
end
end
end
| 20.657534 | 88 | 0.574934 |
08c27a4181fafe962d17455de7dd2fe81d52ae6e | 2,199 | ex | Elixir | lib/enum_extras.ex | codemonium/enum_extras | 17e9c7555980290b35f6ab230aa060889a269feb | [
"MIT"
] | null | null | null | lib/enum_extras.ex | codemonium/enum_extras | 17e9c7555980290b35f6ab230aa060889a269feb | [
"MIT"
] | 1 | 2021-08-03T21:54:50.000Z | 2021-08-03T21:54:50.000Z | lib/enum_extras.ex | codemonium/enum_extras | 17e9c7555980290b35f6ab230aa060889a269feb | [
"MIT"
] | null | null | null | defmodule EnumExtras do
@moduledoc """
Provides additional utility functions for working with enumerables.
"""
@type t :: Enumerable.t()
@type element :: any
@doc """
Calculates the average of the elements in the `enumerable`.
It should return `nil` if the `enumerable` is empty.
"""
@spec average(t) :: nil | integer
def average([]), do: nil
def average(list) when is_list(list) do
# FIXME: Susceptible to floating-point errors.
Enum.sum(list) / Enum.count(list)
end
@doc """
Calculates the weighted average of the elements in the `enumerable`.
It should return `nil` if the `enumerable` is empty or the weights sum to zero.
"""
@spec weighted_average(t, t) :: nil | integer
def weighted_average([], _weights), do: nil
def weighted_average(list, weights) when is_list(list) and is_list(weights) do
# TODO: Handle case when number of weights differs from number of elements in list.
case Enum.sum(weights) do
0 ->
nil
sum ->
# FIXME: Susceptible to floating-point errors.
total =
Enum.zip(list, weights)
|> Enum.reduce(0, fn {element, weight}, acc -> acc + element * weight end)
total / sum
end
end
@doc """
Partitions the elements of the `enumerable` according to the pairwise comparator.
## Examples
iex> EnumExtras.chunk_by_pairwise([1, 2, 3, 4, 1, 2, 3, 1, 2, 1], fn a, b -> a <= b end)
[[1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]
"""
@spec chunk_by_pairwise(t, (element, element -> boolean)) :: t
def chunk_by_pairwise([], _comparator), do: []
def chunk_by_pairwise([value], _comparator), do: [[value]]
def chunk_by_pairwise(values, comparator) do
values
|> Enum.reverse()
|> Enum.chunk_every(2, 1)
|> Enum.reduce([[]], fn
[value], [head | tail] ->
[[value | head] | tail]
[left_value, right_value], [head | tail] ->
acc = [[left_value | head] | tail]
# The arguments in the comparator are reversed because the given list is reversed above.
case comparator.(right_value, left_value) do
true -> acc
false -> [[]] ++ acc
end
end)
end
end
| 28.558442 | 96 | 0.617099 |
08c27f3ac4fdff93827f83fa701b2790a1f749a2 | 709 | ex | Elixir | lib/exfwghtblog/application.ex | Chlorophytus/exfwghtblog | 4508cf1368bfe8ea809acbef3f0abb31702169d5 | [
"MIT"
] | null | null | null | lib/exfwghtblog/application.ex | Chlorophytus/exfwghtblog | 4508cf1368bfe8ea809acbef3f0abb31702169d5 | [
"MIT"
] | null | null | null | lib/exfwghtblog/application.ex | Chlorophytus/exfwghtblog | 4508cf1368bfe8ea809acbef3f0abb31702169d5 | [
"MIT"
] | null | null | null | defmodule Exfwghtblog.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Starts a worker by calling: Exfwghtblog.Worker.start_link(arg)
# {Exfwghtblog.Worker, arg}
{Plug.Cowboy,
scheme: :http, plug: Exfwghtblog.Router, port: Application.fetch_env!(:exfwghtblog, :port)},
Exfwghtblog.AwsAgent
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Exfwghtblog.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 29.541667 | 99 | 0.706629 |
08c2f1325fb031119a23b8517f73a6d61543d076 | 272 | exs | Elixir | sous_chef/test/sous_chef_web/views/layout_view_test.exs | sergiotapia/bakeware | e7b752c873a88c6a4018b6162608c16da109bf14 | [
"Apache-2.0"
] | null | null | null | sous_chef/test/sous_chef_web/views/layout_view_test.exs | sergiotapia/bakeware | e7b752c873a88c6a4018b6162608c16da109bf14 | [
"Apache-2.0"
] | null | null | null | sous_chef/test/sous_chef_web/views/layout_view_test.exs | sergiotapia/bakeware | e7b752c873a88c6a4018b6162608c16da109bf14 | [
"Apache-2.0"
] | null | null | null | defmodule SousChefWeb.LayoutViewTest do
use SousChefWeb.ConnCase, async: true
# When testing helpers, you may want to import Phoenix.HTML and
# use functions such as safe_to_string() to convert the helper
# result into an HTML string.
# import Phoenix.HTML
end
| 30.222222 | 65 | 0.768382 |
08c2fdd29cef67e99f35fc34d9b1dcd96b5854e9 | 3,958 | ex | Elixir | lib/cforum_web/controllers/messages/interesting_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/interesting_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/interesting_controller.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 10 | 2019-02-10T10:39:24.000Z | 2021-07-06T11:46:05.000Z | defmodule CforumWeb.Messages.InterestingController do
use CforumWeb, :controller
alias Cforum.Threads
alias Cforum.Threads.Thread
alias Cforum.Threads.ThreadHelpers
alias Cforum.Messages
alias Cforum.InterestingMessages
alias Cforum.Search
alias Cforum.Search.Finder
alias Cforum.Abilities
alias Cforum.ConfigManager
alias CforumWeb.Views.ViewHelpers.ReturnUrl
alias CforumWeb.Paginator
def index(conn, %{"search" => search_params} = params) do
visible_sections = Search.list_visible_search_sections(conn.assigns.visible_forums)
changeset =
Search.search_changeset(
visible_sections,
Map.put(search_params, "sections", Enum.map(visible_sections, & &1.search_section_id))
)
count = Finder.count_interesting_messages_results(conn.assigns[:current_user], changeset)
paging = Paginator.paginate(count, page: params["p"])
threads =
Finder.search_interesting_messages(conn.assigns.current_user, changeset, paging.params)
|> Enum.map(fn msg -> %Thread{msg.thread | messages: [msg]} end)
|> Threads.apply_user_infos(conn.assigns[:current_user])
|> Threads.apply_highlights(conn)
|> Enum.map(fn thread -> %Thread{thread | message: List.first(thread.messages)} end)
render(conn, "index.html", threads: threads, paging: paging, changeset: changeset)
end
def index(conn, params) do
visible_sections = Search.list_visible_search_sections(conn.assigns.visible_forums)
changeset = Search.search_changeset(visible_sections)
count = InterestingMessages.count_interesting_messages(conn.assigns[:current_user])
paging = Paginator.paginate(count, page: params["p"])
threads =
InterestingMessages.list_interesting_messages(conn.assigns[:current_user], limit: paging.params)
|> Enum.map(fn msg -> %Thread{msg.thread | messages: [msg]} end)
|> Threads.apply_user_infos(conn.assigns[:current_user])
|> Threads.apply_highlights(conn)
|> Enum.map(fn thread -> %Thread{thread | message: List.first(thread.messages)} end)
render(conn, "index.html", threads: threads, paging: paging, changeset: changeset)
end
def interesting(conn, params) do
InterestingMessages.mark_message_interesting(conn.assigns[:current_user], conn.assigns.message)
conn
|> put_flash(:info, gettext("Message was successfully marked as interesting."))
|> redirect(to: ReturnUrl.return_path(conn, params, conn.assigns.thread, conn.assigns.message))
end
def boring(conn, params) do
InterestingMessages.mark_message_boring(conn.assigns[:current_user], conn.assigns.message)
conn
|> put_flash(:info, gettext("Interesting mark was successfully removed."))
|> redirect(to: ReturnUrl.return_path(conn, params, conn.assigns.thread, conn.assigns.message))
end
def load_resource(conn) do
if Phoenix.Controller.action_name(conn) == :index do
conn
else
thread =
Threads.get_thread_by_slug!(conn.assigns[:current_forum], nil, ThreadHelpers.slug_from_params(conn.params))
|> Threads.reject_deleted_threads(conn.assigns[:view_all])
|> Threads.apply_user_infos(conn.assigns[:current_user], omit: [:read, :subscriptions, :open_close])
|> Threads.apply_highlights(conn)
|> 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
end
def allowed?(conn, :interesting, message) do
message = message || conn.assigns.message
Abilities.signed_in?(conn) && message.attribs[:is_interesting] != true
end
def allowed?(conn, :boring, message) do
message = message || conn.assigns.message
Abilities.signed_in?(conn) && message.attribs[:is_interesting] == true
end
def allowed?(conn, _, _), do: Abilities.signed_in?(conn)
end
| 36.990654 | 115 | 0.724356 |
08c31c89d174be1989ff0edd666caffdd65bf555 | 1,457 | ex | Elixir | backend/lib/edgehog/assets/uploaders/system_model_picture.ex | harlem88/edgehog | 7a278d119c3d592431fdbba406207376e194f7eb | [
"Apache-2.0"
] | null | null | null | backend/lib/edgehog/assets/uploaders/system_model_picture.ex | harlem88/edgehog | 7a278d119c3d592431fdbba406207376e194f7eb | [
"Apache-2.0"
] | null | null | null | backend/lib/edgehog/assets/uploaders/system_model_picture.ex | harlem88/edgehog | 7a278d119c3d592431fdbba406207376e194f7eb | [
"Apache-2.0"
] | null | null | null | #
# This file is part of Edgehog.
#
# Copyright 2021 SECO Mind Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
defmodule Edgehog.Assets.Uploaders.SystemModelPicture do
use Waffle.Definition
@acl :public_read
@versions [:original]
@extension_allowlist ~w(.jpg .jpeg .gif .png .svg)
def validate({file, _}) do
file_extension =
file.file_name
|> Path.extname()
|> String.downcase()
Enum.member?(@extension_allowlist, file_extension)
end
def s3_object_headers(_version, {file, _scope}) do
[content_type: MIME.from_path(file.file_name)]
end
def gcs_object_headers(_version, {file, _scope}) do
[contentType: MIME.from_path(file.file_name)]
end
def gcs_optional_params(_version, {_file, _scope}) do
[predefinedAcl: "publicRead"]
end
def storage_dir(_version, {_file, system_model}) do
"uploads/tenants/#{system_model.tenant_id}/system_models/#{system_model.handle}/picture"
end
end
| 28.019231 | 92 | 0.73164 |
08c332dc1e59a4349c07e91fd684a81a4e389805 | 5,177 | ex | Elixir | lib/waffle/definition/storage.ex | tsufurukawa/waffle | f0ba0509fbb4bf05f4bcbfe75c82aff1ee17e714 | [
"Apache-2.0"
] | null | null | null | lib/waffle/definition/storage.ex | tsufurukawa/waffle | f0ba0509fbb4bf05f4bcbfe75c82aff1ee17e714 | [
"Apache-2.0"
] | 1 | 2022-01-22T22:14:56.000Z | 2022-01-22T22:14:56.000Z | lib/waffle/definition/storage.ex | ringofhealth/waffle | b797eabd3b16628370659c805aea067b2da204d5 | [
"Apache-2.0"
] | 2 | 2021-01-12T23:24:19.000Z | 2021-01-13T03:41:24.000Z | defmodule Waffle.Definition.Storage do
@moduledoc ~S"""
Uploader configuration.
Add `use Waffle.Definition` inside your module to use it as uploader.
## Storage directory
By default, the storage directory is `uploads`. But, it can be customized
in two ways.
### By setting up configuration
Customize storage directory via configuration option `:storage_dir`.
config :waffle,
storage_dir: "my/dir"
### By overriding the relevent functions in definition modules
Every definition module has a default `storage_dir/2` which is overridable.
For example, a common pattern for user avatars is to store each user's
uploaded images in a separate subdirectory based on primary key:
def storage_dir(version, {file, scope}) do
"uploads/users/avatars/#{scope.id}"
end
> **Note**: If you are "attaching" a file to a record on creation (eg, while inserting the record at the same time), then you cannot use the model's `id` as a path component. You must either (1) use a different storage path format, such as UUIDs, or (2) attach and update the model after an id has been given. [Read more about how to integrate it with Ecto](https://hexdocs.pm/waffle_ecto/filepath-with-id.html#content)
> **Note**: The storage directory is used for both local filestorage (as the relative or absolute directory), and S3 storage, as the path name (not including the bucket).
## Asynchronous File Uploading
If you specify multiple versions in your definition module, each
version is processed and stored concurrently as independent Tasks.
To prevent an overconsumption of system resources, each Task is
given a specified timeout to wait, after which the process will
fail. By default, the timeout is `15_000` milliseconds.
If you wish to change the time allocated to version transformation
and storage, you can add a configuration option:
config :waffle,
:version_timeout, 15_000 # milliseconds
To disable asynchronous processing, add `@async false` to your
definition module.
## Storage of files
Waffle currently supports:
* `Waffle.Storage.Local`
* `Waffle.Storage.S3`
Override the `__storage` function in your definition module if you
want to use a different type of storage for a particular uploader.
## File Validation
While storing files on S3 eliminates some malicious attack vectors,
it is strongly encouraged to validate the extensions of uploaded
files as well.
Waffle delegates validation to a `validate/1` function with a tuple
of the file and scope. As an example, in order to validate that an
uploaded file conforms to popular image formats, you can use:
defmodule Avatar do
use Waffle.Definition
@extension_whitelist ~w(.jpg .jpeg .gif .png)
def validate({file, _}) do
file_extension = file.file_name |> Path.extname() |> String.downcase()
Enum.member?(@extension_whitelist, file_extension)
end
end
Any uploaded file failing validation will return `{:error, :invalid_file}` when
passed through to `Avatar.store`.
## Passing custom headers when downloading from remote path
By default, when downloading files from remote path request headers are empty,
but if you wish to provide your own, you can override the `remote_file_headers/1`
function in your definition module. For example:
defmodule Avatar do
use Waffle.Definition
def remote_file_headers(%URI{host: "elixir-lang.org"}) do
credentials = Application.get_env(:my_app, :avatar_credentials)
token = Base.encode64(credentials[:username] <> ":" <> credentials[:password])
[{"Authorization", "Basic #{token}")}]
end
end
This code would authenticate request only for specific domain. Otherwise, it would send
empty request headers.
"""
defmacro __using__(_) do
quote do
@acl :private
@async true
def bucket, do: Application.fetch_env!(:waffle, :bucket)
def asset_host, do: Application.get_env(:waffle, :asset_host)
def filename(_, {file, _}), do: Path.basename(file.file_name, Path.extname(file.file_name))
def storage_dir_prefix, do: Application.get_env(:waffle, :storage_dir_prefix, "")
def storage_dir(_, _), do: Application.get_env(:waffle, :storage_dir, "uploads")
def validate(_), do: true
def default_url(version, _), do: default_url(version)
def default_url(_), do: nil
def __storage, do: Application.get_env(:waffle, :storage, Waffle.Storage.S3)
defoverridable storage_dir_prefix: 0,
storage_dir: 2,
filename: 2,
validate: 1,
default_url: 1,
default_url: 2,
__storage: 0,
bucket: 0,
asset_host: 0
@before_compile Waffle.Definition.Storage
end
end
defmacro __before_compile__(_env) do
quote do
def acl(_, _), do: @acl
def s3_object_headers(_, _), do: []
def async, do: @async
def remote_file_headers(_), do: []
end
end
end
| 36.202797 | 422 | 0.688043 |
08c33684c6b0b11a4ae053283b6b942bd163036b | 1,860 | ex | Elixir | lib/todo_app/handlers/base_handler.ex | Angarsk8/todoapp_cowboy_elixir | 38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd | [
"MIT"
] | 134 | 2017-03-28T14:47:37.000Z | 2021-11-25T10:40:15.000Z | lib/todo_app/handlers/base_handler.ex | Angarsk8/todoapp_cowboy_elixir | 38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd | [
"MIT"
] | 5 | 2017-03-30T05:56:55.000Z | 2018-01-17T09:22:51.000Z | lib/todo_app/handlers/base_handler.ex | Angarsk8/todoapp_cowboy_elixir | 38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd | [
"MIT"
] | 14 | 2017-03-28T17:04:31.000Z | 2021-08-07T07:09:21.000Z | defmodule TodoApp.BaseHandler do
defmacro __using__(_opts) do
quote do
alias TodoApp.Repo
import Ecto
import Ecto.Query
import TodoApp.Handler.Helpers
# Default REST Callbacks
def init(req, state) do
{:cowboy_rest, req, state}
end
def content_types_provided(req, state) do
{[{"application/json", :handle}], req, state}
end
def content_types_accepted(req, state) do
{[{"application/json", :handle}], req, state}
end
def options(req, state) do
handle(req, state)
end
def delete_resource(req, state) do
handle(req, state)
end
# Default REST Handlers
def handle(%{method: method} = req, state) do
req = set_headers(req, default_headers())
{decoded_body, req} = read_and_decode_body(req)
bindings = :cowboy_req.bindings(req)
params = Map.put(bindings, :body, decoded_body)
handler = handler_for(method)
apply(__MODULE__, handler, [req, state, params])
end
def options(req, state, _params) do
req = set_header(req, "Access-Control-Allow-Methods", "PUT,PATCH,DELETE")
{:ok, req, state}
end
def delete(req, state, _params) do
{false, req, state}
end
# Private Functions
defp handler_for("OPTIONS"), do: :options
defp handler_for("GET"), do: :index
defp handler_for("POST"), do: :create
defp handler_for("PUT"), do: :update
defp handler_for("PATCH"), do: :update
defp handler_for("DELETE"), do: :delete
defp default_headers do
%{"Access-Control-Allow-Origin" => "*",
"Access-Control-Allow-Headers" => "Content-Type,Authorization"}
end
# Overridable Functions
defoverridable [delete: 3]
end
end
end
| 25.479452 | 81 | 0.600538 |
08c34aab5fb01ccff2042e5b392abb3d93de9ddc | 3,203 | ex | Elixir | lib/mix/lib/mix/generator.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | 1 | 2021-05-20T13:08:37.000Z | 2021-05-20T13:08:37.000Z | lib/mix/lib/mix/generator.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/generator.ex | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Generator do
@moduledoc """
Conveniences for working with paths and generating content.
All of these functions are verbose, in the sense they log
the action to be performed via `Mix.shell/0`.
"""
@doc """
Creates a file with the given contents.
If the file already exists, asks for user confirmation.
## Options
* `:force` - forces installation without a shell prompt.
## Examples
iex> Mix.Generator.create_file ".gitignore", "_build\ndeps\n"
* creating .gitignore
:ok
"""
@spec create_file(Path.t(), iodata, keyword) :: any
def create_file(path, contents, opts \\ []) when is_binary(path) do
Mix.shell().info([:green, "* creating ", :reset, Path.relative_to_cwd(path)])
if opts[:force] || Mix.Utils.can_write?(path) do
File.mkdir_p!(Path.dirname(path))
File.write!(path, contents)
end
end
@doc """
Creates a directory if one does not exist yet.
This function does nothing if the given directory already exists; in this
case, it still logs the directory creation.
## Examples
iex> Mix.Generator.create_directory "path/to/dir"
* creating path/to/dir
:ok
"""
@spec create_directory(Path.t()) :: any
def create_directory(path) when is_binary(path) do
Mix.shell().info([:green, "* creating ", :reset, Path.relative_to_cwd(path)])
File.mkdir_p!(path)
end
@doc """
Embeds a template given by `contents` into the current module.
It will define a private function with the `name` followed by
`_template` that expects assigns as arguments.
This function must be invoked passing a keyword list.
Each key in the keyword list can be accessed in the
template using the `@` macro.
For more information, check `EEx.SmartEngine`.
## Examples
defmodule Mix.Tasks.MyTask do
require Mix.Generator
Mix.Generator.embed_template(:log, "Log: <%= @log %>")
end
"""
defmacro embed_template(name, contents) do
quote bind_quoted: binding() do
contents =
case contents do
[from_file: file] ->
@file file
File.read!(file)
c when is_binary(c) ->
@file {__ENV__.file, __ENV__.line + 1}
c
_ ->
raise ArgumentError, "expected string or from_file: file"
end
require EEx
source = "<% _ = assigns %>" <> contents
EEx.function_from_string(:defp, :"#{name}_template", source, [:assigns])
end
end
@doc """
Embeds a text given by `contents` into the current module.
It will define a private function with the `name` followed by
`_text` that expects no arguments.
## Examples
defmodule Mix.Tasks.MyTask do
require Mix.Generator
Mix.Generator.embed_text(:error, "There was an error!")
end
"""
defmacro embed_text(name, contents) do
quote bind_quoted: binding() do
contents =
case contents do
[from_file: f] -> File.read!(f)
c when is_binary(c) -> c
_ -> raise ArgumentError, "expected string or from_file: file"
end
defp unquote(:"#{name}_text")(), do: unquote(contents)
end
end
end
| 26.04065 | 81 | 0.637527 |
08c38307bd735942a393ca071e10ff3b5109149e | 1,808 | ex | Elixir | lib/pixel_font/table_source/otf_layout/chained_sequence_context_3.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | 17 | 2020-09-14T15:25:38.000Z | 2022-03-05T17:14:24.000Z | lib/pixel_font/table_source/otf_layout/chained_sequence_context_3.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | 1 | 2021-08-19T05:05:37.000Z | 2021-08-19T05:05:37.000Z | lib/pixel_font/table_source/otf_layout/chained_sequence_context_3.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | null | null | null | defmodule PixelFont.TableSource.OTFLayout.ChainedSequenceContext3 do
alias PixelFont.TableSource.OTFLayout.GlyphCoverage
alias PixelFont.TableSource.OTFLayout.Lookup
defstruct backtrack: [], input: [], lookahead: [], lookup_records: []
@type t :: %__MODULE__{
backtrack: [GlyphCoverage.t()],
input: [GlyphCoverage.t()],
lookahead: [GlyphCoverage.t()],
lookup_records: [{integer(), Lookup.id()}]
}
@spec compile(t(), keyword()) :: binary()
def compile(%__MODULE__{} = context, opts) do
lookup_indices = opts[:lookup_indices]
lookup_record_count = length(context.lookup_records)
sequences = [context.backtrack, context.input, context.lookahead]
context_length = sequences |> Enum.map(&length/1) |> Enum.sum()
offset_base = 10 + context_length * 2 + lookup_record_count * 4
{offsets, coverages} = GlyphCoverage.compile_coverage_records(sequences, offset_base)
compiled_lookup_records =
Enum.map(context.lookup_records, fn {glyph_pos, lookup_id} ->
<<glyph_pos::16, lookup_indices[lookup_id]::16>>
end)
IO.iodata_to_binary([
# format
<<3::16>>,
# {backtrack,input,lookahead}{GlyphCount,CoverageOffsets[]}
offsets,
# seqLookupCount
<<lookup_record_count::16>>,
# seqLookupRecords[]
compiled_lookup_records,
# Coverage tables
coverages
])
end
defimpl PixelFont.TableSource.GPOS.Subtable do
alias PixelFont.TableSource.OTFLayout.ChainedSequenceContext3
defdelegate compile(subtable, opts), to: ChainedSequenceContext3
end
defimpl PixelFont.TableSource.GSUB.Subtable do
alias PixelFont.TableSource.OTFLayout.ChainedSequenceContext3
defdelegate compile(subtable, opts), to: ChainedSequenceContext3
end
end
| 33.481481 | 89 | 0.700221 |
08c38317443d5b64852b077483543620255833b3 | 161 | ex | Elixir | lib/mix/tasks/jorel.relup.ex | G-Corp/jorel_mix | d3bea2e19a5b725bbc90532d74613e0fd5441461 | [
"Unlicense"
] | null | null | null | lib/mix/tasks/jorel.relup.ex | G-Corp/jorel_mix | d3bea2e19a5b725bbc90532d74613e0fd5441461 | [
"Unlicense"
] | 1 | 2019-02-13T14:28:48.000Z | 2019-02-13T17:02:49.000Z | lib/mix/tasks/jorel.relup.ex | G-Corp/jorel_mix | d3bea2e19a5b725bbc90532d74613e0fd5441461 | [
"Unlicense"
] | null | null | null | defmodule Mix.Tasks.Jorel.Relup do
use Mix.Task
@shortdoc "Create relup of release"
def run(argv) do
JorelMix.Utils.jorel(argv, ["relup"])
end
end
| 16.1 | 41 | 0.695652 |
08c396732863585c711bec2aec6d6a380c6c2a44 | 840 | ex | Elixir | lib/plausible/billing/enterprise_plan_admin.ex | plausible-insights/plausible | 88173342b9e969894879bfb2e8d203426f6a1b1c | [
"MIT"
] | 984 | 2019-09-02T11:36:41.000Z | 2020-06-08T06:25:48.000Z | lib/plausible/billing/enterprise_plan_admin.ex | plausible-insights/plausible | 88173342b9e969894879bfb2e8d203426f6a1b1c | [
"MIT"
] | 24 | 2019-09-10T09:53:17.000Z | 2020-06-08T07:35:26.000Z | lib/plausible/billing/enterprise_plan_admin.ex | plausible-insights/plausible | 88173342b9e969894879bfb2e8d203426f6a1b1c | [
"MIT"
] | 51 | 2019-09-03T10:48:10.000Z | 2020-06-07T00:23:34.000Z | defmodule Plausible.Billing.EnterprisePlanAdmin do
use Plausible.Repo
def search_fields(_schema) do
[
:paddle_plan_id,
user: [:name, :email]
]
end
def form_fields(_) do
[
user_id: nil,
paddle_plan_id: nil,
billing_interval: %{choices: [{"Yearly", "yearly"}, {"Monthly", "monthly"}]},
monthly_pageview_limit: nil,
hourly_api_request_limit: nil,
site_limit: nil
]
end
def custom_index_query(_conn, _schema, query) do
from(r in query, preload: :user)
end
def index(_) do
[
id: nil,
user_email: %{value: &get_user_email/1},
paddle_plan_id: nil,
billing_interval: nil,
monthly_pageview_limit: nil,
hourly_api_request_limit: nil,
site_limit: nil
]
end
defp get_user_email(plan), do: plan.user.email
end
| 21 | 83 | 0.635714 |
08c3f221b9a5202a10bc2d7f83052befbcf48f9a | 5,665 | exs | Elixir | mix.exs | data-twister/phoenix | 9c5de65b0ddf1e218084608a87ee233f3fda5bd8 | [
"MIT"
] | 7 | 2021-01-31T04:51:08.000Z | 2022-01-09T06:59:28.000Z | mix.exs | data-twister/phoenix | 9c5de65b0ddf1e218084608a87ee233f3fda5bd8 | [
"MIT"
] | null | null | null | mix.exs | data-twister/phoenix | 9c5de65b0ddf1e218084608a87ee233f3fda5bd8 | [
"MIT"
] | 2 | 2021-02-06T08:40:23.000Z | 2021-03-20T16:35:47.000Z | defmodule Phoenix.MixProject do
use Mix.Project
@version "1.6.0-dev"
# If the elixir requirement is updated, we need to make the installer
# use at least the minimum requirement used here. Although often the
# installer is ahead of Phoenix itself.
@elixir_requirement "~> 1.9"
def project do
[
app: :phoenix,
version: @version,
elixir: @elixir_requirement,
deps: deps(),
package: package(),
preferred_cli_env: [docs: :docs],
consolidate_protocols: Mix.env() != :test,
xref: [
exclude: [
{IEx, :started?, 0},
Ecto.Type,
:ranch,
:cowboy_req,
Plug.Cowboy.Conn,
Plug.Cowboy
]
],
elixirc_paths: elixirc_paths(Mix.env()),
name: "Phoenix",
docs: docs(),
aliases: aliases(),
source_url: "https://github.com/phoenixframework/phoenix",
homepage_url: "https://www.phoenixframework.org",
description: """
Productive. Reliable. Fast. A productive web framework that
does not compromise speed or maintainability.
"""
]
end
defp elixirc_paths(:docs), do: ["lib", "installer/lib"]
defp elixirc_paths(_), do: ["lib"]
def application do
[
mod: {Phoenix, []},
extra_applications: [:logger, :eex, :crypto, :public_key],
env: [
logger: true,
stacktrace_depth: nil,
filter_parameters: ["password"],
serve_endpoints: false,
gzippable_exts: ~w(.js .css .txt .text .html .json .svg .eot .ttf),
static_compressors: [Phoenix.Digester.Gzip]
]
]
end
defp deps do
[
{:plug, "~> 1.10"},
{:plug_crypto, "~> 1.1.2 or ~> 1.2"},
{:telemetry, "~> 0.4"},
{:phoenix_pubsub, "~> 2.0"},
# Optional deps
{:plug_cowboy, "~> 2.2", optional: true},
{:jason, "~> 1.0", optional: true},
{:phoenix_view, git: "https://github.com/phoenixframework/phoenix_view.git"},
{:phoenix_html, "~> 2.14.2 or ~> 3.0", optional: true},
# Docs dependencies (some for cross references)
{:ex_doc, "~> 0.22", only: :docs},
{:ecto, ">= 3.0.0", only: :docs},
{:gettext, "~> 0.15.0", only: :docs},
{:telemetry_poller, "~> 0.4", only: :docs},
{:telemetry_metrics, "~> 0.4", only: :docs},
# Test dependencies
{:phx_new, path: "./installer", only: :test},
{:websocket_client, git: "https://github.com/jeremyong/websocket_client.git", only: :test}
]
end
defp package do
[
maintainers: ["Chris McCord", "José Valim", "Gary Rennie", "Jason Stiebs"],
licenses: ["MIT"],
links: %{github: "https://github.com/phoenixframework/phoenix"},
files:
~w(assets/js lib priv CHANGELOG.md LICENSE.md mix.exs package.json README.md .formatter.exs)
]
end
defp docs do
[
source_ref: "v#{@version}",
main: "overview",
logo: "logo.png",
extra_section: "GUIDES",
assets: "guides/assets",
formatters: ["html", "epub"],
groups_for_modules: groups_for_modules(),
extras: extras(),
groups_for_extras: groups_for_extras()
]
end
defp extras do
[
"guides/introduction/overview.md",
"guides/introduction/installation.md",
"guides/introduction/up_and_running.md",
"guides/introduction/community.md",
"guides/directory_structure.md",
"guides/request_lifecycle.md",
"guides/plug.md",
"guides/routing.md",
"guides/controllers.md",
"guides/views.md",
"guides/ecto.md",
"guides/contexts.md",
"guides/mix_tasks.md",
"guides/telemetry.md",
"guides/authentication/mix_phx_gen_auth.md",
"guides/realtime/channels.md",
"guides/realtime/presence.md",
"guides/testing/testing.md",
"guides/testing/testing_contexts.md",
"guides/testing/testing_controllers.md",
"guides/testing/testing_channels.md",
"guides/deployment/deployment.md",
"guides/deployment/releases.md",
"guides/deployment/gigalixir.md",
"guides/deployment/heroku.md",
"guides/howto/custom_error_pages.md",
"guides/howto/using_ssl.md"
]
end
defp groups_for_extras do
[
Introduction: ~r/guides\/introduction\/.?/,
Guides: ~r/guides\/[^\/]+\.md/,
Authentication: ~r/guides\/authentication\/.?/,
"Real-time components": ~r/guides\/realtime\/.?/,
Testing: ~r/guides\/testing\/.?/,
Deployment: ~r/guides\/deployment\/.?/,
"How-to's": ~r/guides\/howto\/.?/
]
end
defp groups_for_modules do
# Ungrouped Modules:
#
# Phoenix
# Phoenix.Channel
# Phoenix.Controller
# Phoenix.Endpoint
# Phoenix.Naming
# Phoenix.Logger
# Phoenix.Param
# Phoenix.Presence
# Phoenix.Router
# Phoenix.Token
# Phoenix.View
[
Testing: [
Phoenix.ChannelTest,
Phoenix.ConnTest
],
"Adapters and Plugs": [
Phoenix.CodeReloader,
Phoenix.Endpoint.Cowboy2Adapter
],
"Socket and Transport": [
Phoenix.Socket,
Phoenix.Socket.Broadcast,
Phoenix.Socket.Message,
Phoenix.Socket.Reply,
Phoenix.Socket.Serializer,
Phoenix.Socket.Transport
],
Templating: [
Phoenix.Template,
Phoenix.Template.EExEngine,
Phoenix.Template.Engine,
Phoenix.Template.ExsEngine
]
]
end
defp aliases do
[
docs: ["docs", &generate_js_docs/1]
]
end
def generate_js_docs(_) do
Mix.Task.run("app.start")
System.cmd("npm", ["run", "docs"], cd: "assets")
end
end
| 27.36715 | 100 | 0.589938 |
08c3f47055053b5256771965103729f394956caf | 2,588 | ex | Elixir | lib/utils/http.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | 5 | 2020-12-10T07:24:18.000Z | 2021-12-15T08:26:05.000Z | lib/utils/http.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | null | null | null | lib/utils/http.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | 2 | 2020-12-12T17:06:13.000Z | 2021-04-09T02:12:31.000Z | defmodule Http do
@moduledoc """
the encapsulation of http
"""
require Logger
@retries 5
@doc """
+----------------------+
| json_rpc_constructer |
+----------------------+
"""
def json_rpc(method, id)
when is_integer(id) do
%{method: method, jsonrpc: "2.0", id: id}
end
def json_rpc(method, params) do
%{method: method, params: params, jsonrpc: "2.0", id: 1}
end
## === util get ===
@spec get(any) :: {:error, <<_::64, _::_*8>>} | {:ok, any}
def get(url) do
do_get(url, @retries)
end
defp do_get(_url, retries) when retries == 0 do
{:error, "retires #{@retries} times and not success"}
end
defp do_get(url, retries) do
url
|> HTTPoison.get([])
|> handle_response()
|> case do
{:ok, body} ->
{:ok, body}
{:error, _} ->
Process.sleep(500)
do_get(url, retries - 1)
end
end
## === util post ===
def post(url, body) do
do_post(url, body, @retries)
end
def post(url, body, :urlencoded) do
do_post(url, body, @retries, :urlencoded)
end
defp do_post(_url, _body, retires) when retires == 0 do
{:error, "retires #{@retries} times and not success"}
end
defp do_post(url, body, retries) do
url
|> HTTPoison.post(
Poison.encode!(body),
[{"Content-Type", "application/json"}]
)
|> handle_response()
|> case do
{:ok, body} ->
{:ok, body}
{:error, _} ->
Process.sleep(500)
do_post(url, body, retries - 1)
end
end
defp do_post(_url, _body, retires, :urlencoded) when retires == 0 do
{:error, "retires #{@retries} times and not success"}
end
defp do_post(url, body, retries, :urlencoded) do
url
|> HTTPoison.post(
body,
[{"Content-Type", "application/x-www-form-urlencoded"}]
)
|> handle_response()
|> case do
{:ok, body} ->
{:ok, body}
{:error, _} ->
Process.sleep(500)
do_post(url, body, retries - 1)
end
end
# normal
defp handle_response({:ok, %HTTPoison.Response{status_code: status_code, body: body}})
when status_code in 200..299 do
case Poison.decode(body) do
{:ok, json_body} ->
{:ok, json_body}
{:error, _} ->
{:ok, body}
end
end
# 404 or sth else
defp handle_response({:ok, %HTTPoison.Response{status_code: status_code, body: _}}) do
Logger.error("Reason: #{status_code} ")
{:error, :network_error}
end
defp handle_response(error) do
Logger.error("Reason: other_error")
error
end
end
| 21.38843 | 88 | 0.560665 |
08c3fe46c3d26f890ed7edfec5abf6354cfe8edd | 4,272 | ex | Elixir | lib/stripe/subscriptions/subscription_item.ex | erhlee-bird/stripity_stripe | 8c4c5712f391bf76e0a168125882c85048d3192f | [
"BSD-3-Clause"
] | 555 | 2016-11-29T05:02:27.000Z | 2022-03-30T00:47:59.000Z | lib/stripe/subscriptions/subscription_item.ex | erhlee-bird/stripity_stripe | 8c4c5712f391bf76e0a168125882c85048d3192f | [
"BSD-3-Clause"
] | 532 | 2016-11-28T18:22:25.000Z | 2022-03-30T17:04:32.000Z | lib/stripe/subscriptions/subscription_item.ex | erhlee-bird/stripity_stripe | 8c4c5712f391bf76e0a168125882c85048d3192f | [
"BSD-3-Clause"
] | 296 | 2016-12-05T14:04:09.000Z | 2022-03-28T20:39:37.000Z | defmodule Stripe.SubscriptionItem do
@moduledoc """
Work with Stripe subscription item objects.
Stripe API reference: https://stripe.com/docs/api#subscription_items
"""
use Stripe.Entity
import Stripe.Request
@type t :: %__MODULE__{
id: Stripe.id(),
object: String.t(),
billing_thresholds: Stripe.Types.collection_method_thresholds() | nil,
created: Stripe.timestamp(),
deleted: boolean | nil,
metadata: Stripe.Types.metadata(),
plan: Stripe.Plan.t(),
price: Stripe.Price.t(),
quantity: non_neg_integer,
subscription: Stripe.id() | Stripe.Subscription.t() | nil,
tax_rates: list(Stripe.TaxRate.t())
}
defstruct [
:id,
:object,
:billing_thresholds,
:created,
:deleted,
:metadata,
:plan,
:price,
:quantity,
:subscription,
:tax_rates
]
@plural_endpoint "subscription_items"
@doc """
Create a subscription item.
"""
@spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
:subscription => Stripe.id() | Stripe.Subscription.t(),
optional(:plan) => Stripe.id() | Stripe.Plan.t(),
optional(:price) => Stripe.id() | Stripe.Price.t(),
optional(:metadata) => Stripe.Types.metadata(),
optional(:prorate) => boolean,
optional(:proration_date) => Stripe.timestamp(),
optional(:quantity) => non_neg_integer,
optional(:tax_rates) => list(String.t())
}
def create(%{subscription: _} = params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_params(params)
|> put_method(:post)
|> cast_to_id([:plan, :price, :subscription])
|> make_request()
end
@doc """
Retrieve a subscription.
"""
@spec retrieve(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
def retrieve(id, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:get)
|> make_request()
end
@doc """
Update a subscription item.
Takes the `id` and a map of changes.
"""
@spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
optional(:metadata) => Stripe.Types.metadata(),
optional(:plan) => Stripe.id() | Stripe.Plan.t(),
optional(:price) => Stripe.id() | Stripe.Price.t(),
optional(:prorate) => boolean,
optional(:proration_date) => Stripe.timestamp(),
optional(:quantity) => non_neg_integer,
optional(:tax_rates) => list(String.t())
}
def update(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:post)
|> put_params(params)
|> cast_to_id([:plan, :price])
|> make_request()
end
@doc """
Delete a subscription.
Takes the `id` and an optional map of `params`.
"""
@spec delete(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params: %{
optional(:clear_usage) => boolean,
optional(:prorate) => boolean,
optional(:proration_date) => Stripe.timestamp()
}
def delete(id, params \\ %{}, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:delete)
|> put_params(params)
|> make_request()
end
@doc """
List all subscriptions.
"""
@spec list(Stripe.id(), params, Stripe.options()) ::
{:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()}
when params: %{
optional(:ending_before) => t | Stripe.id(),
optional(:limit) => 1..100,
optional(:starting_after) => t | Stripe.id()
}
def list(id, params \\ %{}, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "?subscription=" <> id)
|> put_method(:get)
|> put_params(params)
|> cast_to_id([:ending_before, :starting_after])
|> make_request()
end
end
| 31.182482 | 98 | 0.560627 |
08c42311283e693a10b905afb23fef567918ce01 | 444 | exs | Elixir | apps/customer/priv/repo/migrations/20161128040455_create_job_tech_keyword.exs | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 102 | 2017-05-21T18:24:04.000Z | 2022-03-10T12:53:20.000Z | apps/customer/priv/repo/migrations/20161128040455_create_job_tech_keyword.exs | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 2 | 2017-05-21T01:53:30.000Z | 2017-12-01T00:27:06.000Z | apps/customer/priv/repo/migrations/20161128040455_create_job_tech_keyword.exs | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 18 | 2017-05-22T09:51:36.000Z | 2021-09-24T00:57:01.000Z | defmodule Customer.Repo.Migrations.CreateJobTechKeyword do
use Ecto.Migration
def change do
create table(:job_tech_keywords) do
add :tech_keyword_id, references(:tech_keywords, on_delete: :delete_all)
add :job_id, references(:jobs, on_delete: :delete_all)
timestamps()
end
create unique_index(:job_tech_keywords, [:tech_keyword_id, :job_id], name: :job_tech_keywords_tech_keyword_id_job_id_index)
end
end
| 29.6 | 127 | 0.759009 |
08c455af6a0c6e1c6ea469636bb7667a6673dad7 | 990 | ex | Elixir | lib/nookal/practitioner.ex | theo-agilelab/nookal-elixir | 09db7cc48c48ed1e714fb74c5c38c9a21e7e189a | [
"MIT"
] | 1 | 2020-06-11T07:57:06.000Z | 2020-06-11T07:57:06.000Z | lib/nookal/practitioner.ex | theo-agilelab/nookal-elixir | 09db7cc48c48ed1e714fb74c5c38c9a21e7e189a | [
"MIT"
] | null | null | null | lib/nookal/practitioner.ex | theo-agilelab/nookal-elixir | 09db7cc48c48ed1e714fb74c5c38c9a21e7e189a | [
"MIT"
] | 1 | 2019-09-05T08:30:48.000Z | 2019-09-05T08:30:48.000Z | defmodule Nookal.Practitioner do
import Nookal.Utils
@type t() :: %__MODULE__{
id: integer(),
first_name: String.t(),
last_name: String.t(),
speciality: String.t(),
title: String.t(),
email: String.t(),
location_ids: list(integer())
}
defstruct [:id, :first_name, :last_name, :speciality, :title, :email, :location_ids]
@mapping [
{:id, "ID", :integer},
{:first_name, "FirstName", :string},
{:last_name, "LastName", :string},
{:email, "Email", :string},
{:speciality, "Speciality", :string},
{:title, "Title", :string},
{:location_ids, "locations", {:list, :integer}}
]
def new(payload) when is_list(payload) do
with {:error, reason} <- all_or_none_map(payload, &new/1) do
{:error, {:malformed_payload, "could not map practitioners from payload" <> reason}}
end
end
def new(payload) do
extract_fields(@mapping, payload, %__MODULE__{})
end
end
| 27.5 | 90 | 0.594949 |
08c4b454fcead307841942ae610c8d4e790ca7cb | 2,350 | ex | Elixir | lib/sacastats_web.ex | Bentheburrito/sacastats | 4ffcc165b67f03830f4fbf3516ab7ca7a90b0950 | [
"MIT"
] | null | null | null | lib/sacastats_web.ex | Bentheburrito/sacastats | 4ffcc165b67f03830f4fbf3516ab7ca7a90b0950 | [
"MIT"
] | 38 | 2021-07-09T06:13:30.000Z | 2022-03-30T20:22:43.000Z | lib/sacastats_web.ex | Bentheburrito/sacastats | 4ffcc165b67f03830f4fbf3516ab7ca7a90b0950 | [
"MIT"
] | null | null | null | defmodule SacaStatsWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, views, channels and so on.
This can be used in your application as:
use SacaStatsWeb, :controller
use SacaStatsWeb, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define any helper function in modules
and import those modules here.
"""
def controller do
quote do
use Phoenix.Controller, namespace: SacaStatsWeb
import Plug.Conn
import SacaStatsWeb.Gettext
alias SacaStatsWeb.Router.Helpers, as: Routes
end
end
def view do
quote do
use Phoenix.View,
root: "lib/sacastats_web/templates",
namespace: SacaStatsWeb
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]
# Include shared imports and aliases for views
unquote(view_helpers())
end
end
def live_view do
quote do
use Phoenix.LiveView,
layout: {SacaStatsWeb.LayoutView, "live.html"}
unquote(view_helpers())
end
end
def live_component do
quote do
use Phoenix.LiveComponent
unquote(view_helpers())
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
import Phoenix.LiveView.Router
end
end
def channel do
quote do
use Phoenix.Channel
import SacaStatsWeb.Gettext
end
end
defp view_helpers do
quote do
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
# Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc)
import Phoenix.LiveView.Helpers
# Import basic rendering functionality (render, render_layout, etc)
import Phoenix.View
import SacaStatsWeb.ErrorHelpers
import SacaStatsWeb.Gettext
alias SacaStatsWeb.Router.Helpers, as: Routes
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
| 22.815534 | 81 | 0.683404 |
08c4b6a186ed74ee0b19d90a55c0564f3afe0496 | 71 | ex | Elixir | lib/sanbase_web/views/sheets_template_view.ex | santiment/sanbase2 | 9ef6e2dd1e377744a6d2bba570ea6bd477a1db31 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase_web/views/sheets_template_view.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase_web/views/sheets_template_view.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.SheetsTemplateView do
use SanbaseWeb, :view
end
| 17.75 | 42 | 0.830986 |
08c4d9cbcd5059def1d5251b614dbd66dd2f14c9 | 12,881 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/node_types.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/compute/lib/google_api/compute/v1/api/node_types.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/node_types.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Api.NodeTypes do
@moduledoc """
API calls for all endpoints tagged `NodeTypes`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Retrieves an aggregated list of node types.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.NodeTypeAggregatedList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_node_types_aggregated_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.NodeTypeAggregatedList.t()} | {:error, Tesla.Env.t()}
def compute_node_types_aggregated_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/aggregated/nodeTypes", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.NodeTypeAggregatedList{}])
end
@doc """
Returns the specified node type. Gets a list of available node types by making a list() request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - The name of the zone for this request.
* `node_type` (*type:* `String.t`) - Name of the node type to return.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.NodeType{}}` on success
* `{:error, info}` on failure
"""
@spec compute_node_types_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.NodeType.t()} | {:error, Tesla.Env.t()}
def compute_node_types_get(
connection,
project,
zone,
node_type,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/nodeTypes/{nodeType}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"nodeType" => URI.encode(node_type, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.NodeType{}])
end
@doc """
Retrieves a list of node types available to the specified project.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - The name of the zone for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.NodeTypeList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_node_types_list(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.NodeTypeList.t()} | {:error, Tesla.Env.t()}
def compute_node_types_list(connection, project, zone, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/zones/{zone}/nodeTypes", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.NodeTypeList{}])
end
end
| 57.248889 | 414 | 0.675258 |
08c4de22aed28a227aed51a1038a9fb1554b13da | 884 | ex | Elixir | clients/workflows/lib/google_api/workflows/v1/metadata.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/workflows/lib/google_api/workflows/v1/metadata.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/workflows/lib/google_api/workflows/v1/metadata.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Workflows.V1 do
@moduledoc """
API client metadata for GoogleApi.Workflows.V1.
"""
@discovery_revision "20220406"
def discovery_revision(), do: @discovery_revision
end
| 32.740741 | 74 | 0.75905 |
08c4e3d18d758c8346c4e6d98a74108d59dd3611 | 8,138 | ex | Elixir | clients/cloud_billing/lib/google_api/cloud_billing/v1/api/projects.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/cloud_billing/lib/google_api/cloud_billing/v1/api/projects.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/cloud_billing/lib/google_api/cloud_billing/v1/api/projects.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.CloudBilling.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.CloudBilling.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Gets the billing information for a project. The current authenticated user must have [permission to view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).
## Parameters
- connection (GoogleApi.CloudBilling.V1.Connection): Connection to server
- name (String.t): The resource name of the project for which billing information is retrieved. For example, `projects/tokyo-rain-123`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :access_token (String.t): OAuth access token.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :pp (boolean()): Pretty-print response.
- :bearer_token (String.t): OAuth bearer token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
## Returns
{:ok, %GoogleApi.CloudBilling.V1.Model.ProjectBillingInfo{}} on success
{:error, info} on failure
"""
@spec cloudbilling_projects_get_billing_info(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.CloudBilling.V1.Model.ProjectBillingInfo.t()} | {:error, Tesla.Env.t()}
def cloudbilling_projects_get_billing_info(connection, name, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:"$.xgafv" => :query,
:alt => :query,
:key => :query,
:access_token => :query,
:quotaUser => :query,
:pp => :query,
:bearer_token => :query,
:oauth_token => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/billingInfo", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudBilling.V1.Model.ProjectBillingInfo{})
end
@doc """
Sets or updates the billing account associated with a project. You specify the new billing account by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing account. Associating a project with an open billing account enables billing on the project and allows charges for resource usage. If the project already had a billing account, this method changes the billing account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the transaction history of the GCP Console might be billed to the new billing account, even if the charge occurred before the new billing account was assigned to the project. The current authenticated user must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ) and the [billing account](https://cloud.google.com/billing/docs/how-to/billing-access). You can disable billing on the project by setting the `billing_account_name` field to empty. This action disassociates the current billing account from the project. Any billable activity of your in-use services will stop, and your application could stop functioning as expected. Any unbilled charges to date will be billed to the previously associated account. The current authenticated user must be either an owner of the project or an owner of the billing account for the project. Note that associating a project with a *closed* billing account will have much the same effect as disabling billing on the project: any paid resources used by the project will be shut down. Thus, unless you wish to disable billing, you should always call this method with the name of an *open* billing account.
## Parameters
- connection (GoogleApi.CloudBilling.V1.Connection): Connection to server
- name (String.t): The resource name of the project associated with the billing information that you want to update. For example, `projects/tokyo-rain-123`.
- opts (KeywordList): [optional] Optional parameters
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :callback (String.t): JSONP
- :$.xgafv (String.t): V1 error format.
- :alt (String.t): Data format for response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :access_token (String.t): OAuth access token.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :pp (boolean()): Pretty-print response.
- :bearer_token (String.t): OAuth bearer token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :body (ProjectBillingInfo):
## Returns
{:ok, %GoogleApi.CloudBilling.V1.Model.ProjectBillingInfo{}} on success
{:error, info} on failure
"""
@spec cloudbilling_projects_update_billing_info(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.CloudBilling.V1.Model.ProjectBillingInfo.t()} | {:error, Tesla.Env.t()}
def cloudbilling_projects_update_billing_info(connection, name, opts \\ []) do
optional_params = %{
:upload_protocol => :query,
:prettyPrint => :query,
:fields => :query,
:uploadType => :query,
:callback => :query,
:"$.xgafv" => :query,
:alt => :query,
:key => :query,
:access_token => :query,
:quotaUser => :query,
:pp => :query,
:bearer_token => :query,
:oauth_token => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/v1/{+name}/billingInfo", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.CloudBilling.V1.Model.ProjectBillingInfo{})
end
end
| 55.360544 | 1,762 | 0.707668 |
08c4fc49711dd7a6631016b6a467c975dc2a9cb6 | 6,014 | exs | Elixir | .credo.exs | markevich/co2_offset | 98a799d3f30d21b595c9e083d9ee43bb96a4c68c | [
"Apache-2.0"
] | 15 | 2018-12-26T10:31:16.000Z | 2020-12-01T09:27:01.000Z | .credo.exs | markevich/co2_offset | 98a799d3f30d21b595c9e083d9ee43bb96a4c68c | [
"Apache-2.0"
] | 267 | 2018-12-26T07:46:17.000Z | 2020-04-04T17:05:47.000Z | .credo.exs | markevich/co2_offset | 98a799d3f30d21b595c9e083d9ee43bb96a4c68c | [
"Apache-2.0"
] | 1 | 2019-07-12T13:53:25.000Z | 2019-07-12T13:53:25.000Z | # This file contains the configuration for Credo and you are probably reading
# this after creating it with `mix credo.gen.config`.
#
# If you find anything wrong or unclear in this file, please report an
# issue on GitHub: https://github.com/rrrene/credo/issues
#
%{
#
# You can have as many configs as you like in the `configs:` field.
configs: [
%{
#
# Run any exec using `mix credo -C <name>`. If no exec name is given
# "default" is used.
#
name: "default",
#
# These are the files included in the analysis:
files: %{
#
# You can give explicit globs or simply directories.
# In the latter case `**/*.{ex,exs}` will be used.
#
included: ["lib/", "src/", "test/", "web/", "apps/"],
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
},
#
# If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis.
#
requires: [],
#
# If you want to enforce a style guide and need a more traditional linting
# experience, you can change `strict` to `true` below:
#
strict: false,
#
# If you want to use uncolored output by default, you can change `color`
# to `false` below:
#
color: true,
#
# You can customize the parameters of any check by adding a second element
# to the tuple.
#
# To disable a check put `false` as second element:
#
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: [
#
## Consistency Checks
#
{Credo.Check.Consistency.ExceptionNames, []},
{Credo.Check.Consistency.LineEndings, []},
{Credo.Check.Consistency.ParameterPatternMatching, []},
{Credo.Check.Consistency.SpaceAroundOperators, []},
{Credo.Check.Consistency.SpaceInParentheses, []},
{Credo.Check.Consistency.TabsOrSpaces, []},
#
## Design Checks
#
# You can customize the priority of any check
# Priority values are: `low, normal, high, higher`
#
{Credo.Check.Design.AliasUsage,
[priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]},
# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
#
{Credo.Check.Design.TagTODO, false},
{Credo.Check.Design.TagFIXME, []},
#
## Readability Checks
#
{Credo.Check.Readability.AliasOrder, []},
{Credo.Check.Readability.FunctionNames, []},
{Credo.Check.Readability.LargeNumbers, []},
{Credo.Check.Readability.MaxLineLength, [max_length: 120]},
{Credo.Check.Readability.ModuleAttributeNames, []},
{Credo.Check.Readability.ModuleDoc, false},
{Credo.Check.Readability.ModuleNames, []},
{Credo.Check.Readability.ParenthesesInCondition, []},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
{Credo.Check.Readability.PredicateFunctionNames, []},
{Credo.Check.Readability.PreferImplicitTry, []},
{Credo.Check.Readability.RedundantBlankLines, []},
{Credo.Check.Readability.Semicolons, []},
{Credo.Check.Readability.SpaceAfterCommas, []},
{Credo.Check.Readability.StringSigils, []},
{Credo.Check.Readability.TrailingBlankLine, []},
{Credo.Check.Readability.TrailingWhiteSpace, []},
{Credo.Check.Readability.VariableNames, []},
#
## Refactoring Opportunities
#
{Credo.Check.Refactor.CondStatements, []},
{Credo.Check.Refactor.CyclomaticComplexity, []},
{Credo.Check.Refactor.FunctionArity, []},
{Credo.Check.Refactor.LongQuoteBlocks, []},
{Credo.Check.Refactor.MapInto, false},
{Credo.Check.Refactor.MatchInCondition, []},
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
{Credo.Check.Refactor.NegatedConditionsWithElse, []},
{Credo.Check.Refactor.Nesting, []},
{Credo.Check.Refactor.PipeChainStart,
[excluded_argument_types: [:atom, :binary, :fn, :keyword], excluded_functions: []]},
{Credo.Check.Refactor.UnlessWithElse, []},
#
## Warnings
#
{Credo.Check.Warning.BoolOperationOnSameValues, []},
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
{Credo.Check.Warning.IExPry, []},
{Credo.Check.Warning.IoInspect, []},
{Credo.Check.Warning.LazyLogging, false},
{Credo.Check.Warning.OperationOnSameValues, []},
{Credo.Check.Warning.OperationWithConstantResult, []},
{Credo.Check.Warning.RaiseInsideRescue, []},
{Credo.Check.Warning.UnusedEnumOperation, []},
{Credo.Check.Warning.UnusedFileOperation, []},
{Credo.Check.Warning.UnusedKeywordOperation, []},
{Credo.Check.Warning.UnusedListOperation, []},
{Credo.Check.Warning.UnusedPathOperation, []},
{Credo.Check.Warning.UnusedRegexOperation, []},
{Credo.Check.Warning.UnusedStringOperation, []},
{Credo.Check.Warning.UnusedTupleOperation, []},
#
# Controversial and experimental checks (opt-in, just remove `, false`)
#
{Credo.Check.Consistency.MultiAliasImportRequireUse, false},
{Credo.Check.Design.DuplicatedCode},
{Credo.Check.Readability.MultiAlias, false},
{Credo.Check.Readability.Specs, false},
{Credo.Check.Refactor.ABCSize},
{Credo.Check.Refactor.AppendSingleItem},
{Credo.Check.Refactor.DoubleBooleanNegation},
{Credo.Check.Refactor.VariableRebinding},
{Credo.Check.Warning.MapGetUnsafePass},
{Credo.Check.Warning.UnsafeToAtom}
#
# Custom checks can be created using `mix credo.gen.check`.
#
]
}
]
}
| 38.8 | 93 | 0.616395 |
08c4ffd7e8e9e2610e9829ada60e71645828de22 | 4,396 | ex | Elixir | clients/dns/lib/google_api/dns/v1/api/resource_record_sets.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/api/resource_record_sets.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/api/resource_record_sets.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.DNS.V1.Api.ResourceRecordSets do
@moduledoc """
API calls for all endpoints tagged `ResourceRecordSets`.
"""
alias GoogleApi.DNS.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Enumerate ResourceRecordSets that have been created but not yet deleted.
## Parameters
* `connection` (*type:* `GoogleApi.DNS.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Identifies the project addressed by this request.
* `managed_zone` (*type:* `String.t`) - Identifies the managed zone addressed by this request. Can be the managed zone name or id.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:maxResults` (*type:* `integer()`) - Optional. Maximum number of results to be returned. If unspecified, the server will decide how many results to return.
* `:name` (*type:* `String.t`) - Restricts the list to return only records with this fully qualified domain name.
* `:pageToken` (*type:* `String.t`) - Optional. A tag returned by a previous list request that was truncated. Use this parameter to continue a previous list request.
* `:type` (*type:* `String.t`) - Restricts the list to return only records of this type. If present, the "name" parameter must also be present.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dns_resource_record_sets_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def dns_resource_record_sets_list(
connection,
project,
managed_zone,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:maxResults => :query,
:name => :query,
:pageToken => :query,
:type => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/managedZones/{managedZone}/rrsets", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"managedZone" => URI.encode(managed_zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse{}])
end
end
| 43.524752 | 187 | 0.654459 |
08c505926dead8eb736ba4de0879e79f761dd696 | 204 | ex | Elixir | lib/phone/za.ex | yuriy-pavlov-castle-co/phone | c488b8f73a55cadbd15cdd77998af4ac2721fcfc | [
"Apache-2.0"
] | null | null | null | lib/phone/za.ex | yuriy-pavlov-castle-co/phone | c488b8f73a55cadbd15cdd77998af4ac2721fcfc | [
"Apache-2.0"
] | null | null | null | lib/phone/za.ex | yuriy-pavlov-castle-co/phone | c488b8f73a55cadbd15cdd77998af4ac2721fcfc | [
"Apache-2.0"
] | 1 | 2019-05-30T15:05:51.000Z | 2019-05-30T15:05:51.000Z | defmodule Phone.ZA do
@moduledoc false
use Helper.Country
def regex, do: ~r/^(27)()(.{10})/
def country, do: "South Africa"
def a2, do: "ZA"
def a3, do: "ZAF"
matcher(:regex, ["27"])
end
| 15.692308 | 35 | 0.598039 |
08c5263012f65f6432603b887228dbd3f8bccd0d | 2,093 | exs | Elixir | test/grizzly_test.exs | ryanwinchester/grizzly | 86002e01debe63c18f85270ddc948e3875f25043 | [
"Apache-2.0"
] | null | null | null | test/grizzly_test.exs | ryanwinchester/grizzly | 86002e01debe63c18f85270ddc948e3875f25043 | [
"Apache-2.0"
] | null | null | null | test/grizzly_test.exs | ryanwinchester/grizzly | 86002e01debe63c18f85270ddc948e3875f25043 | [
"Apache-2.0"
] | null | null | null | defmodule Grizzly.Test do
use ExUnit.Case
alias Grizzly.Conn
alias Grizzly.CommandClass.SwitchBinary.Set, as: SwitchBinarySet
alias Grizzly.CommandClass.SwitchBinary.Get, as: SwitchBinaryGet
alias Grizzly.CommandClass.NetworkManagementProxy.NodeListGet
alias Grizzly.CommandClass.Battery.Get, as: BatteryGet
alias Grizzly.CommandClass.ZipNd.InvNodeSolicitation
alias Grizzly.CommandClass.ManufacturerSpecific.Get, as: ManufacturerSpecificGet
alias Grizzly.Network.State, as: NetworkState
alias Grizzly.Command.EncodeError
setup do
config = Grizzly.config()
%Conn{} = conn = Conn.open(config)
:ok = NetworkState.set(:idle)
{:ok, %{conn: conn}}
end
describe "sending different types of command classes" do
test "send application command class", %{conn: conn} do
:ok = Grizzly.send_command(conn, SwitchBinarySet, seq_number: 0x08, value: :on)
end
test "send application command class that waits for a report", %{conn: conn} do
{:ok, :on} = Grizzly.send_command(conn, SwitchBinaryGet, seq_number: 0x01)
end
test "send network command class", %{conn: conn} do
{:ok, [1]} = Grizzly.send_command(conn, NodeListGet, seq_number: 0x01)
end
test "send management command class", %{conn: conn} do
{:ok, 90} = Grizzly.send_command(conn, BatteryGet, seq_number: 0x01)
end
test "send raw command class", %{conn: conn} do
{:ok, %{home_id: 3_476_769_508, ip_address: {64768, 48059, 0, 0, 0, 0, 0, 6}, node_id: 6}}
Grizzly.send_command(conn, InvNodeSolicitation, node_id: 0x06)
end
test "send the manufacturer specific command", %{conn: conn} do
assert {:ok, %{manufacturer_id: 335, product_id: 21558, product_type_id: 21570}} ==
Grizzly.send_command(conn, ManufacturerSpecificGet, seq_number: 0x01)
end
end
describe "sending bad stuff to grizzly" do
test "send values to switch binary set", %{conn: conn} do
{:error, %EncodeError{}} =
Grizzly.send_command(conn, SwitchBinarySet, seq_number: 0x08, value: :grizzly)
end
end
end
| 37.375 | 96 | 0.705208 |
08c53fd4f8c68d733b2ac0ad2d5ba0bc6be86441 | 872 | ex | Elixir | clients/run/lib/google_api/run/v1/metadata.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/metadata.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/metadata.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Run.V1 do
@moduledoc """
API client metadata for GoogleApi.Run.V1.
"""
@discovery_revision "20211022"
def discovery_revision(), do: @discovery_revision
end
| 32.296296 | 74 | 0.755734 |
08c55beda683e9d946e0b5cf48267a5e34d901f4 | 660 | ex | Elixir | lib/ready/redis.ex | ckampfe/ready | 33cb1b5f48da1a7950263160588cdecdfc664c91 | [
"MIT"
] | null | null | null | lib/ready/redis.ex | ckampfe/ready | 33cb1b5f48da1a7950263160588cdecdfc664c91 | [
"MIT"
] | null | null | null | lib/ready/redis.ex | ckampfe/ready | 33cb1b5f48da1a7950263160588cdecdfc664c91 | [
"MIT"
] | null | null | null | defmodule Ready.Redis do
alias Ready.EtsStore
require Logger
@crlf "\r\n"
@ok "+OK" <> @crlf
@null "$-1" <> @crlf
def op(["SET", key, value]) do
try do
EtsStore.set(key, value)
@ok
rescue
e ->
Logger.error(e)
@null
end
end
def op(["GET", key]) do
case EtsStore.get(key) do
[{_k, v}] ->
["$", to_string(byte_size(v)), @crlf, v, @crlf]
_ ->
@null
end
end
def op(["PING"]) do
["+PONG", @crlf]
end
def op(["PING", message]) do
message <> @crlf
end
# redis-cli sends this when it starts
def op(["COMMAND"]) do
"*0" <> @crlf
end
end
| 15.348837 | 55 | 0.501515 |
08c56f646b227b94b95edd66b03a0fd8000d72e3 | 830 | exs | Elixir | exercises/list-ops/list_ops.exs | jerith/elixir | 9a3f2a2fbee26a7b6a6b3ad74a9e6d1ff2495ed4 | [
"Apache-2.0"
] | null | null | null | exercises/list-ops/list_ops.exs | jerith/elixir | 9a3f2a2fbee26a7b6a6b3ad74a9e6d1ff2495ed4 | [
"Apache-2.0"
] | null | null | null | exercises/list-ops/list_ops.exs | jerith/elixir | 9a3f2a2fbee26a7b6a6b3ad74a9e6d1ff2495ed4 | [
"Apache-2.0"
] | 1 | 2018-07-19T23:43:56.000Z | 2018-07-19T23:43:56.000Z | defmodule ListOps do
# Please don't use any external modules (especially List) in your
# implementation. The point of this exercise is to create these basic functions
# yourself.
#
# Note that `++` is a function from an external module (Kernel, which is
# automatically imported) and so shouldn't be used either.
@spec count(list) :: non_neg_integer
def count(l) do
end
@spec reverse(list) :: list
def reverse(l) do
end
@spec map(list, (any -> any)) :: list
def map(l, f) do
end
@spec filter(list, (any -> as_boolean(term))) :: list
def filter(l, f) do
end
@type acc :: any
@spec reduce(list, acc, (any, acc -> acc)) :: acc
def reduce(l, acc, f) do
end
@spec append(list, list) :: list
def append(a, b) do
end
@spec concat([[any]]) :: [any]
def concat(ll) do
end
end
| 21.842105 | 81 | 0.642169 |
08c57851fecfbc9ec0a756fa20a1acc7653eb32f | 1,141 | exs | Elixir | sequence_supervisor/config/config.exs | karlosmid/book_programming_elixir_12 | 53769b35728a82eddde3a21d4cbd45c1c21596a4 | [
"MIT"
] | null | null | null | sequence_supervisor/config/config.exs | karlosmid/book_programming_elixir_12 | 53769b35728a82eddde3a21d4cbd45c1c21596a4 | [
"MIT"
] | null | null | null | sequence_supervisor/config/config.exs | karlosmid/book_programming_elixir_12 | 53769b35728a82eddde3a21d4cbd45c1c21596a4 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :sequence_supervisor, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:sequence_supervisor, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.806452 | 73 | 0.756354 |
08c57ab6ae63279a42f3530675ce1a13fa46c2b9 | 198 | exs | Elixir | priv/repo/migrations/20180725182954_add_newlines_to_filter_name_enum.exs | CyberFlameGO/bolt | 225e6276983bec646e7f13519df066e8e1e770ed | [
"ISC"
] | 31 | 2018-12-06T23:12:33.000Z | 2022-03-29T18:34:25.000Z | priv/repo/migrations/20180725182954_add_newlines_to_filter_name_enum.exs | CyberFlameGO/bolt | 225e6276983bec646e7f13519df066e8e1e770ed | [
"ISC"
] | 18 | 2021-06-14T19:03:26.000Z | 2022-03-15T17:46:22.000Z | priv/repo/migrations/20180725182954_add_newlines_to_filter_name_enum.exs | CyberFlameGO/bolt | 225e6276983bec646e7f13519df066e8e1e770ed | [
"ISC"
] | 4 | 2018-11-07T18:52:28.000Z | 2022-03-16T00:14:38.000Z | defmodule Bolt.Repo.Migrations.AddNewlinesToFilterNameEnum do
use Ecto.Migration
@disable_ddl_transaction true
def up do
execute("ALTER TYPE filter_name ADD VALUE 'NEWLINES';")
end
end
| 22 | 61 | 0.782828 |
08c5cf6e565f6e6982763967b89a2d14e09548be | 598 | ex | Elixir | lib/cog/models/types/process_id.ex | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 1,003 | 2016-02-23T17:21:12.000Z | 2022-02-20T14:39:35.000Z | lib/cog/models/types/process_id.ex | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 906 | 2016-02-22T22:54:19.000Z | 2022-03-11T15:19:43.000Z | lib/cog/models/types/process_id.ex | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 95 | 2016-02-23T13:42:31.000Z | 2021-11-30T14:39:55.000Z | defmodule Cog.Models.Types.ProcessId do
@behaviour Ecto.Type
def type, do: :string
def cast(value) when is_pid(value) do
try do
{:ok, pid_to_string(value)}
rescue
_e in ErlangError ->
:error
end
end
def cast(_), do: :error
def load(value) when is_binary(value), do: {:ok, string_to_pid(value)}
def dump(value) when is_binary(value), do: {:ok, value}
def dump(_), do: :error
defp pid_to_string(p) do
String.Chars.to_string(:erlang.pid_to_list(p))
end
defp string_to_pid(p) do
:erlang.list_to_pid(String.to_charlist(p))
end
end
| 19.290323 | 72 | 0.660535 |
08c5d5b7facb099d9cd2879f28d0910b18acd954 | 1,800 | ex | Elixir | apps/xomg_tasks/lib/utils.ex | karmonezz/elixir-omg | 3b26fc072fa553992277e1b9c4bad37b3d61ec6a | [
"Apache-2.0"
] | 1 | 2020-05-01T12:30:09.000Z | 2020-05-01T12:30:09.000Z | apps/xomg_tasks/lib/utils.ex | karmonezz/elixir-omg | 3b26fc072fa553992277e1b9c4bad37b3d61ec6a | [
"Apache-2.0"
] | null | null | null | apps/xomg_tasks/lib/utils.ex | karmonezz/elixir-omg | 3b26fc072fa553992277e1b9c4bad37b3d61ec6a | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule XomgTasks.Utils do
@moduledoc """
Common convenience code used to run Mix.Tasks goes here
"""
@doc """
Runs a specific app for some arguments. Will handle IEx, if one's running
"""
def generic_run(args, apps) when is_list(apps) do
Mix.Task.run("run", args)
_ =
Enum.each(apps, fn app ->
{:ok, _} = Application.ensure_all_started(app)
end)
ensure_one_rpc_loaded(apps)
iex_running?() || Process.sleep(:infinity)
end
@doc """
Will do all the generic preparations on the arguments required
"""
def generic_prepare_args(args) do
args
|> ensure_contains("--no-start")
|> ensure_doesnt_contain("--no-halt")
end
defp iex_running? do
Code.ensure_loaded?(IEx) and IEx.started?()
end
defp ensure_contains(args, arg) do
if Enum.member?(args, arg) do
args
else
[arg | args]
end
end
defp ensure_doesnt_contain(args, arg) do
List.delete(args, arg)
end
# mix loads entire codebase which fools `Response.add_version`
defp ensure_one_rpc_loaded(apps) do
if Enum.member?(apps, :omg_watcher) do
true = :code.delete(OMG.ChildChainRPC)
:code.purge(OMG.ChildChainRPC)
end
end
end
| 26.086957 | 75 | 0.692778 |
08c6015894f1d724a1c79b7a2839fc37ffb5f57b | 1,699 | ex | Elixir | lib/mix/lib/mix/public_key.ex | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | 4 | 2015-12-22T02:46:39.000Z | 2016-04-26T06:11:09.000Z | lib/mix/lib/mix/public_key.ex | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/public_key.ex | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.PublicKey do
@moduledoc false
@in_memory_key """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAslPz1mAfyAvRv8W8xOdv
HQMbDJkDKfRhsL4JBGwGH7qw0xh+TbaUlNaM3pF+i8VUjS/4FeXjT/OAUEAHu5Y2
rBVlx00QcH8Dpbyf+H73XiCs0MXnTSecqDgzx6i6NMi8knklHT7yHySHtuuPmPuN
Po8QTKolCKftwPE/iNDeyZfwufd+hTCoCQdoTVcB01SElfNtvKRtoKbx35q80IPr
rOcGsALmr58+bWqCTY/51kFeRxzrPJ5LdcLU/AebyWddD4IUfPDxk16jTiCagMWA
JPSwo8NUrWDIBbD+rEUp06y0ek276rG5Tzm/3Bma56RN/u6nAqBTBE8F2Hu2QBKj
lQIDAQAB
-----END PUBLIC KEY-----
"""
@doc """
Returns the filesystem path for public keys.
"""
def public_keys_path, do: Path.join(Mix.Utils.mix_home, "public_keys")
@doc """
Returns all public keys as a list.
"""
def public_keys do
path = public_keys_path()
[{"in-memory public key for Elixir v#{System.version}", @in_memory_key}] ++
case File.ls(path) do
{:ok, keys} -> Enum.map(keys, &{&1, File.read!(Path.join(path, &1))})
{:error, _} -> []
end
end
@doc """
Decodes a public key and raises if the key is invalid.
"""
def decode!(id, key) do
[rsa_public_key] = :public_key.pem_decode(key)
:public_key.pem_entry_decode(rsa_public_key)
rescue
_ ->
Mix.raise """
Could not decode public key: #{id}. The public key contents are shown below.
#{key}
Public keys must be valid and be in the PEM format.
"""
end
@doc """
Verifies the given binary has the proper signature using the system public keys.
"""
def verify(binary, hash, signature) do
Enum.any? public_keys(), fn {id, key} ->
:public_key.verify binary, hash, signature, decode!(id, key)
end
end
end
| 28.316667 | 82 | 0.691583 |
08c62d11abb155e29e348f17f8ecc108d3c8913c | 281 | exs | Elixir | daniel/prog_elix/ch24/caesar.exs | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | null | null | null | daniel/prog_elix/ch24/caesar.exs | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | 1 | 2020-02-26T14:55:23.000Z | 2020-02-26T14:55:23.000Z | daniel/prog_elix/ch24/caesar.exs | jdashton/glowing-succotash | 44580c2d4cb300e33156d42e358e8a055948a079 | [
"MIT"
] | null | null | null | defprotocol Caesar do
@fallback_to_any true
def encrypt(string, shift)
end
defimpl Caesar, for: BitString do
def encrypt(string, shift), do: true
end
defimpl Caesar, for: Any do
def is_caesar?(_), do: false
end
my_string = "abcd"
IO.inspect Caesar.encrypt(my_string, 1)
| 17.5625 | 39 | 0.740214 |
08c63d96f733335c2dc6845b49df116bfbb48f75 | 1,002 | ex | Elixir | lib/market/endpoint.ex | ajrob27/steam_community_market_clone | b1bad54d92e69aa8b99df529620ab7856e4787ab | [
"OML"
] | 1 | 2019-11-09T16:30:56.000Z | 2019-11-09T16:30:56.000Z | lib/market/endpoint.ex | codeithuman/steam_community_market_clone | b1bad54d92e69aa8b99df529620ab7856e4787ab | [
"OML"
] | null | null | null | lib/market/endpoint.ex | codeithuman/steam_community_market_clone | b1bad54d92e69aa8b99df529620ab7856e4787ab | [
"OML"
] | null | null | null | defmodule Market.Endpoint do
use Phoenix.Endpoint, otp_app: :market
socket "/socket", Market.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :market, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session,
store: :cookie,
key: "_market_key",
signing_salt: "zwq0E0Sw"
plug Market.Router
end
| 25.05 | 69 | 0.707585 |
08c6521fd24a6c2a4da32e67b60080c839ca24b5 | 1,911 | exs | Elixir | test/rules_test.exs | Fudoshiki/plug_attack | b3af6c1cd477872c5886d97c699a37fb7e638c63 | [
"Apache-2.0"
] | 323 | 2016-11-13T01:06:52.000Z | 2022-03-11T13:04:11.000Z | test/rules_test.exs | Fudoshiki/plug_attack | b3af6c1cd477872c5886d97c699a37fb7e638c63 | [
"Apache-2.0"
] | 21 | 2016-11-16T22:12:13.000Z | 2021-11-26T11:14:53.000Z | test/rules_test.exs | michalmuskala/plug_attack | b3af6c1cd477872c5886d97c699a37fb7e638c63 | [
"Apache-2.0"
] | 22 | 2016-11-13T15:34:41.000Z | 2022-03-29T10:14:17.000Z | defmodule PlugAttack.RuleTest do
use ExUnit.Case, async: true
setup do
{:ok, _} = PlugAttack.Storage.Ets.start_link(__MODULE__)
:ok
end
test "fail2ban" do
assert {:allow, {:fail2ban, :counting, :key}} = fail2ban()
:timer.sleep(1)
assert {:allow, {:fail2ban, :counting, :key}} = fail2ban()
:timer.sleep(150)
assert {:allow, {:fail2ban, :counting, :key}} = fail2ban()
:timer.sleep(1)
assert {:allow, {:fail2ban, :counting, :key}} = fail2ban()
:timer.sleep(1)
assert {:allow, {:fail2ban, :counting, :key}} = fail2ban()
:timer.sleep(100)
assert {:block, {:fail2ban, :banned, :key}} = fail2ban()
:timer.sleep(200)
assert {:allow, {:fail2ban, :counting, :key}} = fail2ban()
end
defp fail2ban() do
PlugAttack.Rule.fail2ban(:key,
storage: {PlugAttack.Storage.Ets, __MODULE__},
period: 100,
limit: 3,
ban_for: 200
)
end
test "throttle" do
assert {:allow, {:throttle, data}} = throttle()
expires = (div(System.system_time(:millisecond), 100) + 1) * 100
assert data[:period] == 100
assert data[:limit] == 5
assert data[:remaining] == 4
assert data[:expires_at] == expires
assert {:allow, _} = throttle()
assert {:allow, _} = throttle()
assert {:allow, _} = throttle()
assert {:allow, _} = throttle()
assert {:block, {:throttle, data}} = throttle()
assert data[:period] == 100
assert data[:limit] == 5
assert data[:remaining] == 0
assert data[:expires_at] == expires
:timer.sleep(90)
assert {:allow, {:throttle, data}} = throttle()
assert data[:period] == 100
assert data[:limit] == 5
assert data[:remaining] == 4
assert data[:expires_at] == expires + 100
end
defp throttle() do
PlugAttack.Rule.throttle(:key,
storage: {PlugAttack.Storage.Ets, __MODULE__},
limit: 5,
period: 100
)
end
end
| 26.915493 | 68 | 0.604919 |
08c6530c11c2e4f9419e5a2c86925115ee683720 | 12,027 | ex | Elixir | lib/google_api/storage/v1/api/notifications.ex | jamesvl/gcs_elixir_api | fd7e0f4a7e2e07f40e01822b4c9e09cfd4922d52 | [
"Apache-2.0"
] | null | null | null | lib/google_api/storage/v1/api/notifications.ex | jamesvl/gcs_elixir_api | fd7e0f4a7e2e07f40e01822b4c9e09cfd4922d52 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | lib/google_api/storage/v1/api/notifications.ex | jamesvl/gcs_elixir_api | fd7e0f4a7e2e07f40e01822b4c9e09cfd4922d52 | [
"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.Storage.V1.Api.Notifications do
@moduledoc """
API calls for all endpoints tagged `Notifications`.
"""
alias GoogleApi.Storage.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Permanently deletes a notification subscription.
## Parameters
* `connection` (*type:* `GoogleApi.Storage.V1.Connection.t`) - Connection to server
* `bucket` (*type:* `String.t`) - The parent bucket of the notification.
* `notification` (*type:* `String.t`) - ID of the notification to delete.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:provisionalUserProject` (*type:* `String.t`) - The project to be billed for this request if the target bucket is requester-pays bucket.
* `:userProject` (*type:* `String.t`) - The project to be billed for this request. Required for Requester Pays buckets.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec storage_notifications_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()}
def storage_notifications_delete(
connection,
bucket,
notification,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:provisionalUserProject => :query,
:userProject => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/storage/v1/b/{bucket}/notificationConfigs/{notification}", %{
"bucket" => URI.encode(bucket, &URI.char_unreserved?/1),
"notification" => URI.encode(notification, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
View a notification configuration.
## Parameters
* `connection` (*type:* `GoogleApi.Storage.V1.Connection.t`) - Connection to server
* `bucket` (*type:* `String.t`) - The parent bucket of the notification.
* `notification` (*type:* `String.t`) - Notification ID
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:provisionalUserProject` (*type:* `String.t`) - The project to be billed for this request if the target bucket is requester-pays bucket.
* `:userProject` (*type:* `String.t`) - The project to be billed for this request. Required for Requester Pays buckets.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Storage.V1.Model.Notification{}}` on success
* `{:error, info}` on failure
"""
@spec storage_notifications_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Storage.V1.Model.Notification.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def storage_notifications_get(
connection,
bucket,
notification,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:provisionalUserProject => :query,
:userProject => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/storage/v1/b/{bucket}/notificationConfigs/{notification}", %{
"bucket" => URI.encode(bucket, &URI.char_unreserved?/1),
"notification" => URI.encode(notification, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Storage.V1.Model.Notification{}])
end
@doc """
Creates a notification subscription for a given bucket.
## Parameters
* `connection` (*type:* `GoogleApi.Storage.V1.Connection.t`) - Connection to server
* `bucket` (*type:* `String.t`) - The parent bucket of the notification.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:provisionalUserProject` (*type:* `String.t`) - The project to be billed for this request if the target bucket is requester-pays bucket.
* `:userProject` (*type:* `String.t`) - The project to be billed for this request. Required for Requester Pays buckets.
* `:body` (*type:* `GoogleApi.Storage.V1.Model.Notification.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Storage.V1.Model.Notification{}}` on success
* `{:error, info}` on failure
"""
@spec storage_notifications_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Storage.V1.Model.Notification.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def storage_notifications_insert(connection, bucket, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:provisionalUserProject => :query,
:userProject => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/storage/v1/b/{bucket}/notificationConfigs", %{
"bucket" => URI.encode(bucket, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Storage.V1.Model.Notification{}])
end
@doc """
Retrieves a list of notification subscriptions for a given bucket.
## Parameters
* `connection` (*type:* `GoogleApi.Storage.V1.Connection.t`) - Connection to server
* `bucket` (*type:* `String.t`) - Name of a Google Cloud Storage bucket.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:provisionalUserProject` (*type:* `String.t`) - The project to be billed for this request if the target bucket is requester-pays bucket.
* `:userProject` (*type:* `String.t`) - The project to be billed for this request. Required for Requester Pays buckets.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Storage.V1.Model.Notifications{}}` on success
* `{:error, info}` on failure
"""
@spec storage_notifications_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Storage.V1.Model.Notifications.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def storage_notifications_list(connection, bucket, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:provisionalUserProject => :query,
:userProject => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/storage/v1/b/{bucket}/notificationConfigs", %{
"bucket" => URI.encode(bucket, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Storage.V1.Model.Notifications{}])
end
end
| 43.734545 | 187 | 0.630082 |
08c655ebc0c1d8b153c2e6305ade4107fc638cbf | 63 | ex | Elixir | lib/hexpm_web/views/opensearch_view.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 691 | 2017-03-08T09:15:45.000Z | 2022-03-23T22:04:47.000Z | lib/hexpm_web/views/opensearch_view.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 491 | 2017-03-07T12:58:42.000Z | 2022-03-29T23:32:54.000Z | lib/hexpm_web/views/opensearch_view.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 200 | 2017-03-12T23:03:39.000Z | 2022-03-05T17:55:52.000Z | defmodule HexpmWeb.OpenSearchView do
use HexpmWeb, :view
end
| 15.75 | 36 | 0.809524 |
08c6955698c8f59a5fd1ab7fd6eabac96456ca6d | 537 | exs | Elixir | config/test.exs | cebartling/horse-racing-demo | 7a50f2de35d275ed0dec2326fbba89f9ab3ee113 | [
"MIT"
] | null | null | null | config/test.exs | cebartling/horse-racing-demo | 7a50f2de35d275ed0dec2326fbba89f9ab3ee113 | [
"MIT"
] | null | null | null | config/test.exs | cebartling/horse-racing-demo | 7a50f2de35d275ed0dec2326fbba89f9ab3ee113 | [
"MIT"
] | null | null | null | use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :horse_racing_demo, HorseRacingDemo.Endpoint,
http: [port: 4001],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :horse_racing_demo, HorseRacingDemo.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "horse_racing_demo_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
| 26.85 | 56 | 0.756052 |
08c6a7f4e4910a34d1a6e8744e5add8c3ae30e11 | 3,234 | ex | Elixir | lib/fika/compiler/parser/types.ex | fika-lang/fika | 15bffc30daed744670bb2c0fba3e674055adac47 | [
"Apache-2.0"
] | 220 | 2020-09-12T18:16:29.000Z | 2022-03-15T14:39:05.000Z | lib/fika/compiler/parser/types.ex | fika-lang/fika | 15bffc30daed744670bb2c0fba3e674055adac47 | [
"Apache-2.0"
] | 60 | 2020-09-23T14:20:36.000Z | 2021-03-08T08:55:57.000Z | lib/fika/compiler/parser/types.ex | fika-lang/fika | 15bffc30daed744670bb2c0fba3e674055adac47 | [
"Apache-2.0"
] | 25 | 2020-09-19T09:06:10.000Z | 2021-08-24T23:48:39.000Z | defmodule Fika.Compiler.Parser.Types do
import NimbleParsec
alias Fika.Compiler.Parser.{Common, Helper}
allow_space = parsec({Common, :allow_space})
identifier_str = parsec({Common, :identifier_str})
atom = parsec({Common, :atom})
atom_type = Helper.to_ast(atom, :atom_type)
type_args =
parsec(:type)
|> optional(
allow_space
|> ignore(string(","))
|> concat(allow_space)
|> parsec(:type_args)
)
function_type =
ignore(string("Fn("))
|> optional(type_args |> map({Helper, :tag, [:arg_type]}))
|> concat(allow_space)
|> ignore(string("->"))
|> concat(allow_space)
|> concat(
parsec(:type)
|> map({Helper, :tag, [:return_type]})
)
|> ignore(string(")"))
|> Helper.to_ast(:function_type)
record_field =
allow_space
|> concat(identifier_str)
|> concat(allow_space)
|> ignore(string(":"))
|> concat(allow_space)
|> parsec(:type)
|> label("key value pair")
|> Helper.to_ast(:record_field)
record_fields =
record_field
|> repeat(
allow_space
|> ignore(string(","))
|> concat(allow_space)
|> concat(record_field)
)
record_type =
ignore(string("{"))
|> concat(record_fields)
|> ignore(string("}"))
|> label("record type")
|> Helper.to_ast(:record_type)
map_type =
ignore(string("Map("))
|> parsec(:type)
|> concat(allow_space)
|> ignore(string(","))
|> concat(allow_space)
|> parsec(:type)
|> concat(allow_space)
|> ignore(string(")"))
|> label("map type")
|> Helper.to_ast(:map_type)
tuple_type =
ignore(string("{"))
|> concat(type_args)
|> ignore(string("}"))
|> label("tuple type")
|> Helper.to_ast(:tuple_type)
list_type =
ignore(string("List("))
|> concat(parsec(:type))
|> ignore(string(")"))
|> label("list type")
|> Helper.to_ast(:list_type)
effect_type =
ignore(string("Effect("))
|> concat(parsec(:type))
|> ignore(string(")"))
|> label("effect type")
|> Helper.to_ast(:effect_type)
string_type =
string("String")
|> label("string")
|> reduce({Helper, :to_atom, []})
int_type =
string("Int")
|> label("int")
|> reduce({Helper, :to_atom, []})
float_type =
string("Float")
|> label("float")
|> reduce({Helper, :to_atom, []})
bool_type =
string("Bool")
|> label("boolean")
|> reduce({Helper, :to_atom, []})
type_variable =
identifier_str
|> label("type variable")
base_type =
choice([
string_type,
int_type,
float_type,
atom_type,
bool_type,
function_type,
list_type,
effect_type,
record_type,
map_type,
tuple_type,
type_variable
])
union_type =
base_type
|> times(
allow_space
|> ignore(string("|"))
|> concat(allow_space)
|> concat(base_type),
min: 1
)
|> label("union type")
|> Helper.to_ast(:union_type)
type = choice([union_type, base_type])
parse_type =
type
|> Helper.to_ast(:type)
defcombinatorp :type_args, type_args
defcombinator :type, type
defcombinator :parse_type, parse_type
end
| 20.864516 | 62 | 0.576994 |
08c6fab6eb181ea055e9a61f17456c0f461bbc6a | 3,683 | ex | Elixir | lib/auth0_ex/management/user.ex | warmwaffles/auth0_ex | d0d7ad895c4db79d366c9c55e289a944c891936c | [
"Apache-2.0"
] | 38 | 2016-08-31T12:44:19.000Z | 2021-06-17T18:23:21.000Z | lib/auth0_ex/management/user.ex | warmwaffles/auth0_ex | d0d7ad895c4db79d366c9c55e289a944c891936c | [
"Apache-2.0"
] | 24 | 2017-01-12T17:53:10.000Z | 2022-03-14T13:43:12.000Z | lib/auth0_ex/management/user.ex | warmwaffles/auth0_ex | d0d7ad895c4db79d366c9c55e289a944c891936c | [
"Apache-2.0"
] | 24 | 2017-01-27T20:51:57.000Z | 2022-03-11T19:58:40.000Z | defmodule Auth0Ex.Management.User do
@moduledoc """
A module representing users on Auth0
"""
use Auth0Ex.Api, for: :mgmt
@path "users"
@doc """
Gets all the users
iex> Auth0Ex.Management.User.all()
iex> Auth0Ex.Management.User.all(fields: "name", q: "app_metadata.admin:'true'")
"""
def all(params \\ %{}) when is_map(params) or is_list(params) do
do_get(@path, params)
end
@doc """
Gets a specific user record with a given user id
iex> Auth0Ex.Management.User.get("auth0|some_user_id")
iex> Auth0Ex.Management.User.get("auth0|some_user_id", %{fields: "email,name,username"})
"""
def get(user_id, params \\ %{}) when is_binary(user_id) and is_map(params) do
do_get("#{@path}/#{user_id}", params)
end
@doc """
Creates a user for the specified connection
iex> Auth0Ex.Management.User.create("test_connection", %{email: "test.user@email.com", username: "test_user_name"})
"""
def create(connection, body \\ %{}) when is_binary(connection) and is_map(body) do
do_post(@path, Map.put(body, :connection, connection))
end
@doc """
Updates a user's information given a user id
iex> Auth0Ex.Management.User.update("auth0|some_user_id", %{app_metadata: %{admin: false}})
"""
def update(user_id, body \\ %{}) when is_binary(user_id) and is_map(body) do
do_patch("#{@path}/#{user_id}", body)
end
@doc """
Deletes a user with a give user id
iex> Auth0Ex.Management.User.delete("auth0|some_user_id")
"""
def delete(user_id) when is_binary(user_id) do
do_delete("#{@path}/#{user_id}")
end
@doc """
Get a user's log
iex> Auth0Ex.Management.User.log("auth0|233423")
iex> Auth0Ex.Management.User.log("auth0|23423", page: 2, per_page: 10)
"""
def log(user_id, params) do
do_get("#{@path}/#{user_id}/logs", params)
end
@doc """
Get all Guardain enrollments for given user_id
iex> Auth0Ex.Management.User.enrollments("auth0|234")
"""
def enrollments(user_id), do: do_get("#{@path}/#{user_id}/enrollments", %{})
@doc """
Deletes a user's multifactor provider
iex> Auth0Ex.Management.User.delete_mfprovider("auth0|23423", "duo")
"""
def delete_mfprovider(user_id, provider) do
do_delete("#{@path}/#{user_id}/multifactor/#{provider}")
end
@doc """
Unlinks an identity from the target user, and it becomes a separated user again.
iex> Auth0Ex.Management.User.unlink("some_user_id", "github", "23984234")
"""
def unlink(primary_id, provider, secondary_id) do
do_delete("#{@path}/#{primary_id}/identities/#{provider}/#{secondary_id}")
end
@doc """
Removes current Guardain recovery code and generates new one
iex> Auth0Ex.Management.User.regenerate_recovery_code("auth0|34234")
"""
def regenerate_recovery_code(id) do
do_post("#{@path}/#{id}/recovery-code-regeneration")
end
@doc """
Links the account specified in the body to the given user_id param
iex> Auth0Ex.Management.User.link("some_user_id", link_with: "secondary_acc_jwt")
iex> Auth0Ex.Management.User.link("some_user_id", provider: "github", user_id: "23423", connection_id: "som")
"""
def link(id, body) do
do_post("#{@path}/#{id}/identities", body)
end
@doc """
List the roles associated with a user. Scopes: read:users read:roles
iex > Auth0Ex.Management.User.roles("auth0|23423")
"""
def roles(user_id, params \\ %{}) do
do_get("#{@path}/#{user_id}/roles", params)
end
@doc false
defp default_params do
case Application.get_env(:auth0_ex, :v2_search) do
true ->
%{}
_ ->
%{search_engine: "v3"}
end
end
end
| 28.330769 | 121 | 0.659788 |
08c709c824545f1b3d7f8b4bc535798d5b38a594 | 26,955 | ex | Elixir | lib/cldr/number/parse.ex | kipcole9/cldr_numbers | c840630fcb729cd8245b843c0b12f08e64fbc8f1 | [
"Apache-2.0"
] | 8 | 2017-12-13T00:39:34.000Z | 2019-04-12T06:00:07.000Z | lib/cldr/number/parse.ex | kipcole9/cldr_numbers | c840630fcb729cd8245b843c0b12f08e64fbc8f1 | [
"Apache-2.0"
] | 8 | 2017-10-29T23:38:32.000Z | 2019-03-20T19:22:43.000Z | lib/cldr/number/parse.ex | kipcole9/cldr_numbers | c840630fcb729cd8245b843c0b12f08e64fbc8f1 | [
"Apache-2.0"
] | 7 | 2017-10-05T11:35:36.000Z | 2018-08-20T12:17:03.000Z | defmodule Cldr.Number.Parser do
@moduledoc """
Functions for parsing numbers and currencies from
a string.
"""
@type per :: :percent | :permille
@number_format "[-+]?[0-9]([0-9_]|[,](?=[0-9]))*(\\.?[0-9_]+([eE][-+]?[0-9]+)?)?"
@doc """
Scans a string in a locale-aware manner and returns
a list of strings and numbers.
## Arguments
* `string` is any `String.t`
* `options` is a keyword list of options
## Options
* `:number` is one of `:integer`, `:float`,
`:decimal` or `nil`. The default is `nil`
meaning that the type auto-detected as either
an `integer` or a `float`.
* `:backend` is any module that includes `use Cldr`
and is therefore a CLDR backend module. The default
is `Cldr.default_backend!/0`.
* `:locale` is any locale returned by `Cldr.known_locale_names/1`
or a `t:Cldr.LanguageTag`. The default is `options[:backend].get_locale/1`.
## Returns
* A list of strings and numbers
## Notes
Number parsing is performed by `Cldr.Number.Parser.parse/2`
and any options provided are passed to that function.
## Examples
iex> Cldr.Number.Parser.scan("£1_000_000.34")
["£", 1000000.34]
iex> Cldr.Number.Parser.scan("I want £1_000_000 dollars")
["I want £", 1000000, " dollars"]
iex> Cldr.Number.Parser.scan("The prize is 23")
["The prize is ", 23]
iex> Cldr.Number.Parser.scan("The lottery number is 23 for the next draw")
["The lottery number is ", 23, " for the next draw"]
iex> Cldr.Number.Parser.scan("The loss is -1.000 euros", locale: "de", number: :integer)
["The loss is ", -1000, " euros"]
iex> Cldr.Number.Parser.scan "1kg"
[1, "kg"]
iex> Cldr.Number.Parser.scan "A number is the arab script ١٢٣٤٥", locale: "ar"
["A number is the arab script ", 12345]
"""
@spec scan(String.t(), Keyword.t()) ::
list(String.t() | integer() | float() | Decimal.t()) |
{:error, {module(), String.t()}}
def scan(string, options \\ []) do
{locale, backend} = Cldr.locale_and_backend_from(options)
with {:ok, locale} <- Cldr.validate_locale(locale, backend),
{:ok, symbols} <- Cldr.Number.Symbol.number_symbols_for(locale, backend),
{:ok, number_system} <- digits_number_system_from(locale) do
symbols =
symbols_for_number_system(symbols, number_system)
scanner =
@number_format
|> localize_format_string(locale, backend, symbols)
|> Regex.compile!([:unicode])
normalized_string =
transliterate(string, number_system, :latn, backend)
scanner
|> Regex.split(normalized_string, include_captures: true, trim: true)
|> Enum.map(&parse_element(&1, options))
end
end
defp parse_element(element, options) do
case parse(element, options) do
{:ok, number} -> number
{:error, _} -> element
end
end
@doc """
Parse a string in a locale-aware manner and return
a number.
## Arguments
* `string` is any `t:String`
* `options` is a keyword list of options
## Options
* `:number` is one of `:integer`, `:float`,
`:decimal` or `nil`. The default is `nil`
meaning that the type auto-detected as either
an `integer` or a `float`.
* `:backend` is any module that includes `use Cldr`
and is therefore a CLDR backend module. The default
is `Cldr.default_backend/0`.
* `:locale` is any locale returned by `Cldr.known_locale_names/1`
or a `Cldr.LanguageTag.t`. The default is `options[:backend].get_locale/1`.
## Returns
* A number of the requested or default type or
* `{:error, {exception, message}}` if no number could be determined
## Notes
This function parses a string to return a number but
in a locale-aware manner. It will normalise digits,
grouping characters and decimal separators.
It will transliterate digits that are in the
number system of the specific locale. For example, if
the locale is `th` (Thailand), then Thai digits are
transliterated to the Latin script before parsing.
Some number systems do not have decimal digits and in this
case an error will be returned, rather than continue
parsing and return misleading results.
It also caters for different forms of
the `+` and `-` symbols that appear in Unicode and
strips any `_` characters that might be used for
formatting in a string.
It then parses the number using the Elixir standard
library functions.
If the option `:number` is used and the parsed number
cannot be coerced to this type without losing precision
then an error is returned.
## Examples
iex> Cldr.Number.Parser.parse("+1.000,34", locale: "de")
{:ok, 1000.34}
iex> Cldr.Number.Parser.parse("-1_000_000.34")
{:ok, -1000000.34}
iex> Cldr.Number.Parser.parse("1.000", locale: "de", number: :integer)
{:ok, 1000}
iex> Cldr.Number.Parser.parse "١٢٣٤٥", locale: "ar"
{:ok, 12345}
# 1_000.34 cannot be coerced into an integer
# without precision loss so an error is returned.
iex> Cldr.Number.Parser.parse("+1.000,34", locale: "de", number: :integer)
{:error,
{Cldr.Number.ParseError,
"The string \\"+1.000,34\\" could not be parsed as a number"}}
iex> Cldr.Number.Parser.parse "一万二千三百四十五", locale: "ja-u-nu-jpan"
{:error,
{Cldr.UnknownNumberSystemError,
"The number system :jpan is not known or does not have digits"}}
"""
@spec parse(String.t(), Keyword.t()) ::
{:ok, integer() | float() | Decimal.t()} |
{:error, {module(), String.t()}}
def parse(string, options \\ []) when is_binary(string) and is_list(options) do
{locale, backend} = Cldr.locale_and_backend_from(options)
with {:ok, locale} <- Cldr.validate_locale(locale, backend),
{:ok, symbols} <- Cldr.Number.Symbol.number_symbols_for(locale, backend),
{:ok, number_system} <- digits_number_system_from(locale) do
symbols =
symbols_for_number_system(symbols, number_system)
normalized_string =
string
|> transliterate(number_system, :latn, backend)
|> normalize_number_string(locale, backend, symbols)
|> String.trim()
case parse_number(normalized_string, Keyword.get(options, :number)) do
{:error, _} -> {:error, parse_error(string)}
success -> success
end
end
end
defp parse_number(string, nil) do
with {:error, string} <- parse_number(string, :integer),
{:error, string} <- parse_number(string, :float) do
{:error, string}
end
end
defp parse_number(string, :integer) do
case Integer.parse(string) do
{integer, ""} -> {:ok, integer}
_other -> {:error, string}
end
end
defp parse_number(string, :float) do
case Float.parse(string) do
{float, ""} -> {:ok, float}
_other -> {:error, string}
end
end
defp parse_number(string, :decimal) do
case Cldr.Decimal.parse(string) do
{:error, ""} -> {:error, string}
{decimal, ""} -> {:ok, decimal}
_other -> {:error, string}
end
end
@doc """
Resolve curencies from strings within
a list.
Currencies can be identified at the
beginning and/or the end of a string.
## Arguments
* `list` is any list in which currency
names and symbols are expected
* `options` is a keyword list of options
## Options
* `:backend` is any module() that includes `use Cldr` and therefore
is a `Cldr` backend module(). The default is `Cldr.default_backend!/0`
* `:locale` is any valid locale returned by `Cldr.known_locale_names/1`
or a `t:Cldr.LanguageTag` struct returned by `Cldr.Locale.new!/2`
The default is `options[:backend].get_locale()`
* `:only` is an `atom` or list of `atoms` representing the
currencies or currency types to be considered for a match.
The equates to a list of acceptable currencies for parsing.
See the notes below for currency types.
* `:except` is an `atom` or list of `atoms` representing the
currencies or currency types to be not considered for a match.
This equates to a list of unacceptable currencies for parsing.
See the notes below for currency types.
* `:fuzzy` is a float greater than `0.0` and less than or
equal to `1.0` which is used as input to
`String.jaro_distance/2` to determine is the provided
currency string is *close enough* to a known currency
string for it to identify definitively a currency code.
It is recommended to use numbers greater than `0.8` in
order to reduce false positives.
## Returns
* An ISO4217 currency code as an atom or
* `{:error, {exception, message}}`
## Notes
The `:only` and `:except` options accept a list of
currency codes and/or currency types. The following
types are recognised.
If both `:only` and `:except` are specified,
the `:except` entries take priority - that means
any entries in `:except` are removed from the `:only`
entries.
* `:all`, the default, considers all currencies
* `:current` considers those currencies that have a `:to`
date of nil and which also is a known ISO4217 currency
* `:historic` is the opposite of `:current`
* `:tender` considers currencies that are legal tender
* `:unannotated` considers currencies that don't have
"(some string)" in their names. These are usually
financial instruments.
## Examples
iex> Cldr.Number.Parser.scan("100 US dollars")
...> |> Cldr.Number.Parser.resolve_currencies
[100, :USD]
iex> Cldr.Number.Parser.scan("100 eurosports")
...> |> Cldr.Number.Parser.resolve_currencies(fuzzy: 0.8)
[100, :EUR]
iex> Cldr.Number.Parser.scan("100 dollars des États-Unis")
...> |> Cldr.Number.Parser.resolve_currencies(locale: "fr")
[100, :USD]
"""
@spec resolve_currencies([String.t(), ...], Keyword.t()) ::
list(Cldr.Currency.code() | String.t())
def resolve_currencies(list, options \\ []) when is_list(list) and is_list(options) do
resolve(list, &resolve_currency/2, options)
end
@doc """
Resolve and tokenize percent and permille
sybols from strings within a list.
Percent and permille symbols can be identified
at the beginning and/or the end of a string.
## Arguments
* `list` is any list in which percent and
permille symbols are expected
* `options` is a keyword list of options
## Options
* `:backend` is any module() that includes `use Cldr` and therefore
is a `Cldr` backend module(). The default is `Cldr.default_backend!/0`
* `:locale` is any valid locale returned by `Cldr.known_locale_names/1`
or a `t:Cldr.LanguageTag` struct returned by `Cldr.Locale.new!/2`
The default is `options[:backend].get_locale()`
## Examples
iex> Cldr.Number.Parser.scan("100%")
...> |> Cldr.Number.Parser.resolve_pers()
[100, :percent]
"""
@doc since: "2.21.0"
@spec resolve_pers([String.t(), ...], Keyword.t()) ::
list(per() | String.t())
def resolve_pers(list, options \\ []) when is_list(list) and is_list(options) do
resolve(list, &resolve_per/2, options)
end
@doc """
Maps a list of terms (usually strings and atoms)
calling a resolver function that operates
on each binary term.
If the resolver function returns `{:error, term}`
then no change is made to the term, otherwise
the return value of the resolver replaces the
original term.
## Arguments
* `list` is a list of terms. Typically this is the
result of calling `Cldr.Number.Parser.scan/1`.
* `resolver` is a function that takes two
arguments. The first is one of the terms
in the `list`. The second is `options`.
* `options` is a keyword list of options
that is passed to the resolver function.
## Note
* The resolver is called only on binary
elements of the list.
## Returns
* `list` as modified through the application
of the resolver function on each binary term.
## Examples
See `Cldr.Number.Parser.resolve_currencies/2` and
`Cldr.Number.Parser.resolve_pers/2` which both
use this function.
"""
@spec resolve(list(any()), fun(), Keyword.t()) :: list()
def resolve(list, resolver, options) do
Enum.map(list, fn
string when is_binary(string) ->
case resolver.(string, options) do
{:error, _} -> string
other -> other
end
other -> other
end)
|> List.flatten()
end
@doc false
defguard is_token(arg) when is_atom(arg) or is_number(arg)
@doc """
Removes any whitespace strings from between
tokens in a list.
Tokens are numbers or atoms.
"""
@whitespace ~r/^\s*$/u
def remove_whitespace_between_tokens([first, second, third | rest])
when is_token(first) and is_token(third) do
if String.match?(second, @whitespace) do
[first | remove_whitespace_between_tokens([third | rest])]
else
[first | remove_whitespace_between_tokens([second, third | rest])]
end
end
def remove_whitespace_between_tokens([first | rest]) do
[first | remove_whitespace_between_tokens(rest)]
end
def remove_whitespace_between_tokens(first) do
first
end
@doc """
Resolve a currency from the beginning
and/or the end of a string
## Arguments
* `list` is any list in which currency
names and symbols are expected
* `options` is a keyword list of options
## Options
* `:backend` is any module() that includes `use Cldr` and therefore
is a `Cldr` backend module(). The default is `Cldr.default_backend!/0`
* `:locale` is any valid locale returned by `Cldr.known_locale_names/1`
or a `Cldr.LanguageTag` struct returned by `Cldr.Locale.new!/2`
The default is `options[:backend].get_locale()`
* `:only` is an `atom` or list of `atoms` representing the
currencies or currency types to be considered for a match.
The equates to a list of acceptable currencies for parsing.
See the notes below for currency types.
* `:except` is an `atom` or list of `atoms` representing the
currencies or currency types to be not considered for a match.
This equates to a list of unacceptable currencies for parsing.
See the notes below for currency types.
* `:fuzzy` is a float greater than `0.0` and less than or
equal to `1.0` which is used as input to
`String.jaro_distance/2` to determine is the provided
currency string is *close enough* to a known currency
string for it to identify definitively a currency code.
It is recommended to use numbers greater than `0.8` in
order to reduce false positives.
## Returns
* An ISO417 currency code as an atom or
* `{:error, {exception, message}}`
## Notes
The `:only` and `:except` options accept a list of
currency codes and/or currency types. The following
types are recognised.
If both `:only` and `:except` are specified,
the `:except` entries take priority - that means
any entries in `:except` are removed from the `:only`
entries.
* `:all`, the default, considers all currencies
* `:current` considers those currencies that have a `:to`
date of nil and which also is a known ISO4217 currency
* `:historic` is the opposite of `:current`
* `:tender` considers currencies that are legal tender
* `:unannotated` considers currencies that don't have
"(some string)" in their names. These are usually
financial instruments.
## Examples
iex> Cldr.Number.Parser.resolve_currency("US dollars")
[:USD]
iex> Cldr.Number.Parser.resolve_currency("100 eurosports", fuzzy: 0.75)
[:EUR]
iex> Cldr.Number.Parser.resolve_currency("dollars des États-Unis", locale: "fr")
[:USD]
iex> Cldr.Number.Parser.resolve_currency("not a known currency", locale: "fr")
{:error,
{Cldr.UnknownCurrencyError,
"The currency \\"not a known currency\\" is unknown or not supported"}}
"""
@spec resolve_currency(String.t(), Keyword.t()) ::
Cldr.Currency.code() | list(Cldr.Currency.code() | String.t()) |
{:error, {module(), String.t()}}
def resolve_currency(string, options \\ []) when is_binary(string) do
{locale, backend} = Cldr.locale_and_backend_from(options)
{only_filter, options} =
Keyword.pop(options, :only, Keyword.get(options, :currency_filter, [:all]))
{except_filter, options} = Keyword.pop(options, :except, [])
{fuzzy, _options} = Keyword.pop(options, :fuzzy, nil)
with {:ok, locale} <- backend.validate_locale(locale),
{:ok, currency_strings} <-
Cldr.Currency.currency_strings(locale, backend, only_filter, except_filter),
{:ok, currency} <- find_and_replace(currency_strings, string, fuzzy) do
currency
else
{:error, {Cldr.Number.ParseError, _}} ->
{:error, unknown_currency_error(string)}
other ->
other
end
end
@doc """
Resolve and tokenize percent or permille
from the beginning and/or the end of a string
## Arguments
* `list` is any list in which percent
and permille symbols are expected
* `options` is a keyword list of options
## Options
* `:backend` is any module() that includes `use Cldr` and therefore
is a `Cldr` backend module(). The default is `Cldr.default_backend!/0`
* `:locale` is any valid locale returned by `Cldr.known_locale_names/1`
or a `Cldr.LanguageTag` struct returned by `Cldr.Locale.new!/2`
The default is `options[:backend].get_locale()`
## Returns
* An `:percent` or `permille` or
* `{:error, {exception, message}}`
## Examples
iex> Cldr.Number.Parser.resolve_per "11%"
["11", :percent]
iex> Cldr.Number.Parser.resolve_per "% of linguists"
[:percent, " of linguists"]
iex> Cldr.Number.Parser.resolve_per "% of linguists %"
[:percent, " of linguists ", :percent]
"""
@doc since: "2.21.0"
@spec resolve_per(String.t(), Keyword.t()) ::
per() | list(per() | String.t()) | {:error, {module(), String.t()}}
def resolve_per(string, options \\ []) when is_binary(string) do
{locale, backend} = Cldr.locale_and_backend_from(options)
{fuzzy, _options} = Keyword.pop(options, :fuzzy, nil)
with {:ok, locale} <- backend.validate_locale(locale),
{:ok, per_strings} <- per_strings(locale, backend),
{:ok, per} <- find_and_replace(per_strings, string, fuzzy) do
per
else
{:error, {Cldr.Number.ParseError, _}} ->
{:error, {Cldr.Number.ParseError, "No percent or permille found"}}
other ->
other
end
end
defp per_strings(locale, backend) do
with {:ok, number_system} <- digits_number_system_from(locale),
{:ok, symbols} <- Cldr.Number.Symbol.number_symbols_for(locale, backend) do
symbols = symbols_for_number_system(symbols, number_system)
parse_map = backend.lenient_parse_map(:general, locale.cldr_locale_name)
{:ok, Map.new(per_map(parse_map, symbols.percent_sign) ++ per_map(parse_map, symbols.per_mille))}
end
end
defp per_map(parse_map, char) do
parse_map
|> Map.fetch!(char)
|> Map.fetch!(:source)
|> String.replace("[", "")
|> String.replace("]", "")
|> String.graphemes()
|> Enum.map(&{&1, :percent})
end
# Replace localised symbols with canonical forms
defp normalize_number_string(string, locale, backend, symbols) do
string
|> String.replace("_", "")
|> backend.normalize_lenient_parse(:number, locale)
|> backend.normalize_lenient_parse(:general, locale)
|> String.replace(symbols.group, "")
|> String.replace(" ", "")
|> String.replace(symbols.decimal, ".")
|> String.replace("_", "-")
end
defp transliterate(string, from, to, backend) do
module = Module.concat(backend, Number.Transliterate)
case module.transliterate_digits(string, from, to) do
{:error, _} -> string
string -> string
end
end
defp digits_number_system_from(locale) do
number_system = Cldr.Number.System.number_system_from_locale(locale)
with {:ok, _digits} <- Cldr.Number.System.number_system_digits(number_system) do
{:ok, number_system}
end
end
defp symbols_for_number_system(symbols, number_system) do
Map.fetch!(symbols, number_system) || Map.fetch!(symbols, :latn)
end
# Replace canonical forms with localised symbols
defp localize_format_string(string, locale, backend, symbols) do
parse_map = backend.lenient_parse_map(:number, locale.cldr_locale_name)
plus_matchers = Map.get(parse_map, "+").source |> String.replace(["[", "]"], "")
minus_matchers = Map.get(parse_map, "_").source |> String.replace(["[", "]"], "")
grouping_matchers = Map.get(parse_map, ",").source |> String.replace(["[", "]"], "")
string
|> String.replace("[-+]", "[" <> plus_matchers <> minus_matchers <> "]")
|> String.replace(",", grouping_matchers <> maybe_add_space(symbols.group))
|> String.replace("\\.", "\\" <> symbols.decimal)
end
# If the grouping symbol is a pop space then
# also allow normal space as a group symbol when parsing
@pop_space " " # 0x202c
@space " " # 0x20
defp maybe_add_space(@pop_space), do: @pop_space <> @space
defp maybe_add_space(other), do: other
@doc """
Find a substring at the beginning and/or end of a
string, and replace it.
Ignore any whitespace found at the start or end of the
string when looking for a match. A match is considered
only if there is no alphabetic character adjacent to
the match.
When multiple matches are found, the longest match
is replaced.
## Arguments
* `string_map` is a map where the keys are the strings
to be matched and the values are the replacement.
* `string` is the string in which the find and replace
operation takes place.
* `fuzzy` is floating point number between 0.0 and 1.0
that is used to implement a fuzzy match using
`String.jaro_distance/2`. The default is `nil` which
means the match is exact at the beginning and/or the
end of the `string`.
## Returns
* `{:ok, list}` where list is `string` broken into the
replacement(s) and the remainder after find and replace. Or
* `{:error, {exception, reason}}` will be returned if
the `fuzzy` parameter is invalid or if no search was found
and no replacement made. In the later case, `exception`
will be `Cldr.Number.ParseError`.
## Examples
iex> Cldr.Number.Parser.find_and_replace(%{"this" => "that"}, "This is a string")
{:ok, ["that", " is a string"]}
iex> Cldr.Number.Parser.find_and_replace(%{"string" => "term"}, "This is a string")
{:ok, ["This is a ", "term"]}
iex> Cldr.Number.Parser.find_and_replace(%{"string" => "term", "this" => "that"}, "This is a string")
{:ok, ["that", " is a ", "term"]}
iex> Cldr.Number.Parser.find_and_replace(%{"unknown" => "term"}, "This is a string")
{:error, {Cldr.Number.ParseError, "No match was found"}}
"""
@doc since: "2.22.0"
@spec find_and_replace(%{binary() => term()}, binary(), float() | nil) ::
{:ok, list()} | {:error, {module(), binary()}}
def find_and_replace(string_map, string, fuzzy \\ nil)
def find_and_replace(string_map, string, fuzzy) when is_map(string_map) and is_binary(string) do
if String.trim(string) == "" do
{:ok, string}
else
do_find_and_replace(string_map, string, fuzzy)
end
end
defp do_find_and_replace(string_map, string, nil) when is_map(string_map) and is_binary(string) do
if code = Map.get(string_map, normalize_search_string(string)) do
{:ok, [code]}
else
[starting_code, remainder] = starting_string(string_map, string)
[remainder, ending_code] = ending_string(string_map, remainder)
if starting_code == "" && ending_code == "" do
{:error, {Cldr.Number.ParseError, "No match was found"}}
else
{:ok, Enum.reject([starting_code, remainder, ending_code], &(&1 == ""))}
end
end
end
defp do_find_and_replace(string_map, search, fuzzy)
when is_float(fuzzy) and fuzzy > 0.0 and fuzzy <= 1.0 do
canonical_search = String.downcase(search)
{distance, code} =
string_map
|> Enum.map(fn {k, v} -> {String.jaro_distance(k, canonical_search), v} end)
|> Enum.sort(fn {k1, _v1}, {k2, _v2} -> k1 > k2 end)
|> hd
if distance >= fuzzy do
{:ok, [code]}
else
{:error, {Cldr.Number.ParseError, "No match was found"}}
end
end
defp do_find_and_replace(_currency_strings, _currency, fuzzy) do
{:error,
{
ArgumentError,
"option :fuzzy must be a number > 0.0 and <= 1.0. Found #{inspect(fuzzy)}"
}}
end
defp starting_string(string_map, search) do
[whitespace, trimmed] =
search
|> String.downcase()
|> String.split(~r/^\s*/, parts: 2, include_captures: true, trim: true)
case starts_with(string_map, trimmed) do
[] ->
["", search]
list ->
{string, match_length, code} = longest_match(list)
[_, remainder] = String.split(trimmed, string, parts: 2)
if String.match?(remainder, ~r/^[[:alpha:]]/u) do
["", search]
else
match_length = match_length + :erlang.byte_size(whitespace)
<< _ :: binary-size(match_length), remainder :: binary>> = search
[code, remainder]
end
end
end
defp ending_string(string_map, search) do
trimmed =
search
|> String.downcase()
|> String.trim_trailing()
case ends_with(string_map, trimmed) do
[] ->
[search, ""]
list ->
{string, match_length, code} = longest_match(list)
[remainder, _] = String.split(trimmed, string, parts: 2)
if String.match?(remainder, ~r/[[:alpha:]]$/u) do
[search, ""]
else
match = :erlang.byte_size(trimmed) - match_length
<< remainder :: binary-size(match), _rest :: binary>> = search
[remainder, code]
end
end
end
defp normalize_search_string(string) do
string
|> String.downcase()
|> String.trim()
end
defp starts_with(strings, search) do
Enum.filter(strings, &String.starts_with?(search, elem(&1, 0)))
end
defp ends_with(strings, search) do
Enum.filter(strings, &String.ends_with?(search, elem(&1, 0)))
end
defp longest_match(matches) do
{match, code} =
matches
|> Enum.sort(fn a, b -> String.length(elem(a, 0)) > String.length(elem(b, 0)) end)
|> hd
{match, :erlang.byte_size(match), code}
end
defp unknown_currency_error(currency) do
{Cldr.UnknownCurrencyError, "The currency #{inspect(currency)} is unknown or not supported"}
end
defp parse_error(string) do
{Cldr.Number.ParseError, "The string #{inspect string} could not be parsed as a number"}
end
end | 30.388952 | 107 | 0.653014 |
08c753d51ce39dd9789828fa4d7a5bb3c2fbc8cd | 252 | exs | Elixir | test/models/stock_test.exs | neilfulwiler/open_pantry | 4b705f2282c7b2365a784503c9f1bdd34c741798 | [
"MIT"
] | 41 | 2017-10-04T00:33:46.000Z | 2021-04-09T01:33:34.000Z | test/models/stock_test.exs | openpantry/open_pantry | 27d898a65dd6f44b325f48d41bc448bb486d9c6f | [
"MIT"
] | 74 | 2017-09-20T03:36:17.000Z | 2018-11-20T20:46:16.000Z | test/models/stock_test.exs | neilfulwiler/open_pantry | 4b705f2282c7b2365a784503c9f1bdd34c741798 | [
"MIT"
] | 12 | 2017-10-04T10:02:49.000Z | 2021-12-28T22:57:20.000Z | defmodule OpenPantry.StockTest do
use OpenPantry.ModelCase
alias OpenPantry.Stock
@invalid_attrs %{}
test "changeset with invalid attributes" do
changeset = Stock.changeset(%Stock{}, @invalid_attrs)
refute changeset.valid?
end
end
| 19.384615 | 57 | 0.746032 |
08c75b22de1e22abea7a85a5d61291cc7a5f2c62 | 148,356 | ex | Elixir | lib/elixir/lib/kernel.ex | sjBao/elixir | 52ee3ac163098f91f15dcb1360ae801a98453a77 | [
"Apache-2.0"
] | 1 | 2020-01-14T18:44:56.000Z | 2020-01-14T18:44:56.000Z | lib/elixir/lib/kernel.ex | sjBao/elixir | 52ee3ac163098f91f15dcb1360ae801a98453a77 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | sjBao/elixir | 52ee3ac163098f91f15dcb1360ae801a98453a77 | [
"Apache-2.0"
] | null | null | null | # Use elixir_bootstrap module to be able to bootstrap Kernel.
# The bootstrap module provides simpler implementations of the
# functions removed, simple enough to bootstrap.
import Kernel,
except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2]
import :elixir_bootstrap
defmodule Kernel do
@moduledoc """
`Kernel` is Elixir's default environment.
It mainly consists of:
* basic language primitives, such as arithmetic operators, spawning of processes,
data type handling, and others
* macros for control-flow and defining new functionality (modules, functions, and the like)
* guard checks for augmenting pattern matching
You can invoke `Kernel` functions and macros anywhere in Elixir code
without the use of the `Kernel.` prefix since they have all been
automatically imported. For example, in IEx, you can call:
iex> is_number(13)
true
If you don't want to import a function or macro from `Kernel`, use the `:except`
option and then list the function/macro by arity:
import Kernel, except: [if: 2, unless: 2]
See `Kernel.SpecialForms.import/2` for more information on importing.
Elixir also has special forms that are always imported and
cannot be skipped. These are described in `Kernel.SpecialForms`.
## The standard library
`Kernel` provides the basic capabilities the Elixir standard library
is built on top of. It is recommended to explore the standard library
for advanced functionality. Here are the main groups of modules in the
standard library (this list is not a complete reference, see the
documentation sidebar for all entries).
### Built-in types
The following modules handle Elixir built-in data types:
* `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms)
* `Float` - numbers with floating point precision
* `Function` - a reference to code chunk, created with the `fn/1` special form
* `Integer` - whole numbers (not fractions)
* `List` - collections of a variable number of elements (linked lists)
* `Map` - collections of key-value pairs
* `Process` - light-weight threads of execution
* `Port` - mechanisms to interact with the external world
* `Tuple` - collections of a fixed number of elements
There are two data types without an accompanying module:
* Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>/1`.
When the number of bits is divisible by 8, they are called binaries and can
be manipulated with Erlang's `:binary` module
* Reference - a unique value in the runtime system, created with `make_ref/0`
### Data types
Elixir also provides other data types that are built on top of the types
listed above. Some of them are:
* `Date` - `year-month-day` structs in a given calendar
* `DateTime` - date and time with time zone in a given calendar
* `Exception` - data raised from errors and unexpected scenarios
* `MapSet` - unordered collections of unique elements
* `NaiveDateTime` - date and time without time zone in a given calendar
* `Keyword` - lists of two-element tuples, often representing optional values
* `Range` - inclusive ranges between two integers
* `Regex` - regular expressions
* `String` - UTF-8 encoded binaries representing characters
* `Time` - `hour:minute:second` structs in a given calendar
* `URI` - representation of URIs that identify resources
* `Version` - representation of versions and requirements
### System modules
Modules that interface with the underlying system, such as:
* `IO` - handles input and output
* `File` - interacts with the underlying file system
* `Path` - manipulates file system paths
* `System` - reads and writes system information
### Protocols
Protocols add polymorphic dispatch to Elixir. They are contracts
implementable by data types. See `defprotocol/2` for more information on
protocols. Elixir provides the following protocols in the standard library:
* `Collectable` - collects data into a data type
* `Enumerable` - handles collections in Elixir. The `Enum` module
provides eager functions for working with collections, the `Stream`
module provides lazy functions
* `Inspect` - converts data types into their programming language
representation
* `List.Chars` - converts data types to their outside world
representation as charlists (non-programming based)
* `String.Chars` - converts data types to their outside world
representation as strings (non-programming based)
### Process-based and application-centric functionality
The following modules build on top of processes to provide concurrency,
fault-tolerance, and more.
* `Agent` - a process that encapsulates mutable state
* `Application` - functions for starting, stopping and configuring
applications
* `GenServer` - a generic client-server API
* `Registry` - a key-value process-based storage
* `Supervisor` - a process that is responsible for starting,
supervising and shutting down other processes
* `Task` - a process that performs computations
* `Task.Supervisor` - a supervisor for managing tasks exclusively
### Supporting documents
Elixir documentation also includes supporting documents under the
"Pages" section. Those are:
* [Compatibility and Deprecations](compatibility-and-deprecations.html) - lists
compatibility between every Elixir version and Erlang/OTP, release schema;
lists all deprecated functions, when they were deprecated and alternatives
* [Library Guidelines](library-guidelines.html) - general guidelines, anti-patterns,
and rules for those writing libraries
* [Naming Conventions](naming-conventions.html) - naming conventions for Elixir code
* [Operators](operators.html) - lists all Elixir operators and their precedence
* [Patterns and Guards](patterns-and-guards.html) - an introduction to patterns,
guards, and extensions
* [Syntax Reference](syntax-reference.html) - the language syntax reference
* [Typespecs](typespecs.html)- types and function specifications, including list of types
* [Unicode Syntax](unicode-syntax.html) - outlines Elixir support for Unicode
* [Writing Documentation](writing-documentation.html) - guidelines for writing
documentation in Elixir
## Guards
This module includes the built-in guards used by Elixir developers.
They are a predefined set of functions and macros that augment pattern
matching, typically invoked after the `when` operator. For example:
def drive(%User{age: age}) when age >= 16 do
...
end
The clause above will only be invoked if the user's age is more than
or equal to 16. Guards also support joining multiple conditions with
`and` and `or`. The whole guard is true if all guard expressions will
evaluate to `true`. A more complete introduction to guards is available
[in the "Patterns and Guards" page](patterns-and-guards.html).
## Inlining
Some of the functions described in this module are inlined by
the Elixir compiler into their Erlang counterparts in the
[`:erlang` module](http://www.erlang.org/doc/man/erlang.html).
Those functions are called BIFs (built-in internal functions)
in Erlang-land and they exhibit interesting properties, as some
of them are allowed in guards and others are used for compiler
optimizations.
Most of the inlined functions can be seen in effect when
capturing the function:
iex> &Kernel.is_atom/1
&:erlang.is_atom/1
Those functions will be explicitly marked in their docs as
"inlined by the compiler".
## Truthy and falsy values
Besides the booleans `true` and `false`, Elixir has the
concept of a "truthy" or "falsy" value.
* a value is truthy when it is neither `false` nor `nil`
* a value is falsy when it is either `false` or `nil`
Elixir has functions, like `and/2`, that *only* work with
booleans, but also functions that work with these
truthy/falsy values, like `&&/2` and `!/1`.
### Examples
We can check the truthiness of a value by using the `!/1`
function twice.
Truthy values:
iex> !!true
true
iex> !!5
true
iex> !![1,2]
true
iex> !!"foo"
true
Falsy values (of which there are exactly two):
iex> !!false
false
iex> !!nil
false
"""
# We need this check only for bootstrap purposes.
# Once Kernel is loaded and we recompile, it is a no-op.
@compile {:inline, bootstrapped?: 1}
case :code.ensure_loaded(Kernel) do
{:module, _} ->
defp bootstrapped?(_), do: true
{:error, _} ->
defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module}
end
## Delegations to Erlang with inlining (macros)
@doc """
Returns an integer or float which is the arithmetical absolute value of `number`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> abs(-3.33)
3.33
iex> abs(-3)
3
"""
@doc guard: true
@spec abs(number) :: number
def abs(number) do
:erlang.abs(number)
end
@doc """
Invokes the given anonymous function `fun` with the list of
arguments `args`.
Inlined by the compiler.
## Examples
iex> apply(fn x -> x * 2 end, [2])
4
"""
@spec apply(fun, [any]) :: any
def apply(fun, args) do
:erlang.apply(fun, args)
end
@doc """
Invokes the given function from `module` with the list of
arguments `args`.
`apply/3` is used to invoke functions where the module, function
name or arguments are defined dynamically at runtime. For this
reason, you can't invoke macros using `apply/3`, only functions.
Inlined by the compiler.
## Examples
iex> apply(Enum, :reverse, [[1, 2, 3]])
[3, 2, 1]
"""
@spec apply(module, function_name :: atom, [any]) :: any
def apply(module, function_name, args) do
:erlang.apply(module, function_name, args)
end
@doc """
Extracts the part of the binary starting at `start` with length `length`.
Binaries are zero-indexed.
If `start` or `length` reference in any way outside the binary, an
`ArgumentError` exception is raised.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> binary_part("foo", 1, 2)
"oo"
A negative `length` can be used to extract bytes that come *before* the byte
at `start`:
iex> binary_part("Hello", 5, -3)
"llo"
"""
@doc guard: true
@spec binary_part(binary, non_neg_integer, integer) :: binary
def binary_part(binary, start, length) do
:erlang.binary_part(binary, start, length)
end
@doc """
Returns an integer which is the size in bits of `bitstring`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> bit_size(<<433::16, 3::3>>)
19
iex> bit_size(<<1, 2, 3>>)
24
"""
@doc guard: true
@spec bit_size(bitstring) :: non_neg_integer
def bit_size(bitstring) do
:erlang.bit_size(bitstring)
end
@doc """
Returns the number of bytes needed to contain `bitstring`.
That is, if the number of bits in `bitstring` is not divisible by 8, the
resulting number of bytes will be rounded up (by excess). This operation
happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> byte_size(<<433::16, 3::3>>)
3
iex> byte_size(<<1, 2, 3>>)
3
"""
@doc guard: true
@spec byte_size(bitstring) :: non_neg_integer
def byte_size(bitstring) do
:erlang.byte_size(bitstring)
end
@doc """
Returns the smallest integer greater than or equal to `number`.
If you want to perform ceil operation on other decimal places,
use `Float.ceil/2` instead.
Allowed in guard tests. Inlined by the compiler.
"""
@doc since: "1.8.0", guard: true
@spec ceil(number) :: integer
def ceil(number) do
:erlang.ceil(number)
end
@doc """
Performs an integer division.
Raises an `ArithmeticError` exception if one of the arguments is not an
integer, or when the `divisor` is `0`.
`div/2` performs *truncated* integer division. This means that
the result is always rounded towards zero.
If you want to perform floored integer division (rounding towards negative infinity),
use `Integer.floor_div/2` instead.
Allowed in guard tests. Inlined by the compiler.
## Examples
div(5, 2)
#=> 2
div(6, -4)
#=> -1
div(-99, 2)
#=> -49
div(100, 0)
** (ArithmeticError) bad argument in arithmetic expression
"""
@doc guard: true
@spec div(integer, neg_integer | pos_integer) :: integer
def div(dividend, divisor) do
:erlang.div(dividend, divisor)
end
@doc """
Stops the execution of the calling process with the given reason.
Since evaluating this function causes the process to terminate,
it has no return value.
Inlined by the compiler.
## Examples
When a process reaches its end, by default it exits with
reason `:normal`. You can also call `exit/1` explicitly if you
want to terminate a process but not signal any failure:
exit(:normal)
In case something goes wrong, you can also use `exit/1` with
a different reason:
exit(:seems_bad)
If the exit reason is not `:normal`, all the processes linked to the process
that exited will crash (unless they are trapping exits).
## OTP exits
Exits are used by the OTP to determine if a process exited abnormally
or not. The following exits are considered "normal":
* `exit(:normal)`
* `exit(:shutdown)`
* `exit({:shutdown, term})`
Exiting with any other reason is considered abnormal and treated
as a crash. This means the default supervisor behaviour kicks in,
error reports are emitted, and so forth.
This behaviour is relied on in many different places. For example,
`ExUnit` uses `exit(:shutdown)` when exiting the test process to
signal linked processes, supervision trees and so on to politely
shut down too.
## CLI exits
Building on top of the exit signals mentioned above, if the
process started by the command line exits with any of the three
reasons above, its exit is considered normal and the Operating
System process will exit with status 0.
It is, however, possible to customize the operating system exit
signal by invoking:
exit({:shutdown, integer})
This will cause the operating system process to exit with the status given by
`integer` while signaling all linked Erlang processes to politely
shut down.
Any other exit reason will cause the operating system process to exit with
status `1` and linked Erlang processes to crash.
"""
@spec exit(term) :: no_return
def exit(reason) do
:erlang.exit(reason)
end
@doc """
Returns the largest integer smaller than or equal to `number`.
If you want to perform floor operation on other decimal places,
use `Float.floor/2` instead.
Allowed in guard tests. Inlined by the compiler.
"""
@doc since: "1.8.0", guard: true
@spec floor(number) :: integer
def floor(number) do
:erlang.floor(number)
end
@doc """
Returns the head of a list. Raises `ArgumentError` if the list is empty.
It works with improper lists.
Allowed in guard tests. Inlined by the compiler.
## Examples
hd([1, 2, 3, 4])
#=> 1
hd([])
** (ArgumentError) argument error
hd([1 | 2])
#=> 1
"""
@doc guard: true
@spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term
def hd(list) do
:erlang.hd(list)
end
@doc """
Returns `true` if `term` is an atom; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_atom(term) :: boolean
def is_atom(term) do
:erlang.is_atom(term)
end
@doc """
Returns `true` if `term` is a binary; otherwise returns `false`.
A binary always contains a complete number of bytes.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> is_binary("foo")
true
iex> is_binary(<<1::3>>)
false
"""
@doc guard: true
@spec is_binary(term) :: boolean
def is_binary(term) do
:erlang.is_binary(term)
end
@doc """
Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> is_bitstring("foo")
true
iex> is_bitstring(<<1::3>>)
true
"""
@doc guard: true
@spec is_bitstring(term) :: boolean
def is_bitstring(term) do
:erlang.is_bitstring(term)
end
@doc """
Returns `true` if `term` is either the atom `true` or the atom `false` (i.e.,
a boolean); otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_boolean(term) :: boolean
def is_boolean(term) do
:erlang.is_boolean(term)
end
@doc """
Returns `true` if `term` is a floating-point number; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_float(term) :: boolean
def is_float(term) do
:erlang.is_float(term)
end
@doc """
Returns `true` if `term` is a function; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_function(term) :: boolean
def is_function(term) do
:erlang.is_function(term)
end
@doc """
Returns `true` if `term` is a function that can be applied with `arity` number of arguments;
otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> is_function(fn x -> x * 2 end, 1)
true
iex> is_function(fn x -> x * 2 end, 2)
false
"""
@doc guard: true
@spec is_function(term, non_neg_integer) :: boolean
def is_function(term, arity) do
:erlang.is_function(term, arity)
end
@doc """
Returns `true` if `term` is an integer; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_integer(term) :: boolean
def is_integer(term) do
:erlang.is_integer(term)
end
@doc """
Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_list(term) :: boolean
def is_list(term) do
:erlang.is_list(term)
end
@doc """
Returns `true` if `term` is either an integer or a floating-point number;
otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_number(term) :: boolean
def is_number(term) do
:erlang.is_number(term)
end
@doc """
Returns `true` if `term` is a PID (process identifier); otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_pid(term) :: boolean
def is_pid(term) do
:erlang.is_pid(term)
end
@doc """
Returns `true` if `term` is a port identifier; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_port(term) :: boolean
def is_port(term) do
:erlang.is_port(term)
end
@doc """
Returns `true` if `term` is a reference; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_reference(term) :: boolean
def is_reference(term) do
:erlang.is_reference(term)
end
@doc """
Returns `true` if `term` is a tuple; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_tuple(term) :: boolean
def is_tuple(term) do
:erlang.is_tuple(term)
end
@doc """
Returns `true` if `term` is a map; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec is_map(term) :: boolean
def is_map(term) do
:erlang.is_map(term)
end
@doc """
Returns `true` if `key` is a key in `map`; otherwise returns `false`.
It raises `BadMapError` if the first element is not a map.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true, since: "1.10.0"
@spec is_map_key(map, term) :: boolean
def is_map_key(map, key) do
:erlang.is_map_key(key, map)
end
@doc """
Returns the length of `list`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])
9
"""
@doc guard: true
@spec length(list) :: non_neg_integer
def length(list) do
:erlang.length(list)
end
@doc """
Returns an almost unique reference.
The returned reference will re-occur after approximately 2^82 calls;
therefore it is unique enough for practical purposes.
Inlined by the compiler.
## Examples
make_ref()
#=> #Reference<0.0.0.135>
"""
@spec make_ref() :: reference
def make_ref() do
:erlang.make_ref()
end
@doc """
Returns the size of a map.
The size of a map is the number of key-value pairs that the map contains.
This operation happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> map_size(%{a: "foo", b: "bar"})
2
"""
@doc guard: true
@spec map_size(map) :: non_neg_integer
def map_size(map) do
:erlang.map_size(map)
end
@doc """
Returns the biggest of the two given terms according to
Erlang's term ordering.
If the terms compare equal, the first one is returned.
Inlined by the compiler.
## Examples
iex> max(1, 2)
2
iex> max(:a, :b)
:b
Using Erlang's term ordering means that comparisons are
structural and not semantic. For example, when comparing dates:
iex> max(~D[2017-03-31], ~D[2017-04-01])
~D[2017-03-31]
In the example above, `max/2` returned March 31st instead of April 1st
because the structural comparison compares the day before the year. In
such cases it is common for modules to provide functions such as
`Date.compare/2` that perform semantic comparison.
"""
@spec max(first, second) :: first | second when first: term, second: term
def max(first, second) do
:erlang.max(first, second)
end
@doc """
Returns the smallest of the two given terms according to
Erlang's term ordering.
If the terms compare equal, the first one is returned.
Inlined by the compiler.
## Examples
iex> min(1, 2)
1
iex> min("foo", "bar")
"bar"
Using Erlang's term ordering means that comparisons are
structural and not semantic. For example, when comparing dates:
iex> min(~D[2017-03-31], ~D[2017-04-01])
~D[2017-04-01]
In the example above, `min/2` returned April 1st instead of March 31st
because the structural comparison compares the day before the year. In
such cases it is common for modules to provide functions such as
`Date.compare/2` that perform semantic comparison.
"""
@spec min(first, second) :: first | second when first: term, second: term
def min(first, second) do
:erlang.min(first, second)
end
@doc """
Returns an atom representing the name of the local node.
If the node is not alive, `:nonode@nohost` is returned instead.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec node() :: node
def node do
:erlang.node()
end
@doc """
Returns the node where the given argument is located.
The argument can be a PID, a reference, or a port.
If the local node is not alive, `:nonode@nohost` is returned.
Allowed in guard tests. Inlined by the compiler.
"""
@doc guard: true
@spec node(pid | reference | port) :: node
def node(arg) do
:erlang.node(arg)
end
@doc """
Computes the remainder of an integer division.
`rem/2` uses truncated division, which means that
the result will always have the sign of the `dividend`.
Raises an `ArithmeticError` exception if one of the arguments is not an
integer, or when the `divisor` is `0`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> rem(5, 2)
1
iex> rem(6, -4)
2
"""
@doc guard: true
@spec rem(integer, neg_integer | pos_integer) :: integer
def rem(dividend, divisor) do
:erlang.rem(dividend, divisor)
end
@doc """
Rounds a number to the nearest integer.
If the number is equidistant to the two nearest integers, rounds away from zero.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> round(5.6)
6
iex> round(5.2)
5
iex> round(-9.9)
-10
iex> round(-9)
-9
iex> round(2.5)
3
iex> round(-2.5)
-3
"""
@doc guard: true
@spec round(number) :: integer
def round(number) do
:erlang.round(number)
end
@doc """
Sends a message to the given `dest` and returns the message.
`dest` may be a remote or local PID, a local port, a locally
registered name, or a tuple in the form of `{registered_name, node}` for a
registered name at another node.
Inlined by the compiler.
## Examples
iex> send(self(), :hello)
:hello
"""
@spec send(dest :: Process.dest(), message) :: message when message: any
def send(dest, message) do
:erlang.send(dest, message)
end
@doc """
Returns the PID (process identifier) of the calling process.
Allowed in guard clauses. Inlined by the compiler.
"""
@doc guard: true
@spec self() :: pid
def self() do
:erlang.self()
end
@doc """
Spawns the given function and returns its PID.
Typically developers do not use the `spawn` functions, instead they use
abstractions such as `Task`, `GenServer` and `Agent`, built on top of
`spawn`, that spawns processes with more conveniences in terms of
introspection and debugging.
Check the `Process` module for more process-related functions.
The anonymous function receives 0 arguments, and may return any value.
Inlined by the compiler.
## Examples
current = self()
child = spawn(fn -> send(current, {self(), 1 + 2}) end)
receive do
{^child, 3} -> IO.puts("Received 3 back")
end
"""
@spec spawn((() -> any)) :: pid
def spawn(fun) do
:erlang.spawn(fun)
end
@doc """
Spawns the given function `fun` from the given `module` passing it the given
`args` and returns its PID.
Typically developers do not use the `spawn` functions, instead they use
abstractions such as `Task`, `GenServer` and `Agent`, built on top of
`spawn`, that spawns processes with more conveniences in terms of
introspection and debugging.
Check the `Process` module for more process-related functions.
Inlined by the compiler.
## Examples
spawn(SomeModule, :function, [1, 2, 3])
"""
@spec spawn(module, atom, list) :: pid
def spawn(module, fun, args) do
:erlang.spawn(module, fun, args)
end
@doc """
Spawns the given function, links it to the current process, and returns its PID.
Typically developers do not use the `spawn` functions, instead they use
abstractions such as `Task`, `GenServer` and `Agent`, built on top of
`spawn`, that spawns processes with more conveniences in terms of
introspection and debugging.
Check the `Process` module for more process-related functions. For more
information on linking, check `Process.link/1`.
The anonymous function receives 0 arguments, and may return any value.
Inlined by the compiler.
## Examples
current = self()
child = spawn_link(fn -> send(current, {self(), 1 + 2}) end)
receive do
{^child, 3} -> IO.puts("Received 3 back")
end
"""
@spec spawn_link((() -> any)) :: pid
def spawn_link(fun) do
:erlang.spawn_link(fun)
end
@doc """
Spawns the given function `fun` from the given `module` passing it the given
`args`, links it to the current process, and returns its PID.
Typically developers do not use the `spawn` functions, instead they use
abstractions such as `Task`, `GenServer` and `Agent`, built on top of
`spawn`, that spawns processes with more conveniences in terms of
introspection and debugging.
Check the `Process` module for more process-related functions. For more
information on linking, check `Process.link/1`.
Inlined by the compiler.
## Examples
spawn_link(SomeModule, :function, [1, 2, 3])
"""
@spec spawn_link(module, atom, list) :: pid
def spawn_link(module, fun, args) do
:erlang.spawn_link(module, fun, args)
end
@doc """
Spawns the given function, monitors it and returns its PID
and monitoring reference.
Typically developers do not use the `spawn` functions, instead they use
abstractions such as `Task`, `GenServer` and `Agent`, built on top of
`spawn`, that spawns processes with more conveniences in terms of
introspection and debugging.
Check the `Process` module for more process-related functions.
The anonymous function receives 0 arguments, and may return any value.
Inlined by the compiler.
## Examples
current = self()
spawn_monitor(fn -> send(current, {self(), 1 + 2}) end)
"""
@spec spawn_monitor((() -> any)) :: {pid, reference}
def spawn_monitor(fun) do
:erlang.spawn_monitor(fun)
end
@doc """
Spawns the given module and function passing the given args,
monitors it and returns its PID and monitoring reference.
Typically developers do not use the `spawn` functions, instead they use
abstractions such as `Task`, `GenServer` and `Agent`, built on top of
`spawn`, that spawns processes with more conveniences in terms of
introspection and debugging.
Check the `Process` module for more process-related functions.
Inlined by the compiler.
## Examples
spawn_monitor(SomeModule, :function, [1, 2, 3])
"""
@spec spawn_monitor(module, atom, list) :: {pid, reference}
def spawn_monitor(module, fun, args) do
:erlang.spawn_monitor(module, fun, args)
end
@doc """
A non-local return from a function.
Check `Kernel.SpecialForms.try/1` for more information.
Inlined by the compiler.
"""
@spec throw(term) :: no_return
def throw(term) do
:erlang.throw(term)
end
@doc """
Returns the tail of a list. Raises `ArgumentError` if the list is empty.
It works with improper lists.
Allowed in guard tests. Inlined by the compiler.
## Examples
tl([1, 2, 3, :go])
#=> [2, 3, :go]
tl([])
** (ArgumentError) argument error
tl([:one])
#=> []
tl([:a, :b | :c])
#=> [:b | :c]
tl([:a | %{b: 1}])
#=> %{b: 1}
"""
@doc guard: true
@spec tl(nonempty_maybe_improper_list(elem, tail)) :: maybe_improper_list(elem, tail) | tail
when elem: term, tail: term
def tl(list) do
:erlang.tl(list)
end
@doc """
Returns the integer part of `number`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> trunc(5.4)
5
iex> trunc(-5.99)
-5
iex> trunc(-5)
-5
"""
@doc guard: true
@spec trunc(number) :: integer
def trunc(number) do
:erlang.trunc(number)
end
@doc """
Returns the size of a tuple.
This operation happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> tuple_size({:a, :b, :c})
3
"""
@doc guard: true
@spec tuple_size(tuple) :: non_neg_integer
def tuple_size(tuple) do
:erlang.tuple_size(tuple)
end
@doc """
Arithmetic addition.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 + 2
3
"""
@doc guard: true
@spec integer + integer :: integer
@spec float + float :: float
@spec integer + float :: float
@spec float + integer :: float
def left + right do
:erlang.+(left, right)
end
@doc """
Arithmetic subtraction.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 - 2
-1
"""
@doc guard: true
@spec integer - integer :: integer
@spec float - float :: float
@spec integer - float :: float
@spec float - integer :: float
def left - right do
:erlang.-(left, right)
end
@doc """
Arithmetic unary plus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> +1
1
"""
@doc guard: true
@spec +integer :: integer
@spec +float :: float
def +value do
:erlang.+(value)
end
@doc """
Arithmetic unary minus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> -2
-2
"""
@doc guard: true
@spec -0 :: 0
@spec -pos_integer :: neg_integer
@spec -neg_integer :: pos_integer
@spec -float :: float
def -value do
:erlang.-(value)
end
@doc """
Arithmetic multiplication.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 * 2
2
"""
@doc guard: true
@spec integer * integer :: integer
@spec float * float :: float
@spec integer * float :: float
@spec float * integer :: float
def left * right do
:erlang.*(left, right)
end
@doc """
Arithmetic division.
The result is always a float. Use `div/2` and `rem/2` if you want
an integer division or the remainder.
Raises `ArithmeticError` if `right` is 0 or 0.0.
Allowed in guard tests. Inlined by the compiler.
## Examples
1 / 2
#=> 0.5
-3.0 / 2.0
#=> -1.5
5 / 1
#=> 5.0
7 / 0
** (ArithmeticError) bad argument in arithmetic expression
"""
@doc guard: true
@spec number / number :: float
def left / right do
:erlang./(left, right)
end
@doc """
Concatenates a proper list and a term, returning a list.
The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly
appending to lists of arbitrary length, for example, `list ++ [element]`.
Instead, consider prepending via `[element | rest]` and then reversing.
If the `right` operand is not a proper list, it returns an improper list.
If the `left` operand is not a proper list, it raises `ArgumentError`.
Inlined by the compiler.
## Examples
iex> [1] ++ [2, 3]
[1, 2, 3]
iex> 'foo' ++ 'bar'
'foobar'
# returns an improper list
iex> [1] ++ 2
[1 | 2]
# returns a proper list
iex> [1] ++ [2]
[1, 2]
# improper list on the right will return an improper list
iex> [1] ++ [2 | 3]
[1, 2 | 3]
"""
@spec list ++ term :: maybe_improper_list
def left ++ right do
:erlang.++(left, right)
end
@doc """
Removes the first occurrence of an element on the left list
for each element on the right.
The complexity of `a -- b` is proportional to `length(a) * length(b)`,
meaning that it will be very slow if both `a` and `b` are long lists.
In such cases, consider converting each list to a `MapSet` and using
`MapSet.difference/2`.
Inlined by the compiler.
## Examples
iex> [1, 2, 3] -- [1, 2]
[3]
iex> [1, 2, 3, 2, 1] -- [1, 2, 2]
[3, 1]
"""
@spec list -- list :: list
def left -- right do
:erlang.--(left, right)
end
@doc """
Boolean not.
`arg` must be a boolean; if it's not, an `ArgumentError` exception is raised.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> not false
true
"""
@doc guard: true
@spec not true :: false
@spec not false :: true
def not value do
:erlang.not(value)
end
@doc """
Returns `true` if left is less than right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 < 2
true
"""
@doc guard: true
@spec term < term :: boolean
def left < right do
:erlang.<(left, right)
end
@doc """
Returns `true` if left is more than right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 > 2
false
"""
@doc guard: true
@spec term > term :: boolean
def left > right do
:erlang.>(left, right)
end
@doc """
Returns `true` if left is less than or equal to right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 <= 2
true
"""
@doc guard: true
@spec term <= term :: boolean
def left <= right do
:erlang."=<"(left, right)
end
@doc """
Returns `true` if left is more than or equal to right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 >= 2
false
"""
@doc guard: true
@spec term >= term :: boolean
def left >= right do
:erlang.>=(left, right)
end
@doc """
Returns `true` if the two terms are equal.
This operator considers 1 and 1.0 to be equal. For stricter
semantics, use `===/2` instead.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 == 2
false
iex> 1 == 1.0
true
"""
@doc guard: true
@spec term == term :: boolean
def left == right do
:erlang.==(left, right)
end
@doc """
Returns `true` if the two terms are not equal.
This operator considers 1 and 1.0 to be equal. For match
comparison, use `!==/2` instead.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 != 2
true
iex> 1 != 1.0
false
"""
@doc guard: true
@spec term != term :: boolean
def left != right do
:erlang."/="(left, right)
end
@doc """
Returns `true` if the two terms are exactly equal.
The terms are only considered to be exactly equal if they
have the same value and are of the same type. For example,
`1 == 1.0` returns `true`, but since they are of different
types, `1 === 1.0` returns `false`.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 === 2
false
iex> 1 === 1.0
false
"""
@doc guard: true
@spec term === term :: boolean
def left === right do
:erlang."=:="(left, right)
end
@doc """
Returns `true` if the two terms are not exactly equal.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 !== 2
true
iex> 1 !== 1.0
true
"""
@doc guard: true
@spec term !== term :: boolean
def left !== right do
:erlang."=/="(left, right)
end
@doc """
Gets the element at the zero-based `index` in `tuple`.
It raises `ArgumentError` when index is negative or it is out of range of the tuple elements.
Allowed in guard tests. Inlined by the compiler.
## Examples
tuple = {:foo, :bar, 3}
elem(tuple, 1)
#=> :bar
elem({}, 0)
** (ArgumentError) argument error
elem({:foo, :bar}, 2)
** (ArgumentError) argument error
"""
@doc guard: true
@spec elem(tuple, non_neg_integer) :: term
def elem(tuple, index) do
:erlang.element(index + 1, tuple)
end
@doc """
Puts `value` at the given zero-based `index` in `tuple`.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar, 3}
iex> put_elem(tuple, 0, :baz)
{:baz, :bar, 3}
"""
@spec put_elem(tuple, non_neg_integer, term) :: tuple
def put_elem(tuple, index, value) do
:erlang.setelement(index + 1, tuple, value)
end
## Implemented in Elixir
defp optimize_boolean({:case, meta, args}) do
{:case, [{:optimize_boolean, true} | meta], args}
end
@doc """
Boolean or.
If `left` is `true`, returns `true`; otherwise returns `right`.
Requires only the `left` operand to be a boolean since it short-circuits.
If the `left` operand is not a boolean, an `ArgumentError` exception is
raised.
Allowed in guard tests.
## Examples
iex> true or false
true
iex> false or 42
42
"""
@doc guard: true
defmacro left or right do
case __CALLER__.context do
nil -> build_boolean_check(:or, left, true, right)
:match -> invalid_match!(:or)
:guard -> quote(do: :erlang.orelse(unquote(left), unquote(right)))
end
end
@doc """
Boolean and.
If `left` is `false`, returns `false`; otherwise returns `right`.
Requires only the `left` operand to be a boolean since it short-circuits. If
the `left` operand is not a boolean, an `ArgumentError` exception is raised.
Allowed in guard tests.
## Examples
iex> true and false
false
iex> true and "yay!"
"yay!"
"""
@doc guard: true
defmacro left and right do
case __CALLER__.context do
nil -> build_boolean_check(:and, left, right, false)
:match -> invalid_match!(:and)
:guard -> quote(do: :erlang.andalso(unquote(left), unquote(right)))
end
end
defp build_boolean_check(operator, check, true_clause, false_clause) do
optimize_boolean(
quote do
case unquote(check) do
false -> unquote(false_clause)
true -> unquote(true_clause)
other -> :erlang.error({:badbool, unquote(operator), other})
end
end
)
end
@doc """
Boolean not.
Receives any argument (not just booleans) and returns `true` if the argument
is `false` or `nil`; returns `false` otherwise.
Not allowed in guard clauses.
## Examples
iex> !Enum.empty?([])
false
iex> !List.first([])
true
"""
defmacro !value
defmacro !{:!, _, [value]} do
assert_no_match_or_guard_scope(__CALLER__.context, "!")
optimize_boolean(
quote do
case unquote(value) do
x when :"Elixir.Kernel".in(x, [false, nil]) -> false
_ -> true
end
end
)
end
defmacro !value do
assert_no_match_or_guard_scope(__CALLER__.context, "!")
optimize_boolean(
quote do
case unquote(value) do
x when :"Elixir.Kernel".in(x, [false, nil]) -> true
_ -> false
end
end
)
end
@doc """
Concatenates two binaries.
## Examples
iex> "foo" <> "bar"
"foobar"
The `<>/2` operator can also be used in pattern matching (and guard clauses) as
long as the left argument is a literal binary:
iex> "foo" <> x = "foobar"
iex> x
"bar"
`x <> "bar" = "foobar"` would have resulted in a `CompileError` exception.
"""
defmacro left <> right do
concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__)
quote(do: <<unquote_splicing(concats)>>)
end
# Extracts concatenations in order to optimize many
# concatenations into one single clause.
defp extract_concatenations({:<>, _, [left, right]}, caller) do
[wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)]
end
defp extract_concatenations(other, caller) do
[wrap_concatenation(other, :right, caller)]
end
defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do
binary
end
defp wrap_concatenation(literal, _side, _caller)
when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do
:erlang.error(
ArgumentError.exception(
"expected binary argument in <> operator but got: #{Macro.to_string(literal)}"
)
)
end
defp wrap_concatenation(other, side, caller) do
expanded = expand_concat_argument(other, side, caller)
{:"::", [], [expanded, {:binary, [], nil}]}
end
defp expand_concat_argument(arg, :left, %{context: :match} = caller) do
expanded_arg =
case bootstrapped?(Macro) do
true -> Macro.expand(arg, caller)
false -> arg
end
case expanded_arg do
{var, _, nil} when is_atom(var) ->
invalid_concat_left_argument_error(Atom.to_string(var))
{:^, _, [{var, _, nil}]} when is_atom(var) ->
invalid_concat_left_argument_error("^#{Atom.to_string(var)}")
_ ->
expanded_arg
end
end
defp expand_concat_argument(arg, _, _) do
arg
end
defp invalid_concat_left_argument_error(arg) do
:erlang.error(
ArgumentError.exception(
"the left argument of <> operator inside a match should always be a literal " <>
"binary because its size can't be verified. Got: #{arg}"
)
)
end
@doc """
Raises an exception.
If the argument `msg` is a binary, it raises a `RuntimeError` exception
using the given argument as message.
If `msg` is an atom, it just calls `raise/2` with the atom as the first
argument and `[]` as the second argument.
If `msg` is an exception struct, it is raised as is.
If `msg` is anything else, `raise` will fail with an `ArgumentError`
exception.
## Examples
iex> raise "oops"
** (RuntimeError) oops
try do
1 + :foo
rescue
x in [ArithmeticError] ->
IO.puts("that was expected")
raise x
end
"""
defmacro raise(message) do
# Try to figure out the type at compilation time
# to avoid dead code and make Dialyzer happy.
message =
case not is_binary(message) and bootstrapped?(Macro) do
true -> Macro.expand(message, __CALLER__)
false -> message
end
case message do
message when is_binary(message) ->
quote do
:erlang.error(RuntimeError.exception(unquote(message)))
end
{:<<>>, _, _} = message ->
quote do
:erlang.error(RuntimeError.exception(unquote(message)))
end
alias when is_atom(alias) ->
quote do
:erlang.error(unquote(alias).exception([]))
end
_ ->
quote do
:erlang.error(Kernel.Utils.raise(unquote(message)))
end
end
end
@doc """
Raises an exception.
Calls the `exception/1` function on the given argument (which has to be a
module name like `ArgumentError` or `RuntimeError`) passing `attrs` as the
attributes in order to retrieve the exception struct.
Any module that contains a call to the `defexception/1` macro automatically
implements the `c:Exception.exception/1` callback expected by `raise/2`.
For more information, see `defexception/1`.
## Examples
iex> raise(ArgumentError, "Sample")
** (ArgumentError) Sample
"""
defmacro raise(exception, attributes) do
quote do
:erlang.error(unquote(exception).exception(unquote(attributes)))
end
end
@doc """
Raises an exception preserving a previous stacktrace.
Works like `raise/1` but does not generate a new stacktrace.
Notice that `__STACKTRACE__` can be used inside catch/rescue
to retrieve the current stacktrace.
## Examples
try do
raise "oops"
rescue
exception ->
reraise exception, __STACKTRACE__
end
"""
defmacro reraise(message, stacktrace) do
# Try to figure out the type at compilation time
# to avoid dead code and make Dialyzer happy.
case Macro.expand(message, __CALLER__) do
message when is_binary(message) ->
quote do
:erlang.error(
:erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))
)
end
{:<<>>, _, _} = message ->
quote do
:erlang.error(
:erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))
)
end
alias when is_atom(alias) ->
quote do
:erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace)))
end
message ->
quote do
:erlang.error(
:erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace))
)
end
end
end
@doc """
Raises an exception preserving a previous stacktrace.
`reraise/3` works like `reraise/2`, except it passes arguments to the
`exception/1` function as explained in `raise/2`.
## Examples
try do
raise "oops"
rescue
exception ->
reraise WrapperError, [exception: exception], __STACKTRACE__
end
"""
defmacro reraise(exception, attributes, stacktrace) do
quote do
:erlang.raise(
:error,
unquote(exception).exception(unquote(attributes)),
unquote(stacktrace)
)
end
end
@doc """
Matches the term on the `left` against the regular expression or string on the
`right`.
Returns `true` if `left` matches `right` (if it's a regular expression)
or contains `right` (if it's a string).
## Examples
iex> "abcd" =~ ~r/c(d)/
true
iex> "abcd" =~ ~r/e/
false
iex> "abcd" =~ "bc"
true
iex> "abcd" =~ "ad"
false
iex> "abcd" =~ ""
true
"""
@spec String.t() =~ (String.t() | Regex.t()) :: boolean
def left =~ "" when is_binary(left), do: true
def left =~ right when is_binary(left) and is_binary(right) do
:binary.match(left, right) != :nomatch
end
def left =~ right when is_binary(left) do
Regex.match?(right, left)
end
@doc ~S"""
Inspects the given argument according to the `Inspect` protocol.
The second argument is a keyword list with options to control
inspection.
## Options
`inspect/2` accepts a list of options that are internally
translated to an `Inspect.Opts` struct. Check the docs for
`Inspect.Opts` to see the supported options.
## Examples
iex> inspect(:foo)
":foo"
iex> inspect([1, 2, 3, 4, 5], limit: 3)
"[1, 2, 3, ...]"
iex> inspect([1, 2, 3], pretty: true, width: 0)
"[1,\n 2,\n 3]"
iex> inspect("olá" <> <<0>>)
"<<111, 108, 195, 161, 0>>"
iex> inspect("olá" <> <<0>>, binaries: :as_strings)
"\"olá\\0\""
iex> inspect("olá", binaries: :as_binaries)
"<<111, 108, 195, 161>>"
iex> inspect('bar')
"'bar'"
iex> inspect([0 | 'bar'])
"[0, 98, 97, 114]"
iex> inspect(100, base: :octal)
"0o144"
iex> inspect(100, base: :hex)
"0x64"
Note that the `Inspect` protocol does not necessarily return a valid
representation of an Elixir term. In such cases, the inspected result
must start with `#`. For example, inspecting a function will return:
inspect(fn a, b -> a + b end)
#=> #Function<...>
The `Inspect` protocol can be derived to hide certain fields
from structs, so they don't show up in logs, inspects and similar.
See the "Deriving" section of the documentation of the `Inspect`
protocol for more information.
"""
@spec inspect(Inspect.t(), keyword) :: String.t()
def inspect(term, opts \\ []) when is_list(opts) do
opts = struct(Inspect.Opts, opts)
limit =
case opts.pretty do
true -> opts.width
false -> :infinity
end
doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts))
IO.iodata_to_binary(Inspect.Algebra.format(doc, limit))
end
@doc """
Creates and updates a struct.
The `struct` argument may be an atom (which defines `defstruct`)
or a `struct` itself. The second argument is any `Enumerable` that
emits two-element tuples (key-value pairs) during enumeration.
Keys in the `Enumerable` that don't exist in the struct are automatically
discarded. Note that keys must be atoms, as only atoms are allowed when
defining a struct. If keys in the `Enumerable` are duplicated, the last
entry will be taken (same behaviour as `Map.new/1`).
This function is useful for dynamically creating and updating structs, as
well as for converting maps to structs; in the latter case, just inserting
the appropriate `:__struct__` field into the map may not be enough and
`struct/2` should be used instead.
## Examples
defmodule User do
defstruct name: "john"
end
struct(User)
#=> %User{name: "john"}
opts = [name: "meg"]
user = struct(User, opts)
#=> %User{name: "meg"}
struct(user, unknown: "value")
#=> %User{name: "meg"}
struct(User, %{name: "meg"})
#=> %User{name: "meg"}
# String keys are ignored
struct(User, %{"name" => "meg"})
#=> %User{name: "john"}
"""
@spec struct(module | struct, Enum.t()) :: struct
def struct(struct, fields \\ []) do
struct(struct, fields, fn
{:__struct__, _val}, acc ->
acc
{key, val}, acc ->
case acc do
%{^key => _} -> %{acc | key => val}
_ -> acc
end
end)
end
@doc """
Similar to `struct/2` but checks for key validity.
The function `struct!/2` emulates the compile time behaviour
of structs. This means that:
* when building a struct, as in `struct!(SomeStruct, key: :value)`,
it is equivalent to `%SomeStruct{key: :value}` and therefore this
function will check if every given key-value belongs to the struct.
If the struct is enforcing any key via `@enforce_keys`, those will
be enforced as well;
* when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`,
it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this
function will check if every given key-value belongs to the struct.
However, updating structs does not enforce keys, as keys are enforced
only when building;
"""
@spec struct!(module | struct, Enum.t()) :: struct
def struct!(struct, fields \\ [])
def struct!(struct, fields) when is_atom(struct) do
validate_struct!(struct.__struct__(fields), struct, 1)
end
def struct!(struct, fields) when is_map(struct) do
struct(struct, fields, fn
{:__struct__, _}, acc ->
acc
{key, val}, acc ->
Map.replace!(acc, key, val)
end)
end
defp struct(struct, [], _fun) when is_atom(struct) do
validate_struct!(struct.__struct__(), struct, 0)
end
defp struct(struct, fields, fun) when is_atom(struct) do
struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun)
end
defp struct(%_{} = struct, [], _fun) do
struct
end
defp struct(%_{} = struct, fields, fun) do
Enum.reduce(fields, struct, fun)
end
defp validate_struct!(%{__struct__: module} = struct, module, _arity) do
struct
end
defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do
error_message =
"expected struct name returned by #{inspect(module)}.__struct__/#{arity} to be " <>
"#{inspect(module)}, got: #{inspect(struct_name)}"
:erlang.error(ArgumentError.exception(error_message))
end
defp validate_struct!(expr, module, arity) do
error_message =
"expected #{inspect(module)}.__struct__/#{arity} to return a map with a :__struct__ " <>
"key that holds the name of the struct (atom), got: #{inspect(expr)}"
:erlang.error(ArgumentError.exception(error_message))
end
@doc """
Returns true if `term` is a struct; otherwise returns `false`.
Allowed in guard tests.
## Examples
iex> is_struct(URI.parse("/"))
true
iex> is_struct(%{})
false
"""
@doc since: "1.10.0", guard: true
defmacro is_struct(term) do
case __CALLER__.context do
nil ->
quote do
case unquote(term) do
%_{} -> true
_ -> false
end
end
:match ->
invalid_match!(:is_struct)
:guard ->
quote do
is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and
is_atom(:erlang.map_get(:__struct__, unquote(term)))
end
end
end
@doc """
Returns true if `term` is a struct of `name`; otherwise returns `false`.
Allowed in guard tests.
## Examples
iex> is_struct(URI.parse("/"), URI)
true
iex> is_struct(URI.parse("/"), Macro.Env)
false
"""
@doc since: "1.11.0", guard: true
defmacro is_struct(term, name) do
case __CALLER__.context do
nil ->
quote do
case unquote(name) do
name when is_atom(name) ->
case unquote(term) do
%{__struct__: ^name} -> true
_ -> false
end
_ ->
raise ArgumentError
end
end
:match ->
invalid_match!(:is_struct)
:guard ->
quote do
is_map(unquote(term)) and
(is_atom(unquote(name)) or :fail) and
:erlang.is_map_key(:__struct__, unquote(term)) and
:erlang.map_get(:__struct__, unquote(term)) == unquote(name)
end
end
end
@doc """
Gets a value from a nested structure.
Uses the `Access` module to traverse the structures
according to the given `keys`, unless the `key` is a
function, which is detailed in a later section.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["john", :age])
27
In case any of the entries in the middle returns `nil`, `nil` will
be returned as per the `Access` module:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["unknown", :age])
nil
## Functions as keys
If a key is a function, the function will be invoked passing three
arguments:
* the operation (`:get`)
* the data to be accessed
* a function to be invoked next
This means `get_in/2` can be extended to provide custom lookups.
The downside is that functions cannot be stored as keys in the accessed
data structures.
In the example below, we use a function to get all the maps inside
a list:
iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}]
iex> all = fn :get, data, next -> Enum.map(data, next) end
iex> get_in(users, [all, :age])
[27, 23]
If the previous value before invoking the function is `nil`,
the function *will* receive `nil` as a value and must handle it
accordingly.
The `Access` module ships with many convenience accessor functions,
like the `all` anonymous function defined above. See `Access.all/0`,
`Access.key/2`, and others as examples.
"""
@spec get_in(Access.t(), nonempty_list(term)) :: term
def get_in(data, keys)
def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1)
def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t))
def get_in(nil, [_]), do: nil
def get_in(nil, [_ | t]), do: get_in(nil, t)
def get_in(data, [h]), do: Access.get(data, h)
def get_in(data, [h | t]), do: get_in(Access.get(data, h), t)
@doc """
Puts a value in a nested structure.
Uses the `Access` module to traverse the structures
according to the given `keys`, unless the `key` is a
function. If the key is a function, it will be invoked
as specified in `get_and_update_in/3`.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users, ["john", :age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of the entries in the middle returns `nil`,
an error will be raised when trying to access it next.
"""
@spec put_in(Access.t(), nonempty_list(term), term) :: Access.t()
def put_in(data, [_ | _] = keys, value) do
elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)
end
@doc """
Updates a key in a nested structure.
Uses the `Access` module to traverse the structures
according to the given `keys`, unless the `key` is a
function. If the key is a function, it will be invoked
as specified in `get_and_update_in/3`.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users, ["john", :age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of the entries in the middle returns `nil`,
an error will be raised when trying to access it next.
"""
@spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t()
def update_in(data, [_ | _] = keys, fun) when is_function(fun) do
elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1)
end
@doc """
Gets a value and updates a nested structure.
`data` is a nested structure (that is, a map, keyword
list, or struct that implements the `Access` behaviour).
The `fun` argument receives the value of `key` (or `nil` if `key`
is not present) and must return one of the following values:
* a two-element tuple `{get_value, new_value}`. In this case,
`get_value` is the retrieved value which can possibly be operated on before
being returned. `new_value` is the new value to be stored under `key`.
* `:pop`, which implies that the current value under `key`
should be removed from the structure and returned.
This function uses the `Access` module to traverse the structures
according to the given `keys`, unless the `key` is a function,
which is detailed in a later section.
## Examples
This function is useful when there is a need to retrieve the current
value (or something calculated in function of the current value) and
update it at the same time. For example, it could be used to read the
current age of a user while increasing it by one in one pass:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1})
{27, %{"john" => %{age: 28}, "meg" => %{age: 23}}}
## Functions as keys
If a key is a function, the function will be invoked passing three
arguments:
* the operation (`:get_and_update`)
* the data to be accessed
* a function to be invoked next
This means `get_and_update_in/3` can be extended to provide custom
lookups. The downside is that functions cannot be stored as keys
in the accessed data structures.
When one of the keys is a function, the function is invoked.
In the example below, we use a function to get and increment all
ages inside a list:
iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}]
iex> all = fn :get_and_update, data, next ->
...> data |> Enum.map(next) |> Enum.unzip()
...> end
iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})
{[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]}
If the previous value before invoking the function is `nil`,
the function *will* receive `nil` as a value and must handle it
accordingly (be it by failing or providing a sane default).
The `Access` module ships with many convenience accessor functions,
like the `all` anonymous function defined above. See `Access.all/0`,
`Access.key/2`, and others as examples.
"""
@spec get_and_update_in(
structure :: Access.t(),
keys,
(term -> {get_value, update_value} | :pop)
) :: {get_value, structure :: Access.t()}
when keys: nonempty_list(any),
get_value: var,
update_value: term
def get_and_update_in(data, keys, fun)
def get_and_update_in(data, [head], fun) when is_function(head, 3),
do: head.(:get_and_update, data, fun)
def get_and_update_in(data, [head | tail], fun) when is_function(head, 3),
do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun))
def get_and_update_in(data, [head], fun) when is_function(fun, 1),
do: Access.get_and_update(data, head, fun)
def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1),
do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun))
@doc """
Pops a key from the given nested structure.
Uses the `Access` protocol to traverse the structures
according to the given `keys`, unless the `key` is a
function. If the key is a function, it will be invoked
as specified in `get_and_update_in/3`.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> pop_in(users, ["john", :age])
{27, %{"john" => %{}, "meg" => %{age: 23}}}
In case any entry returns `nil`, its key will be removed
and the deletion will be considered a success.
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> pop_in(users, ["jane", :age])
{nil, %{"john" => %{age: 27}, "meg" => %{age: 23}}}
"""
@spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data}
when data: Access.container()
def pop_in(data, keys)
def pop_in(nil, [key | _]) do
raise ArgumentError, "could not pop key #{inspect(key)} on a nil value"
end
def pop_in(data, [_ | _] = keys) do
pop_in_data(data, keys)
end
defp pop_in_data(nil, [_ | _]), do: :pop
defp pop_in_data(data, [fun]) when is_function(fun),
do: fun.(:get_and_update, data, fn _ -> :pop end)
defp pop_in_data(data, [fun | tail]) when is_function(fun),
do: fun.(:get_and_update, data, &pop_in_data(&1, tail))
defp pop_in_data(data, [key]), do: Access.pop(data, key)
defp pop_in_data(data, [key | tail]),
do: Access.get_and_update(data, key, &pop_in_data(&1, tail))
@doc """
Puts a value in a nested structure via the given `path`.
This is similar to `put_in/3`, except the path is extracted via
a macro rather than passing a list. For example:
put_in(opts[:foo][:bar], :baz)
Is equivalent to:
put_in(opts, [:foo, :bar], :baz)
This also works with nested structs and the `struct.path.to.value` way to specify
paths:
put_in(struct.foo.bar, :baz)
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check `get_and_update_in/2` docs.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"][:age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"].age, 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
"""
defmacro put_in(path, value) do
case unnest(path, [], true, "put_in/2") do
{[h | t], true} ->
nest_update_in(h, t, quote(do: fn _ -> unquote(value) end))
{[h | t], false} ->
expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end))
quote(do: :erlang.element(2, unquote(expr)))
end
end
@doc """
Pops a key from the nested structure via the given `path`.
This is similar to `pop_in/2`, except the path is extracted via
a macro rather than passing a list. For example:
pop_in(opts[:foo][:bar])
Is equivalent to:
pop_in(opts, [:foo, :bar])
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check `get_and_update_in/2` docs.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> pop_in(users["john"][:age])
{27, %{"john" => %{}, "meg" => %{age: 23}}}
iex> users = %{john: %{age: 27}, meg: %{age: 23}}
iex> pop_in(users.john[:age])
{27, %{john: %{}, meg: %{age: 23}}}
In case any entry returns `nil`, its key will be removed
and the deletion will be considered a success.
"""
defmacro pop_in(path) do
{[h | t], _} = unnest(path, [], true, "pop_in/1")
nest_pop_in(:map, h, t)
end
@doc """
Updates a nested structure via the given `path`.
This is similar to `update_in/3`, except the path is extracted via
a macro rather than passing a list. For example:
update_in(opts[:foo][:bar], &(&1 + 1))
Is equivalent to:
update_in(opts, [:foo, :bar], &(&1 + 1))
This also works with nested structs and the `struct.path.to.value` way to specify
paths:
update_in(struct.foo.bar, &(&1 + 1))
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check `get_and_update_in/2` docs.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users["john"][:age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users["john"].age, &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
"""
defmacro update_in(path, fun) do
case unnest(path, [], true, "update_in/2") do
{[h | t], true} ->
nest_update_in(h, t, fun)
{[h | t], false} ->
expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end))
quote(do: :erlang.element(2, unquote(expr)))
end
end
@doc """
Gets a value and updates a nested data structure via the given `path`.
This is similar to `get_and_update_in/3`, except the path is extracted
via a macro rather than passing a list. For example:
get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1})
Is equivalent to:
get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1})
This also works with nested structs and the `struct.path.to.value` way to specify
paths:
get_and_update_in(struct.foo.bar, &{&1, &1 + 1})
Note that in order for this macro to work, the complete path must always
be visible by this macro. See the "Paths" section below.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_and_update_in(users["john"].age, &{&1, &1 + 1})
{27, %{"john" => %{age: 28}, "meg" => %{age: 23}}}
## Paths
A path may start with a variable, local or remote call, and must be
followed by one or more:
* `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil,
`nil` is returned
* `foo.bar` - accesses a map/struct field; in case the field is not
present, an error is raised
Here are some valid paths:
users["john"][:age]
users["john"].age
User.all()["john"].age
all_users()["john"].age
Here are some invalid ones:
# Does a remote call after the initial value
users["john"].do_something(arg1, arg2)
# Does not access any key or field
users
"""
defmacro get_and_update_in(path, fun) do
{[h | t], _} = unnest(path, [], true, "get_and_update_in/2")
nest_get_and_update_in(h, t, fun)
end
defp nest_update_in([], fun), do: fun
defp nest_update_in(list, fun) do
quote do
fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end
end
end
defp nest_update_in(h, [{:map, key} | t], fun) do
quote do
Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun)))
end
end
defp nest_get_and_update_in([], fun), do: fun
defp nest_get_and_update_in(list, fun) do
quote do
fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end
end
end
defp nest_get_and_update_in(h, [{:access, key} | t], fun) do
quote do
Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))
end
end
defp nest_get_and_update_in(h, [{:map, key} | t], fun) do
quote do
Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))
end
end
defp nest_pop_in(kind, list) do
quote do
fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end
end
end
defp nest_pop_in(:map, h, [{:access, key}]) do
quote do
case unquote(h) do
nil -> {nil, nil}
h -> Access.pop(h, unquote(key))
end
end
end
defp nest_pop_in(_, _, [{:map, key}]) do
raise ArgumentError,
"cannot use pop_in when the last segment is a map/struct field. " <>
"This would effectively remove the field #{inspect(key)} from the map/struct"
end
defp nest_pop_in(_, h, [{:map, key} | t]) do
quote do
Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t)))
end
end
defp nest_pop_in(_, h, [{:access, key}]) do
quote do
case unquote(h) do
nil -> :pop
h -> Access.pop(h, unquote(key))
end
end
end
defp nest_pop_in(_, h, [{:access, key} | t]) do
quote do
Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t)))
end
end
defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do
unnest(expr, [{:access, key} | acc], false, kind)
end
defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind)
when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and
:erlang.element(1, expr) != :__MODULE__ do
unnest(expr, [{:map, key} | acc], all_map?, kind)
end
defp unnest(other, [], _all_map?, kind) do
raise ArgumentError,
"expected expression given to #{kind} to access at least one element, " <>
"got: #{Macro.to_string(other)}"
end
defp unnest(other, acc, all_map?, kind) do
case proper_start?(other) do
true ->
{[other | acc], all_map?}
false ->
raise ArgumentError,
"expression given to #{kind} must start with a variable, local or remote call " <>
"and be followed by an element access, got: #{Macro.to_string(other)}"
end
end
defp proper_start?({{:., _, [expr, _]}, _, _args})
when is_atom(expr)
when :erlang.element(1, expr) == :__aliases__
when :erlang.element(1, expr) == :__MODULE__,
do: true
defp proper_start?({atom, _, _args})
when is_atom(atom),
do: true
defp proper_start?(other), do: not is_tuple(other)
@doc """
Converts the argument to a string according to the
`String.Chars` protocol.
This is the function invoked when there is string interpolation.
## Examples
iex> to_string(:foo)
"foo"
"""
defmacro to_string(term) do
quote(do: :"Elixir.String.Chars".to_string(unquote(term)))
end
@doc """
Converts the given term to a charlist according to the `List.Chars` protocol.
## Examples
iex> to_charlist(:foo)
'foo'
"""
defmacro to_charlist(term) do
quote(do: List.Chars.to_charlist(unquote(term)))
end
@doc """
Returns `true` if `term` is `nil`, `false` otherwise.
Allowed in guard clauses.
## Examples
iex> is_nil(1)
false
iex> is_nil(nil)
true
"""
@doc guard: true
defmacro is_nil(term) do
quote(do: unquote(term) == nil)
end
@doc """
A convenience macro that checks if the right side (an expression) matches the
left side (a pattern).
## Examples
iex> match?(1, 1)
true
iex> match?({1, _}, {1, 2})
true
iex> map = %{a: 1, b: 2}
iex> match?(%{a: _}, map)
true
iex> a = 1
iex> match?(^a, 1)
true
`match?/2` is very useful when filtering or finding a value in an enumerable:
iex> list = [a: 1, b: 2, a: 3]
iex> Enum.filter(list, &match?({:a, _}, &1))
[a: 1, a: 3]
Guard clauses can also be given to the match:
iex> list = [a: 1, b: 2, a: 3]
iex> Enum.filter(list, &match?({:a, x} when x < 2, &1))
[a: 1]
However, variables assigned in the match will not be available
outside of the function call (unlike regular pattern matching with the `=`
operator):
iex> match?(_x, 1)
true
iex> binding()
[]
"""
defmacro match?(pattern, expr) do
success =
quote do
unquote(pattern) -> true
end
failure =
quote generated: true do
_ -> false
end
{:case, [], [expr, [do: success ++ failure]]}
end
@doc """
Reads and writes attributes of the current module.
The canonical example for attributes is annotating that a module
implements an OTP behaviour, such as `GenServer`:
defmodule MyServer do
@behaviour GenServer
# ... callbacks ...
end
By default Elixir supports all the module attributes supported by Erlang, but
custom attributes can be used as well:
defmodule MyServer do
@my_data 13
IO.inspect(@my_data)
#=> 13
end
Unlike Erlang, such attributes are not stored in the module by default since
it is common in Elixir to use custom attributes to store temporary data that
will be available at compile-time. Custom attributes may be configured to
behave closer to Erlang by using `Module.register_attribute/3`.
Finally, notice that attributes can also be read inside functions:
defmodule MyServer do
@my_data 11
def first_data, do: @my_data
@my_data 13
def second_data, do: @my_data
end
MyServer.first_data()
#=> 11
MyServer.second_data()
#=> 13
It is important to note that reading an attribute takes a snapshot of
its current value. In other words, the value is read at compilation
time and not at runtime. Check the `Module` module for other functions
to manipulate module attributes.
"""
defmacro @expr
defmacro @{:__aliases__, _meta, _args} do
raise ArgumentError, "module attributes set via @ cannot start with an uppercase letter"
end
defmacro @{name, meta, args} do
assert_module_scope(__CALLER__, :@, 1)
function? = __CALLER__.function != nil
cond do
# Check for Macro as it is compiled later than Kernel
not bootstrapped?(Macro) ->
nil
not function? and __CALLER__.context == :match ->
raise ArgumentError,
"invalid write attribute syntax, you probably meant to use: @#{name} expression"
# Typespecs attributes are currently special cased by the compiler
is_list(args) and typespec?(name) ->
case bootstrapped?(Kernel.Typespec) do
false ->
:ok
true ->
pos = :elixir_locals.cache_env(__CALLER__)
%{line: line, file: file, module: module} = __CALLER__
quote do
Kernel.Typespec.deftypespec(
unquote(name),
unquote(Macro.escape(hd(args), unquote: true)),
unquote(line),
unquote(file),
unquote(module),
unquote(pos)
)
end
end
true ->
do_at(args, meta, name, function?, __CALLER__)
end
end
# @attribute(value)
defp do_at([arg], meta, name, function?, env) do
line =
case :lists.keymember(:context, 1, meta) do
true -> nil
false -> env.line
end
cond do
function? ->
raise ArgumentError, "cannot set attribute @#{name} inside function/macro"
name == :behavior ->
warn_message = "@behavior attribute is not supported, please use @behaviour instead"
IO.warn(warn_message, Macro.Env.stacktrace(env))
:lists.member(name, [:moduledoc, :typedoc, :doc]) ->
arg = {env.line, arg}
quote do
Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line))
end
true ->
quote do
Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line))
end
end
end
# @attribute or @attribute()
defp do_at(args, _meta, name, function?, env) when is_atom(args) or args == [] do
line = env.line
doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc])
case function? do
true ->
value =
case Module.__get_attribute__(env.module, name, line) do
{_, doc} when doc_attr? -> doc
other -> other
end
try do
:elixir_quote.escape(value, :default, false)
rescue
ex in [ArgumentError] ->
raise ArgumentError,
"cannot inject attribute @#{name} into function/macro because " <>
Exception.message(ex)
end
false when doc_attr? ->
quote do
case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do
{_, doc} -> doc
other -> other
end
end
false ->
quote do
Module.__get_attribute__(__MODULE__, unquote(name), unquote(line))
end
end
end
# All other cases
defp do_at(args, _meta, name, _function?, _env) do
raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}"
end
defp typespec?(:type), do: true
defp typespec?(:typep), do: true
defp typespec?(:opaque), do: true
defp typespec?(:spec), do: true
defp typespec?(:callback), do: true
defp typespec?(:macrocallback), do: true
defp typespec?(_), do: false
@doc """
Returns the binding for the given context as a keyword list.
In the returned result, keys are variable names and values are the
corresponding variable values.
If the given `context` is `nil` (by default it is), the binding for the
current context is returned.
## Examples
iex> x = 1
iex> binding()
[x: 1]
iex> x = 2
iex> binding()
[x: 2]
iex> binding(:foo)
[]
iex> var!(x, :foo) = 1
1
iex> binding(:foo)
[x: 1]
"""
defmacro binding(context \\ nil) do
in_match? = Macro.Env.in_match?(__CALLER__)
bindings =
for {v, c} <- Macro.Env.vars(__CALLER__), c == context do
{v, wrap_binding(in_match?, {v, [generated: true], c})}
end
:lists.sort(bindings)
end
defp wrap_binding(true, var) do
quote(do: ^unquote(var))
end
defp wrap_binding(_, var) do
var
end
@doc """
Provides an `if/2` macro.
This macro expects the first argument to be a condition and the second
argument to be a keyword list.
## One-liner examples
if(foo, do: bar)
In the example above, `bar` will be returned if `foo` evaluates to
a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be
returned.
An `else` option can be given to specify the opposite:
if(foo, do: bar, else: baz)
## Blocks examples
It's also possible to pass a block to the `if/2` macro. The first
example above would be translated to:
if foo do
bar
end
Note that `do/end` become delimiters. The second example would
translate to:
if foo do
bar
else
baz
end
In order to compare more than two clauses, the `cond/1` macro has to be used.
"""
defmacro if(condition, clauses) do
build_if(condition, clauses)
end
defp build_if(condition, do: do_clause) do
build_if(condition, do: do_clause, else: nil)
end
defp build_if(condition, do: do_clause, else: else_clause) do
optimize_boolean(
quote do
case unquote(condition) do
x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(else_clause)
_ -> unquote(do_clause)
end
end
)
end
defp build_if(_condition, _arguments) do
raise ArgumentError,
"invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted"
end
@doc """
Provides an `unless` macro.
This macro evaluates and returns the `do` block passed in as the second
argument if `condition` evaluates to a falsy value (`false` or `nil`).
Otherwise, it returns the value of the `else` block if present or `nil` if not.
See also `if/2`.
## Examples
iex> unless(Enum.empty?([]), do: "Hello")
nil
iex> unless(Enum.empty?([1, 2, 3]), do: "Hello")
"Hello"
iex> unless Enum.sum([2, 2]) == 5 do
...> "Math still works"
...> else
...> "Math is broken"
...> end
"Math still works"
"""
defmacro unless(condition, clauses) do
build_unless(condition, clauses)
end
defp build_unless(condition, do: do_clause) do
build_unless(condition, do: do_clause, else: nil)
end
defp build_unless(condition, do: do_clause, else: else_clause) do
quote do
if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause))
end
end
defp build_unless(_condition, _arguments) do
raise ArgumentError,
"invalid or duplicate keys for unless, " <>
"only \"do\" and an optional \"else\" are permitted"
end
@doc """
Destructures two lists, assigning each term in the
right one to the matching term in the left one.
Unlike pattern matching via `=`, if the sizes of the left
and right lists don't match, destructuring simply stops
instead of raising an error.
## Examples
iex> destructure([x, y, z], [1, 2, 3, 4, 5])
iex> {x, y, z}
{1, 2, 3}
In the example above, even though the right list has more entries than the
left one, destructuring works fine. If the right list is smaller, the
remaining elements are simply set to `nil`:
iex> destructure([x, y, z], [1])
iex> {x, y, z}
{1, nil, nil}
The left-hand side supports any expression you would use
on the left-hand side of a match:
x = 1
destructure([^x, y, z], [1, 2, 3])
The example above will only work if `x` matches the first value in the right
list. Otherwise, it will raise a `MatchError` (like the `=` operator would
do).
"""
defmacro destructure(left, right) when is_list(left) do
quote do
unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left)))
end
end
@doc """
Returns a range with the specified `first` and `last` integers.
If last is larger than first, the range will be increasing from
first to last. If first is larger than last, the range will be
decreasing from first to last. If first is equal to last, the range
will contain one element, which is the number itself.
## Examples
iex> 0 in 1..3
false
iex> 1 in 1..3
true
iex> 2 in 1..3
true
iex> 3 in 1..3
true
"""
defmacro first..last do
case bootstrapped?(Macro) do
true ->
first = Macro.expand(first, __CALLER__)
last = Macro.expand(last, __CALLER__)
range(__CALLER__.context, first, last)
false ->
range(__CALLER__.context, first, last)
end
end
defp range(_context, first, last) when is_integer(first) and is_integer(last) do
{:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}
end
defp range(_context, first, last)
when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or
is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do
raise ArgumentError,
"ranges (first..last) expect both sides to be integers, " <>
"got: #{Macro.to_string({:.., [], [first, last]})}"
end
defp range(nil, first, last) do
quote(do: Elixir.Range.new(unquote(first), unquote(last)))
end
defp range(_, first, last) do
{:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}
end
@doc """
Provides a short-circuit operator that evaluates and returns
the second expression only if the first one evaluates to a truthy value
(neither `false` nor `nil`). Returns the first expression
otherwise.
Not allowed in guard clauses.
## Examples
iex> Enum.empty?([]) && Enum.empty?([])
true
iex> List.first([]) && true
nil
iex> Enum.empty?([]) && List.first([1])
1
iex> false && throw(:bad)
false
Note that, unlike `and/2`, this operator accepts any expression
as the first argument, not only booleans.
"""
defmacro left && right do
assert_no_match_or_guard_scope(__CALLER__.context, "&&")
quote do
case unquote(left) do
x when :"Elixir.Kernel".in(x, [false, nil]) ->
x
_ ->
unquote(right)
end
end
end
@doc """
Provides a short-circuit operator that evaluates and returns the second
expression only if the first one does not evaluate to a truthy value (that is,
it is either `nil` or `false`). Returns the first expression otherwise.
Not allowed in guard clauses.
## Examples
iex> Enum.empty?([1]) || Enum.empty?([1])
false
iex> List.first([]) || true
true
iex> Enum.empty?([1]) || 1
1
iex> Enum.empty?([]) || throw(:bad)
true
Note that, unlike `or/2`, this operator accepts any expression
as the first argument, not only booleans.
"""
defmacro left || right do
assert_no_match_or_guard_scope(__CALLER__.context, "||")
quote do
case unquote(left) do
x when :"Elixir.Kernel".in(x, [false, nil]) ->
unquote(right)
x ->
x
end
end
end
@doc """
Pipe operator.
This operator introduces the expression on the left-hand side as
the first argument to the function call on the right-hand side.
## Examples
iex> [1, [2], 3] |> List.flatten()
[1, 2, 3]
The example above is the same as calling `List.flatten([1, [2], 3])`.
The `|>` operator is mostly useful when there is a desire to execute a series
of operations resembling a pipeline:
iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end)
[2, 4, 6]
In the example above, the list `[1, [2], 3]` is passed as the first argument
to the `List.flatten/1` function, then the flattened list is passed as the
first argument to the `Enum.map/2` function which doubles each element of the
list.
In other words, the expression above simply translates to:
Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)
## Pitfalls
There are two common pitfalls when using the pipe operator.
The first one is related to operator precedence. For example,
the following expression:
String.graphemes "Hello" |> Enum.reverse
Translates to:
String.graphemes("Hello" |> Enum.reverse())
which results in an error as the `Enumerable` protocol is not defined
for binaries. Adding explicit parentheses resolves the ambiguity:
String.graphemes("Hello") |> Enum.reverse()
Or, even better:
"Hello" |> String.graphemes() |> Enum.reverse()
The second pitfall is that the `|>` operator works on calls.
For example, when you write:
"Hello" |> some_function()
Elixir sees the right-hand side is a function call and pipes
to it. This means that, if you want to pipe to an anonymous
or captured function, it must also be explicitly called.
Given the anonymous function:
fun = fn x -> IO.puts(x) end
fun.("Hello")
This won't work as it will rather try to invoke the local
function `fun`:
"Hello" |> fun()
This works:
"Hello" |> fun.()
As you can see, the `|>` operator retains the same semantics
as when the pipe is not used since both require the `fun.(...)`
notation.
"""
defmacro left |> right do
[{h, _} | t] = Macro.unpipe({:|>, [], [left, right]})
fun = fn {x, pos}, acc ->
Macro.pipe(acc, x, pos)
end
:lists.foldl(fun, h, t)
end
@doc """
Returns `true` if `module` is loaded and contains a
public `function` with the given `arity`, otherwise `false`.
Note that this function does not load the module in case
it is not loaded. Check `Code.ensure_loaded/1` for more
information.
Inlined by the compiler.
## Examples
iex> function_exported?(Enum, :map, 2)
true
iex> function_exported?(Enum, :map, 10)
false
iex> function_exported?(List, :to_string, 1)
true
"""
@spec function_exported?(module, atom, arity) :: boolean
def function_exported?(module, function, arity) do
:erlang.function_exported(module, function, arity)
end
@doc """
Returns `true` if `module` is loaded and contains a
public `macro` with the given `arity`, otherwise `false`.
Note that this function does not load the module in case
it is not loaded. Check `Code.ensure_loaded/1` for more
information.
If `module` is an Erlang module (as opposed to an Elixir module), this
function always returns `false`.
## Examples
iex> macro_exported?(Kernel, :use, 2)
true
iex> macro_exported?(:erlang, :abs, 1)
false
"""
@spec macro_exported?(module, atom, arity) :: boolean
def macro_exported?(module, macro, arity)
when is_atom(module) and is_atom(macro) and is_integer(arity) and
(arity >= 0 and arity <= 255) do
function_exported?(module, :__info__, 1) and
:lists.member({macro, arity}, module.__info__(:macros))
end
@doc """
Checks if the element on the left-hand side is a member of the
collection on the right-hand side.
## Examples
iex> x = 1
iex> x in [1, 2, 3]
true
This operator (which is a macro) simply translates to a call to
`Enum.member?/2`. The example above would translate to:
Enum.member?([1, 2, 3], x)
Elixir also supports `left not in right`, which evaluates to
`not(left in right)`:
iex> x = 1
iex> x not in [1, 2, 3]
false
## Guards
The `in/2` operator (as well as `not in`) can be used in guard clauses as
long as the right-hand side is a range or a list. In such cases, Elixir will
expand the operator to a valid guard expression. For example:
when x in [1, 2, 3]
translates to:
when x === 1 or x === 2 or x === 3
When using ranges:
when x in 1..3
translates to:
when is_integer(x) and x >= 1 and x <= 3
Note that only integers can be considered inside a range by `in`.
### AST considerations
`left not in right` is parsed by the compiler into the AST:
{:not, _, [{:in, _, [left, right]}]}
This is the same AST as `not(left in right)`.
Additionally, `Macro.to_string/2` will translate all occurrences of
this AST to `left not in right`.
"""
@doc guard: true
defmacro left in right do
in_module? = __CALLER__.context == nil
expand =
case bootstrapped?(Macro) do
true -> &Macro.expand(&1, __CALLER__)
false -> & &1
end
case expand.(right) do
[] when not in_module? ->
false
[] ->
quote do
_ = unquote(left)
false
end
[head | tail] = list when not in_module? ->
in_var(in_module?, left, &in_list(&1, head, tail, expand, list, in_module?))
[_ | _] = list when in_module? ->
case ensure_evaled(list, {0, []}, expand) do
{[head | tail], {_, []}} ->
in_var(in_module?, left, &in_list(&1, head, tail, expand, list, in_module?))
{[head | tail], {_, vars_values}} ->
{vars, values} = :lists.unzip(:lists.reverse(vars_values))
is_in_list = &in_list(&1, head, tail, expand, list, in_module?)
quote do
{unquote_splicing(vars)} = {unquote_splicing(values)}
unquote(in_var(in_module?, left, is_in_list))
end
end
{:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last]} ->
in_var(in_module?, left, &in_range(&1, expand.(first), expand.(last)))
right when in_module? ->
quote(do: Elixir.Enum.member?(unquote(right), unquote(left)))
%{__struct__: Elixir.Range, first: _, last: _} ->
raise ArgumentError, "non-literal range in guard should be escaped with Macro.escape/2"
right ->
raise_on_invalid_args_in_2(right)
end
end
defp raise_on_invalid_args_in_2(right) do
raise ArgumentError, <<
"invalid right argument for operator \"in\", it expects a compile-time proper list ",
"or compile-time range on the right side when used in guard expressions, got: ",
Macro.to_string(right)::binary
>>
end
defp in_var(false, ast, fun), do: fun.(ast)
defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context),
do: fun.(var)
defp in_var(true, ast, fun) do
quote do
var = unquote(ast)
unquote(fun.(quote(do: var)))
end
end
# Called as ensure_evaled(list, {0, []}). Note acc is reversed.
defp ensure_evaled(list, acc, expand) do
fun = fn
{:|, meta, [head, tail]}, acc ->
{head, acc} = ensure_evaled_element(head, acc)
{tail, acc} = ensure_evaled_tail(expand.(tail), acc, expand)
{{:|, meta, [head, tail]}, acc}
elem, acc ->
ensure_evaled_element(elem, acc)
end
:lists.mapfoldl(fun, acc, list)
end
defp ensure_evaled_element(elem, acc)
when is_number(elem) or is_atom(elem) or is_binary(elem) do
{elem, acc}
end
defp ensure_evaled_element(elem, acc) do
ensure_evaled_var(elem, acc)
end
defp ensure_evaled_tail(elem, acc, expand) when is_list(elem) do
ensure_evaled(elem, acc, expand)
end
defp ensure_evaled_tail(elem, acc, _expand) do
ensure_evaled_var(elem, acc)
end
defp ensure_evaled_var(elem, {index, ast}) do
var = {String.to_atom("arg" <> Integer.to_string(index)), [], __MODULE__}
{var, {index + 1, [{var, elem} | ast]}}
end
defp in_range(left, first, last) do
case is_integer(first) and is_integer(last) do
true ->
in_range_literal(left, first, last)
false ->
quote do
:erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and
:erlang.is_integer(unquote(last)) and
((:erlang."=<"(unquote(first), unquote(last)) and
unquote(increasing_compare(left, first, last))) or
(:erlang.<(unquote(last), unquote(first)) and
unquote(decreasing_compare(left, first, last))))
end
end
end
defp in_range_literal(left, first, first) do
quote do
:erlang."=:="(unquote(left), unquote(first))
end
end
defp in_range_literal(left, first, last) when first < last do
quote do
:erlang.andalso(
:erlang.is_integer(unquote(left)),
unquote(increasing_compare(left, first, last))
)
end
end
defp in_range_literal(left, first, last) do
quote do
:erlang.andalso(
:erlang.is_integer(unquote(left)),
unquote(decreasing_compare(left, first, last))
)
end
end
defp in_list(left, head, tail, expand, right, in_module?) do
[head | tail] =
:lists.foldl(
&[comp(left, &1, expand, right, in_module?) | &2],
[],
[head | tail]
)
:lists.foldl("e(do: :erlang.orelse(unquote(&1), unquote(&2))), head, tail)
end
defp comp(left, {:|, _, [head, tail]}, expand, right, in_module?) do
case expand.(tail) do
[] ->
quote(do: :erlang."=:="(unquote(left), unquote(head)))
[tail_head | tail] ->
quote do
:erlang.orelse(
:erlang."=:="(unquote(left), unquote(head)),
unquote(in_list(left, tail_head, tail, expand, right, in_module?))
)
end
tail when in_module? ->
quote do
:erlang.orelse(
:erlang."=:="(unquote(left), unquote(head)),
:lists.member(unquote(left), unquote(tail))
)
end
_ ->
raise_on_invalid_args_in_2(right)
end
end
defp comp(left, right, _expand, _right, _in_module?) do
quote(do: :erlang."=:="(unquote(left), unquote(right)))
end
defp increasing_compare(var, first, last) do
quote do
:erlang.andalso(
:erlang.>=(unquote(var), unquote(first)),
:erlang."=<"(unquote(var), unquote(last))
)
end
end
defp decreasing_compare(var, first, last) do
quote do
:erlang.andalso(
:erlang."=<"(unquote(var), unquote(first)),
:erlang.>=(unquote(var), unquote(last))
)
end
end
@doc """
When used inside quoting, marks that the given variable should
not be hygienized.
The argument can be either a variable unquoted or in standard tuple form
`{name, meta, context}`.
Check `Kernel.SpecialForms.quote/2` for more information.
"""
defmacro var!(var, context \\ nil)
defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do
# Remove counter and force them to be vars
meta = :lists.keydelete(:counter, 1, meta)
meta = :lists.keystore(:var, 1, meta, {:var, true})
case Macro.expand(context, __CALLER__) do
context when is_atom(context) ->
{name, meta, context}
other ->
raise ArgumentError,
"expected var! context to expand to an atom, got: #{Macro.to_string(other)}"
end
end
defmacro var!(other, _context) do
raise ArgumentError, "expected a variable to be given to var!, got: #{Macro.to_string(other)}"
end
@doc """
When used inside quoting, marks that the given alias should not
be hygienized. This means the alias will be expanded when
the macro is expanded.
Check `Kernel.SpecialForms.quote/2` for more information.
"""
defmacro alias!(alias) when is_atom(alias) do
alias
end
defmacro alias!({:__aliases__, meta, args}) do
# Simply remove the alias metadata from the node
# so it does not affect expansion.
{:__aliases__, :lists.keydelete(:alias, 1, meta), args}
end
## Definitions implemented in Elixir
@doc ~S"""
Defines a module given by name with the given contents.
This macro defines a module with the given `alias` as its name and with the
given contents. It returns a tuple with four elements:
* `:module`
* the module name
* the binary contents of the module
* the result of evaluating the contents block
## Examples
defmodule Number do
def one, do: 1
def two, do: 2
end
#=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}}
Number.one()
#=> 1
Number.two()
#=> 2
## Nesting
Nesting a module inside another module affects the name of the nested module:
defmodule Foo do
defmodule Bar do
end
end
In the example above, two modules - `Foo` and `Foo.Bar` - are created.
When nesting, Elixir automatically creates an alias to the inner module,
allowing the second module `Foo.Bar` to be accessed as `Bar` in the same
lexical scope where it's defined (the `Foo` module). This only happens
if the nested module is defined via an alias.
If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in
the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or
an alias has to be explicitly set in the `Foo` module with the help of
`Kernel.SpecialForms.alias/2`.
defmodule Foo.Bar do
# code
end
defmodule Foo do
alias Foo.Bar
# code here can refer to "Foo.Bar" as just "Bar"
end
## Dynamic names
Elixir module names can be dynamically generated. This is very
useful when working with macros. For instance, one could write:
defmodule String.to_atom("Foo#{1}") do
# contents ...
end
Elixir will accept any module name as long as the expression passed as the
first argument to `defmodule/2` evaluates to an atom.
Note that, when a dynamic name is used, Elixir won't nest the name under
the current module nor automatically set up an alias.
## Reserved module names
If you attempt to define a module that already exists, you will get a
warning saying that a module has been redefined.
There are some modules that Elixir does not currently implement but it
may be implement in the future. Those modules are reserved and defining
them will result in a compilation error:
defmodule Any do
# code
end
** (CompileError) iex:1: module Any is reserved and cannot be defined
Elixir reserves the following module names: `Elixir`, `Any`, `BitString`,
`PID`, and `Reference`.
"""
defmacro defmodule(alias, do_block)
defmacro defmodule(alias, do: block) do
env = __CALLER__
boot? = bootstrapped?(Macro)
expanded =
case boot? do
true -> Macro.expand(alias, env)
false -> alias
end
{expanded, with_alias} =
case boot? and is_atom(expanded) do
true ->
# Expand the module considering the current environment/nesting
{full, old, new} = expand_module(alias, expanded, env)
meta = [defined: full, context: env.module] ++ alias_meta(alias)
{full, {:alias, meta, [old, [as: new, warn: false]]}}
false ->
{expanded, nil}
end
# We do this so that the block is not tail-call optimized and stacktraces
# are not messed up. Basically, we just insert something between the return
# value of the block and what is returned by defmodule. Using just ":ok" or
# similar doesn't work because it's likely optimized away by the compiler.
block =
quote do
result = unquote(block)
:elixir_utils.noop()
result
end
escaped =
case env do
%{function: nil, lexical_tracker: pid} when is_pid(pid) ->
integer = Kernel.LexicalTracker.write_cache(pid, block)
quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer)))
%{} ->
:elixir_quote.escape(block, :default, false)
end
module_vars = :lists.map(&module_var/1, :maps.keys(elem(env.current_vars, 0)))
quote do
unquote(with_alias)
:elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__)
end
end
defp alias_meta({:__aliases__, meta, _}), do: meta
defp alias_meta(_), do: []
# defmodule Elixir.Alias
defp expand_module({:__aliases__, _, [:"Elixir", _ | _]}, module, _env),
do: {module, module, nil}
# defmodule Alias in root
defp expand_module({:__aliases__, _, _}, module, %{module: nil}),
do: {module, module, nil}
# defmodule Alias nested
defp expand_module({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do
module = :elixir_aliases.concat([env.module, h])
alias = String.to_atom("Elixir." <> Atom.to_string(h))
case t do
[] -> {module, module, alias}
_ -> {String.to_atom(Enum.join([module | t], ".")), module, alias}
end
end
# defmodule _
defp expand_module(_raw, module, _env) do
{module, module, nil}
end
defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind}
defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil}
@doc ~S"""
Defines a public function with the given name and body.
## Examples
defmodule Foo do
def bar, do: :baz
end
Foo.bar()
#=> :baz
A function that expects arguments can be defined as follows:
defmodule Foo do
def sum(a, b) do
a + b
end
end
In the example above, a `sum/2` function is defined; this function receives
two arguments and returns their sum.
## Default arguments
`\\` is used to specify a default value for a parameter of a function. For
example:
defmodule MyMath do
def multiply_by(number, factor \\ 2) do
number * factor
end
end
MyMath.multiply_by(4, 3)
#=> 12
MyMath.multiply_by(4)
#=> 8
The compiler translates this into multiple functions with different arities,
here `MyMath.multiply_by/1` and `MyMath.multiply_by/2`, that represent cases when
arguments for parameters with default values are passed or not passed.
When defining a function with default arguments as well as multiple
explicitly declared clauses, you must write a function head that declares the
defaults. For example:
defmodule MyString do
def join(string1, string2 \\ nil, separator \\ " ")
def join(string1, nil, _separator) do
string1
end
def join(string1, string2, separator) do
string1 <> separator <> string2
end
end
Note that `\\` can't be used with anonymous functions because they
can only have a sole arity.
## Function and variable names
Function and variable names have the following syntax:
A _lowercase ASCII letter_ or an _underscore_, followed by any number of
_lowercase or uppercase ASCII letters_, _numbers_, or _underscores_.
Optionally they can end in either an _exclamation mark_ or a _question mark_.
For variables, any identifier starting with an underscore should indicate an
unused variable. For example:
def foo(bar) do
[]
end
#=> warning: variable bar is unused
def foo(_bar) do
[]
end
#=> no warning
def foo(_bar) do
_bar
end
#=> warning: the underscored variable "_bar" is used after being set
## `rescue`/`catch`/`after`/`else`
Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try/1`
does. For example, the following two functions are equivalent:
def format(value) do
try do
format!(value)
catch
:exit, reason -> {:error, reason}
end
end
def format(value) do
format!(value)
catch
:exit, reason -> {:error, reason}
end
"""
defmacro def(call, expr \\ []) do
define(:def, call, expr, __CALLER__)
end
@doc """
Defines a private function with the given name and body.
Private functions are only accessible from within the module in which they are
defined. Trying to access a private function from outside the module it's
defined in results in an `UndefinedFunctionError` exception.
Check `def/2` for more information.
## Examples
defmodule Foo do
def bar do
sum(1, 2)
end
defp sum(a, b), do: a + b
end
Foo.bar()
#=> 3
Foo.sum(1, 2)
** (UndefinedFunctionError) undefined function Foo.sum/2
"""
defmacro defp(call, expr \\ []) do
define(:defp, call, expr, __CALLER__)
end
@doc """
Defines a public macro with the given name and body.
Macros must be defined before its usage.
Check `def/2` for rules on naming and default arguments.
## Examples
defmodule MyLogic do
defmacro unless(expr, opts) do
quote do
if !unquote(expr), unquote(opts)
end
end
end
require MyLogic
MyLogic.unless false do
IO.puts("It works")
end
"""
defmacro defmacro(call, expr \\ []) do
define(:defmacro, call, expr, __CALLER__)
end
@doc """
Defines a private macro with the given name and body.
Private macros are only accessible from the same module in which they are
defined.
Private macros must be defined before its usage.
Check `defmacro/2` for more information, and check `def/2` for rules on
naming and default arguments.
"""
defmacro defmacrop(call, expr \\ []) do
define(:defmacrop, call, expr, __CALLER__)
end
defp define(kind, call, expr, env) do
module = assert_module_scope(env, kind, 2)
assert_no_function_scope(env, kind, 2)
unquoted_call = :elixir_quote.has_unquotes(call)
unquoted_expr = :elixir_quote.has_unquotes(expr)
escaped_call = :elixir_quote.escape(call, :default, true)
escaped_expr =
case unquoted_expr do
true ->
:elixir_quote.escape(expr, :default, true)
false ->
key = :erlang.unique_integer()
:elixir_module.write_cache(module, key, expr)
quote(do: :elixir_module.read_cache(unquote(module), unquote(key)))
end
# Do not check clauses if any expression was unquoted
check_clauses = not (unquoted_expr or unquoted_call)
pos = :elixir_locals.cache_env(env)
quote do
:elixir_def.store_definition(
unquote(kind),
unquote(check_clauses),
unquote(escaped_call),
unquote(escaped_expr),
unquote(pos)
)
end
end
@doc """
Defines a struct.
A struct is a tagged map that allows developers to provide
default values for keys, tags to be used in polymorphic
dispatches and compile time assertions.
To define a struct, a developer must define both `__struct__/0` and
`__struct__/1` functions. `defstruct/1` is a convenience macro which
defines such functions with some conveniences.
For more information about structs, please check `Kernel.SpecialForms.%/2`.
## Examples
defmodule User do
defstruct name: nil, age: nil
end
Struct fields are evaluated at compile-time, which allows
them to be dynamic. In the example below, `10 + 11` is
evaluated at compile-time and the age field is stored
with value `21`:
defmodule User do
defstruct name: nil, age: 10 + 11
end
The `fields` argument is usually a keyword list with field names
as atom keys and default values as corresponding values. `defstruct/1`
also supports a list of atoms as its argument: in that case, the atoms
in the list will be used as the struct's field names and they will all
default to `nil`.
defmodule Post do
defstruct [:title, :content, :author]
end
## Deriving
Although structs are maps, by default structs do not implement
any of the protocols implemented for maps. For example, attempting
to use a protocol with the `User` struct leads to an error:
john = %User{name: "John"}
MyProtocol.call(john)
** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...}
`defstruct/1`, however, allows protocol implementations to be
*derived*. This can be done by defining a `@derive` attribute as a
list before invoking `defstruct/1`:
defmodule User do
@derive [MyProtocol]
defstruct name: nil, age: 10 + 11
end
MyProtocol.call(john) # it works!
For each protocol in the `@derive` list, Elixir will assert the protocol has
been implemented for `Any`. If the `Any` implementation defines a
`__deriving__/3` callback, the callback will be invoked and it should define
the implementation module. Otherwise an implementation that simply points to
the `Any` implementation is automatically derived. For more information on
the `__deriving__/3` callback, see `Protocol.derive/3`.
## Enforcing keys
When building a struct, Elixir will automatically guarantee all keys
belongs to the struct:
%User{name: "john", unknown: :key}
** (KeyError) key :unknown not found in: %User{age: 21, name: nil}
Elixir also allows developers to enforce certain keys must always be
given when building the struct:
defmodule User do
@enforce_keys [:name]
defstruct name: nil, age: 10 + 11
end
Now trying to build a struct without the name key will fail:
%User{age: 21}
** (ArgumentError) the following keys must also be given when building struct User: [:name]
Keep in mind `@enforce_keys` is a simple compile-time guarantee
to aid developers when building structs. It is not enforced on
updates and it does not provide any sort of value-validation.
## Types
It is recommended to define types for structs. By convention such type
is called `t`. To define a struct inside a type, the struct literal syntax
is used:
defmodule User do
defstruct name: "John", age: 25
@type t :: %__MODULE__{name: String.t(), age: non_neg_integer}
end
It is recommended to only use the struct syntax when defining the struct's
type. When referring to another struct it's better to use `User.t` instead of
`%User{}`.
The types of the struct fields that are not included in `%User{}` default to
`term()` (see `t:term/0`).
Structs whose internal structure is private to the local module (pattern
matching them or directly accessing their fields should not be allowed) should
use the `@opaque` attribute. Structs whose internal structure is public should
use `@type`.
"""
defmacro defstruct(fields) do
builder =
case bootstrapped?(Enum) do
true ->
quote do
case @enforce_keys do
[] ->
def __struct__(kv) do
Enum.reduce(kv, @struct, fn {key, val}, map ->
Map.replace!(map, key, val)
end)
end
_ ->
def __struct__(kv) do
{map, keys} =
Enum.reduce(kv, {@struct, @enforce_keys}, fn {key, val}, {map, keys} ->
{Map.replace!(map, key, val), List.delete(keys, key)}
end)
case keys do
[] ->
map
_ ->
raise ArgumentError,
"the following keys must also be given when building " <>
"struct #{inspect(__MODULE__)}: #{inspect(keys)}"
end
end
end
end
false ->
quote do
_ = @enforce_keys
def __struct__(kv) do
:lists.foldl(fn {key, val}, acc -> Map.replace!(acc, key, val) end, @struct, kv)
end
end
end
quote do
if Module.has_attribute?(__MODULE__, :struct) do
raise ArgumentError,
"defstruct has already been called for " <>
"#{Kernel.inspect(__MODULE__)}, defstruct can only be called once per module"
end
{struct, keys, derive} = Kernel.Utils.defstruct(__MODULE__, unquote(fields))
@struct struct
@enforce_keys keys
case derive do
[] -> :ok
_ -> Protocol.__derive__(derive, __MODULE__, __ENV__)
end
def __struct__() do
@struct
end
unquote(builder)
Kernel.Utils.announce_struct(__MODULE__)
struct
end
end
@doc ~S"""
Defines an exception.
Exceptions are structs backed by a module that implements
the `Exception` behaviour. The `Exception` behaviour requires
two functions to be implemented:
* [`exception/1`](`c:Exception.exception/1`) - receives the arguments given to `raise/2`
and returns the exception struct. The default implementation
accepts either a set of keyword arguments that is merged into
the struct or a string to be used as the exception's message.
* [`message/1`](`c:Exception.message/1`) - receives the exception struct and must return its
message. Most commonly exceptions have a message field which
by default is accessed by this function. However, if an exception
does not have a message field, this function must be explicitly
implemented.
Since exceptions are structs, the API supported by `defstruct/1`
is also available in `defexception/1`.
## Raising exceptions
The most common way to raise an exception is via `raise/2`:
defmodule MyAppError do
defexception [:message]
end
value = [:hello]
raise MyAppError,
message: "did not get what was expected, got: #{inspect(value)}"
In many cases it is more convenient to pass the expected value to
`raise/2` and generate the message in the `c:Exception.exception/1` callback:
defmodule MyAppError do
defexception [:message]
@impl true
def exception(value) do
msg = "did not get what was expected, got: #{inspect(value)}"
%MyAppError{message: msg}
end
end
raise MyAppError, value
The example above shows the preferred strategy for customizing
exception messages.
"""
defmacro defexception(fields) do
quote bind_quoted: [fields: fields] do
@behaviour Exception
struct = defstruct([__exception__: true] ++ fields)
if Map.has_key?(struct, :message) do
@impl true
def message(exception) do
exception.message
end
defoverridable message: 1
@impl true
def exception(msg) when Kernel.is_binary(msg) do
exception(message: msg)
end
end
# Calls to Kernel functions must be fully-qualified to ensure
# reproducible builds; otherwise, this macro will generate ASTs
# with different metadata (:import, :context) depending on if
# it is the bootstrapped version or not.
# TODO: Change the implementation on v2.0 to simply call Kernel.struct!/2
@impl true
def exception(args) when Kernel.is_list(args) do
struct = __struct__()
{valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end)
case invalid do
[] ->
:ok
_ ->
IO.warn(
"the following fields are unknown when raising " <>
"#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. " <>
"Please make sure to only give known fields when raising " <>
"or redefine #{Kernel.inspect(__MODULE__)}.exception/1 to " <>
"discard unknown fields. Future Elixir versions will raise on " <>
"unknown fields given to raise/2"
)
end
Kernel.struct!(struct, valid)
end
defoverridable exception: 1
end
end
@doc """
Defines a protocol.
See the `Protocol` module for more information.
"""
defmacro defprotocol(name, do_block)
defmacro defprotocol(name, do: block) do
Protocol.__protocol__(name, do: block)
end
@doc """
Defines an implementation for the given protocol.
See the `Protocol` module for more information.
"""
defmacro defimpl(name, opts, do_block \\ []) do
merged = Keyword.merge(opts, do_block)
merged = Keyword.put_new(merged, :for, __CALLER__.module)
Protocol.__impl__(name, merged)
end
@doc """
Makes the given functions in the current module overridable.
An overridable function is lazily defined, allowing a developer to override
it.
Macros cannot be overridden as functions and vice-versa.
## Example
defmodule DefaultMod do
defmacro __using__(_opts) do
quote do
def test(x, y) do
x + y
end
defoverridable test: 2
end
end
end
defmodule InheritMod do
use DefaultMod
def test(x, y) do
x * y + super(x, y)
end
end
As seen as in the example above, `super` can be used to call the default
implementation.
If `@behaviour` has been defined, `defoverridable` can also be called with a
module as an argument. All implemented callbacks from the behaviour above the
call to `defoverridable` will be marked as overridable.
## Example
defmodule Behaviour do
@callback foo :: any
end
defmodule DefaultMod do
defmacro __using__(_opts) do
quote do
@behaviour Behaviour
def foo do
"Override me"
end
defoverridable Behaviour
end
end
end
defmodule InheritMod do
use DefaultMod
def foo do
"Overridden"
end
end
"""
defmacro defoverridable(keywords_or_behaviour) do
quote do
Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour))
end
end
@doc """
Generates a macro suitable for use in guard expressions.
It raises at compile time if the definition uses expressions that aren't
allowed in guards, and otherwise creates a macro that can be used both inside
or outside guards.
Note the convention in Elixir is to name functions/macros allowed in
guards with the `is_` prefix, such as `is_list/1`. If, however, the
function/macro returns a boolean and is not allowed in guards, it should
have no prefix and end with a question mark, such as `Keyword.keyword?/1`.
## Example
defmodule Integer.Guards do
defguard is_even(value) when is_integer(value) and rem(value, 2) == 0
end
defmodule Collatz do
@moduledoc "Tools for working with the Collatz sequence."
import Integer.Guards
@doc "Determines the number of steps `n` takes to reach `1`."
# If this function never converges, please let me know what `n` you used.
def converge(n) when n > 0, do: step(n, 0)
defp step(1, step_count) do
step_count
end
defp step(n, step_count) when is_even(n) do
step(div(n, 2), step_count + 1)
end
defp step(n, step_count) do
step(3 * n + 1, step_count + 1)
end
end
"""
@doc since: "1.6.0"
@spec defguard(Macro.t()) :: Macro.t()
defmacro defguard(guard) do
define_guard(:defmacro, guard, __CALLER__)
end
@doc """
Generates a private macro suitable for use in guard expressions.
It raises at compile time if the definition uses expressions that aren't
allowed in guards, and otherwise creates a private macro that can be used
both inside or outside guards in the current module.
Similar to `defmacrop/2`, `defguardp/1` must be defined before its use
in the current module.
"""
@doc since: "1.6.0"
@spec defguardp(Macro.t()) :: Macro.t()
defmacro defguardp(guard) do
define_guard(:defmacrop, guard, __CALLER__)
end
defp define_guard(kind, guard, env) do
case :elixir_utils.extract_guards(guard) do
{call, [_, _ | _]} ->
raise ArgumentError,
"invalid syntax in defguard #{Macro.to_string(call)}, " <>
"only a single when clause is allowed"
{call, impls} ->
case Macro.decompose_call(call) do
{_name, args} ->
validate_variable_only_args!(call, args)
macro_definition =
case impls do
[] ->
define(kind, call, [], env)
[guard] ->
quoted =
quote do
require Kernel.Utils
Kernel.Utils.defguard(unquote(args), unquote(guard))
end
define(kind, call, [do: quoted], env)
end
quote do
@doc guard: true
unquote(macro_definition)
end
_invalid_definition ->
raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}"
end
end
end
defp validate_variable_only_args!(call, args) do
Enum.each(args, fn
{ref, _meta, context} when is_atom(ref) and is_atom(context) ->
:ok
{:\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) ->
:ok
_match ->
raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}"
end)
end
@doc """
Uses the given module in the current context.
When calling:
use MyModule, some: :options
the `__using__/1` macro from the `MyModule` module is invoked with the second
argument passed to `use` as its argument. Since `__using__/1` is a macro, all
the usual macro rules apply, and its return value should be quoted code
that is then inserted where `use/2` is called.
## Examples
For example, in order to write test cases using the `ExUnit` framework
provided with Elixir, a developer should `use` the `ExUnit.Case` module:
defmodule AssertionTest do
use ExUnit.Case, async: true
test "always pass" do
assert true
end
end
In this example, `ExUnit.Case.__using__/1` is called with the keyword list
`[async: true]` as its argument; `use/2` translates to:
defmodule AssertionTest do
require ExUnit.Case
ExUnit.Case.__using__(async: true)
test "always pass" do
assert true
end
end
`ExUnit.Case` will then define the `__using__/1` macro:
defmodule ExUnit.Case do
defmacro __using__(opts) do
# do something with opts
quote do
# return some code to inject in the caller
end
end
end
## Best practices
`__using__/1` is typically used when there is a need to set some state (via
module attributes) or callbacks (like `@before_compile`, see the documentation
for `Module` for more information) into the caller.
`__using__/1` may also be used to alias, require, or import functionality
from different modules:
defmodule MyModule do
defmacro __using__(_opts) do
quote do
import MyModule.Foo
import MyModule.Bar
import MyModule.Baz
alias MyModule.Repo
end
end
end
However, do not provide `__using__/1` if all it does is to import,
alias or require the module itself. For example, avoid this:
defmodule MyModule do
defmacro __using__(_opts) do
quote do
import MyModule
end
end
end
In such cases, developers should instead import or alias the module
directly, so that they can customize those as they wish,
without the indirection behind `use/2`.
Finally, developers should also avoid defining functions inside
the `__using__/1` callback, unless those functions are the default
implementation of a previously defined `@callback` or are functions
meant to be overridden (see `defoverridable/1`). Even in these cases,
defining functions should be seen as a "last resort".
In case you want to provide some existing functionality to the user module,
please define it in a module which will be imported accordingly; for example,
`ExUnit.Case` doesn't define the `test/3` macro in the module that calls
`use ExUnit.Case`, but it defines `ExUnit.Case.test/3` and just imports that
into the caller when used.
"""
defmacro use(module, opts \\ []) do
calls =
Enum.map(expand_aliases(module, __CALLER__), fn
expanded when is_atom(expanded) ->
quote do
require unquote(expanded)
unquote(expanded).__using__(unquote(opts))
end
_otherwise ->
raise ArgumentError,
"invalid arguments for use, " <>
"expected a compile time atom or alias, got: #{Macro.to_string(module)}"
end)
quote(do: (unquote_splicing(calls)))
end
defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do
base = Macro.expand(base, env)
Enum.map(refs, fn
{:__aliases__, _, ref} ->
Module.concat([base | ref])
ref when is_atom(ref) ->
Module.concat(base, ref)
other ->
other
end)
end
defp expand_aliases(module, env) do
[Macro.expand(module, env)]
end
@doc """
Defines a function that delegates to another module.
Functions defined with `defdelegate/2` are public and can be invoked from
outside the module they're defined in, as if they were defined using `def/2`.
Therefore, `defdelegate/2` is about extending the current module's public API.
If what you want is to invoke a function defined in another module without
using its full module name, then use `alias/2` to shorten the module name or use
`import/2` to be able to invoke the function without the module name altogether.
Delegation only works with functions; delegating macros is not supported.
Check `def/2` for rules on naming and default arguments.
## Options
* `:to` - the module to dispatch to.
* `:as` - the function to call on the target given in `:to`.
This parameter is optional and defaults to the name being
delegated (`funs`).
## Examples
defmodule MyList do
defdelegate reverse(list), to: Enum
defdelegate other_reverse(list), to: Enum, as: :reverse
end
MyList.reverse([1, 2, 3])
#=> [3, 2, 1]
MyList.other_reverse([1, 2, 3])
#=> [3, 2, 1]
"""
defmacro defdelegate(funs, opts) do
funs = Macro.escape(funs, unquote: true)
quote bind_quoted: [funs: funs, opts: opts] do
target =
Keyword.get(opts, :to) || raise ArgumentError, "expected to: to be given as argument"
if is_list(funs) do
IO.warn(
"passing a list to Kernel.defdelegate/2 is deprecated, please define each delegate separately",
Macro.Env.stacktrace(__ENV__)
)
end
if Keyword.has_key?(opts, :append_first) do
IO.warn(
"Kernel.defdelegate/2 :append_first option is deprecated",
Macro.Env.stacktrace(__ENV__)
)
end
for fun <- List.wrap(funs) do
{name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts)
@doc delegate_to: {target, as, :erlang.length(as_args)}
def unquote(name)(unquote_splicing(args)) do
unquote(target).unquote(as)(unquote_splicing(as_args))
end
end
end
end
## Sigils
@doc ~S"""
Handles the sigil `~S` for strings.
It returns a string without interpolations and without escape
characters, except for the escaping of the closing sigil character
itself.
## Examples
iex> ~S(foo)
"foo"
iex> ~S(f#{o}o)
"f\#{o}o"
iex> ~S(\o/)
"\\o/"
However, if you want to re-use the sigil character itself on
the string, you need to escape it:
iex> ~S((\))
"()"
"""
defmacro sigil_S(term, modifiers)
defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary
@doc ~S"""
Handles the sigil `~s` for strings.
It returns a string as if it was a double quoted string, unescaping characters
and replacing interpolations.
## Examples
iex> ~s(foo)
"foo"
iex> ~s(f#{:o}o)
"foo"
iex> ~s(f\#{:o}o)
"f\#{:o}o"
"""
defmacro sigil_s(term, modifiers)
defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do
:elixir_interpolation.unescape_chars(piece)
end
defmacro sigil_s({:<<>>, line, pieces}, []) do
{:<<>>, line, unescape_tokens(pieces)}
end
@doc ~S"""
Handles the sigil `~C` for charlists.
It returns a charlist without interpolations and without escape
characters, except for the escaping of the closing sigil character
itself.
## Examples
iex> ~C(foo)
'foo'
iex> ~C(f#{o}o)
'f\#{o}o'
"""
defmacro sigil_C(term, modifiers)
defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do
String.to_charlist(string)
end
@doc ~S"""
Handles the sigil `~c` for charlists.
It returns a charlist as if it was a single quoted string, unescaping
characters and replacing interpolations.
## Examples
iex> ~c(foo)
'foo'
iex> ~c(f#{:o}o)
'foo'
iex> ~c(f\#{:o}o)
'f\#{:o}o'
"""
defmacro sigil_c(term, modifiers)
# We can skip the runtime conversion if we are
# creating a binary made solely of series of chars.
defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do
String.to_charlist(:elixir_interpolation.unescape_chars(string))
end
defmacro sigil_c({:<<>>, _meta, pieces}, []) do
quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces))))
end
@doc """
Handles the sigil `~r` for regular expressions.
It returns a regular expression pattern, unescaping characters and replacing
interpolations.
More information on regular expressions can be found in the `Regex` module.
## Examples
iex> Regex.match?(~r(foo), "foo")
true
iex> Regex.match?(~r/a#{:b}c/, "abc")
true
"""
defmacro sigil_r(term, modifiers)
defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do
binary = :elixir_interpolation.unescape_chars(string, &Regex.unescape_map/1)
regex = Regex.compile!(binary, :binary.list_to_bin(options))
Macro.escape(regex)
end
defmacro sigil_r({:<<>>, meta, pieces}, options) do
binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map/1)}
quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options))))
end
@doc ~S"""
Handles the sigil `~R` for regular expressions.
It returns a regular expression pattern without interpolations and
without escape characters. Note it still supports escape of Regex
tokens (such as escaping `+` or `?`) and it also requires you to
escape the closing sigil character itself if it appears on the Regex.
More information on regexes can be found in the `Regex` module.
## Examples
iex> Regex.match?(~R(f#{1,3}o), "f#o")
true
"""
defmacro sigil_R(term, modifiers)
defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do
regex = Regex.compile!(string, :binary.list_to_bin(options))
Macro.escape(regex)
end
@doc ~S"""
Handles the sigil `~D` for dates.
By default, this sigil uses the built-in `Calendar.ISO`, which
requires dates to be written in the ISO8601 format:
~D[yyyy-mm-dd]
such as:
~D[2015-01-13]
If you are using alternative calendars, any representation can
be used as long as you follow the representation by a single space
and the calendar name:
~D[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case `~d` variant does not exist as interpolation
and escape characters are not useful for date sigils.
More information on dates can be found in the `Date` module.
## Examples
iex> ~D[2015-01-13]
~D[2015-01-13]
"""
defmacro sigil_D(date_string, modifiers)
defmacro sigil_D({:<<>>, _, [string]}, []) do
{{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, "Date")
to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day)
end
@doc ~S"""
Handles the sigil `~T` for times.
By default, this sigil uses the built-in `Calendar.ISO`, which
requires times to be written in the ISO8601 format:
~T[hh:mm:ss]
~T[hh:mm:ss.ssssss]
such as:
~T[13:00:07]
~T[13:00:07.123]
If you are using alternative calendars, any representation can
be used as long as you follow the representation by a single space
and the calendar name:
~T[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case `~t` variant does not exist as interpolation
and escape characters are not useful for time sigils.
More information on times can be found in the `Time` module.
## Examples
iex> ~T[13:00:07]
~T[13:00:07]
iex> ~T[13:00:07.001]
~T[13:00:07.001]
"""
defmacro sigil_T(time_string, modifiers)
defmacro sigil_T({:<<>>, _, [string]}, []) do
{{:ok, {hour, minute, second, microsecond}}, calendar} =
parse_with_calendar!(string, :parse_time, "Time")
to_calendar_struct(Time,
calendar: calendar,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond
)
end
@doc ~S"""
Handles the sigil `~N` for naive date times.
By default, this sigil uses the built-in `Calendar.ISO`, which
requires naive date times to be written in the ISO8601 format:
~N[yyyy-mm-dd hh:mm:ss]
~N[yyyy-mm-dd hh:mm:ss.ssssss]
~N[yyyy-mm-ddThh:mm:ss.ssssss]
such as:
~N[2015-01-13 13:00:07]
~N[2015-01-13T13:00:07.123]
If you are using alternative calendars, any representation can
be used as long as you follow the representation by a single space
and the calendar name:
~N[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case `~n` variant does not exist as interpolation
and escape characters are not useful for date time sigils.
More information on naive date times can be found in the
`NaiveDateTime` module.
## Examples
iex> ~N[2015-01-13 13:00:07]
~N[2015-01-13 13:00:07]
iex> ~N[2015-01-13T13:00:07.001]
~N[2015-01-13 13:00:07.001]
"""
defmacro sigil_N(naive_datetime_string, modifiers)
defmacro sigil_N({:<<>>, _, [string]}, []) do
{{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} =
parse_with_calendar!(string, :parse_naive_datetime, "NaiveDateTime")
to_calendar_struct(NaiveDateTime,
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond
)
end
@doc ~S"""
Handles the sigil `~U` to create a UTC `DateTime`.
By default, this sigil uses the built-in `Calendar.ISO`, which
requires UTC date times to be written in the ISO8601 format:
~U[yyyy-mm-dd hh:mm:ssZ]
~U[yyyy-mm-dd hh:mm:ss.ssssssZ]
~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00]
such as:
~U[2015-01-13 13:00:07Z]
~U[2015-01-13T13:00:07.123+00:00]
If you are using alternative calendars, any representation can
be used as long as you follow the representation by a single space
and the calendar name:
~U[SOME-REPRESENTATION My.Alternative.Calendar]
The given `datetime_string` must include "Z" or "00:00" offset
which marks it as UTC, otherwise an error is raised.
The lower case `~u` variant does not exist as interpolation
and escape characters are not useful for date time sigils.
More information on date times can be found in the `DateTime` module.
## Examples
iex> ~U[2015-01-13 13:00:07Z]
~U[2015-01-13 13:00:07Z]
iex> ~U[2015-01-13T13:00:07.001+00:00]
~U[2015-01-13 13:00:07.001Z]
"""
@doc since: "1.9.0"
defmacro sigil_U(datetime_string, modifiers)
defmacro sigil_U({:<<>>, _, [string]}, []) do
{{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} =
parse_with_calendar!(string, :parse_utc_datetime, "UTC DateTime")
if offset != 0 do
raise ArgumentError,
"cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset"
end
to_calendar_struct(DateTime,
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond,
time_zone: "Etc/UTC",
zone_abbr: "UTC",
utc_offset: 0,
std_offset: 0
)
end
defp parse_with_calendar!(string, fun, context) do
{calendar, string} = extract_calendar(string)
result = apply(calendar, fun, [string])
{maybe_raise!(result, calendar, context, string), calendar}
end
defp extract_calendar(string) do
case :binary.split(string, " ", [:global]) do
[_] -> {Calendar.ISO, string}
parts -> maybe_atomize_calendar(List.last(parts), string)
end
end
defp maybe_atomize_calendar(<<alias, _::binary>> = last_part, string)
when alias >= ?A and alias <= ?Z do
string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1)
{String.to_atom("Elixir." <> last_part), string}
end
defp maybe_atomize_calendar(_last_part, string) do
{Calendar.ISO, string}
end
defp maybe_raise!({:error, reason}, calendar, type, string) do
raise ArgumentError,
"cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, " <>
"reason: #{inspect(reason)}"
end
defp maybe_raise!(other, _calendar, _type, _string), do: other
defp to_calendar_struct(type, fields) do
quote do
%{unquote_splicing([__struct__: type] ++ fields)}
end
end
@doc ~S"""
Handles the sigil `~w` for list of words.
It returns a list of "words" split by whitespace. Character unescaping and
interpolation happens for each word.
## Modifiers
* `s`: words in the list are strings (default)
* `a`: words in the list are atoms
* `c`: words in the list are charlists
## Examples
iex> ~w(foo #{:bar} baz)
["foo", "bar", "baz"]
iex> ~w(foo #{" bar baz "})
["foo", "bar", "baz"]
iex> ~w(--source test/enum_test.exs)
["--source", "test/enum_test.exs"]
iex> ~w(foo bar baz)a
[:foo, :bar, :baz]
"""
defmacro sigil_w(term, modifiers)
defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do
split_words(:elixir_interpolation.unescape_chars(string), modifiers, __CALLER__)
end
defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do
binary = {:<<>>, meta, unescape_tokens(pieces)}
split_words(binary, modifiers, __CALLER__)
end
@doc ~S"""
Handles the sigil `~W` for list of words.
It returns a list of "words" split by whitespace without interpolations
and without escape characters, except for the escaping of the closing
sigil character itself.
## Modifiers
* `s`: words in the list are strings (default)
* `a`: words in the list are atoms
* `c`: words in the list are charlists
## Examples
iex> ~W(foo #{bar} baz)
["foo", "\#{bar}", "baz"]
"""
defmacro sigil_W(term, modifiers)
defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do
split_words(string, modifiers, __CALLER__)
end
defp split_words(string, [], caller) do
split_words(string, [?s], caller)
end
defp split_words(string, [mod], caller)
when mod == ?s or mod == ?a or mod == ?c do
case is_binary(string) do
true ->
parts = String.split(string)
parts_with_trailing_comma = :lists.filter(&(:binary.last(&1) == ?,), parts)
if parts_with_trailing_comma != [] do
stacktrace = Macro.Env.stacktrace(caller)
IO.warn(
"the sigils ~w/~W do not allow trailing commas at the end of each word. " <>
"If the comma is necessary, define a regular list with [...], otherwise remove the comma.",
stacktrace
)
end
case mod do
?s -> parts
?a -> :lists.map(&String.to_atom/1, parts)
?c -> :lists.map(&String.to_charlist/1, parts)
end
false ->
parts = quote(do: String.split(unquote(string)))
case mod do
?s -> parts
?a -> quote(do: :lists.map(&String.to_atom/1, unquote(parts)))
?c -> quote(do: :lists.map(&String.to_charlist/1, unquote(parts)))
end
end
end
defp split_words(_string, _mods, _caller) do
raise ArgumentError, "modifier must be one of: s, a, c"
end
## Shared functions
defp assert_module_scope(env, fun, arity) do
case env.module do
nil -> raise ArgumentError, "cannot invoke #{fun}/#{arity} outside module"
mod -> mod
end
end
defp assert_no_function_scope(env, fun, arity) do
case env.function do
nil -> :ok
_ -> raise ArgumentError, "cannot invoke #{fun}/#{arity} inside function/macro"
end
end
defp assert_no_match_or_guard_scope(context, exp) do
case context do
:match ->
invalid_match!(exp)
:guard ->
raise ArgumentError,
"invalid expression in guard, #{exp} is not allowed in guards. " <>
"To learn more about guards, visit: https://hexdocs.pm/elixir/patterns-and-guards.html"
_ ->
:ok
end
end
defp invalid_match!(exp) do
raise ArgumentError,
"invalid expression in match, #{exp} is not allowed in patterns " <>
"such as function clauses, case clauses or on the left side of the = operator"
end
# Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens
defp unescape_tokens(tokens) do
case :elixir_interpolation.unescape_tokens(tokens) do
{:ok, unescaped_tokens} -> unescaped_tokens
{:error, reason} -> raise ArgumentError, to_string(reason)
end
end
defp unescape_tokens(tokens, unescape_map) do
case :elixir_interpolation.unescape_tokens(tokens, unescape_map) do
{:ok, unescaped_tokens} -> unescaped_tokens
{:error, reason} -> raise ArgumentError, to_string(reason)
end
end
defp unescape_list_tokens(tokens) do
escape = fn
{:"::", _, [expr, _]} -> expr
binary when is_binary(binary) -> :elixir_interpolation.unescape_chars(binary)
end
:lists.map(escape, tokens)
end
@doc false
# TODO: Remove on v2.0 (also hard-coded in elixir_dispatch)
@deprecated "Use Kernel.to_charlist/1 instead"
defmacro to_char_list(arg) do
quote(do: Kernel.to_charlist(unquote(arg)))
end
end
| 26.79841 | 111 | 0.634528 |
08c7c34f6f006b0ec8ad9278e03588d48cd2e2ad | 244 | exs | Elixir | config/releases.exs | pedrosnk/erlef-website | bb8da73d09930056c9d31bcc75a92b8fb3caf6da | [
"Apache-2.0"
] | null | null | null | config/releases.exs | pedrosnk/erlef-website | bb8da73d09930056c9d31bcc75a92b8fb3caf6da | [
"Apache-2.0"
] | null | null | null | config/releases.exs | pedrosnk/erlef-website | bb8da73d09930056c9d31bcc75a92b8fb3caf6da | [
"Apache-2.0"
] | null | null | null | import Config
config :erlef, ErlefWeb.Endpoint,
server: true,
http: [port: {:system, "PORT"}],
url: [host: "erlef.org", port: 443],
check_origin: [
"//erlef.com",
"//www.erlef.com",
"//erlef.org",
"//www.erlef.org"
]
| 18.769231 | 38 | 0.569672 |
08c7de951f1c2dbd95581c04f0d8807474191c8e | 1,295 | ex | Elixir | examples/example4.ex | OpenEuphoria/euphoria-mvc | 05237f792b130ed8d8de3148c32f641f315c7256 | [
"MIT"
] | 15 | 2018-09-23T19:51:36.000Z | 2022-01-31T04:07:56.000Z | examples/example4.ex | OpenEuphoria/euphoria-mvc | 05237f792b130ed8d8de3148c32f641f315c7256 | [
"MIT"
] | 12 | 2019-03-11T00:19:15.000Z | 2020-12-13T20:24:58.000Z | examples/example4.ex | OpenEuphoria/euphoria-mvc | 05237f792b130ed8d8de3148c32f641f315c7256 | [
"MIT"
] | 3 | 2019-05-05T13:34:25.000Z | 2022-03-10T08:42:21.000Z | --
-- This is like example3.ex but uses the built-in web server.
--
include std/map.e
include std/filesys.e
include std/search.e
include mvc/app.e
include mvc/logger.e
include mvc/server.e
include mvc/template.e
if search:ends( "examples", current_dir() ) then
-- make sure we can find our templates
-- if we're in the 'examples' directory
set_template_path( "../templates" )
end if
function user_id( object request )
integer id = map:get( request, "id", -1 )
map response = map:new()
map:put( response, "title", "User" )
map:put( response, "id", id )
return render_template( "user.html", response )
end function
app:route( "/user/<id:integer>", "user_id" )
function user_name( object request )
sequence name = map:get( request, "name", "undefined" )
map response = map:new()
map:put( response, "title", "User" )
map:put( response, "name", name )
return render_template( "user.html", response )
end function
app:route( "/user/<name:string>", "user_name" )
function index( object request )
map response = map:new()
map:put( response, "title", "Index" )
map:put( response, "message", "Hello, world!" )
return render_template( "index.html", response )
end function
app:route( "/index", "index" )
app:route( "/", "root",, routine_id("index") )
server:start()
| 23.545455 | 61 | 0.682625 |
08c7ef22e3b1fbf5caf06fa90533163583547164 | 60,781 | exs | Elixir | lib/elixir/test/elixir/kernel/expansion_test.exs | alexcastano/elixir | 0221ce1f79d1cfd0955a9fa46a6d84d0193ad838 | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/kernel/expansion_test.exs | alexcastano/elixir | 0221ce1f79d1cfd0955a9fa46a6d84d0193ad838 | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/kernel/expansion_test.exs | alexcastano/elixir | 0221ce1f79d1cfd0955a9fa46a6d84d0193ad838 | [
"Apache-2.0"
] | 1 | 2021-09-30T01:21:02.000Z | 2021-09-30T01:21:02.000Z | Code.require_file("../test_helper.exs", __DIR__)
defmodule Kernel.ExpansionTarget do
defmacro seventeen, do: 17
defmacro bar, do: "bar"
end
defmodule Kernel.ExpansionTest do
use ExUnit.Case, async: false
describe "__block__" do
test "expands to nil when empty" do
assert expand(quote(do: unquote(:__block__)())) == nil
end
test "expands to argument when arity is 1" do
assert expand(quote(do: unquote(:__block__)(1))) == 1
end
test "is recursive to argument when arity is 1" do
expanded =
quote do
_ = 1
2
end
assert expand(quote(do: unquote(:__block__)(_ = 1, unquote(:__block__)(2)))) == expanded
end
test "accumulates vars" do
before_expansion =
quote do
a = 1
a
end
after_expansion =
quote do
a = 1
a
end
assert expand(before_expansion) == after_expansion
end
end
describe "alias" do
test "expand args, defines alias and returns itself" do
alias true, as: True
input = quote(do: alias(:hello, as: World, warn: True))
{output, env} = expand_env(input, __ENV__)
assert output == :hello
assert env.aliases == [{:"Elixir.True", true}, {:"Elixir.World", :hello}]
end
test "invalid alias" do
message =
~r"invalid value for option :as, expected a simple alias, got nested alias: Sample.Lists"
assert_raise CompileError, message, fn ->
expand(quote(do: alias(:lists, as: Sample.Lists)))
end
message = ~r"invalid argument for alias, expected a compile time atom or alias, got: 1 \+ 2"
assert_raise CompileError, message, fn ->
expand(quote(do: alias(1 + 2)))
end
message = ~r"invalid value for option :as, expected an alias, got: :foobar"
assert_raise CompileError, message, fn ->
expand(quote(do: alias(:lists, as: :foobar)))
end
end
test "invalid expansion" do
assert_raise CompileError, ~r"invalid alias: \"foo\.Foo\"", fn ->
code =
quote do
foo = :foo
foo.Foo
end
expand(code)
end
end
test "raises if :as is passed to multi-alias aliases" do
assert_raise CompileError, ~r":as option is not supported by multi-alias call", fn ->
expand(quote(do: alias(Foo.{Bar, Baz}, as: BarBaz)))
end
end
test "invalid options" do
assert_raise CompileError, ~r"unsupported option :ops given to alias", fn ->
expand(quote(do: alias(Foo, ops: 1)))
end
end
end
describe "__aliases__" do
test "expands even if no alias" do
assert expand(quote(do: World)) == :"Elixir.World"
assert expand(quote(do: Elixir.World)) == :"Elixir.World"
end
test "expands with alias" do
alias Hello, as: World
assert expand_env(quote(do: World), __ENV__) |> elem(0) == :"Elixir.Hello"
end
test "expands with alias is recursive" do
alias Source, as: Hello
alias Hello, as: World
assert expand_env(quote(do: World), __ENV__) |> elem(0) == :"Elixir.Source"
end
end
describe "import" do
test "raises on invalid macro" do
message = ~r"cannot import Kernel.invalid/1 because it is undefined or private"
assert_raise CompileError, message, fn ->
expand(quote(do: import(Kernel, only: [invalid: 1])))
end
end
test "raises on invalid options" do
message = ~r"invalid :only option for import, expected a keyword list with integer values"
assert_raise CompileError, message, fn ->
expand(quote(do: import(Kernel, only: [invalid: nil])))
end
message = ~r"invalid :except option for import, expected a keyword list with integer values"
assert_raise CompileError, message, fn ->
expand(quote(do: import(Kernel, except: [invalid: nil])))
end
message = ~r/invalid options for import, expected a keyword list, got: "invalid_options"/
assert_raise CompileError, message, fn ->
expand(quote(do: import(Kernel, "invalid_options")))
end
end
test "raises on conflicting options" do
message =
~r":only and :except can only be given together to import when :only is either :functions or :macros"
assert_raise CompileError, message, fn ->
expand(quote(do: import(Kernel, only: [], except: [])))
end
end
test "invalid import option" do
assert_raise CompileError, ~r"unsupported option :ops given to import", fn ->
expand(quote(do: import(:lists, ops: 1)))
end
end
test "raises for non-compile-time module" do
assert_raise CompileError, ~r"invalid argument for import, .*, got: {:a, :tuple}", fn ->
expand(quote(do: import({:a, :tuple})))
end
end
end
describe "require" do
test "raises for non-compile-time module" do
assert_raise CompileError, ~r"invalid argument for require, .*, got: {:a, :tuple}", fn ->
expand(quote(do: require({:a, :tuple})))
end
end
test "invalid options" do
assert_raise CompileError, ~r"unsupported option :ops given to require", fn ->
expand(quote(do: require(Foo, ops: 1)))
end
end
end
describe "=" do
test "sets context to match" do
assert expand(quote(do: __ENV__.context = :match)) == quote(do: :match = :match)
end
test "defines vars" do
{output, env} = expand_env(quote(do: a = 1), __ENV__)
assert output == quote(do: a = 1)
assert Macro.Env.has_var?(env, {:a, __MODULE__})
end
test "does not define _" do
{output, env} = expand_env(quote(do: _ = 1), __ENV__)
assert output == quote(do: _ = 1)
assert Macro.Env.vars(env) == []
end
end
describe "environment macros" do
test "__MODULE__" do
assert expand(quote(do: __MODULE__)) == __MODULE__
end
test "__DIR__" do
assert expand(quote(do: __DIR__)) == __DIR__
end
test "__ENV__" do
env = %{__ENV__ | line: 0}
assert expand_env(quote(do: __ENV__), env) == {Macro.escape(env), env}
end
test "__ENV__.accessor" do
env = %{__ENV__ | line: 0}
assert expand_env(quote(do: __ENV__.file), env) == {__ENV__.file, env}
assert expand_env(quote(do: __ENV__.unknown), env) ==
{quote(do: unquote(Macro.escape(env)).unknown), env}
end
end
describe "vars" do
test "expand to local call" do
{output, env} = expand_env(quote(do: a), __ENV__)
assert output == quote(do: a())
assert Macro.Env.vars(env) == []
end
test "forces variable to exist" do
code =
quote do
var!(a) = 1
var!(a)
end
assert expand(code)
message = ~r"expected \"a\" to expand to an existing variable or be part of a match"
assert_raise CompileError, message, fn ->
expand(quote(do: var!(a)))
end
message =
~r"expected \"a\" \(context Unknown\) to expand to an existing variable or be part of a match"
assert_raise CompileError, message, fn ->
expand(quote(do: var!(a, Unknown)))
end
end
test "raises for _ used outside of a match" do
assert_raise CompileError, ~r"invalid use of _", fn ->
expand(quote(do: {1, 2, _}))
end
end
end
describe "^" do
test "expands args" do
before_expansion =
quote do
after_expansion = 1
^after_expansion = 1
end
after_expansion =
quote do
after_expansion = 1
^after_expansion = 1
end
assert expand(before_expansion) == after_expansion
end
test "raises outside match" do
assert_raise CompileError, ~r"cannot use \^a outside of match clauses", fn ->
expand(quote(do: ^a))
end
end
test "raises without var" do
message =
~r"invalid argument for unary operator \^, expected an existing variable, got: \^1"
assert_raise CompileError, message, fn ->
expand(quote(do: ^1 = 1))
end
end
test "raises when the var is undefined" do
assert_raise CompileError, ~r"undefined variable \^foo", fn ->
expand(quote(do: ^foo = :foo))
end
end
end
describe "locals" do
test "expands to remote calls" do
assert {{:., _, [Kernel, :=~]}, _, [{:a, _, []}, {:b, _, []}]} = expand(quote(do: a =~ b))
end
test "in matches" do
message = ~r"cannot invoke local foo/1 inside match, called as: foo\(:bar\)"
assert_raise CompileError, message, fn ->
expand(quote(do: foo(:bar) = :bar))
end
end
test "in guards" do
code = quote(do: fn pid when :erlang.==(pid, self) -> pid end)
expanded_code = quote(do: fn pid when :erlang.==(pid, :erlang.self()) -> pid end)
assert clean_meta(expand(code), [:import, :context]) == expanded_code
message = ~r"cannot invoke local foo/1 inside guard, called as: foo\(arg\)"
assert_raise CompileError, message, fn ->
expand(quote(do: fn arg when foo(arg) -> arg end))
end
end
test "custom imports" do
before_expansion =
quote do
import Kernel.ExpansionTarget
seventeen()
end
after_expansion =
quote do
:"Elixir.Kernel.ExpansionTarget"
17
end
assert expand(before_expansion) == after_expansion
end
end
describe "tuples" do
test "expanded as arguments" do
assert expand(quote(do: {after_expansion = 1, a})) == quote(do: {after_expansion = 1, a()})
assert expand(quote(do: {b, after_expansion = 1, a})) ==
quote(do: {b(), after_expansion = 1, a()})
end
end
describe "maps" do
test "expanded as arguments" do
assert expand(quote(do: %{a: after_expansion = 1, b: a})) ==
quote(do: %{a: after_expansion = 1, b: a()})
end
test "with variables on keys" do
ast =
quote do
%{(x = 1) => 1}
end
assert expand(ast) == ast
ast =
quote do
x = 1
%{%{^x => 1} => 2} = y()
end
assert expand(ast) == ast
assert_raise CompileError,
~r"cannot use pin operator \^x inside a data structure as a map key in a pattern",
fn ->
expand(
quote do
x = 1
%{{^x} => 1} = %{}
end
)
end
assert_raise CompileError, ~r"cannot use variable x as map key inside a pattern", fn ->
expand(quote(do: %{x => 1} = %{}))
end
assert_raise CompileError, ~r"undefined variable \^x", fn ->
expand(quote(do: {x, %{^x => 1}} = %{}))
end
end
test "expects key-value pairs" do
assert_raise CompileError, ~r"expected key-value pairs in a map, got: :foo", fn ->
expand(quote(do: unquote({:%{}, [], [:foo]})))
end
end
end
defmodule User do
defstruct name: "", age: 0
end
describe "structs" do
test "expanded as arguments" do
assert expand(quote(do: %User{})) ==
quote(do: %:"Elixir.Kernel.ExpansionTest.User"{age: 0, name: ""})
assert expand(quote(do: %User{name: "john doe"})) ==
quote(do: %:"Elixir.Kernel.ExpansionTest.User"{age: 0, name: "john doe"})
end
test "expects atoms" do
expand(quote(do: %unknown{a: 1} = x))
message = ~r"expected struct name to be a compile time atom or alias"
assert_raise CompileError, message, fn ->
expand(quote(do: %unknown{a: 1}))
end
message = ~r"expected struct name to be a compile time atom or alias"
assert_raise CompileError, message, fn ->
expand(quote(do: %unquote(1){a: 1}))
end
message = ~r"expected struct name in a match to be a compile time atom, alias or a variable"
assert_raise CompileError, message, fn ->
expand(quote(do: %unquote(1){a: 1} = x))
end
end
test "update syntax" do
expand(quote(do: %{%{a: 0} | a: 1}))
assert_raise CompileError, ~r"cannot use map/struct update syntax in match", fn ->
expand(quote(do: %{%{a: 0} | a: 1} = %{}))
end
end
test "dynamic syntax expands to itself" do
assert expand(quote(do: %x{} = 1)) == quote(do: %x{} = 1)
end
test "unknown ^keys in structs" do
message = ~r"unknown key \^my_key for struct Kernel\.ExpansionTest\.User"
assert_raise CompileError, message, fn ->
code =
quote do
my_key = :my_key
%User{^my_key => :my_value} = %{}
end
expand(code)
end
end
end
describe "quote" do
test "expanded to raw forms" do
assert expand(quote(do: quote(do: hello))) == {:{}, [], [:hello, [], __MODULE__]}
end
test "raises if the :context option is nil or not a compile-time module" do
assert_raise CompileError, ~r"invalid :context for quote, .*, got: :erlang\.self\(\)", fn ->
expand(quote(do: quote(context: self(), do: :ok)))
end
assert_raise CompileError, ~r"invalid :context for quote, .*, got: nil", fn ->
expand(quote(do: quote(context: nil, do: :ok)))
end
end
test "raises for missing do" do
assert_raise CompileError, ~r"missing :do option in \"quote\"", fn ->
expand(quote(do: quote(context: Foo)))
end
end
test "raises for invalid arguments" do
assert_raise CompileError, ~r"invalid arguments for \"quote\"", fn ->
expand(quote(do: quote(1 + 1)))
end
end
test "raises unless its options are a keyword list" do
assert_raise CompileError, ~r"invalid options for quote, expected a keyword list", fn ->
expand(quote(do: quote(:foo, do: :foo)))
end
end
end
describe "anonymous calls" do
test "expands base and args" do
assert expand(quote(do: a.(b))) == quote(do: a().(b()))
end
test "raises on atom base" do
assert_raise CompileError, ~r"invalid function call :foo.()", fn ->
expand(quote(do: :foo.(a)))
end
end
end
describe "remotes" do
test "expands to Erlang" do
assert expand(quote(do: Kernel.is_atom(a))) == quote(do: :erlang.is_atom(a()))
end
test "expands macros" do
assert expand(quote(do: Kernel.ExpansionTest.thirteen())) == 13
end
test "expands receiver and args" do
assert expand(quote(do: a.is_atom(b))) == quote(do: a().is_atom(b()))
assert expand(quote(do: (after_expansion = :foo).is_atom(a))) ==
quote(do: (after_expansion = :foo).is_atom(a()))
end
test "modules must be required for macros" do
before_expansion =
quote do
require Kernel.ExpansionTarget
Kernel.ExpansionTarget.seventeen()
end
after_expansion =
quote do
:"Elixir.Kernel.ExpansionTarget"
17
end
assert expand(before_expansion) == after_expansion
end
test "raises when not required" do
msg =
~r"you must require Kernel\.ExpansionTarget before invoking the macro Kernel\.ExpansionTarget\.seventeen/0"
assert_raise CompileError, msg, fn ->
expand(quote(do: Kernel.ExpansionTarget.seventeen()))
end
end
test "in matches" do
message =
~r"cannot invoke remote function Hello.something_that_does_not_exist/0 inside match"
assert_raise CompileError, message, fn ->
expand(quote(do: Hello.something_that_does_not_exist() = :foo))
end
message = ~r"cannot invoke remote function :erlang.make_ref/0 inside match"
assert_raise CompileError, message, fn -> expand(quote(do: make_ref() = :foo)) end
message = ~r"invalid argument for \+\+ operator"
assert_raise CompileError, message, fn ->
expand(quote(do: "a" ++ "b" = "ab"))
end
assert_raise CompileError, message, fn ->
expand(quote(do: [1 | 2] ++ [3] = [1, 2, 3]))
end
assert_raise CompileError, message, fn ->
expand(quote(do: [1] ++ 2 ++ [3] = [1, 2, 3]))
end
end
test "in guards" do
message =
~r"cannot invoke remote function Hello.something_that_does_not_exist/1 inside guard"
assert_raise CompileError, message, fn ->
expand(quote(do: fn arg when Hello.something_that_does_not_exist(arg) -> arg end))
end
message = ~r"cannot invoke remote function :erlang.make_ref/0 inside guard"
assert_raise CompileError, message, fn ->
expand(quote(do: fn arg when make_ref() -> arg end))
end
end
end
describe "comprehensions" do
test "variables do not leak with enums" do
before_expansion =
quote do
for(a <- b, do: c = 1)
c
end
after_expansion =
quote do
for(a <- b(), do: c = 1)
c()
end
assert expand(before_expansion) == after_expansion
end
test "variables do not leak with binaries" do
before_expansion =
quote do
for(<<a <- b>>, do: c = 1)
c
end
after_expansion =
quote do
for(<<(<<a::integer()>> <- b())>>, do: c = 1)
c()
end
assert expand(before_expansion) |> clean_meta([:alignment]) == after_expansion
end
test "variables inside filters are available in blocks" do
assert expand(quote(do: for(a <- b, c = a, do: c))) ==
quote(do: for(a <- b(), c = a, do: c))
end
test "variables inside options do not leak" do
before_expansion =
quote do
for(a <- c = b, into: [], do: 1)
c
end
after_expansion =
quote do
for(a <- c = b(), do: 1, into: [])
c()
end
assert expand(before_expansion) == after_expansion
before_expansion =
quote do
for(a <- b, into: c = [], do: 1)
c
end
after_expansion =
quote do
for(a <- b(), do: 1, into: c = [])
c()
end
assert expand(before_expansion) == after_expansion
end
test "must start with generators" do
assert_raise CompileError, ~r"for comprehensions must start with a generator", fn ->
expand(quote(do: for(is_atom(:foo), do: :foo)))
end
assert_raise CompileError, ~r"for comprehensions must start with a generator", fn ->
expand(quote(do: for(do: :foo)))
end
end
test "requires size on binary generators" do
message = ~r"a binary field without size is only allowed at the end of a binary pattern"
assert_raise CompileError, message, fn ->
expand(quote(do: for(<<x::binary <- "123">>, do: x)))
end
end
test "require do option" do
assert_raise CompileError, ~r"missing :do option in \"for\"", fn ->
expand(quote(do: for(_ <- 1..2)))
end
end
test "uniq option is boolean" do
message = ~r":uniq option for comprehensions only accepts a boolean, got: x"
assert_raise CompileError, message, fn ->
expand(quote(do: for(x <- 1..2, uniq: x, do: x)))
end
end
test "raise error for unknown options" do
assert_raise CompileError, ~r"unsupported option :else given to for", fn ->
expand(quote(do: for(_ <- 1..2, do: 1, else: 1)))
end
assert_raise CompileError, ~r"unsupported option :other given to for", fn ->
expand(quote(do: for(_ <- 1..2, do: 1, other: 1)))
end
end
end
describe "with" do
test "variables do not leak" do
before_expansion =
quote do
with({foo} <- {bar}, do: baz = :ok)
baz
end
after_expansion =
quote do
with({foo} <- {bar()}, do: baz = :ok)
baz()
end
assert expand(before_expansion) == after_expansion
end
test "variables are available in do option" do
before_expansion =
quote do
with({foo} <- {bar}, do: baz = foo)
baz
end
after_expansion =
quote do
with({foo} <- {bar()}, do: baz = foo)
baz()
end
assert expand(before_expansion) == after_expansion
end
test "variables inside else do not leak" do
before_expansion =
quote do
with({foo} <- {bar}, do: :ok, else: (baz -> baz))
baz
end
after_expansion =
quote do
with({foo} <- {bar()}, do: :ok, else: (baz -> baz))
baz()
end
assert expand(before_expansion) == after_expansion
end
test "fails if \"do\" is missing" do
assert_raise CompileError, ~r"missing :do option in \"with\"", fn ->
expand(quote(do: with(_ <- true, [])))
end
end
test "fails on invalid else option" do
assert_raise CompileError, ~r"expected -> clauses for :else in \"with\"", fn ->
expand(quote(do: with(_ <- true, do: :ok, else: [:error])))
end
assert_raise CompileError, ~r"expected -> clauses for :else in \"with\"", fn ->
expand(quote(do: with(_ <- true, do: :ok, else: :error)))
end
end
test "fails for invalid options" do
# Only the required "do" is present alongside the unexpected option.
assert_raise CompileError, ~r"unexpected option :foo in \"with\"", fn ->
expand(quote(do: with(_ <- true, foo: :bar, do: :ok)))
end
# More options are present alongside the unexpected option.
assert_raise CompileError, ~r"unexpected option :foo in \"with\"", fn ->
expand(quote(do: with(_ <- true, do: :ok, else: (_ -> :ok), foo: :bar)))
end
end
end
describe "&" do
test "keeps locals" do
assert expand(quote(do: &unknown/2)) == {:&, [], [{:/, [], [{:unknown, [], nil}, 2]}]}
assert expand(quote(do: &unknown(&1, &2))) == {:&, [], [{:/, [], [{:unknown, [], nil}, 2]}]}
end
test "expands remotes" do
assert expand(quote(do: &List.flatten/2)) ==
quote(do: &:"Elixir.List".flatten/2) |> clean_meta([:import, :context])
assert expand(quote(do: &Kernel.is_atom/1)) ==
quote(do: &:erlang.is_atom/1) |> clean_meta([:import, :context])
end
test "expands macros" do
before_expansion =
quote do
require Kernel.ExpansionTarget
&Kernel.ExpansionTarget.seventeen/0
end
after_expansion =
quote do
:"Elixir.Kernel.ExpansionTarget"
fn -> 17 end
end
assert expand(before_expansion) == after_expansion
end
test "fails on non-continuous" do
assert_raise CompileError, ~r"capture &0 is not allowed", fn ->
expand(quote(do: &foo(&0)))
end
assert_raise CompileError, ~r"capture &2 cannot be defined without &1", fn ->
expand(quote(do: & &2))
end
assert_raise CompileError, ~r"capture &255 cannot be defined without &1", fn ->
expand(quote(do: & &255))
end
end
test "fails on block" do
message = ~r"invalid args for &, block expressions are not allowed, got: \(\n 1\n 2\n\)"
assert_raise CompileError, message, fn ->
code =
quote do
&(
1
2
)
end
expand(code)
end
end
test "fails on other types" do
message =
~r"invalid args for &, expected an expression in the format of &Mod.fun/arity, &local/arity or a capture containing at least one argument as &1, got: :foo"
assert_raise CompileError, message, fn ->
expand(quote(do: &:foo))
end
end
test "fails on invalid arity" do
message = ~r"invalid arity for &, expected a number between 0 and 255, got: 256"
assert_raise CompileError, message, fn ->
expand(quote(do: &Mod.fun/256))
end
end
test "fails when no captures" do
message =
~r"invalid args for &, expected an expression in the format of &Mod.fun/arity, &local/arity or a capture containing at least one argument as &1, got: foo()"
assert_raise CompileError, message, fn ->
expand(quote(do: &foo()))
end
end
test "fails on nested capture" do
assert_raise CompileError, ~r"nested captures via & are not allowed: &\(&1\)", fn ->
expand(quote(do: &(& &1)))
end
end
test "fails on integers" do
assert_raise CompileError, ~r"unhandled &1 outside of a capture", fn ->
expand(quote(do: &1))
end
end
end
describe "fn" do
test "expands each clause" do
before_expansion =
quote do
fn
x -> x
_ -> x
end
end
after_expansion =
quote do
fn
x -> x
_ -> x()
end
end
assert expand(before_expansion) == after_expansion
end
test "does not share lexical scope between clauses" do
before_expansion =
quote do
fn
1 -> import List
2 -> flatten([1, 2, 3])
end
end
after_expansion =
quote do
fn
1 -> :"Elixir.List"
2 -> flatten([1, 2, 3])
end
end
assert expand(before_expansion) == after_expansion
end
test "expands guards" do
assert expand(quote(do: fn x when x when __ENV__.context -> true end)) ==
quote(do: fn x when x when :guard -> true end)
end
test "does not leak vars" do
before_expansion =
quote do
fn x -> x end
x
end
after_expansion =
quote do
fn x -> x end
x()
end
assert expand(before_expansion) == after_expansion
end
test "raises on mixed arities" do
message = ~r"cannot mix clauses with different arities in anonymous functions"
assert_raise CompileError, message, fn ->
code =
quote do
fn
x -> x
x, y -> x + y
end
end
expand(code)
end
end
end
describe "cond" do
test "expands each clause" do
before_expansion =
quote do
cond do
x = 1 -> x
true -> x
end
end
after_expansion =
quote do
cond do
x = 1 -> x
true -> x()
end
end
assert expand(before_expansion) == after_expansion
end
test "does not share lexical scope between clauses" do
before_expansion =
quote do
cond do
1 -> import List
2 -> flatten([1, 2, 3])
end
end
after_expansion =
quote do
cond do
1 -> :"Elixir.List"
2 -> flatten([1, 2, 3])
end
end
assert expand(before_expansion) == after_expansion
end
test "does not leaks vars on head" do
before_expansion =
quote do
cond do
x = 1 -> x
y = 2 -> y
end
:erlang.+(x, y)
end
after_expansion =
quote do
cond do
x = 1 -> x
y = 2 -> y
end
:erlang.+(x(), y())
end
assert expand(before_expansion) == after_expansion
end
test "does not leak vars" do
before_expansion =
quote do
cond do
1 -> x = 1
2 -> y = 2
end
:erlang.+(x, y)
end
after_expansion =
quote do
cond do
1 -> x = 1
2 -> y = 2
end
:erlang.+(x(), y())
end
assert expand(before_expansion) == after_expansion
end
test "expects exactly one do" do
assert_raise CompileError, ~r"missing :do option in \"cond\"", fn ->
expand(quote(do: cond([])))
end
assert_raise CompileError, ~r"duplicated :do clauses given for \"cond\"", fn ->
expand(quote(do: cond(do: (x -> x), do: (y -> y))))
end
end
test "expects clauses" do
assert_raise CompileError, ~r"expected -> clauses for :do in \"cond\"", fn ->
expand(quote(do: cond(do: :ok)))
end
assert_raise CompileError, ~r"expected -> clauses for :do in \"cond\"", fn ->
expand(quote(do: cond(do: [:not, :clauses])))
end
end
test "expects one argument in clauses" do
assert_raise CompileError, ~r"expected one arg for :do clauses \(->\) in \"cond\"", fn ->
code =
quote do
cond do
_, _ -> :ok
end
end
expand(code)
end
end
test "raises for invalid arguments" do
assert_raise CompileError, ~r"invalid arguments for \"cond\"", fn ->
expand(quote(do: cond(:foo)))
end
end
test "raises with invalid options" do
assert_raise CompileError, ~r"unexpected option :foo in \"cond\"", fn ->
expand(quote(do: cond(do: (1 -> 1), foo: :bar)))
end
end
test "raises for _ in clauses" do
message = ~r"invalid use of _ inside \"cond\"\. If you want the last clause"
assert_raise CompileError, message, fn ->
code =
quote do
cond do
x -> x
_ -> :raise
end
end
expand(code)
end
end
end
describe "case" do
test "expands each clause" do
before_expansion =
quote do
case w do
x -> x
_ -> x
end
end
after_expansion =
quote do
case w() do
x -> x
_ -> x()
end
end
assert expand(before_expansion) == after_expansion
end
test "does not share lexical scope between clauses" do
before_expansion =
quote do
case w do
1 -> import List
2 -> flatten([1, 2, 3])
end
end
after_expansion =
quote do
case w() do
1 -> :"Elixir.List"
2 -> flatten([1, 2, 3])
end
end
assert expand(before_expansion) == after_expansion
end
test "expands guards" do
before_expansion =
quote do
case w do
x when x when __ENV__.context -> true
end
end
after_expansion =
quote do
case w() do
x when x when :guard -> true
end
end
assert expand(before_expansion) == after_expansion
end
test "does not leaks vars on head" do
before_expansion =
quote do
case w do
x -> x
y -> y
end
:erlang.+(x, y)
end
after_expansion =
quote do
case w() do
x -> x
y -> y
end
:erlang.+(x(), y())
end
assert expand(before_expansion) == after_expansion
end
test "does not leak vars" do
before_expansion =
quote do
case w do
x -> x = x
y -> y = y
end
:erlang.+(x, y)
end
after_expansion =
quote do
case w() do
x -> x = x
y -> y = y
end
:erlang.+(x(), y())
end
assert expand(before_expansion) == after_expansion
end
test "expects exactly one do" do
assert_raise CompileError, ~r"missing :do option in \"case\"", fn ->
expand(quote(do: case(e, [])))
end
assert_raise CompileError, ~r"duplicated :do clauses given for \"case\"", fn ->
expand(quote(do: case(e, do: (x -> x), do: (y -> y))))
end
end
test "expects clauses" do
assert_raise CompileError, ~r"expected -> clauses for :do in \"case\"", fn ->
code =
quote do
case e do
x
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :do in \"case\"", fn ->
code =
quote do
case e do
[:not, :clauses]
end
end
expand(code)
end
end
test "expects exactly one argument in clauses" do
assert_raise CompileError, ~r"expected one arg for :do clauses \(->\) in \"case\"", fn ->
code =
quote do
case e do
_, _ -> :ok
end
end
expand(code)
end
end
test "fails with invalid arguments" do
assert_raise CompileError, ~r"invalid arguments for \"case\"", fn ->
expand(quote(do: case(:foo, :bar)))
end
end
test "fails for invalid options" do
assert_raise CompileError, ~r"unexpected option :foo in \"case\"", fn ->
expand(quote(do: case(e, do: (x -> x), foo: :bar)))
end
end
end
describe "receive" do
test "expands each clause" do
before_expansion =
quote do
receive do
x -> x
_ -> x
end
end
after_expansion =
quote do
receive do
x -> x
_ -> x()
end
end
assert expand(before_expansion) == after_expansion
end
test "does not share lexical scope between clauses" do
before_expansion =
quote do
receive do
1 -> import List
2 -> flatten([1, 2, 3])
end
end
after_expansion =
quote do
receive do
1 -> :"Elixir.List"
2 -> flatten([1, 2, 3])
end
end
assert expand(before_expansion) == after_expansion
end
test "expands guards" do
before_expansion =
quote do
receive do
x when x when __ENV__.context -> true
end
end
after_expansion =
quote do
receive do
x when x when :guard -> true
end
end
assert expand(before_expansion) == after_expansion
end
test "does not leaks clause vars" do
before_expansion =
quote do
receive do
x -> x
y -> y
end
:erlang.+(x, y)
end
after_expansion =
quote do
receive do
x -> x
y -> y
end
:erlang.+(x(), y())
end
assert expand(before_expansion) == after_expansion
end
test "does not leak vars" do
before_expansion =
quote do
receive do
x -> x = x
y -> y = y
end
:erlang.+(x, y)
end
after_expansion =
quote do
receive do
x -> x = x
y -> y = y
end
:erlang.+(x(), y())
end
assert expand(before_expansion) == after_expansion
end
test "does not leak vars on after" do
before_expansion =
quote do
receive do
x -> x = x
after
y ->
y
w = y
end
:erlang.+(x, w)
end
after_expansion =
quote do
receive do
x -> x = x
after
y() ->
y()
w = y()
end
:erlang.+(x(), w())
end
assert expand(before_expansion) == after_expansion
end
test "expects exactly one do or after" do
assert_raise CompileError, ~r"missing :do/:after option in \"receive\"", fn ->
expand(quote(do: receive([])))
end
assert_raise CompileError, ~r"duplicated :do clauses given for \"receive\"", fn ->
expand(quote(do: receive(do: (x -> x), do: (y -> y))))
end
assert_raise CompileError, ~r"duplicated :after clauses given for \"receive\"", fn ->
code =
quote do
receive do
x -> x
after
y -> y
after
z -> z
end
end
expand(code)
end
end
test "expects clauses" do
assert_raise CompileError, ~r"expected -> clauses for :do in \"receive\"", fn ->
code =
quote do
receive do
x
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :do in \"receive\"", fn ->
code =
quote do
receive do
[:not, :clauses]
end
end
expand(code)
end
end
test "expects on argument for do/after clauses" do
assert_raise CompileError, ~r"expected one arg for :do clauses \(->\) in \"receive\"", fn ->
code =
quote do
receive do
_, _ -> :ok
end
end
expand(code)
end
message = ~r"expected one arg for :after clauses \(->\) in \"receive\""
assert_raise CompileError, message, fn ->
code =
quote do
receive do
x -> x
after
_, _ -> :ok
end
end
expand(code)
end
end
test "expects a single clause for \"after\"" do
assert_raise CompileError, ~r"expected a single -> clause for :after in \"receive\"", fn ->
code =
quote do
receive do
x -> x
after
1 -> y
2 -> z
end
end
expand(code)
end
end
test "raises for invalid arguments" do
assert_raise CompileError, ~r"invalid arguments for \"receive\"", fn ->
expand(quote(do: receive(:foo)))
end
end
test "raises with invalid options" do
assert_raise CompileError, ~r"unexpected option :foo in \"receive\"", fn ->
expand(quote(do: receive(do: (x -> x), foo: :bar)))
end
end
end
describe "try" do
test "expands catch" do
before_expansion =
quote do
try do
x
catch
x, y -> z = :erlang.+(x, y)
end
z
end
after_expansion =
quote do
try do
x()
catch
x, y -> z = :erlang.+(x, y)
end
z()
end
assert expand(before_expansion) == after_expansion
end
test "expands after" do
before_expansion =
quote do
try do
x
after
z = y
end
z
end
after_expansion =
quote do
try do
x()
after
z = y()
end
z()
end
assert expand(before_expansion) == after_expansion
end
test "expands else" do
before_expansion =
quote do
try do
x
else
z -> z
end
z
end
after_expansion =
quote do
try do
x()
else
z -> z
end
z()
end
assert expand(before_expansion) == after_expansion
end
test "expands rescue" do
before_expansion =
quote do
try do
x
rescue
x -> x
Error -> x
end
x
end
after_expansion =
quote do
try do
x()
rescue
x -> x
unquote(:in)(_, [:"Elixir.Error"]) -> x()
end
x()
end
assert expand(before_expansion) == after_expansion
end
test "expects more than do" do
assert_raise CompileError, ~r"missing :catch/:rescue/:after/:else option in \"try\"", fn ->
code =
quote do
try do
x = y
end
x
end
expand(code)
end
end
test "raises if do is missing" do
assert_raise CompileError, ~r"missing :do option in \"try\"", fn ->
expand(quote(do: try([])))
end
end
test "expects at most one clause" do
assert_raise CompileError, ~r"duplicated :do clauses given for \"try\"", fn ->
expand(quote(do: try(do: e, do: f)))
end
assert_raise CompileError, ~r"duplicated :rescue clauses given for \"try\"", fn ->
code =
quote do
try do
e
rescue
x -> x
rescue
y -> y
end
end
expand(code)
end
assert_raise CompileError, ~r"duplicated :after clauses given for \"try\"", fn ->
code =
quote do
try do
e
after
x = y
after
x = y
end
end
expand(code)
end
assert_raise CompileError, ~r"duplicated :else clauses given for \"try\"", fn ->
code =
quote do
try do
e
else
x -> x
else
y -> y
end
end
expand(code)
end
assert_raise CompileError, ~r"duplicated :catch clauses given for \"try\"", fn ->
code =
quote do
try do
e
catch
x -> x
catch
y -> y
end
end
expand(code)
end
end
test "raises with invalid arguments" do
assert_raise CompileError, ~r"invalid arguments for \"try\"", fn ->
expand(quote(do: try(:foo)))
end
end
test "raises with invalid options" do
assert_raise CompileError, ~r"unexpected option :foo in \"try\"", fn ->
expand(quote(do: try(do: x, foo: :bar)))
end
end
test "expects exactly one argument in rescue clauses" do
assert_raise CompileError, ~r"expected one arg for :rescue clauses \(->\) in \"try\"", fn ->
code =
quote do
try do
x
rescue
_, _ -> :ok
end
end
expand(code)
end
end
test "expects an alias, a variable, or \"var in [alias]\" as the argument of rescue clauses" do
assert_raise CompileError, ~r"invalid \"rescue\" clause\. The clause should match", fn ->
code =
quote do
try do
x
rescue
function(:call) -> :ok
end
end
expand(code)
end
end
test "expects one or two args for catch clauses" do
message = ~r"expected one or two args for :catch clauses \(->\) in \"try\""
assert_raise CompileError, message, fn ->
code =
quote do
try do
x
catch
_, _, _ -> :ok
end
end
expand(code)
end
end
test "expects clauses for rescue, else, catch" do
assert_raise CompileError, ~r"expected -> clauses for :rescue in \"try\"", fn ->
code =
quote do
try do
e
rescue
x
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :rescue in \"try\"", fn ->
code =
quote do
try do
e
rescue
[:not, :clauses]
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :catch in \"try\"", fn ->
code =
quote do
try do
e
catch
x
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :catch in \"try\"", fn ->
code =
quote do
try do
e
catch
[:not, :clauses]
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :else in \"try\"", fn ->
code =
quote do
try do
e
else
x
end
end
expand(code)
end
assert_raise CompileError, ~r"expected -> clauses for :else in \"try\"", fn ->
code =
quote do
try do
e
else
[:not, :clauses]
end
end
expand(code)
end
end
end
describe "bitstrings" do
test "parallel match" do
assert expand(quote(do: <<foo>> = <<bar>>)) |> clean_meta([:alignment]) ==
quote(do: <<foo::integer()>> = <<bar()::integer()>>)
assert expand(quote(do: <<foo>> = baz = <<bar>>)) |> clean_meta([:alignment]) ==
quote(do: <<foo::integer()>> = baz = <<bar()::integer()>>)
assert expand(quote(do: <<foo>> = {<<baz>>} = bar())) |> clean_meta([:alignment]) ==
quote(do: <<foo::integer()>> = {<<baz::integer()>>} = bar())
message = ~r"binary patterns cannot be matched in parallel using \"=\""
assert_raise CompileError, message, fn ->
expand(quote(do: <<foo>> = <<baz>> = bar()))
end
assert_raise CompileError, message, fn ->
expand(quote(do: <<foo>> = qux = <<baz>> = bar()))
end
assert_raise CompileError, message, fn ->
expand(quote(do: {<<foo>>} = {qux} = {<<baz>>} = bar()))
end
assert expand(quote(do: {:foo, <<foo>>} = {<<baz>>, :baz} = bar()))
# 2-element tuples are special cased
assert_raise CompileError, message, fn ->
expand(quote(do: {:foo, <<foo>>} = {:foo, <<baz>>} = bar()))
end
assert_raise CompileError, message, fn ->
expand(quote(do: %{foo: <<foo>>} = %{baz: <<qux>>, foo: <<baz>>} = bar()))
end
assert expand(quote(do: %{foo: <<foo>>} = %{baz: <<baz>>} = bar()))
assert_raise CompileError, message, fn ->
expand(quote(do: %_{foo: <<foo>>} = %_{foo: <<baz>>} = bar()))
end
assert expand(quote(do: %_{foo: <<foo>>} = %_{baz: <<baz>>} = bar()))
assert_raise CompileError, message, fn ->
expand(quote(do: %_{foo: <<foo>>} = %{foo: <<baz>>} = bar()))
end
assert expand(quote(do: %_{foo: <<foo>>} = %{baz: <<baz>>} = bar()))
assert_raise CompileError, message, fn ->
code =
quote do
case bar() do
<<foo>> = <<baz>> -> nil
end
end
expand(code)
end
assert_raise CompileError, message, fn ->
code =
quote do
case bar() do
<<foo>> = qux = <<baz>> -> nil
end
end
expand(code)
end
assert_raise CompileError, message, fn ->
code =
quote do
case bar() do
[<<foo>>] = [<<baz>>] -> nil
end
end
expand(code)
end
end
test "nested match" do
assert expand(quote(do: <<foo = bar>>)) |> clean_meta([:alignment]) ==
quote(do: <<foo = bar()::integer()>>)
assert expand(quote(do: <<?-, <<_, _::binary>> = rest()::binary>>))
|> clean_meta([:alignment]) ==
quote(do: <<45::integer(), <<_::integer(), _::binary()>> = rest()::binary()>>)
message = ~r"cannot pattern match inside a bitstring that is already in match"
assert_raise CompileError, message, fn ->
expand(quote(do: <<bar = baz>> = foo()))
end
assert_raise CompileError, message, fn ->
expand(quote(do: <<?-, <<_, _::binary>> = rest::binary>> = foo()))
end
end
test "inlines binaries inside interpolation" do
import Kernel.ExpansionTarget
assert expand(quote(do: "foo#{bar()}" = "foobar")) |> clean_meta([:alignment]) ==
quote(do: <<"foo"::binary(), "bar"::binary()>> = "foobar")
end
test "expands size * unit" do
import Kernel, except: [-: 2]
assert expand(quote(do: <<x::13>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()-size(13)>>)
assert expand(quote(do: <<x::13*6>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()-unit(6)-size(13)>>)
assert expand(quote(do: <<x::_*6-binary>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::binary()-unit(6)>>)
assert expand(quote(do: <<x::13*6-binary>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::binary()-unit(6)-size(13)>>)
assert expand(quote(do: <<x::binary-(13 * 6)-binary>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::binary()-unit(6)-size(13)>>)
end
test "expands binary/bitstring specifiers" do
import Kernel, except: [-: 2]
assert expand(quote(do: <<x::binary>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::binary()>>)
assert expand(quote(do: <<x::bytes>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::binary()>>)
assert expand(quote(do: <<x::bitstring>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::bitstring()>>)
assert expand(quote(do: <<x::bits>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::bitstring()>>)
assert expand(quote(do: <<x::binary-little>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::binary()>>)
message = ~r"signed and unsigned specifiers are supported only on integer and float type"
assert_raise CompileError, message, fn ->
expand(quote(do: <<x()::binary-signed>>))
end
end
test "expands utf* specifiers" do
import Kernel, except: [-: 2]
assert expand(quote(do: <<x::utf8>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::utf8()>>)
assert expand(quote(do: <<x::utf16>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::utf16()>>)
assert expand(quote(do: <<x::utf32-little>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::utf32()-little()>>)
message = ~r"signed and unsigned specifiers are supported only on integer and float type"
assert_raise CompileError, message, fn ->
expand(quote(do: <<x()::utf8-signed>>))
end
assert_raise CompileError, ~r"size and unit are not supported on utf types", fn ->
expand(quote(do: <<x()::utf8-size(32)>>))
end
end
test "expands numbers specifiers" do
import Kernel, except: [-: 2]
assert expand(quote(do: <<x::integer>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()>>)
assert expand(quote(do: <<x::little>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()-little()>>)
assert expand(quote(do: <<x::signed>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()-signed()>>)
assert expand(quote(do: <<x::signed-native>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()-native()-signed()>>)
assert expand(quote(do: <<x::float-signed-native>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::float()-native()-signed()>>)
message =
~r"integer and float types require a size specifier if the unit specifier is given"
assert_raise CompileError, message, fn ->
expand(quote(do: <<x::unit(8)>>))
end
end
test "expands macro specifiers" do
import Kernel, except: [-: 2]
import Kernel.ExpansionTarget
assert expand(quote(do: <<x::seventeen>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer()-size(17)>>)
assert expand(quote(do: <<seventeen::seventeen, x::size(seventeen)>> = 1))
|> clean_meta([:alignment]) ==
quote(do: <<seventeen::integer()-size(17), x::integer()-size(seventeen)>> = 1)
end
test "expands macro in args" do
import Kernel, except: [-: 2]
before_expansion =
quote do
require Kernel.ExpansionTarget
<<x::size(Kernel.ExpansionTarget.seventeen())>>
end
after_expansion =
quote do
:"Elixir.Kernel.ExpansionTarget"
<<x()::integer()-size(17)>>
end
assert expand(before_expansion) |> clean_meta([:alignment]) == after_expansion
end
test "supports dynamic size" do
import Kernel, except: [-: 2]
before_expansion =
quote do
var = 1
<<x::size(var)-unit(8)>>
end
after_expansion =
quote do
var = 1
<<x()::integer()-unit(8)-size(var)>>
end
assert expand(before_expansion) |> clean_meta([:alignment]) == after_expansion
end
test "merges bitstrings" do
import Kernel, except: [-: 2]
assert expand(quote(do: <<x, <<y::signed-native>>, z>>)) |> clean_meta([:alignment]) ==
quote(do: <<x()::integer(), y()::integer()-native()-signed(), z()::integer()>>)
assert expand(quote(do: <<x, <<y::signed-native>>::bitstring, z>>))
|> clean_meta([:alignment]) ==
quote(do: <<x()::integer(), y()::integer()-native()-signed(), z()::integer()>>)
end
test "merges binaries" do
import Kernel, except: [-: 2]
assert expand(quote(do: "foo" <> x)) |> clean_meta([:alignment]) ==
quote(do: <<"foo"::binary(), x()::binary()>>)
assert expand(quote(do: "foo" <> <<x::size(4), y::size(4)>>)) |> clean_meta([:alignment]) ==
quote(do: <<"foo"::binary(), x()::integer()-size(4), y()::integer()-size(4)>>)
assert expand(quote(do: <<"foo", <<x::size(4), y::size(4)>>::binary>>))
|> clean_meta([:alignment]) ==
quote(do: <<"foo"::binary(), x()::integer()-size(4), y()::integer()-size(4)>>)
end
test "raises on unaligned binaries in match" do
message = ~r"cannot verify size of binary expression in match"
assert_raise CompileError, message, fn ->
expand(quote(do: <<rest::bits>> <> _ = "foo"))
end
assert_raise CompileError, message, fn ->
expand(quote(do: <<rest::size(3)>> <> _ = "foo"))
end
end
test "raises on size or unit for literal bitstrings" do
message = ~r"literal <<>> in bitstring supports only type specifiers"
assert_raise CompileError, message, fn ->
expand(quote(do: <<(<<"foo">>)::32>>))
end
end
test "raises on size or unit for literal strings" do
message = ~r"literal string in bitstring supports only endianness and type specifiers"
assert_raise CompileError, message, fn ->
expand(quote(do: <<"foo"::32>>))
end
end
test "raises for invalid size * unit for floats" do
message = ~r"float requires size\*unit to be 32 or 64 \(default\), got: 128"
assert_raise CompileError, message, fn ->
expand(quote(do: <<12.3::32*4>>))
end
message = ~r"float requires size\*unit to be 32 or 64 \(default\), got: 256"
assert_raise CompileError, message, fn ->
expand(quote(do: <<12.3::256>>))
end
end
test "raises for invalid size" do
message = ~r"size in bitstring expects an integer or a variable as argument, got: :oops"
assert_raise CompileError, message, fn ->
expand(quote(do: <<"foo"::size(:oops)>>))
end
end
test "raises for invalid unit" do
message = ~r"unit in bitstring expects an integer as argument, got: :oops"
assert_raise CompileError, message, fn ->
expand(quote(do: <<"foo"::size(8)-unit(:oops)>>))
end
end
test "raises for unknown specifier" do
assert_raise CompileError, ~r"unknown bitstring specifier: unknown()", fn ->
expand(quote(do: <<1::unknown>>))
end
end
test "raises for conflicting specifiers" do
assert_raise CompileError, ~r"conflicting endianness specification for bit field", fn ->
expand(quote(do: <<1::little-big>>))
end
assert_raise CompileError, ~r"conflicting unit specification for bit field", fn ->
expand(quote(do: <<x::bitstring-unit(2)>>))
end
end
test "raises for invalid literals" do
assert_raise CompileError, ~r"invalid literal :foo in <<>>", fn ->
expand(quote(do: <<:foo>>))
end
assert_raise CompileError, ~r"invalid literal \[\] in <<>>", fn ->
expand(quote(do: <<[]::size(8)>>))
end
end
test "raises on binary fields with size in matches" do
assert expand(quote(do: <<x::binary-size(3), y::binary>> = "foobar"))
message = ~r"a binary field without size is only allowed at the end of a binary pattern"
assert_raise CompileError, message, fn ->
expand(quote(do: <<x::binary, y::binary>> = "foobar"))
end
end
end
describe "op ambiguity" do
test "raises when a call is ambiguous" do
message = ~r["a -1" looks like a function call but there is a variable named "a"]
assert_raise CompileError, message, fn ->
# We use string_to_quoted! here to avoid the formatter adding parentheses to "a -1".
code =
Code.string_to_quoted!("""
a = 1
a -1
""")
expand(code)
end
end
end
test "handles invalid expressions" do
assert_raise CompileError, ~r"invalid quoted expression: {1, 2, 3}", fn ->
expand(quote(do: unquote({1, 2, 3})))
end
assert_raise CompileError, ~r"invalid quoted expression: #Function<", fn ->
expand(quote(do: unquote({:sample, fn -> nil end})))
end
assert_raise CompileError, ~r"invalid pattern in match", fn ->
code =
quote do
case true do
true && true -> true
end
end
expand(code)
end
assert_raise CompileError, ~r"invalid pattern in match", fn ->
code =
quote do
x = & &1
case true do
x.(false) -> true
end
end
expand(code)
end
assert_raise CompileError, ~r"invalid expression in guard", fn ->
code =
quote do
x = & &1
case true do
true when x.(true) -> true
end
end
expand(code)
end
assert_raise CompileError, ~r"invalid call foo\(1\)\(2\)", fn ->
expand(quote(do: foo(1)(2)))
end
assert_raise CompileError, ~r"invalid call 1\.foo\(\)", fn ->
expand(quote(do: 1.foo))
end
assert_raise CompileError, ~r"unhandled operator ->", fn ->
expand(quote(do: (foo -> bar)))
end
message = ~r/"wrong_fun" cannot handle clauses with the ->/
assert_raise CompileError, message, fn ->
code =
quote do
wrong_fun do
_ -> :ok
end
end
expand(code)
end
assert_raise CompileError, message, fn ->
code =
quote do
wrong_fun do
foo -> bar
after
:ok
end
end
expand(code)
end
assert_raise CompileError, ~r/"length" cannot handle clauses with the ->/, fn ->
code =
quote do
length do
_ -> :ok
end
end
expand(code)
end
assert_raise CompileError, ~r/undefined variable "foo"/, fn ->
code =
quote do
fn <<_::size(foo)>> -> :ok end
end
expand(code)
end
message = ~r"size in bitstring expects an integer or a variable as argument, got: foo()"
assert_raise CompileError, message, fn ->
code =
quote do
fn <<_::size(foo())>> -> :ok end
end
expand(code)
end
end
## Helpers
defmacro thirteen do
13
end
defp clean_meta(expr, vars) do
cleaner = &Keyword.drop(&1, vars)
Macro.prewalk(expr, &Macro.update_meta(&1, cleaner))
end
defp expand(expr) do
expand_env(expr, __ENV__) |> elem(0)
end
defp expand_env(expr, env) do
ExUnit.CaptureIO.capture_io(:stderr, fn ->
send(self(), {:expand_env, :elixir_expand.expand(expr, env)})
end)
receive do
{:expand_env, {expr, env}} -> {clean_meta(expr, [:version]), env}
end
end
end
| 25.474015 | 164 | 0.525822 |
08c801ad206baf7c960eb9f2e2ee114042f9848a | 249 | ex | Elixir | lib/bosque.ex | prio101/bosque | 3b9d0a789a4c33dce829d5cab9d198145f28b8fd | [
"MIT"
] | null | null | null | lib/bosque.ex | prio101/bosque | 3b9d0a789a4c33dce829d5cab9d198145f28b8fd | [
"MIT"
] | null | null | null | lib/bosque.ex | prio101/bosque | 3b9d0a789a4c33dce829d5cab9d198145f28b8fd | [
"MIT"
] | null | null | null | defmodule Bosque do
@moduledoc """
Bosque keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 24.9 | 66 | 0.751004 |
08c812a932c9d98c93922c1360a882a0a69f60f8 | 25,540 | exs | Elixir | deps/ecto/integration_test/cases/preload.exs | rpillar/Top5_Elixir | 9c450d2e9b291108ff1465dc066dfe442dbca822 | [
"MIT"
] | null | null | null | deps/ecto/integration_test/cases/preload.exs | rpillar/Top5_Elixir | 9c450d2e9b291108ff1465dc066dfe442dbca822 | [
"MIT"
] | null | null | null | deps/ecto/integration_test/cases/preload.exs | rpillar/Top5_Elixir | 9c450d2e9b291108ff1465dc066dfe442dbca822 | [
"MIT"
] | null | null | null | defmodule Ecto.Integration.PreloadTest do
use Ecto.Integration.Case, async: Application.get_env(:ecto, :async_integration_tests, true)
alias Ecto.Integration.TestRepo
import Ecto.Query
alias Ecto.Integration.Post
alias Ecto.Integration.Comment
alias Ecto.Integration.Permalink
alias Ecto.Integration.User
alias Ecto.Integration.Custom
test "preload with parameter from select_merge" do
p1 = TestRepo.insert!(%Post{title: "p1"})
TestRepo.insert!(%Comment{text: "c1", post: p1})
comments =
from(c in Comment, select: struct(c, [:text]))
|> select_merge([c], %{post_id: c.post_id})
|> preload(:post)
|> TestRepo.all()
assert [%{text: "c1", post: %{title: "p1"}}] = comments
end
test "preload has_many" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
p3 = TestRepo.insert!(%Post{title: "3"})
# We use the same text to expose bugs in preload sorting
%Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
%Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
%Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
%Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
assert %Ecto.Association.NotLoaded{} = p1.comments
[p3, p1, p2] = TestRepo.preload([p3, p1, p2], :comments)
assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id
assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id
assert [] = p3.comments
end
test "preload has_one" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
p3 = TestRepo.insert!(%Post{title: "3"})
%Permalink{id: pid1} = TestRepo.insert!(%Permalink{url: "1", post_id: p1.id})
%Permalink{} = TestRepo.insert!(%Permalink{url: "2", post_id: nil})
%Permalink{id: pid3} = TestRepo.insert!(%Permalink{url: "3", post_id: p3.id})
assert %Ecto.Association.NotLoaded{} = p1.permalink
assert %Ecto.Association.NotLoaded{} = p2.permalink
[p3, p1, p2] = TestRepo.preload([p3, p1, p2], :permalink)
assert %Permalink{id: ^pid1} = p1.permalink
refute p2.permalink
assert %Permalink{id: ^pid3} = p3.permalink
end
test "preload belongs_to" do
%Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
TestRepo.insert!(%Post{title: "2"})
%Post{id: pid3} = TestRepo.insert!(%Post{title: "3"})
pl1 = TestRepo.insert!(%Permalink{url: "1", post_id: pid1})
pl2 = TestRepo.insert!(%Permalink{url: "2", post_id: nil})
pl3 = TestRepo.insert!(%Permalink{url: "3", post_id: pid3})
assert %Ecto.Association.NotLoaded{} = pl1.post
[pl3, pl1, pl2] = TestRepo.preload([pl3, pl1, pl2], :post)
assert %Post{id: ^pid1} = pl1.post
refute pl2.post
assert %Post{id: ^pid3} = pl3.post
end
test "preload belongs_to with shared assocs" do
%Post{id: pid1} = TestRepo.insert!(%Post{title: "1"})
%Post{id: pid2} = TestRepo.insert!(%Post{title: "2"})
c1 = TestRepo.insert!(%Comment{text: "1", post_id: pid1})
c2 = TestRepo.insert!(%Comment{text: "2", post_id: pid1})
c3 = TestRepo.insert!(%Comment{text: "3", post_id: pid2})
[c3, c1, c2] = TestRepo.preload([c3, c1, c2], :post)
assert %Post{id: ^pid1} = c1.post
assert %Post{id: ^pid1} = c2.post
assert %Post{id: ^pid2} = c3.post
end
test "preload many_to_many" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
p3 = TestRepo.insert!(%Post{title: "3"})
# We use the same name to expose bugs in preload sorting
%User{id: uid1} = TestRepo.insert!(%User{name: "1"})
%User{id: uid3} = TestRepo.insert!(%User{name: "2"})
%User{id: uid2} = TestRepo.insert!(%User{name: "2"})
%User{id: uid4} = TestRepo.insert!(%User{name: "3"})
TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
[post_id: p1.id, user_id: uid2],
[post_id: p2.id, user_id: uid3],
[post_id: p2.id, user_id: uid4],
[post_id: p3.id, user_id: uid1],
[post_id: p3.id, user_id: uid4]]
assert %Ecto.Association.NotLoaded{} = p1.users
[p1, p2, p3] = TestRepo.preload([p1, p2, p3], :users)
assert [%User{id: ^uid1}, %User{id: ^uid2}] = p1.users |> sort_by_id
assert [%User{id: ^uid3}, %User{id: ^uid4}] = p2.users |> sort_by_id
assert [%User{id: ^uid1}, %User{id: ^uid4}] = p3.users |> sort_by_id
end
test "preload has_many through" do
%Post{id: pid1} = p1 = TestRepo.insert!(%Post{})
%Post{id: pid2} = p2 = TestRepo.insert!(%Post{})
%User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
%User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2})
[p1, p2] = TestRepo.preload([p1, p2], :comments_authors)
# Through was preloaded
[u1, u2] = p1.comments_authors |> sort_by_id
assert u1.id == uid1
assert u2.id == uid2
[u2] = p2.comments_authors
assert u2.id == uid2
# But we also preloaded everything along the way
assert [c1, c2, c3] = p1.comments |> sort_by_id
assert c1.author.id == uid1
assert c2.author.id == uid1
assert c3.author.id == uid2
assert [c4] = p2.comments
assert c4.author.id == uid2
end
test "preload has_one through" do
%Post{id: pid1} = TestRepo.insert!(%Post{})
%Post{id: pid2} = TestRepo.insert!(%Post{})
%Permalink{id: lid1} = TestRepo.insert!(%Permalink{post_id: pid1})
%Permalink{id: lid2} = TestRepo.insert!(%Permalink{post_id: pid2})
%Comment{} = c1 = TestRepo.insert!(%Comment{post_id: pid1})
%Comment{} = c2 = TestRepo.insert!(%Comment{post_id: pid1})
%Comment{} = c3 = TestRepo.insert!(%Comment{post_id: pid2})
[c1, c2, c3] = TestRepo.preload([c1, c2, c3], :post_permalink)
# Through was preloaded
assert c1.post.id == pid1
assert c1.post.permalink.id == lid1
assert c1.post_permalink.id == lid1
assert c2.post.id == pid1
assert c2.post.permalink.id == lid1
assert c2.post_permalink.id == lid1
assert c3.post.id == pid2
assert c3.post.permalink.id == lid2
assert c3.post_permalink.id == lid2
end
test "preload through with nil association" do
%Comment{} = c = TestRepo.insert!(%Comment{post_id: nil})
c = TestRepo.preload(c, [:post, :post_permalink])
assert c.post == nil
assert c.post_permalink == nil
c = TestRepo.preload(c, [:post, :post_permalink])
assert c.post == nil
assert c.post_permalink == nil
end
test "preload has_many through-through" do
%Post{id: pid1} = TestRepo.insert!(%Post{})
%Post{id: pid2} = TestRepo.insert!(%Post{})
%Permalink{} = l1 = TestRepo.insert!(%Permalink{post_id: pid1})
%Permalink{} = l2 = TestRepo.insert!(%Permalink{post_id: pid2})
%User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
%User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid2, author_id: uid2})
# With assoc query
[l1, l2] = TestRepo.preload([l1, l2], :post_comments_authors)
# Through was preloaded
[u1, u2] = l1.post_comments_authors |> sort_by_id
assert u1.id == uid1
assert u2.id == uid2
[u2] = l2.post_comments_authors
assert u2.id == uid2
# But we also preloaded everything along the way
assert l1.post.id == pid1
assert l1.post.comments != []
assert l2.post.id == pid2
assert l2.post.comments != []
end
test "preload has_many through many_to_many" do
%Post{} = p1 = TestRepo.insert!(%Post{})
%Post{} = p2 = TestRepo.insert!(%Post{})
%User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
%User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
[post_id: p1.id, user_id: uid2],
[post_id: p2.id, user_id: uid2]]
%Comment{id: cid1} = TestRepo.insert!(%Comment{author_id: uid1})
%Comment{id: cid2} = TestRepo.insert!(%Comment{author_id: uid1})
%Comment{id: cid3} = TestRepo.insert!(%Comment{author_id: uid2})
%Comment{id: cid4} = TestRepo.insert!(%Comment{author_id: uid2})
[p1, p2] = TestRepo.preload([p1, p2], :users_comments)
# Through was preloaded
[c1, c2, c3, c4] = p1.users_comments |> sort_by_id
assert c1.id == cid1
assert c2.id == cid2
assert c3.id == cid3
assert c4.id == cid4
[c3, c4] = p2.users_comments |> sort_by_id
assert c3.id == cid3
assert c4.id == cid4
# But we also preloaded everything along the way
assert [u1, u2] = p1.users |> sort_by_id
assert u1.id == uid1
assert u2.id == uid2
assert [u2] = p2.users
assert u2.id == uid2
end
## Empties
test "preload empty" do
assert TestRepo.preload([], :anything_goes) == []
end
test "preload has_many with no associated entries" do
p = TestRepo.insert!(%Post{title: "1"})
p = TestRepo.preload(p, :comments)
assert p.title == "1"
assert p.comments == []
end
test "preload has_one with no associated entries" do
p = TestRepo.insert!(%Post{title: "1"})
p = TestRepo.preload(p, :permalink)
assert p.title == "1"
assert p.permalink == nil
end
test "preload belongs_to with no associated entry" do
c = TestRepo.insert!(%Comment{text: "1"})
c = TestRepo.preload(c, :post)
assert c.text == "1"
assert c.post == nil
end
test "preload many_to_many with no associated entries" do
p = TestRepo.insert!(%Post{title: "1"})
p = TestRepo.preload(p, :users)
assert p.title == "1"
assert p.users == []
end
## With queries
test "preload with function" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
p3 = TestRepo.insert!(%Post{title: "3"})
# We use the same text to expose bugs in preload sorting
%Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
%Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
%Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
%Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
comments: fn _ -> TestRepo.all(Comment) end)
assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = pe1.comments
assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = pe2.comments
assert [] = pe3.comments
end
test "preload many_to_many with function" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
p3 = TestRepo.insert!(%Post{title: "3"})
# We use the same name to expose bugs in preload sorting
%User{id: uid1} = TestRepo.insert!(%User{name: "1"})
%User{id: uid3} = TestRepo.insert!(%User{name: "2"})
%User{id: uid2} = TestRepo.insert!(%User{name: "2"})
%User{id: uid4} = TestRepo.insert!(%User{name: "3"})
TestRepo.insert_all "posts_users", [[post_id: p1.id, user_id: uid1],
[post_id: p1.id, user_id: uid2],
[post_id: p2.id, user_id: uid3],
[post_id: p2.id, user_id: uid4],
[post_id: p3.id, user_id: uid1],
[post_id: p3.id, user_id: uid4]]
wrong_preloader = fn post_ids ->
TestRepo.all(
from u in User,
join: pu in "posts_users",
where: pu.post_id in ^post_ids and pu.user_id == u.id,
order_by: u.id,
select: map(u, [:id])
)
end
assert_raise RuntimeError, ~r/invalid custom preload for `users` on `Ecto.Integration.Post`/, fn ->
TestRepo.preload([p1, p2, p3], users: wrong_preloader)
end
right_preloader = fn post_ids ->
TestRepo.all(
from u in User,
join: pu in "posts_users",
where: pu.post_id in ^post_ids and pu.user_id == u.id,
order_by: u.id,
select: {pu.post_id, map(u, [:id])}
)
end
[p1, p2, p3] = TestRepo.preload([p1, p2, p3], users: right_preloader)
assert p1.users == [%{id: uid1}, %{id: uid2}]
assert p2.users == [%{id: uid3}, %{id: uid4}]
assert p3.users == [%{id: uid1}, %{id: uid4}]
end
test "preload with query" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
p3 = TestRepo.insert!(%Post{title: "3"})
# We use the same text to expose bugs in preload sorting
%Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
%Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
%Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
%Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
assert %Ecto.Association.NotLoaded{} = p1.comments
# With empty query
assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
comments: from(c in Comment, where: false))
assert [] = pe1.comments
assert [] = pe2.comments
assert [] = pe3.comments
# With custom select
assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
comments: from(c in Comment, select: c.id))
assert [^cid1, ^cid2] = pe1.comments
assert [^cid3, ^cid4] = pe2.comments
assert [] = pe3.comments
# With custom ordered query
assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
comments: from(c in Comment, order_by: [desc: c.text]))
assert [%Comment{id: ^cid2}, %Comment{id: ^cid1}] = pe1.comments
assert [%Comment{id: ^cid4}, %Comment{id: ^cid3}] = pe2.comments
assert [] = pe3.comments
# With custom ordered query with preload
assert [pe3, pe1, pe2] = TestRepo.preload([p3, p1, p2],
comments: {from(c in Comment, order_by: [desc: c.text]), :post})
assert [%Comment{id: ^cid2} = c2, %Comment{id: ^cid1} = c1] = pe1.comments
assert [%Comment{id: ^cid4} = c4, %Comment{id: ^cid3} = c3] = pe2.comments
assert [] = pe3.comments
assert c1.post.title == "1"
assert c2.post.title == "1"
assert c3.post.title == "2"
assert c4.post.title == "2"
end
test "preload through with query" do
%Post{id: pid1} = p1 = TestRepo.insert!(%Post{})
u1 = TestRepo.insert!(%User{name: "foo"})
u2 = TestRepo.insert!(%User{name: "bar"})
u3 = TestRepo.insert!(%User{name: "baz"})
u4 = TestRepo.insert!(%User{name: "norf"})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u1.id})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u1.id})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u2.id})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u3.id})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: u4.id})
np1 = TestRepo.preload(p1, comments_authors: from(u in User, where: u.name == "foo"))
assert np1.comments_authors == [u1]
assert_raise ArgumentError, ~r/Ecto expected a map\/struct with the key `id` but got: \d+/, fn ->
TestRepo.preload(p1, comments_authors: from(u in User, order_by: u.name, select: u.id))
end
# The subpreload order does not matter because the result is dictated by comments
np1 = TestRepo.preload(p1, comments_authors: from(u in User, order_by: u.name, select: %{id: u.id}))
assert np1.comments_authors ==
[%{id: u1.id}, %{id: u2.id}, %{id: u3.id}, %{id: u4.id}]
end
## With take
test "preload with take" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
_p = TestRepo.insert!(%Post{title: "3"})
%Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
%Comment{id: cid3} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
%Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
%Comment{id: cid4} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
assert %Ecto.Association.NotLoaded{} = p1.comments
posts = TestRepo.all(from Post, preload: [:comments], select: [:id, comments: [:id, :post_id]])
[p1, p2, p3] = sort_by_id(posts)
assert p1.title == nil
assert p2.title == nil
assert p3.title == nil
assert [%{id: ^cid1, text: nil}, %{id: ^cid2, text: nil}] = sort_by_id(p1.comments)
assert [%{id: ^cid3, text: nil}, %{id: ^cid4, text: nil}] = sort_by_id(p2.comments)
assert [] = sort_by_id(p3.comments)
end
test "preload through with take" do
%Post{id: pid1} = TestRepo.insert!(%Post{})
%User{id: uid1} = TestRepo.insert!(%User{name: "foo"})
%User{id: uid2} = TestRepo.insert!(%User{name: "bar"})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid1})
%Comment{} = TestRepo.insert!(%Comment{post_id: pid1, author_id: uid2})
[p1] = TestRepo.all from Post, preload: [:comments_authors], select: [:id, comments_authors: :id]
[%{id: ^uid1, name: nil}, %{id: ^uid2, name: nil}] = p1.comments_authors |> sort_by_id
end
## Nested
test "preload many assocs" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
assert [p2, p1] = TestRepo.preload([p2, p1], [:comments, :users])
assert p1.comments == []
assert p2.comments == []
assert p1.users == []
assert p2.users == []
end
test "preload nested" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
TestRepo.insert!(%Comment{text: "4", post_id: p2.id})
assert [p2, p1] = TestRepo.preload([p2, p1], [comments: :post])
assert [c1, c2] = p1.comments
assert [c3, c4] = p2.comments
assert p1.id == c1.post.id
assert p1.id == c2.post.id
assert p2.id == c3.post.id
assert p2.id == c4.post.id
end
test "preload nested via custom query" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
TestRepo.insert!(%Comment{text: "4", post_id: p2.id})
query = from(c in Comment, preload: :post, order_by: [desc: c.text])
assert [p2, p1] = TestRepo.preload([p2, p1], comments: query)
assert [c2, c1] = p1.comments
assert [c4, c3] = p2.comments
assert p1.id == c1.post.id
assert p1.id == c2.post.id
assert p2.id == c3.post.id
assert p2.id == c4.post.id
end
## Others
@tag :invalid_prefix
test "preload custom prefix from schema" do
p = TestRepo.insert!(%Post{title: "1"})
p = Ecto.put_meta(p, prefix: "this_surely_does_not_exist")
# This preload should fail because it points to a prefix that does not exist
assert catch_error(TestRepo.preload(p, [:comments]))
end
@tag :invalid_prefix
test "preload custom prefix from options" do
p = TestRepo.insert!(%Post{title: "1"})
# This preload should fail because it points to a prefix that does not exist
assert catch_error(TestRepo.preload(p, [:comments], prefix: "this_surely_does_not_exist"))
end
test "preload with binary_id" do
c = TestRepo.insert!(%Custom{})
u = TestRepo.insert!(%User{custom_id: c.bid})
u = TestRepo.preload(u, :custom)
assert u.custom.bid == c.bid
end
test "preload skips with association set but without id" do
c1 = TestRepo.insert!(%Comment{text: "1"})
u1 = TestRepo.insert!(%User{name: "name"})
p1 = TestRepo.insert!(%Post{title: "title"})
c1 = %{c1 | author: u1, author_id: nil, post: p1, post_id: nil}
c1 = TestRepo.preload(c1, [:author, :post])
assert c1.author == u1
assert c1.post == p1
end
test "preload skips already loaded for cardinality one" do
%Post{id: pid} = TestRepo.insert!(%Post{title: "1"})
c1 = %Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: pid})
c2 = %Comment{id: _cid} = TestRepo.insert!(%Comment{text: "2", post_id: nil})
[c1, c2] = TestRepo.preload([c1, c2], :post)
assert %Post{id: ^pid} = c1.post
assert c2.post == nil
[c1, c2] = TestRepo.preload([c1, c2], post: :comments)
assert [%Comment{id: ^cid1}] = c1.post.comments
TestRepo.update_all Post, set: [title: "0"]
TestRepo.update_all Comment, set: [post_id: pid]
# Preloading once again shouldn't change the result
[c1, c2] = TestRepo.preload([c1, c2], :post)
assert %Post{id: ^pid, title: "1", comments: [_|_]} = c1.post
assert c2.post == nil
[c1, c2] = TestRepo.preload([c1, %{c2 | post_id: pid}], :post, force: true)
assert %Post{id: ^pid, title: "0", comments: %Ecto.Association.NotLoaded{}} = c1.post
assert %Post{id: ^pid, title: "0", comments: %Ecto.Association.NotLoaded{}} = c2.post
end
test "preload skips already loaded for cardinality many" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
%Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
%Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p2.id})
[p1, p2] = TestRepo.preload([p1, p2], :comments)
assert [%Comment{id: ^cid1}] = p1.comments
assert [%Comment{id: ^cid2}] = p2.comments
[p1, p2] = TestRepo.preload([p1, p2], comments: :post)
assert hd(p1.comments).post.id == p1.id
assert hd(p2.comments).post.id == p2.id
TestRepo.update_all Comment, set: [text: "0"]
# Preloading once again shouldn't change the result
[p1, p2] = TestRepo.preload([p1, p2], :comments)
assert [%Comment{id: ^cid1, text: "1", post: %Post{}}] = p1.comments
assert [%Comment{id: ^cid2, text: "2", post: %Post{}}] = p2.comments
[p1, p2] = TestRepo.preload([p1, p2], :comments, force: true)
assert [%Comment{id: ^cid1, text: "0", post: %Ecto.Association.NotLoaded{}}] = p1.comments
assert [%Comment{id: ^cid2, text: "0", post: %Ecto.Association.NotLoaded{}}] = p2.comments
end
test "preload keyword query" do
p1 = TestRepo.insert!(%Post{title: "1"})
p2 = TestRepo.insert!(%Post{title: "2"})
TestRepo.insert!(%Post{title: "3"})
%Comment{id: cid1} = TestRepo.insert!(%Comment{text: "1", post_id: p1.id})
%Comment{id: cid2} = TestRepo.insert!(%Comment{text: "2", post_id: p1.id})
%Comment{id: cid3} = TestRepo.insert!(%Comment{text: "3", post_id: p2.id})
%Comment{id: cid4} = TestRepo.insert!(%Comment{text: "4", post_id: p2.id})
# Regular query
query = from(p in Post, preload: [:comments], select: p)
assert [p1, p2, p3] = TestRepo.all(query) |> sort_by_id
assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id
assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id
assert [] = p3.comments
# Query with interpolated preload query
query = from(p in Post, preload: [comments: ^from(c in Comment, where: false)], select: p)
assert [p1, p2, p3] = TestRepo.all(query)
assert [] = p1.comments
assert [] = p2.comments
assert [] = p3.comments
# Now let's use an interpolated preload too
comments = [:comments]
query = from(p in Post, preload: ^comments, select: {0, [p], 1, 2})
posts = TestRepo.all(query)
[p1, p2, p3] = Enum.map(posts, fn {0, [p], 1, 2} -> p end) |> sort_by_id
assert [%Comment{id: ^cid1}, %Comment{id: ^cid2}] = p1.comments |> sort_by_id
assert [%Comment{id: ^cid3}, %Comment{id: ^cid4}] = p2.comments |> sort_by_id
assert [] = p3.comments
end
defp sort_by_id(values) do
Enum.sort_by(values, &(&1.id))
end
end
| 38.52187 | 111 | 0.594323 |
08c83f0e37de5c89f68315d379f0f5347f35d48e | 713 | exs | Elixir | lib/mix/test/mix/escriptize_test.exs | joearms/elixir | 9a0f8107bd8bbd089acb96fe0041d61a05e88a9b | [
"Apache-2.0"
] | 4 | 2016-04-05T05:51:36.000Z | 2019-10-31T06:46:35.000Z | lib/mix/test/mix/escriptize_test.exs | joearms/elixir | 9a0f8107bd8bbd089acb96fe0041d61a05e88a9b | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/escriptize_test.exs | joearms/elixir | 9a0f8107bd8bbd089acb96fe0041d61a05e88a9b | [
"Apache-2.0"
] | 5 | 2015-02-01T06:01:19.000Z | 2019-08-29T09:02:35.000Z | Code.require_file "../test_helper.exs", __DIR__
defmodule Mix.EscriptizeTest do
use MixTest.Case
test "generate simple escript" do
in_fixture "escripttest", fn ->
output = mix "escriptize"
assert output =~ %r/Generated escript escripttest/
assert System.cmd("escript escripttest") == "TEST\n"
output = mix "escriptize"
assert output == ""
end
end
test "generate simple escript with path" do
in_fixture "escripttestwithpath", fn ->
output = mix "escriptize"
assert output =~ %r/Generated escript ebin(\/|\\)escripttestwithpath/
assert System.cmd("escript " <> Path.join("ebin", "escripttestwithpath")) == "TEST_WITH_PATH\n"
end
end
end
| 28.52 | 101 | 0.669004 |
08c848533d513916bb30628687250e10860cd73c | 3,314 | ex | Elixir | lib/ketbin_web/controllers/page_controller.ex | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 4 | 2020-08-05T20:05:34.000Z | 2020-10-01T10:01:56.000Z | lib/ketbin_web/controllers/page_controller.ex | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 1 | 2020-07-08T05:02:12.000Z | 2020-09-25T10:05:11.000Z | lib/ketbin_web/controllers/page_controller.ex | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 1 | 2020-08-30T12:59:49.000Z | 2020-08-30T12:59:49.000Z | defmodule KetbinWeb.PageController do
require Logger
use KetbinWeb, :controller
alias Ketbin.Pastes
alias Ketbin.Pastes.Paste
alias Ketbin.Pastes.Utils
def index(conn, _params) do
changeset = Pastes.change_paste(%Paste{})
render(conn, "index.html", changeset: changeset)
end
def show(%{assigns: %{show_edit: show_edit}} = conn, %{"id" => id}) do
[head | tail] = String.split(id, ".")
# fetch paste from db
paste = Pastes.get_paste!(head)
# paste is a url, redirect
# regular paste, show content
if paste.is_url do
redirect(conn,
external: paste.content |> String.replace("\r", "") |> String.replace("\n", "")
)
else
render(conn, "show.html",
paste: paste,
show_edit: show_edit,
extension: List.first(tail) || ""
)
end
end
def showlink(%{assigns: %{show_edit: show_edit}} = conn, %{"id" => id}) do
[head | tail] = String.split(id, ".")
paste = Pastes.get_paste!(head)
render(conn, "show.html",
paste: paste,
show_edit: show_edit,
extension: if(tail == [], do: "", else: tail)
)
end
def raw(conn, %{"id" => id}) do
paste = Pastes.get_paste!(id)
text(conn, paste.content)
end
def create(%{assigns: %{current_user: current_user}} = conn, %{"paste" => paste_params}) do
# generate phonetic key
id = Utils.generate_key()
# check if content is a url
is_url =
Map.get(paste_params, "content")
|> Utils.is_url?()
# put id and is_url values into changeset
paste_params =
Map.put(paste_params, "id", id)
|> Map.put("is_url", is_url)
|> Map.put("belongs_to", current_user && current_user.id)
# attempt to create a paste
case Pastes.create_paste(paste_params) do
# all good, redirect
{:ok, paste} ->
unless is_url do
conn
# is a regular paste, take to regular route
|> redirect(to: Routes.page_path(conn, :show, paste))
else
conn
# is a url, take to route with /v/ prefix
|> redirect(to: Routes.page_path(conn, :showlink, paste))
end
# something went wrong, bail
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "index.html", changeset: changeset)
end
end
def edit(conn, %{"id" => id}) do
paste = Pastes.get_paste!(id)
changeset = Pastes.change_paste(paste)
render(conn, "edit.html", paste: paste, changeset: changeset)
end
def update(conn, %{"id" => id, "paste" => paste_params}) do
paste = Pastes.get_paste!(id)
# check if content is a url
is_url =
Map.get(paste_params, "content")
|> Utils.is_url?()
paste_params = Map.put(paste_params, "is_url", is_url)
case Pastes.update_paste(paste, paste_params) do
{:ok, paste} ->
unless is_url do
conn
|> put_flash(:info, "Paste updated successfully.")
|> redirect(to: Routes.page_path(conn, :show, paste))
else
conn
|> put_flash(:info, "Paste updated successfully.")
|> redirect(to: Routes.page_path(conn, :showlink, paste))
end
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "edit.html", paste: paste, changeset: changeset)
end
end
end
| 27.616667 | 93 | 0.595353 |
08c8821f01818156ca27e38a331c07a800d52578 | 53,491 | ex | Elixir | lib/baiji/service/direct_connect.ex | wrren/baiji | d3d9e1cad875c6e1ddb47bf52511c3a07321764a | [
"MIT"
] | null | null | null | lib/baiji/service/direct_connect.ex | wrren/baiji | d3d9e1cad875c6e1ddb47bf52511c3a07321764a | [
"MIT"
] | null | null | null | lib/baiji/service/direct_connect.ex | wrren/baiji | d3d9e1cad875c6e1ddb47bf52511c3a07321764a | [
"MIT"
] | null | null | null | defmodule Baiji.DirectConnect do
@moduledoc """
AWS Direct Connect links your internal network to an AWS Direct Connect
location over a standard 1 gigabit or 10 gigabit Ethernet fiber-optic
cable. One end of the cable is connected to your router, the other to an
AWS Direct Connect router. With this connection in place, you can create
virtual interfaces directly to the AWS cloud (for example, to Amazon
Elastic Compute Cloud (Amazon EC2) and Amazon Simple Storage Service
(Amazon S3)) and to Amazon Virtual Private Cloud (Amazon VPC), bypassing
Internet service providers in your network path. An AWS Direct Connect
location provides access to AWS in the region it is associated with, as
well as access to other US regions. For example, you can provision a single
connection to any AWS Direct Connect location in the US and use it to
access public AWS services in all US Regions and AWS GovCloud (US).
"""
@doc """
Creates a new public virtual interface. A virtual interface is the VLAN
that transports AWS Direct Connect traffic. A public virtual interface
supports sending traffic to public services of AWS such as Amazon Simple
Storage Service (Amazon S3).
When creating an IPv6 public virtual interface (addressFamily is 'ipv6'),
the customer and amazon address fields should be left blank to use
auto-assigned IPv6 space. Custom IPv6 Addresses are currently not
supported.
"""
def create_public_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "CreatePublicVirtualInterface",
method: :post,
input_shape: "CreatePublicVirtualInterfaceRequest",
output_shape: "VirtualInterface",
endpoint: __spec__()
}
end
@doc """
Associates an existing connection with a link aggregation group (LAG). The
connection is interrupted and re-established as a member of the LAG
(connectivity to AWS will be interrupted). The connection must be hosted on
the same AWS Direct Connect endpoint as the LAG, and its bandwidth must
match the bandwidth for the LAG. You can reassociate a connection that's
currently associated with a different LAG; however, if removing the
connection will cause the original LAG to fall below its setting for
minimum number of operational connections, the request fails.
Any virtual interfaces that are directly associated with the connection are
automatically re-associated with the LAG. If the connection was originally
associated with a different LAG, the virtual interfaces remain associated
with the original LAG.
For interconnects, any hosted connections are automatically re-associated
with the LAG. If the interconnect was originally associated with a
different LAG, the hosted connections remain associated with the original
LAG.
"""
def associate_connection_with_lag(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AssociateConnectionWithLag",
method: :post,
input_shape: "AssociateConnectionWithLagRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Returns the LOA-CFA for a connection, interconnect, or link aggregation
group (LAG).
The Letter of Authorization - Connecting Facility Assignment (LOA-CFA) is a
document that is used when establishing your cross connect to AWS at the
colocation facility. For more information, see [Requesting Cross Connects
at AWS Direct Connect
Locations](http://docs.aws.amazon.com/directconnect/latest/UserGuide/Colocation.html)
in the AWS Direct Connect user guide.
"""
def describe_loa(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeLoa",
method: :post,
input_shape: "DescribeLoaRequest",
output_shape: "Loa",
endpoint: __spec__()
}
end
@doc """
Associates a virtual interface with a specified link aggregation group
(LAG) or connection. Connectivity to AWS is temporarily interrupted as the
virtual interface is being migrated. If the target connection or LAG has an
associated virtual interface with a conflicting VLAN number or a
conflicting IP address, the operation fails.
Virtual interfaces associated with a hosted connection cannot be associated
with a LAG; hosted connections must be migrated along with their virtual
interfaces using `AssociateHostedConnection`.
Hosted virtual interfaces (an interface for which the owner of the
connection is not the owner of physical connection) can only be
reassociated by the owner of the physical connection.
"""
def associate_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AssociateVirtualInterface",
method: :post,
input_shape: "AssociateVirtualInterfaceRequest",
output_shape: "VirtualInterface",
endpoint: __spec__()
}
end
@doc """
Adds the specified tags to the specified Direct Connect resource. Each
Direct Connect resource can have a maximum of 50 tags.
Each tag consists of a key and an optional value. If a tag with the same
key is already associated with the Direct Connect resource, this action
updates its value.
"""
def tag_resource(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "TagResource",
method: :post,
input_shape: "TagResourceRequest",
output_shape: "TagResourceResponse",
endpoint: __spec__()
}
end
@doc """
Deprecated in favor of `DescribeLoa`.
Returns the LOA-CFA for an Interconnect.
The Letter of Authorization - Connecting Facility Assignment (LOA-CFA) is a
document that is used when establishing your cross connect to AWS at the
colocation facility. For more information, see [Requesting Cross Connects
at AWS Direct Connect
Locations](http://docs.aws.amazon.com/directconnect/latest/UserGuide/Colocation.html)
in the AWS Direct Connect user guide.
"""
def describe_interconnect_loa(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeInterconnectLoa",
method: :post,
input_shape: "DescribeInterconnectLoaRequest",
output_shape: "DescribeInterconnectLoaResponse",
endpoint: __spec__()
}
end
@doc """
Deletes a BGP peer on the specified virtual interface that matches the
specified customer address and ASN. You cannot delete the last BGP peer
from a virtual interface.
"""
def delete_b_g_p_peer(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DeleteBGPPeer",
method: :post,
input_shape: "DeleteBGPPeerRequest",
output_shape: "DeleteBGPPeerResponse",
endpoint: __spec__()
}
end
@doc """
Deprecated in favor of `AllocateHostedConnection`.
Creates a hosted connection on an interconnect.
Allocates a VLAN number and a specified amount of bandwidth for use by a
hosted connection on the given interconnect.
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def allocate_connection_on_interconnect(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AllocateConnectionOnInterconnect",
method: :post,
input_shape: "AllocateConnectionOnInterconnectRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Deletes a virtual interface.
"""
def delete_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DeleteVirtualInterface",
method: :post,
input_shape: "DeleteVirtualInterfaceRequest",
output_shape: "DeleteVirtualInterfaceResponse",
endpoint: __spec__()
}
end
@doc """
Deletes a link aggregation group (LAG). You cannot delete a LAG if it has
active virtual interfaces or hosted connections.
"""
def delete_lag(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DeleteLag",
method: :post,
input_shape: "DeleteLagRequest",
output_shape: "Lag",
endpoint: __spec__()
}
end
@doc """
Describes the link aggregation groups (LAGs) in your account.
If a LAG ID is provided, only information about the specified LAG is
returned.
"""
def describe_lags(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeLags",
method: :post,
input_shape: "DescribeLagsRequest",
output_shape: "Lags",
endpoint: __spec__()
}
end
@doc """
Returns a list of hosted connections that have been provisioned on the
given interconnect or link aggregation group (LAG).
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def describe_hosted_connections(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeHostedConnections",
method: :post,
input_shape: "DescribeHostedConnectionsRequest",
output_shape: "Connections",
endpoint: __spec__()
}
end
@doc """
Deprecated in favor of `DescribeHostedConnections`.
Returns a list of connections that have been provisioned on the given
interconnect.
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def describe_connections_on_interconnect(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeConnectionsOnInterconnect",
method: :post,
input_shape: "DescribeConnectionsOnInterconnectRequest",
output_shape: "Connections",
endpoint: __spec__()
}
end
@doc """
Removes one or more tags from the specified Direct Connect resource.
"""
def untag_resource(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "UntagResource",
method: :post,
input_shape: "UntagResourceRequest",
output_shape: "UntagResourceResponse",
endpoint: __spec__()
}
end
@doc """
Associates a hosted connection and its virtual interfaces with a link
aggregation group (LAG) or interconnect. If the target interconnect or LAG
has an existing hosted connection with a conflicting VLAN number or IP
address, the operation fails. This action temporarily interrupts the hosted
connection's connectivity to AWS as it is being migrated.
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def associate_hosted_connection(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AssociateHostedConnection",
method: :post,
input_shape: "AssociateHostedConnectionRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Returns the list of AWS Direct Connect locations in the current AWS region.
These are the locations that may be selected when calling CreateConnection
or CreateInterconnect.
"""
def describe_locations(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeLocations",
method: :post,
input_shape: "",
output_shape: "Locations",
endpoint: __spec__()
}
end
@doc """
Creates a new connection between the customer network and a specific AWS
Direct Connect location.
A connection links your internal network to an AWS Direct Connect location
over a standard 1 gigabit or 10 gigabit Ethernet fiber-optic cable. One end
of the cable is connected to your router, the other to an AWS Direct
Connect router. An AWS Direct Connect location provides access to Amazon
Web Services in the region it is associated with. You can establish
connections with AWS Direct Connect locations in multiple regions, but a
connection in one region does not provide connectivity to other regions.
You can automatically add the new connection to a link aggregation group
(LAG) by specifying a LAG ID in the request. This ensures that the new
connection is allocated on the same AWS Direct Connect endpoint that hosts
the specified LAG. If there are no available ports on the endpoint, the
request fails and no connection will be created.
"""
def create_connection(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "CreateConnection",
method: :post,
input_shape: "CreateConnectionRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Creates a new link aggregation group (LAG) with the specified number of
bundled physical connections between the customer network and a specific
AWS Direct Connect location. A LAG is a logical interface that uses the
Link Aggregation Control Protocol (LACP) to aggregate multiple 1 gigabit or
10 gigabit interfaces, allowing you to treat them as a single interface.
All connections in a LAG must use the same bandwidth (for example, 10
Gbps), and must terminate at the same AWS Direct Connect endpoint.
You can have up to 10 connections per LAG. Regardless of this limit, if you
request more connections for the LAG than AWS Direct Connect can allocate
on a single endpoint, no LAG is created.
You can specify an existing physical connection or interconnect to include
in the LAG (which counts towards the total number of connections). Doing so
interrupts the current physical connection or hosted connections, and
re-establishes them as a member of the LAG. The LAG will be created on the
same AWS Direct Connect endpoint to which the connection terminates. Any
virtual interfaces associated with the connection are automatically
disassociated and re-associated with the LAG. The connection ID does not
change.
If the AWS account used to create a LAG is a registered AWS Direct Connect
partner, the LAG is automatically enabled to host sub-connections. For a
LAG owned by a partner, any associated virtual interfaces cannot be
directly configured.
"""
def create_lag(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "CreateLag",
method: :post,
input_shape: "CreateLagRequest",
output_shape: "Lag",
endpoint: __spec__()
}
end
@doc """
Disassociates a connection from a link aggregation group (LAG). The
connection is interrupted and re-established as a standalone connection
(the connection is not deleted; to delete the connection, use the
`DeleteConnection` request). If the LAG has associated virtual interfaces
or hosted connections, they remain associated with the LAG. A disassociated
connection owned by an AWS Direct Connect partner is automatically
converted to an interconnect.
If disassociating the connection will cause the LAG to fall below its
setting for minimum number of operational connections, the request fails,
except when it's the last member of the LAG. If all connections are
disassociated, the LAG continues to exist as an empty LAG with no physical
connections.
"""
def disassociate_connection_from_lag(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DisassociateConnectionFromLag",
method: :post,
input_shape: "DisassociateConnectionFromLagRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Returns a list of virtual private gateways owned by the AWS account.
You can create one or more AWS Direct Connect private virtual interfaces
linking to a virtual private gateway. A virtual private gateway can be
managed via Amazon Virtual Private Cloud (VPC) console or the [EC2
CreateVpnGateway](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnGateway.html)
action.
"""
def describe_virtual_gateways(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeVirtualGateways",
method: :post,
input_shape: "",
output_shape: "VirtualGateways",
endpoint: __spec__()
}
end
@doc """
Accept ownership of a public virtual interface created by another customer.
After the virtual interface owner calls this function, the specified
virtual interface will be created and made available for handling traffic.
"""
def confirm_public_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "ConfirmPublicVirtualInterface",
method: :post,
input_shape: "ConfirmPublicVirtualInterfaceRequest",
output_shape: "ConfirmPublicVirtualInterfaceResponse",
endpoint: __spec__()
}
end
@doc """
Deletes the specified interconnect.
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def delete_interconnect(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DeleteInterconnect",
method: :post,
input_shape: "DeleteInterconnectRequest",
output_shape: "DeleteInterconnectResponse",
endpoint: __spec__()
}
end
@doc """
Displays all connections in this region.
If a connection ID is provided, the call returns only that particular
connection.
"""
def describe_connections(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeConnections",
method: :post,
input_shape: "DescribeConnectionsRequest",
output_shape: "Connections",
endpoint: __spec__()
}
end
@doc """
Returns a list of interconnects owned by the AWS account.
If an interconnect ID is provided, it will only return this particular
interconnect.
"""
def describe_interconnects(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeInterconnects",
method: :post,
input_shape: "DescribeInterconnectsRequest",
output_shape: "Interconnects",
endpoint: __spec__()
}
end
@doc """
Deletes the connection.
Deleting a connection only stops the AWS Direct Connect port hour and data
transfer charges. You need to cancel separately with the providers any
services or charges for cross-connects or network circuits that connect you
to the AWS Direct Connect location.
"""
def delete_connection(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DeleteConnection",
method: :post,
input_shape: "DeleteConnectionRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Accept ownership of a private virtual interface created by another
customer.
After the virtual interface owner calls this function, the virtual
interface will be created and attached to the given virtual private
gateway, and will be available for handling traffic.
"""
def confirm_private_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "ConfirmPrivateVirtualInterface",
method: :post,
input_shape: "ConfirmPrivateVirtualInterfaceRequest",
output_shape: "ConfirmPrivateVirtualInterfaceResponse",
endpoint: __spec__()
}
end
@doc """
Updates the attributes of a link aggregation group (LAG).
You can update the following attributes:
<ul> <li> The name of the LAG.
</li> <li> The value for the minimum number of connections that must be
operational for the LAG itself to be operational.
</li> </ul> When you create a LAG, the default value for the minimum number
of operational connections is zero (0). If you update this value, and the
number of operational connections falls below the specified value, the LAG
will automatically go down to avoid overutilization of the remaining
connections. Adjusting this value should be done with care as it could
force the LAG down if the value is set higher than the current number of
operational connections.
"""
def update_lag(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "UpdateLag",
method: :post,
input_shape: "UpdateLagRequest",
output_shape: "Lag",
endpoint: __spec__()
}
end
@doc """
Provisions a public virtual interface to be owned by a different customer.
The owner of a connection calls this function to provision a public virtual
interface which will be owned by another AWS customer.
Virtual interfaces created using this function must be confirmed by the
virtual interface owner by calling ConfirmPublicVirtualInterface. Until
this step has been completed, the virtual interface will be in 'Confirming'
state, and will not be available for handling traffic.
When creating an IPv6 public virtual interface (addressFamily is 'ipv6'),
the customer and amazon address fields should be left blank to use
auto-assigned IPv6 space. Custom IPv6 Addresses are currently not
supported.
"""
def allocate_public_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AllocatePublicVirtualInterface",
method: :post,
input_shape: "AllocatePublicVirtualInterfaceRequest",
output_shape: "VirtualInterface",
endpoint: __spec__()
}
end
@doc """
Describes the tags associated with the specified Direct Connect resources.
"""
def describe_tags(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeTags",
method: :post,
input_shape: "DescribeTagsRequest",
output_shape: "DescribeTagsResponse",
endpoint: __spec__()
}
end
@doc """
Creates a hosted connection on an interconnect or a link aggregation group
(LAG).
Allocates a VLAN number and a specified amount of bandwidth for use by a
hosted connection on the given interconnect or LAG.
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def allocate_hosted_connection(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AllocateHostedConnection",
method: :post,
input_shape: "AllocateHostedConnectionRequest",
output_shape: "Connection",
endpoint: __spec__()
}
end
@doc """
Creates a new interconnect between a AWS Direct Connect partner's network
and a specific AWS Direct Connect location.
An interconnect is a connection which is capable of hosting other
connections. The AWS Direct Connect partner can use an interconnect to
provide sub-1Gbps AWS Direct Connect service to tier 2 customers who do not
have their own connections. Like a standard connection, an interconnect
links the AWS Direct Connect partner's network to an AWS Direct Connect
location over a standard 1 Gbps or 10 Gbps Ethernet fiber-optic cable. One
end is connected to the partner's router, the other to an AWS Direct
Connect router.
You can automatically add the new interconnect to a link aggregation group
(LAG) by specifying a LAG ID in the request. This ensures that the new
interconnect is allocated on the same AWS Direct Connect endpoint that
hosts the specified LAG. If there are no available ports on the endpoint,
the request fails and no interconnect will be created.
For each end customer, the AWS Direct Connect partner provisions a
connection on their interconnect by calling
AllocateConnectionOnInterconnect. The end customer can then connect to AWS
resources by creating a virtual interface on their connection, using the
VLAN assigned to them by the AWS Direct Connect partner.
<note> This is intended for use by AWS Direct Connect partners only.
</note>
"""
def create_interconnect(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "CreateInterconnect",
method: :post,
input_shape: "CreateInterconnectRequest",
output_shape: "Interconnect",
endpoint: __spec__()
}
end
@doc """
Provisions a private virtual interface to be owned by another AWS customer.
Virtual interfaces created using this action must be confirmed by the
virtual interface owner by using the `ConfirmPrivateVirtualInterface`
action. Until then, the virtual interface will be in 'Confirming' state,
and will not be available for handling traffic.
"""
def allocate_private_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "AllocatePrivateVirtualInterface",
method: :post,
input_shape: "AllocatePrivateVirtualInterfaceRequest",
output_shape: "VirtualInterface",
endpoint: __spec__()
}
end
@doc """
Confirm the creation of a hosted connection on an interconnect.
Upon creation, the hosted connection is initially in the 'Ordering' state,
and will remain in this state until the owner calls ConfirmConnection to
confirm creation of the hosted connection.
"""
def confirm_connection(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "ConfirmConnection",
method: :post,
input_shape: "ConfirmConnectionRequest",
output_shape: "ConfirmConnectionResponse",
endpoint: __spec__()
}
end
@doc """
Deprecated in favor of `DescribeLoa`.
Returns the LOA-CFA for a Connection.
The Letter of Authorization - Connecting Facility Assignment (LOA-CFA) is a
document that your APN partner or service provider uses when establishing
your cross connect to AWS at the colocation facility. For more information,
see [Requesting Cross Connects at AWS Direct Connect
Locations](http://docs.aws.amazon.com/directconnect/latest/UserGuide/Colocation.html)
in the AWS Direct Connect user guide.
"""
def describe_connection_loa(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeConnectionLoa",
method: :post,
input_shape: "DescribeConnectionLoaRequest",
output_shape: "DescribeConnectionLoaResponse",
endpoint: __spec__()
}
end
@doc """
Displays all virtual interfaces for an AWS account. Virtual interfaces
deleted fewer than 15 minutes before you make the request are also
returned. If you specify a connection ID, only the virtual interfaces
associated with the connection are returned. If you specify a virtual
interface ID, then only a single virtual interface is returned.
A virtual interface (VLAN) transmits the traffic between the AWS Direct
Connect location and the customer.
"""
def describe_virtual_interfaces(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "DescribeVirtualInterfaces",
method: :post,
input_shape: "DescribeVirtualInterfacesRequest",
output_shape: "VirtualInterfaces",
endpoint: __spec__()
}
end
@doc """
Creates a new private virtual interface. A virtual interface is the VLAN
that transports AWS Direct Connect traffic. A private virtual interface
supports sending traffic to a single virtual private cloud (VPC).
"""
def create_private_virtual_interface(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "CreatePrivateVirtualInterface",
method: :post,
input_shape: "CreatePrivateVirtualInterfaceRequest",
output_shape: "VirtualInterface",
endpoint: __spec__()
}
end
@doc """
Creates a new BGP peer on a specified virtual interface. The BGP peer
cannot be in the same address family (IPv4/IPv6) of an existing BGP peer on
the virtual interface.
You must create a BGP peer for the corresponding address family in order to
access AWS resources that also use that address family.
When creating a IPv6 BGP peer, the Amazon address and customer address
fields must be left blank. IPv6 addresses are automatically assigned from
Amazon's pool of IPv6 addresses; you cannot specify custom IPv6 addresses.
For a public virtual interface, the Autonomous System Number (ASN) must be
private or already whitelisted for the virtual interface.
"""
def create_b_g_p_peer(input \\ %{}, options \\ []) do
%Baiji.Operation{
path: "/",
input: input,
options: options,
action: "CreateBGPPeer",
method: :post,
input_shape: "CreateBGPPeerRequest",
output_shape: "CreateBGPPeerResponse",
endpoint: __spec__()
}
end
@doc """
Outputs values common to all actions
"""
def __spec__ do
%Baiji.Endpoint{
service: "directconnect",
target_prefix: "OvertureService",
endpoint_prefix: "directconnect",
type: :json,
version: "2012-10-25",
shapes: __shapes__()
}
end
@doc """
Returns a map containing the input/output shapes for this endpoint
"""
def __shapes__ do
%{"ConfirmPublicVirtualInterfaceRequest" => %{"members" => %{"virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "required" => ["virtualInterfaceId"], "type" => "structure"}, "InterconnectList" => %{"member" => %{"shape" => "Interconnect"}, "type" => "list"}, "NewPublicVirtualInterface" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "customerAddress" => %{"shape" => "CustomerAddress"}, "routeFilterPrefixes" => %{"shape" => "RouteFilterPrefixList"}, "virtualInterfaceName" => %{"shape" => "VirtualInterfaceName"}, "vlan" => %{"shape" => "VLAN"}}, "required" => ["virtualInterfaceName", "vlan", "asn"], "type" => "structure"}, "DeleteLagRequest" => %{"members" => %{"lagId" => %{"shape" => "LagId"}}, "required" => ["lagId"], "type" => "structure"}, "ResourceTagList" => %{"member" => %{"shape" => "ResourceTag"}, "type" => "list"}, "TagKeyList" => %{"member" => %{"shape" => "TagKey"}, "type" => "list"}, "VirtualGatewayState" => %{"type" => "string"}, "CreatePrivateVirtualInterfaceRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "newPrivateVirtualInterface" => %{"shape" => "NewPrivateVirtualInterface"}}, "required" => ["connectionId", "newPrivateVirtualInterface"], "type" => "structure"}, "AwsDevice" => %{"type" => "string"}, "LagName" => %{"type" => "string"}, "DescribeHostedConnectionsRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}}, "required" => ["connectionId"], "type" => "structure"}, "AssociateHostedConnectionRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "parentConnectionId" => %{"shape" => "ConnectionId"}}, "required" => ["connectionId", "parentConnectionId"], "type" => "structure"}, "RouterConfig" => %{"type" => "string"}, "ErrorMessage" => %{"type" => "string"}, "LagState" => %{"enum" => ["requested", "pending", "available", "down", "deleting", "deleted"], "type" => "string"}, "DeleteVirtualInterfaceResponse" => %{"members" => %{"virtualInterfaceState" => %{"shape" => "VirtualInterfaceState"}}, "type" => "structure"}, "Interconnect" => %{"members" => %{"awsDevice" => %{"shape" => "AwsDevice"}, "bandwidth" => %{"shape" => "Bandwidth"}, "interconnectId" => %{"shape" => "InterconnectId"}, "interconnectName" => %{"shape" => "InterconnectName"}, "interconnectState" => %{"shape" => "InterconnectState"}, "lagId" => %{"shape" => "LagId"}, "loaIssueTime" => %{"shape" => "LoaIssueTime"}, "location" => %{"shape" => "LocationCode"}, "region" => %{"shape" => "Region"}}, "type" => "structure"}, "Count" => %{"type" => "integer"}, "ConnectionState" => %{"enum" => ["ordering", "requested", "pending", "available", "down", "deleting", "deleted", "rejected"], "type" => "string"}, "NewBGPPeer" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "customerAddress" => %{"shape" => "CustomerAddress"}}, "type" => "structure"}, "DescribeInterconnectLoaRequest" => %{"members" => %{"interconnectId" => %{"shape" => "InterconnectId"}, "loaContentType" => %{"shape" => "LoaContentType"}, "providerName" => %{"shape" => "ProviderName"}}, "required" => ["interconnectId"], "type" => "structure"}, "CIDR" => %{"type" => "string"}, "ConnectionId" => %{"type" => "string"}, "BGPPeerList" => %{"member" => %{"shape" => "BGPPeer"}, "type" => "list"}, "BGPAuthKey" => %{"type" => "string"}, "DescribeInterconnectLoaResponse" => %{"members" => %{"loa" => %{"shape" => "Loa"}}, "type" => "structure"}, "ConfirmPublicVirtualInterfaceResponse" => %{"members" => %{"virtualInterfaceState" => %{"shape" => "VirtualInterfaceState"}}, "type" => "structure"}, "UpdateLagRequest" => %{"members" => %{"lagId" => %{"shape" => "LagId"}, "lagName" => %{"shape" => "LagName"}, "minimumLinks" => %{"shape" => "Count"}}, "required" => ["lagId"], "type" => "structure"}, "LoaContentType" => %{"enum" => ["application/pdf"], "type" => "string"}, "LoaContent" => %{"type" => "blob"}, "ConfirmPrivateVirtualInterfaceResponse" => %{"members" => %{"virtualInterfaceState" => %{"shape" => "VirtualInterfaceState"}}, "type" => "structure"}, "DeleteBGPPeerResponse" => %{"members" => %{"virtualInterface" => %{"shape" => "VirtualInterface"}}, "type" => "structure"}, "AssociateVirtualInterfaceRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "required" => ["virtualInterfaceId", "connectionId"], "type" => "structure"}, "LocationCode" => %{"type" => "string"}, "DescribeInterconnectsRequest" => %{"members" => %{"interconnectId" => %{"shape" => "InterconnectId"}}, "type" => "structure"}, "DeleteBGPPeerRequest" => %{"members" => %{"asn" => %{"shape" => "ASN"}, "customerAddress" => %{"shape" => "CustomerAddress"}, "virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "type" => "structure"}, "ConnectionName" => %{"type" => "string"}, "Region" => %{"type" => "string"}, "DuplicateTagKeysException" => %{"exception" => true, "members" => %{}, "type" => "structure"}, "DirectConnectServerException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "ErrorMessage"}}, "type" => "structure"}, "CreateBGPPeerRequest" => %{"members" => %{"newBGPPeer" => %{"shape" => "NewBGPPeer"}, "virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "type" => "structure"}, "ConfirmPrivateVirtualInterfaceRequest" => %{"members" => %{"virtualGatewayId" => %{"shape" => "VirtualGatewayId"}, "virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "required" => ["virtualInterfaceId", "virtualGatewayId"], "type" => "structure"}, "BGPStatus" => %{"enum" => ["up", "down"], "type" => "string"}, "LocationList" => %{"member" => %{"shape" => "Location"}, "type" => "list"}, "CreateLagRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "connectionsBandwidth" => %{"shape" => "Bandwidth"}, "lagName" => %{"shape" => "LagName"}, "location" => %{"shape" => "LocationCode"}, "numberOfConnections" => %{"shape" => "Count"}}, "required" => ["numberOfConnections", "location", "connectionsBandwidth", "lagName"], "type" => "structure"}, "NewPublicVirtualInterfaceAllocation" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "customerAddress" => %{"shape" => "CustomerAddress"}, "routeFilterPrefixes" => %{"shape" => "RouteFilterPrefixList"}, "virtualInterfaceName" => %{"shape" => "VirtualInterfaceName"}, "vlan" => %{"shape" => "VLAN"}}, "required" => ["virtualInterfaceName", "vlan", "asn"], "type" => "structure"}, "DeleteInterconnectResponse" => %{"members" => %{"interconnectState" => %{"shape" => "InterconnectState"}}, "type" => "structure"}, "ResourceTag" => %{"members" => %{"resourceArn" => %{"shape" => "ResourceArn"}, "tags" => %{"shape" => "TagList"}}, "type" => "structure"}, "VLAN" => %{"type" => "integer"}, "Lags" => %{"members" => %{"lags" => %{"shape" => "LagList"}}, "type" => "structure"}, "VirtualInterfaces" => %{"members" => %{"virtualInterfaces" => %{"shape" => "VirtualInterfaceList"}}, "type" => "structure"}, "UntagResourceRequest" => %{"members" => %{"resourceArn" => %{"shape" => "ResourceArn"}, "tagKeys" => %{"shape" => "TagKeyList"}}, "required" => ["resourceArn", "tagKeys"], "type" => "structure"}, "ResourceArnList" => %{"member" => %{"shape" => "ResourceArn"}, "type" => "list"}, "VirtualInterfaceType" => %{"type" => "string"}, "Tag" => %{"members" => %{"key" => %{"shape" => "TagKey"}, "value" => %{"shape" => "TagValue"}}, "required" => ["key"], "type" => "structure"}, "Lag" => %{"members" => %{"allowsHostedConnections" => %{"shape" => "BooleanFlag"}, "awsDevice" => %{"shape" => "AwsDevice"}, "connections" => %{"shape" => "ConnectionList"}, "connectionsBandwidth" => %{"shape" => "Bandwidth"}, "lagId" => %{"shape" => "LagId"}, "lagName" => %{"shape" => "LagName"}, "lagState" => %{"shape" => "LagState"}, "location" => %{"shape" => "LocationCode"}, "minimumLinks" => %{"shape" => "Count"}, "numberOfConnections" => %{"shape" => "Count"}, "ownerAccount" => %{"shape" => "OwnerAccount"}, "region" => %{"shape" => "Region"}}, "type" => "structure"}, "InterconnectName" => %{"type" => "string"}, "OwnerAccount" => %{"type" => "string"}, "InterconnectState" => %{"enum" => ["requested", "pending", "available", "down", "deleting", "deleted"], "type" => "string"}, "RouteFilterPrefix" => %{"members" => %{"cidr" => %{"shape" => "CIDR"}}, "type" => "structure"}, "ConfirmConnectionRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}}, "required" => ["connectionId"], "type" => "structure"}, "TagList" => %{"member" => %{"shape" => "Tag"}, "min" => 1, "type" => "list"}, "TagValue" => %{"max" => 256, "min" => 0, "pattern" => "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$", "type" => "string"}, "AddressFamily" => %{"enum" => ["ipv4", "ipv6"], "type" => "string"}, "NewPrivateVirtualInterface" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "customerAddress" => %{"shape" => "CustomerAddress"}, "virtualGatewayId" => %{"shape" => "VirtualGatewayId"}, "virtualInterfaceName" => %{"shape" => "VirtualInterfaceName"}, "vlan" => %{"shape" => "VLAN"}}, "required" => ["virtualInterfaceName", "vlan", "asn", "virtualGatewayId"], "type" => "structure"}, "VirtualInterfaceId" => %{"type" => "string"}, "AllocatePrivateVirtualInterfaceRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "newPrivateVirtualInterfaceAllocation" => %{"shape" => "NewPrivateVirtualInterfaceAllocation"}, "ownerAccount" => %{"shape" => "OwnerAccount"}}, "required" => ["connectionId", "ownerAccount", "newPrivateVirtualInterfaceAllocation"], "type" => "structure"}, "DescribeConnectionLoaResponse" => %{"members" => %{"loa" => %{"shape" => "Loa"}}, "type" => "structure"}, "VirtualGatewayId" => %{"type" => "string"}, "BGPPeer" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "bgpPeerState" => %{"shape" => "BGPPeerState"}, "bgpStatus" => %{"shape" => "BGPStatus"}, "customerAddress" => %{"shape" => "CustomerAddress"}}, "type" => "structure"}, "DescribeTagsRequest" => %{"members" => %{"resourceArns" => %{"shape" => "ResourceArnList"}}, "required" => ["resourceArns"], "type" => "structure"}, "AllocateHostedConnectionRequest" => %{"members" => %{"bandwidth" => %{"shape" => "Bandwidth"}, "connectionId" => %{"shape" => "ConnectionId"}, "connectionName" => %{"shape" => "ConnectionName"}, "ownerAccount" => %{"shape" => "OwnerAccount"}, "vlan" => %{"shape" => "VLAN"}}, "required" => ["connectionId", "ownerAccount", "bandwidth", "connectionName", "vlan"], "type" => "structure"}, "InterconnectId" => %{"type" => "string"}, "UntagResourceResponse" => %{"members" => %{}, "type" => "structure"}, "DescribeTagsResponse" => %{"members" => %{"resourceTags" => %{"shape" => "ResourceTagList"}}, "type" => "structure"}, "Location" => %{"members" => %{"locationCode" => %{"shape" => "LocationCode"}, "locationName" => %{"shape" => "LocationName"}}, "type" => "structure"}, "LoaIssueTime" => %{"type" => "timestamp"}, "DescribeLoaRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "loaContentType" => %{"shape" => "LoaContentType"}, "providerName" => %{"shape" => "ProviderName"}}, "required" => ["connectionId"], "type" => "structure"}, "BGPPeerState" => %{"enum" => ["verifying", "pending", "available", "deleting", "deleted"], "type" => "string"}, "ResourceArn" => %{"type" => "string"}, "PartnerName" => %{"type" => "string"}, "NewPrivateVirtualInterfaceAllocation" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "customerAddress" => %{"shape" => "CustomerAddress"}, "virtualInterfaceName" => %{"shape" => "VirtualInterfaceName"}, "vlan" => %{"shape" => "VLAN"}}, "required" => ["virtualInterfaceName", "vlan", "asn"], "type" => "structure"}, "TagResourceRequest" => %{"members" => %{"resourceArn" => %{"shape" => "ResourceArn"}, "tags" => %{"shape" => "TagList"}}, "required" => ["resourceArn", "tags"], "type" => "structure"}, "AllocatePublicVirtualInterfaceRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "newPublicVirtualInterfaceAllocation" => %{"shape" => "NewPublicVirtualInterfaceAllocation"}, "ownerAccount" => %{"shape" => "OwnerAccount"}}, "required" => ["connectionId", "ownerAccount", "newPublicVirtualInterfaceAllocation"], "type" => "structure"}, "LagId" => %{"type" => "string"}, "AmazonAddress" => %{"type" => "string"}, "Loa" => %{"members" => %{"loaContent" => %{"shape" => "LoaContent"}, "loaContentType" => %{"shape" => "LoaContentType"}}, "type" => "structure"}, "DescribeLagsRequest" => %{"members" => %{"lagId" => %{"shape" => "LagId"}}, "type" => "structure"}, "VirtualInterfaceList" => %{"member" => %{"shape" => "VirtualInterface"}, "type" => "list"}, "AssociateConnectionWithLagRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "lagId" => %{"shape" => "LagId"}}, "required" => ["connectionId", "lagId"], "type" => "structure"}, "DirectConnectClientException" => %{"exception" => true, "members" => %{"message" => %{"shape" => "ErrorMessage"}}, "type" => "structure"}, "ConnectionList" => %{"member" => %{"shape" => "Connection"}, "type" => "list"}, "Locations" => %{"members" => %{"locations" => %{"shape" => "LocationList"}}, "type" => "structure"}, "VirtualGateway" => %{"members" => %{"virtualGatewayId" => %{"shape" => "VirtualGatewayId"}, "virtualGatewayState" => %{"shape" => "VirtualGatewayState"}}, "type" => "structure"}, "VirtualGateways" => %{"members" => %{"virtualGateways" => %{"shape" => "VirtualGatewayList"}}, "type" => "structure"}, "DeleteInterconnectRequest" => %{"members" => %{"interconnectId" => %{"shape" => "InterconnectId"}}, "required" => ["interconnectId"], "type" => "structure"}, "RouteFilterPrefixList" => %{"member" => %{"shape" => "RouteFilterPrefix"}, "type" => "list"}, "ASN" => %{"type" => "integer"}, "CreateInterconnectRequest" => %{"members" => %{"bandwidth" => %{"shape" => "Bandwidth"}, "interconnectName" => %{"shape" => "InterconnectName"}, "lagId" => %{"shape" => "LagId"}, "location" => %{"shape" => "LocationCode"}}, "required" => ["interconnectName", "bandwidth", "location"], "type" => "structure"}, "CreateConnectionRequest" => %{"members" => %{"bandwidth" => %{"shape" => "Bandwidth"}, "connectionName" => %{"shape" => "ConnectionName"}, "lagId" => %{"shape" => "LagId"}, "location" => %{"shape" => "LocationCode"}}, "required" => ["location", "bandwidth", "connectionName"], "type" => "structure"}, "DeleteConnectionRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}}, "required" => ["connectionId"], "type" => "structure"}, "LocationName" => %{"type" => "string"}, "ProviderName" => %{"type" => "string"}, "TooManyTagsException" => %{"exception" => true, "members" => %{}, "type" => "structure"}, "CustomerAddress" => %{"type" => "string"}, "TagResourceResponse" => %{"members" => %{}, "type" => "structure"}, "TagKey" => %{"max" => 128, "min" => 1, "pattern" => "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$", "type" => "string"}, "VirtualInterface" => %{"members" => %{"addressFamily" => %{"shape" => "AddressFamily"}, "amazonAddress" => %{"shape" => "AmazonAddress"}, "asn" => %{"shape" => "ASN"}, "authKey" => %{"shape" => "BGPAuthKey"}, "bgpPeers" => %{"shape" => "BGPPeerList"}, "connectionId" => %{"shape" => "ConnectionId"}, "customerAddress" => %{"shape" => "CustomerAddress"}, "customerRouterConfig" => %{"shape" => "RouterConfig"}, "location" => %{"shape" => "LocationCode"}, "ownerAccount" => %{"shape" => "OwnerAccount"}, "routeFilterPrefixes" => %{"shape" => "RouteFilterPrefixList"}, "virtualGatewayId" => %{"shape" => "VirtualGatewayId"}, "virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}, "virtualInterfaceName" => %{"shape" => "VirtualInterfaceName"}, "virtualInterfaceState" => %{"shape" => "VirtualInterfaceState"}, "virtualInterfaceType" => %{"shape" => "VirtualInterfaceType"}, "vlan" => %{"shape" => "VLAN"}}, "type" => "structure"}, "VirtualGatewayList" => %{"member" => %{"shape" => "VirtualGateway"}, "type" => "list"}, "DescribeConnectionsOnInterconnectRequest" => %{"members" => %{"interconnectId" => %{"shape" => "InterconnectId"}}, "required" => ["interconnectId"], "type" => "structure"}, "Bandwidth" => %{"type" => "string"}, "CreateBGPPeerResponse" => %{"members" => %{"virtualInterface" => %{"shape" => "VirtualInterface"}}, "type" => "structure"}, "ConfirmConnectionResponse" => %{"members" => %{"connectionState" => %{"shape" => "ConnectionState"}}, "type" => "structure"}, "Interconnects" => %{"members" => %{"interconnects" => %{"shape" => "InterconnectList"}}, "type" => "structure"}, "VirtualInterfaceState" => %{"enum" => ["confirming", "verifying", "pending", "available", "down", "deleting", "deleted", "rejected"], "type" => "string"}, "Connection" => %{"members" => %{"awsDevice" => %{"shape" => "AwsDevice"}, "bandwidth" => %{"shape" => "Bandwidth"}, "connectionId" => %{"shape" => "ConnectionId"}, "connectionName" => %{"shape" => "ConnectionName"}, "connectionState" => %{"shape" => "ConnectionState"}, "lagId" => %{"shape" => "LagId"}, "loaIssueTime" => %{"shape" => "LoaIssueTime"}, "location" => %{"shape" => "LocationCode"}, "ownerAccount" => %{"shape" => "OwnerAccount"}, "partnerName" => %{"shape" => "PartnerName"}, "region" => %{"shape" => "Region"}, "vlan" => %{"shape" => "VLAN"}}, "type" => "structure"}, "LagList" => %{"member" => %{"shape" => "Lag"}, "type" => "list"}, "DeleteVirtualInterfaceRequest" => %{"members" => %{"virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "required" => ["virtualInterfaceId"], "type" => "structure"}, "DescribeVirtualInterfacesRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "virtualInterfaceId" => %{"shape" => "VirtualInterfaceId"}}, "type" => "structure"}, "Connections" => %{"members" => %{"connections" => %{"shape" => "ConnectionList"}}, "type" => "structure"}, "AllocateConnectionOnInterconnectRequest" => %{"members" => %{"bandwidth" => %{"shape" => "Bandwidth"}, "connectionName" => %{"shape" => "ConnectionName"}, "interconnectId" => %{"shape" => "InterconnectId"}, "ownerAccount" => %{"shape" => "OwnerAccount"}, "vlan" => %{"shape" => "VLAN"}}, "required" => ["bandwidth", "connectionName", "ownerAccount", "interconnectId", "vlan"], "type" => "structure"}, "VirtualInterfaceName" => %{"type" => "string"}, "DescribeConnectionLoaRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "loaContentType" => %{"shape" => "LoaContentType"}, "providerName" => %{"shape" => "ProviderName"}}, "required" => ["connectionId"], "type" => "structure"}, "BooleanFlag" => %{"type" => "boolean"}, "DescribeConnectionsRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}}, "type" => "structure"}, "DisassociateConnectionFromLagRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "lagId" => %{"shape" => "LagId"}}, "required" => ["connectionId", "lagId"], "type" => "structure"}, "CreatePublicVirtualInterfaceRequest" => %{"members" => %{"connectionId" => %{"shape" => "ConnectionId"}, "newPublicVirtualInterface" => %{"shape" => "NewPublicVirtualInterface"}}, "required" => ["connectionId", "newPublicVirtualInterface"], "type" => "structure"}}
end
end | 58.910793 | 19,936 | 0.619543 |
08c8b8d711b4b8fa9104090a5ab87ac81b31f3e1 | 135 | exs | Elixir | test/elixir_test.exs | LucasVinicius314/elixir | b9262c635233a563cffddfb32c9de90ec96be372 | [
"MIT"
] | 29 | 2019-11-13T06:57:13.000Z | 2021-01-31T19:42:51.000Z | test/elixir_test.exs | LucasVinicius314/elixir | b9262c635233a563cffddfb32c9de90ec96be372 | [
"MIT"
] | 1 | 2021-11-21T04:04:00.000Z | 2022-02-09T15:33:48.000Z | test/elixir_test.exs | LucasVinicius314/elixir | b9262c635233a563cffddfb32c9de90ec96be372 | [
"MIT"
] | 3 | 2021-06-17T15:30:21.000Z | 2022-03-17T22:27:18.000Z | defmodule ElixirTest do
use ExUnit.Case
doctest Elixir
test "greets the world" do
assert Elixir.hello() == :world
end
end
| 15 | 35 | 0.703704 |
08c8d43f3f3d8fd3a1f97ec2371266d5842795f8 | 1,044 | ex | Elixir | lib/volunteerbase/endpoint.ex | nihonjinrxs/VolunteerBase | e555ec9ae1d0b4401ae33c0a9fdc411b855f04a4 | [
"MIT"
] | null | null | null | lib/volunteerbase/endpoint.ex | nihonjinrxs/VolunteerBase | e555ec9ae1d0b4401ae33c0a9fdc411b855f04a4 | [
"MIT"
] | 1 | 2016-06-24T03:43:06.000Z | 2016-06-24T03:43:06.000Z | lib/volunteerbase/endpoint.ex | nihonjinrxs/VolunteerBase | e555ec9ae1d0b4401ae33c0a9fdc411b855f04a4 | [
"MIT"
] | null | null | null | defmodule Volunteerbase.Endpoint do
use Phoenix.Endpoint, otp_app: :volunteerbase
socket "/socket", Volunteerbase.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :volunteerbase, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session,
store: :cookie,
key: "_volunteerbase_key",
signing_salt: "t+8WiOGX"
plug Volunteerbase.Router
end
| 26.1 | 69 | 0.718391 |
08c8df2e3c28eb9a0e82a6a680cb2eda96700d6b | 64 | ex | Elixir | lib/glimesh_web/views/article_view.ex | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 328 | 2020-07-23T22:13:49.000Z | 2022-03-31T21:22:28.000Z | lib/glimesh_web/views/article_view.ex | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 362 | 2020-07-23T22:38:38.000Z | 2022-03-24T02:11:16.000Z | lib/glimesh_web/views/article_view.ex | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 72 | 2020-07-23T22:50:46.000Z | 2022-02-02T11:59:32.000Z | defmodule GlimeshWeb.ArticleView do
use GlimeshWeb, :view
end
| 16 | 35 | 0.8125 |
08c9071fc49e4374e4a65e1529aa7b68d3fc6039 | 2,425 | exs | Elixir | test/k8s/discovery/resource_finder_test.exs | thephw/k8s | a4d157ad0191ac49b27ec9197f342d8d4d33e52a | [
"MIT"
] | 226 | 2019-02-03T00:49:32.000Z | 2022-03-30T15:02:22.000Z | test/k8s/discovery/resource_finder_test.exs | thephw/k8s | a4d157ad0191ac49b27ec9197f342d8d4d33e52a | [
"MIT"
] | 109 | 2019-01-20T20:39:33.000Z | 2022-03-31T20:21:34.000Z | test/k8s/discovery/resource_finder_test.exs | FreedomBen/k8s | 9cfd7bec869cd1f2d8a6c543923f3849710941a5 | [
"MIT"
] | 43 | 2019-02-07T01:18:31.000Z | 2022-03-08T04:15:33.000Z | defmodule K8s.Discovery.ResourceFinderTest do
use ExUnit.Case, async: true
doctest K8s.Discovery.ResourceFinder
alias K8s.Discovery.ResourceFinder
@spec daemonset :: map
defp daemonset do
%{
"kind" => "DaemonSet",
"name" => "daemonsets",
"namespaced" => true
}
end
@spec deployment :: map
defp deployment do
%{
"kind" => "Deployment",
"name" => "deployments",
"namespaced" => true
}
end
@spec deployment_status :: map
defp deployment_status do
%{
"kind" => "Deployment",
"name" => "deployments/status",
"namespaced" => true
}
end
@spec resources :: list(map)
defp resources do
[daemonset(), deployment(), deployment_status()]
end
describe "resource_name_for_kind/3" do
test "returns the REST resource name given a kubernetes kind" do
{:ok, conn} = K8s.Conn.from_file("test/support/kube-config.yaml")
{:ok, name} = ResourceFinder.resource_name_for_kind(conn, "v1", "Pod")
assert name == "pods"
end
test "returns the REST resoruce name given a subresource name" do
{:ok, conn} = K8s.Conn.from_file("test/support/kube-config.yaml")
{:ok, name} = ResourceFinder.resource_name_for_kind(conn, "v1", "pods/eviction")
assert name == "pods/eviction"
end
end
describe "find_resource_by_name/2" do
test "finds a resource by name" do
{:ok, deployment_status} =
ResourceFinder.find_resource_by_name(resources(), "deployments/status")
assert deployment_status == deployment_status()
end
test "finds a resource by atom kind" do
{:ok, deployment} = ResourceFinder.find_resource_by_name(resources(), :deployment)
assert %{"kind" => "Deployment"} = deployment
end
test "finds a resource by plural atom kind" do
{:ok, deployment} = ResourceFinder.find_resource_by_name(resources(), :deployments)
assert %{"kind" => "Deployment"} = deployment
end
test "finds a resource by string kind" do
{:ok, deployment} = ResourceFinder.find_resource_by_name(resources(), "Deployment")
assert %{"kind" => "Deployment"} = deployment
end
test "returns an error when the resource is not supported" do
{:error, %K8s.Discovery.Error{message: message}} =
ResourceFinder.find_resource_by_name(resources(), "Foo")
assert message =~ ~r/Unsupported.*Foo/
end
end
end
| 29.216867 | 89 | 0.654845 |
08c947be5267b279b8d573ee106ab5491f6b0179 | 1,241 | exs | Elixir | test/support/conn_case.exs | lumenlunae/sentinel | 189d9b02aeeea942a41963b42ef8523ef192fd03 | [
"MIT"
] | null | null | null | test/support/conn_case.exs | lumenlunae/sentinel | 189d9b02aeeea942a41963b42ef8523ef192fd03 | [
"MIT"
] | null | null | null | test/support/conn_case.exs | lumenlunae/sentinel | 189d9b02aeeea942a41963b42ef8523ef192fd03 | [
"MIT"
] | null | null | null | defmodule Sentinel.ConnCase do
alias Sentinel.TestRepo
use ExUnit.CaseTemplate
@default_opts [
store: :cookie,
key: "default",
encryption_salt: "encrypted cookie salt",
signing_salt: "signing salt"
]
@secret String.duplicate("abcdef0123456789", 8)
@signing_opts Plug.Session.init(Keyword.put(@default_opts, :encrypt, false))
using do
quote do
alias Plug.Conn
alias Sentinel.Config
alias Sentinel.Factory
alias Sentinel.Mailer
alias Sentinel.TestRepo
alias Sentinel.TestRouter
alias Sentinel.User
import Mock
import Sentinel.TestRouter.Helpers
use Plug.Test
import Plug.Conn
import Phoenix.ConnTest
use Bamboo.Test, shared: true
@endpoint Sentinel.Endpoint
end
end
def conn_with_fetched_session(the_conn) do
the_conn.secret_key_base
|> put_in(@secret)
|> Plug.Session.call(@signing_opts)
|> Plug.Conn.fetch_session()
end
def run_plug(conn, plug_module) do
opts = apply(plug_module, :init, [])
apply(plug_module, :call, [conn, opts])
end
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(TestRepo)
Ecto.Adapters.SQL.Sandbox.mode(TestRepo, {:shared, self()})
end
end
| 22.981481 | 78 | 0.68332 |
08c955e36b45c996b035a9182bd2c11a5af49556 | 1,074 | ex | Elixir | lib/githubist/application.ex | alpcanaydin/githubist-api | 6481f8177c5b8573da2d5df52ffaff41340b25d0 | [
"MIT"
] | 33 | 2018-10-13T16:40:36.000Z | 2021-05-23T14:13:34.000Z | lib/githubist/application.ex | 5l1v3r1/githubist-api | 6481f8177c5b8573da2d5df52ffaff41340b25d0 | [
"MIT"
] | 1 | 2018-12-23T19:59:05.000Z | 2018-12-24T18:08:00.000Z | lib/githubist/application.ex | 5l1v3r1/githubist-api | 6481f8177c5b8573da2d5df52ffaff41340b25d0 | [
"MIT"
] | 3 | 2018-10-13T22:18:38.000Z | 2020-03-29T23:41:23.000Z | defmodule Githubist.Application do
@moduledoc false
use Application
alias GithubistWeb.Endpoint
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(Githubist.Repo, []),
# Start the endpoint when the application starts
supervisor(GithubistWeb.Endpoint, [])
# Start your own worker by calling: Githubist.Worker.start_link(arg1, arg2, arg3)
# worker(Githubist.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Githubist.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
Endpoint.config_change(changed, removed)
:ok
end
end
| 29.833333 | 87 | 0.717877 |
08c97b883dd3c0a4e46dda8dbc028953d416d926 | 307 | exs | Elixir | installer/mix.exs | manukall/phoenix | 5ce19ebb63b1b31e37da5fe6465edb6c4850772e | [
"MIT"
] | null | null | null | installer/mix.exs | manukall/phoenix | 5ce19ebb63b1b31e37da5fe6465edb6c4850772e | [
"MIT"
] | null | null | null | installer/mix.exs | manukall/phoenix | 5ce19ebb63b1b31e37da5fe6465edb6c4850772e | [
"MIT"
] | null | null | null | defmodule Phoenix.New.Mixfile do
use Mix.Project
def project do
[app: :phoenix_new,
version: "1.1.0-dev",
elixir: "~> 1.0-dev"]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: []]
end
end
| 18.058824 | 52 | 0.651466 |
08c98e27100eb9d789ac167cd512e679e6bc902d | 1,607 | ex | Elixir | clients/testing/lib/google_api/testing/v1/model/google_auto.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/testing/lib/google_api/testing/v1/model/google_auto.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/testing/lib/google_api/testing/v1/model/google_auto.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.Testing.V1.Model.GoogleAuto do
@moduledoc """
Enables automatic Google account login.
If set, the service automatically generates a Google test account and adds
it to the device, before executing the test. Note that test accounts might be
reused.
Many applications show their full set of functionalities when an account is
present on the device. Logging into the device with these generated accounts
allows testing more functionalities.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.Testing.V1.Model.GoogleAuto do
def decode(value, options) do
GoogleApi.Testing.V1.Model.GoogleAuto.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Testing.V1.Model.GoogleAuto do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.479167 | 79 | 0.766024 |
08c9b0cd752481af2cecacf0dd2c500f16e4e253 | 1,094 | ex | Elixir | lib/free_fall_web/channels/user_socket.ex | Goose-Vic/free_fall | 84d95e33cbd0d6e06dd9170576726929e97b25ac | [
"MIT"
] | 1 | 2021-11-17T21:16:30.000Z | 2021-11-17T21:16:30.000Z | lib/free_fall_web/channels/user_socket.ex | Goose-Vic/free_fall | 84d95e33cbd0d6e06dd9170576726929e97b25ac | [
"MIT"
] | null | null | null | lib/free_fall_web/channels/user_socket.ex | Goose-Vic/free_fall | 84d95e33cbd0d6e06dd9170576726929e97b25ac | [
"MIT"
] | 9 | 2021-07-29T23:36:54.000Z | 2021-09-30T22:47:39.000Z | defmodule FreeFallWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", FreeFallWeb.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
@impl true
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# FreeFallWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
@impl true
def id(_socket), do: nil
end
| 30.388889 | 83 | 0.695612 |
08c9bc74d94db3b470dcf17a55f81baa6d608cfa | 2,162 | ex | Elixir | lib/btrz_healthchecker.ex | Betterez/btrz-ex-health-checker | 040dd4f712268f0269cc8abef6f818b368591c5c | [
"MIT"
] | null | null | null | lib/btrz_healthchecker.ex | Betterez/btrz-ex-health-checker | 040dd4f712268f0269cc8abef6f818b368591c5c | [
"MIT"
] | null | null | null | lib/btrz_healthchecker.ex | Betterez/btrz-ex-health-checker | 040dd4f712268f0269cc8abef6f818b368591c5c | [
"MIT"
] | null | null | null | defmodule BtrzHealthchecker do
@moduledoc """
BtrzHealthchecker main module.
Used to get the information about the desired services passed as Checkers.
"""
alias BtrzHealthchecker.{Info, EnvironmentInfo}
@environment_info_api Application.get_env(:btrz_ex_health_checker, :environment_info_api) ||
EnvironmentInfo
@typedoc """
A checker that implements the Checker behaviour
"""
@type checker :: Map.t()
@doc """
Returns the Info struct with the status of the desired services.
## Examples
iex> my_connection_opts = [hostname: "localhost", username: "postgres", password: "mypass", database: "mydb"]
iex> BtrzHealthchecker.info([%{checker_module: BtrzHealthchecker.Checkers.Postgres, opts: my_connection_opts}])
%BtrzHealthchecker.Info{build: "d3b3f9133f68b8877347e06b3d7285dd1d5d3921", commit: "3d7285dd1d5d3921d3b3f9133f68b8877347e06b",
instanceId: "i-b3f9133f68b88", services: [%{name: "postgres", status: 200}], status: 200}
Or without any service
iex> BtrzHealthchecker.info()
%BtrzHealthchecker.Info{build: "d3b3f9133f68b8877347e06b3d7285dd1d5d3921", commit: "3d7285dd1d5d3921d3b3f9133f68b8877347e06b",
instanceId: "i-b3f9133f68b88", services: [], status: 200}
"""
@spec info() :: %Info{}
def info() do
%Info{} =
set_environment_info()
|> Map.put(:status, 200)
end
@spec info([checker]) :: %Info{}
def info(checkers) when is_list(checkers) do
services_status =
checkers
|> Enum.map(fn checker_item ->
Task.async(fn ->
%{
name: checker_item.checker_module.name,
status: checker_item.checker_module.check_status(checker_item.opts)
}
end)
end)
|> Enum.map(&Task.await/1)
%Info{} =
set_environment_info()
|> Map.put(:status, 200)
|> Map.put(:services, services_status)
end
defp set_environment_info() do
%Info{
commit: @environment_info_api.git_revision_hash(),
instanceId: @environment_info_api.ec2_instance_id(),
build: @environment_info_api.build_number()
}
end
end
| 32.268657 | 132 | 0.672525 |
08c9cd1d21608162df4c0a2533c77cc98641dbeb | 104 | ex | Elixir | lib/inmana/repo.ex | alexfariac/inmana | 8ff51040c7c4902ef7a62b129373e5cad054c275 | [
"MIT"
] | 14 | 2021-04-26T14:19:28.000Z | 2021-09-12T03:29:42.000Z | lib/inmana/repo.ex | rwtrecs/rocketseat-nlw5-inmana | 8ce8bc32e0bdd005c423394bb163945747b557e2 | [
"MIT"
] | null | null | null | lib/inmana/repo.ex | rwtrecs/rocketseat-nlw5-inmana | 8ce8bc32e0bdd005c423394bb163945747b557e2 | [
"MIT"
] | 6 | 2021-04-27T12:41:16.000Z | 2021-07-02T04:11:53.000Z | defmodule Inmana.Repo do
use Ecto.Repo,
otp_app: :inmana,
adapter: Ecto.Adapters.Postgres
end
| 17.333333 | 35 | 0.721154 |
08c9dee6d2dc6327429a36e16e0a4ea8b961eec8 | 2,116 | exs | Elixir | config/dev.exs | shawnonthenet/mathmatical | d0f8d9e77dc71edfdc88776daca973fcd9cd106b | [
"Apache-2.0"
] | null | null | null | config/dev.exs | shawnonthenet/mathmatical | d0f8d9e77dc71edfdc88776daca973fcd9cd106b | [
"Apache-2.0"
] | null | null | null | config/dev.exs | shawnonthenet/mathmatical | d0f8d9e77dc71edfdc88776daca973fcd9cd106b | [
"Apache-2.0"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :mathmatical, MathmaticalWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch-stdin",
cd: Path.expand("../assets", __DIR__)
]
]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :mathmatical, MathmaticalWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/mathmatical_web/views/.*(ex)$},
~r{lib/mathmatical_web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
# Configure your database
config :mathmatical, Mathmatical.Repo,
username: "postgres",
password: "postgres",
database: "mathmatical_dev",
hostname: "localhost",
pool_size: 10
| 27.842105 | 68 | 0.691871 |
08c9e4a0fddc10702597b38a4827a9774d8f4c10 | 2,043 | ex | Elixir | clients/display_video/lib/google_api/display_video/v1/model/advertiser_ad_server_config.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/display_video/lib/google_api/display_video/v1/model/advertiser_ad_server_config.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/display_video/lib/google_api/display_video/v1/model/advertiser_ad_server_config.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.DisplayVideo.V1.Model.AdvertiserAdServerConfig do
@moduledoc """
Ad server related settings of an advertiser.
## Attributes
* `cmHybridConfig` (*type:* `GoogleApi.DisplayVideo.V1.Model.CmHybridConfig.t`, *default:* `nil`) - The configuration for advertisers that use both Campaign Manager (CM) and third-party ad servers.
* `thirdPartyOnlyConfig` (*type:* `GoogleApi.DisplayVideo.V1.Model.ThirdPartyOnlyConfig.t`, *default:* `nil`) - The configuration for advertisers that use third-party ad servers only.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:cmHybridConfig => GoogleApi.DisplayVideo.V1.Model.CmHybridConfig.t(),
:thirdPartyOnlyConfig => GoogleApi.DisplayVideo.V1.Model.ThirdPartyOnlyConfig.t()
}
field(:cmHybridConfig, as: GoogleApi.DisplayVideo.V1.Model.CmHybridConfig)
field(:thirdPartyOnlyConfig, as: GoogleApi.DisplayVideo.V1.Model.ThirdPartyOnlyConfig)
end
defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.AdvertiserAdServerConfig do
def decode(value, options) do
GoogleApi.DisplayVideo.V1.Model.AdvertiserAdServerConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.AdvertiserAdServerConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.86 | 201 | 0.764072 |
08c9f093b2d009ae1ccf4a6d88d3d221918c72bd | 3,245 | exs | Elixir | apps/tai/mix.exs | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 276 | 2018-01-16T06:36:06.000Z | 2021-03-20T21:48:01.000Z | apps/tai/mix.exs | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 73 | 2018-10-05T18:45:06.000Z | 2021-02-08T05:46:33.000Z | apps/tai/mix.exs | ccamateur/tai | 41c4b3e09dafc77987fa3f6b300c15461d981e16 | [
"MIT"
] | 43 | 2018-06-09T09:54:51.000Z | 2021-03-07T07:35:17.000Z | defmodule Tai.Mixfile do
use Mix.Project
def project do
[
app: :tai,
version: "0.0.74",
elixir: "~> 1.11",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
package: package(),
start_permanent: Mix.env() == :prod,
description: description(),
elixirc_paths: elixirc_paths(Mix.env()),
deps: deps(),
test_coverage: [tool: ExCoveralls]
]
end
def application do
[
mod: {Tai.Application, []},
start_phases: [venues: []],
extra_applications: [
:phoenix_pubsub,
:logger,
:iex,
:jason,
:tai_events,
:ecto_term,
:postgrex
]
]
end
defp deps do
[
{:confex, "~> 3.4"},
{:ecto, "~> 3.6"},
{:ecto_sql, "~> 3.6"},
{:ecto_sqlite3, "~> 0.7.1", optional: true},
# {:ecto_term, github: "fremantle-industries/ecto_term"},
{:ecto_term, "~> 0.0.1"},
{:enumerati, "~> 0.0.8"},
{:ex2ms, "~> 1.0"},
{:ex_binance, "~> 0.0.10"},
# {:ex_bitmex, github: "fremantle-industries/ex_bitmex", branch: "main"},
{:ex_bitmex, "~> 0.6.1"},
# {:ex_bybit, github: "fremantle-industries/ex_bybit", branch: "main"},
{:ex_bybit, "~> 0.0.1"},
{:ex_delta_exchange, "~> 0.0.3"},
# {:ex_deribit, github: "fremantle-industries/ex_deribit", branch: "main"},
{:ex_deribit, "~> 0.0.9"},
# {:ex_ftx, github: "fremantle-industries/ex_ftx", branch: "main"},
{:ex_ftx, "~> 0.0.13"},
# {:ex_okex, github: "fremantle-industries/ex_okex", branch: "main"},
{:ex_okex, "~> 0.6"},
{:ex_gdax, "~> 0.2"},
# {:ex_huobi, github: "fremantle-industries/ex_huobi", branch: "main"},
{:ex_huobi, "~> 0.0.2"},
{:decimal, "~> 2.0"},
{:httpoison, "~> 1.0"},
{:jason, "~> 1.1"},
{:juice, "~> 0.0.3"},
{:murmur, "~> 1.0"},
{:paged_query, "~> 0.0.2"},
{:phoenix_pubsub, "~> 2.0"},
{:polymorphic_embed, "~> 1.7"},
{:poolboy, "~> 1.5.1"},
{:postgrex, "~> 0.15", optional: true},
{:table_rex, "~> 3.0"},
# {:tai_events, path: "../../packages/tai_events"},
{:tai_events, "~> 0.0.2"},
{:telemetry, "~> 0.4 or ~> 1.0"},
{:timex, "~> 3.6"},
{:stored, "~> 0.0.8"},
{:vex, "~> 0.7"},
{:websockex, "~> 0.4.3"},
{:credo, "~> 1.0", only: [:dev, :test], runtime: false},
{:exvcr, "~> 0.13.0", only: [:dev, :test]},
{:logger_file_backend_with_formatters, "~> 0.0.1", only: [:dev, :test]},
{:logger_file_backend_with_formatters_stackdriver, "~> 0.0.4", only: [:dev, :test]},
{:echo_boy, "~> 0.6", runtime: false, optional: true},
{:mock, "~> 0.3", only: :test},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
defp description do
"A composable, real time, market data and trade execution toolkit"
end
defp package do
%{
licenses: ["MIT"],
maintainers: ["Alex Kwiatkowski"],
links: %{"GitHub" => "https://github.com/fremantle-industries/tai"}
}
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
end
| 30.613208 | 90 | 0.506317 |
08ca2bf50c25954f968f647fb5ec71e463e18235 | 1,832 | exs | Elixir | mix.exs | bigbassroller/ueberauth_example | 5e889abaf060b6a37add2eb8a3cf1938f394c4af | [
"MIT"
] | null | null | null | mix.exs | bigbassroller/ueberauth_example | 5e889abaf060b6a37add2eb8a3cf1938f394c4af | [
"MIT"
] | null | null | null | mix.exs | bigbassroller/ueberauth_example | 5e889abaf060b6a37add2eb8a3cf1938f394c4af | [
"MIT"
] | null | null | null | defmodule MyApp.MixProject do
use Mix.Project
def project do
[
app: :my_app,
version: "0.0.1",
elixir: "~> 1.11",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {MyApp.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.5.7"},
{:phoenix_ecto, "~> 4.1"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:telemetry_metrics, "~> 0.4"},
{:telemetry_poller, "~> 0.4"},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0"},
{:ueberauth, "~> 0.6"},
{:oauth2, "~> 2.0", override: true},
{:ueberauth_facebook, "~> 0.8"},
{:ueberauth_google, "~> 0.8"},
{:ueberauth_github, "~> 0.7"},
{:ueberauth_identity, "~> 0.2"},
{:ueberauth_slack, "~> 0.6"},
{:ueberauth_twitter, "~> 0.3"},
{:credo, "~> 1.5", only: [:dev, :test], runtime: false}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get", "cmd npm install --prefix assets"]
]
end
end
| 26.941176 | 84 | 0.569869 |
08ca3b3569c15ab09af92865aed3377111c357ba | 1,747 | ex | Elixir | lib/nerves/artifact/cache.ex | petrus-jvrensburg/nerves | 717372ede5248e30684ce7fcd2c6515ae7a90333 | [
"Apache-2.0"
] | null | null | null | lib/nerves/artifact/cache.ex | petrus-jvrensburg/nerves | 717372ede5248e30684ce7fcd2c6515ae7a90333 | [
"Apache-2.0"
] | null | null | null | lib/nerves/artifact/cache.ex | petrus-jvrensburg/nerves | 717372ede5248e30684ce7fcd2c6515ae7a90333 | [
"Apache-2.0"
] | null | null | null | defmodule Nerves.Artifact.Cache do
alias Nerves.Artifact
@checksum "CHECKSUM"
def get(pkg) do
path = path(pkg)
if valid?(pkg) do
path
else
nil
end
end
def put(pkg, path) do
ext = Artifact.ext(pkg)
dest = path(pkg)
File.rm_rf(dest)
if String.ends_with?(path, ext) do
File.mkdir_p!(dest)
:ok = Nerves.Utils.File.untar(path, dest)
else
Path.dirname(dest)
|> File.mkdir_p!()
File.ln_s!(path, dest)
end
Path.join(dest, @checksum)
|> File.write(Artifact.checksum(pkg))
end
def delete(pkg) do
path(pkg)
|> File.rm_rf()
end
def valid?(pkg) do
path = checksum_path(pkg)
case read_checksum(path) do
nil ->
try_link(pkg)
checksum ->
valid_checksum?(pkg, checksum)
end
end
def path(pkg) do
Artifact.base_dir()
|> Path.join(Artifact.name(pkg))
|> Path.expand()
end
def checksum_path(pkg) do
path(pkg)
|> Path.join(@checksum)
end
defp read_checksum(path) do
case File.read(path) do
{:ok, checksum} ->
String.trim(checksum)
{:error, _reason} ->
nil
end
end
defp valid_checksum?(_pkg, nil), do: false
defp valid_checksum?(pkg, checksum) do
pkg
|> Artifact.checksum()
|> String.equivalent?(checksum)
end
defp try_link(pkg) do
build_path_link = Artifact.build_path_link(pkg)
checksum_path = Path.join(build_path_link, @checksum)
checksum = read_checksum(checksum_path)
if valid_checksum?(pkg, checksum) do
dest = path(pkg)
File.mkdir_p(Artifact.base_dir())
File.rm_rf!(dest)
File.ln_s!(build_path_link, dest)
true
else
false
end
end
end
| 17.826531 | 57 | 0.606754 |
08ca51c6662f2bc465f6993cfbe2caebb2cb8c5f | 5,970 | exs | Elixir | test/credo/check/readability/max_line_length_test.exs | ak3nji/credo | 688b39901cbb1dbdea08a73fa5e15e74d5eb8101 | [
"MIT"
] | null | null | null | test/credo/check/readability/max_line_length_test.exs | ak3nji/credo | 688b39901cbb1dbdea08a73fa5e15e74d5eb8101 | [
"MIT"
] | null | null | null | test/credo/check/readability/max_line_length_test.exs | ak3nji/credo | 688b39901cbb1dbdea08a73fa5e15e74d5eb8101 | [
"MIT"
] | null | null | null | defmodule Credo.Check.Readability.MaxLineLengthTest do
use Credo.Test.Case
@described_check Credo.Check.Readability.MaxLineLength
#
# cases NOT raising issues
#
test "it should NOT report expected code" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
assert 1 + 1 == 2
end
end
"""
|> to_source_file
|> run_check(@described_check)
|> refute_issues()
end
test "it should NOT report a violation for URLs" do
"""
def fun do
# Based on https://github.com/rrrene/credo/blob/7dec9aecdd21ef33fdc20cc4ac6c94efb4bcddc3/lib/credo.ex#L4
nil
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80)
|> refute_issues()
end
test "it should NOT report expected code /2" do
"""
defmacro some_macro(type) do
quote do
fragment("CASE
WHEN
(? = 'some_text'
OR ? = 'some_text_2'
OR ? = 'some_text_3')
THEN '1'
ELSE '2'
END", unquote(type), unquote(type), unquote(type))
end
end
"""
|> to_source_file
|> run_check(@described_check)
|> refute_issues()
end
test "it should NOT report expected code if function definitions are excluded" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun({atom, meta, arguments} = ast, issues, source_file, max_complexity) do
assert 1 + 1 == 2
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80, ignore_definitions: true)
|> refute_issues()
end
test "it should NOT report expected code if @spec's are excluded" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
@spec some_fun(binary, binary, binary, binary, binary, binary, binary, binary, binary)
def some_fun(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) do
assert 1 + 1 == 2
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80, ignore_specs: true)
|> refute_issues()
end
test "it should NOT report a violation if strings are excluded" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
IO.puts 1
"long string, right? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 == 2"
IO.puts 2
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80, ignore_strings: true)
|> refute_issues()
end
test "it should NOT report a violation if strings are excluded for heredocs" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
IO.puts 1
\"\"\"
long string, right? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 == 2
\"\"\"
IO.puts 2
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80, ignore_strings: true)
|> refute_issues()
end
test "it should NOT report a violation if strings are excluded for heredocs /2" do
~S'''
defmodule CredoSampleModule do
def render(assigns) do
~H"""
My render template
"""
end
def long_string do
"This is a very long string that is after a ~H sigil, I would expect that it is ignored because I set the `ignore_strings` rule to be true."
end
end
'''
|> to_source_file
|> run_check(@described_check, max_length: 80)
|> refute_issues()
end
test "it should NOT report a violation with exec" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
assert 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 == 2
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 90)
|> refute_issues()
end
test "it should NOT report a violation if regex are excluded for regex" do
~S"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
opts =
TOMLConfigProvider.init(
"test/support/mysupercharts/fixture/config/#{platform()}/invalid_config.toml"
)
assert_raise ArgumentError,
~r<^Invalid configuration file "test/support/mysupercharts/fixture/config/(unix|win32)/invalid_config\.toml": %\{"locations" =\> \[%\{db: %\{hostname: \["can't be blank"\]\}\}, %\{\}\]\}$>,
fn -> TOMLConfigProvider.load(@config, opts) end
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80)
|> refute_issues()
end
#
# cases raising issues
#
test "it should report a violation" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
assert 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 == 2
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80)
|> assert_issue(fn issue ->
assert 81 == issue.column
assert "2" == issue.trigger
end)
end
test "it should report a violation /2" do
"""
defmodule CredoSampleModule do
use ExUnit.Case
def some_fun do
assert "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" <> "1" == "2"
end
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80)
|> assert_issue(fn issue ->
assert 81 == issue.column
assert issue.message =~ ~r/max is 80, was 112/
end)
end
test "it should report a violation /3" do
"""
def fun do
# Based on https://github.com/rrrene/credo/blob/7dec9aecdd21ef33fdc20cc4ac6c94efb4bcddc3/lib/credo.ex#L4
nil
end
"""
|> to_source_file
|> run_check(@described_check, max_length: 80, ignore_urls: false)
|> assert_issue()
end
end
| 25.732759 | 210 | 0.58258 |
08ca54bc4e3e31871a4c80775f84a35a7d2e35d3 | 1,503 | ex | Elixir | src/core/controllers/endpoint.ex | salespaulo/inmana | 26c0c1c1b61f37e4b108800eb8ed29fca986b9b7 | [
"MIT"
] | null | null | null | src/core/controllers/endpoint.ex | salespaulo/inmana | 26c0c1c1b61f37e4b108800eb8ed29fca986b9b7 | [
"MIT"
] | null | null | null | src/core/controllers/endpoint.ex | salespaulo/inmana | 26c0c1c1b61f37e4b108800eb8ed29fca986b9b7 | [
"MIT"
] | null | null | null | defmodule InmanaWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :inmana
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_inmana_key",
signing_salt: "IIS4jt7E"
]
socket "/socket", InmanaWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :inmana,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :inmana
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug InmanaWeb.Router
end
| 28.358491 | 97 | 0.71324 |
08ca574c87ad0ab415f7f3e6f320efc25b5bd555 | 4,617 | ex | Elixir | apps/aecore/lib/aecore/chain/identifier.ex | aeternity/epoch-elixir | d35613f5541a9bbebe61f90b8503a9b3416fe8b4 | [
"0BSD"
] | 131 | 2018-03-10T01:35:56.000Z | 2021-12-27T13:44:41.000Z | apps/aecore/lib/aecore/chain/identifier.ex | aeternity/elixir-node | d35613f5541a9bbebe61f90b8503a9b3416fe8b4 | [
"0BSD"
] | 445 | 2018-03-12T09:46:17.000Z | 2018-12-12T09:52:07.000Z | apps/aecore/lib/aecore/chain/identifier.ex | aeternity/epoch-elixir | d35613f5541a9bbebe61f90b8503a9b3416fe8b4 | [
"0BSD"
] | 23 | 2018-03-12T12:01:28.000Z | 2022-03-06T09:22:17.000Z | defmodule Aecore.Chain.Identifier do
@moduledoc """
Utility module for interacting with identifiers.
Our binaries like account pubkey or hashes will already be represented as encoded (with already specified tag) binaries, using the following format:
<<Tag:1/unsigned-integer-unit:8, Binary:32/binary-unit:8>>,
Where Tag is a non-negative integer ranging from 1 to 6 (at the current state of this documentation, for more info - :aecore, :binary_ids list in config.exs)
and Binary is a regular 32 byte binary
"""
alias __MODULE__
defstruct type: :undefined, value: ""
@typedoc "Structure of the Identifier Transaction type"
@type t() :: %Identifier{type: type(), value: value()}
@type type() :: :account | :name | :commitment | :oracle | :contract | :channel
@type value() :: binary()
@tag_size 8
@spec create_identity(value(), type()) :: Identifier.t()
def create_identity(value, type)
when is_atom(type) and is_binary(value) do
%Identifier{type: type, value: value}
end
@spec valid?(Identifier.t() | list(Identifier.t()), type()) :: boolean()
def valid?(%Identifier{value: value} = id, type) do
create_identity(value, type) == id
end
def valid?(ids_list, type) when is_list(ids_list) do
Enum.all?(ids_list, fn id -> valid?(id, type) end)
end
def valid?(_, _) do
false
end
@spec create_encoded_to_binary(value(), type()) :: binary()
def create_encoded_to_binary(value, type) do
value
|> create_identity(type)
|> encode_to_binary()
end
@spec create_encoded_to_binary_list(list(value()), type()) :: list(binary())
def create_encoded_to_binary_list([value | rest], type) do
[create_encoded_to_binary(value, type) | create_encoded_to_binary_list(rest, type)]
end
def create_encoded_to_binary_list([], _) do
[]
end
# API needed for RLP
@spec encode_to_binary(Identifier.t()) :: binary()
def encode_to_binary(%Identifier{value: value, type: type}) do
tag = type_to_tag(type)
<<tag::unsigned-integer-size(@tag_size), value::binary>>
end
@spec decode_from_binary(binary()) :: tuple() | {:error, String.t()}
def decode_from_binary(<<tag::unsigned-integer-size(@tag_size), data::binary>>)
when is_binary(data) do
case tag_to_type(tag) do
{:error, msg} ->
{:error, msg}
{:ok, type} ->
{:ok, %Identifier{type: type, value: data}}
end
end
@spec decode_from_binary_to_value(binary(), type()) :: {:ok, value()} | {:error, String.t()}
def decode_from_binary_to_value(data, type) do
case decode_from_binary(data) do
{:ok, %Identifier{type: ^type, value: value}} ->
{:ok, value}
{:ok, %Identifier{type: received_type}} ->
{:error, "#{__MODULE__}: Unexpected type. Expected #{type}, but got #{received_type}"}
{:error, _} = error ->
error
end
end
@spec decode_from_binary_list_to_value_list(list(binary()), type()) ::
{:ok, list(value())} | {:error, String.t()}
def decode_from_binary_list_to_value_list([encoded_identifier | rest], type) do
with {:ok, value} <- decode_from_binary_to_value(encoded_identifier, type),
{:ok, rest_values} <- decode_from_binary_list_to_value_list(rest, type) do
{:ok, [value | rest_values]}
else
{:error, _} = error ->
error
end
end
def decode_from_binary_list_to_value_list([], _) do
{:ok, []}
end
@spec encode_list_to_binary(list(t())) :: list(binary())
def encode_list_to_binary([]), do: []
def encode_list_to_binary([head | rest]) do
[encode_to_binary(head) | encode_list_to_binary(rest)]
end
@spec decode_list_from_binary(list(binary())) ::
{:ok, list(Identifier.t())} | {:error, String.t()}
def decode_list_from_binary([]), do: {:ok, []}
def decode_list_from_binary([head | rest]) do
with {:ok, head_decoded} <- decode_from_binary(head),
{:ok, rest_decoded} <- decode_list_from_binary(rest) do
{:ok, [head_decoded | rest_decoded]}
else
{:error, _} = error -> error
end
end
defp type_to_tag(:account), do: 1
defp type_to_tag(:name), do: 2
defp type_to_tag(:commitment), do: 3
defp type_to_tag(:oracle), do: 4
defp type_to_tag(:contract), do: 5
defp type_to_tag(:channel), do: 6
defp tag_to_type(1), do: {:ok, :account}
defp tag_to_type(2), do: {:ok, :name}
defp tag_to_type(3), do: {:ok, :commitment}
defp tag_to_type(4), do: {:ok, :oracle}
defp tag_to_type(5), do: {:ok, :contract}
defp tag_to_type(6), do: {:ok, :channel}
defp tag_to_type(_), do: {:error, "#{__MODULE__}: Invalid tag"}
end
| 32.744681 | 160 | 0.659736 |
08ca628cf36563c49c97fae10c383e2ad601dad4 | 2,302 | ex | Elixir | clients/genomics/lib/google_api/genomics/v1/model/status.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/genomics/lib/google_api/genomics/v1/model/status.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/genomics/lib/google_api/genomics/v1/model/status.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.Genomics.V1.Model.Status do
@moduledoc """
The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
## Attributes
* `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code.
* `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use.
* `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => integer(),
:details => list(map()),
:message => String.t()
}
field(:code)
field(:details, type: :list)
field(:message)
end
defimpl Poison.Decoder, for: GoogleApi.Genomics.V1.Model.Status do
def decode(value, options) do
GoogleApi.Genomics.V1.Model.Status.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Genomics.V1.Model.Status do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.433962 | 427 | 0.720243 |
08ca7fc2f9b68d425f44196a5778e82b1d308bac | 124 | ex | Elixir | examples/route_guide/lib/endpoint.ex | braverhealth/grpc | eff8a8828d27ddd7f63a3c1dd5aae86246df215e | [
"Apache-2.0"
] | 561 | 2019-03-18T09:10:57.000Z | 2022-03-27T17:34:59.000Z | examples/route_guide/lib/endpoint.ex | braverhealth/grpc | eff8a8828d27ddd7f63a3c1dd5aae86246df215e | [
"Apache-2.0"
] | 94 | 2019-03-20T09:34:38.000Z | 2022-02-27T20:44:04.000Z | examples/route_guide/lib/endpoint.ex | braverhealth/grpc | eff8a8828d27ddd7f63a3c1dd5aae86246df215e | [
"Apache-2.0"
] | 112 | 2019-03-25T03:27:26.000Z | 2022-03-21T12:43:59.000Z | defmodule Routeguide.Endpoint do
use GRPC.Endpoint
intercept GRPC.Logger.Server
run Routeguide.RouteGuide.Server
end
| 17.714286 | 34 | 0.814516 |
08ca8939710c473aa6344d0569f6430f6d6ffdda | 1,050 | ex | Elixir | bullion/test/support/conn_case.ex | ttymck/bullion | d15babe80d30f9775e45f2a143b88a66b539d318 | [
"MIT"
] | null | null | null | bullion/test/support/conn_case.ex | ttymck/bullion | d15babe80d30f9775e45f2a143b88a66b539d318 | [
"MIT"
] | 8 | 2021-03-10T20:53:42.000Z | 2021-07-30T06:52:16.000Z | bullion/test/support/conn_case.ex | ttymck/bullion | d15babe80d30f9775e45f2a143b88a66b539d318 | [
"MIT"
] | null | null | null | defmodule BullionWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias BullionWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint BullionWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Bullion.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Bullion.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.923077 | 69 | 0.718095 |
08cac658ab5bbbfac2d2074aac966b0ba2f20cd5 | 77 | ex | Elixir | portfolio/lib/portfolio_web/views/user_confirmation_view.ex | JackMaarek/portfolio | 4423e67df870b14228edbc9e4ce3f3cdf1bccc2d | [
"MIT"
] | null | null | null | portfolio/lib/portfolio_web/views/user_confirmation_view.ex | JackMaarek/portfolio | 4423e67df870b14228edbc9e4ce3f3cdf1bccc2d | [
"MIT"
] | 11 | 2020-04-29T10:28:20.000Z | 2020-04-29T11:03:13.000Z | portfolio/lib/portfolio_web/views/user_confirmation_view.ex | JackMaarek/portfolio | 4423e67df870b14228edbc9e4ce3f3cdf1bccc2d | [
"MIT"
] | null | null | null | defmodule PortfolioWeb.UserConfirmationView do
use PortfolioWeb, :view
end
| 19.25 | 46 | 0.844156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.