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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08b375e0884d2b19d09d70bff5d460c1eb2a8b78 | 351 | exs | Elixir | priv/repo/migrations/20150902201300_create_vehicle_position.exs | bus-detective/pro | d313f4facdb4c9229bd7a022eeabb85170000e18 | [
"MIT"
] | null | null | null | priv/repo/migrations/20150902201300_create_vehicle_position.exs | bus-detective/pro | d313f4facdb4c9229bd7a022eeabb85170000e18 | [
"MIT"
] | null | null | null | priv/repo/migrations/20150902201300_create_vehicle_position.exs | bus-detective/pro | d313f4facdb4c9229bd7a022eeabb85170000e18 | [
"MIT"
] | null | null | null | defmodule BdPro.Repo.Migrations.CreateVehiclePosition do
use Ecto.Migration
def change do
create table(:vehicle_positions) do
add :trip_remote_id, :integer
add :lat, :float
add :lng, :float
add :vehicle_id, references(:vehicles)
timestamps
end
create index(:vehicle_positions, [:vehicle_id])
end
end
| 20.647059 | 56 | 0.689459 |
08b379becb2bc211f43711c7dde722e34db7da9f | 1,046 | exs | Elixir | config/config.exs | majeX/phoenix-liveview-demo | e6c27fdd771eae8d64b3e8950a53e2534be72168 | [
"MIT"
] | null | null | null | config/config.exs | majeX/phoenix-liveview-demo | e6c27fdd771eae8d64b3e8950a53e2534be72168 | [
"MIT"
] | null | null | null | config/config.exs | majeX/phoenix-liveview-demo | e6c27fdd771eae8d64b3e8950a53e2534be72168 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
use Mix.Config
# Configures the endpoint
config :mcf_phoenix, McfPhoenixWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "gxfjgDU8TgtR2ys6AZHzPOCCMwfc8Sxv+U7tttW+9pBoqaZjeqbRq3Bg8N6oYxAR",
render_errors: [view: McfPhoenixWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: McfPhoenix.PubSub, adapter: Phoenix.PubSub.PG2],
live_view: [
signing_salt: "Rq4Elk9kXgSMn8qgA7ZIDoNg5yTB+D0s"
]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 33.741935 | 86 | 0.770554 |
08b387819542e881715925acf4461c5d250c6398 | 1,031 | exs | Elixir | apps/zones/mix.exs | mbta/crispy-spoon | 7ef28a1a6adc73899b007e334b9220f7a48a60fa | [
"MIT"
] | null | null | null | apps/zones/mix.exs | mbta/crispy-spoon | 7ef28a1a6adc73899b007e334b9220f7a48a60fa | [
"MIT"
] | null | null | null | apps/zones/mix.exs | mbta/crispy-spoon | 7ef28a1a6adc73899b007e334b9220f7a48a60fa | [
"MIT"
] | null | null | null | defmodule Zones.Mixfile do
use Mix.Project
def project do
[
app: :zones,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
deps: deps()
]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger, :csv]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# To depend on another app inside the umbrella:
#
# {:myapp, in_umbrella: true}
#
# Type "mix help deps" for more examples and options
defp deps do
[
{:csv, "~> 2.3"},
{:exvcr_helpers, in_umbrella: true, only: :test}
]
end
end
| 22.413043 | 77 | 0.57517 |
08b38dda0b3c82a80c66eddb5a187714cba148cb | 3,675 | exs | Elixir | mix.exs | j127/tesla | 9ea2e9e663b6ec3ca1acad7178a863b76da0cab9 | [
"MIT"
] | 1 | 2021-10-16T22:37:03.000Z | 2021-10-16T22:37:03.000Z | mix.exs | barisbalic/tesla | 979595465e83102b47e71bfd223a16c99e97f778 | [
"MIT"
] | null | null | null | mix.exs | barisbalic/tesla | 979595465e83102b47e71bfd223a16c99e97f778 | [
"MIT"
] | null | null | null | defmodule Tesla.Mixfile do
use Mix.Project
@version "1.3.0"
def project do
[
app: :tesla,
version: @version,
description: description(),
package: package(),
source_ref: "v#{@version}",
source_url: "https://github.com/teamon/tesla",
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
deps: deps(),
lockfile: lockfile(System.get_env("LOCKFILE")),
test_coverage: [tool: ExCoveralls],
dialyzer: [
plt_add_apps: [:inets],
plt_add_deps: :project
],
docs: docs()
]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: applications(Mix.env())]
end
def applications(:test), do: applications(:dev) ++ [:httparrot, :hackney, :ibrowse, :gun]
def applications(_), do: [:logger, :ssl, :inets]
defp description do
"HTTP client library, with support for middleware and multiple adapters."
end
defp package do
[
maintainers: ["Tymon Tobolski"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/teamon/tesla"}
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp lockfile(nil), do: "mix.lock"
defp lockfile(lockfile), do: "test/lockfiles/#{lockfile}.lock"
defp deps do
[
{:mime, "~> 1.0"},
# http clients
{:ibrowse, "~> 4.4.0", optional: true},
{:hackney, "~> 1.6", optional: true},
{:gun, "~> 1.3", optional: true},
{:castore, "~> 0.1", optional: true},
{:mint, "~> 1.0", optional: true},
# json parsers
{:jason, ">= 1.0.0", optional: true},
{:poison, ">= 1.0.0", optional: true},
{:exjsx, ">= 3.0.0", optional: true},
# other
{:fuse, "~> 2.4", optional: true},
{:telemetry, "~> 0.3", optional: true},
# testing & docs
{:excoveralls, "~> 0.8", only: :test},
{:httparrot, "~> 1.2", only: :test},
{:ex_doc, "~> 0.21", only: :dev},
{:mix_test_watch, "~> 1.0", only: :dev},
{:dialyxir, "~> 1.0.0-rc.3", only: [:dev, :test]},
{:inch_ex, "~> 0.5.6", only: :docs}
]
end
defp docs do
[
main: "readme",
extras: ["README.md"],
groups_for_modules: [
Behaviours: [
Tesla.Adapter,
Tesla.Middleware
],
Adapters: [
Tesla.Adapter.Gun,
Tesla.Adapter.Hackney,
Tesla.Adapter.Httpc,
Tesla.Adapter.Ibrowse,
Tesla.Adapter.Mint
],
Middlewares: [
Tesla.Middleware.BaseUrl,
Tesla.Middleware.BasicAuth,
Tesla.Middleware.Compression,
Tesla.Middleware.CompressRequest,
Tesla.Middleware.DecodeJson,
Tesla.Middleware.DecodeRels,
Tesla.Middleware.DecompressResponse,
Tesla.Middleware.DigestAuth,
Tesla.Middleware.EncodeJson,
Tesla.Middleware.FollowRedirects,
Tesla.Middleware.FormUrlencoded,
Tesla.Middleware.Fuse,
Tesla.Middleware.Headers,
Tesla.Middleware.JSON,
Tesla.Middleware.KeepRequest,
Tesla.Middleware.Logger,
Tesla.Middleware.MethodOverride,
Tesla.Middleware.Opts,
Tesla.Middleware.PathParams,
Tesla.Middleware.Query,
Tesla.Middleware.Retry,
Tesla.Middleware.Telemetry,
Tesla.Middleware.Timeout
]
],
nest_modules_by_prefix: [
Tesla.Adapter,
Tesla.Middleware
]
]
end
end
| 27.222222 | 91 | 0.566259 |
08b3d922f68c102a4de21899289faab82c67954c | 225 | exs | Elixir | tor_practice_snippets/mylist.exs | TheDeepEnd/elixir-snippets | 68d1429706f725410e690ef86406eb4bf900aff2 | [
"MIT"
] | null | null | null | tor_practice_snippets/mylist.exs | TheDeepEnd/elixir-snippets | 68d1429706f725410e690ef86406eb4bf900aff2 | [
"MIT"
] | null | null | null | tor_practice_snippets/mylist.exs | TheDeepEnd/elixir-snippets | 68d1429706f725410e690ef86406eb4bf900aff2 | [
"MIT"
] | null | null | null | defmodule MyList do
def len([]), do: 0
def len( [ _head | tail ] ), do: 1 + len(tail)
def square([]), do: []
def square( [ head | tail ] ), do: [ head * head | square(tail) ]
end
| 22.5 | 67 | 0.453333 |
08b4017727d6417332fae6bb8daced37935535ba | 1,159 | ex | Elixir | lib/dialyxir/warnings/pattern_match_covered.ex | legoscia/dialyxir | 39579cb3abf6570da56a2a7185204452c49f9b5c | [
"Apache-2.0"
] | null | null | null | lib/dialyxir/warnings/pattern_match_covered.ex | legoscia/dialyxir | 39579cb3abf6570da56a2a7185204452c49f9b5c | [
"Apache-2.0"
] | null | null | null | lib/dialyxir/warnings/pattern_match_covered.ex | legoscia/dialyxir | 39579cb3abf6570da56a2a7185204452c49f9b5c | [
"Apache-2.0"
] | null | null | null | defmodule Dialyxir.Warnings.PatternMatchCovered do
@behaviour Dialyxir.Warning
@impl Dialyxir.Warning
@spec warning() :: :pattern_match_cov
def warning(), do: :pattern_match_cov
@impl Dialyxir.Warning
@spec format_short([String.t()]) :: String.t()
def format_short(_) do
"The pattern can never match the type since it covered by previous clauses."
end
@impl Dialyxir.Warning
@spec format_long([String.t()]) :: String.t()
def format_long([pattern, type]) do
pretty_pattern = Erlex.pretty_print_pattern(pattern)
pretty_type = Erlex.pretty_print_type(type)
"""
The pattern
#{pretty_pattern}
can never match since previous clauses completely cover the type
#{pretty_type}
"""
end
@impl Dialyxir.Warning
@spec explain() :: String.t()
def explain() do
"""
The pattern match has a later clause that will never be executed
because a more general clause is higher in the matching order.
Example:
defmodule Example do
def ok() do
unmatched(:error)
end
defp unmatched(_), do: :ok
defp unmatched(:error), do: :error
end
"""
end
end
| 22.72549 | 80 | 0.67472 |
08b4279342875377a7fdcd03ef4a733ae66cb9e2 | 12,413 | exs | Elixir | test/mastani_server_web/query/cms/job_comment_test.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | 1 | 2019-05-07T15:03:54.000Z | 2019-05-07T15:03:54.000Z | test/mastani_server_web/query/cms/job_comment_test.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | test/mastani_server_web/query/cms/job_comment_test.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | defmodule MastaniServer.Test.Query.JobComment do
use MastaniServer.TestTools
alias MastaniServer.CMS
setup do
{:ok, job} = db_insert(:job)
{:ok, user} = db_insert(:user)
{:ok, community} = db_insert(:community)
guest_conn = simu_conn(:guest)
user_conn = simu_conn(:user)
{:ok, ~m(user_conn guest_conn job user community)a}
end
describe "[job dataloader comment]" do
@query """
query($filter: PagedJobsFilter) {
pagedJobs(filter: $filter) {
entries {
id
title
commentsParticipators(filter: { first: 5 }) {
id
nickname
}
pagedCommentsParticipators {
entries {
id
}
totalCount
}
commentsCount
}
totalCount
}
}
"""
test "can get comments participators of a job", ~m(user guest_conn)a do
{:ok, user2} = db_insert(:user)
{:ok, community} = db_insert(:community)
{:ok, job} = CMS.create_content(community, :job, mock_attrs(:job), user)
variables = %{thread: "JOB", filter: %{community: community.raw}}
guest_conn |> query_result(@query, variables, "pagedJobs")
body = "this is a test comment"
assert {:ok, _comment} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
assert {:ok, _comment} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
assert {:ok, _comment} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user2)
variables = %{filter: %{community: community.raw}}
results = guest_conn |> query_result(@query, variables, "pagedJobs")
comments_count = results["entries"] |> List.first() |> Map.get("commentsCount")
assert comments_count == 3
end
test "can get comments participators of a job with multi user", ~m(user guest_conn)a do
body = "this is a test comment"
{:ok, community} = db_insert(:community)
{:ok, job1} = CMS.create_content(community, :job, mock_attrs(:job), user)
{:ok, job2} = CMS.create_content(community, :job, mock_attrs(:job), user)
{:ok, users_list} = db_insert_multi(:user, 10)
{:ok, users_list2} = db_insert_multi(:user, 10)
Enum.each(
users_list,
&CMS.create_comment(:job, job1.id, %{community: community.raw, body: body}, &1)
)
Enum.each(
users_list2,
&CMS.create_comment(:job, job2.id, %{community: community.raw, body: body}, &1)
)
variables = %{thread: "JOB", filter: %{community: community.raw}}
results = guest_conn |> query_result(@query, variables, "pagedJobs")
assert results["entries"] |> List.first() |> Map.get("commentsParticipators") |> length ==
10
assert results["entries"] |> List.last() |> Map.get("commentsParticipators") |> length == 10
end
test "can get paged commetns participators of a job", ~m(user guest_conn)a do
body = "this is a test comment"
{:ok, community} = db_insert(:community)
{:ok, job} = CMS.create_content(community, :job, mock_attrs(:job), user)
{:ok, users_list} = db_insert_multi(:user, 10)
Enum.each(
users_list,
&CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, &1)
)
variables = %{filter: %{community: community.raw}}
results = guest_conn |> query_result(@query, variables, "pagedJobs")
participators = results["entries"] |> List.first() |> Map.get("pagedCommentsParticipators")
assert participators["totalCount"] == 10
end
end
@query """
query($id: ID!, $thread: CmsThread, $filter: PagedFilter!) {
pagedCommentsParticipators(id: $id, thread: $thread, filter: $filter) {
entries {
id
nickname
}
totalPages
totalCount
pageSize
pageNumber
}
}
"""
test "can get job's paged commetns participators", ~m(user guest_conn)a do
body = "this is a test comment"
{:ok, community} = db_insert(:community)
{:ok, job} = CMS.create_content(community, :job, mock_attrs(:job), user)
{:ok, users_list} = db_insert_multi(:user, 10)
Enum.each(
users_list,
&CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, &1)
)
variables = %{id: job.id, thread: "JOB", filter: %{page: 1, size: 20}}
results = guest_conn |> query_result(@query, variables, "pagedCommentsParticipators")
assert results |> is_valid_pagination?()
assert results["totalCount"] == 10
end
# TODO: user can get specific user's replies :list_replies
describe "[job comment]" do
@query """
query($filter: PagedJobsFilter) {
pagedJobs(filter: $filter) {
entries {
id
title
commentsCount
}
totalCount
}
}
"""
test "can get comments info in paged jobs", ~m(user guest_conn)a do
body = "this is a test comment"
{:ok, community} = db_insert(:community)
{:ok, job} = CMS.create_content(community, :job, mock_attrs(:job), user)
{:ok, _comment} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
variables = %{filter: %{community: community.raw}}
results = guest_conn |> query_result(@query, variables, "pagedJobs")
assert results["entries"] |> List.first() |> Map.get("commentsCount") == 1
end
@query """
query($thread: CmsThread, $id: ID!, $filter: CommentsFilter!) {
pagedComments(thread: $thread, id: $id, filter: $filter) {
entries {
id
body
likesCount
dislikesCount
}
totalPages
totalCount
pageSize
pageNumber
}
}
"""
test "guest user can get a paged comment", ~m(guest_conn job user community)a do
body = "test comment"
Enum.reduce(1..30, [], fn _, acc ->
{:ok, value} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
acc ++ [value]
end)
variables = %{thread: "JOB", id: job.id, filter: %{page: 1, size: 10}}
results = guest_conn |> query_result(@query, variables, "pagedComments")
assert results |> is_valid_pagination?
assert results["totalCount"] == 30
end
test "MOST_LIKES filter should work", ~m(guest_conn job user community)a do
body = "test comment"
comments =
Enum.reduce(1..10, [], fn _, acc ->
{:ok, value} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
acc ++ [value]
end)
[comment_1, _comment_2, comment_3, _comment_last] = comments |> firstn_and_last(3)
{:ok, [user_1, user_2, user_3, user_4, user_5]} = db_insert_multi(:user, 5)
# comment_3 is most likes
{:ok, _} = CMS.like_comment(:job_comment, comment_3.id, user_1)
{:ok, _} = CMS.like_comment(:job_comment, comment_3.id, user_2)
{:ok, _} = CMS.like_comment(:job_comment, comment_3.id, user_3)
{:ok, _} = CMS.like_comment(:job_comment, comment_3.id, user_4)
{:ok, _} = CMS.like_comment(:job_comment, comment_3.id, user_5)
{:ok, _} = CMS.like_comment(:job_comment, comment_1.id, user_1)
{:ok, _} = CMS.like_comment(:job_comment, comment_1.id, user_2)
{:ok, _} = CMS.like_comment(:job_comment, comment_1.id, user_3)
{:ok, _} = CMS.like_comment(:job_comment, comment_1.id, user_4)
variables = %{
thread: "JOB",
id: job.id,
filter: %{page: 1, size: 10, sort: "MOST_LIKES"}
}
results = guest_conn |> query_result(@query, variables, "pagedComments")
entries = results["entries"]
assert entries |> Enum.at(0) |> Map.get("id") == to_string(comment_3.id)
assert entries |> Enum.at(0) |> Map.get("likesCount") == 5
assert entries |> Enum.at(1) |> Map.get("id") == to_string(comment_1.id)
assert entries |> Enum.at(1) |> Map.get("likesCount") == 4
end
test "MOST_DISLIKES filter should work", ~m(guest_conn job user community)a do
body = "test comment"
comments =
Enum.reduce(1..10, [], fn _, acc ->
{:ok, value} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
acc ++ [value]
end)
[comment_1, _comment_2, comment_3, _comment_last] = comments |> firstn_and_last(3)
{:ok, [user_1, user_2, user_3, user_4, user_5]} = db_insert_multi(:user, 5)
# comment_3 is most likes
{:ok, _} = CMS.dislike_comment(:job_comment, comment_3.id, user_1)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_3.id, user_2)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_3.id, user_3)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_3.id, user_4)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_3.id, user_5)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_1.id, user_1)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_1.id, user_2)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_1.id, user_3)
{:ok, _} = CMS.dislike_comment(:job_comment, comment_1.id, user_4)
variables = %{
thread: "JOB",
id: job.id,
filter: %{page: 1, size: 10, sort: "MOST_DISLIKES"}
}
results = guest_conn |> query_result(@query, variables, "pagedComments")
entries = results["entries"]
assert entries |> Enum.at(0) |> Map.get("id") == to_string(comment_3.id)
assert entries |> Enum.at(0) |> Map.get("dislikesCount") == 5
assert entries |> Enum.at(1) |> Map.get("id") == to_string(comment_1.id)
assert entries |> Enum.at(1) |> Map.get("dislikesCount") == 4
end
@query """
query($thread: CmsThread, $id: ID!, $filter: CommentsFilter!) {
pagedComments(thread: $thread, id: $id, filter: $filter) {
entries {
id
viewerHasLiked
}
}
}
"""
test "login user can get hasLiked feedBack", ~m(user_conn job user community)a do
body = "test comment"
{:ok, comment} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
{:ok, _like} = CMS.like_comment(:job_comment, comment.id, user)
variables = %{thread: "JOB", id: job.id, filter: %{page: 1, size: 10}}
results = user_conn |> query_result(@query, variables, "pagedComments")
found =
results["entries"] |> Enum.filter(&(&1["id"] == to_string(comment.id))) |> List.first()
assert found["viewerHasLiked"] == false
own_like_conn = simu_conn(:user, user)
results = own_like_conn |> query_result(@query, variables, "pagedComments")
found =
results["entries"] |> Enum.filter(&(&1["id"] == to_string(comment.id))) |> List.first()
assert found["viewerHasLiked"] == true
end
@query """
query($thread: CmsThread, $id: ID!, $filter: PagedFilter!) {
pagedComments(thread: $thread, id: $id, filter: $filter) {
entries {
id
body
replyTo {
id
body
}
repliesCount
replies {
id
body
}
}
}
}
"""
test "guest user can get replies info", ~m(guest_conn job user community)a do
body = "test comment"
{:ok, comment} =
CMS.create_comment(:job, job.id, %{community: community.raw, body: body}, user)
{:ok, reply} = CMS.reply_comment(:job, comment.id, %{body: "reply body"}, user)
variables = %{thread: "JOB", id: job.id, filter: %{page: 1, size: 10}}
results = guest_conn |> query_result(@query, variables, "pagedComments")
found =
results["entries"] |> Enum.filter(&(&1["id"] == to_string(comment.id))) |> List.first()
found_reply =
results["entries"] |> Enum.filter(&(&1["id"] == to_string(reply.id))) |> List.first()
# author = found |> Map.get("author")
assert found["repliesCount"] == 1
assert found["replies"] |> Enum.any?(&(&1["id"] == to_string(reply.id)))
assert found["replyTo"] == nil
assert found_reply["replyTo"] |> Map.get("id") == to_string(comment.id)
end
end
end
| 33.013298 | 98 | 0.591799 |
08b46e9caf9fcf8e02f74bee94e4de2ad3b6caef | 45,020 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/instance_group_managers.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/instance_group_managers.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/instance_group_managers.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.Compute.V1.Api.InstanceGroupManagers do
@moduledoc """
API calls for all endpoints tagged `InstanceGroupManagers`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstanceGroupManagersAbandonInstancesRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_abandon_instances(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_abandon_instances(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/abandonInstances",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Retrieves the list of managed instance groups and groups them by zone.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (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 (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 (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 (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.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceGroupManagerAggregatedList{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_aggregated_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.InstanceGroupManagerAggregatedList.t()}
| {:error, Tesla.Env.t()}
def compute_instance_group_managers_aggregated_list(connection, project, opts \\ []) do
optional_params = %{
: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/instanceGroupManagers", %{
"project" => URI.encode_www_form(project)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.InstanceGroupManagerAggregatedList{})
end
@doc """
Deletes the specified managed instance group and all of the instances in that group. Note that the instance group must not belong to a backend service. Read Deleting an instance group for more information.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group to delete.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_delete(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}", %{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstanceGroupManagersDeleteInstancesRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_delete_instances(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_delete_instances(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/deleteInstances",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Returns all of the details about the specified managed instance group. Gets a list of available managed instance groups by making a list() request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceGroupManager{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.InstanceGroupManager.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_get(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
: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}/instanceGroupManagers/{instanceGroupManager}", %{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.InstanceGroupManager{})
end
@doc """
Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method. A managed instance group can have up to 1000 VM instances per group. Please contact Cloud Support if you need an increase in this limit.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where you want to create the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstanceGroupManager):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_insert(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_insert(connection, project, zone, opts \\ []) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/zones/{zone}/instanceGroupManagers", %{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Retrieves a list of managed instance groups that are contained within the specified project and zone.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (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 (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 (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 (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.
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceGroupManagerList{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.InstanceGroupManagerList.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_list(connection, project, zone, opts \\ []) do
optional_params = %{
: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}/instanceGroupManagers", %{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone)
})
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.InstanceGroupManagerList{})
end
@doc """
Lists all of the instances in the managed instance group. Each instance in the list has a currentAction, which indicates the action that the managed instance group is performing on the instance. For example, if the group is still creating an instance, the currentAction is CREATING. If a previous action failed, the list displays the errors for that failed action.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :filter (String.t):
- :maxResults (integer()):
- :order_by (String.t):
- :pageToken (String.t):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_list_managed_instances(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse.t()}
| {:error, Tesla.Env.t()}
def compute_instance_group_managers_list_managed_instances(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:order_by => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/listManagedInstances",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(
struct: %GoogleApi.Compute.V1.Model.InstanceGroupManagersListManagedInstancesResponse{}
)
end
@doc """
Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstanceGroupManagersRecreateInstancesRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_recreate_instances(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_recreate_instances(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/recreateInstances",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group deletes instances. The resize operation is marked DONE when the resize actions are scheduled even if the group has not yet added or deleted any instances. You must separately verify the status of the creating or deleting actions with the listmanagedinstances method. If the group is part of a backend service that has enabled connection draining, it can take up to 60 seconds after the connection draining duration has elapsed before the VM instance is removed or deleted.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- size (integer()): The number of running instances that the managed instance group should maintain at any given time. The group automatically adds or removes instances to maintain the number of instances specified by this parameter.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_resize(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
integer(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_resize(
connection,
project,
zone,
instance_group_manager,
size,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/resize",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_param(:query, :size, size)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Specifies the instance template to use when creating new instances in this group. The templates for existing instances in the group do not change unless you recreate them.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstanceGroupManagersSetInstanceTemplateRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_set_instance_template(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_set_instance_template(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/setInstanceTemplate",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
@doc """
Modifies the target pools to which all instances in this managed instance group are assigned. The target pools automatically apply to all of the instances in the managed instance group. This operation is marked DONE when you make the request even if the instances have not yet been added to their target pools. The change might take some time to apply to all of the instances in the group depending on the size of the group.
## Parameters
- connection (GoogleApi.Compute.V1.Connection): Connection to server
- project (String.t): Project ID for this request.
- zone (String.t): The name of the zone where the managed instance group is located.
- instance_group_manager (String.t): The name of the managed instance group.
- opts (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial 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.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
- :body (InstanceGroupManagersSetTargetPoolsRequest):
## Returns
{:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success
{:error, info} on failure
"""
@spec compute_instance_group_managers_set_target_pools(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_instance_group_managers_set_target_pools(
connection,
project,
zone,
instance_group_manager,
opts \\ []
) do
optional_params = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/setTargetPools",
%{
"project" => URI.encode_www_form(project),
"zone" => URI.encode_www_form(zone),
"instanceGroupManager" => URI.encode_www_form(instance_group_manager)
}
)
|> Request.add_optional_params(optional_params, opts)
connection
|> Connection.execute(request)
|> Response.decode(struct: %GoogleApi.Compute.V1.Model.Operation{})
end
end
| 54.835566 | 1,213 | 0.701888 |
08b491a441eb0bb3d9656275f6b5d62193970058 | 107 | ex | Elixir | src/Makefile.ex | w-guo/Network-TDA | 6af7241cb65eb1b6f46fa5bb898a21423b4beee1 | [
"MIT"
] | null | null | null | src/Makefile.ex | w-guo/Network-TDA | 6af7241cb65eb1b6f46fa5bb898a21423b4beee1 | [
"MIT"
] | null | null | null | src/Makefile.ex | w-guo/Network-TDA | 6af7241cb65eb1b6f46fa5bb898a21423b4beee1 | [
"MIT"
] | 1 | 2021-11-08T21:45:00.000Z | 2021-11-08T21:45:00.000Z | #
# configuration variables for the example
## Main application file
MAIN = main_dyCPM
DEPH =
DEPCPP =
| 11.888889 | 41 | 0.728972 |
08b4ab08a7f0d80e94523921d3a8d6c411037c84 | 1,637 | ex | Elixir | lib/blockquote_web.ex | allen-garvey/block-quote-phoenix | 5c0f5d16daf6bb515a8f1846c3e4311b368a7bdb | [
"MIT"
] | 4 | 2019-10-04T16:11:15.000Z | 2021-08-18T21:00:13.000Z | apps/blockquote/lib/blockquote_web.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 5 | 2020-03-16T23:52:25.000Z | 2021-09-03T16:52:17.000Z | apps/blockquote/lib/blockquote_web.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | null | null | null | defmodule BlockquoteWeb 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 BlockquoteWeb, :controller
use BlockquoteWeb, :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: BlockquoteWeb
import Plug.Conn
import BlockquoteWeb.Router.Helpers
import BlockquoteWeb.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "lib/blockquote_web/templates",
namespace: BlockquoteWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import BlockquoteWeb.Router.Helpers
import BlockquoteWeb.ErrorHelpers
import BlockquoteWeb.Gettext
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
import BlockquoteWeb.Gettext
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 24.073529 | 69 | 0.693341 |
08b4d5e67c852dd95518d6a1068a9118c51b355a | 1,225 | ex | Elixir | lib/jeopardy_web/components/tv/pre_jeopardy/awaiting_start.ex | ryoung786/jeopardy | 5558fc49013c5a22e556a0040cbc116aa8f63912 | [
"MIT"
] | null | null | null | lib/jeopardy_web/components/tv/pre_jeopardy/awaiting_start.ex | ryoung786/jeopardy | 5558fc49013c5a22e556a0040cbc116aa8f63912 | [
"MIT"
] | 32 | 2020-06-08T14:50:46.000Z | 2021-01-01T05:40:44.000Z | lib/jeopardy_web/components/tv/pre_jeopardy/awaiting_start.ex | ryoung786/jeopardy | 5558fc49013c5a22e556a0040cbc116aa8f63912 | [
"MIT"
] | null | null | null | defmodule JeopardyWeb.Components.TV.PreJeopardy.AwaitingStart do
use JeopardyWeb.Components.Base, :tv
alias Jeopardy.GameEngine, as: Engine
@impl true
def handle_event("start_game", _params, socket) do
with :ok <- Engine.event(:start_game, socket.assigns.game.id) do
{:noreply, socket}
else
_ ->
# live flash?
{:noreply, socket}
end
end
@impl true
def handle_event("confirm_remove_player", %{"value" => player_id}, socket) do
with :ok <- Engine.event(:remove_player, String.to_integer(player_id), socket.assigns.game.id) do
{:noreply, assign(socket, modal: false)}
else
_ ->
{:noreply, socket}
end
end
@impl true
def handle_event("maybe_cancel_modal", %{"key" => "Escape"}, socket),
do: {:noreply, assign(socket, modal: false)}
@impl true
def handle_event("maybe_cancel_modal", _, socket), do: {:noreply, socket}
@impl true
def handle_event("cancel_remove_player", _params, socket),
do: {:noreply, assign(socket, modal: false)}
@impl true
def handle_event("remove_player_modal_open", %{"name" => name, "id" => id}, socket),
do: {:noreply, assign(socket, modal: %{player_name: name, player_id: id})}
end
| 29.878049 | 101 | 0.663673 |
08b535f3eaa02e25ae99ec1f6a99a65d78281734 | 863 | exs | Elixir | mix.exs | alice-bot/alice_doge_me | 927bc47f7aa5bdf83eeb8db2ca7c44a91b021e1d | [
"MIT"
] | null | null | null | mix.exs | alice-bot/alice_doge_me | 927bc47f7aa5bdf83eeb8db2ca7c44a91b021e1d | [
"MIT"
] | null | null | null | mix.exs | alice-bot/alice_doge_me | 927bc47f7aa5bdf83eeb8db2ca7c44a91b021e1d | [
"MIT"
] | null | null | null | defmodule AliceDogeMe.Mixfile do
use Mix.Project
def project do
[app: :alice_doge_me,
version: "0.1.1",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description,
package: package,
deps: deps]
end
def application do
[applications: [:logger]]
end
defp deps do
[
{:alice, "~> 0.3"},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
defp description do
"""
This handler will allow Alice to create Doge images with user input.
"""
end
defp package do
[files: ["lib", "config", "mix.exs", "README*"],
maintainers: ["Tyler Clemens"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/alice-bot/alice_doge_me/",
"Docs" => "https://github.com/alice-bot/alice_doge_me/"}]
end
end
| 21.575 | 73 | 0.575898 |
08b53c655af93aa7737ed5d421fd988b1bb72468 | 619 | exs | Elixir | test/my_bot_ex_test/client/slack/reporter_test.exs | KazuCocoa/my_bot_ex | 9d3d71b4340109f35cf6e72b84346a3e609f40a5 | [
"MIT"
] | null | null | null | test/my_bot_ex_test/client/slack/reporter_test.exs | KazuCocoa/my_bot_ex | 9d3d71b4340109f35cf6e72b84346a3e609f40a5 | [
"MIT"
] | null | null | null | test/my_bot_ex_test/client/slack/reporter_test.exs | KazuCocoa/my_bot_ex | 9d3d71b4340109f35cf6e72b84346a3e609f40a5 | [
"MIT"
] | null | null | null | defmodule MyBotExTest.Client.Slack.ReporterTest do
use ExUnit.Case, async: true
alias MyBotEx.Client.Slack.Reporter, as: SlackReporter
test "correct GooglePlay review url" do
review_uel = "https://play.google.com/store/getreviews?id=com.android.chrome&xhr=1&reviewSortOrder=0&reviewType=1&pageNum=0&hl=en"
assert Reporter.GooglePlay.review_url("com.android.chrome") == review_uel
end
test "correct AppStore review url" do
review_uel = "https://itunes.apple.com/en/rss/customerreviews/id=375380948/sortby=mostrecent/json"
assert Reporter.AppStore.rss_json(375380948) == review_uel
end
end
| 38.6875 | 134 | 0.770598 |
08b5acf39fcce0ab6fd6c77c8ae7d9773b25763f | 1,018 | ex | Elixir | lib/files/save_url.ex | ijunaid8989/elixir_dropbox | c726a16fe38372d1199bd146849512ed829f5ed8 | [
"MIT"
] | null | null | null | lib/files/save_url.ex | ijunaid8989/elixir_dropbox | c726a16fe38372d1199bd146849512ed829f5ed8 | [
"MIT"
] | null | null | null | lib/files/save_url.ex | ijunaid8989/elixir_dropbox | c726a16fe38372d1199bd146849512ed829f5ed8 | [
"MIT"
] | null | null | null | defmodule ElixirDropbox.Files.SaveUrl do
@moduledoc """
"""
import ElixirDropbox
@doc """
Save a specified URL into a file in user's Dropbox.
## Example
ElixirDropbox.Files.SaveUrl.save_url(client, "/a.txt", "http://example.com/a.txt")
More info at: https://www.dropbox.com/developers/documentation/http/documentation#files-save_url
"""
def save_url(client, path, url) do
body = %{"path" => path, "url" => url}
result = to_string(Poison.Encoder.encode(body, []))
post(client, "/files/save_url", result)
end
@doc """
Check the status of a save_url job.
## Example
ElixirDropbox.Files.SaveUrl.check_job_status(client, "34g93hh34h04y384084")
More info at: https://www.dropbox.com/developers/documentation/http/documentation#files-save_url
"""
def check_job_status(client, async_job_id) do
body = %{"async_job_id" => async_job_id}
result = to_string(Poison.Encoder.encode(body, []))
post(client, "/files/save_url/check_job_status", result)
end
end
| 28.277778 | 98 | 0.698428 |
08b5b32e970f14d6c9549bb1f1e070fbf1e32fae | 3,718 | exs | Elixir | mix.exs | mattjg908/custom_rpi4 | 3824f85a3fc3d18730c2aafa104136fde40f3487 | [
"Apache-2.0"
] | null | null | null | mix.exs | mattjg908/custom_rpi4 | 3824f85a3fc3d18730c2aafa104136fde40f3487 | [
"Apache-2.0"
] | null | null | null | mix.exs | mattjg908/custom_rpi4 | 3824f85a3fc3d18730c2aafa104136fde40f3487 | [
"Apache-2.0"
] | null | null | null | defmodule CustomRpi4.MixProject do
use Mix.Project
#@github_organization "nerves-project"
@github_organization "mattjg908"
#@app :nerves_system_rpi4
@app :custom_rpi4
@source_url "https://github.com/#{@github_organization}/#{@app}"
@version Path.join(__DIR__, "VERSION")
|> File.read!()
|> String.trim()
def project do
[
app: @app,
version: @version,
elixir: "~> 1.6",
compilers: Mix.compilers() ++ [:nerves_package],
nerves_package: nerves_package(),
description: description(),
package: package(),
deps: deps(),
aliases: [loadconfig: [&bootstrap/1], docs: ["docs", ©_images/1]],
docs: docs(),
preferred_cli_env: %{
docs: :docs,
"hex.build": :docs,
"hex.publish": :docs
}
]
end
def application do
[]
end
defp bootstrap(args) do
set_target()
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
defp nerves_package do
[
type: :system,
artifact_sites: [
{:github_releases, "#{@github_organization}/#{@app}"}
],
build_runner_opts: build_runner_opts(),
platform: Nerves.System.BR,
platform_config: [
defconfig: "nerves_defconfig"
],
# The :env key is an optional experimental feature for adding environment
# variables to the crosscompile environment. These are intended for
# llvm-based tooling that may need more precise processor information.
env: [
{"TARGET_ARCH", "aarch64"},
{"TARGET_CPU", "cortex_a72"},
{"TARGET_OS", "linux"},
{"TARGET_ABI", "gnu"},
{"TARGET_GCC_FLAGS",
"-mabi=lp64 -fstack-protector-strong -mcpu=cortex-a72 -fPIE -pie -Wl,-z,now -Wl,-z,relro"}
],
checksum: package_files()
]
end
defp deps do
[
{:nerves, "~> 1.5.4 or ~> 1.6.0 or ~> 1.7.15", runtime: false},
{:nerves_system_br, "1.18.4", runtime: false},
{:nerves_toolchain_aarch64_nerves_linux_gnu, "~> 1.5.0", runtime: false},
{:nerves_system_linter, "~> 0.4", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.22", only: :docs, runtime: false}
]
end
defp description do
"""
Nerves System - Raspberry Pi 4
"""
end
defp docs do
[
extras: ["README.md", "CHANGELOG.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: ["Apache-2.0"],
links: %{"GitHub" => @source_url}
]
end
defp package_files do
[
"fwup_include",
"rootfs_overlay",
"CHANGELOG.md",
"cmdline.txt",
"config.txt",
"fwup-revert.conf",
"fwup.conf",
"LICENSE",
"linux-5.10.defconfig",
"mix.exs",
"nerves_defconfig",
"post-build.sh",
"post-createfs.sh",
"ramoops.dts",
"README.md",
"VERSION"
]
end
# Copy the images referenced by docs, since ex_doc doesn't do this.
defp copy_images(_) do
File.cp_r("assets", "doc/assets")
end
defp build_runner_opts() do
# Download source files first to get download errors right away.
[make_args: primary_site() ++ ["source", "all", "legal-info"]]
end
defp primary_site() do
case System.get_env("BR2_PRIMARY_SITE") do
nil -> []
primary_site -> ["BR2_PRIMARY_SITE=#{primary_site}"]
end
end
defp set_target() do
if function_exported?(Mix, :target, 1) do
apply(Mix, :target, [:target])
else
System.put_env("MIX_TARGET", "target")
end
end
end
| 24.95302 | 99 | 0.589564 |
08b5b81807fef5d6c0c88d3af6391cb7e30af9f9 | 1,188 | ex | Elixir | lib/game_engine.ex | NikitaNaumenko/brain_games_elixir | 25ef3898164846faab5813096804661734d54af8 | [
"MIT"
] | null | null | null | lib/game_engine.ex | NikitaNaumenko/brain_games_elixir | 25ef3898164846faab5813096804661734d54af8 | [
"MIT"
] | null | null | null | lib/game_engine.ex | NikitaNaumenko/brain_games_elixir | 25ef3898164846faab5813096804661734d54af8 | [
"MIT"
] | null | null | null | defmodule BrainGames.GameEngine do
@moduledoc """
Main game engine which run, a chosen game
"""
alias BrainGames.Games.{Even, Calc, Gcd, Progression, Prime}
@games %{"1" => Even, "2" => Calc, "3" => Gcd, "4" => Progression, "5" => Prime}
@rounds_count 3
@spec play(game_number :: String.t(), user :: String.t()) :: :ok
def play(game_number, user) do
game = @games[game_number]
play_round(game, user, @rounds_count)
end
@spec play_round(game :: module(), user :: String.t(), rounds_count :: integer()) :: :ok
def play_round(game, user, rounds_count) when rounds_count > 0 do
game_data = game.generate_game_data()
task = game.get_task()
question = game_data["question"]
answer = game_data["answer"]
IO.puts(task)
IO.puts("Question: #{question}")
user_answer = ExPrompt.string("Your answer? \n")
if answer != user_answer do
IO.puts("#{user_answer} is wrong answer ;( Correct answer was #{answer}\n")
IO.puts("Let's try again #{user}\n")
else
IO.puts("Correct!\n")
play_round(game, user, rounds_count - 1)
end
end
def play_round(_, user, _), do: IO.puts("Congratulations, #{user}\n")
end
| 31.263158 | 90 | 0.637205 |
08b5c63b881362803238d9edc97870f725ca20ff | 2,779 | exs | Elixir | exercises/concept/rpg-character-sheet/test/rpg/character_sheet_test.exs | SaschaMann/elixir | 2489747bba72a0ba5efa27e7e00441a428fdf987 | [
"MIT"
] | 1 | 2021-06-09T06:57:02.000Z | 2021-06-09T06:57:02.000Z | exercises/concept/rpg-character-sheet/test/rpg/character_sheet_test.exs | SaschaMann/elixir | 2489747bba72a0ba5efa27e7e00441a428fdf987 | [
"MIT"
] | 6 | 2022-03-04T13:05:25.000Z | 2022-03-30T18:36:49.000Z | exercises/concept/rpg-character-sheet/test/rpg/character_sheet_test.exs | SaschaMann/elixir | 2489747bba72a0ba5efa27e7e00441a428fdf987 | [
"MIT"
] | null | null | null | defmodule RPG.CharacterSheetTest do
use ExUnit.Case
import ExUnit.CaptureIO
describe "welcome/0" do
@task_id 1
test "it prints a welcome message" do
io =
capture_io(fn ->
assert RPG.CharacterSheet.welcome() == :ok
end)
assert io == "Welcome! Let's fill out your character sheet together.\n"
end
end
describe "ask_name/0" do
@task_id 2
test "it prints a prompt" do
io =
capture_io("\n", fn ->
RPG.CharacterSheet.ask_name()
end)
assert io == "What is your character's name?\n"
end
@task_id 2
test "returns the trimmed input" do
capture_io("Maxwell The Great\n", fn ->
assert RPG.CharacterSheet.ask_name() == "Maxwell The Great"
end)
end
end
describe "ask_class/0" do
@task_id 3
test "it prints a prompt" do
io =
capture_io("\n", fn ->
RPG.CharacterSheet.ask_class()
end)
assert io == "What is your character's class?\n"
end
@task_id 3
test "returns the trimmed input" do
capture_io("rogue\n", fn ->
assert RPG.CharacterSheet.ask_class() == "rogue"
end)
end
end
describe "ask_level/0" do
@task_id 4
test "it prints a prompt" do
io =
capture_io("1\n", fn ->
RPG.CharacterSheet.ask_level()
end)
assert io == "What is your character's level?\n"
end
@task_id 4
test "returns the trimmed input as an integer" do
capture_io("3\n", fn ->
assert RPG.CharacterSheet.ask_level() == 3
end)
end
end
describe "run/0" do
@task_id 5
test "it asks for name, class, and level" do
io =
capture_io("Susan The Fearless\nfighter\n6\n", fn ->
RPG.CharacterSheet.run()
end)
assert io =~ """
Welcome! Let's fill out your character sheet together.
What is your character's name?
What is your character's class?
What is your character's level?
"""
end
@task_id 5
test "it returns a character map" do
capture_io("The Stranger\nrogue\n2\n", fn ->
assert RPG.CharacterSheet.run() == %{
name: "The Stranger",
class: "rogue",
level: 2
}
end)
end
@task_id 5
test "it inspects the character map" do
io =
capture_io("Anne\nhealer\n4\n", fn ->
RPG.CharacterSheet.run()
end)
assert io =~
inspect(
%{
name: "Anne",
class: "healer",
level: 4
},
label: "Your character"
)
end
end
end
| 23.158333 | 77 | 0.530407 |
08b5ceb7260314f19486ce132e3f1400e52f1c17 | 7,478 | ex | Elixir | lib/fika/compiler/parser/helper.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/helper.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/helper.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.Helper do
import NimbleParsec
alias Fika.Compiler.TypeChecker.Types, as: T
@keywords ~w(fn do if else end case)
def to_ast(c, kind) do
c
|> line()
|> byte_offset()
|> map({__MODULE__, :put_line_offset, []})
|> post_traverse({__MODULE__, :post_traverse, [kind]})
end
def post_traverse(_, [result], context, _, _, kind) do
case kind do
kind when kind in [:remote_function_call, :function_ref] ->
case do_to_ast(result, context, kind) do
{:error, _} = error ->
error
result ->
{[result], context}
end
:identifier ->
{[str], _} = result
if str in @keywords do
{:error, "Identifier cannot be one of #{inspect(@keywords)}"}
else
{[do_to_ast(result, kind)], context}
end
_ ->
{[do_to_ast(result, kind)], context}
end
end
def put_line_offset({[{result, {line, line_start_offset}}], string_offset}) do
{result, {line, line_start_offset, string_offset}}
end
def do_to_ast({[value], line}, :integer) do
{:integer, line, value}
end
def do_to_ast({[value], line}, :boolean) do
{:boolean, line, value == "true"}
end
def do_to_ast({[condition, true_block, false_block], line}, :exp_if_else) do
{{:if, line}, condition, true_block, false_block}
end
def do_to_ast({[exp, clauses], line}, :exp_case) do
{{:case, line}, exp, clauses}
end
def do_to_ast({[args, exps], line}, :anonymous_function) do
{:anonymous_function, line, args, exps}
end
def do_to_ast({[left, bin_op, right | rest], line}, :exp_bin_op)
when bin_op in ["+", "-", "*", "/", "|", "&", "<", ">", "<=", ">=", "==", "!="] do
new_left = {:call, {String.to_atom(bin_op), line}, [left, right], "fika/kernel"}
do_to_ast({[new_left | rest], line}, :exp_bin_op)
end
def do_to_ast({[result], _line}, :exp_bin_op) do
result
end
def do_to_ast({[unary_op, exp], line}, :unary_op)
when unary_op in ["!", "-"] do
{:call, {String.to_atom(unary_op), line}, [exp], "fika/kernel"}
end
def do_to_ast({[name], line}, :identifier) do
{:identifier, line, String.to_atom(name)}
end
def do_to_ast({[name], line}, :module_name) do
{:module_name, line, name}
end
def do_to_ast({[name, args, type, exps], line}, :public_function_def) do
{:identifier, _, name} = name
{:function, [position: line], {name, args, type, exps}}
end
def do_to_ast(
{[name, args, type, ext_module, ext_function, arg_names], line},
:ext_function_def
) do
{:identifier, _, name} = name
{:type, _, ext_type} = type
call = {:ext_call, line, {ext_module, ext_function, arg_names, ext_type}}
{:function, [position: line], {name, args, type, [call]}}
end
def do_to_ast({[], line}, :return_type) do
{:type, line, nil}
end
def do_to_ast({[type], _line}, :return_type) do
type
end
def do_to_ast({[{_, _, inner_type}], _line}, :list_type) when is_struct(inner_type) do
%T.List{type: inner_type}
end
def do_to_ast({[inner_type], _line}, :list_type) do
%T.List{type: inner_type}
end
def do_to_ast({[{_, _, inner_type}], _line}, :effect_type) when is_struct(inner_type) do
%T.Effect{type: inner_type}
end
def do_to_ast({[inner_type], _line}, :effect_type) do
%T.Effect{type: inner_type}
end
def do_to_ast({inner_types, _line}, :tuple_type) do
%T.Tuple{elements: inner_types}
end
def do_to_ast({[key_type, value_type], _line}, :map_type) do
%T.Map{key_type: key_type, value_type: value_type}
end
def do_to_ast({[key, value], _line}, :record_field) do
{String.to_atom(key), value}
end
def do_to_ast({fields, _line}, :record_type) do
%T.Record{fields: Enum.sort_by(fields, &elem(&1, 0))}
end
def do_to_ast({[{:atom, _, atom}], _line}, :atom_type) do
atom
end
def do_to_ast({types, _line}, :function_type) do
arg_types = types |> Keyword.take([:arg_type]) |> Keyword.values()
return_type = Keyword.get(types, :return_type)
%T.FunctionRef{arg_types: arg_types, return_type: return_type}
end
def do_to_ast({types, _line}, :union_type) do
T.Union.new(types)
end
def do_to_ast({[{_, _, type}], line}, :type) when is_struct(type) do
{:type, line, type}
end
def do_to_ast({[type], line}, :type) do
{:type, line, type}
end
def do_to_ast({[identifier, type], _line}, :arg) do
{identifier, type}
end
def do_to_ast({[name, args], line}, :local_function_call) do
{:identifier, _, name} = name
{:call, {name, line}, args, nil}
end
def do_to_ast({val, line}, :function_ref_call) do
case val do
[exp, args] ->
{:call, {exp, line}, args}
[val] ->
val
end
end
def do_to_ast({[identifier, exp], line}, :exp_match) do
{{:=, line}, identifier, exp}
end
def do_to_ast({value, line}, :string) do
str =
value
|> Enum.chunk_by(&is_tuple/1)
|> Enum.flat_map(fn
[h | _tail] = interpolations when is_tuple(h) -> interpolations
charlist -> [to_string(charlist)]
end)
{:string, line, str}
end
def do_to_ast({result, line}, :exp_list) do
{:list, line, result}
end
def do_to_ast({result, line}, :tuple) do
{:tuple, line, result}
end
def do_to_ast({key_values, line}, :map) do
{:map, line, key_values}
end
def do_to_ast({[k, v], _line}, :key_value) do
{k, v}
end
def do_to_ast({[name | key_values], line}, :record) do
name =
case name do
[] -> nil
[name] -> name
end
{:record, line, name, key_values}
end
def do_to_ast({[{:identifier, line, value}], line}, :atom) when value in [true, false] do
{:boolean, line, value}
end
def do_to_ast({[{:identifier, line, value}], line}, :atom) do
{:atom, line, value}
end
def do_to_ast({[value], line}, :use_module) do
{value, line}
end
def do_to_ast({str, _line}, :ext_atom) do
List.to_atom(str)
end
def do_to_ast({ast, line}, context, :function_ref) do
case ast do
[[], function, arg_types] ->
{:function_ref, line, {nil, value_from_identifier(function), arg_types}}
[[module_alias], function, arg_types] ->
if module = expand_module(module_alias, context) do
{:function_ref, line,
{value_from_identifier(module), value_from_identifier(function), arg_types}}
else
{:module_name, _line, module_name} = module_alias
{:error, "Unknown module #{module_name}"}
end
end
end
def do_to_ast({[module_alias, name, args], line}, context, :remote_function_call) do
if module = expand_module(module_alias, context) do
{:identifier, _, module} = module
{:identifier, _, name} = name
{:call, {name, line}, args, module}
else
{:module_name, _line, module_name} = module_alias
{:error, "Unknown module #{module_name}"}
end
end
defp value_from_identifier({:identifier, _line, value}) do
value
end
def to_atom([value]), do: String.to_atom(value)
def tag(value, tag) do
{tag, value}
end
defp expand_module({:module_name, line, module}, context) do
fika_modules = ["kernel", "io", "list"]
module =
if module in fika_modules do
"fika/#{module}"
else
context[module]
end
module && {:identifier, line, module}
end
end
| 25.435374 | 91 | 0.611661 |
08b5d4e000b4500508ac93e8572125452f6b9d6e | 1,791 | ex | Elixir | clients/file/lib/google_api/file/v1/model/schedule.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/file/lib/google_api/file/v1/model/schedule.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/file/lib/google_api/file/v1/model/schedule.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.File.V1.Model.Schedule do
@moduledoc """
Configure the schedule.
## Attributes
* `day` (*type:* `String.t`, *default:* `nil`) - Allows to define schedule that runs specified day of the week.
* `duration` (*type:* `String.t`, *default:* `nil`) - Output only. Duration of the time window, set by service producer.
* `startTime` (*type:* `GoogleApi.File.V1.Model.TimeOfDay.t`, *default:* `nil`) - Time within the window to start the operations.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:day => String.t(),
:duration => String.t(),
:startTime => GoogleApi.File.V1.Model.TimeOfDay.t()
}
field(:day)
field(:duration)
field(:startTime, as: GoogleApi.File.V1.Model.TimeOfDay)
end
defimpl Poison.Decoder, for: GoogleApi.File.V1.Model.Schedule do
def decode(value, options) do
GoogleApi.File.V1.Model.Schedule.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.File.V1.Model.Schedule do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.792453 | 133 | 0.708543 |
08b5d6471329625e099e79462356aa72ff12dc16 | 616 | exs | Elixir | test/makeup/lexers/elixir_lexer/registry_test.exs | davydog187/makeup_elixir | 462b0edd8b7ec878202587c6506ae1fe029aaca9 | [
"BSD-2-Clause"
] | 14 | 2018-07-11T17:37:33.000Z | 2020-08-03T15:22:45.000Z | test/makeup/lexers/elixir_lexer/registry_test.exs | davydog187/makeup_elixir | 462b0edd8b7ec878202587c6506ae1fe029aaca9 | [
"BSD-2-Clause"
] | 14 | 2020-09-29T17:22:28.000Z | 2022-02-08T12:50:28.000Z | test/makeup/lexers/elixir_lexer/registry_test.exs | davydog187/makeup_elixir | 462b0edd8b7ec878202587c6506ae1fe029aaca9 | [
"BSD-2-Clause"
] | 9 | 2018-07-11T14:42:30.000Z | 2020-04-23T09:06:01.000Z | defmodule Makeup.Lexers.ElixirLexer.RegistryTest do
use ExUnit.Case, async: true
alias Makeup.Registry
alias Makeup.Lexers.ElixirLexer
describe "the elixir lexer has successfully registered itself:" do
test "language name" do
assert {:ok, {ElixirLexer, []}} == Registry.fetch_lexer_by_name("elixir")
assert {:ok, {ElixirLexer, []}} == Registry.fetch_lexer_by_name("iex")
end
test "file extension" do
assert {:ok, {ElixirLexer, []}} == Registry.fetch_lexer_by_extension("exs")
assert {:ok, {ElixirLexer, []}} == Registry.fetch_lexer_by_extension("ex")
end
end
end
| 32.421053 | 81 | 0.693182 |
08b606abef96a67cd4743f3a53f552a91a04cc1e | 2,539 | exs | Elixir | test_fixtures/precompiled/good-posts.exs | nallwhy/Serum | ed9f51a83e328789ccfca18d2a0397b45ac4be0f | [
"MIT"
] | null | null | null | test_fixtures/precompiled/good-posts.exs | nallwhy/Serum | ed9f51a83e328789ccfca18d2a0397b45ac4be0f | [
"MIT"
] | null | null | null | test_fixtures/precompiled/good-posts.exs | nallwhy/Serum | ed9f51a83e328789ccfca18d2a0397b45ac4be0f | [
"MIT"
] | null | null | null | [%{__struct__: Serum.Post, date: "2019-01-01", file: %{__struct__: Serum.File, src: "/home/dalgona/repo/Serum/priv/fixtures/posts/good-post.md"}, html: "<h1>Hello, world!</h1>\n<p>The quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog.</p>\n", output: "/dest/home/dalgona/repo/Serum/priv/fixtures/posts/good-post.html", preview: "Hello, world! The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qu…", raw_date: {{2019, 1, 1}, {12, 34, 56}}, tags: [%{__struct__: Serum.Tag, list_url: "/test-site/tags/tag1", name: "tag1"}, %{__struct__: Serum.Tag, list_url: "/test-site/tags/tag2", name: "tag2"}], template: nil, title: "Test Post", url: "/test-site/home/dalgona/repo/Serum/priv/fixtures/posts/good-post.html"}, %{__struct__: Serum.Post, date: "2019-01-01", file: %{__struct__: Serum.File, src: "/home/dalgona/repo/Serum/priv/fixtures/posts/good-minimal-header.md"}, html: "<h1>Hello, world!</h1>\n<p>The quick brown fox jumps over the lazy dog.</p>\n", output: "/dest/home/dalgona/repo/Serum/priv/fixtures/posts/good-minimal-header.html", preview: "Hello, world! The quick brown fox jumps over the lazy dog.", raw_date: {{2019, 1, 1}, {0, 0, 0}}, tags: [], template: nil, title: "Test Post", url: "/test-site/home/dalgona/repo/Serum/priv/fixtures/posts/good-minimal-header.html"}, %{__struct__: Serum.Post, date: "2019-01-01", file: %{__struct__: Serum.File, src: "/home/dalgona/repo/Serum/priv/fixtures/posts/good-alternative-date.md"}, html: "<h1>Hello, world!</h1>\n<p>The quick brown fox jumps over the lazy dog.</p>\n", output: "/dest/home/dalgona/repo/Serum/priv/fixtures/posts/good-alternative-date.html", preview: "Hello, world! The quick brown fox jumps over the lazy dog.", raw_date: {{2019, 1, 1}, {0, 0, 0}}, tags: [%{__struct__: Serum.Tag, list_url: "/test-site/tags/tag3", name: "tag3"}, %{__struct__: Serum.Tag, list_url: "/test-site/tags/tag4", name: "tag4"}], template: nil, title: "Test Post", url: "/test-site/home/dalgona/repo/Serum/priv/fixtures/posts/good-alternative-date.html"}]
| 1,269.5 | 2,538 | 0.719968 |
08b606e377e55d25a1db27029fa9ff8406e4bd08 | 475 | ex | Elixir | lib/flip.ex | kdisneur/flip | 78b8f4a36ecd23ddce3e4fc5b16f81da48737a2b | [
"MIT"
] | null | null | null | lib/flip.ex | kdisneur/flip | 78b8f4a36ecd23ddce3e4fc5b16f81da48737a2b | [
"MIT"
] | null | null | null | lib/flip.ex | kdisneur/flip | 78b8f4a36ecd23ddce3e4fc5b16f81da48737a2b | [
"MIT"
] | null | null | null | defmodule Flip do
@doc """
Flip the first and second parameter when calling a method. The second
parameter needs to be an array. The last one is the method which is
going to be called.
## Examples
iex> 2 |> Flip.flip([10], &Kernel.-/2)
8
iex> 2 |> Flip.flip([10, 3], fn (x1, x2, x3) -> (x1 - x2) * x3 end)
24
"""
def flip(parameter_2, [parameter_1|other_parameters], method) do
apply(method, [parameter_1, parameter_2|other_parameters])
end
end
| 26.388889 | 71 | 0.663158 |
08b60f1fe67b93f4b3e412aafe7037dde4d46010 | 537 | exs | Elixir | mix.exs | totorigolo/xain | 54421fb20f8fa4d8576710bbd0d6e804dfefeda7 | [
"MIT"
] | null | null | null | mix.exs | totorigolo/xain | 54421fb20f8fa4d8576710bbd0d6e804dfefeda7 | [
"MIT"
] | null | null | null | mix.exs | totorigolo/xain | 54421fb20f8fa4d8576710bbd0d6e804dfefeda7 | [
"MIT"
] | null | null | null | defmodule Xain.Mixfile do
use Mix.Project
@version "0.6.1"
def project do
[app: :xain,
version: @version,
elixir: "~> 1.0",
package: package(),
deps: [],
description: """
An html DSL package.
"""
]
end
def application do
[applications: [:logger]]
end
defp package do
[ maintainers: ["Stephen Pallen", "Roman Smirnov"],
licenses: ["MIT"],
links: %{ "Github" => "https://github.com/smpallen99/xain"},
files: ~w(lib README.md mix.exs LICENSE)]
end
end
| 18.517241 | 66 | 0.569832 |
08b647a303dc545b8a191940d286be0372e557cb | 866 | exs | Elixir | app/test/noodl_web/live/experiences/show/show_test.exs | nathanjohnson320/noodl | 2e449aab15b54fc5a1dc45ebf4b79e7b64b7c967 | [
"MIT"
] | 1 | 2021-01-20T20:00:50.000Z | 2021-01-20T20:00:50.000Z | app/test/noodl_web/live/experiences/show/show_test.exs | nathanjohnson320/noodl | 2e449aab15b54fc5a1dc45ebf4b79e7b64b7c967 | [
"MIT"
] | null | null | null | app/test/noodl_web/live/experiences/show/show_test.exs | nathanjohnson320/noodl | 2e449aab15b54fc5a1dc45ebf4b79e7b64b7c967 | [
"MIT"
] | null | null | null | defmodule NoodlWeb.LiveEventsShow do
use NoodlWeb.ConnCase
import Noodl.Factory
describe "Logged In" do
test "renders an event" do
conn = session_conn()
user = insert(:user)
conn = conn |> put_session(:user, user.id)
event = insert(:event, creator: user)
conn =
conn
|> get(
Routes.events_show_path(
conn,
:show,
event.slug
)
)
assert html_response(conn, :ok)
end
end
describe "Not Logged In" do
test "renders an event" do
conn = session_conn()
event = insert(:event, creator: insert(:user))
conn =
conn
|> get(
Routes.events_show_path(
conn,
:show,
event.slug
)
)
assert html_response(conn, :ok)
end
end
end
| 18.041667 | 52 | 0.518476 |
08b68902fcd06bfae1ce8d0fc50925e182afde6a | 3,547 | ex | Elixir | lib/ecto_list.ex | popo63301/ecto_list | adce0006617f2e88aedcf4e493b642b41b227b5a | [
"MIT"
] | 18 | 2019-07-18T09:11:27.000Z | 2020-08-07T11:01:22.000Z | lib/ecto_list.ex | popo63301/ecto_list | adce0006617f2e88aedcf4e493b642b41b227b5a | [
"MIT"
] | null | null | null | lib/ecto_list.ex | popo63301/ecto_list | adce0006617f2e88aedcf4e493b642b41b227b5a | [
"MIT"
] | null | null | null | defmodule EctoList do
@moduledoc """
Implements conveniences to handle the items order of a list.
"""
@doc """
Returns the list of items ordered according to the items_order list.
If ids are missing in items_order, the items will be ordered according to their inserted date.
## Examples
all_items = [%{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]},
%{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]},
%{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]},
%{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]},
%{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}]
items_order = [5, 3, 1]
ordered_items_list(all_items, items_order)
# [%{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]},
# %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]},
# %{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]},
# %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]},
# %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}]
"""
def ordered_items_list(items, items_order \\ []) do
complete_items_order = complete_items_order(items, items_order)
search_function = fn x -> Enum.find(items, fn item -> item.id == x end) end
Enum.map(complete_items_order, search_function)
|> Enum.filter(&(!is_nil(&1)))
end
@doc """
Returns the list of ids composed of the current list order + all the missings ids ordered by insertion date.
## Examples
all_items = [%{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]},
%{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]},
%{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]},
%{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]},
%{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}]
items_order = [5, 3, 1]
complete_items_order(all_items, items_order)
# [5, 3, 1, 2, 4]
"""
def complete_items_order(items, nil), do: complete_items_order(items, [])
def complete_items_order(items, items_order) do
missing_ids_list = missing_ids_list(items, items_order)
items_order ++ missing_ids_list
end
@doc """
Same as `missing_ids_list/2` but returns all ids ordered by insertion date.
"""
def missing_ids_list(all_items), do: missing_ids_list(all_items, [])
@doc """
Returns the list of missing ids ordered by insertion date.
## Examples
all_items = [%{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]},
%{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]},
%{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]},
%{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]},
%{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}]
items_order = [5, 3, 1]
missing_ids_list(all_items, items_order)
# [2, 4]
"""
def missing_ids_list(all_items, nil), do: missing_ids_list(all_items, [])
def missing_ids_list(all_items, items_order) do
all_items
|> sorted_items_by_inserted_date
|> Enum.reduce([], fn x, acc ->
if !Enum.member?(items_order ++ acc, x.id) do
acc ++ [x.id]
else
acc
end
end)
end
defp sorted_items_by_inserted_date(items) do
items
|> Enum.sort(&(NaiveDateTime.compare(&1.inserted_at, &2.inserted_at) == :lt))
end
end
| 33.780952 | 110 | 0.610093 |
08b6a45b60ea8e569a313f5ed49729bf45372c07 | 150 | exs | Elixir | elixir-class/advanced/executables/test/executables_test.exs | ikhlas-firlana/learning-class | 58c2db1e8121eaec47190105dffa47d6db84bb55 | [
"Apache-2.0"
] | null | null | null | elixir-class/advanced/executables/test/executables_test.exs | ikhlas-firlana/learning-class | 58c2db1e8121eaec47190105dffa47d6db84bb55 | [
"Apache-2.0"
] | null | null | null | elixir-class/advanced/executables/test/executables_test.exs | ikhlas-firlana/learning-class | 58c2db1e8121eaec47190105dffa47d6db84bb55 | [
"Apache-2.0"
] | null | null | null | defmodule ExecutablesTest do
use ExUnit.Case
doctest Executables
test "greets the world" do
assert Executables.hello() == :world
end
end
| 16.666667 | 40 | 0.733333 |
08b711478caa5c93d7565df00c00cc95348f7634 | 2,614 | ex | Elixir | lib/api/dev_tools.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | 1 | 2020-02-09T23:04:33.000Z | 2020-02-09T23:04:33.000Z | lib/api/dev_tools.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | null | null | null | lib/api/dev_tools.ex | JediLuke/franklin | 8eb77a342547de3eb43d28dcf9f835ff443ad489 | [
"Apache-2.0"
] | null | null | null | defmodule DevTools do
# require Logger
# def widget_workbench do
# Logger.debug "#{__MODULE__} opening the WidgetWorkbench..."
# Flamelex.Fluxus.action({Flamelex.Fluxus.Reducers.DevTools, :open_widget_workbench})
# end
def refresh_menubar do
radix_state = Flamelex.Fluxus.RadixStore.get()
_res = send Flamelex.GUI.Component.MenuBar, {:radix_state_change, radix_state}
:ok
end
end
# defmodule Flamelex.API.Mode do
# @moduledoc """
# Gives a user full control over all things related to the input mode
# of the GUI.
# ## A short note on `modes`
# There are several famous & intelligent engineers who are strongly opposed
# to the concept of modes - and I respect their opinion; it is not without
# merit. Modes are complicated and unintuitive to the user. They require
# training and practice to use effectively - when that is achieved though,
# it has been my experience in using vim at least, that a very satisfying,
# intuitive (or perhaps just, performed in the "back of my mind", not the
# same part that likes to think about what I'm programming), efficient &
# economical form of Human-Computer interaction. So yeah, I think if people
# want to maximize their bandwidth when interacting with computers, I think
# it's worth learning a modal editor.
# In a future life, when we're all Start Fleet officers, we can continue
# the discussion, about whether or not modes would be a good/bad idea in
# LCARS.
# In Flamelex, I treat modes as a strictly user-input side concern. The
# mode changes what happens when you press the buttons. It changes how
# some things are rendered. However, nothing "internal" to Flamelex ever
# changes. There is no concept of a mode in the `Buffer` API, for example.
# Changing the mode, doesn't affect the result of any of those underlying
# functions, there is no internal state in that part of the application
# which understands modes.
# Right now, modes are global. Insert mode will put the active Buffer, into
# insert mode. It might be prudent at some point to scope modes to active
# (or not?) Buffers/Windows.
# """
# use Flamelex.ProjectAliases
# @doc """
# Returns the current input mode.
# """
# def current_mode do
# radix = GenServer.call(Flamelex.FluxusRadix, :get_state)
# radix.mode
# end
# def switch_mode(m) do
# Flamelex.FluxusRadix
# |> GenServer.cast({:action, {:switch_mode, m}})
# end
# end
| 39.014925 | 93 | 0.680566 |
08b7182479f71b7026e4c405dcdda6c59163dac6 | 7,372 | ex | Elixir | test/support/v3/services/test_pool/test_worker_entity.ex | noizu-labs/SimplePoolAdvanced | 9555071e42917d280c7ce4846c19ef208c77f14e | [
"MIT"
] | null | null | null | test/support/v3/services/test_pool/test_worker_entity.ex | noizu-labs/SimplePoolAdvanced | 9555071e42917d280c7ce4846c19ef208c77f14e | [
"MIT"
] | null | null | null | test/support/v3/services/test_pool/test_worker_entity.ex | noizu-labs/SimplePoolAdvanced | 9555071e42917d280c7ce4846c19ef208c77f14e | [
"MIT"
] | null | null | null | #-------------------------------------------------------------------------------
# Author: Keith Brings
# Copyright (C) 2022 Noizu Labs, Inc. All rights reserved.
#-------------------------------------------------------------------------------
defmodule Noizu.AdvancedPool.Support.TestV3Worker do
use Noizu.AdvancedPool.ServiceWorker
@vsn 1.0
@sref "noizu-test"
defmodule Entity do
@pool Noizu.AdvancedPool.Support.TestV3Pool
Noizu.AdvancedPool.ServiceWorker.service_worker_entity() do
identifier :string
public_field :data, %{}
end
def supervisor_hint(ref) do
id = id(ref)
cond do
is_integer(id) -> id
is_bitstring(id) ->
"test_" <> ts = id
String.to_integer(ts)
end
end
#-----------------------------------------------------------------------------
# Behaviour
#-----------------------------------------------------------------------------
def load(ref), do: load(ref, nil, nil)
def load(ref, context), do: load(ref, nil, context)
def load(ref, _options, _context) do
%__MODULE__{
identifier: id(ref)
}
end
#-----------------------------------------------------------------------------
# Implementation
#-----------------------------------------------------------------------------
def test_s_call!(this, value, _context) do
state = put_in(this, [Access.key(:data), :s_call!], value)
{:reply, :s_call!, state}
end
def test_s_call(this, value, _context), do: {:reply, :s_call, put_in(this, [Access.key(:data), :s_call], value)}
def test_s_cast!(this, value, _context), do: {:noreply, put_in(this, [Access.key(:data), :s_cast!], value)}
def test_s_cast(this, value, _context) do
updated_state = put_in(this, [Access.key(:data), :s_cast], value)
{:noreply, updated_state}
end
#-----------------------------------------------------------------------------
# call_forwarding
#-----------------------------------------------------------------------------
#------------------------------------------------------------------------
# call router
#------------------------------------------------------------------------
def __handle_call__({:spawn, envelope}, from, state), do: __handle_call__(envelope, from, state)
def __handle_call__({:passive, envelope}, from, state), do: __handle_call__(envelope, from, state)
def __handle_call__({:s, {:test_s_call!, value}, context}, _from, state), do: test_s_call!(state, value, context)
def __handle_call__({:s, {:test_s_call, value}, context}, _from, state), do: test_s_call(state, value, context)
def __handle_call__(call, from, state), do: super(call, from, state)
def __handle_cast__({:spawn, envelope}, state), do: __handle_cast__(envelope, state)
def __handle_cast__({:passive, envelope}, state), do: __handle_cast__(envelope, state)
def __handle_cast__({:s, {:test_s_cast!, value}, context}, state), do: test_s_cast!(state, value, context)
def __handle_cast__({:s, {:test_s_cast, value}, context}, state), do: test_s_cast(state, value, context)
def __handle_cast__(call, state), do: super(call, state)
#-------------------
# id/1
#-------------------
def id({:ref, __MODULE__, identifier}), do: identifier
def id("ref.noizu-test." <> identifier), do: identifier
def id(%__MODULE__{} = entity), do: entity.identifier
#-------------------
# ref/1
#-------------------
def ref(identifier) when is_integer(identifier), do: {:ref, __MODULE__, identifier}
def ref({:ref, __MODULE__, identifier}), do: {:ref, __MODULE__, identifier}
def ref("ref.noizu-test." <> identifier), do: {:ref, __MODULE__, identifier}
def ref(%__MODULE__{} = entity), do: {:ref, __MODULE__, entity.identifier}
#-------------------
# sref/1
#-------------------
def sref({:ref, __MODULE__, identifier}), do: "ref.noizu-test.#{identifier}"
def sref("ref.noizu-test." <> identifier), do: "ref.noizu-test.#{identifier}"
def sref("test_" <> _ = identifier), do: "ref.noizu-test.#{identifier}"
def sref(%__MODULE__{} = entity), do: "ref.noizu-test.#{entity.identifier}"
def sref(_), do: nil
#-------------------
# entity/2
#-------------------
def entity(ref, options \\ %{})
def entity({:ref, __MODULE__, identifier}, _options), do: %__MODULE__{identifier: identifier}
def entity("ref.noizu-test." <> identifier, _options), do: %__MODULE__{identifier: identifier}
def entity(%__MODULE__{} = entity, _options), do: entity
#-------------------
# entity!/2
#-------------------
def entity!(ref, options \\ %{})
def entity!({:ref, __MODULE__, identifier}, _options), do: %__MODULE__{identifier: identifier}
def entity!("ref.noizu-test." <> identifier, _options), do: %__MODULE__{identifier: identifier}
def entity!(%__MODULE__{} = entity, _options), do: entity
#-------------------
# record/2
#-------------------
def record(ref, options \\ %{})
def record({:ref, __MODULE__, identifier}, _options), do: %__MODULE__{identifier: identifier}
def record("ref.noizu-test." <> identifier, _options), do: %__MODULE__{identifier: identifier}
def record(%__MODULE__{} = entity, _options), do: entity
#-------------------
# record!/2
#-------------------
def record!(ref, options \\ %{})
def record!({:ref, __MODULE__, identifier}, _options), do: %__MODULE__{identifier: identifier}
def record!("ref.noizu-test." <> identifier, _options), do: %__MODULE__{identifier: identifier}
def record!(%__MODULE__{} = entity, _options), do: entity
def id_ok(o) do
r = id(o)
r && {:ok, r} || {:error, o}
end
def ref_ok(o) do
r = ref(o)
r && {:ok, r} || {:error, o}
end
def sref_ok(o) do
r = sref(o)
r && {:ok, r} || {:error, o}
end
def entity_ok(o, options \\ %{}) do
r = entity(o, options)
r && {:ok, r} || {:error, o}
end
def entity_ok!(o, options \\ %{}) do
r = entity!(o, options)
r && {:ok, r} || {:error, o}
end
end
defmodule Repo do
Noizu.AdvancedPool.ServiceWorker.service_worker_repo() do
end
end
end # end defmacro
defimpl Noizu.ERP, for: Noizu.AdvancedPool.Support.TestV3Worker.Entity do
def id(obj) do
obj.identifier
end # end sref/1
def ref(obj) do
{:ref, Noizu.AdvancedPool.Support.TestV3Worker.Entity, obj.identifier}
end # end ref/1
def sref(obj) do
"ref.noizu-test.#{obj.identifier}"
end # end sref/1
def record(obj, _options \\ nil) do
obj
end # end record/2
def record!(obj, _options \\ nil) do
obj
end # end record/2
def entity(obj, _options \\ nil) do
obj
end # end entity/2
def entity!(obj, _options \\ nil) do
obj
end # end defimpl EntityReferenceProtocol, for: Tuple
def id_ok(o) do
r = ref(o)
r && {:ok, r} || {:error, o}
end
def ref_ok(o) do
r = ref(o)
r && {:ok, r} || {:error, o}
end
def sref_ok(o) do
r = sref(o)
r && {:ok, r} || {:error, o}
end
def entity_ok(o, options \\ %{}) do
r = entity(o, options)
r && {:ok, r} || {:error, o}
end
def entity_ok!(o, options \\ %{}) do
r = entity!(o, options)
r && {:ok, r} || {:error, o}
end
end | 34.610329 | 117 | 0.530521 |
08b726e6b04f5d6ad71091760992951b9f6bfa75 | 62 | exs | Elixir | config/config.exs | LaudateCorpus1/gen_registry | 74246ae4e4d9b3c330bacc529c9dd32851378446 | [
"MIT"
] | 39 | 2020-04-11T07:21:23.000Z | 2022-02-03T13:17:59.000Z | config/config.exs | LaudateCorpus1/gen_registry | 74246ae4e4d9b3c330bacc529c9dd32851378446 | [
"MIT"
] | 2 | 2019-06-21T17:47:11.000Z | 2019-06-21T19:10:35.000Z | config/config.exs | LaudateCorpus1/gen_registry | 74246ae4e4d9b3c330bacc529c9dd32851378446 | [
"MIT"
] | 7 | 2021-01-19T00:00:10.000Z | 2022-03-17T09:51:10.000Z | use Mix.Config
config :gen_registry,
gen_module: GenServer
| 12.4 | 23 | 0.790323 |
08b72b18e828b83285718aab89a2e998c5883fd6 | 992 | ex | Elixir | lib/api/graphql/mutations/users.ex | nunopolonia/psc-api | 2e358503851cc04cdaa89201a3f56586f8746736 | [
"MIT"
] | 1 | 2017-09-10T23:51:40.000Z | 2017-09-10T23:51:40.000Z | lib/api/graphql/mutations/users.ex | nunopolonia/psc-api | 2e358503851cc04cdaa89201a3f56586f8746736 | [
"MIT"
] | 24 | 2018-03-14T18:17:00.000Z | 2021-03-01T07:47:53.000Z | lib/api/graphql/mutations/users.ex | portosummerofcode/psc-api | 2e358503851cc04cdaa89201a3f56586f8746736 | [
"MIT"
] | null | null | null | defmodule Api.GraphQL.Mutations.Users do
use Absinthe.Schema.Notation
use Absinthe.Relay.Schema.Notation, :modern
alias Api.GraphQL.Middleware.{RequireAdmin}
alias Api.Accounts
object :users_mutations do
@desc "Makes a user admin (admin only)"
field :make_admin, :user do
arg :id, non_null(:string)
middleware RequireAdmin
resolve fn %{id: id}, _info ->
Accounts.update_any_user(id, %{role: "admin"})
end
end
@desc "Makes a user participant (admin only)"
field :make_participant, :user do
arg :id, non_null(:string)
middleware RequireAdmin
resolve fn %{id: id}, _info ->
Accounts.update_any_user(id, %{role: "participant"})
end
end
@desc "Removes a user (admin only)"
field :remove_user, :string do
arg :id, non_null(:string)
middleware RequireAdmin
resolve fn %{id: id}, _info ->
Accounts.delete_any_user(id)
id
end
end
end
end
| 22.044444 | 60 | 0.638105 |
08b72ec290bddd8de135d113b76caf6d209513a9 | 625 | exs | Elixir | 25-set.exs | yortz/30-days-of-elixir | b7126eeee16b726df0b00234fd4aff03a5c3e1a9 | [
"MIT"
] | null | null | null | 25-set.exs | yortz/30-days-of-elixir | b7126eeee16b726df0b00234fd4aff03a5c3e1a9 | [
"MIT"
] | null | null | null | 25-set.exs | yortz/30-days-of-elixir | b7126eeee16b726df0b00234fd4aff03a5c3e1a9 | [
"MIT"
] | null | null | null | ExUnit.start
defmodule SetTest do
use ExUnit.Case
test "to_list" do
list = HashSet.new([1, 2, 2, 3]) |> HashSet.to_list
assert list == [2, 3, 1] # unintuitive ordering
end
test "union" do
union = HashSet.new([1, 2, 3]) |> HashSet.union(HashSet.new([2, 3, 4]))
assert Set.to_list(union) == [2, 3, 4, 1] # unintuitive, but somewhat more understandable
end
test "intersection" do
union = HashSet.new([1, 2, 3]) |> HashSet.intersection(HashSet.new([2, 3, 4]))
assert Set.to_list(union) == [2, 3]
end
test "member?" do
refute HashSet.new([1, 3, 5]) |> HashSet.member?(2)
end
end
| 25 | 93 | 0.6224 |
08b74d9292b7c9817ce3c439f2686215eba1b571 | 92 | exs | Elixir | test/boots_of_speed_web/views/layout_view_test.exs | Baradoy/boots_of_speed | 6004da8fb43e15cb7443e0bd00fe70c936a41015 | [
"MIT"
] | 1 | 2019-04-18T05:10:21.000Z | 2019-04-18T05:10:21.000Z | test/boots_of_speed_web/views/layout_view_test.exs | Baradoy/boots_of_speed | 6004da8fb43e15cb7443e0bd00fe70c936a41015 | [
"MIT"
] | 3 | 2020-07-16T17:41:44.000Z | 2021-05-08T03:39:49.000Z | test/boots_of_speed_web/views/layout_view_test.exs | Baradoy/boots_of_speed | 6004da8fb43e15cb7443e0bd00fe70c936a41015 | [
"MIT"
] | null | null | null | defmodule BootsOfSpeedWeb.LayoutViewTest do
use BootsOfSpeedWeb.ConnCase, async: true
end
| 23 | 43 | 0.847826 |
08b78b5ed100fa8aafd72cfeb28dfe39dce8c30e | 3,560 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_form_parameter.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_form_parameter.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_form_parameter.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"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.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameter do
@moduledoc """
Represents a form parameter.
## Attributes
* `defaultValue` (*type:* `any()`, *default:* `nil`) - The default value of an optional parameter. If the parameter is required, the default value will be ignored.
* `displayName` (*type:* `String.t`, *default:* `nil`) - Required. The human-readable name of the parameter, unique within the form.
* `entityType` (*type:* `String.t`, *default:* `nil`) - Required. The entity type of the parameter. Format: `projects/-/locations/-/agents/-/entityTypes/` for system entity types (for example, `projects/-/locations/-/agents/-/entityTypes/sys.date`), or `projects//locations//agents//entityTypes/` for developer entity types.
* `fillBehavior` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior.t`, *default:* `nil`) - Required. Defines fill behavior for the parameter.
* `isList` (*type:* `boolean()`, *default:* `nil`) - Indicates whether the parameter represents a list of values.
* `redact` (*type:* `boolean()`, *default:* `nil`) - Indicates whether the parameter content should be redacted in text and audio. If the flag is set to true, the parameter content will be replaced by parameter name in both request and response. Note: the parameter content is subject to redaction if either parameter level redaction or entity type level redaction is enabled.
* `required` (*type:* `boolean()`, *default:* `nil`) - Indicates whether the parameter is required. Optional parameters will not trigger prompts; however, they are filled if the user specifies them. Required parameters must be filled before form filling concludes.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:defaultValue => any(),
:displayName => String.t(),
:entityType => String.t(),
:fillBehavior =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior.t(),
:isList => boolean(),
:redact => boolean(),
:required => boolean()
}
field(:defaultValue)
field(:displayName)
field(:entityType)
field(:fillBehavior,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior
)
field(:isList)
field(:redact)
field(:required)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameter do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameter.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1FormParameter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 47.466667 | 380 | 0.729494 |
08b79a6a1e00892f00705fddb5d6d1858257c229 | 1,055 | exs | Elixir | test/wabanex_web/controllers/imc_controller_test.exs | riosvictor/wabanex | 380b8078db1ac700d6cf2a232a92730fbe3ffc64 | [
"MIT"
] | 1 | 2022-03-16T20:41:59.000Z | 2022-03-16T20:41:59.000Z | test/wabanex_web/controllers/imc_controller_test.exs | riosvictor/wabanex | 380b8078db1ac700d6cf2a232a92730fbe3ffc64 | [
"MIT"
] | null | null | null | test/wabanex_web/controllers/imc_controller_test.exs | riosvictor/wabanex | 380b8078db1ac700d6cf2a232a92730fbe3ffc64 | [
"MIT"
] | null | null | null | defmodule WabanexWeb.IMCControllerTest do
use WabanexWeb.ConnCase, async: true
describe "index/2" do
test "when all params are valid, returns the imc info", %{conn: conn} do
params = %{"filename" => "students.csv"}
response =
conn
|> get(Routes.imc_path(conn, :index, params))
|> json_response(:ok)
expected_response = %{
"result" => %{
"Dani" => 23.437499999999996,
"Diego" => 23.04002019946976,
"Gabul" => 22.857142857142858,
"Rafael" => 24.897060231734173,
"Rodrigo" => 26.234567901234566
}
}
assert response == expected_response
end
test "when there are invalid params, returns an error", %{conn: conn} do
params = %{"filename" => "chuchu.csv"}
response =
conn
|> get(Routes.imc_path(conn, :index, params))
|> json_response(:bad_request)
expected_response = %{"result" => "Error while opening the file"}
assert response == expected_response
end
end
end
| 26.375 | 76 | 0.58673 |
08b7aa934524448e176f3550240d358718ea7580 | 850 | ex | Elixir | fogex/lib/fogex/modules/connector/handlers/mqtt/supevisor.ex | FogEx/poc | 0d3a26b482152b4b73a279dfdb2bf69008234c06 | [
"MIT"
] | null | null | null | fogex/lib/fogex/modules/connector/handlers/mqtt/supevisor.ex | FogEx/poc | 0d3a26b482152b4b73a279dfdb2bf69008234c06 | [
"MIT"
] | null | null | null | fogex/lib/fogex/modules/connector/handlers/mqtt/supevisor.ex | FogEx/poc | 0d3a26b482152b4b73a279dfdb2bf69008234c06 | [
"MIT"
] | null | null | null | defmodule FogEx.Modules.Connector.MQTT.Supervisor do
use Supervisor
def start_link(init_arg) do
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
def init(_init_arg) do
mqtt_host = Application.get_env(:fogex, :mqtt_host)
mqtt_port = Application.get_env(:fogex, :mqtt_port)
mqtt_opts = [
name: MqttPotion.Connection,
host: mqtt_host,
port: mqtt_port,
ssl: false,
protocol_version: 5,
client_id: "connector_mqtt_client",
ssl_opts: [],
handler_pid: FogEx.Modules.Connector.MQTT.Handler,
subscriptions: [
{"vital_signs/#", 0},
{"body_temperature/#", 0}
]
]
children = [
{MqttPotion.Connection, mqtt_opts},
FogEx.Modules.Connector.MQTT.Handler
]
Supervisor.init(children, strategy: :one_for_one)
end
end
| 24.285714 | 65 | 0.658824 |
08b7b17e0e2c70278be41e0dbbe77efe70c48690 | 2,896 | ex | Elixir | clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_page_line.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_page_line.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_page_line.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.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLine do
@moduledoc """
A collection of tokens that a human would perceive as a line. Does not cross column boundaries, can be horizontal, vertical, etc.
## Attributes
* `detectedLanguages` (*type:* `list(GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage.t)`, *default:* `nil`) - A list of detected languages together with confidence.
* `layout` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLayout.t`, *default:* `nil`) - Layout for Line.
* `provenance` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentProvenance.t`, *default:* `nil`) - The history of this annotation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:detectedLanguages =>
list(
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage.t()
)
| nil,
:layout =>
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLayout.t()
| nil,
:provenance =>
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentProvenance.t()
| nil
}
field(:detectedLanguages,
as:
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage,
type: :list
)
field(:layout,
as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLayout
)
field(:provenance,
as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentProvenance
)
end
defimpl Poison.Decoder,
for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLine do
def decode(value, options) do
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLine.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageLine do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.105263 | 212 | 0.746547 |
08b7ba01c4e857344a98eab3296438f1920f4628 | 1,954 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/projects_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/projects_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/projects_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V33.Model.ProjectsListResponse do
@moduledoc """
Project List Response
## Attributes
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#projectsListResponse".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation.
* `projects` (*type:* `list(GoogleApi.DFAReporting.V33.Model.Project.t)`, *default:* `nil`) - Project collection.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t() | nil,
:nextPageToken => String.t() | nil,
:projects => list(GoogleApi.DFAReporting.V33.Model.Project.t()) | nil
}
field(:kind)
field(:nextPageToken)
field(:projects, as: GoogleApi.DFAReporting.V33.Model.Project, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.ProjectsListResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.ProjectsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.ProjectsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.867925 | 156 | 0.725691 |
08b7dd8cc72001c980259c1775f4e0cac1e8d03a | 2,669 | ex | Elixir | lib/guardian/token.ex | gestsol/guardian | ee173c7ff0343d77cf10c559bd11ac2c88804ad8 | [
"MIT"
] | null | null | null | lib/guardian/token.ex | gestsol/guardian | ee173c7ff0343d77cf10c559bd11ac2c88804ad8 | [
"MIT"
] | null | null | null | lib/guardian/token.ex | gestsol/guardian | ee173c7ff0343d77cf10c559bd11ac2c88804ad8 | [
"MIT"
] | null | null | null | defmodule Guardian.Token do
@moduledoc """
The behaviour module for all token modules.
Token modules are responsible for all the heavy lifting
in Guardian.
"""
@type token :: String.t()
@type claims :: map
@type resource :: any
@type ttl ::
{pos_integer, :second}
| {pos_integer, :seconds}
| {pos_integer, :minute}
| {pos_integer, :minutes}
| {pos_integer, :day}
| {pos_integer, :days}
| {pos_integer, :week}
| {pos_integer, :weeks}
@type secret_error :: {:error, :secret_not_found}
@type signing_error :: {:error, :signing_error}
@type encoding_error :: {:error, atom}
@type decoding_error :: {:error, atom}
@doc """
Inspect the contents of the token without validation or signature checking
"""
@callback peek(module :: module, token :: token) :: map
@doc """
Generate a unique id for a token
"""
@callback token_id() :: String.t()
@doc """
Build the default claims for the token
"""
@callback build_claims(
mod :: module,
resource :: any,
sub :: String.t(),
claims :: claims,
options :: Keyword.t()
) :: {:ok, claims} | {:error, atom}
@doc """
Create the token including serializing and signing
"""
@callback create_token(mod :: module, claims :: claims, options :: Guardian.options()) ::
{:ok, token} | signing_error | secret_error | encoding_error
@doc """
Decode the token. Without verification of the claims within it.
"""
@callback decode_token(mod :: module, token :: token, options :: Guardian.options()) ::
{:ok, token} | secret_error | decoding_error
@doc """
Verify the claims of a token
"""
@callback verify_claims(mod :: module, claims :: claims, options :: Guardian.options()) ::
{:ok, claims} | {:error, any}
@doc """
Revoke a token (if appropriate)
"""
@callback revoke(mod :: module, claims :: claims, token :: token, options :: Guardian.options()) ::
{:ok, claims | {:error, any}}
@doc """
Refresh a token
"""
@callback refresh(mod :: module, old_token :: token, options :: Guardian.options()) ::
{:ok, {token, claims}, {token, claims}} | {:error, any}
@doc """
Exchange a token from one type to another
"""
@callback exchange(
mod :: module,
old_token :: token,
from_type :: String.t() | [String.t(), ...],
to_type :: String.t(),
options :: Guardian.options()
) :: {:ok, {token, claims}, {token, claims}} | {:error, any}
end
| 30.329545 | 101 | 0.568752 |
08b7fa6615985a85b50ced713da0a14aa0a3a143 | 1,300 | ex | Elixir | lib/cog/chat/slack/formatter.ex | NiyiOdumosu/cog | f1f7b66894bd13e865e47e89df6379d78fd79e88 | [
"Apache-2.0"
] | null | null | null | lib/cog/chat/slack/formatter.ex | NiyiOdumosu/cog | f1f7b66894bd13e865e47e89df6379d78fd79e88 | [
"Apache-2.0"
] | null | null | null | lib/cog/chat/slack/formatter.ex | NiyiOdumosu/cog | f1f7b66894bd13e865e47e89df6379d78fd79e88 | [
"Apache-2.0"
] | null | null | null | defmodule Cog.Chat.Slack.Formatter do
@channel ~r/<\#(C.*)(\|(.*))?>/U
@user ~r/<\@(U.*)(\|(.*))?>/U
@command ~r/<\!(.*)(\|(.*))?>/U
@link ~r/<(.*)(\|(.*))?>/U
def unescape(message, slack) do
message
|> unescape_channels(slack)
|> unescape_users(slack)
|> unescape_commands
|> unescape_links
end
defp unescape_channels(message, slack) do
Regex.replace(@channel, message, fn
_match, channel_id, "", "" ->
Slack.Lookups.lookup_channel_name(channel_id, slack)
_match, _channel_id, _right, channel_name ->
"#" <> channel_name
end)
end
defp unescape_users(message, slack) do
Regex.replace(@user, message, fn
_match, user_id, "", "" ->
Slack.Lookups.lookup_user_name(user_id, slack)
_match, _user_id, _right, user_name ->
"@" <> user_name
end)
end
defp unescape_commands(message) do
Regex.replace(@command, message, fn
_match, command_name, "", "" ->
"@" <> command_name
_match, _command_name, _right, label ->
"@" <> label
end)
end
defp unescape_links(message) do
Regex.replace(@link, message, fn
_match, full_link, "", "" ->
full_link
_match, _full_link, _right, short_link ->
short_link
end)
end
end
| 25.490196 | 60 | 0.583846 |
08b89130e082b310e9a243abf5915872b0a05af9 | 979 | exs | Elixir | test/support/endpoint.exs | andriybohdan/ex_admin | e31c725078ac4e7390204a87d96360a21ffe7b90 | [
"MIT"
] | 1 | 2018-08-30T20:20:56.000Z | 2018-08-30T20:20:56.000Z | test/support/endpoint.exs | 8thlight/ex_admin | 314d4068270c47799ec54f719073a565222bcfad | [
"MIT"
] | null | null | null | test/support/endpoint.exs | 8thlight/ex_admin | 314d4068270c47799ec54f719073a565222bcfad | [
"MIT"
] | 2 | 2018-07-12T07:44:50.000Z | 2018-07-19T11:45:09.000Z | defmodule TestExAdmin.Endpoint do
use Phoenix.Endpoint, otp_app: :ex_admin
# 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: :ex_admin, 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: "_binaryid_key",
signing_salt: "JFbk5iZ6"
plug TestExAdmin.Router
end
| 25.763158 | 69 | 0.711951 |
08b8aa8097d8a5ca069861a4cfecb93ff191af8c | 320 | exs | Elixir | config/prod.exs | Navneet-gupta01/commanded-extreme-adapter | daac1726573d4b979aaeddd0dae9aca0473a9446 | [
"MIT"
] | null | null | null | config/prod.exs | Navneet-gupta01/commanded-extreme-adapter | daac1726573d4b979aaeddd0dae9aca0473a9446 | [
"MIT"
] | null | null | null | config/prod.exs | Navneet-gupta01/commanded-extreme-adapter | daac1726573d4b979aaeddd0dae9aca0473a9446 | [
"MIT"
] | null | null | null | use Mix.Config
config :extreme, :event_store,
db_type: :node,
host: "localhost",
port: 1113,
username: "admin",
password: "changeit",
reconnect_delay: 2_000,
max_attempts: :infinity
config :commanded_extreme_adapter,
serializer: Commanded.Serialization.JsonSerializer,
stream_prefix: "commandedprod"
| 21.333333 | 53 | 0.75 |
08b8af5112cf5c94fb87eddb5909799215c26227 | 105,654 | ex | Elixir | clients/managed_identities/lib/google_api/managed_identities/v1/api/projects.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | clients/managed_identities/lib/google_api/managed_identities/v1/api/projects.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"Apache-2.0"
] | null | null | null | clients/managed_identities/lib/google_api/managed_identities/v1/api/projects.ex | corp-momenti/elixir-google-api | fe1580e305789ab2ca0741791b8ffe924bd3240c | [
"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.ManagedIdentities.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.ManagedIdentities.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets information about a location.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name for the location.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Location{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Location.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Location{}])
end
@doc """
Lists information about the supported locations for this service.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in [AIP-160](https://google.aip.dev/160).
* `:pageSize` (*type:* `integer()`) - The maximum number of results to return. If not set, the service selects a default.
* `:pageToken` (*type:* `String.t`) - A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.ListLocationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.ListLocationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_list(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/locations", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.ListLocationsResponse{}]
)
end
@doc """
Adds an AD trust to a domain.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The resource domain name, project name and location using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.AttachTrustRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_attach_trust(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_attach_trust(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:attachTrust", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Creates a Microsoft AD domain.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The resource project name and location using the form: `projects/{project_id}/locations/global`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:domainName` (*type:* `String.t`) - Required. The fully qualified domain name. e.g. mydomain.myorganization.com, with the following restrictions: * Must contain only lowercase letters, numbers, periods and hyphens. * Must start with a letter. * Must contain between 2-64 characters. * Must end with a number or a letter. * Must not start with period. * First segment length (mydomain for example above) shouldn't exceed 15 chars. * The last segment cannot be fully numeric. * Must be unique within the customer project.
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.Domain.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:domainName => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/domains", %{
"parent" => URI.encode(parent, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Deletes a domain.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The domain resource name using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Removes an AD trust.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The resource domain name, project name, and location using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.DetachTrustRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_detach_trust(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_detach_trust(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:detachTrust", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Gets information about a domain.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The domain resource name using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Domain{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Domain.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Domain{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"options.requestedPolicyVersion"` (*type:* `integer()`) - Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any conditional bindings must specify version 3. Policies without any conditional bindings may specify any valid value or leave the field unset. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"options.requestedPolicyVersion" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &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.ManagedIdentities.V1.Model.Policy{}])
end
@doc """
Gets the domain ldaps settings.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The domain resource name using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.LDAPSSettings{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_get_ldapssettings(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.LDAPSSettings.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_get_ldapssettings(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/ldapssettings", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.LDAPSSettings{}])
end
@doc """
Lists domains in a project.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The resource name of the domain location using the form: `projects/{project_id}/locations/global`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Optional. A filter specifying constraints of a list operation. For example, `Domain.fqdn="mydomain.myorginization"`.
* `:orderBy` (*type:* `String.t`) - Optional. Specifies the ordering of results. See [Sorting order](https://cloud.google.com/apis/design/design_patterns#sorting_order) for more information.
* `:pageSize` (*type:* `integer()`) - Optional. The maximum number of items to return. If not specified, a default value of 1000 will be used. Regardless of the page_size value, the response may include a partial list. Callers should rely on a response's next_page_token to determine if there are additional results to list.
* `:pageToken` (*type:* `String.t`) - Optional. The `next_page_token` value returned from a previous ListDomainsRequest request, if any.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.ListDomainsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.ListDomainsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:orderBy => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/domains", %{
"parent" => URI.encode(parent, &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.ManagedIdentities.V1.Model.ListDomainsResponse{}]
)
end
@doc """
Updates the metadata and configuration of a domain.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The unique name of the domain using the form: `projects/{project_id}/locations/global/domains/{domain_name}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. Mask of fields to update. At least one path must be supplied in this field. The elements of the repeated paths field may only include fields from Domain: * `labels` * `locations` * `authorized_networks` * `audit_logs_enabled`
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.Domain.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Updates the DNS conditional forwarder.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The resource domain name, project name and location using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.ReconfigureTrustRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_reconfigure_trust(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_reconfigure_trust(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:reconfigureTrust", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Resets a domain's administrator password.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The domain resource name using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.ResetAdminPasswordRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.ResetAdminPasswordResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_reset_admin_password(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.ResetAdminPasswordResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_reset_admin_password(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:resetAdminPassword", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.ResetAdminPasswordResponse{}]
)
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &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.ManagedIdentities.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &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.ManagedIdentities.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Patches a single ldaps settings.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource name of the LDAPS settings. Uses the form: `projects/{project}/locations/{location}/domains/{domain}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. Mask of fields to update. At least one path must be supplied in this field. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.LDAPSSettings.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_update_ldapssettings(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_update_ldapssettings(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}/ldapssettings", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Validates a trust state, that the target domain is reachable, and that the target domain is able to accept incoming trust requests.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The resource domain name, project name, and location using the form: `projects/{project_id}/locations/global/domains/{domain_name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.ValidateTrustRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_validate_trust(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_validate_trust(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:validateTrust", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Gets details of a single sqlIntegration.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. SQLIntegration resource name using the form: `projects/{project_id}/locations/global/domains/{domain}/sqlIntegrations/{name}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.SqlIntegration{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_sql_integrations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.SqlIntegration.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_sql_integrations_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.SqlIntegration{}])
end
@doc """
Lists SqlIntegrations in a given domain.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The resource name of the SqlIntegrations using the form: `projects/{project_id}/locations/global/domains/*`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Optional. Filter specifying constraints of a list operation. For example, `SqlIntegration.name="sql"`.
* `:orderBy` (*type:* `String.t`) - Optional. Specifies the ordering of results following syntax at https://cloud.google.com/apis/design/design_patterns#sorting_order.
* `:pageSize` (*type:* `integer()`) - Optional. The maximum number of items to return. If not specified, a default value of 1000 will be used by the service. Regardless of the page_size value, the response may include a partial list and a caller should only rely on response'ANIZATIONs next_page_token to determine if there are more instances left to be queried.
* `:pageToken` (*type:* `String.t`) - Optional. The next_page_token value returned from a previous List request, if any.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.ListSqlIntegrationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_domains_sql_integrations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.ListSqlIntegrationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_domains_sql_integrations_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:orderBy => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/sqlIntegrations", %{
"parent" => URI.encode(parent, &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.ManagedIdentities.V1.Model.ListSqlIntegrationsResponse{}]
)
end
@doc """
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be cancelled.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.CancelOperationRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_operations_cancel(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_operations_cancel(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:cancel", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Empty{}])
end
@doc """
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be deleted.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_operations_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_operations_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Empty{}])
end
@doc """
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_operations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_operations_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation's parent resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.ListOperationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_operations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.ListOperationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_operations_list(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.ListOperationsResponse{}]
)
end
@doc """
Creates a Peering for Managed AD instance.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource project name and location using the form: `projects/{project_id}/locations/global`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:peeringId` (*type:* `String.t`) - Required. Peering Id, unique name to identify peering. It should follow the regex format "^(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)$"
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.Peering.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:peeringId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/peerings", %{
"parent" => URI.encode(parent, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Deletes identified Peering.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Peering resource name using the form: `projects/{project_id}/locations/global/peerings/{peering_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Gets details of a single Peering.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Peering resource name using the form: `projects/{project_id}/locations/global/peerings/{peering_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Peering{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Peering.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Peering{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:"options.requestedPolicyVersion"` (*type:* `integer()`) - Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any conditional bindings must specify version 3. Policies without any conditional bindings may specify any valid value or leave the field unset. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:"options.requestedPolicyVersion" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &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.ManagedIdentities.V1.Model.Policy{}])
end
@doc """
Lists Peerings in a given project.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The resource name of the peering location using the form: `projects/{project_id}/locations/global`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Optional. Filter specifying constraints of a list operation. For example, `peering.authorized_network="projects/myprojectid/global/networks/mynetwork"`.
* `:orderBy` (*type:* `String.t`) - Optional. Specifies the ordering of results following syntax at https://cloud.google.com/apis/design/design_patterns#sorting_order.
* `:pageSize` (*type:* `integer()`) - Optional. The maximum number of items to return. If not specified, a default value of 1000 will be used by the service. Regardless of the page_size value, the response may include a partial list and a caller should only rely on response's next_page_token to determine if there are more instances left to be queried.
* `:pageToken` (*type:* `String.t`) - Optional. The next_page_token value returned from a previous List request, if any.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.ListPeeringsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.ListPeeringsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:orderBy => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/peerings", %{
"parent" => URI.encode(parent, &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.ManagedIdentities.V1.Model.ListPeeringsResponse{}]
)
end
@doc """
Updates the labels for specified Peering.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Output only. Unique name of the peering in this scope including projects and location using the form: `projects/{project_id}/locations/global/peerings/{peering_id}`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. Mask of fields to update. At least one path must be supplied in this field. The elements of the repeated paths field may only include these fields from Peering: * `labels`
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.Peering.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &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.ManagedIdentities.V1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &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.ManagedIdentities.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.ManagedIdentities.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.ManagedIdentities.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.ManagedIdentities.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec managedidentities_projects_locations_global_peerings_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.ManagedIdentities.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def managedidentities_projects_locations_global_peerings_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &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.ManagedIdentities.V1.Model.TestIamPermissionsResponse{}]
)
end
end
| 46.05667 | 607 | 0.619305 |
08b8ede20f4c6207d171f22d0de8c23e64208247 | 652 | ex | Elixir | lib/xuber/coordinator.ex | CCL77/trackme | af3e2dbfb3cbf92e96c0bdc8f2f6a19595d92140 | [
"MIT"
] | 3 | 2017-06-14T15:27:29.000Z | 2017-09-13T12:54:30.000Z | lib/xuber/coordinator.ex | joshnuss/xuber | a5fb61e4ddac87dbb8c140edb8d1550f5c2b1cff | [
"MIT"
] | null | null | null | lib/xuber/coordinator.ex | joshnuss/xuber | a5fb61e4ddac87dbb8c140edb8d1550f5c2b1cff | [
"MIT"
] | 2 | 2019-07-22T04:04:38.000Z | 2020-08-15T14:50:18.000Z | defmodule XUber.Coordinator do
@name __MODULE__
def start_link,
do: Agent.start_link(fn -> %{} end, name: @name)
def register(name),
do: Agent.update(@name, &Map.put(&1, name, []))
def known,
do: Agent.get(@name, &Map.keys(&1))
def positions do
Agent.get(@name, fn names ->
for {key, coords} <- names, into: %{} do
{key, List.first(coords)}
end
end)
end
def move(name, coords) do
Agent.update(@name, fn names ->
Map.update(names, name, [coords], &[coords | &1])
end)
end
def drop(name) do
Agent.update(@name, fn names ->
Map.delete(names, name)
end)
end
end
| 19.757576 | 55 | 0.582822 |
08b90e7f75f9faf4bf75b82671e3e92f3d0e909b | 71 | ex | Elixir | lib/web/views/layout_view.ex | irisTa56/sdo_elixir | de856596c462141477bb27aee5d63cb7b95a3b67 | [
"MIT"
] | null | null | null | lib/web/views/layout_view.ex | irisTa56/sdo_elixir | de856596c462141477bb27aee5d63cb7b95a3b67 | [
"MIT"
] | 2 | 2021-03-10T17:42:11.000Z | 2021-05-11T13:38:31.000Z | lib/web/views/layout_view.ex | irisTa56/sdo_elixir | de856596c462141477bb27aee5d63cb7b95a3b67 | [
"MIT"
] | null | null | null | defmodule SdoPhoenix.Web.LayoutView do
use SdoPhoenix.Web, :view
end
| 17.75 | 38 | 0.802817 |
08b910cf20e2e4c1d243fd77c31a3418ff43a04d | 1,209 | ex | Elixir | apps/note_it_web/lib/note_it_web/endpoint.ex | sushilman/note-it | c47edafb4272b9f01d53f8566f5ed7858f2d355c | [
"Apache-2.0"
] | null | null | null | apps/note_it_web/lib/note_it_web/endpoint.ex | sushilman/note-it | c47edafb4272b9f01d53f8566f5ed7858f2d355c | [
"Apache-2.0"
] | null | null | null | apps/note_it_web/lib/note_it_web/endpoint.ex | sushilman/note-it | c47edafb4272b9f01d53f8566f5ed7858f2d355c | [
"Apache-2.0"
] | null | null | null | defmodule NoteItWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :note_it_web
socket "/socket", NoteItWeb.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: :note_it_web, 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
# 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.
plug Plug.Session,
store: :cookie,
key: "_note_it_web_key",
signing_salt: "rayuyKlz"
plug NoteItWeb.Router
end
| 28.116279 | 69 | 0.718776 |
08b9306a17f0678fcb3c686effbd9e9fee9b47ce | 102 | ex | Elixir | lib/binance_ex/orderbook.ex | Jonsey/BinanceEx | cf41f06f649d4d347ef17c7ae6b3bd8f50c224ca | [
"MIT"
] | null | null | null | lib/binance_ex/orderbook.ex | Jonsey/BinanceEx | cf41f06f649d4d347ef17c7ae6b3bd8f50c224ca | [
"MIT"
] | null | null | null | lib/binance_ex/orderbook.ex | Jonsey/BinanceEx | cf41f06f649d4d347ef17c7ae6b3bd8f50c224ca | [
"MIT"
] | null | null | null | defmodule BinanceEx.Orderbook do
defstruct [:bids, :asks, :last_update_id]
use ExConstructor
end
| 17 | 43 | 0.77451 |
08b9429c76a99cdc21169cbec8fc7628af16cb6f | 1,042 | exs | Elixir | chromoid_web/config/test.exs | ConnorRigby/chromoid | 6424a9234227d18d7c287ded869caeb31511bb97 | [
"Apache-2.0"
] | 7 | 2020-11-18T11:29:20.000Z | 2022-01-16T03:16:14.000Z | chromoid_web/config/test.exs | ConnorRigby/chromoid | 6424a9234227d18d7c287ded869caeb31511bb97 | [
"Apache-2.0"
] | null | null | null | chromoid_web/config/test.exs | ConnorRigby/chromoid | 6424a9234227d18d7c287ded869caeb31511bb97 | [
"Apache-2.0"
] | 1 | 2021-01-06T15:40:46.000Z | 2021-01-06T15:40:46.000Z | use Mix.Config
# Only in tests, remove the complexity from the password hashing algorithm
config :bcrypt_elixir, :log_rounds, 1
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :chromoid, Chromoid.Repo,
username: "postgres",
password: "postgres",
database: "chromoid_test#{System.get_env("MIX_TEST_PARTITION")}",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :chromoid, ChromoidWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
config :chromoid, ChromoidDiscord.OAuth, url: "http://localhost:4000/discord/oauth"
config :chromoid, ChromoidDiscord.Guild.Responder, api: ChromoidDiscord.FakeAPI
config :chromoid, ChromoidDiscord.Supervisor, dispatch_source: ChromoidDiscord.FakeDiscordSource
| 34.733333 | 96 | 0.778311 |
08b943ea2e125428f35fb66f7be8630c28d9e7bd | 954 | ex | Elixir | lib/adventofcode.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | 2 | 2019-01-16T16:10:31.000Z | 2019-05-14T04:41:15.000Z | lib/adventofcode.ex | scmx/advent-of-code-2019-elixir | f3022efb422e15abead6b882c78855b26b138443 | [
"MIT"
] | null | null | null | lib/adventofcode.ex | scmx/advent-of-code-2019-elixir | f3022efb422e15abead6b882c78855b26b138443 | [
"MIT"
] | 1 | 2020-12-10T10:47:21.000Z | 2020-12-10T10:47:21.000Z | defmodule Adventofcode do
@moduledoc """
Base module for day solutions. By `use`ing this module a `puzzle_input/0`
function will be provided that reads puzzle input to a string. Will probably
only be used during tests
"""
defmacro __using__(options) do
quote do
import Adventofcode
def puzzle_input do
read_puzzle_input_for(__MODULE__, unquote(options))
end
end
end
@doc false
def read_puzzle_input_for(module, options) do
case File.read(Path.join(["input", input_filename(module) <> ".txt"])) do
{:ok, data} -> trim(data, Keyword.get(options, :trim))
{:error, _} -> nil
end
end
defp input_filename(module) do
module
|> to_string()
|> String.split(".")
|> Enum.at(2)
|> Macro.underscore()
|> String.replace(~r/(\w)(\d)/, "\\1_\\2")
end
defp trim(text, false), do: String.trim_trailing(text, "\n")
defp trim(text, _), do: String.trim(text)
end
| 25.105263 | 78 | 0.642558 |
08b96bc5959aac8e93d06035dab7732faab213a6 | 4,415 | ex | Elixir | lib/credo/check/refactor/cyclomatic_complexity.ex | isaacsanders/credo | 5623570bb2e3944345f1bf11819ca613533b5e10 | [
"MIT"
] | null | null | null | lib/credo/check/refactor/cyclomatic_complexity.ex | isaacsanders/credo | 5623570bb2e3944345f1bf11819ca613533b5e10 | [
"MIT"
] | null | null | null | lib/credo/check/refactor/cyclomatic_complexity.ex | isaacsanders/credo | 5623570bb2e3944345f1bf11819ca613533b5e10 | [
"MIT"
] | 1 | 2020-06-30T16:32:44.000Z | 2020-06-30T16:32:44.000Z | defmodule Credo.Check.Refactor.CyclomaticComplexity do
@moduledoc false
@checkdoc """
Cyclomatic complexity is a software complexity metric closely correlated with
coding errors.
If a function feels like it's gotten too complex, it more often than not also
has a high CC value. So, if anything, this is useful to convince team members
and bosses of a need to refactor parts of the code based on "objective"
metrics.
"""
@explanation [
check: @checkdoc,
params: [
max_complexity: "The maximum cyclomatic complexity a function should have."
]
]
@default_params [max_complexity: 9]
@def_ops [:def, :defp, :defmacro]
# these have two outcomes: it succeeds or does not
@double_condition_ops [:if, :unless, :for, :try, :and, :or, :&&, :||]
# these can have multiple outcomes as they are defined in their do blocks
@multiple_condition_ops [:case, :cond]
@op_complexity_map [
def: 1,
defp: 1,
defmacro: 1,
if: 1,
unless: 1,
for: 1,
try: 1,
and: 1,
or: 1,
&&: 1,
||: 1,
case: 1,
cond: 1
]
use Credo.Check
@doc false
def run(source_file, params \\ []) do
issue_meta = IssueMeta.for(source_file, params)
max_complexity = Params.get(params, :max_complexity, @default_params)
Credo.Code.prewalk(
source_file,
&traverse(&1, &2, issue_meta, max_complexity)
)
end
# exception for `__using__` macros
defp traverse({:defmacro, _, [{:__using__, _, _}, _]} = ast, issues, _, _) do
{ast, issues}
end
for op <- @def_ops do
defp traverse(
{unquote(op), meta, arguments} = ast,
issues,
issue_meta,
max_complexity
)
when is_list(arguments) do
complexity =
ast
|> complexity_for
|> round
if complexity > max_complexity do
fun_name = Credo.Code.Module.def_name(ast)
{
ast,
issues ++
[
issue_for(
issue_meta,
meta[:line],
fun_name,
max_complexity,
complexity
)
]
}
else
{ast, issues}
end
end
end
defp traverse(ast, issues, _source_file, _max_complexity) do
{ast, issues}
end
@doc """
Returns the Cyclomatic Complexity score for the block inside the given AST,
which is expected to represent a function or macro definition.
iex> {:def, [line: 1],
...> [
...> {:first_fun, [line: 1], nil},
...> [do: {:=, [line: 2], [{:x, [line: 2], nil}, 1]}]
...> ]
...> } |> Credo.Check.Refactor.CyclomaticComplexity.complexity_for
1.0
"""
def complexity_for({_def_op, _meta, _arguments} = ast) do
Credo.Code.prewalk(ast, &traverse_complexity/2, 0)
end
for op <- @def_ops do
defp traverse_complexity(
{unquote(op) = op, _meta, arguments} = ast,
complexity
)
when is_list(arguments) do
{ast, complexity + @op_complexity_map[op]}
end
end
for op <- @double_condition_ops do
defp traverse_complexity(
{unquote(op) = op, _meta, arguments} = ast,
complexity
)
when is_list(arguments) do
{ast, complexity + @op_complexity_map[op]}
end
end
for op <- @multiple_condition_ops do
defp traverse_complexity({unquote(op), _meta, nil} = ast, complexity) do
{ast, complexity}
end
defp traverse_complexity(
{unquote(op) = op, _meta, arguments} = ast,
complexity
)
when is_list(arguments) do
block_cc =
arguments
|> Credo.Code.Block.do_block_for!()
|> do_block_complexity(op)
{ast, complexity + block_cc}
end
end
defp traverse_complexity(ast, complexity) do
{ast, complexity}
end
defp do_block_complexity(nil, _), do: 0
defp do_block_complexity(block, op) do
count =
block
|> List.wrap()
|> Enum.count()
count * @op_complexity_map[op]
end
def issue_for(issue_meta, line_no, trigger, max_value, actual_value) do
format_issue(
issue_meta,
message: "Function is too complex (CC is #{actual_value}, max is #{max_value}).",
trigger: trigger,
line_no: line_no,
severity: Severity.compute(actual_value, max_value)
)
end
end
| 24.803371 | 87 | 0.590034 |
08b9ac9d7638ed6449bfe9cb59b535b9ffcf2a73 | 27,729 | exs | Elixir | test/lib/bamboo/adapters/smtp_adapter_test.exs | kianmeng/bamboo_smtp | e6f159d230a785a9c67aa180a199eb5ec3af3f41 | [
"MIT"
] | null | null | null | test/lib/bamboo/adapters/smtp_adapter_test.exs | kianmeng/bamboo_smtp | e6f159d230a785a9c67aa180a199eb5ec3af3f41 | [
"MIT"
] | null | null | null | test/lib/bamboo/adapters/smtp_adapter_test.exs | kianmeng/bamboo_smtp | e6f159d230a785a9c67aa180a199eb5ec3af3f41 | [
"MIT"
] | null | null | null | defmodule Bamboo.SMTPAdapterTest do
use ExUnit.Case
alias Bamboo.Email
alias Bamboo.SMTPAdapter
defmodule FakeGenSMTP do
use GenServer
@impl true
def init(args) do
{:ok, args}
end
def start_link(_) do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
def send_blocking(email, config) do
GenServer.call(__MODULE__, {:send_email, {email, config}})
end
def fetch_sent_emails do
GenServer.call(__MODULE__, :fetch_emails)
end
@impl true
def handle_call(:fetch_emails, _from, state) do
{:reply, state, state}
end
@impl true
def handle_call({:send_email, {email, config}}, _from, state) do
case check_validity(email, config) do
:ok ->
{:reply, "200 Ok 1234567890", [{email, config} | state]}
error ->
{:reply, error, state}
end
end
defp check_validity(email, config) do
with :ok <- check_configuration(config),
:ok <- check_credentials(config[:username], config[:password], config[:auth]),
:ok <- check_email(email),
do: :ok
end
defp check_credentials(username, password, :always = _auth)
when is_nil(username) or is_nil(password) do
{:error, :no_credentials}
end
defp check_credentials(_username, _password, _auth), do: :ok
defp check_configuration(config) do
case Keyword.fetch(config, :relay) do
{:ok, wrong_domain = "wrong.smtp.domain"} ->
{:error, :retries_exceeded, {:network_failure, wrong_domain, {:error, :nxdomain}}}
_ ->
:ok
end
end
defp check_email({from, _to, _raw}) do
case from do
"wrong@user.com" ->
{:error, :no_more_hosts,
{:permanent_failure, "an-smtp-adddress",
"554 Message rejected: Email address is not verified.\r\n"}}
_ ->
:ok
end
end
end
@configuration %{
adapter: SMTPAdapter,
server: "smtp.domain",
port: 1025,
hostname: "your.domain",
username: "your.name@your.domain",
password: "pa55word",
transport: FakeGenSMTP,
no_mx_lookups: false
}
@email [
from: {"John Doe", "john@doe.com"},
to: [{"Jane Doe", "jane@doe.com"}],
cc: [{"Richard Roe", "richard@roe.com"}],
bcc: [{"Mary Major", "mary@major.com"}, {"Joe Major", "joe@major.com"}],
subject: "Hello from Bamboo",
html_body: "<h1>Bamboo is awesome!</h1>",
text_body: "*Bamboo is awesome!*",
headers: %{
"Reply-To" => "reply@doe.com"
}
]
@email_in_utf8 [
from: {"John Doe", "john@doe.com"},
to: [{"Jane Doe", "jane@doe.com"}],
cc: [{"Richard Roe", "richard@roe.com"}],
bcc: [{"Mary Major", "mary@major.com"}, {"Joe Major", "joe@major.com"}],
subject: "日本語のsubject",
html_body: "<h1>Bamboo is awesome!</h1>",
text_body: "*Bamboo is awesome!*",
headers: %{
"Reply-To" => "reply@doe.com"
}
]
setup do
start_supervised!(FakeGenSMTP)
:ok
end
test "raises if the server is nil" do
assert_raise ArgumentError, ~r/Key server is required/, fn ->
SMTPAdapter.handle_config(configuration(%{server: nil}))
end
end
test "raises if the port is nil" do
assert_raise ArgumentError, ~r/Key port is required/, fn ->
SMTPAdapter.handle_config(configuration(%{port: nil}))
end
end
test "sets default tls key if not present" do
%{tls: tls} = SMTPAdapter.handle_config(configuration())
assert :if_available == tls
end
test "doesn't set a default tls key if present" do
%{tls: tls} = SMTPAdapter.handle_config(configuration(%{tls: :always}))
assert :always == tls
end
test "sets default ssl key if not present" do
%{ssl: ssl} = SMTPAdapter.handle_config(configuration())
refute ssl
end
test "doesn't set a default ssl key if present" do
%{ssl: ssl} = SMTPAdapter.handle_config(configuration(%{ssl: true}))
assert ssl
end
test "sets default retries key if not present" do
%{retries: retries} = SMTPAdapter.handle_config(configuration())
assert retries == 1
end
test "doesn't set a default retries key if present" do
%{retries: retries} = SMTPAdapter.handle_config(configuration(%{retries: 42}))
assert retries == 42
end
test "sets server and port from System when specified" do
System.put_env("SERVER", "server")
System.put_env("PORT", "123")
config = %{
server: {:system, "SERVER"},
port: {:system, "PORT"}
}
bamboo_email = new_email()
bamboo_config = SMTPAdapter.handle_config(configuration(config))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:relay] == "server"
assert gen_smtp_config[:port] == 123
end
test "sets tls if_available from System when specified" do
System.put_env("TLS", "if_available")
config = SMTPAdapter.handle_config(configuration(%{tls: {:system, "TLS"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:tls] == :if_available
end
test "sets tls always from System when specified" do
System.put_env("TLS", "always")
config = SMTPAdapter.handle_config(configuration(%{tls: {:system, "TLS"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:tls] == :always
end
test "sets tls never from System when specified" do
System.put_env("TLS", "never")
config = SMTPAdapter.handle_config(configuration(%{tls: {:system, "TLS"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:tls] == :never
end
test "sets username and password from System when specified" do
System.put_env("SMTP_USER", "joeblow")
System.put_env("SMTP_PASS", "fromkokomo")
bamboo_email = new_email()
bamboo_config =
configuration(%{username: {:system, "SMTP_USER"}, password: {:system, "SMTP_PASS"}})
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:username] == "joeblow"
assert gen_smtp_config[:password] == "fromkokomo"
end
test "sets ssl true from System when specified" do
System.put_env("SSL", "true")
config = SMTPAdapter.handle_config(configuration(%{ssl: {:system, "SSL"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:ssl]
end
test "sets ssl false from System when specified" do
System.put_env("SSL", "false")
config = SMTPAdapter.handle_config(configuration(%{ssl: {:system, "SSL"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
refute gen_smtp_config[:ssl]
end
test "sets retries from System when specified" do
bamboo_email = new_email()
System.put_env("RETRIES", "123")
config = SMTPAdapter.handle_config(configuration(%{retries: {:system, "RETRIES"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert 123 == gen_smtp_config[:retries]
end
test "sets tls versions from System when specified" do
System.put_env("ALLOWED_TLS_VERSIONS", "tlsv1,tlsv1.2")
config =
SMTPAdapter.handle_config(
configuration(%{allowed_tls_versions: {:system, "ALLOWED_TLS_VERSIONS"}})
)
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert [:tlsv1, :"tlsv1.2"] == gen_smtp_config[:tls_options][:versions]
end
test "sets no_mx_lookups false from System when specified" do
System.put_env("NO_MX_LOOKUPS", "false")
config =
SMTPAdapter.handle_config(configuration(%{no_mx_lookups: {:system, "NO_MX_LOOKUPS"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
refute gen_smtp_config[:no_mx_lookups]
end
test "sets no_mx_lookups true from System when specified" do
System.put_env("NO_MX_LOOKUPS", "true")
config =
SMTPAdapter.handle_config(configuration(%{no_mx_lookups: {:system, "NO_MX_LOOKUPS"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:no_mx_lookups]
end
test "deliver raises an exception when username and password configuration are required" do
bamboo_email = new_email()
bamboo_config =
configuration(%{
username: nil,
password: nil,
auth: :always
})
assert_raise SMTPAdapter.SMTPError, ~r/no_credentials/, fn ->
SMTPAdapter.deliver(bamboo_email, bamboo_config)
end
try do
SMTPAdapter.deliver(bamboo_email, bamboo_config)
rescue
error in SMTPAdapter.SMTPError ->
assert {:no_credentials, "Username and password were not provided for authentication."} =
error.raw
end
end
test "deliver is successful when username and password are required and present" do
bamboo_email = new_email()
bamboo_config =
configuration(%{
username: "a",
password: "b",
auth: :always
})
assert {:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
end
test "deliver is successful when username and password configuration are not required" do
bamboo_email = new_email()
bamboo_config =
configuration(%{
username: nil,
password: nil,
auth: :if_available
})
assert {:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
end
test "deliver raises an exception when server configuration is wrong" do
bamboo_email = new_email()
bamboo_config = configuration(%{server: "wrong.smtp.domain"})
assert_raise SMTPAdapter.SMTPError, ~r/network_failure/, fn ->
SMTPAdapter.deliver(bamboo_email, bamboo_config)
end
try do
SMTPAdapter.deliver(bamboo_email, bamboo_config)
rescue
error ->
assert {:retries_exceeded, _detail} = error.raw
end
end
test "sets default auth key if not present" do
%{auth: auth} = SMTPAdapter.handle_config(configuration())
assert :if_available == auth
end
test "doesn't set a default auth key if present" do
%{auth: auth} = SMTPAdapter.handle_config(configuration(%{auth: :always}))
assert :always == auth
end
test "sets auth if_available from System when specified" do
System.put_env("AUTH", "if_available")
config = SMTPAdapter.handle_config(configuration(%{auth: {:system, "AUTH"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:auth] == :if_available
end
test "sets auth always from System when specified" do
System.put_env("AUTH", "always")
config = SMTPAdapter.handle_config(configuration(%{auth: {:system, "AUTH"}}))
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(new_email(), config)
[{{_from, _to, _raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert gen_smtp_config[:auth] == :always
end
test "emails raise an exception when email can't be sent" do
bamboo_email = new_email(from: {"Wrong User", "wrong@user.com"})
bamboo_config = configuration()
assert_raise SMTPAdapter.SMTPError, ~r/554 Message rejected/, fn ->
SMTPAdapter.deliver(bamboo_email, bamboo_config)
end
try do
SMTPAdapter.deliver(bamboo_email, bamboo_config)
rescue
error ->
assert {:no_more_hosts, _detail} = error.raw
end
end
test "emails looks fine when only text body is set" do
bamboo_email = new_email(text_body: nil)
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{from, to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
[multipart_header] =
Regex.run(
~r{Content-Type: multipart/alternative; boundary="([^"]+)"\r\n},
raw_email,
capture: :all_but_first
)
assert format_email_as_string(bamboo_email.from, false) == from
assert format_email(bamboo_email.to ++ bamboo_email.cc ++ bamboo_email.bcc, false) == to
rfc822_subject = "Subject: =?UTF-8?B?Hello from Bamboo?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
assert String.contains?(raw_email, "From: #{format_email_as_string(bamboo_email.from)}\r\n")
assert String.contains?(raw_email, "To: #{format_email_as_string(bamboo_email.to)}\r\n")
assert String.contains?(raw_email, "Cc: #{format_email_as_string(bamboo_email.cc)}\r\n")
assert String.contains?(raw_email, "Bcc: #{format_email_as_string(bamboo_email.bcc)}\r\n")
assert String.contains?(raw_email, "Reply-To: reply@doe.com\r\n")
assert String.contains?(raw_email, "MIME-Version: 1.0\r\n")
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/html;charset=UTF-8\r\n" <>
"Content-Transfer-Encoding: base64\r\n" <>
"\r\n" <>
"#{SMTPAdapter.base64_and_split(bamboo_email.html_body)}\r\n"
)
refute String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/plain;charset=UTF-8\r\n" <>
"\r\n"
)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "email is sent when subject is not set" do
bamboo_email = new_email(subject: nil)
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{_from, _to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
rfc822_subject = "Subject: \r\n"
assert String.contains?(raw_email, rfc822_subject)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "emails looks fine when only HTML body is set" do
bamboo_email = new_email(html_body: nil)
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{from, to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
[multipart_header] =
Regex.run(
~r{Content-Type: multipart/alternative; boundary="([^"]+)"\r\n},
raw_email,
capture: :all_but_first
)
assert format_email_as_string(bamboo_email.from, false) == from
assert format_email(bamboo_email.to ++ bamboo_email.cc ++ bamboo_email.bcc, false) == to
rfc822_subject = "Subject: =?UTF-8?B?Hello from Bamboo?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
assert String.contains?(raw_email, "From: #{format_email_as_string(bamboo_email.from)}\r\n")
assert String.contains?(raw_email, "To: #{format_email_as_string(bamboo_email.to)}\r\n")
assert String.contains?(raw_email, "Cc: #{format_email_as_string(bamboo_email.cc)}\r\n")
assert String.contains?(raw_email, "Bcc: #{format_email_as_string(bamboo_email.bcc)}\r\n")
assert String.contains?(raw_email, "Reply-To: reply@doe.com\r\n")
assert String.contains?(raw_email, "MIME-Version: 1.0\r\n")
refute String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/html;charset=UTF-8\r\n" <>
"\r\n"
)
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/plain;charset=UTF-8\r\n" <>
"\r\n" <>
"#{bamboo_email.text_body}\r\n"
)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "emails looks fine when text and HTML bodys are sets" do
bamboo_email = new_email()
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{from, to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
[multipart_header] =
Regex.run(
~r{Content-Type: multipart/alternative; boundary="([^"]+)"\r\n},
raw_email,
capture: :all_but_first
)
assert format_email_as_string(bamboo_email.from, false) == from
assert format_email(bamboo_email.to ++ bamboo_email.cc ++ bamboo_email.bcc, false) == to
rfc822_subject = "Subject: =?UTF-8?B?Hello from Bamboo?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
assert String.contains?(raw_email, "From: #{format_email_as_string(bamboo_email.from)}\r\n")
assert String.contains?(raw_email, "To: #{format_email_as_string(bamboo_email.to)}\r\n")
assert String.contains?(raw_email, "Cc: #{format_email_as_string(bamboo_email.cc)}\r\n")
assert String.contains?(raw_email, "Bcc: #{format_email_as_string(bamboo_email.bcc)}\r\n")
assert String.contains?(raw_email, "Reply-To: reply@doe.com\r\n")
assert String.contains?(raw_email, "MIME-Version: 1.0\r\n")
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/html;charset=UTF-8\r\n" <>
"Content-Transfer-Encoding: base64\r\n" <>
"\r\n" <>
"#{SMTPAdapter.base64_and_split(bamboo_email.html_body)}\r\n"
)
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/plain;charset=UTF-8\r\n" <>
"\r\n" <>
"#{bamboo_email.text_body}\r\n"
)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "email looks fine when no bcc: is set" do
bamboo_email = new_email(bcc: [])
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{from, to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
[multipart_header] =
Regex.run(
~r{Content-Type: multipart/alternative; boundary="([^"]+)"\r\n},
raw_email,
capture: :all_but_first
)
assert format_email_as_string(bamboo_email.from, false) == from
assert format_email(bamboo_email.to ++ bamboo_email.cc ++ bamboo_email.bcc, false) == to
rfc822_subject = "Subject: =?UTF-8?B?Hello from Bamboo?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
assert String.contains?(raw_email, "From: #{format_email_as_string(bamboo_email.from)}\r\n")
assert String.contains?(raw_email, "To: #{format_email_as_string(bamboo_email.to)}\r\n")
assert String.contains?(raw_email, "Cc: #{format_email_as_string(bamboo_email.cc)}\r\n")
refute String.contains?(raw_email, "Bcc: #{format_email_as_string(bamboo_email.bcc)}\r\n")
assert String.contains?(raw_email, "Reply-To: reply@doe.com\r\n")
assert String.contains?(raw_email, "MIME-Version: 1.0\r\n")
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/html;charset=UTF-8\r\n" <>
"Content-Transfer-Encoding: base64\r\n" <>
"\r\n" <>
"#{SMTPAdapter.base64_and_split(bamboo_email.html_body)}\r\n"
)
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/plain;charset=UTF-8\r\n" <>
"\r\n"
)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "email looks fine when no cc: is set" do
bamboo_email = new_email(cc: [])
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{from, to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
[multipart_header] =
Regex.run(
~r{Content-Type: multipart/alternative; boundary="([^"]+)"\r\n},
raw_email,
capture: :all_but_first
)
assert format_email_as_string(bamboo_email.from, false) == from
assert format_email(bamboo_email.to ++ bamboo_email.cc ++ bamboo_email.bcc, false) == to
rfc822_subject = "Subject: =?UTF-8?B?Hello from Bamboo?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
assert String.contains?(raw_email, "From: #{format_email_as_string(bamboo_email.from)}\r\n")
assert String.contains?(raw_email, "To: #{format_email_as_string(bamboo_email.to)}\r\n")
refute String.contains?(raw_email, "Cc: #{format_email_as_string(bamboo_email.cc)}\r\n")
assert String.contains?(raw_email, "Bcc: #{format_email_as_string(bamboo_email.bcc)}\r\n")
assert String.contains?(raw_email, "Reply-To: reply@doe.com\r\n")
assert String.contains?(raw_email, "MIME-Version: 1.0\r\n")
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/html;charset=UTF-8\r\n" <>
"Content-Transfer-Encoding: base64\r\n" <>
"\r\n" <>
"#{SMTPAdapter.base64_and_split(bamboo_email.html_body)}\r\n"
)
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/plain;charset=UTF-8\r\n" <>
"\r\n"
)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "email looks fine when they have non-ASCII characters in subject, from and to" do
bamboo_email =
new_email(
from: {"Awesome Person 😎", "awesome@person.local"},
to: {"Person Awesome 🤩", "person@awesome.local"},
subject: "Hello! 👋"
)
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{from, to, raw_email}, gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
[multipart_header] =
Regex.run(
~r{Content-Type: multipart/alternative; boundary="([^"]+)"\r\n},
raw_email,
capture: :all_but_first
)
assert format_email_as_string(bamboo_email.from, false) == from
assert format_email(bamboo_email.to ++ bamboo_email.cc ++ bamboo_email.bcc, false) == to
rfc822_subject = "Subject: =?UTF-8?B?SGVsbG8hIPCfkYs=?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
assert String.contains?(raw_email, "From: #{format_email_as_string(bamboo_email.from)}\r\n")
assert String.contains?(raw_email, "To: #{format_email_as_string(bamboo_email.to)}\r\n")
assert String.contains?(raw_email, "Cc: #{format_email_as_string(bamboo_email.cc)}\r\n")
assert String.contains?(raw_email, "Bcc: #{format_email_as_string(bamboo_email.bcc)}\r\n")
assert String.contains?(raw_email, "Reply-To: reply@doe.com\r\n")
assert String.contains?(raw_email, "MIME-Version: 1.0\r\n")
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/html;charset=UTF-8\r\n" <>
"Content-Transfer-Encoding: base64\r\n" <>
"\r\n" <>
"#{SMTPAdapter.base64_and_split(bamboo_email.html_body)}\r\n"
)
assert String.contains?(
raw_email,
"--#{multipart_header}\r\n" <>
"Content-Type: text/plain;charset=UTF-8\r\n" <>
"\r\n"
)
assert_configuration(bamboo_config, gen_smtp_config)
end
test "email have a Content-ID properly set when attaching files with content_id" do
bamboo_email =
new_email()
|> Bamboo.Email.put_attachment(Path.absname("test/attachments/attachment_one.txt"),
content_id: "12345"
)
|> Bamboo.Email.put_attachment(Path.absname("test/attachments/attachment_two.txt"),
content_id: "54321"
)
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
assert 1 = length(FakeGenSMTP.fetch_sent_emails())
[{{_from, _to, raw_email}, _gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
assert Regex.run(~r{Content-ID: <12345>\r\n}, raw_email, capture: :all_but_first)
assert Regex.run(~r{Content-ID: <54321>\r\n}, raw_email, capture: :all_but_first)
end
test "check rfc822 encoding for subject" do
bamboo_email =
@email_in_utf8
|> Email.new_email()
|> Bamboo.Mailer.normalize_addresses()
bamboo_config = configuration()
{:ok, "200 Ok 1234567890"} = SMTPAdapter.deliver(bamboo_email, bamboo_config)
[{{_from, _to, raw_email}, _gen_smtp_config}] = FakeGenSMTP.fetch_sent_emails()
rfc822_subject = "Subject: =?UTF-8?B?5pel5pys6Kqe44Gu772T772V772C772K772F772D772U?=\r\n"
assert String.contains?(raw_email, rfc822_subject)
end
defp format_email(emails), do: format_email(emails, true)
defp format_email({name, email}, true), do: "#{rfc822_encode(name)} <#{email}>"
defp format_email({_name, email}, false), do: email
defp format_email(emails, format) when is_list(emails) do
emails |> Enum.map(&format_email_as_string(&1, format))
end
defp format_email_as_string(emails) when is_list(emails) do
emails |> format_email |> Enum.join(", ")
end
defp format_email_as_string(email, format \\ true) do
format_email(email, format)
end
defp rfc822_encode(content) do
if contains_only_ascii_characters?(content) do
"=?UTF-8?B?#{content}?="
else
"=?UTF-8?B?#{Base.encode64(content)}?="
end
end
defp contains_only_ascii_characters?(content) do
content
|> String.to_charlist()
|> List.ascii_printable?()
end
defp assert_configuration(bamboo_config, gen_smtp_config) do
assert bamboo_config[:server] == gen_smtp_config[:relay]
assert bamboo_config[:port] == gen_smtp_config[:port]
assert bamboo_config[:hostname] == gen_smtp_config[:hostname]
assert bamboo_config[:username] == gen_smtp_config[:username]
assert bamboo_config[:password] == gen_smtp_config[:password]
assert bamboo_config[:tls] == gen_smtp_config[:tls]
assert bamboo_config[:ssl] == gen_smtp_config[:ssl]
assert bamboo_config[:retries] == gen_smtp_config[:retries]
assert bamboo_config[:no_mx_lookups] == gen_smtp_config[:no_mx_lookups]
end
defp configuration(override \\ %{}), do: Map.merge(@configuration, override)
defp new_email(override \\ []) do
@email
|> Keyword.merge(override)
|> Email.new_email()
|> Bamboo.Mailer.normalize_addresses()
end
end
| 33.692588 | 97 | 0.657326 |
08b9cf42a69d4407995a73354571585df36ccc98 | 401 | exs | Elixir | test/repo_test.exs | jcarlos7121/ex_admin | 60a07320efaf549814d29f3593715543aef51e6b | [
"MIT"
] | 1,347 | 2015-10-05T18:23:49.000Z | 2022-01-09T18:38:36.000Z | test/repo_test.exs | leonardzhou/ex_admin | c241e956503c548a472e3ee89751e64a16477638 | [
"MIT"
] | 402 | 2015-10-03T13:53:32.000Z | 2021-07-08T09:52:22.000Z | test/repo_test.exs | leonardzhou/ex_admin | c241e956503c548a472e3ee89751e64a16477638 | [
"MIT"
] | 333 | 2015-10-12T22:56:57.000Z | 2021-05-26T18:40:24.000Z | defmodule ExAdmin.RepoTest do
use ExUnit.Case
require Logger
defmodule Schema do
defstruct id: 0, name: nil
end
defmodule Schema2 do
defstruct id: 0, field: nil
end
defmodule Cs1 do
defstruct model: nil, changes: %{}
end
defmodule Cs2 do
defstruct data: nil, changes: %{}
end
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(TestExAdmin.Repo)
end
end
| 16.04 | 62 | 0.680798 |
08b9e5bb54ce91cc02691b4c33af50917bb8b414 | 487 | ex | Elixir | lib/pongo_web/views/error_view.ex | cristianberneanu/pongo | c158d32981deebbc09c70bd1568c4e5fca4df226 | [
"MIT"
] | 2 | 2020-09-21T12:13:35.000Z | 2020-09-21T14:58:28.000Z | lib/pongo_web/views/error_view.ex | cristianberneanu/pongo | c158d32981deebbc09c70bd1568c4e5fca4df226 | [
"MIT"
] | null | null | null | lib/pongo_web/views/error_view.ex | cristianberneanu/pongo | c158d32981deebbc09c70bd1568c4e5fca4df226 | [
"MIT"
] | null | null | null | defmodule PongoWeb.ErrorView do
use PongoWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 28.647059 | 61 | 0.73306 |
08b9f7d145f24dd32d7fa13326f88ff8d8d4e06a | 1,758 | ex | Elixir | clients/memcache/lib/google_api/memcache/v1beta2/model/update_parameters_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/memcache/lib/google_api/memcache/v1beta2/model/update_parameters_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/memcache/lib/google_api/memcache/v1beta2/model/update_parameters_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Memcache.V1beta2.Model.UpdateParametersRequest do
@moduledoc """
Request for UpdateParameters.
## Attributes
* `parameters` (*type:* `GoogleApi.Memcache.V1beta2.Model.MemcacheParameters.t`, *default:* `nil`) - The parameters to apply to the instance.
* `updateMask` (*type:* `String.t`, *default:* `nil`) - Required. Mask of fields to update.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:parameters => GoogleApi.Memcache.V1beta2.Model.MemcacheParameters.t(),
:updateMask => String.t()
}
field(:parameters, as: GoogleApi.Memcache.V1beta2.Model.MemcacheParameters)
field(:updateMask)
end
defimpl Poison.Decoder, for: GoogleApi.Memcache.V1beta2.Model.UpdateParametersRequest do
def decode(value, options) do
GoogleApi.Memcache.V1beta2.Model.UpdateParametersRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Memcache.V1beta2.Model.UpdateParametersRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.16 | 145 | 0.745165 |
08b9ffa22f6c6777cce672d2c8fa1917b292f2e0 | 816 | ex | Elixir | lib/meeseeks/selector/xpath/expr/boolean.ex | RichMorin/meeseeks | d52a15a0b78acfc4d7b979d1df6e146482dc3a10 | [
"Apache-2.0",
"MIT"
] | 291 | 2017-03-27T15:53:36.000Z | 2022-03-14T23:01:42.000Z | lib/meeseeks/selector/xpath/expr/boolean.ex | RichMorin/meeseeks | d52a15a0b78acfc4d7b979d1df6e146482dc3a10 | [
"Apache-2.0",
"MIT"
] | 70 | 2017-03-30T23:32:34.000Z | 2021-06-27T06:26:28.000Z | lib/meeseeks/selector/xpath/expr/boolean.ex | RichMorin/meeseeks | d52a15a0b78acfc4d7b979d1df6e146482dc3a10 | [
"Apache-2.0",
"MIT"
] | 23 | 2017-06-18T10:29:04.000Z | 2021-11-04T13:08:12.000Z | defmodule Meeseeks.Selector.XPath.Expr.Boolean do
use Meeseeks.Selector.XPath.Expr
@moduledoc false
alias Meeseeks.Selector.XPath.Expr
defstruct op: nil, e1: nil, e2: nil
@impl true
def eval(%Expr.Boolean{op: :or} = expr, node, document, context) do
v1 =
Expr.eval(expr.e1, node, document, context)
|> Expr.Helpers.boolean(document)
if v1 do
true
else
Expr.eval(expr.e2, node, document, context)
|> Expr.Helpers.boolean(document)
end
end
def eval(%Expr.Boolean{op: :and} = expr, node, document, context) do
v1 =
Expr.eval(expr.e1, node, document, context)
|> Expr.Helpers.boolean(document)
if v1 do
Expr.eval(expr.e2, node, document, context)
|> Expr.Helpers.boolean(document)
else
false
end
end
end
| 22.666667 | 70 | 0.644608 |
08ba37a5e278986eee51d084acb3fa78f29e7306 | 1,235 | ex | Elixir | clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/list_debuggees_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/list_debuggees_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/list_debuggees_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.CloudDebugger.V2.Model.ListDebuggeesResponse do
@moduledoc """
Response for listing debuggees.
"""
@derive [Poison.Encoder]
defstruct [
:"debuggees"
]
end
defimpl Poison.Decoder, for: GoogleApi.CloudDebugger.V2.Model.ListDebuggeesResponse do
import GoogleApi.CloudDebugger.V2.Deserializer
def decode(value, options) do
value
|> deserialize(:"debuggees", :list, GoogleApi.CloudDebugger.V2.Model.Debuggee, options)
end
end
| 31.666667 | 91 | 0.757895 |
08ba603be2be7a37c05b64f8b708bdd0000a8e25 | 136 | exs | Elixir | plugins/one_pages/mix.exs | smpallen99/ucx_ucc | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 11 | 2017-05-15T18:35:05.000Z | 2018-02-05T18:27:40.000Z | plugins/one_pages/mix.exs | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 15 | 2017-11-27T10:38:05.000Z | 2018-02-09T20:42:08.000Z | plugins/one_pages/mix.exs | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 4 | 2017-09-13T11:34:16.000Z | 2018-02-26T13:37:06.000Z | defmodule OnePages.Mixfile do
use Mix.Project
def project do
[
app: :one_pages,
version: "0.0.1",
]
end
end
| 11.333333 | 29 | 0.580882 |
08ba618432ae46fa6501cb02e2adddfef6860b7b | 69 | ex | Elixir | examples/phoenix_shell/web/views/page_view.ex | acj/parley | 56b5c7b34f39c74af6ccd4a85a23ceccfc117bdf | [
"MIT"
] | 1 | 2021-07-02T22:50:40.000Z | 2021-07-02T22:50:40.000Z | examples/phoenix_shell/web/views/page_view.ex | acj/parley | 56b5c7b34f39c74af6ccd4a85a23ceccfc117bdf | [
"MIT"
] | null | null | null | examples/phoenix_shell/web/views/page_view.ex | acj/parley | 56b5c7b34f39c74af6ccd4a85a23ceccfc117bdf | [
"MIT"
] | null | null | null | defmodule PhoenixShell.PageView do
use PhoenixShell.Web, :view
end
| 17.25 | 34 | 0.811594 |
08baa75e8e3d33e7b157a3e71a0c34f03248b5e9 | 2,988 | exs | Elixir | test/unit/discovery_api_web/utilities/geojson_utils_test.exs | folkengine/discovery_api | 0bb7a0aff4603a4f7532cc65ca8c8dbb37a57217 | [
"Apache-2.0"
] | null | null | null | test/unit/discovery_api_web/utilities/geojson_utils_test.exs | folkengine/discovery_api | 0bb7a0aff4603a4f7532cc65ca8c8dbb37a57217 | [
"Apache-2.0"
] | null | null | null | test/unit/discovery_api_web/utilities/geojson_utils_test.exs | folkengine/discovery_api | 0bb7a0aff4603a4f7532cc65ca8c8dbb37a57217 | [
"Apache-2.0"
] | null | null | null | defmodule DiscoveryApiWeb.Utilities.GeojsonUtilsTest do
use ExUnit.Case
use Placebo
import Checkov
require Logger
alias DiscoveryApiWeb.Utilities.GeojsonUtils
describe("calculate_bounding_box/1") do
data_test "calculates bounding box for #{geometry_type}" do
Logger.debug("Testing #{geometry_type}")
features = [
%{"geometry" => %{"coordinates" => coordinates}}
]
bounding_box = GeojsonUtils.calculate_bounding_box(features)
assert bounding_box == expected_bounding_box
where([
[:geometry_type, :coordinates, :expected_bounding_box],
["point", [[1, 0]], [1, 0, 1, 0]],
["line", [[1, 0], [2, 0], [2, 1]], [1, 0, 2, 1]],
[
"polygon",
[[[1, 1], [1, 0], [0, 1], [1, 1]], [[3, 3], [3, 2], [2, 3], [3, 3]]],
[0, 0, 3, 3]
],
[
"multiline string",
[
[[10, 10], [20, 20], [10, 40]],
[[40, 40], [30, 30], [40, 20], [30, 10]]
],
[10, 10, 40, 40]
],
["empty coordinates", [], nil]
])
end
test "the bounding box of a list of polygons is calculated" do
features = [
%{
"geometry" => %{
"coordinates" => [[[-1, 8], [4, 8], [4, 13], [-1, 13], [-1, 8]]]
}
},
%{
"geometry" => %{
"coordinates" => [[[-7, 12], [-12, 11], [-9, 8], [-3, 10], [-7, 12]]]
}
}
]
bounding_box = GeojsonUtils.calculate_bounding_box(features)
assert bounding_box == [-12, 8, 4, 13]
end
test "the bounding box of a list of features where one has no coordinates is not nil" do
features = [
%{
"geometry" => %{
"coordinates" => []
}
},
%{
"geometry" => %{
"coordinates" => [[1, 0]]
}
}
]
bounding_box = GeojsonUtils.calculate_bounding_box(features)
assert bounding_box == [1, 0, 1, 0]
end
test "the bounding box of a single feature with a one-dimensional point does not raise an error" do
feature = %{
"geometry" => %{
"coordinates" => [-1, 0]
}
}
bounding_box = GeojsonUtils.calculate_bounding_box(feature)
assert bounding_box == [-1, 0, -1, 0]
end
data_test "throws an exception when feature has #{error_reason}" do
Logger.debug("Testing #{error_reason}")
features = [%{"geometry" => %{"coordinates" => coordinates}}]
assert_raise MalformedGeometryError, fn ->
GeojsonUtils.calculate_bounding_box(features)
end
where([
[:error_reason, :coordinates],
["malformed geometry", [[[-1, "a"], [4, 8], [4, 13], [-1, 13], [-1, 8]]]],
["null coordinate axes", [[[-1, nil], [4, 8], [4, 13], [nil, 13], [-1, 8]]]],
["missing coordinate axes", [[[-1], [4, 8], [4, 13], [13], [-1, 8]]]]
])
end
end
end
| 27.666667 | 103 | 0.494311 |
08babcbc85957ee40aaf789f1ae7bbf5e93137fa | 1,373 | exs | Elixir | config/config.exs | arpnetwork/dapp_demo | ff87809625ae6053378ddffd63e27c6225d93370 | [
"Apache-2.0"
] | null | null | null | config/config.exs | arpnetwork/dapp_demo | ff87809625ae6053378ddffd63e27c6225d93370 | [
"Apache-2.0"
] | null | null | null | config/config.exs | arpnetwork/dapp_demo | ff87809625ae6053378ddffd63e27c6225d93370 | [
"Apache-2.0"
] | 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 your application as:
#
# config :dapp_demo, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:dapp_demo, :key)
#
# You can also 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"
import_config "#{Mix.env()}.exs"
config :dapp_demo,
data_dir: System.user_home() |> Path.join(".dapp_demo"),
port: 8080,
eth_node: nil,
amount: nil,
price: nil,
app_list: nil,
ip: nil,
keystore_file: nil,
min_idle_device: nil
| 31.204545 | 73 | 0.736344 |
08bae6ede1c54ea586e10379332d5bceb8690709 | 1,359 | ex | Elixir | lib/new_relic/aggregate/reporter.ex | tpitale/elixir_agent | f356b588fe9d7cc3b9db00d9a251e009a20b3e0e | [
"Apache-2.0"
] | 227 | 2018-09-05T15:33:23.000Z | 2022-02-25T18:12:06.000Z | lib/new_relic/aggregate/reporter.ex | tpitale/elixir_agent | f356b588fe9d7cc3b9db00d9a251e009a20b3e0e | [
"Apache-2.0"
] | 211 | 2018-09-05T21:42:41.000Z | 2022-03-25T17:51:56.000Z | lib/new_relic/aggregate/reporter.ex | tpitale/elixir_agent | f356b588fe9d7cc3b9db00d9a251e009a20b3e0e | [
"Apache-2.0"
] | 84 | 2018-09-05T04:26:26.000Z | 2022-03-09T14:28:14.000Z | defmodule NewRelic.Aggregate.Reporter do
use GenServer
alias NewRelic.Aggregate
# This GenServer collects aggregate metric measurements, aggregates them,
# and reports them to the Harvester at the defined sample_cycle
@moduledoc false
def start_link(_) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
def init(:ok) do
NewRelic.sample_process()
if NewRelic.Config.enabled?(), do: send(self(), :report)
{:ok, %{}}
end
def report_aggregate(meta, values), do: GenServer.cast(__MODULE__, {:aggregate, meta, values})
def handle_cast({:aggregate, meta, values}, state) do
metric =
state
|> Map.get(meta, %Aggregate{meta: meta})
|> Aggregate.merge(values)
{:noreply, Map.put(state, meta, metric)}
end
def handle_info(:report, state) do
record_aggregates(state)
Process.send_after(self(), :report, NewRelic.Sampler.Reporter.sample_cycle())
{:noreply, %{}}
end
def handle_call(:report, _from, state) do
record_aggregates(state)
{:reply, :ok, %{}}
end
def record_aggregates(state) do
Enum.map(state, fn {_meta, metric} ->
NewRelic.report_custom_event(aggregate_event_type(), Aggregate.annotate(metric))
end)
end
def aggregate_event_type,
do: Application.get_env(:new_relic_agent, :aggregate_event_type, "ElixirAggregate")
end
| 26.647059 | 96 | 0.699043 |
08bafee76ebaa543210cb8055dc23273322aaeec | 69 | ex | Elixir | lib/ninescraft_web/views/layout_view.ex | drobertduke/ninescraft | 00a08e4f3433b1ffd8f0a8dc77927d043b4e3ce8 | [
"Apache-2.0"
] | null | null | null | lib/ninescraft_web/views/layout_view.ex | drobertduke/ninescraft | 00a08e4f3433b1ffd8f0a8dc77927d043b4e3ce8 | [
"Apache-2.0"
] | null | null | null | lib/ninescraft_web/views/layout_view.ex | drobertduke/ninescraft | 00a08e4f3433b1ffd8f0a8dc77927d043b4e3ce8 | [
"Apache-2.0"
] | null | null | null | defmodule NinescraftWeb.LayoutView do
use NinescraftWeb, :view
end
| 17.25 | 37 | 0.826087 |
08bb1ba4a2636e5c5cca1d9c102f59701ba6afe1 | 261 | ex | Elixir | test/support/application.ex | blockfi/pg_ranges | d61f51323169fb10706fe61d902dec4b3f42595b | [
"MIT"
] | null | null | null | test/support/application.ex | blockfi/pg_ranges | d61f51323169fb10706fe61d902dec4b3f42595b | [
"MIT"
] | null | null | null | test/support/application.ex | blockfi/pg_ranges | d61f51323169fb10706fe61d902dec4b3f42595b | [
"MIT"
] | null | null | null | defmodule PgRanges.Application do
@moduledoc false
use Application
def start(_type, _args) do
children = [
PgRanges.Repo
]
opts = [strategy: :one_for_one, name: PgRanges.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 17.4 | 62 | 0.693487 |
08bb45f36a4c224a95afc735d294ebb9ffe0685c | 1,865 | ex | Elixir | apps/omg_watcher/lib/web/views/utxo.ex | Pongch/elixir-omg | 8a33c246898b49cba62b847e0989d9b6c89f5106 | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher/lib/web/views/utxo.ex | Pongch/elixir-omg | 8a33c246898b49cba62b847e0989d9b6c89f5106 | [
"Apache-2.0"
] | null | null | null | apps/omg_watcher/lib/web/views/utxo.ex | Pongch/elixir-omg | 8a33c246898b49cba62b847e0989d9b6c89f5106 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.Watcher.Web.View.Utxo do
@moduledoc """
The utxo view for rendering json
"""
use OMG.Watcher.Web, :view
alias OMG.Watcher.DB.EthEventDB
alias OMG.Watcher.DB.TransactionDB
alias OMG.Watcher.DB.TxOutputDB
alias OMG.Watcher.Web.Serializer
def render("utxo_exit.json", %{utxo_exit: utxo_exit}) do
utxo_exit
|> Serializer.Response.serialize(:success)
end
def render("utxos.json", %{utxos: utxos}) do
utxos
|> Enum.map(&to_view/1)
|> Serializer.Response.serialize(:success)
end
defp get_position(
%TransactionDB{blknum: blknum, txindex: txindex},
deposit
)
when is_nil(deposit) do
{blknum, txindex}
end
defp get_position(
tx,
%EthEventDB{deposit_blknum: blknum, deposit_txindex: txindex}
)
when is_nil(tx) do
{blknum, txindex}
end
defp to_view(%TxOutputDB{
amount: amount,
currency: currency,
creating_tx_oindex: oindex,
creating_transaction: tx,
deposit: deposit
}) do
{blknum, txindex} = get_position(tx, deposit)
%{
amount: amount,
currency: currency,
blknum: blknum,
txindex: txindex,
oindex: oindex,
txbytes: tx && tx.txbytes
}
end
end
| 25.547945 | 74 | 0.669705 |
08bb4cf3ddc23872edb25935e1a53c80fadd19b5 | 4,858 | ex | Elixir | lib/oli_web/live/sections/overview_view.ex | AnkitKadamATS/oli-torus | 3f9d5e8d568684b28d2ed65e17f796ae4c27c072 | [
"MIT"
] | null | null | null | lib/oli_web/live/sections/overview_view.ex | AnkitKadamATS/oli-torus | 3f9d5e8d568684b28d2ed65e17f796ae4c27c072 | [
"MIT"
] | null | null | null | lib/oli_web/live/sections/overview_view.ex | AnkitKadamATS/oli-torus | 3f9d5e8d568684b28d2ed65e17f796ae4c27c072 | [
"MIT"
] | 1 | 2021-10-30T05:58:19.000Z | 2021-10-30T05:58:19.000Z | defmodule OliWeb.Sections.OverviewView do
use Surface.LiveView, layout: {OliWeb.LayoutView, "live.html"}
alias Oli.Repo.{Paging, Sorting}
alias OliWeb.Common.{Breadcrumb}
alias OliWeb.Common.Properties.{Groups, Group, ReadOnly}
alias Oli.Delivery.Sections.{EnrollmentBrowseOptions}
alias OliWeb.Router.Helpers, as: Routes
alias Oli.Delivery.Sections
alias OliWeb.Sections.{Instructors, UnlinkSection}
alias OliWeb.Sections.Mount
prop user, :any
data breadcrumbs, :any
data title, :string, default: "Section Details"
data section, :any, default: nil
data instructors, :list, default: []
data updates_count, :integer
def set_breadcrumbs(:admin, section) do
OliWeb.Sections.SectionsView.set_breadcrumbs()
|> breadcrumb(section)
end
def set_breadcrumbs(:user, section) do
breadcrumb([], section)
end
def breadcrumb(previous, section) do
previous ++
[
Breadcrumb.new(%{
full_title: "Section Overview",
link: Routes.live_path(OliWeb.Endpoint, __MODULE__, section.slug)
})
]
end
def mount(%{"section_slug" => section_slug}, session, socket) do
case Mount.for(section_slug, session) do
{:error, e} ->
Mount.handle_error(socket, {:error, e})
{type, user, section} ->
updates_count =
Sections.check_for_available_publication_updates(section)
|> Enum.count()
{:ok,
assign(socket,
is_admin: Mount.is_lms_or_system_admin?(user, section),
breadcrumbs: set_breadcrumbs(type, section),
instructors: fetch_instructors(section),
user: user,
section: section,
updates_count: updates_count
)}
end
end
defp fetch_instructors(section) do
Sections.browse_enrollments(
section,
%Paging{offset: 0, limit: 50},
%Sorting{direction: :asc, field: :name},
%EnrollmentBrowseOptions{
is_student: false,
is_instructor: true,
text_search: nil
}
)
end
def render(assigns) do
~F"""
<Groups>
<Group label="Overview" description="Overview of this course section">
<ReadOnly label="Title" value={@section.title}/>
<ReadOnly label="Course Section Type" value={type_to_string(@section)}/>
</Group>
<Group label="Instructors" description="Manage the users with instructor level access">
<Instructors users={@instructors}/>
</Group>
<Group label="Curriculum" description="Manage the content delivered to students">
<ul class="link-list">
<li><a href={Routes.page_delivery_path(OliWeb.Endpoint, :index, @section.slug)}>Enter Course</a></li>
<li><a href={Routes.live_path(OliWeb.Endpoint, OliWeb.Delivery.RemixSection, @section.slug)}>Customize Curriculum</a></li>
<li>
<a disabled={@updates_count == 0} href={Routes.page_delivery_path(OliWeb.Endpoint, :updates, @section.slug)}>
Manage Updates
{#if @updates_count > 0}
<span class="badge badge-primary">{@updates_count} available</span>
{/if}
</a>
</li>
</ul>
</Group>
<Group label="Manage" description="Manage all aspects of course delivery">
<ul class="link-list">
<li><a href={Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.EnrollmentsView, @section.slug)}>View Enrolled Students</a></li>
<li><a href={Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.EditView, @section.slug)}>Edit Section Details</a></li>
</ul>
</Group>
<Group label="Grading" description="View and manage student grades and progress">
<ul class="link-list">
<li><a href={Routes.live_path(OliWeb.Endpoint, OliWeb.Grades.GradebookView, @section.slug)}>View Grades</a></li>
<li><a href={Routes.page_delivery_path(OliWeb.Endpoint, :export_gradebook, @section.slug)}>Download Gradebook as <code>.csv</code> file</a></li>
{#if !@section.open_and_free}
<li><a href={Routes.live_path(OliWeb.Endpoint, OliWeb.Grades.GradesLive, @section.slug)}>Manage LMS Gradebook</a></li>
{/if}
</ul>
</Group>
{#if @is_admin and !@section.open_and_free}
<Group label="LMS Admin" description="Administrator LMS Connection">
<UnlinkSection unlink="unlink" section={@section}/>
</Group>
{/if}
</Groups>
"""
end
defp type_to_string(section) do
case section.open_and_free do
true -> "LMS-Lite"
_ -> "LTI"
end
end
def handle_event("unlink", _, socket) do
%{section: section} = socket.assigns
{:ok, _deleted} = Oli.Delivery.Sections.soft_delete_section(section)
{:noreply, push_redirect(socket, to: Routes.delivery_path(socket, :index))}
end
end
| 35.202899 | 154 | 0.640387 |
08bb525e996ab59f73f863f30c0673d05d43f1e1 | 387 | ex | Elixir | lib/apus/application.ex | deniskulicek/apus | be40b09a5507a56feee87d98d68d8720826f5bda | [
"MIT"
] | null | null | null | lib/apus/application.ex | deniskulicek/apus | be40b09a5507a56feee87d98d68d8720826f5bda | [
"MIT"
] | null | null | null | lib/apus/application.ex | deniskulicek/apus | be40b09a5507a56feee87d98d68d8720826f5bda | [
"MIT"
] | null | null | null | defmodule Apus.Application do
@moduledoc false
use Application
def start(_type, _args) do
children = [
%{id: Apus.SentMessages, start: {Apus.SentMessages, :start_link, []}},
{Task.Supervisor, name: Apus.TaskSupervisorStrategy.supervisor_name()}
]
opts = [strategy: :one_for_one, name: Apus.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 24.1875 | 76 | 0.69509 |
08bb58779dc1857cee8cccffd7cdeada92f297bf | 712 | exs | Elixir | priv/repo/migrations/20201229220716_move_tag_checks_into_database.exs | CyberFlameGO/bolt | 225e6276983bec646e7f13519df066e8e1e770ed | [
"ISC"
] | 31 | 2018-12-06T23:12:33.000Z | 2022-03-29T18:34:25.000Z | priv/repo/migrations/20201229220716_move_tag_checks_into_database.exs | CyberFlameGO/bolt | 225e6276983bec646e7f13519df066e8e1e770ed | [
"ISC"
] | 18 | 2021-06-14T19:03:26.000Z | 2022-03-15T17:46:22.000Z | priv/repo/migrations/20201229220716_move_tag_checks_into_database.exs | CyberFlameGO/bolt | 225e6276983bec646e7f13519df066e8e1e770ed | [
"ISC"
] | 4 | 2018-11-07T18:52:28.000Z | 2022-03-16T00:14:38.000Z | defmodule Bolt.Repo.Migrations.MoveTagChecksIntoDatabase do
use Ecto.Migration
def change do
create(constraint("tags", :name_length, check: "length(name) BETWEEN 3 AND 40"))
create(constraint("tags", :content_length, check: "length(content) BETWEEN 10 AND 2000"))
create(
constraint("tags", :name_not_blacklisted,
check:
"name NOT IN ('create', 'del', 'delete', 'edit', 'help', 'info', 'insert', 'modify', 'pop', 'push', 'raw', 'recent', 'remove', 'replace', 'rm', 'show', 'update')"
)
)
create(
constraint("tags", :name_no_guild_mentions,
check: "position('@everyone' IN name) = 0 AND position('@here' IN name) = 0"
)
)
end
end
| 32.363636 | 172 | 0.617978 |
08bb5aef902f0041149e096eff966b34458dd05f | 4,068 | ex | Elixir | clients/safe_browsing/lib/google_api/safe_browsing/v4/model/google_security_safebrowsing_v4_fetch_threat_list_updates_response_list_update_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/safe_browsing/lib/google_api/safe_browsing/v4/model/google_security_safebrowsing_v4_fetch_threat_list_updates_response_list_update_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/safe_browsing/lib/google_api/safe_browsing/v4/model/google_security_safebrowsing_v4_fetch_threat_list_updates_response_list_update_response.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.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse do
@moduledoc """
An update to an individual list.
## Attributes
* `additions` (*type:* `list(GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4ThreatEntrySet.t)`, *default:* `nil`) - A set of entries to add to a local threat type's list. Repeated to allow for a combination of compressed and raw data to be sent in a single response.
* `checksum` (*type:* `GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4Checksum.t`, *default:* `nil`) - The expected SHA256 hash of the client state; that is, of the sorted list of all hashes present in the database after applying the provided update. If the client state doesn't match the expected state, the client must disregard this update and retry later.
* `newClientState` (*type:* `String.t`, *default:* `nil`) - The new client state, in encrypted format. Opaque to clients.
* `platformType` (*type:* `String.t`, *default:* `nil`) - The platform type for which data is returned.
* `removals` (*type:* `list(GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4ThreatEntrySet.t)`, *default:* `nil`) - A set of entries to remove from a local threat type's list. In practice, this field is empty or contains exactly one ThreatEntrySet.
* `responseType` (*type:* `String.t`, *default:* `nil`) - The type of response. This may indicate that an action is required by the client when the response is received.
* `threatEntryType` (*type:* `String.t`, *default:* `nil`) - The format of the threats.
* `threatType` (*type:* `String.t`, *default:* `nil`) - The threat type for which data is returned.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:additions =>
list(GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4ThreatEntrySet.t()),
:checksum => GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4Checksum.t(),
:newClientState => String.t(),
:platformType => String.t(),
:removals =>
list(GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4ThreatEntrySet.t()),
:responseType => String.t(),
:threatEntryType => String.t(),
:threatType => String.t()
}
field(:additions,
as: GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4ThreatEntrySet,
type: :list
)
field(:checksum, as: GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4Checksum)
field(:newClientState)
field(:platformType)
field(:removals,
as: GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4ThreatEntrySet,
type: :list
)
field(:responseType)
field(:threatEntryType)
field(:threatType)
end
defimpl Poison.Decoder,
for:
GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse do
def decode(value, options) do
GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.SafeBrowsing.V4.Model.GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 47.302326 | 376 | 0.738692 |
08bb6f4e08ffe5bd3f22b7efdb37a2220a3fb6d4 | 2,032 | exs | Elixir | test/controllers/bar_controller_test.exs | matthewphilyaw/basic_auth_test | 9bd6b62c8680ec603314adab940b8840e50b240c | [
"MIT"
] | null | null | null | test/controllers/bar_controller_test.exs | matthewphilyaw/basic_auth_test | 9bd6b62c8680ec603314adab940b8840e50b240c | [
"MIT"
] | null | null | null | test/controllers/bar_controller_test.exs | matthewphilyaw/basic_auth_test | 9bd6b62c8680ec603314adab940b8840e50b240c | [
"MIT"
] | null | null | null | defmodule FooApi.BarControllerTest do
use FooApi.ConnCase
alias FooApi.Bar
@valid_attrs %{barnism: "some content"}
@invalid_attrs %{}
setup do
conn = conn() |> put_req_header("accept", "application/json")
{:ok, conn: conn}
end
test "lists all entries on index", %{conn: conn} do
conn = get conn, bar_path(conn, :index)
assert json_response(conn, 200)["data"] == []
end
test "shows chosen resource", %{conn: conn} do
bar = Repo.insert! %Bar{}
conn = get conn, bar_path(conn, :show, bar)
assert json_response(conn, 200)["data"] == %{id: bar.id,
barnism: bar.barnism}
end
test "does not show resource and instead throw error when id is nonexistent", %{conn: conn} do
assert_raise Ecto.NoResultsError, fn ->
get conn, bar_path(conn, :show, -1)
end
end
test "creates and renders resource when data is valid", %{conn: conn} do
conn = post conn, bar_path(conn, :create), bar: @valid_attrs
assert json_response(conn, 201)["data"]["id"]
assert Repo.get_by(Bar, @valid_attrs)
end
test "does not create resource and renders errors when data is invalid", %{conn: conn} do
conn = post conn, bar_path(conn, :create), bar: @invalid_attrs
assert json_response(conn, 422)["errors"] != %{}
end
test "updates and renders chosen resource when data is valid", %{conn: conn} do
bar = Repo.insert! %Bar{}
conn = put conn, bar_path(conn, :update, bar), bar: @valid_attrs
assert json_response(conn, 200)["data"]["id"]
assert Repo.get_by(Bar, @valid_attrs)
end
test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do
bar = Repo.insert! %Bar{}
conn = put conn, bar_path(conn, :update, bar), bar: @invalid_attrs
assert json_response(conn, 422)["errors"] != %{}
end
test "deletes chosen resource", %{conn: conn} do
bar = Repo.insert! %Bar{}
conn = delete conn, bar_path(conn, :delete, bar)
assert response(conn, 204)
refute Repo.get(Bar, bar.id)
end
end
| 32.774194 | 98 | 0.660925 |
08bb76f7c6a327369cd1353c1c43ceb7d67bbf72 | 124 | exs | Elixir | config/prod.exs | mrhooray/dwolla-elixir | 843c40fbef7e1356bb77b4c2f21fd8a534eef5da | [
"MIT"
] | null | null | null | config/prod.exs | mrhooray/dwolla-elixir | 843c40fbef7e1356bb77b4c2f21fd8a534eef5da | [
"MIT"
] | null | null | null | config/prod.exs | mrhooray/dwolla-elixir | 843c40fbef7e1356bb77b4c2f21fd8a534eef5da | [
"MIT"
] | null | null | null | use Mix.Config
config :dwolla,
root_uri: "https://api.dwolla.com/",
oauth_uri: "https://www.dwolla.com/oauth/v2/token"
| 20.666667 | 52 | 0.701613 |
08bb7a184c2e88398a5c36362c06aa0dd904924d | 248 | ex | Elixir | lib/supabase_surface/components/utils.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | 5 | 2021-06-08T08:02:43.000Z | 2022-02-09T23:13:46.000Z | lib/supabase_surface/components/utils.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | null | null | null | lib/supabase_surface/components/utils.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | 1 | 2021-07-14T05:20:31.000Z | 2021-07-14T05:20:31.000Z | defmodule SupabaseSurface.Components.Utils do
def get_style(assigns) do
assigns.style
|> Stream.filter(fn {_key, value} -> not is_nil(value) end)
|> Enum.map(fn {key, value} -> "#{key}: #{value}" end)
|> Enum.join("; ")
end
end
| 27.555556 | 63 | 0.629032 |
08bba01f2aa226df08dcc34d25ba77a41e80f92a | 195 | ex | Elixir | lib/edgar.ex | david-christensen/edgar | 32fdcf5b60b5a9be2f9604ea6d57e4cc1ab27e93 | [
"MIT"
] | null | null | null | lib/edgar.ex | david-christensen/edgar | 32fdcf5b60b5a9be2f9604ea6d57e4cc1ab27e93 | [
"MIT"
] | null | null | null | lib/edgar.ex | david-christensen/edgar | 32fdcf5b60b5a9be2f9604ea6d57e4cc1ab27e93 | [
"MIT"
] | null | null | null | defmodule Edgar do
@moduledoc """
Documentation for `Edgar`.
"""
@doc """
Hello world.
## Examples
iex> Edgar.hello()
:world
"""
def hello do
:world
end
end
| 10.263158 | 28 | 0.54359 |
08bbb3ab31e420f25b4478e55ae084512a7717a4 | 945 | exs | Elixir | kousa/test/broth/_calls/schedule_room_test.exs | AhmetEsad/dogehouse | ba8c757bc0419ac07bd9bf062c67a39ab74cdfa6 | [
"MIT"
] | 1 | 2021-04-22T08:37:55.000Z | 2021-04-22T08:37:55.000Z | kousa/test/broth/_calls/schedule_room_test.exs | mateuszklysz/dogehouse | ba8c757bc0419ac07bd9bf062c67a39ab74cdfa6 | [
"MIT"
] | null | null | null | kousa/test/broth/_calls/schedule_room_test.exs | mateuszklysz/dogehouse | ba8c757bc0419ac07bd9bf062c67a39ab74cdfa6 | [
"MIT"
] | null | null | null | defmodule BrothTest.ScheduleRoomTest do
use ExUnit.Case, async: true
use KousaTest.Support.EctoSandbox
alias Beef.Schemas.User
alias BrothTest.WsClient
alias BrothTest.WsClientFactory
alias KousaTest.Support.Factory
require WsClient
setup do
user = Factory.create(User)
client_ws = WsClientFactory.create_client_for(user)
{:ok, user: user, client_ws: client_ws}
end
describe "the websocket schedule_room operation" do
test "creates a scheduled room", t do
time = DateTime.utc_now() |> DateTime.add(10, :second)
ref =
WsClient.send_call_legacy(
t.client_ws,
"schedule_room",
%{"name" => "foo room", "scheduledFor" => DateTime.to_iso8601(time)}
)
WsClient.assert_reply_legacy(
ref,
%{"id" => room_id, "name" => "foo room"}
)
assert %{name: "foo room"} = Beef.ScheduledRooms.get_by_id(room_id)
end
end
end
| 24.230769 | 78 | 0.657143 |
08bbd04c92b2d1aa353f41726106ebc9683cb762 | 929 | ex | Elixir | test/support/channel_case.ex | johndavedecano/kwerk | a9e5928c2c5eb7a9a8dfaba30450627c257832a3 | [
"MIT"
] | 2 | 2018-09-23T08:45:07.000Z | 2020-01-20T15:47:45.000Z | test/support/channel_case.ex | johndavedecano/kwerk | a9e5928c2c5eb7a9a8dfaba30450627c257832a3 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | johndavedecano/kwerk | a9e5928c2c5eb7a9a8dfaba30450627c257832a3 | [
"MIT"
] | null | null | null | defmodule KwerkWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common datastructures 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 channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint KwerkWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Kwerk.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Kwerk.Repo, {:shared, self()})
end
:ok
end
end
| 24.447368 | 67 | 0.713671 |
08bc025987e2ce82cf3d2f9e8fe324f6ce8503c0 | 85 | ex | Elixir | web/views/layout_view.ex | KazuCocoa/web_qa | cd0074e950ef354eeafb7d48db685c82d653cc60 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | KazuCocoa/web_qa | cd0074e950ef354eeafb7d48db685c82d653cc60 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | KazuCocoa/web_qa | cd0074e950ef354eeafb7d48db685c82d653cc60 | [
"MIT"
] | null | null | null | defmodule WebQaVote.LayoutView do
@moduledoc false
use WebQaVote.Web, :view
end
| 14.166667 | 33 | 0.776471 |
08bc3902a97813064dc40a871655832ed25fe6b4 | 1,790 | exs | Elixir | clients/sheets/mix.exs | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/sheets/mix.exs | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/sheets/mix.exs | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Sheets.Mixfile do
use Mix.Project
@version "0.25.0"
def project() do
[
app: :google_api_sheets,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/sheets"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Google Sheets API client library. Reads and writes Google Sheets.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/sheets",
"Homepage" => "https://developers.google.com/sheets/"
}
]
end
end
| 26.716418 | 97 | 0.649162 |
08bc56d87af43b623668c4ab7417ec089b6ca10e | 9,228 | ex | Elixir | lib/mix/tasks/new.ex | milmazz/scenic_new | 08e3557fc481d23d6cc274e7e1b3a22809a41324 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/new.ex | milmazz/scenic_new | 08e3557fc481d23d6cc274e7e1b3a22809a41324 | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/new.ex | milmazz/scenic_new | 08e3557fc481d23d6cc274e7e1b3a22809a41324 | [
"Apache-2.0"
] | null | null | null | #
# Created by Boyd Multerer on August, 2018.
# Copyright © 2018 Kry10 Industries. All rights reserved.
#
defmodule Mix.Tasks.Scenic.New do
use Mix.Task
import Mix.Generator
@moduledoc """
Generates a starter Scenic application.
This is the easiest way to set up a new Scenic project.
## Install `scenic.new`
```bash
mix archive.install hex scenic_new
```
## Build the Starter App
First, navigate the command-line to the directory where you want to create your new Scenic app. Then run the following commands: (change `my_app` to the name of your app...)
```bash
mix scenic.new my_app
cd my_app
mix do deps.get, scenic.run
```
## Running and Debugging
Once the app and its dependencies are set up, there are two main ways to run it.
If you want to run your app under IEx so that you can debug it, simply run
```bash
iex -S mix
```
This works just like any other Elixir application.
If you want to run your app outside of iex, you should start it like this:
```bash
mix scenic.run
```
## The Starter App
The starter app created by the generator above shows the basics of building a Scenic application. It has four scenes, two components, and a simulated sensor.
Scene | Description
--- | ---
Splash | The Splash scene is configured to run when the app is started in the `config/config.exs` file. It runs a simple animation, then transitions to the Sensor scene. It also shows how intercept basic user input to exit the scene early.
Sensor | The Sensor scene depicts a simulated temperature sensor. The sensor is always running and updates it's data through the `Scenic.SensorPubSub` server.
Primitives | The Primitives scenes displays an overview of the basic primitive types and some of the styles that can be applied to them.
Components | The Components scene shows the basic components that come with Scenic. The crash button will cause a match error that will crash the scene, showing how the supervison tree restarts the scene. It also shows how to receive events from components.
Component | Description
--- | ---
Nav | The nav bar at the top of the main scenes shows how to navigate between scenes and how to construct a simple component and pass a parameter to it. Note that it references a clock, creating a nested component. The clock is positioned by dynamically querying the width of the ViewPort
Notes | The notes section at the bottom of each scene is very simple and also shows passing in custom data from the parent.
The simulated temperature sensor doesn't collect any actual data, but does show how you would set up a real sensor and publish data from it into the Scenic.SensorPubSub service.
## What to read next
Next, you should read guides describing the overall Scenic structure. This is in the documentation for Scenic itself
"""
# import IEx
@switches [
app: :string,
module: :string
]
@scenic_version Mix.Project.config()[:version]
@parrot_bin File.read!("static/scenic_parrot.png")
@cyanoramphus_bin File.read!("static/cyanoramphus_zealandicus_1849.jpg")
# --------------------------------------------------------
def run(argv) do
{opts, argv} = OptionParser.parse!(argv, strict: @switches)
case argv do
[] ->
Mix.raise("Expected app PATH to be given, please use \"mix scenic.new PATH\"")
[path | _] ->
app = opts[:app] || Path.basename(Path.expand(path))
check_application_name!(app, !opts[:app])
mod = opts[:module] || Macro.camelize(app)
check_mod_name_validity!(mod)
check_mod_name_availability!(mod)
unless path == "." do
check_directory_existence!(path)
File.mkdir_p!(path)
end
File.cd!(path, fn ->
generate(app, mod, path, opts)
end)
end
end
# --------------------------------------------------------
defp generate(app, mod, path, _opts) do
assigns = [
app: app,
mod: mod,
elixir_version: get_version(System.version()),
scenic_version: @scenic_version
]
create_file("README.md", readme_template(assigns))
create_file(".formatter.exs", formatter_template(assigns))
create_file(".gitignore", gitignore_template(assigns))
create_file("mix.exs", mix_exs_template(assigns))
create_file("Makefile", makefile_template(assigns))
create_directory("config")
create_file("config/config.exs", config_template(assigns))
create_directory("lib")
create_file("lib/#{app}.ex", app_template(assigns))
create_directory("static")
create_file("static/images/attribution.txt", attribution_template(assigns))
create_file("static/images/scenic_parrot.png", @parrot_bin)
create_file("static/images/cyanoramphus_zealandicus_1849.jpg", @cyanoramphus_bin)
create_directory("lib/scenes")
create_file("lib/scenes/components.ex", scene_components_template(assigns))
create_file("lib/scenes/sensor.ex", scene_sensor_template(assigns))
create_file("lib/scenes/primitives.ex", scene_primitives_template(assigns))
create_file("lib/scenes/transforms.ex", scene_transforms_template(assigns))
create_file("lib/scenes/splash.ex", scene_splash_template(assigns))
create_directory("lib/components")
create_file("lib/components/nav.ex", nav_template(assigns))
create_file("lib/components/notes.ex", notes_template(assigns))
create_directory("lib/sensors")
create_file("lib/sensors/supervisor.ex", sensor_sup_template(assigns))
create_file("lib/sensors/temperature.ex", sensor_temp_template(assigns))
# create_directory("test")
# create_file("test/test_helper.exs", test_helper_template(assigns))
# create_file("test/#{app}_test.exs", test_template(assigns))
"""
Your Scenic project was created successfully.
Next steps for getting started:
$ cd #{path}
$ mix deps.get
You can start your app with:
$ mix scenic.run
You can also run it interactively like this:
$ iex -S mix
"""
# |> String.trim_trailing()
|> Mix.shell().info()
end
# --------------------------------------------------------
defp get_version(version) do
{:ok, version} = Version.parse(version)
"#{version.major}.#{version.minor}" <>
case version.pre do
[h | _] -> "-#{h}"
[] -> ""
end
end
# ============================================================================
# template files
embed_template(:readme, from_file: "templates/README.md.eex")
embed_template(:formatter, from_file: "templates/formatter.exs")
embed_template(:gitignore, from_file: "templates/gitignore")
embed_template(:mix_exs, from_file: "templates/mix.exs.eex")
embed_template(:makefile, from_file: "templates/Makefile")
embed_template(:config, from_file: "templates/config/config.exs.eex")
embed_template(:app, from_file: "templates/lib/app.ex.eex")
embed_template(:nav, from_file: "templates/lib/components/nav.ex.eex")
embed_template(:notes, from_file: "templates/lib/components/notes.ex.eex")
embed_template(:attribution, from_file: "static/attribution.txt")
embed_template(:scene_components, from_file: "templates/lib/scenes/components.ex.eex")
embed_template(:scene_sensor, from_file: "templates/lib/scenes/sensor.ex.eex")
embed_template(:scene_primitives, from_file: "templates/lib/scenes/primitives.ex.eex")
embed_template(:scene_transforms, from_file: "templates/lib/scenes/transforms.ex.eex")
embed_template(:scene_splash, from_file: "templates/lib/scenes/splash.ex.eex")
embed_template(:sensor_sup, from_file: "templates/lib/sensors/supervisor.ex.eex")
embed_template(:sensor_temp, from_file: "templates/lib/sensors/temperature.ex.eex")
# ============================================================================
# validity functions taken from Elixir new task
defp check_application_name!(name, inferred?) do
unless name =~ Regex.recompile!(~r/^[a-z][a-z0-9_]*$/) do
Mix.raise(
"Application name must start with a lowercase ASCII letter, followed by " <>
"lowercase ASCII letters, numbers, or underscores, got: #{inspect(name)}" <>
if inferred? do
". The application name is inferred from the path, if you'd like to " <>
"explicitly name the application then use the \"--app APP\" option"
else
""
end
)
end
end
defp check_mod_name_validity!(name) do
unless name =~ Regex.recompile!(~r/^[A-Z]\w*(\.[A-Z]\w*)*$/) do
Mix.raise(
"Module name must be a valid Elixir alias (for example: Foo.Bar), got: #{inspect(name)}"
)
end
end
defp check_mod_name_availability!(name) do
name = Module.concat(Elixir, name)
if Code.ensure_loaded?(name) do
Mix.raise("Module name #{inspect(name)} is already taken, please choose another name")
end
end
defp check_directory_existence!(path) do
msg = "The directory #{inspect(path)} already exists. Are you sure you want to continue?"
if File.dir?(path) and not Mix.shell().yes?(msg) do
Mix.raise("Please select another directory for installation")
end
end
end
| 35.629344 | 290 | 0.67772 |
08bc7504a0c4348e1194f5e4378aa1512a7b5e89 | 1,539 | ex | Elixir | clients/tool_results/lib/google_api/tool_results/v1beta3/model/tool_exit_code.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/tool_results/lib/google_api/tool_results/v1beta3/model/tool_exit_code.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/tool_results/lib/google_api/tool_results/v1beta3/model/tool_exit_code.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ToolResults.V1beta3.Model.ToolExitCode do
@moduledoc """
Exit code from a tool execution.
## Attributes
* `number` (*type:* `integer()`, *default:* `nil`) - Tool execution exit code. A value of 0 means that the execution was
successful.
- In response: always set
- In create/update request: always set
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:number => integer()
}
field(:number)
end
defimpl Poison.Decoder, for: GoogleApi.ToolResults.V1beta3.Model.ToolExitCode do
def decode(value, options) do
GoogleApi.ToolResults.V1beta3.Model.ToolExitCode.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ToolResults.V1beta3.Model.ToolExitCode do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.176471 | 124 | 0.730344 |
08bcc1854b90567b1da9fd1094dce7a753719798 | 2,278 | ex | Elixir | lib/md0/scanner/table_scanner_impl.ex | RobertDober/md0 | b2337e69a9bea6b2b17951b75daa15fe7fe8cfad | [
"Apache-2.0"
] | null | null | null | lib/md0/scanner/table_scanner_impl.ex | RobertDober/md0 | b2337e69a9bea6b2b17951b75daa15fe7fe8cfad | [
"Apache-2.0"
] | null | null | null | lib/md0/scanner/table_scanner_impl.ex | RobertDober/md0 | b2337e69a9bea6b2b17951b75daa15fe7fe8cfad | [
"Apache-2.0"
] | null | null | null | defmodule Md0.Scanner.TableScannerImpl do
@typep token :: {atom(), String.t, number()}
@typep tokens :: list(token)
@typep graphemes :: list(String.t)
@typep scan_info :: {atom(), graphemes(), number(), IO.chardata(), tokens()}
def scan_line({line, lnb}, table),
do: scan({:start, String.graphemes(line), 1, [], []}, table) |> Enum.map(&add_lnb(&1, lnb))
defp add_lnb({tk, ct, col}, lnb), do: {tk, ct, lnb, col}
@spec scan( scan_info(), map() ) :: tokens()
defp scan(scan_info, table)
defp scan({state, [], _, _, _} = info, table) do
{type, token, action} = table[state][:eof]
action.(token_to_info(info, token || type))
end
defp scan({state, [grapheme|_], _, _, _}=info, table) do
{new_state, token, action} = (table[state][grapheme] || table[state][true])
case action.(token_to_info(info, token)) do
[_] = tokens -> tokens
{_, input, col, partial, tokens} -> scan({new_state, input, col, partial, tokens}, table)
end
end
@doc false
@spec collect( scan_info() ) :: scan_info()
def collect({state, [grapheme|rest], col, partial, tokens}), do: {state, rest, col, [grapheme|partial], tokens}
@spec collect_emit( scan_info() ) :: tokens()
def collect_emit({emit_state, [grapheme | rest ], col, partial, tokens}) do
with rendered <- string_from([grapheme|partial]),
do: { nil, rest, col + String.length(rendered), [], [{emit_state, rendered, col} | tokens] }
end
@doc false
@spec emit_collect( scan_info() ) :: scan_info()
def emit_collect({emit_state,[grapheme|input], col, partial, tokens}) do
rendered = string_from(partial)
{nil, input, col + String.length(rendered), [grapheme], [{emit_state, rendered, col}|tokens]}
end
@spec emit_return( scan_info() ) :: tokens()
def emit_return({state, _, col, partial, tokens}), do: [{state, string_from(partial), col} | tokens] |> Enum.reverse
@spec return( scan_info() ) :: tokens()
def return({_, _, _, _, tokens}), do: tokens |> Enum.reverse
defp string_from(partial), do: partial |> IO.iodata_to_binary() |> String.reverse()
defp token_to_info(info, token)
defp token_to_info(info, nil), do: info
defp token_to_info({_,input, col, partial, tokens}, token), do: {token ,input, col, partial, tokens}
end
| 39.275862 | 118 | 0.645303 |
08bcef28a722d7c594836572e29fd9ea8b9ca024 | 6,187 | ex | Elixir | clients/binary_authorization/lib/google_api/binary_authorization/v1/model/iam_policy.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/binary_authorization/lib/google_api/binary_authorization/v1/model/iam_policy.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/binary_authorization/lib/google_api/binary_authorization/v1/model/iam_policy.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.BinaryAuthorization.V1.Model.IamPolicy do
@moduledoc """
An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A `Policy` is a collection of `bindings`. A `binding` binds one or more `members`, or principals, to a single `role`. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features, see the [IAM documentation](https://cloud.google.com/iam/docs/).
## Attributes
* `bindings` (*type:* `list(GoogleApi.BinaryAuthorization.V1.Model.Binding.t)`, *default:* `nil`) - Associates a list of `members`, or principals, with a `role`. Optionally, may specify a `condition` that determines how and when the `bindings` are applied. Each of the `bindings` must contain at least one principal. The `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 of these principals can be Google groups. Each occurrence of a principal counts towards these limits. For example, if the `bindings` grant 50 different roles to `user:alice@example.com`, and not to any other principal, then you can add another 1,450 principals to the `bindings` in the `Policy`.
* `etag` (*type:* `String.t`, *default:* `nil`) - `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected to put that etag in the request to `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:** If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the version `3` policy are lost.
* `version` (*type:* `integer()`, *default:* `nil`) - Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid value are rejected. Any operation that affects conditional role bindings must specify version `3`. This requirement applies to the following operations: * Getting a policy that includes a conditional role binding * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing any role binding, with or without a condition, from a policy that includes conditions **Important:** If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on that policy may specify any valid version or leave the field unset. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:bindings => list(GoogleApi.BinaryAuthorization.V1.Model.Binding.t()) | nil,
:etag => String.t() | nil,
:version => integer() | nil
}
field(:bindings, as: GoogleApi.BinaryAuthorization.V1.Model.Binding, type: :list)
field(:etag)
field(:version)
end
defimpl Poison.Decoder, for: GoogleApi.BinaryAuthorization.V1.Model.IamPolicy do
def decode(value, options) do
GoogleApi.BinaryAuthorization.V1.Model.IamPolicy.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BinaryAuthorization.V1.Model.IamPolicy do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 116.735849 | 2,012 | 0.755778 |
08bd03b34c5db4c48a3f57511eee1274376c8331 | 3,575 | exs | Elixir | test/lib/absinthe/phase/document/validation/known_argument_names_test.exs | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | 3 | 2017-06-22T16:33:58.000Z | 2021-07-07T15:21:09.000Z | test/lib/absinthe/phase/document/validation/known_argument_names_test.exs | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | test/lib/absinthe/phase/document/validation/known_argument_names_test.exs | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | defmodule Absinthe.Phase.Document.Validation.KnownArgumentNamesTest do
use Absinthe.Case, async: true
@rule Absinthe.Phase.Document.Validation.KnownArgumentNames
use Support.Harness.Validation
alias Absinthe.{Blueprint}
context "Valid" do
it "single arg is known" do
assert_passes_rule(@rule,
"""
fragment argOnRequiredArg on Dog {
doesKnowCommand(dogCommand: SIT)
}
""",
[]
)
end
it "multiple args are known" do
assert_passes_rule(@rule,
"""
fragment multipleArgs on ComplicatedArgs {
multipleReqs(req1: 1, req2: 2)
}
""",
[]
)
end
it "multiple args in reverse order are known" do
assert_passes_rule(@rule,
"""
fragment multipleArgsReverseOrder on ComplicatedArgs {
multipleReqs(req2: 2, req1: 1)
}
""",
[]
)
end
it "no args on optional arg" do
assert_passes_rule(@rule,
"""
fragment noArgOnOptionalArg on Dog {
isHousetrained
}
""",
[]
)
end
it "args are known deeply" do
assert_passes_rule(@rule,
"""
{
dog {
doesKnowCommand(dogCommand: SIT)
}
human {
pet {
... on Dog {
doesKnowCommand(dogCommand: SIT)
}
}
}
}
""",
[]
)
end
it "directive args are known" do
assert_passes_rule(@rule,
"""
{
dog @skip(if: true)
}
""",
[]
)
end
end
context "Invalid" do
it "undirective args are invalid" do
assert_fails_rule(@rule,
"""
{
dog @skip(unless: true)
}
""",
[],
[
bad_value(Blueprint.Input.Argument, @rule.directive_error_message("unless", "skip"), 2, name: "unless")
]
)
end
it "invalid arg name" do
assert_fails_rule(@rule,
"""
fragment invalidArgName on Dog {
doesKnowCommand(unknown: true)
}
""",
[],
[
bad_value(Blueprint.Input.Argument, @rule.field_error_message("unknown", "doesKnowCommand", "Dog"), 2, name: "unknown")
]
)
end
it "unknown args amongst known args" do
assert_fails_rule(@rule,
"""
fragment oneGoodArgOneInvalidArg on Dog {
doesKnowCommand(whoknows: 1, dogCommand: SIT, unknown: true)
}
""",
[],
[
bad_value(Blueprint.Input.Argument, @rule.field_error_message("unknown", "doesKnowCommand", "Dog"), 2, name: "unknown"),
bad_value(Blueprint.Input.Argument, @rule.field_error_message("whoknows", "doesKnowCommand", "Dog"), 2, name: "whoknows")
]
)
end
it "unknown args deeply" do
assert_fails_rule(@rule,
"""
{
dog {
doesKnowCommand(unknown: true)
}
human {
pet {
... on Dog {
doesKnowCommand(unknown: true)
}
}
}
}
""",
[],
[
bad_value(Blueprint.Input.Argument, @rule.field_error_message("unknown", "doesKnowCommand", "Dog"), 3, name: "unknown"),
bad_value(Blueprint.Input.Argument,@rule.field_error_message("unknown", "doesKnowCommand", "Dog"), 8, name: "unknown")
]
)
end
end
end
| 22.34375 | 131 | 0.503776 |
08bd4c73ac224ca8fa732fd99b379987bc1dbfa5 | 2,349 | ex | Elixir | clients/classroom/lib/google_api/classroom/v1/model/feed.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/classroom/lib/google_api/classroom/v1/model/feed.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/classroom/lib/google_api/classroom/v1/model/feed.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.Classroom.V1.Model.Feed do
@moduledoc """
A class of notifications that an application can register to receive.
For example: "all roster changes for a domain".
## Attributes
* `courseRosterChangesInfo` (*type:* `GoogleApi.Classroom.V1.Model.CourseRosterChangesInfo.t`, *default:* `nil`) - Information about a `Feed` with a `feed_type` of `COURSE_ROSTER_CHANGES`.
This field must be specified if `feed_type` is `COURSE_ROSTER_CHANGES`.
* `courseWorkChangesInfo` (*type:* `GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo.t`, *default:* `nil`) - Information about a `Feed` with a `feed_type` of `COURSE_WORK_CHANGES`.
This field must be specified if `feed_type` is `COURSE_WORK_CHANGES`.
* `feedType` (*type:* `String.t`, *default:* `nil`) - The type of feed.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:courseRosterChangesInfo => GoogleApi.Classroom.V1.Model.CourseRosterChangesInfo.t(),
:courseWorkChangesInfo => GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo.t(),
:feedType => String.t()
}
field(:courseRosterChangesInfo, as: GoogleApi.Classroom.V1.Model.CourseRosterChangesInfo)
field(:courseWorkChangesInfo, as: GoogleApi.Classroom.V1.Model.CourseWorkChangesInfo)
field(:feedType)
end
defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.Feed do
def decode(value, options) do
GoogleApi.Classroom.V1.Model.Feed.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.Feed do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.946429 | 192 | 0.742018 |
08bd5c2b27047a1141eb74ceeca756543e138cc2 | 2,316 | exs | Elixir | config/config.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 2 | 2019-01-20T07:03:30.000Z | 2019-04-11T10:20:14.000Z | config/config.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 6 | 2018-09-20T05:52:14.000Z | 2019-04-23T19:27:39.000Z | config/config.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# General application configuration
config :jumubase,
ecto_repos: [Jumubase.Repo]
# API keys
config :jumubase, JumubaseWeb.MapHelpers, google_api_key: System.get_env("GOOGLE_API_KEY")
config :jumubase, JumubaseWeb.ApiAuth, api_key: System.get_env("JUMU_API_KEY")
# Companion app IDs
config :jumubase, :app_ids,
android: System.get_env("JUMU_APP_ID_ANDROID"),
ios: System.get_env("JUMU_APP_ID_IOS")
# Set default locale
locale = "de"
config :jumubase, Jumubase.Gettext, default_locale: locale
config :timex, default_locale: locale
config :timex, Timex.Gettext, default_locale: locale
# Configure the endpoint
config :jumubase, JumubaseWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "CItDuu3F0bThL/GnGj6lG4CNhFF/JPz/LHyWFVkLRdht2gpHfuFftGiO1paelppz",
render_errors: [view: JumubaseWeb.ErrorView, accepts: ~w(html json)],
pubsub_server: Jumubase.PubSub,
live_view: [signing_salt: "4+PLR3SMvBIBZG4im48JLB2wWM+2prRB"]
# Keep microsecond precision in timestamps
config :jumubase, Jumubase.Repo, migration_timestamps: [type: :naive_datetime_usec]
# Configure mailer
config :jumubase, Jumubase.Mailer, adapter: Bamboo.LocalAdapter
# Configure email
config :jumubase, JumubaseWeb.Email,
default_sender: {"Jumu weltweit", "no-reply@jumu-weltweit.org"},
contact_email: System.get_env("JUMU_CONTACT_EMAIL"),
admin_email: System.get_env("JUMU_ADMIN_EMAIL")
# Configure release level
config :jumubase, release_level: System.get_env("RELEASE_LEVEL")
# Configure Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Configure Sentry
config :sentry,
dsn: System.get_env("SENTRY_DSN"),
filter: Jumubase.SentryEventFilter,
included_environments: ~w(staging production),
environment_name: System.get_env("RELEASE_LEVEL") || "development"
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 33.085714 | 90 | 0.780656 |
08bd73c67c4970410d9e5862d8a58b91311a06de | 16,972 | ex | Elixir | lib/ex_unit/lib/ex_unit/case.ex | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/lib/ex_unit/case.ex | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/lib/ex_unit/case.ex | andrewtimberlake/elixir | a1c4ffc897f9407fe7e739e20e697805fbbff810 | [
"Apache-2.0"
] | null | null | null | defmodule ExUnit.DuplicateTestError do
defexception [:message]
end
defmodule ExUnit.DuplicateDescribeError do
defexception [:message]
end
defmodule ExUnit.Case do
@moduledoc """
Helpers for defining test cases.
This module must be used in other modules as a way to configure
and prepare them for testing.
When used, it accepts the following options:
* `:async` - configures tests in this module to run concurrently with
tests in other modules. Tests in the same module never run concurrently.
It should be enabled only if tests do not change any global state.
Defaults to `false`.
This module automatically includes all callbacks defined in
`ExUnit.Callbacks`. See that module for more information on `setup`,
`start_supervised`, `on_exit` and the test process lifecycle.
For grouping tests together, see `describe/2` in this module.
## Examples
defmodule AssertionTest do
# Use the module
use ExUnit.Case, async: true
# The "test" macro is imported by ExUnit.Case
test "always pass" do
assert true
end
end
## Context
All tests receive a context as an argument. The context is particularly
useful for sharing information between callbacks and tests:
defmodule KVTest do
use ExUnit.Case
setup do
{:ok, pid} = KV.start_link()
{:ok, pid: pid}
end
test "stores key-value pairs", context do
assert KV.put(context[:pid], :hello, :world) == :ok
assert KV.get(context[:pid], :hello) == :world
end
end
As the context is a map, it can be pattern matched on to extract
information:
test "stores key-value pairs", %{pid: pid} = _context do
assert KV.put(pid, :hello, :world) == :ok
assert KV.get(pid, :hello) == :world
end
## Tags
The context is used to pass information from the callbacks to
the test. In order to pass information from the test to the
callback, ExUnit provides tags.
By tagging a test, the tag value can be accessed in the context,
allowing the developer to customize the test. Let's see an
example:
defmodule FileTest do
# Changing directory cannot be async
use ExUnit.Case, async: false
setup context do
# Read the :cd tag value
if cd = context[:cd] do
prev_cd = File.cwd!()
File.cd!(cd)
on_exit(fn -> File.cd!(prev_cd) end)
end
:ok
end
@tag cd: "fixtures"
test "reads UTF-8 fixtures" do
File.read("README.md")
end
end
In the example above, we have defined a tag called `:cd` that is
read in the setup callback to configure the working directory the
test is going to run on.
Tags are also very effective when used with case templates
(`ExUnit.CaseTemplate`) allowing callbacks in the case template
to customize the test behaviour.
Note a tag can be set in two different ways:
@tag key: value
@tag :key # equivalent to setting @tag key: true
If a tag is given more than once, the last value wins.
### Module and describe tags
A tag can be set for all tests in a module or describe block by
setting `@moduletag` or `@describetag` inside each context
respectively:
defmodule ApiTest do
use ExUnit.Case
@moduletag :external
describe "makes calls to the right endpoint" do
@describetag :endpoint
# ...
end
end
If you are setting a `@moduletag`, you must set that after your
call to `use ExUnit.Case` otherwise you will see compilation errors.
If the same key is set via `@tag`, the `@tag` value has higher
precedence.
### Known tags
The following tags are set automatically by ExUnit and are
therefore reserved:
* `:module` - the module on which the test was defined
* `:file` - the file on which the test was defined
* `:line` - the line on which the test was defined
* `:test` - the test name
* `:async` - if the test case is in async mode
* `:registered` - used for `ExUnit.Case.register_attribute/3` values
* `:describe` - the describe block the test belongs to
The following tags customize how tests behave:
* `:capture_log` - see the "Log Capture" section below
* `:skip` - skips the test with the given reason
* `:timeout` - customizes the test timeout in milliseconds (defaults to 60000).
Accepts `:infinity` as a timeout value.
The `:test_type` tag is automatically set by ExUnit, but is _not_ reserved.
This tag is available for users to customize if they desire.
## Filters
Tags can also be used to identify specific tests, which can then
be included or excluded using filters. The most common functionality
is to exclude some particular tests from running, which can be done
via `ExUnit.configure/1`:
# Exclude all external tests from running
ExUnit.configure(exclude: [external: true])
From now on, ExUnit will not run any test that has the `:external` option
set to `true`. This behaviour can be reversed with the `:include` option
which is usually passed through the command line:
mix test --include external:true
Run `mix help test` for more information on how to run filters via Mix.
Another use case for tags and filters is to exclude all tests that have
a particular tag by default, regardless of its value, and include only
a certain subset:
ExUnit.configure(exclude: :os, include: [os: :unix])
A given include/exclude filter can be given more than once:
ExUnit.configure(exclude: [os: :unix, os: :windows])
Keep in mind that all tests are included by default, so unless they are
excluded first, the `include` option has no effect.
## Log Capture
ExUnit can optionally suppress printing of log messages that are generated
during a test. Log messages generated while running a test are captured and
only if the test fails are they printed to aid with debugging.
You can opt into this behaviour for individual tests by tagging them with
`:capture_log` or enable log capture for all tests in the ExUnit configuration:
ExUnit.start(capture_log: true)
This default can be overridden by `@tag capture_log: false` or
`@moduletag capture_log: false`.
Since `setup_all` blocks don't belong to a specific test, log messages generated
in them (or between tests) are never captured. If you want to suppress these
messages as well, remove the console backend globally by setting:
config :logger, backends: []
"""
@reserved [:module, :file, :line, :test, :async, :registered, :describe]
@doc false
defmacro __using__(opts) do
unless Process.whereis(ExUnit.Server) do
raise "cannot use ExUnit.Case without starting the ExUnit application, " <>
"please call ExUnit.start() or explicitly start the :ex_unit app"
end
quote do
async = !!unquote(opts)[:async]
unless Module.get_attribute(__MODULE__, :ex_unit_tests) do
moduletag_check = Module.get_attribute(__MODULE__, :moduletag)
tag_check = Module.get_attribute(__MODULE__, :tag)
if moduletag_check || tag_check do
raise "you must set @tag and @moduletag after the call to \"use ExUnit.Case\""
end
attributes = [
:ex_unit_tests,
:tag,
:describetag,
:moduletag,
:ex_unit_registered,
:ex_unit_used_describes
]
Enum.each(attributes, &Module.register_attribute(__MODULE__, &1, accumulate: true))
@before_compile ExUnit.Case
@after_compile ExUnit.Case
@ex_unit_async async
@ex_unit_describe nil
use ExUnit.Callbacks
end
import ExUnit.Callbacks
import ExUnit.Assertions
import ExUnit.Case, only: [describe: 2, test: 1, test: 2, test: 3]
import ExUnit.DocTest
end
end
@doc """
Defines a test with a string.
Provides a convenient macro that allows a test to be
defined with a string. This macro automatically inserts
the atom `:ok` as the last line of the test. That said,
a passing test always returns `:ok`, but, more importantly,
it forces Elixir to not tail call optimize the test and
therefore avoids hiding lines from the backtrace.
## Examples
test "true is equal to true" do
assert true == true
end
"""
defmacro test(message, var \\ quote(do: _), contents) do
contents =
case contents do
[do: block] ->
quote do
unquote(block)
:ok
end
_ ->
quote do
try(unquote(contents))
:ok
end
end
var = Macro.escape(var)
contents = Macro.escape(contents, unquote: true)
quote bind_quoted: [var: var, contents: contents, message: message] do
name = ExUnit.Case.register_test(__ENV__, :test, message, [])
def unquote(name)(unquote(var)), do: unquote(contents)
end
end
@doc """
Defines a not implemented test with a string.
Provides a convenient macro that allows a test to be defined
with a string, but not yet implemented. The resulting test will
always fail and print a "Not implemented" error message. The
resulting test case is also tagged with `:not_implemented`.
## Examples
test "this will be a test in future"
"""
defmacro test(message) do
quote bind_quoted: binding() do
name = ExUnit.Case.register_test(__ENV__, :test, message, [:not_implemented])
def unquote(name)(_), do: flunk("Not implemented")
end
end
@doc """
Describes tests together.
Every describe block receives a name which is used as prefix for
upcoming tests. Inside a block, `ExUnit.Callbacks.setup/1` may be
invoked and it will define a setup callback to run only for the
current block. The describe name is also added as a tag, allowing
developers to run tests for specific blocks.
## Examples
defmodule StringTest do
use ExUnit.Case, async: true
describe "String.capitalize/1" do
test "first grapheme is in uppercase" do
assert String.capitalize("hello") == "Hello"
end
test "converts remaining graphemes to lowercase" do
assert String.capitalize("HELLO") == "Hello"
end
end
end
When using Mix, you can run all tests in a describe block by name:
mix test --only describe:"String.capitalize/1"
or by passing the exact line the describe block starts on:
mix test path/to/file:123
Note describe blocks cannot be nested. Instead of relying on hierarchy
for composition, developers should build on top of named setups. For
example:
defmodule UserManagementTest do
use ExUnit.Case, async: true
describe "when user is logged in and is an admin" do
setup [:log_user_in, :set_type_to_admin]
test ...
end
describe "when user is logged in and is a manager" do
setup [:log_user_in, :set_type_to_manager]
test ...
end
defp log_user_in(context) do
# ...
end
end
By forbidding hierarchies in favor of named setups, it is straightforward
for the developer to glance at each describe block and know exactly the
setup steps involved.
"""
defmacro describe(message, do: block) do
quote do
ExUnit.Case.__describe__(__MODULE__, __ENV__.line, unquote(message))
try do
unquote(block)
after
@ex_unit_describe nil
Module.delete_attribute(__MODULE__, :describetag)
end
end
end
@doc false
def __describe__(module, line, message) do
if Module.get_attribute(module, :ex_unit_describe) do
raise "cannot call \"describe\" inside another \"describe\". See the documentation " <>
"for ExUnit.Case.describe/2 on named setups and how to handle hierarchies"
end
cond do
not is_binary(message) ->
raise ArgumentError, "describe name must be a string, got: #{inspect(message)}"
message in Module.get_attribute(module, :ex_unit_used_describes) ->
raise ExUnit.DuplicateDescribeError,
"describe #{inspect(message)} is already defined in #{inspect(module)}"
true ->
:ok
end
if Module.get_attribute(module, :describetag) != [] do
raise "@describetag must be set inside describe/2 blocks"
end
Module.put_attribute(module, :ex_unit_describe, {line, message})
Module.put_attribute(module, :ex_unit_used_describes, message)
:ok
end
@doc false
defmacro __before_compile__(_) do
quote do
def __ex_unit__ do
%ExUnit.TestModule{name: __MODULE__, tests: @ex_unit_tests}
end
end
end
@doc false
def __after_compile__(%{module: module}, _) do
if Module.get_attribute(module, :ex_unit_async) do
ExUnit.Server.add_async_module(module)
else
ExUnit.Server.add_sync_module(module)
end
end
@doc """
Registers a function to run as part of this case.
This is used by third-party projects, like QuickCheck, to
implement macros like `property/3` that works like `test`
but instead defines a property. See `test/3` implementation
for an example of invoking this function.
The test type will be converted to a string and pluralized for
display. You can use `ExUnit.plural_rule/2` to set a custom
pluralization.
"""
def register_test(%{module: mod, file: file, line: line}, test_type, name, tags) do
moduletag = Module.get_attribute(mod, :moduletag)
unless moduletag do
raise "cannot define #{test_type}. Please make sure you have invoked " <>
"\"use ExUnit.Case\" in the current module"
end
registered_attributes = Module.get_attribute(mod, :ex_unit_registered)
registered = Map.new(registered_attributes, &{&1, Module.get_attribute(mod, &1)})
tag = Module.delete_attribute(mod, :tag)
async = Module.get_attribute(mod, :ex_unit_async)
{name, describe, describe_line, describetag} =
case Module.get_attribute(mod, :ex_unit_describe) do
{line, describe} ->
description = :"#{test_type} #{describe} #{name}"
{description, describe, line, Module.get_attribute(mod, :describetag)}
_ ->
{:"#{test_type} #{name}", nil, nil, []}
end
if Module.defines?(mod, {name, 1}) do
raise ExUnit.DuplicateTestError, ~s("#{name}" is already defined in #{inspect(mod)})
end
tags =
(tags ++ tag ++ describetag ++ moduletag)
|> normalize_tags
|> validate_tags
|> Map.merge(%{
line: line,
file: file,
registered: registered,
async: async,
describe: describe,
describe_line: describe_line,
test_type: test_type
})
test = %ExUnit.Test{name: name, case: mod, tags: tags, module: mod}
Module.put_attribute(mod, :ex_unit_tests, test)
Enum.each(registered_attributes, fn attribute ->
Module.delete_attribute(mod, attribute)
end)
name
end
@doc """
Registers a new attribute to be used during `ExUnit.Case` tests.
The attribute values will be available through `context.registered`.
Registered values are cleared after each `ExUnit.Case.test/3` similar
to `@tag`.
`Module.register_attribute/3` is used to register the attribute,
this function takes the same options.
## Examples
defmodule MyTest do
use ExUnit.Case
ExUnit.Case.register_attribute(__MODULE__, :fixtures, accumulate: true)
@fixtures :user
@fixtures {:post, insert: false}
test "using custom attribute", context do
assert context.registered.fixtures == [{:post, insert: false}, :user]
end
test "custom attributes are cleared per test", context do
assert context.registered.fixtures == []
end
end
"""
def register_attribute(env, name, opts \\ [])
def register_attribute(%{module: module}, name, opts) do
register_attribute(module, name, opts)
end
def register_attribute(mod, name, opts) when is_atom(mod) and is_atom(name) and is_list(opts) do
Module.register_attribute(mod, name, opts)
Module.put_attribute(mod, :ex_unit_registered, name)
end
defp validate_tags(tags) do
for tag <- @reserved, Map.has_key?(tags, tag) do
raise "cannot set tag #{inspect(tag)} because it is reserved by ExUnit"
end
unless is_atom(tags[:test_type]) do
raise("value for tag \":test_type\" must be an atom")
end
tags
end
defp normalize_tags(tags) do
Enum.reduce(Enum.reverse(tags), %{}, fn
tag, acc when is_atom(tag) -> Map.put(acc, tag, true)
tag, acc when is_list(tag) -> tag |> Enum.into(acc)
end)
end
end
| 30.145648 | 98 | 0.663622 |
08bd74a9380d683e452fd1c4496503d81d0add80 | 6,534 | ex | Elixir | lib/app/router.ex | george124816/elixir-telegram-bot-boilerplate | 8bfd24d46b4caacd705dfeac3b379d39cdd0b6c9 | [
"MIT"
] | 148 | 2016-11-19T05:59:26.000Z | 2022-02-28T05:09:29.000Z | lib/app/router.ex | george124816/elixir-telegram-bot-boilerplate | 8bfd24d46b4caacd705dfeac3b379d39cdd0b6c9 | [
"MIT"
] | 17 | 2017-01-14T23:49:04.000Z | 2020-06-02T13:35:21.000Z | lib/app/router.ex | george124816/elixir-telegram-bot-boilerplate | 8bfd24d46b4caacd705dfeac3b379d39cdd0b6c9 | [
"MIT"
] | 37 | 2016-11-19T08:40:55.000Z | 2022-02-25T23:37:39.000Z | defmodule App.Router do
@bot_name Application.get_env(:app, :bot_name)
# Code injectors
defmacro __using__(_opts) do
quote do
require Logger
import App.Router
def match_message(message) do
try do
apply(__MODULE__, :do_match_message, [message])
rescue
err in FunctionClauseError ->
Logger.log(:warn, """
Errored when matching command. #{Poison.encode!(err)}
Message was: #{Poison.encode!(message)}
""")
end
end
end
end
def generate_message_matcher(handler) do
quote do
def do_match_message(var!(update)) do
handle_message(unquote(handler), [var!(update)])
end
end
end
defp generate_command(command, handler) do
quote do
def do_match_message(
%{
message: %{
text: "/" <> unquote(command)
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
message: %{
text: "/" <> unquote(command) <> " " <> _
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
message: %{
text: "/" <> unquote(command) <> "@" <> unquote(@bot_name)
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
message: %{
text: "/" <> unquote(command) <> "@" <> unquote(@bot_name) <> " " <> _
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_inline_query_matcher(handler) do
quote do
def do_match_message(%{inline_query: inline_query} = var!(update))
when not is_nil(inline_query) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_inline_query_command(command, handler) do
quote do
def do_match_message(
%{
inline_query: %{query: "/" <> unquote(command)}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
inline_query: %{query: "/" <> unquote(command) <> " " <> _}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_callback_query_matcher(handler) do
quote do
def do_match_message(%{callback_query: callback_query} = var!(update))
when not is_nil(callback_query) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_callback_query_command(command, handler) do
quote do
def do_match_message(
%{
callback_query: %{data: "/" <> unquote(command)}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
callback_query: %{data: "/" <> unquote(command) <> " " <> _}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
end
end
# Receiver Macros
## Match All
defmacro message(do: function) do
generate_message_matcher(function)
end
defmacro message(module, function) do
generate_message_matcher({module, function})
end
## Command
defmacro command(commands, do: function)
when is_list(commands) do
Enum.map(commands, fn command ->
generate_command(command, function)
end)
end
defmacro command(command, do: function) do
generate_command(command, function)
end
defmacro command(commands, module, function)
when is_list(commands) do
Enum.map(commands, fn command ->
generate_command(command, {module, function})
end)
end
defmacro command(command, module, function) do
generate_command(command, {module, function})
end
## Inline query
defmacro inline_query(do: function) do
generate_inline_query_matcher(function)
end
defmacro inline_query(module, function) do
generate_inline_query_matcher({module, function})
end
defmacro inline_query_command(commands, do: function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_inline_query_command(item, function)
end)
end
defmacro inline_query_command(command, do: function) do
generate_inline_query_command(command, function)
end
defmacro inline_query_command(commands, module, function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_inline_query_command(item, {module, function})
end)
end
defmacro inline_query_command(command, module, function) do
generate_inline_query_command(command, {module, function})
end
## Callback query
defmacro callback_query(do: function) do
generate_callback_query_matcher(function)
end
defmacro callback_query(module, function) do
generate_callback_query_matcher({module, function})
end
defmacro callback_query_command(commands, do: function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_callback_query_command(item, function)
end)
end
defmacro callback_query_command(command, do: function) do
generate_callback_query_command(command, function)
end
defmacro callback_query_command(commands, module, function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_callback_query_command(item, {module, function})
end)
end
defmacro callback_query_command(command, module, function) do
generate_callback_query_command(command, {module, function})
end
# Helpers
def handle_message({module, function}, update)
when is_atom(function) and is_list(update) do
Task.start(fn ->
apply(module, function, [hd(update)])
end)
end
def handle_message({module, function}, update)
when is_atom(function) do
Task.start(fn ->
apply(module, function, [update])
end)
end
def handle_message(function, update)
when is_function(function) do
Task.start(fn ->
function.()
end)
end
def handle_message(_, _), do: nil
end
| 25.130769 | 86 | 0.609428 |
08bdb6862cc4987a72deb0f46fc38c9b6eeef196 | 1,063 | ex | Elixir | lib/blue_jet_web/views/point_transaction_view.ex | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 44 | 2018-05-09T01:08:57.000Z | 2021-01-19T07:25:26.000Z | lib/blue_jet_web/views/point_transaction_view.ex | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 36 | 2018-05-08T23:59:54.000Z | 2018-09-28T13:50:30.000Z | lib/blue_jet_web/views/point_transaction_view.ex | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 9 | 2018-05-09T14:09:19.000Z | 2021-03-21T21:04:04.000Z | defmodule BlueJetWeb.PointTransactionView do
use BlueJetWeb, :view
use JaSerializer.PhoenixView
attributes [
:status,
:code,
:name,
:label,
:reason_label,
:amount,
:balance_after_commit,
:caption,
:description,
:custom_data,
:committed_at,
:inserted_at
]
has_one :point_account, serializer: BlueJetWeb.PointAccountView, identifiers: :always
has_one :source, serializer: BlueJetWeb.IdentifierView, identifiers: :always
def type do
"PointTransaction"
end
def source(%{ source_id: nil }, _), do: nil
def source(%{ source_id: source_id, source_type: source_type, source: nil }, _), do: %{ id: source_id, type: source_type }
def source(%{ source: source }, _), do: source
def point_account(%{ point_account_id: nil }, _), do: nil
def point_account(%{ point_account_id: point_account_id, point_account: %Ecto.Association.NotLoaded{} }, _) do
%{ id: point_account_id, type: "PointAccount" }
end
def point_account(%{ point_account: point_account }, _), do: point_account
end
| 25.309524 | 124 | 0.695202 |
08bdf184ede05e60e7962dc42ac1354d85ac33f9 | 5,438 | ex | Elixir | lib/brando/trait.ex | univers-agency/brando | 69c3c52498a3f64518da3522cd9f27294a52cc68 | [
"Apache-2.0"
] | 1 | 2020-04-26T09:53:02.000Z | 2020-04-26T09:53:02.000Z | lib/brando/trait.ex | univers-agency/brando | 69c3c52498a3f64518da3522cd9f27294a52cc68 | [
"Apache-2.0"
] | 198 | 2019-08-20T16:16:07.000Z | 2020-07-03T15:42:07.000Z | lib/brando/trait.ex | univers-agency/brando | 69c3c52498a3f64518da3522cd9f27294a52cc68 | [
"Apache-2.0"
] | null | null | null | defmodule Brando.Trait do
@moduledoc """
## Changeset phase
If you need your trait's `changeset_mutator` to run before `validate_required`
when your `changeset` is generated, you can set `@changeset_phase :before_validate_required`
in your trait. This is useful if you're inserting a required field into the changeset and
do not want it erroring out. The default changeset phase is `:after_validate_required`.
"""
@type changeset :: Ecto.Changeset.t()
@type entry :: map()
@type user :: Brando.Users.User.t()
@type config :: list()
@type opts :: Keyword.t()
@callback changeset_mutator(module, config, changeset, user, opts) :: changeset
@callback trait_attributes(list(), list(), list()) :: list()
@callback trait_assets(list(), list(), list()) :: list()
@callback trait_relations(list(), list(), list()) :: list()
@callback validate(module, config) :: true | no_return
@callback after_save(entry, changeset, user) :: any()
@callback before_save(changeset, user) :: any()
defmacro __using__(_) do
defprotocol Module.concat([__CALLER__.module, Implemented]) do
@doc "Dummy function to ensure implementation"
def implemented(dummy)
end
quote location: :keep do
@behaviour Brando.Trait
import Brando.Blueprint.Assets
import Brando.Blueprint.Attributes
import Brando.Blueprint.Relations
import Brando.Trait
@before_compile Brando.Trait
@changeset_phase :after_validate_required
# Runs if no mutator is set.
# NOTE: This does not function as a fallback clause if a mutator is implemented.
# In that case you must implement the fallback yourself.
def changeset_mutator(_module, _cfg, changeset, _user, _opts), do: changeset
defoverridable changeset_mutator: 5
def validate(_, _), do: true
defoverridable validate: 2
def trait_attributes(_, _, _), do: []
defoverridable trait_attributes: 3
def before_save(changeset, _), do: changeset
defoverridable before_save: 2
def after_save(_, _, _), do: :ok
defoverridable after_save: 3
def list_implementations, do: list_implementations(__MODULE__)
end
end
defmacro __before_compile__(_) do
quote do
if Module.get_attribute(__MODULE__, :attrs) do
def all_trait_attributes(attrs, assets, relations) do
trait_attributes(attrs, assets, relations) ++ @attrs
end
else
def all_trait_attributes(attrs, assets, relations) do
trait_attributes(attrs, assets, relations)
end
end
if Module.get_attribute(__MODULE__, :relations) do
def trait_relations(_, _, _) do
@relations
end
defoverridable trait_relations: 3
else
def trait_relations(_, _, _) do
[]
end
defoverridable trait_relations: 3
end
if Module.get_attribute(__MODULE__, :assets) do
def trait_assets(_, _, _) do
@assets
end
defoverridable trait_assets: 3
else
def trait_assets(_, _, _) do
[]
end
defoverridable trait_assets: 3
end
def __changeset_phase__ do
@changeset_phase
end
end
end
def run_changeset_mutators(changeset, module, traits, user, opts) do
Enum.reduce(traits, changeset, fn {trait, trait_opts}, updated_changeset ->
trait.changeset_mutator(module, Enum.into(trait_opts, %{}), updated_changeset, user, opts)
end)
end
def split_traits_by_changeset_phase(traits) do
Enum.split_with(traits, &(elem(&1, 0).__changeset_phase__() == :before_validate_required))
end
def get_relations(nil), do: []
@doc """
NOTE: This list of attrs and relations does NOT include added
attributes and relations from other traits, only attrs and relations
specified directly in the blueprint
"""
def get_relations(attrs, relations, assets, traits) do
Enum.reduce(traits, [], fn {trait, _opts}, rf ->
trait.trait_relations(attrs, assets, relations) ++ rf
end)
end
def get_attributes(nil), do: []
@doc """
NOTE: This list of attrs and relations does NOT include added
attributes and relations from other traits, only attrs and relations
specified directly in the blueprint
"""
def get_attributes(attrs, assets, relations, traits) do
Enum.reduce(traits, [], fn {trait, _opts}, rf ->
trait.all_trait_attributes(attrs, assets, relations) ++ rf
end)
end
def get_assets(nil), do: []
@doc """
NOTE: This list of attrs and relations does NOT include added
attributes and relations from other traits, only attrs and relations
specified directly in the blueprint
"""
def get_assets(attrs, assets, relations, traits) do
Enum.reduce(traits, [], fn {trait, _opts}, rf ->
trait.trait_assets(attrs, assets, relations) ++ rf
end)
end
def list_implementations(trait) do
{:consolidated, impls} = Module.concat([trait, Implemented]).__protocol__(:impls)
impls
end
def run_trait_before_save_callbacks(changeset, schema, user) do
Enum.reduce(schema.__traits__(), changeset, fn {trait, _opts}, updated_cs ->
trait.before_save(updated_cs, user)
end)
end
def run_trait_after_save_callbacks(schema, entry, changeset, user) do
for {trait, _} <- schema.__traits__() do
trait.after_save(entry, changeset, user)
end
end
end
| 30.897727 | 96 | 0.679846 |
08be07a2b661088ceab33d886c98c7d1bc927287 | 334 | ex | Elixir | lib/supabase_surface/components/icons/icon_map.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | 5 | 2021-06-08T08:02:43.000Z | 2022-02-09T23:13:46.000Z | lib/supabase_surface/components/icons/icon_map.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | null | null | null | lib/supabase_surface/components/icons/icon_map.ex | treebee/supabase-surface | 5a184ca92323c085dd81e2fc8aa8c10367f2382e | [
"Apache-2.0"
] | 1 | 2021-07-14T05:20:31.000Z | 2021-07-14T05:20:31.000Z | defmodule SupabaseSurface.Components.Icons.IconMap do
use SupabaseSurface.Components.Icon
@impl true
def render(assigns) do
icon_size = IconContainer.get_size(assigns.size)
~F"""
<IconContainer assigns={assigns}>
{Feathericons.map(width: icon_size, height: icon_size)}
</IconContainer>
"""
end
end
| 22.266667 | 61 | 0.712575 |
08be0c2a773939502f1480141c9d3c231eadddd9 | 9,911 | ex | Elixir | lib/sparrow/hns/v1/android.ex | muratgurdal/sparrow | 0bb9ff4c4ab21802bcba369b3496749d2637b473 | [
"Apache-2.0"
] | null | null | null | lib/sparrow/hns/v1/android.ex | muratgurdal/sparrow | 0bb9ff4c4ab21802bcba369b3496749d2637b473 | [
"Apache-2.0"
] | null | null | null | lib/sparrow/hns/v1/android.ex | muratgurdal/sparrow | 0bb9ff4c4ab21802bcba369b3496749d2637b473 | [
"Apache-2.0"
] | 1 | 2021-07-06T11:29:18.000Z | 2021-07-06T11:29:18.000Z | defmodule Sparrow.HNS.V1.Android do
@moduledoc """
Struct reflecting HNS object(AndroidConfig).
See: https://firebase.google.com/docs/reference/hns/rest/v1/projects.messages#AndroidConfig
"""
@type priority :: :NORMAL | :HIGH
@type field ::
{:collapse_key, String.t()}
| {:priority, priority}
| {:ttl, String.t()}
| {:restricted_package_name, String.t()}
| {:data, map}
@type key ::
:collapse_key
| :priority
| :ttl
| :restricted_package_name
| :data
@type value :: String.t() | priority | map
@type t :: %__MODULE__{
fields: [field],
notification: Sparrow.HNS.V1.Android.Notification.t()
}
defstruct [
:fields,
:notification
]
@doc """
Create new empty `Sparrow.HNS.V1.Android`.
"""
@spec new :: t
def new do
%__MODULE__{
fields: [],
notification: Sparrow.HNS.V1.Android.Notification.new()
}
end
@doc """
Changes `Sparrow.HNS.V1.Android` to map for easier change to json.
"""
@spec to_map(t) :: map
def to_map(android) do
notification =
Sparrow.HNS.V1.Android.Notification.to_map(android.notification)
android.fields
|> Map.new()
|> Map.put(:notification, notification)
end
@doc """
Adds collapse_key to `Sparrow.HNS.V1.Android`.
"""
@spec add_collapse_key(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_collapse_key(android, value) do
add(android, :collapse_key, value)
end
@doc """
Adds priority to `Sparrow.HNS.V1.Android`.
"""
@spec add_priority(__MODULE__.t(), priority) :: __MODULE__.t()
def add_priority(android, :NORMAL) do
add(android, :priority, :NORMAL)
end
def add_priority(android, :HIGH) do
add(android, :priority, :HIGH)
end
@doc """
Adds ttl to `Sparrow.HNS.V1.Android`.
## Arguments
* `android` - Sparrow.HNS.V1.Android struct you want add `ttl` param to.
* 'value' - non_neg_integer value (in seconds) that will be converted to correct format: 5 -> "5s"
"""
@spec add_ttl(__MODULE__.t(), non_neg_integer) :: __MODULE__.t()
def add_ttl(android, value) do
string_value = Integer.to_string(value) <> "s"
add(android, :ttl, string_value)
end
@doc """
Adds restricted_package_name to `Sparrow.HNS.V1.Android`.
"""
@spec add_restricted_package_name(__MODULE__.t(), String.t()) ::
__MODULE__.t()
def add_restricted_package_name(android, value) do
add(android, :restricted_package_name, value)
end
@doc """
Adds data to `Sparrow.HNS.V1.Android`.
"""
@spec add_data(__MODULE__.t(), map) :: __MODULE__.t()
def add_data(android, value) do
add(android, :data, value)
end
@doc """
Adds title to the `Sparrow.HNS.V1.Android`.
The notification's title.
If present, it will override google.firebase.hns.v1.Notification.title.
"""
@spec add_title(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_title(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:title,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds body to the `Sparrow.HNS.V1.Android`.
The notification's body text.
If present, it will override google.firebase.hns.v1.Notification.body.
"""
@spec add_body(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_body(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:body,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds icon to the `Sparrow.HNS.V1.Android`.
The notification's icon.
Sets the notification icon to myicon for drawable resource myicon.
If you don't send this key in the request,
HNS displays the launcher icon specified in your app manifest.
"""
@spec add_icon(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_icon(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:icon,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds color to the `Sparrow.HNS.V1.Android`.
The notification's icon color, expressed in #rrggbb format.
"""
@spec add_color(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_color(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:color,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds sound to the `Sparrow.HNS.V1.Android`.
The sound to play when the device receives the notification.
Supports "default" or the filename of a sound resource bundled in the app.
Sound files must reside in /res/raw/.
"""
@spec add_sound(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_sound(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:sound,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds tag to the `Sparrow.HNS.V1.Android`.
Identifier used to replace existing notifications in the notification drawer.
If not specified, each request creates a new notification.
If specified and a notification with the same tag is already being shown,
the new notification replaces the existing one in the notification drawer.
"""
@spec add_tag(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_tag(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:tag,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds click_action to the `Sparrow.HNS.V1.Android`.
The action associated with a user click on the notification.
If specified, an activity with a matching intent filter is launched when a user clicks on the notification.
"""
@spec add_click_action(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_click_action(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:click_action,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds body_loc_key to the `Sparrow.HNS.V1.Android`.
The key to the body string in the app's string resources to use to localize the body text to the user's current localization.
See String Resources (https://goo.gl/NdFZGI) for more information.
"""
@spec add_body_loc_key(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_body_loc_key(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:body_loc_key,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds body_loc_args[] to the `Sparrow.HNS.V1.Android`.
Variable string values to be used in place of the format specifiers in body_loc_key to use to localize the body text to the user's current localization.
See Formatting and Styling for more information.
"""
@spec add_body_loc_args(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_body_loc_args(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:"body_loc_args[]",
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds title_loc_key to the `Sparrow.HNS.V1.Android`.
The key to the title string in the app's string resources to use to localize the title text to the user's current localization.
See String Resources for more information.
"""
@spec add_title_loc_key(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_title_loc_key(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:title_loc_key,
value
)
%{android | notification: updated_android_notification}
end
@doc """
Adds title_loc_args[] to the `Sparrow.HNS.V1.Android`.
Variable string values to be used in place of the format specifiers in title_loc_key to use to localize the title text to the user's current localization.
See Formatting and Styling for more information.
"""
@spec add_title_loc_args(__MODULE__.t(), String.t()) :: __MODULE__.t()
def add_title_loc_args(android, value) do
updated_android_notification =
Sparrow.HNS.V1.Android.Notification.add(
android.notification,
:"title_loc_args[]",
value
)
%{android | notification: updated_android_notification}
end
@spec add(__MODULE__.t(), key, value) :: __MODULE__.t()
defp add(android, key, value) do
%{android | fields: [{key, value} | android.fields]}
end
@spec normalize(t | nil) ::
{:ok, t | nil} | {:error, :invalid_notification}
def normalize(nil), do: {:ok, nil}
def normalize(notification) do
case Keyword.get(notification.fields, :data) do
nil ->
{:ok, notification}
data ->
data = Enum.map(data, &normalize_value/1)
case Enum.all?(data) do
false ->
{:error, :invalid_notification}
true ->
{:ok,
%{
notification
| fields: Keyword.put(notification.fields, :data, Map.new(data))
}}
end
end
end
defp normalize_value({k, v}) do
{k, to_string(v)}
rescue
Protocol.UndefinedError -> false
end
end
| 29.85241 | 158 | 0.660377 |
08be3615ce04af68d9a167acae25c8bd4beca995 | 133 | exs | Elixir | config/config.exs | dch/sofa | 38cfec41eede03a383cee86682557cf30f13bebf | [
"BSD-2-Clause"
] | null | null | null | config/config.exs | dch/sofa | 38cfec41eede03a383cee86682557cf30f13bebf | [
"BSD-2-Clause"
] | 1 | 2021-07-08T06:06:45.000Z | 2021-07-27T12:36:39.000Z | config/config.exs | dch/sofa | 38cfec41eede03a383cee86682557cf30f13bebf | [
"BSD-2-Clause"
] | 1 | 2021-07-27T15:21:20.000Z | 2021-07-27T15:21:20.000Z | import Config
if config_env() == :test do
config :tesla, adapter: Tesla.Mock
else
config :tesla, adapter: Tesla.Adapter.Gun
end
| 16.625 | 43 | 0.729323 |
08be3f55dfd8a7d428d30641077068eae9eca996 | 831 | ex | Elixir | lib/coherence/plugs/authorization/credential_store/agent.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | lib/coherence/plugs/authorization/credential_store/agent.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | lib/coherence/plugs/authorization/credential_store/agent.ex | remigijusj/coherence | 36fe35b0bfe7ac63b44b4046f3ba62f2fe69603a | [
"MIT"
] | null | null | null | defmodule Coherence.CredentialStore.Agent do
@behaviour Coherence.CredentialStore
@doc """
Starts a new credentials store.
"""
def start_link do
Agent.start_link(&HashDict.new/0, name: __MODULE__)
end
@doc """
Gets the user data for the given credentials
"""
def get_user_data(credentials) do
Agent.get(__MODULE__, &HashDict.get(&1, credentials))
end
@doc """
Puts the `user_data` for the given `credentials`.
"""
def put_credentials(credentials, user_data) do
Agent.update(__MODULE__, &HashDict.put(&1, credentials, user_data))
end
@doc """
Deletes `credentials` from the store.
Returns the current value of `credentials`, if `credentials` exists.
"""
def delete_credentials(credentials) do
Agent.get_and_update(__MODULE__, &HashDict.pop(&1, credentials))
end
end
| 23.742857 | 71 | 0.709988 |
08be5444b870544173609492e829c3630f0107e5 | 2,286 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/target_https_proxies_scoped_list_warning.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/target_https_proxies_scoped_list_warning.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/target_https_proxies_scoped_list_warning.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"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.Compute.V1.Model.TargetHttpsProxiesScopedListWarning do
@moduledoc """
Informational warning which replaces the list of backend services when the list is empty.
## Attributes
* `code` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response.
* `data` (*type:* `list(GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarningData.t)`, *default:* `nil`) - [Output Only] Metadata about this warning in key: value format. For example:
"data": [ { "key": "scope", "value": "zones/us-east1-d" }
* `message` (*type:* `String.t`, *default:* `nil`) - [Output Only] A human-readable description of the warning code.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => String.t() | nil,
:data =>
list(GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarningData.t()) | nil,
:message => String.t() | nil
}
field(:code)
field(:data, as: GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarningData, type: :list)
field(:message)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarning do
def decode(value, options) do
GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarning.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarning do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.105263 | 196 | 0.728346 |
08be56aeed497c843e2a0fbce4c0595292e24664 | 1,589 | ex | Elixir | lib/bike_brigade_web/live/campaign_live/new.ex | bikebrigade/dispatch | eb622fe4f6dab7c917d678d3d7a322a01f97da44 | [
"Apache-2.0"
] | 28 | 2021-10-11T01:53:53.000Z | 2022-03-24T17:45:55.000Z | lib/bike_brigade_web/live/campaign_live/new.ex | bikebrigade/dispatch | eb622fe4f6dab7c917d678d3d7a322a01f97da44 | [
"Apache-2.0"
] | 20 | 2021-10-21T08:12:31.000Z | 2022-03-31T13:35:53.000Z | lib/bike_brigade_web/live/campaign_live/new.ex | bikebrigade/dispatch | eb622fe4f6dab7c917d678d3d7a322a01f97da44 | [
"Apache-2.0"
] | null | null | null | defmodule BikeBrigadeWeb.CampaignLive.New do
use BikeBrigadeWeb, :live_view
alias BikeBrigade.Delivery
alias BikeBrigade.Delivery.Campaign
alias NimbleCSV.RFC4180, as: CSV
@impl Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:page, :campaigns)
|> assign(:page_title, "New Campaign")
|> assign(:campaign, %Campaign{})
|> assign(:changeset, Delivery.change_campaign(%Campaign{}))
|> assign(:delivery_spreadsheet, nil)
|> allow_upload(:delivery_spreadsheet,
accept: ~w(.csv),
progress: &handle_progress/3,
auto_upload: true
)}
end
@impl Phoenix.LiveView
def handle_event("validate", %{"campaign" => campaign_params}, socket) do
IO.inspect(campaign_params)
changeset =
socket.assigns.campaign
|> Delivery.change_campaign(campaign_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
def handle_event("save", params, socket) do
IO.inspect(params)
{:noreply, socket}
end
defp handle_progress(:delivery_spreadsheet, entry, socket) do
if entry.done? do
uploaded_file =
consume_uploaded_entry(socket, entry, fn %{path: path} ->
File.read!(path)
|> CSV.parse_string(skip_headers: false)
end)
{:noreply, socket |> assign(:delivery_spreadsheet, uploaded_file)}
else
{:noreply, socket}
end
end
defp pickup_location(%Ecto.Changeset{} = changeset) do
Ecto.Changeset.fetch_field!(changeset, :pickup_location)
end
end
| 26.483333 | 75 | 0.668345 |
08be6243367c49b8378c43a70bb79b9de25f4858 | 1,113 | ex | Elixir | lib/imager/instrumenter/storage.ex | appunite/imager | b41f76be975faf4d255ad0a5d8e972df1924356b | [
"MIT"
] | 55 | 2018-10-02T14:56:04.000Z | 2021-12-10T21:08:07.000Z | lib/imager/instrumenter/storage.ex | appunite/imager | b41f76be975faf4d255ad0a5d8e972df1924356b | [
"MIT"
] | 27 | 2018-10-02T14:57:09.000Z | 2019-04-11T07:51:11.000Z | lib/imager/instrumenter/storage.ex | appunite/imager | b41f76be975faf4d255ad0a5d8e972df1924356b | [
"MIT"
] | 3 | 2018-10-12T18:31:41.000Z | 2020-04-22T15:26:25.000Z | defmodule Imager.Instrumenter.Storage do
def setup do
:prometheus_counter.declare(
name: :store_retrieved_total,
help: "Count of retrieves from the given store",
labels: [:store]
)
:prometheus_counter.declare(
name: :store_saved_total,
help: "Count of saves into the given store",
labels: [:store]
)
:prometheus_summary.declare(
name: :store_retrieved_bytes,
help: "Bytes retrieved from the store",
labels: [:store]
)
:prometheus_summary.declare(
name: :store_saved_bytes,
help: "Saved bytes to given store",
labels: [:store]
)
end
def retrieved(stream, store) do
:prometheus_counter.inc(:store_retrieved_total, [store])
Stream.each(
stream,
&:prometheus_summary.observe(
:store_retrieved_bytes,
[store],
byte_size(&1)
)
)
end
def saved(stream, store) do
:prometheus_counter.inc(:store_saved_total, [store])
Stream.each(
stream,
&:prometheus_summary.observe(:store_saved_bytes, [store], byte_size(&1))
)
end
end
| 22.26 | 78 | 0.634322 |
08be65ee80e3c3a16532bdbdd1ab7bf4dd4d14c7 | 8,091 | exs | Elixir | test/lib/bamboo/mailer_test.exs | speeddragon/bamboo | b7bc9df132c7710ac3344be677b22a156e4eecd3 | [
"MIT"
] | null | null | null | test/lib/bamboo/mailer_test.exs | speeddragon/bamboo | b7bc9df132c7710ac3344be677b22a156e4eecd3 | [
"MIT"
] | null | null | null | test/lib/bamboo/mailer_test.exs | speeddragon/bamboo | b7bc9df132c7710ac3344be677b22a156e4eecd3 | [
"MIT"
] | null | null | null | defmodule Bamboo.MailerTest do
use ExUnit.Case
alias Bamboo.Email
defmodule FooAdapter do
def deliver(email, config) do
send(:mailer_test, {:deliver, email, config})
end
def handle_config(config), do: config
def supports_attachments?, do: true
end
defmodule CustomConfigAdapter do
def deliver(email, config) do
send(:mailer_test, {:deliver, email, config})
end
def handle_config(config) do
config |> Map.put(:custom_key, "Set by the adapter")
end
end
defmodule AdapterWithoutAttachmentSupport do
def deliver(_email, _config) do
:noop
end
def handle_config(config), do: config
end
@custom_config adapter: CustomConfigAdapter, foo: :bar
Application.put_env(:bamboo, __MODULE__.CustomConfigMailer, @custom_config)
defmodule CustomConfigMailer do
use Bamboo.Mailer, otp_app: :bamboo
end
@mailer_config adapter: AdapterWithoutAttachmentSupport, foo: :bar
Application.put_env(:bamboo, __MODULE__.AdapterWithoutAttachmentSupportMailer, @mailer_config)
defmodule AdapterWithoutAttachmentSupportMailer do
use Bamboo.Mailer, otp_app: :bamboo
end
@mailer_config adapter: FooAdapter, foo: :bar
Application.put_env(:bamboo, __MODULE__.FooMailer, @mailer_config)
defmodule FooMailer do
use Bamboo.Mailer, otp_app: :bamboo
end
setup do
Process.register(self(), :mailer_test)
:ok
end
test "raise if adapter does not support attachments and attachments are sent" do
path = Path.join(__DIR__, "../../support/attachment.docx")
email = new_email(to: "foo@bar.com") |> Email.put_attachment(path)
assert_raise RuntimeError, ~r/does not support attachments/, fn ->
AdapterWithoutAttachmentSupportMailer.deliver_now(email)
end
assert_raise RuntimeError, ~r/does not support attachments/, fn ->
AdapterWithoutAttachmentSupportMailer.deliver_later(email)
end
end
test "does not raise if adapter supports attachments" do
path = Path.join(__DIR__, "../../support/attachment.docx")
email = new_email(to: "foo@bar.com") |> Email.put_attachment(path)
FooMailer.deliver_now(email)
assert_received {:deliver, _email, _config}
end
test "does not raise if no attachments are on the email" do
email = new_email(to: "foo@bar.com")
AdapterWithoutAttachmentSupportMailer.deliver_now(email)
end
test "uses adapter's handle_config/1 to customize or validate the config" do
email = new_email(to: "foo@bar.com")
CustomConfigMailer.deliver_now(email)
assert_received {:deliver, _email, config}
assert config.custom_key == "Set by the adapter"
end
test "sets a default deliver_later_strategy if none is set" do
email = new_email(to: "foo@bar.com")
FooMailer.deliver_now(email)
assert_received {:deliver, _email, config}
assert config.deliver_later_strategy == Bamboo.TaskSupervisorStrategy
end
test "deliver/1 raises a helpful error message" do
assert_raise RuntimeError, ~r/Use deliver_now/, fn ->
FooMailer.deliver(:anything)
end
end
test "deliver_now/1 calls the adapter with the email and config as a map" do
email = new_email(to: "foo@bar.com")
returned_email = FooMailer.deliver_now(email)
assert returned_email == Bamboo.Mailer.normalize_addresses(email)
assert_received {:deliver, %Bamboo.Email{}, config}
config_with_default_strategy =
Enum.into(@mailer_config, %{})
|> Map.put(:deliver_later_strategy, Bamboo.TaskSupervisorStrategy)
assert config == config_with_default_strategy
end
test "deliver_now/1 with no from address" do
assert_raise Bamboo.EmptyFromAddressError, fn ->
FooMailer.deliver_now(new_email(from: nil))
end
assert_raise Bamboo.EmptyFromAddressError, fn ->
FooMailer.deliver_now(new_email(from: {"foo", nil}))
end
end
test "deliver_now/1 with empty lists for recipients does not deliver email" do
new_email(to: [], cc: [], bcc: []) |> FooMailer.deliver_now()
refute_received {:deliver, _, _}
new_email(to: [], cc: nil, bcc: nil) |> FooMailer.deliver_now()
refute_received {:deliver, _, _}
new_email(to: nil, cc: [], bcc: nil) |> FooMailer.deliver_now()
refute_received {:deliver, _, _}
new_email(to: nil, cc: nil, bcc: []) |> FooMailer.deliver_now()
refute_received {:deliver, _, _}
end
test "deliver_later/1 with empty lists for recipients does not deliver email" do
new_email(to: [], cc: [], bcc: []) |> FooMailer.deliver_later()
refute_received {:deliver, _, _}
new_email(to: [], cc: nil, bcc: nil) |> FooMailer.deliver_later()
refute_received {:deliver, _, _}
new_email(to: nil, cc: [], bcc: nil) |> FooMailer.deliver_later()
refute_received {:deliver, _, _}
new_email(to: nil, cc: nil, bcc: []) |> FooMailer.deliver_later()
refute_received {:deliver, _, _}
end
test "deliver_later/1 calls deliver on the adapter" do
email = new_email()
FooMailer.deliver_later(email)
assert_receive {:deliver, delivered_email, _config}
assert delivered_email == Bamboo.Mailer.normalize_addresses(email)
end
test "deliver_now/1 wraps the recipients in a list" do
address = {"Someone", "foo@bar.com"}
email = new_email(to: address, cc: address, bcc: address)
FooMailer.deliver_now(email)
assert_received {:deliver, delivered_email, _}
assert delivered_email.to == [address]
assert delivered_email.cc == [address]
assert delivered_email.bcc == [address]
end
test "deliver_now/1 converts binary addresses to %{name: name, email: email}" do
address = "foo@bar.com"
email = new_email(from: address, to: address, cc: address, bcc: address)
FooMailer.deliver_now(email)
converted_address = {nil, address}
assert_received {:deliver, delivered_email, _}
assert delivered_email.from == converted_address
assert delivered_email.to == [converted_address]
assert delivered_email.cc == [converted_address]
assert delivered_email.bcc == [converted_address]
end
test "converts structs with custom protocols" do
user = %Bamboo.Test.User{first_name: "Paul", email: "foo@bar.com"}
email = new_email(from: user, to: user, cc: user, bcc: user)
FooMailer.deliver_now(email)
converted_recipient = {user.first_name, user.email}
assert_received {:deliver, delivered_email, _}
assert delivered_email.from == {"#{user.first_name} (MyApp)", user.email}
assert delivered_email.to == [converted_recipient]
assert delivered_email.cc == [converted_recipient]
assert delivered_email.bcc == [converted_recipient]
end
test "raises an error if an address does not have a protocol implemented" do
email = new_email(from: 1)
assert_raise Protocol.UndefinedError, fn ->
FooMailer.deliver_now(email)
end
end
test "raises if all recipients are nil" do
assert_raise Bamboo.NilRecipientsError, fn ->
new_email(to: nil, cc: nil, bcc: nil) |> FooMailer.deliver_now()
end
assert_raise Bamboo.NilRecipientsError, fn ->
new_email(to: {"foo", nil})
|> FooMailer.deliver_now()
end
assert_raise Bamboo.NilRecipientsError, fn ->
new_email(to: [{"foo", nil}])
|> FooMailer.deliver_now()
end
assert_raise Bamboo.NilRecipientsError, fn ->
new_email(to: [nil])
|> FooMailer.deliver_now()
end
end
test "raises if a map is passed in" do
email = new_email(from: %{foo: :bar})
assert_raise ArgumentError, fn ->
FooMailer.deliver_now(email)
end
end
test "raises an error if deliver_now or deliver_later is called directly" do
email = new_email(from: %{foo: :bar})
assert_raise RuntimeError, ~r/cannot call Bamboo.Mailer/, fn ->
Bamboo.Mailer.deliver_now(email)
end
assert_raise RuntimeError, ~r/cannot call Bamboo.Mailer/, fn ->
Bamboo.Mailer.deliver_later(email)
end
end
defp new_email(attrs \\ []) do
attrs = Keyword.merge([from: "foo@bar.com", to: "foo@bar.com"], attrs)
Email.new_email(attrs)
end
end
| 30.078067 | 96 | 0.70152 |
08be67c6c653816da2ad329744c0bebf69b4815e | 1,377 | ex | Elixir | example-1-wordcount/lib/wordcount.ex | TattdCodeMonkey/ets-workshop | 42e72b8a5a08742e76f3aa08e5e7c014b4cd7ac2 | [
"MIT"
] | null | null | null | example-1-wordcount/lib/wordcount.ex | TattdCodeMonkey/ets-workshop | 42e72b8a5a08742e76f3aa08e5e7c014b4cd7ac2 | [
"MIT"
] | null | null | null | example-1-wordcount/lib/wordcount.ex | TattdCodeMonkey/ets-workshop | 42e72b8a5a08742e76f3aa08e5e7c014b4cd7ac2 | [
"MIT"
] | null | null | null | defmodule WordCount do
@top_n_words 10
@switches [file: :string]
def main(argv) do
{options, _, _} = OptionParser.parse(argv, strict: @switches)
options
|> run
|> to_exit_status
end
def run(options) do
with {:ok, _} <- WordCount.State.init,
{:ok, file_stream} <- get_file(options),
:ok <- do_counting(file_stream),
{:ok, result} <- summarize(),
do: IO.puts(result)
end
def to_exit_status({:error, reason}) do
IO.puts(reason)
1
end
def to_exit_status(_), do: 0
def get_file(options) do
case Keyword.has_key?(options, :file) do
false -> {:error, "Provide file to process with --file"}
true ->
path = options[:file]
case File.exists?(path) do
false -> {:error, "File provided could not be found: #{path}"}
true -> {:ok, File.stream!(path, [], :line)}
end
end
end
def do_counting(stream) do
task = Task.async(fn -> WorkCount.Counter.count(stream) end)
Task.await(task, :infinity)
:ok
end
def summarize do
sorted_words = WordCount.State.sort_desc
|> Enum.take(@top_n_words)
|> Enum.with_index(1)
|> Enum.map(fn {{word, count}, index} ->
"#{index}: #{word} - #{count}"
end)
|> Enum.join("\n")
{:ok, "Count complete, Top #{@top_n_words} words by usage:\n" <> sorted_words}
end
end
| 23.741379 | 82 | 0.591866 |
08be808263a39d424dd53ffe0a2506d6d0c4620b | 181 | exs | Elixir | priv/repo/migrations/20220201223427_create_topics.exs | frunox/discuss | d19367eceb8c68ebef4e565981ceef256b5cb04e | [
"MIT"
] | null | null | null | priv/repo/migrations/20220201223427_create_topics.exs | frunox/discuss | d19367eceb8c68ebef4e565981ceef256b5cb04e | [
"MIT"
] | null | null | null | priv/repo/migrations/20220201223427_create_topics.exs | frunox/discuss | d19367eceb8c68ebef4e565981ceef256b5cb04e | [
"MIT"
] | null | null | null | defmodule Discuss.Repo.Migrations.CreateTopics do
use Ecto.Migration
def change do
create table(:topics) do
add :title, :string
timestamps()
end
end
end
| 15.083333 | 49 | 0.679558 |
08bece39a11c9c26170a2eb4683215fb34c25035 | 2,164 | ex | Elixir | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/store_layout.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/store_layout.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/store_layout.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.AndroidEnterprise.V1.Model.StoreLayout do
@moduledoc """
General setting for the managed Google Play store layout, currently only specifying the page to display the first time the store is opened.
## Attributes
- homepageId (String): The ID of the store page to be used as the homepage. The homepage is the first page shown in the managed Google Play Store. Not specifying a homepage is equivalent to setting the store layout type to \"basic\". Defaults to: `null`.
- kind (String): Identifies what kind of resource this is. Value: the fixed string \"androidenterprise#storeLayout\". Defaults to: `null`.
- storeLayoutType (String): The store layout type. By default, this value is set to \"basic\" if the homepageId field is not set, and to \"custom\" otherwise. If set to \"basic\", the layout will consist of all approved apps that have been whitelisted for the user. Defaults to: `null`.
"""
defstruct [
:"homepageId",
:"kind",
:"storeLayoutType"
]
end
defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.StoreLayout do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.StoreLayout do
def encode(value, options) do
GoogleApi.AndroidEnterprise.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 43.28 | 318 | 0.755083 |
08bef2d30b5b27cf804dfd82b4afa347f239ce7c | 1,307 | exs | Elixir | bench/exmetrics_bench.exs | fourcube/metrics | 0c8cf2ea5b9351d4897b61a619986b738bfc7497 | [
"MIT"
] | null | null | null | bench/exmetrics_bench.exs | fourcube/metrics | 0c8cf2ea5b9351d4897b61a619986b738bfc7497 | [
"MIT"
] | 2 | 2016-02-12T06:48:08.000Z | 2016-02-16T09:59:32.000Z | bench/exmetrics_bench.exs | fourcube/metrics | 0c8cf2ea5b9351d4897b61a619986b738bfc7497 | [
"MIT"
] | null | null | null | defmodule Exmetrics.Bench do
use Benchfella
require Logger
setup_all do
Application.ensure_all_started(:exmetrics)
end
teardown_all _ do
Application.stop(:exmetrics)
end
after_each_bench _ do
Exmetrics.reset
end
bench "Exmetrics.Gauge.set/2" do
Exmetrics.Gauge.set "foo", 1
end
bench "Exmetrics.Gauge.get/1" do
Exmetrics.Gauge.get "foo"
end
bench "Exmetrics.Histogram.new/3" do
Exmetrics.Histogram.new "foo", 1000000, 3
end
bench "Exmetrics.snapshot/0 - 1 histogram", [unused: new_histogram(1)] do
Exmetrics.snapshot
end
bench "Exmetrics.snapshot/0 - 10 histograms", [unused: new_histogram(10)] do
Exmetrics.snapshot
end
bench "Exmetrics.snapshot/0 - 100 histograms", [unused: new_histogram(100)] do
Exmetrics.snapshot
end
bench "Exmetrics.record/2", [unused: new_histogram(0)] do
Exmetrics.Histogram.record "foo0", 10000
end
bench "Exmetrics.Counter.incr/1" do
Exmetrics.Counter.incr "foo"
end
bench "Exmetrics.Counter.add/2" do
Exmetrics.Counter.add "foo", 42
end
bench "Exmetrics.Counter.get/1", [unused: Exmetrics.Counter.incr "foo"] do
Exmetrics.Counter.get "foo"
end
def new_histogram(n) do
Enum.each 0..(n-1), &(Exmetrics.Histogram.new "foo#{&1}", 1000000, 3)
end
end
| 20.746032 | 80 | 0.697781 |
08bf27613d7b44c2724dabf8a7ffdf4481a98bca | 1,174 | exs | Elixir | test/scarecrow/models/timestamps_test.exs | azukiapp/scarecrow | c5d500d36173c74ed8c7e6e4923293de8b39ea9b | [
"Apache-2.0"
] | 1 | 2015-06-13T03:35:02.000Z | 2015-06-13T03:35:02.000Z | test/scarecrow/models/timestamps_test.exs | azukiapp/scarecrow | c5d500d36173c74ed8c7e6e4923293de8b39ea9b | [
"Apache-2.0"
] | null | null | null | test/scarecrow/models/timestamps_test.exs | azukiapp/scarecrow | c5d500d36173c74ed8c7e6e4923293de8b39ea9b | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../test_helper.exs", __DIR__
defmodule ScarecrowModelsTimestampsTest do
use ExUnit.Case
alias Scarecrow.Models
defmodule DocumentTest do
use Models.Document
use Models.Timestamps
end
test "document record have a timestamps fields" do
assert is_record(DocumentTest.new, DocumentTest)
assert ListDict.has_key?(DocumentTest.__record__(:fields), :created_at)
assert ListDict.has_key?(DocumentTest.__record__(:fields), :updated_at)
end
test "set date after new object" do
doc = DocumentTest.new
assert is_record(doc.created_at, Date.Gregorian)
assert is_record(doc.updated_at, Date.Gregorian)
assert doc.created_at == doc.updated_at
end
test "support to force a timestamps values" do
date = Date.shift(Date.now, 1, :days)
doc = DocumentTest.new(created_at: date, updated_at: date)
assert date == doc.created_at
assert date == doc.updated_at
end
test "inject touch method" do
date = Date.shift(Date.now, 1, :sec)
doc = DocumentTest.new(created_at: date, updated_at: date)
doc = doc.touch
assert 1 >= Date.diff(doc.created_at, doc.updated_at, :sec)
end
end
| 29.35 | 75 | 0.723169 |
08bf95bfda9a5c675cda2c9a80e3d4ddd1e1d3ff | 1,897 | ex | Elixir | clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_batch_get_user_links_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_batch_get_user_links_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_batch_get_user_links_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchGetUserLinksResponse do
@moduledoc """
Response message for BatchGetUserLinks RPC.
## Attributes
* `userLinks` (*type:* `list(GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaUserLink.t)`, *default:* `nil`) - The requested user links.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:userLinks =>
list(GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaUserLink.t())
| nil
}
field(:userLinks,
as: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaUserLink,
type: :list
)
end
defimpl Poison.Decoder,
for: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchGetUserLinksResponse do
def decode(value, options) do
GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchGetUserLinksResponse.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchGetUserLinksResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.280702 | 158 | 0.761202 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.