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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03c3eb16f1781b4d5d059d45a388097a4a8a76c5 | 579 | ex | Elixir | backend/lib/functional_vote_web/views/changeset_view.ex | maxrchung/FunctionalVote | 95c54c7614a74718e14c6fe74fd0bd4e84f85444 | [
"MIT"
] | 10 | 2020-03-13T12:56:06.000Z | 2021-06-28T22:13:27.000Z | backend/lib/functional_vote_web/views/changeset_view.ex | maxrchung/FunctionalVote | 95c54c7614a74718e14c6fe74fd0bd4e84f85444 | [
"MIT"
] | 132 | 2020-02-08T02:01:03.000Z | 2022-02-18T20:38:38.000Z | backend/lib/functional_vote_web/views/changeset_view.ex | maxrchung/FunctionalVote | 95c54c7614a74718e14c6fe74fd0bd4e84f85444 | [
"MIT"
] | 1 | 2021-03-17T06:22:55.000Z | 2021-03-17T06:22:55.000Z | defmodule FunctionalVoteWeb.ChangesetView do
use FunctionalVoteWeb, :view
@doc """
Traverses and translates changeset errors.
See `Ecto.Changeset.traverse_errors/2` and
`FunctionalVoteWeb.ErrorHelpers.translate_error/1` for more details.
"""
def translate_errors(changeset) do
Ecto.Changeset.traverse_errors(changeset, &translate_error/1)
end
def render("error.json", %{changeset: changeset}) do
# When encoded, the changeset returns its errors
# as a JSON object. So we just pass it forward.
%{errors: translate_errors(changeset)}
end
end
| 28.95 | 70 | 0.747841 |
03c3fb0b50e12791c74d2cfc3059bdff5badfd64 | 666 | exs | Elixir | config/test.exs | joseluis8906/platform | f1b4c49b5de60dd880f0075ec3020aef03c557af | [
"Apache-2.0"
] | null | null | null | config/test.exs | joseluis8906/platform | f1b4c49b5de60dd880f0075ec3020aef03c557af | [
"Apache-2.0"
] | 1 | 2021-05-11T14:48:01.000Z | 2021-05-11T14:48:01.000Z | config/test.exs | joseluis8906/platform | f1b4c49b5de60dd880f0075ec3020aef03c557af | [
"Apache-2.0"
] | null | null | null | use Mix.Config
# 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 :platform, Platform.Repo,
username: "postgres",
password: "postgres",
database: "platform_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 :platform, PlatformWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 28.956522 | 67 | 0.750751 |
03c405f4efe68374e23d3d591224ae9b68130268 | 285 | exs | Elixir | test/cowsay_test.exs | bbrock25/cowsay | c8f41fef678c09652fa5cadc25ef40f5a5c37c20 | [
"MIT"
] | 5 | 2015-09-19T08:12:26.000Z | 2021-07-18T10:40:03.000Z | test/cowsay_test.exs | bbrock25/cowsay | c8f41fef678c09652fa5cadc25ef40f5a5c37c20 | [
"MIT"
] | null | null | null | test/cowsay_test.exs | bbrock25/cowsay | c8f41fef678c09652fa5cadc25ef40f5a5c37c20 | [
"MIT"
] | null | null | null | defmodule CowsayTest do
use ExUnit.Case
test "Cowsay returns a string containing a thought" do
assert ( Cowsay.say("thought") |> String.contains?("thought"))
end
test "Cowsay print outputs to standard IO" do
assert :ok == Cowsay.print("I'm a tested cow.")
end
end
| 23.75 | 66 | 0.691228 |
03c41af334cd96b37852d34086fd3bde94bbe3ec | 11,206 | ex | Elixir | lib/coherence.ex | thefuture2092/coherence | 377d91ff01622773b5a9ec39fadf1f8c27328879 | [
"MIT"
] | 1,347 | 2016-07-04T23:20:10.000Z | 2022-02-10T20:10:48.000Z | lib/coherence.ex | thefuture2092/coherence | 377d91ff01622773b5a9ec39fadf1f8c27328879 | [
"MIT"
] | 378 | 2016-07-06T16:30:28.000Z | 2021-09-16T13:34:05.000Z | lib/coherence.ex | thefuture2092/coherence | 377d91ff01622773b5a9ec39fadf1f8c27328879 | [
"MIT"
] | 276 | 2016-07-06T20:26:17.000Z | 2021-12-06T19:32:41.000Z | defmodule Coherence do
@moduledoc """
Coherence is a full featured, configurable authentication and user
management system for Phoenix, providing a number of optional features
configured with a installation mix task:
* Database Authenticatable: handles hashing and storing an encrypted password in the database.
* Invitable: sends invites to new users with a sign-up link, allowing the user to create their account with their own password.
* Registerable: allows anonymous users to register a users email address and password.
* Confirmable: new accounts require clicking a link in a confirmation email.
* Recoverable: provides a link to generate a password reset link with token expiry.
* Trackable: saves login statics like login counts, timestamps, and IP address for each user.
* Lockable: locks an account when a specified number of failed sign-in attempts has been exceeded.
* Unlockable With Token: provides a link to send yourself an unlock email.
* Rememberable: provides persistent login with 'Remember me?' check box on login page.
See the [README](readme.html) file for an overview, installation, and
setup instructions.
### Authenticatable
Handles hashing and storing an encrypted password in the database.
Provides `/sessions/new` and `/sessions/delete` routes for logging in and out with
the appropriate templates and view.
The following columns are added the `<timestamp>_add_coherence_to_user.exs` migration:
* :password_hash, :string - the encrypted password
The following options can be customized (default shown):
config :coherence,
password_hash_field: :password_hash # you must recompile Coherence after changing this
### Invitable
Handles sending invites to new users with a sign-up link, allowing the user to create their account with their own password.
Provides `/invitations/new` and `invitations/edit` routes for creating a new invitation and creating a new account from the invite email.
These routes can be configured to require login by using the `coherence_routes :protected` macro in your router.exs file.
Invitation token timeout will be added in the future.
The following table is created by the generated `<timestamp>_create_coherence_invitable.exs` migration:
create table(:invitations) do
add :name, :string
add :email, :string
add :token, :string
end
### Registerable
Allows anonymous users to register a users email address and password.
Provides `/registrations/new` and `/registrations/create` routes for creating a new registration.
Adds a `Register New Account` to the log-in page.
It is recommended that the :confirmable option is used with :registerable to
ensure a valid email address is captured.
### Confirmable
Requires a new account be conformed. During registration, a confirmation token is generated and sent to the registering email. This link must be clicked before the user can sign-in.
Provides `edit` action for the `/confirmations` route.
The following options can be customized (default shown):
config :coherence,
confirmation_token_expire_days: 5,
allow_unconfirmed_access_for: 0 # number of days. 0 to disable
### Recoverable
Allows users to reset their password using an expiring token send by email.
Provides `new`, `create`, `edit`, `update` actions for the `/passwords` route.
Adds a "Forgot your password?" link to the log-in form. When clicked, the user provides their email address and if found, sends a reset password instructions email with a reset link.
The following options can be customized (default shown):
config :coherence,
reset_token_expire_days: 2
### Trackable
Saves login statics like login counts, timestamps, and IP address for each user.
Adds the following database field to your User model with the generated migration:
add :sign_in_count, :integer, default: 0 # how many times the user has logged in
add :current_sign_in_at, :datetime # the current login timestamp
add :last_sign_in_at, :datetime # the timestamp of the previous login
add :current_sign_in_ip, :string # the current login IP adddress
add :last_sign_in_ip, :string # the IP address of the previous login
### Lockable
Locks an account when a specified number of failed sign-in attempts has been exceeded.
The following defaults can be changed with the following config entries:
The following options can be customized (default shown):
config :coherence,
unlock_timeout_minutes: 5,
max_failed_login_attempts: 5
Adds the following database field to your User model with the generated migration:
add :failed_attempts, :integer, default: 0
add :unlock_token, :string
add :locked_at, :datetime
### Unlockable with Token
Provides a link to send yourself an unlock email. When the user clicks the link, the user is presented a form to enter their email address and password. If the token has not expired and the email and password are valid, a unlock email is sent to the user's email address with an expiring token.
The following options can be customized (default shown):
config :coherence,
unlock_token_expire_minutes: 5
### Remember Me
The `rememberable` option provides persistent login when the 'Remember Me?' box is checked during login.
With this feature, you will automatically be logged in from the same browser when your current login session dies using a configurable expiring persistent cookie.
For security, both a token and series number stored in the cookie on initial login. Each new creates a new token, but preserves the series number, providing protection against fraud. As well, both the token and series numbers are hashed before saving them to the database, providing protection if the database is compromised.
The following options can be customized (default shown):
config :coherence,
rememberable_cookie_expire_hours: 2*24,
login_cookie: "coherence_login"
The following table is created by the generated `<timestamp>_create_coherence_rememberable.exs` migration:
create table(:rememberables) do
add :series_hash, :string
add :token_hash, :string
add :token_created_at, :datetime
add :user_id, references(:users, on_delete: :delete_all)
timestamps
end
create index(:rememberables, [:user_id])
create index(:rememberables, [:series_hash])
create index(:rememberables, [:token_hash])
create unique_index(:rememberables, [:user_id, :series_hash, :token_hash])
The `--rememberable` install option is not provided in any of the installer group options. You must provide the `--rememberable` option to install the migration and its support.
## Mix Tasks
Backwords compatibility note: For versions of Phoenix previous to 1.3 use `mix coherence.<command>`. The new `mix coh.<command>` better understands the newer Phoenix patterns.
### Installer
The following examples illustrate various configuration scenarios for the install mix task:
# Install with only the `authenticatable` option
$ mix coh.install
# Install all the options except `confirmable` and `invitable`
$ mix coh.install --full
# Install all the options except `invitable`
$ mix coh.install --full-confirmable
# Install all the options except `confirmable`
$ mix coh.install --full-invitable
# Install the `full` options except `lockable` and `trackable`
$ mix coh.install --full --no-lockable --no-trackable
And some reinstall examples:
# Reinstall with defaults (--silent --no-migrations --no-config --confirm-once)
$ mix coh.install --reinstall
# Confirm to overwrite files, show instructions, and generate migrations
$ mix coh.install --reinstall --no-confirm-once --with-migrations
Run `$ mix help coh.install` for more information.
### Clean
The following examples illustrate how to remove the files created by the installer:
# Clean all the installed files
$ mix coh.clean --all
# Clean only the installed view and template files
$ mix coh.clean --views --templates
# Clean all but the models
$ mix coh.clean --all --no-models
# Prompt once to confirm the removal
$ mix coh.clean --all --confirm-once
After installation, if you later want to remove one more options, here are a couple examples:
# Clean one option
$ mix coh.clean --options=recoverable
# Clean several options without confirmation
$ mix coh.clicked --no-confirm --options="recoverable unlockable-with-token"
# Test the uninstaller without removing files
$ mix coh.clicked --dry-run --options="recoverable unlockable-with-token"
Run `$ mix help coh.install` or `$ mix help coherence.install` for more information.
"""
use Application
alias Coherence.{Config, Messages}
@doc false
def start(_type, _args) do
Coherence.Supervisor.start_link()
end
@doc """
Get the currently logged in user data.
"""
def current_user(conn), do: conn.assigns[Config.assigns_key()]
@doc """
Updates the user login data in the current sessions.
Other sessions belonging to the same user won't be updated.
Requires access to the `conn`, which means it can't be called outside of the context of a conn.
To update all session belonging to the user see `t:update_user_login/1`.
"""
def update_user_login(conn, user) do
apply(
Config.auth_module(),
Config.update_login(),
[conn, user, [id_key: Config.schema_key()]]
)
end
@doc """
Updates the user login data in the all sessions belonging to the user.
All sessions belonging to the same user will be updated.
Doesn't need access to the `conn`, which means it can be called anywhere.
To update only the current session see `t:update_user_login/2`
"""
def update_user_logins(user) do
# Handle a user's DBStore
Coherence.CredentialStore.Server.update_user_logins(user)
end
@doc """
Get the currently logged in user name.
"""
def current_user_name(conn, field \\ :name) do
(current_user(conn) || %{}) |> Map.get(field)
end
@doc """
Get the currently assigned user_token
"""
def user_token(conn), do: conn.assigns[Config.token_assigns_key()]
@doc """
Verify a user token for channel authentication.
"""
def verify_user_token(socket, token, assign_fun) do
result =
case Config.verify_user_token() do
fun when is_function(fun) ->
fun.(socket, token)
{mod, fun, args} ->
apply(mod, fun, args)
error ->
{:error,
Messages.backend().verify_user_token(
user_token: Config.verify_user_token(),
error: error
)}
end
case result do
{:ok, user_id} -> {:ok, assign_fun.(socket, :user_id, user_id)}
error -> error
end
end
@doc """
Check if user is logged in.
"""
def logged_in?(conn), do: !!current_user(conn)
end
| 36.501629 | 327 | 0.715331 |
03c42d31339c734c157e8a9e9f90c4115adafc18 | 1,079 | ex | Elixir | lib/square_up/resources/v2/break_types.ex | beaver21/SquareUp | c9791d96ed9335926933403a966eba5076fbc15b | [
"MIT"
] | 4 | 2020-10-21T18:34:50.000Z | 2022-03-16T06:25:44.000Z | lib/square_up/resources/v2/break_types.ex | beaver21/SquareUp | c9791d96ed9335926933403a966eba5076fbc15b | [
"MIT"
] | 5 | 2020-10-21T23:16:32.000Z | 2021-05-13T13:42:44.000Z | lib/square_up/resources/v2/break_types.ex | beaver21/SquareUp | c9791d96ed9335926933403a966eba5076fbc15b | [
"MIT"
] | 3 | 2020-10-21T21:20:36.000Z | 2021-03-15T18:00:30.000Z | defmodule SquareUp.V2.BreakTypes do
import Norm
import SquareUp.Client, only: [call: 2]
@spec list(SquareUp.Client.t(), %{}, %{}, %{
optional(:location_id) => binary(),
optional(:limit) => integer(),
optional(:cursor) => binary()
}) :: SquareUp.Client.response(SquareUp.TypeSpecs.list_break_types_response())
def list(client, path_params \\ %{}, params \\ %{}, query_params \\ %{}) do
path_params_spec = schema(%{})
params_spec = schema(%{})
query_params_spec =
schema(%{
location_id: spec(is_binary()),
limit: spec(is_integer()),
cursor: spec(is_binary())
})
response_spec = {:delegate, &SquareUp.ResponseSchema.list_break_types_response/0}
call(client, %{
method: :get,
path_params: path_params,
params: params,
query_params: query_params,
path_params_spec: path_params_spec,
params_spec: params_spec,
query_params_spec: query_params_spec,
response_spec: response_spec,
path: "/v2/labor/break-types"
})
end
end
| 29.972222 | 86 | 0.627433 |
03c4456e506d2afd4be09b51dd0254db1a1beb84 | 3,750 | exs | Elixir | test/asls/runtime_test.exs | Shopify/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 23 | 2021-02-05T01:50:07.000Z | 2021-12-10T13:24:41.000Z | test/asls/runtime_test.exs | saulecabrera/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 5 | 2020-07-20T00:33:07.000Z | 2020-09-30T16:09:47.000Z | test/asls/runtime_test.exs | saulecabrera/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 1 | 2020-10-24T09:02:22.000Z | 2020-10-24T09:02:22.000Z | defmodule AssemblyScriptLS.RuntimeTest do
alias AssemblyScriptLS.Runtime
use ExUnit.Case, async: false
import Mock
@valid_config_file %{
targets: %{
debug: %{}
}
}
describe "ensure/1" do
test "returns an error message when the root directory doesn't exist" do
{:error, msg} = Runtime.ensure "non-existent"
assert msg == "The project root is invalid or doesn't exist."
end
test "default asconfig? false and release target when the configuration file is not found" do
exists = fn
"./node_modules/.bin/asc" -> true
_ -> false
end
with_mock File, [:passthrough], [cd: fn _ -> :ok end, exists?: exists] do
{:ok, rt} = Runtime.ensure "root"
refute rt.asconfig?
assert rt.target == "release"
end
end
test "returns an error message when the configuration file is invalid" do
with_mock File, [cd: fn _ -> :ok end, exists?: fn _ -> true end, read!: fn _ -> "" end] do
{:error, reason} = Runtime.ensure "root"
assert reason == "Invalid asconfig.json file."
end
end
test "returns an error message when the configuration file doesn't contain a target" do
with_mock File, [cd: fn _ -> :ok end, exists?: fn _ -> true end, read!: fn _ -> "{}" end] do
{:error, reason} = Runtime.ensure "root"
assert String.trim(reason) == String.trim(~s(
Your asconfig.json file should include at least one target definition.
))
end
end
test "returns an error message when no assemblyscript executable is found" do
exists = fn
"./node_modules/.bin/asc" -> false
_ -> true
end
file = {File, [:passthrough], [cd: fn _ -> :ok end, exists?: exists, read!: fn _ -> Jason.encode!(@valid_config_file) end]}
system = {System, [], [cmd: fn _, _ -> {0, 1} end]}
with_mocks([file, system]) do
{:error, reason} = Runtime.ensure "root"
assert String.trim(reason) == String.trim(~s(
No executable for AssemblyScript found.
))
end
end
test "returns an env with the global assemblyscript installation when no local one is found" do
exists = fn
"./node_modules/.bin/asc" -> false
_ -> true
end
file = {File, [:passthrough], [cd: fn _ -> :ok end, exists?: exists, read!: fn _ -> Jason.encode!(@valid_config_file) end]}
system = {System, [], [cmd: fn _, _ -> {0, 0} end]}
with_mocks([file, system]) do
{:ok, env} = Runtime.ensure "root"
assert env.executable == "asc"
assert env.target == "debug"
assert env.root_uri == "root"
end
end
test "returns an env with the local assemblyscript installation" do
exists = fn _-> true end
file = {File, [:passthrough], [cd: fn _ -> :ok end, exists?: exists, read!: fn _ -> Jason.encode!(@valid_config_file) end]}
with_mocks([file]) do
{:ok, env} = Runtime.ensure "root"
assert String.contains?(env.executable, "/node_modules/.bin/asc")
assert env.target == "debug"
assert env.root_uri == "root"
end
end
end
describe "to_string/1" do
test "returns a string representation of the given runtime struct" do
exists = fn _-> true end
file = {File, [:passthrough], [cd: fn _ -> :ok end, exists?: exists, read!: fn _ -> Jason.encode!(@valid_config_file) end]}
with_mocks([file]) do
{:ok, env} = Runtime.ensure "root"
expected = """
Project root: root;
AssemblyScript compiler: #{env.executable};
Compilation target: #{env.target};
"""
assert expected == Runtime.to_string(env)
end
end
end
end
| 33.783784 | 129 | 0.5944 |
03c451b6481fcbc27c913c793e1a70a5a623a44b | 65 | ex | Elixir | web/views/layout_view.ex | kagemiku/ciphoenix | 1d75529d5f92d4605bdc650e330414c9cda0c128 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | kagemiku/ciphoenix | 1d75529d5f92d4605bdc650e330414c9cda0c128 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | kagemiku/ciphoenix | 1d75529d5f92d4605bdc650e330414c9cda0c128 | [
"MIT"
] | null | null | null | defmodule Ciphoenix.LayoutView do
use Ciphoenix.Web, :view
end
| 16.25 | 33 | 0.8 |
03c45c311a82c51866255ff11c82b7159668f470 | 434 | ex | Elixir | lib/stripe_post/application.ex | aforward/stripe-post | 2aa29bab7c69495bd43d53202589b7af48c9fa8c | [
"MIT"
] | null | null | null | lib/stripe_post/application.ex | aforward/stripe-post | 2aa29bab7c69495bd43d53202589b7af48c9fa8c | [
"MIT"
] | 1 | 2021-07-22T19:32:28.000Z | 2021-07-22T20:04:03.000Z | lib/stripe_post/application.ex | aforward/stripe-post | 2aa29bab7c69495bd43d53202589b7af48c9fa8c | [
"MIT"
] | null | null | null | defmodule StripePost.Application do
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
worker(StripePost.Worker, [])
]
opts = [strategy: :one_for_one, name: StripePost.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 22.842105 | 66 | 0.714286 |
03c4854f6fdab9f94d7883174d1d15859f759272 | 1,940 | ex | Elixir | lib/authable/authentications/bearer.ex | liberumed/authable | 6db9951aa07000b358f16ffe413a13aa9aa89192 | [
"Unlicense"
] | null | null | null | lib/authable/authentications/bearer.ex | liberumed/authable | 6db9951aa07000b358f16ffe413a13aa9aa89192 | [
"Unlicense"
] | null | null | null | lib/authable/authentications/bearer.ex | liberumed/authable | 6db9951aa07000b358f16ffe413a13aa9aa89192 | [
"Unlicense"
] | 1 | 2021-01-12T00:55:56.000Z | 2021-01-12T00:55:56.000Z | defmodule Authable.Authentication.Bearer do
@moduledoc """
Bearer authentication helper module, implements Authable.Authentication
behaviour.
"""
alias Authable.Authentication.Token, as: TokenAuthentication
@behaviour Authable.Authentication
@doc """
Authenticates resource-owner using access_token map.
It reads access_token value from given input and delegates value to
Authable.Authentication.Bearer.authenticate/1 function.
## Examples
# Suppose we have a access_token at 'token store(Authable.Token)'
# with token value "at123456789"
# If we pass the token value to the function,
# it will return resource-owner.
Authable.Authentication.Bearer.authenticate(
%{"access_token" => "at123456789"}, ["read"])
# or
Authable.Authentication.Bearer.authenticate("at123456789", ["read"])
# or
Authable.Authentication.Bearer.authenticate("Bearer at123456789",
["read"])
"""
def authenticate(%{"access_token" => access_token}, required_scopes),
do: authenticate(access_token, required_scopes)
def authenticate("Bearer " <> access_token, required_scopes),
do: authenticate(access_token, required_scopes)
def authenticate(access_token, required_scopes) do
case TokenAuthentication.authenticate(
{"access_token", access_token},
required_scopes
) do
{:ok, user} ->
{:ok, user}
{:error, errors, status} ->
{:error, Map.put(errors, :headers, error_headers(errors)), status}
end
end
defp error_headers(errors) do
error_message = generate_error_header_message(errors)
[%{"www-authenticate" => "Bearer realm=\"authable\", #{error_message}"}]
end
defp generate_error_header_message(errors) do
{error, error_message} =
errors
|> Map.to_list()
|> List.first()
"error=\"#{error}\", error_description=\"#{error_message}\""
end
end
| 30.3125 | 76 | 0.686082 |
03c4928366fb4138cdaa89832ca383d0a544aad9 | 2,949 | ex | Elixir | lib/holidays/define.ex | CoderDennis/holidays | 939f4f6a88540eddc4edbb51c1a0b0515a4eea11 | [
"MIT"
] | 16 | 2016-01-11T16:18:38.000Z | 2022-02-24T09:41:05.000Z | lib/holidays/define.ex | CoderDennis/holidays_ex | 939f4f6a88540eddc4edbb51c1a0b0515a4eea11 | [
"MIT"
] | 9 | 2016-08-14T01:26:16.000Z | 2021-02-08T01:00:35.000Z | lib/holidays/define.ex | CoderDennis/holidays_ex | 939f4f6a88540eddc4edbb51c1a0b0515a4eea11 | [
"MIT"
] | 8 | 2017-06-08T09:23:46.000Z | 2021-08-17T19:03:05.000Z | defmodule Holidays.Define do
use GenServer
alias Holidays.DateCalculator.DateMath
def start_link() do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
def holiday(name, %{month: month, day: day, regions: regions}) do
GenServer.cast(__MODULE__, {:add_entry, :static, {name, month, day, regions}})
end
def holiday(name, %{month: month, week: week, weekday: weekday, regions: regions}) do
GenServer.cast(__MODULE__, {:add_entry, :nth, {name, month, week, weekday, regions}})
end
def holiday(name, %{function: function, regions: regions}) do
GenServer.cast(__MODULE__, {:add_entry, :fun, {name, function, regions}})
end
@spec on(:calendar.date, [Holidays.region]) :: list
def on(date, regions) do
GenServer.call(__MODULE__, {:on, date, regions})
end
defp on_all(%{static: statics, nth: nths, fun: funs}, date) do
on_static(statics, date) ++
on_nth(nths, date) ++
on_fun(funs, date)
end
defp on_static(holidays, {_, month, day}) do
holidays
|> Enum.filter(fn
{_, ^month, ^day, _} -> true
_ -> false
end)
|> Enum.map(fn {name, _, _, regions} -> %{name: name, regions: regions} end)
end
defp on_nth(holidays, date) do
DateMath.get_week_and_weekday(date)
|> Enum.flat_map(&on_nth(&1, holidays, date))
end
defp on_nth({week, weekday}, holidays, {_, month, _}) do
holidays
|> Enum.filter(&match?({_, ^month, ^week, ^weekday, _}, &1))
|> Enum.map(fn {name, _, _, _, regions} -> %{name: name, regions: regions} end)
end
defp on_fun(holidays, date) do
holidays
|> Enum.filter(fn {_, fun, _} -> apply_fun(fun, date) == date end)
|> Enum.map(fn {name, _, regions} -> %{name: name, regions: regions} end)
end
defp apply_fun({mod, fun, args, days}, date) do
apply_fun({mod, fun, args}, date)
|> DateMath.add_days(days)
end
defp apply_fun({mod, fun, [:year]}, {year, _, _}) do
apply(mod, fun, [year])
end
defp region_match?(%{regions: holiday_regions}, regions_set) do
!(MapSet.new(holiday_regions)
|> MapSet.disjoint?(regions_set))
end
defp split_region(region) do
chunks = region |> Atom.to_string() |> String.downcase() |> String.split("_")
Enum.map(Enum.count(chunks)..1, &join_chunks(chunks, &1))
end
defp join_chunks(chunks, length) do
Enum.take(chunks, length)
|> Enum.join("_")
|> String.to_atom()
end
def init([]) do
{:ok, %{static: [], nth: [], fun: []}}
end
def handle_cast({:add_entry, type, definition}, state) do
{:noreply, Map.update!(state, type, &([definition | &1]))}
end
def handle_call({:on, date, regions}, _valuefrom, state) do
regions_set = regions
|> Enum.flat_map(&split_region/1)
|> MapSet.new()
result = state
|> on_all(date)
|> Enum.filter(®ion_match?(&1, regions_set))
|> Enum.map(fn %{name: name} -> %{name: name} end)
{:reply, result, state}
end
end
| 29.19802 | 89 | 0.629705 |
03c4b6fd1c94d7781e281330b4c21af5621d9580 | 576 | ex | Elixir | priv/templates/phx.gen.embedded/embedded_schema.ex | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 18,092 | 2015-01-01T01:51:04.000Z | 2022-03-31T19:37:14.000Z | priv/templates/phx.gen.embedded/embedded_schema.ex | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 3,905 | 2015-01-01T00:22:47.000Z | 2022-03-31T17:06:21.000Z | priv/templates/phx.gen.embedded/embedded_schema.ex | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 3,205 | 2015-01-03T10:58:22.000Z | 2022-03-30T14:55:57.000Z | defmodule <%= inspect schema.module %> do
use Ecto.Schema
import Ecto.Changeset
alias <%= inspect schema.module %>
embedded_schema do
<%= for {k, v} <- schema.types do %> field <%= inspect k %>, <%= inspect v %><%= schema.defaults[k] %>
<% end %> end
@doc false
def changeset(%<%= inspect schema.alias %>{} = <%= schema.singular %>, attrs) do
<%= schema.singular %>
|> cast(attrs, [<%= Enum.map_join(schema.attrs, ", ", &inspect(elem(&1, 0))) %>])
|> validate_required([<%= Enum.map_join(schema.attrs, ", ", &inspect(elem(&1, 0))) %>])
end
end
| 33.882353 | 105 | 0.590278 |
03c4d04e7b74c0f54dae6881e6f9831731461276 | 3,495 | ex | Elixir | lib/plaid/client.ex | ktayah/elixir-plaid | 2e537d4b79f36b5a31df8b27de079e2cc1dedfda | [
"MIT"
] | 16 | 2021-03-09T02:29:32.000Z | 2022-03-13T07:18:03.000Z | lib/plaid/client.ex | ktayah/elixir-plaid | 2e537d4b79f36b5a31df8b27de079e2cc1dedfda | [
"MIT"
] | 5 | 2021-04-24T20:38:14.000Z | 2022-03-19T22:03:09.000Z | lib/plaid/client.ex | ktayah/elixir-plaid | 2e537d4b79f36b5a31df8b27de079e2cc1dedfda | [
"MIT"
] | 2 | 2021-06-11T02:15:01.000Z | 2022-03-15T18:39:59.000Z | defmodule Plaid.Client do
@moduledoc """
Make API calls to plaid and convert the responses from JSON -> well typed elixir structs.
To use a different HTTP client, create a new module like `MyApp.PlaidClient` which implements
`post/3` and implements the `@behaviour Plaid.Client` behaviour. The success response of those functions must return a `:body` key with a JSON string value
and a `:status_code` key with an integer HTTP status. For an example, see the `Plaid.Client.HTTPoison` module.
> For network errors where you don't get a body or status code, you may return an error tuple
> with any error value, but the error value is not currently utilized.
"""
require Logger
alias Plaid.Castable
@doc """
Callback to POST the data to the Plaid API.
Will be called with the full URL, payload, and headers. Simply take these values
execute the HTTP request.
> `headers` passed in will be a list of two item tuples where the first item is the header key
> and the second is the value. e.g. `[{"content-type", "application/json"}]`
## Examples
iex> post("https://production.plaid.com/categories/get", ~s<{"thing": "stuff"}>, [{"content-type", "application/json"}])
{:ok, %{body: ~s<{"foo": "bar"}>, status_code: 200}}
"""
@callback post(url :: String.t(), payload :: String.t(), headers :: [{String.t(), String.t()}]) ::
{:ok, %{body: String.t(), status_code: integer()}} | {:error, any()}
@doc """
Make a Plaid API call.
Takes in everything needed to complete the request and
return a well formed struct of the response.
## Examples
call(
"/categories/get",
%{},
Plaid.Categories.GetResponse,
client_id: "123",
secret: "abc"
)
{:ok, %Plaid.Categories.GetResponse{}}
"""
@spec call(String.t(), map(), module(), Plaid.config()) ::
{:ok, any()} | {:error, Plaid.Error.t()}
def call(endpoint, payload \\ %{}, castable_module, config) do
url = build_url(config, endpoint)
payload =
payload
|> add_auth(config)
|> Jason.encode!()
headers = [{"content-type", "application/json"}]
http_client = Keyword.get(config, :http_client, Plaid.Client.HTTPoison)
case http_client.post(url, payload, headers) do
{:ok, %{body: body, status_code: status_code}} when status_code in 200..299 ->
{:ok, cast_body(body, castable_module)}
{:ok, %{body: body}} ->
{:error, cast_body(body, Plaid.Error)}
{:error, _error} ->
{:error, Castable.cast(Plaid.Error, %{})}
end
end
@spec build_url(Plaid.config(), String.t()) :: String.t()
defp build_url(config, endpoint) do
test_api_host = Keyword.get(config, :test_api_host)
if is_binary(test_api_host) do
test_api_host <> endpoint
else
env = Keyword.get(config, :env, :sandbox)
"https://#{env}.plaid.com#{endpoint}"
end
end
@spec add_auth(map(), Plaid.config()) :: map()
defp add_auth(payload, config) do
auth =
config
|> Map.new()
|> Map.take([:client_id, :secret])
Map.merge(payload, auth)
end
@spec cast_body(String.t(), module() | :raw) :: String.t() | %{optional(any) => any}
defp cast_body(body, :raw) do
body
end
defp cast_body(json_body, castable_module) do
case Jason.decode(json_body) do
{:ok, generic_map} -> Castable.cast(castable_module, generic_map)
_ -> Castable.cast(Plaid.Error, %{})
end
end
end
| 30.929204 | 157 | 0.636338 |
03c4f235ee2dfb492c1e28a9ed0d9f263eca4c15 | 3,662 | exs | Elixir | 13-phoenix/chirp/test/chirp_web/live/post_live_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | null | null | null | 13-phoenix/chirp/test/chirp_web/live/post_live_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | null | null | null | 13-phoenix/chirp/test/chirp_web/live/post_live_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | 1 | 2020-11-17T07:06:17.000Z | 2020-11-17T07:06:17.000Z | defmodule ChirpWeb.PostLiveTest do
use ChirpWeb.ConnCase
import Phoenix.LiveViewTest
alias Chirp.Timeline
@create_attrs %{body: "some body", like_count: 42, reports_count: 42, username: "some username"}
@update_attrs %{body: "some updated body", like_count: 43, reports_count: 43, username: "some updated username"}
@invalid_attrs %{body: nil, like_count: nil, reports_count: nil, username: nil}
defp fixture(:post) do
{:ok, post} = Timeline.create_post(@create_attrs)
post
end
defp create_post(_) do
post = fixture(:post)
%{post: post}
end
describe "Index" do
setup [:create_post]
test "lists all posts", %{conn: conn, post: post} do
{:ok, _index_live, html} = live(conn, Routes.post_index_path(conn, :index))
assert html =~ "Listing Posts"
assert html =~ post.body
end
test "saves new post", %{conn: conn} do
{:ok, index_live, _html} = live(conn, Routes.post_index_path(conn, :index))
assert index_live |> element("a", "New Post") |> render_click() =~
"New Post"
assert_patch(index_live, Routes.post_index_path(conn, :new))
assert index_live
|> form("#post-form", post: @invalid_attrs)
|> render_change() =~ "can't be blank"
{:ok, _, html} =
index_live
|> form("#post-form", post: @create_attrs)
|> render_submit()
|> follow_redirect(conn, Routes.post_index_path(conn, :index))
assert html =~ "Post created successfully"
assert html =~ "some body"
end
test "updates post in listing", %{conn: conn, post: post} do
{:ok, index_live, _html} = live(conn, Routes.post_index_path(conn, :index))
assert index_live |> element("#post-#{post.id} a", "Edit") |> render_click() =~
"Edit Post"
assert_patch(index_live, Routes.post_index_path(conn, :edit, post))
assert index_live
|> form("#post-form", post: @invalid_attrs)
|> render_change() =~ "can't be blank"
{:ok, _, html} =
index_live
|> form("#post-form", post: @update_attrs)
|> render_submit()
|> follow_redirect(conn, Routes.post_index_path(conn, :index))
assert html =~ "Post updated successfully"
assert html =~ "some updated body"
end
test "deletes post in listing", %{conn: conn, post: post} do
{:ok, index_live, _html} = live(conn, Routes.post_index_path(conn, :index))
assert index_live |> element("#post-#{post.id} a", "Delete") |> render_click()
refute has_element?(index_live, "#post-#{post.id}")
end
end
describe "Show" do
setup [:create_post]
test "displays post", %{conn: conn, post: post} do
{:ok, _show_live, html} = live(conn, Routes.post_show_path(conn, :show, post))
assert html =~ "Show Post"
assert html =~ post.body
end
test "updates post within modal", %{conn: conn, post: post} do
{:ok, show_live, _html} = live(conn, Routes.post_show_path(conn, :show, post))
assert show_live |> element("a", "Edit") |> render_click() =~
"Edit Post"
assert_patch(show_live, Routes.post_show_path(conn, :edit, post))
assert show_live
|> form("#post-form", post: @invalid_attrs)
|> render_change() =~ "can't be blank"
{:ok, _, html} =
show_live
|> form("#post-form", post: @update_attrs)
|> render_submit()
|> follow_redirect(conn, Routes.post_show_path(conn, :show, post))
assert html =~ "Post updated successfully"
assert html =~ "some updated body"
end
end
end
| 31.299145 | 114 | 0.612234 |
03c52015fd236d2d55dcbf811bae9bcb0ddb3fd6 | 355 | exs | Elixir | plugins/ucc_webrtc/priv/repo/seeds.exs | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | plugins/ucc_webrtc/priv/repo/seeds.exs | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | plugins/ucc_webrtc/priv/repo/seeds.exs | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# UccWebrtc.Repo.insert!(%UccWebrtc.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 29.583333 | 61 | 0.709859 |
03c5390d43776f9d91775e9d82352d28b0fb84a9 | 962 | exs | Elixir | mix.exs | neocortexlab/myelin | 0f352c90b41de61133402fe32474a880b544d199 | [
"Apache-2.0"
] | null | null | null | mix.exs | neocortexlab/myelin | 0f352c90b41de61133402fe32474a880b544d199 | [
"Apache-2.0"
] | null | null | null | mix.exs | neocortexlab/myelin | 0f352c90b41de61133402fe32474a880b544d199 | [
"Apache-2.0"
] | null | null | null | defmodule Myelin.MixProject do
use Mix.Project
def project do
[
app: :myelin,
version: "0.1.1",
elixir: "~> 1.7",
description: "The Pallium Network development framework",
start_permanent: Mix.env() == :prod,
deps: deps(),
package: [
maintainers: [
"Anton Zhuravlev <anton@pallium.network>",
"Dmitry Zhelnin <dmitry.zhelnin@gmail.com>",
],
links: %{"GitHub" => "https://github.com/neocortexlab/myelin"}
],
escript: [main_module: Myelin.CmdSpec]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:neuron, "~> 0.7.0"},
{:optimus, "~> 0.1.8"},
{:pallium_core, github: "neocortexlab/pallium-core"},
{:thrift, github: "pinterest/elixir-thrift"},
]
end
end
| 24.05 | 70 | 0.577963 |
03c540211a0635e935217e759a7fba9bafecec35 | 394 | ex | Elixir | lib/genstage_importer_web/views/error_view.ex | altmer/genstage_importer | a8d8242fa0bc79d83d05212dea667c93990685c7 | [
"MIT"
] | 4 | 2019-10-08T19:43:09.000Z | 2021-11-07T07:06:58.000Z | lib/genstage_importer_web/views/error_view.ex | altmer/genstage_importer | a8d8242fa0bc79d83d05212dea667c93990685c7 | [
"MIT"
] | null | null | null | lib/genstage_importer_web/views/error_view.ex | altmer/genstage_importer | a8d8242fa0bc79d83d05212dea667c93990685c7 | [
"MIT"
] | 2 | 2018-08-02T11:01:15.000Z | 2019-11-15T12:35:40.000Z | defmodule GenstageImporterWeb.ErrorView do
use GenstageImporterWeb, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 21.888889 | 47 | 0.715736 |
03c540bf916d1eaa805aed1e1dd5357b1d6d6b62 | 568 | exs | Elixir | backend/test/views/error_view_test.exs | jchamet/PEEP-clean | a87245a77776e2b03b6893539ed2431f95426ab0 | [
"MIT"
] | null | null | null | backend/test/views/error_view_test.exs | jchamet/PEEP-clean | a87245a77776e2b03b6893539ed2431f95426ab0 | [
"MIT"
] | null | null | null | backend/test/views/error_view_test.exs | jchamet/PEEP-clean | a87245a77776e2b03b6893539ed2431f95426ab0 | [
"MIT"
] | null | null | null | defmodule Backend.ErrorViewTest do
use Backend.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(Backend.ErrorView, "404.html", []) ==
"Page not found"
end
test "render 500.html" do
assert render_to_string(Backend.ErrorView, "500.html", []) ==
"Server internal error"
end
test "render any other" do
assert render_to_string(Backend.ErrorView, "505.html", []) ==
"Server internal error"
end
end
| 25.818182 | 66 | 0.676056 |
03c581b6dc150910a3bd1f0e47e4efdefd23e351 | 12,671 | ex | Elixir | lib/mapper/cp850.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | null | null | null | lib/mapper/cp850.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | 1 | 2020-07-16T09:38:33.000Z | 2020-07-16T09:38:33.000Z | lib/mapper/cp850.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | null | null | null | defmodule Exconv.Mapper.Cp850 do
def to_unicode(255), do: 160 # <<194, 160>> | " "
def to_unicode(254), do: 9632 # <<226, 150, 160>> | "■"
def to_unicode(253), do: 178 # <<194, 178>> | "²"
def to_unicode(252), do: 179 # <<194, 179>> | "³"
def to_unicode(251), do: 185 # <<194, 185>> | "¹"
def to_unicode(250), do: 183 # <<194, 183>> | "·"
def to_unicode(249), do: 168 # <<194, 168>> | "¨"
def to_unicode(248), do: 176 # <<194, 176>> | "°"
def to_unicode(247), do: 184 # <<194, 184>> | "¸"
def to_unicode(246), do: 247 # <<195, 183>> | "÷"
def to_unicode(245), do: 167 # <<194, 167>> | "§"
def to_unicode(244), do: 182 # <<194, 182>> | "¶"
def to_unicode(243), do: 190 # <<194, 190>> | "¾"
def to_unicode(242), do: 8215 # <<226, 128, 151>> | "‗"
def to_unicode(241), do: 177 # <<194, 177>> | "±"
def to_unicode(240), do: 173 # <<194, 173>> | ""
def to_unicode(239), do: 180 # <<194, 180>> | "´"
def to_unicode(238), do: 175 # <<194, 175>> | "¯"
def to_unicode(237), do: 221 # <<195, 157>> | "Ý"
def to_unicode(236), do: 253 # <<195, 189>> | "ý"
def to_unicode(235), do: 217 # <<195, 153>> | "Ù"
def to_unicode(234), do: 219 # <<195, 155>> | "Û"
def to_unicode(233), do: 218 # <<195, 154>> | "Ú"
def to_unicode(232), do: 222 # <<195, 158>> | "Þ"
def to_unicode(231), do: 254 # <<195, 190>> | "þ"
def to_unicode(230), do: 181 # <<194, 181>> | "µ"
def to_unicode(229), do: 213 # <<195, 149>> | "Õ"
def to_unicode(228), do: 245 # <<195, 181>> | "õ"
def to_unicode(227), do: 210 # <<195, 146>> | "Ò"
def to_unicode(226), do: 212 # <<195, 148>> | "Ô"
def to_unicode(225), do: 223 # <<195, 159>> | "ß"
def to_unicode(224), do: 211 # <<195, 147>> | "Ó"
def to_unicode(223), do: 9600 # <<226, 150, 128>> | "▀"
def to_unicode(222), do: 204 # <<195, 140>> | "Ì"
def to_unicode(221), do: 166 # <<194, 166>> | "¦"
def to_unicode(220), do: 9604 # <<226, 150, 132>> | "▄"
def to_unicode(219), do: 9608 # <<226, 150, 136>> | "█"
def to_unicode(218), do: 9484 # <<226, 148, 140>> | "┌"
def to_unicode(217), do: 9496 # <<226, 148, 152>> | "┘"
def to_unicode(216), do: 207 # <<195, 143>> | "Ï"
def to_unicode(215), do: 206 # <<195, 142>> | "Î"
def to_unicode(214), do: 205 # <<195, 141>> | "Í"
def to_unicode(213), do: 305 # <<196, 177>> | "ı"
def to_unicode(212), do: 200 # <<195, 136>> | "È"
def to_unicode(211), do: 203 # <<195, 139>> | "Ë"
def to_unicode(210), do: 202 # <<195, 138>> | "Ê"
def to_unicode(209), do: 208 # <<195, 144>> | "Ð"
def to_unicode(208), do: 240 # <<195, 176>> | "ð"
def to_unicode(207), do: 164 # <<194, 164>> | "¤"
def to_unicode(206), do: 9580 # <<226, 149, 172>> | "╬"
def to_unicode(205), do: 9552 # <<226, 149, 144>> | "═"
def to_unicode(204), do: 9568 # <<226, 149, 160>> | "╠"
def to_unicode(203), do: 9574 # <<226, 149, 166>> | "╦"
def to_unicode(202), do: 9577 # <<226, 149, 169>> | "╩"
def to_unicode(201), do: 9556 # <<226, 149, 148>> | "╔"
def to_unicode(200), do: 9562 # <<226, 149, 154>> | "╚"
def to_unicode(199), do: 195 # <<195, 131>> | "Ã"
def to_unicode(198), do: 227 # <<195, 163>> | "ã"
def to_unicode(197), do: 9532 # <<226, 148, 188>> | "┼"
def to_unicode(196), do: 9472 # <<226, 148, 128>> | "─"
def to_unicode(195), do: 9500 # <<226, 148, 156>> | "├"
def to_unicode(194), do: 9516 # <<226, 148, 172>> | "┬"
def to_unicode(193), do: 9524 # <<226, 148, 180>> | "┴"
def to_unicode(192), do: 9492 # <<226, 148, 148>> | "└"
def to_unicode(191), do: 9488 # <<226, 148, 144>> | "┐"
def to_unicode(190), do: 165 # <<194, 165>> | "¥"
def to_unicode(189), do: 162 # <<194, 162>> | "¢"
def to_unicode(188), do: 9565 # <<226, 149, 157>> | "╝"
def to_unicode(187), do: 9559 # <<226, 149, 151>> | "╗"
def to_unicode(186), do: 9553 # <<226, 149, 145>> | "║"
def to_unicode(185), do: 9571 # <<226, 149, 163>> | "╣"
def to_unicode(184), do: 169 # <<194, 169>> | "©"
def to_unicode(183), do: 192 # <<195, 128>> | "À"
def to_unicode(182), do: 194 # <<195, 130>> | "Â"
def to_unicode(181), do: 193 # <<195, 129>> | "Á"
def to_unicode(180), do: 9508 # <<226, 148, 164>> | "┤"
def to_unicode(179), do: 9474 # <<226, 148, 130>> | "│"
def to_unicode(178), do: 9619 # <<226, 150, 147>> | "▓"
def to_unicode(177), do: 9618 # <<226, 150, 146>> | "▒"
def to_unicode(176), do: 9617 # <<226, 150, 145>> | "░"
def to_unicode(175), do: 187 # <<194, 187>> | "»"
def to_unicode(174), do: 171 # <<194, 171>> | "«"
def to_unicode(173), do: 161 # <<194, 161>> | "¡"
def to_unicode(172), do: 188 # <<194, 188>> | "¼"
def to_unicode(171), do: 189 # <<194, 189>> | "½"
def to_unicode(170), do: 172 # <<194, 172>> | "¬"
def to_unicode(169), do: 174 # <<194, 174>> | "®"
def to_unicode(168), do: 191 # <<194, 191>> | "¿"
def to_unicode(167), do: 186 # <<194, 186>> | "º"
def to_unicode(166), do: 170 # <<194, 170>> | "ª"
def to_unicode(165), do: 209 # <<195, 145>> | "Ñ"
def to_unicode(164), do: 241 # <<195, 177>> | "ñ"
def to_unicode(163), do: 250 # <<195, 186>> | "ú"
def to_unicode(162), do: 243 # <<195, 179>> | "ó"
def to_unicode(161), do: 237 # <<195, 173>> | "í"
def to_unicode(160), do: 225 # <<195, 161>> | "á"
def to_unicode(159), do: 402 # <<198, 146>> | "ƒ"
def to_unicode(158), do: 215 # <<195, 151>> | "×"
def to_unicode(157), do: 216 # <<195, 152>> | "Ø"
def to_unicode(156), do: 163 # <<194, 163>> | "£"
def to_unicode(155), do: 248 # <<195, 184>> | "ø"
def to_unicode(154), do: 220 # <<195, 156>> | "Ü"
def to_unicode(153), do: 214 # <<195, 150>> | "Ö"
def to_unicode(152), do: 255 # <<195, 191>> | "ÿ"
def to_unicode(151), do: 249 # <<195, 185>> | "ù"
def to_unicode(150), do: 251 # <<195, 187>> | "û"
def to_unicode(149), do: 242 # <<195, 178>> | "ò"
def to_unicode(148), do: 246 # <<195, 182>> | "ö"
def to_unicode(147), do: 244 # <<195, 180>> | "ô"
def to_unicode(146), do: 198 # <<195, 134>> | "Æ"
def to_unicode(145), do: 230 # <<195, 166>> | "æ"
def to_unicode(144), do: 201 # <<195, 137>> | "É"
def to_unicode(143), do: 197 # <<195, 133>> | "Å"
def to_unicode(142), do: 196 # <<195, 132>> | "Ä"
def to_unicode(141), do: 236 # <<195, 172>> | "ì"
def to_unicode(140), do: 238 # <<195, 174>> | "î"
def to_unicode(139), do: 239 # <<195, 175>> | "ï"
def to_unicode(138), do: 232 # <<195, 168>> | "è"
def to_unicode(137), do: 235 # <<195, 171>> | "ë"
def to_unicode(136), do: 234 # <<195, 170>> | "ê"
def to_unicode(135), do: 231 # <<195, 167>> | "ç"
def to_unicode(134), do: 229 # <<195, 165>> | "å"
def to_unicode(133), do: 224 # <<195, 160>> | "à"
def to_unicode(132), do: 228 # <<195, 164>> | "ä"
def to_unicode(131), do: 226 # <<195, 162>> | "â"
def to_unicode(130), do: 233 # <<195, 169>> | "é"
def to_unicode(129), do: 252 # <<195, 188>> | "ü"
def to_unicode(128), do: 199 # <<195, 135>> | "Ç"
def to_unicode(127), do: 127 # <<127>> | "\d"
def to_unicode(126), do: 126 # <<126>> | "~"
def to_unicode(125), do: 125 # <<125>> | "}"
def to_unicode(124), do: 124 # <<124>> | "|"
def to_unicode(123), do: 123 # <<123>> | "{"
def to_unicode(122), do: 122 # <<122>> | "z"
def to_unicode(121), do: 121 # <<121>> | "y"
def to_unicode(120), do: 120 # <<120>> | "x"
def to_unicode(119), do: 119 # <<119>> | "w"
def to_unicode(118), do: 118 # <<118>> | "v"
def to_unicode(117), do: 117 # <<117>> | "u"
def to_unicode(116), do: 116 # <<116>> | "t"
def to_unicode(115), do: 115 # <<115>> | "s"
def to_unicode(114), do: 114 # <<114>> | "r"
def to_unicode(113), do: 113 # <<113>> | "q"
def to_unicode(112), do: 112 # <<112>> | "p"
def to_unicode(111), do: 111 # <<111>> | "o"
def to_unicode(110), do: 110 # <<110>> | "n"
def to_unicode(109), do: 109 # <<109>> | "m"
def to_unicode(108), do: 108 # <<108>> | "l"
def to_unicode(107), do: 107 # <<107>> | "k"
def to_unicode(106), do: 106 # <<106>> | "j"
def to_unicode(105), do: 105 # <<105>> | "i"
def to_unicode(104), do: 104 # <<104>> | "h"
def to_unicode(103), do: 103 # <<103>> | "g"
def to_unicode(102), do: 102 # <<102>> | "f"
def to_unicode(101), do: 101 # <<101>> | "e"
def to_unicode(100), do: 100 # <<100>> | "d"
def to_unicode(99), do: 99 # <<99>> | "c"
def to_unicode(98), do: 98 # <<98>> | "b"
def to_unicode(97), do: 97 # <<97>> | "a"
def to_unicode(96), do: 96 # <<96>> | "`"
def to_unicode(95), do: 95 # <<95>> | "_"
def to_unicode(94), do: 94 # <<94>> | "^"
def to_unicode(93), do: 93 # <<93>> | "]"
def to_unicode(92), do: 92 # <<92>> | "\\"
def to_unicode(91), do: 91 # <<91>> | "["
def to_unicode(90), do: 90 # <<90>> | "Z"
def to_unicode(89), do: 89 # <<89>> | "Y"
def to_unicode(88), do: 88 # <<88>> | "X"
def to_unicode(87), do: 87 # <<87>> | "W"
def to_unicode(86), do: 86 # <<86>> | "V"
def to_unicode(85), do: 85 # <<85>> | "U"
def to_unicode(84), do: 84 # <<84>> | "T"
def to_unicode(83), do: 83 # <<83>> | "S"
def to_unicode(82), do: 82 # <<82>> | "R"
def to_unicode(81), do: 81 # <<81>> | "Q"
def to_unicode(80), do: 80 # <<80>> | "P"
def to_unicode(79), do: 79 # <<79>> | "O"
def to_unicode(78), do: 78 # <<78>> | "N"
def to_unicode(77), do: 77 # <<77>> | "M"
def to_unicode(76), do: 76 # <<76>> | "L"
def to_unicode(75), do: 75 # <<75>> | "K"
def to_unicode(74), do: 74 # <<74>> | "J"
def to_unicode(73), do: 73 # <<73>> | "I"
def to_unicode(72), do: 72 # <<72>> | "H"
def to_unicode(71), do: 71 # <<71>> | "G"
def to_unicode(70), do: 70 # <<70>> | "F"
def to_unicode(69), do: 69 # <<69>> | "E"
def to_unicode(68), do: 68 # <<68>> | "D"
def to_unicode(67), do: 67 # <<67>> | "C"
def to_unicode(66), do: 66 # <<66>> | "B"
def to_unicode(65), do: 65 # <<65>> | "A"
def to_unicode(64), do: 64 # <<64>> | "@"
def to_unicode(63), do: 63 # <<63>> | "?"
def to_unicode(62), do: 62 # <<62>> | ">"
def to_unicode(61), do: 61 # <<61>> | "="
def to_unicode(60), do: 60 # <<60>> | "<"
def to_unicode(59), do: 59 # <<59>> | ";"
def to_unicode(58), do: 58 # <<58>> | ":"
def to_unicode(57), do: 57 # <<57>> | "9"
def to_unicode(56), do: 56 # <<56>> | "8"
def to_unicode(55), do: 55 # <<55>> | "7"
def to_unicode(54), do: 54 # <<54>> | "6"
def to_unicode(53), do: 53 # <<53>> | "5"
def to_unicode(52), do: 52 # <<52>> | "4"
def to_unicode(51), do: 51 # <<51>> | "3"
def to_unicode(50), do: 50 # <<50>> | "2"
def to_unicode(49), do: 49 # <<49>> | "1"
def to_unicode(48), do: 48 # <<48>> | "0"
def to_unicode(47), do: 47 # <<47>> | "/"
def to_unicode(46), do: 46 # <<46>> | "."
def to_unicode(45), do: 45 # <<45>> | "-"
def to_unicode(44), do: 44 # <<44>> | ","
def to_unicode(43), do: 43 # <<43>> | "+"
def to_unicode(42), do: 42 # <<42>> | "*"
def to_unicode(41), do: 41 # <<41>> | ")"
def to_unicode(40), do: 40 # <<40>> | "("
def to_unicode(39), do: 39 # <<39>> | "'"
def to_unicode(38), do: 38 # <<38>> | "&"
def to_unicode(37), do: 37 # <<37>> | "%"
def to_unicode(36), do: 36 # <<36>> | "$"
def to_unicode(35), do: 35 # <<35>> | "#"
def to_unicode(34), do: 34 # <<34>> | "\""
def to_unicode(33), do: 33 # <<33>> | "!"
def to_unicode(32), do: 32 # <<32>> | " "
def to_unicode(31), do: nil # <<31>> | <<31>>
def to_unicode(30), do: nil # <<30>> | <<30>>
def to_unicode(29), do: nil # <<29>> | <<29>>
def to_unicode(28), do: nil # <<28>> | <<28>>
def to_unicode(27), do: 27 # <<27>> | "\e"
def to_unicode(26), do: nil # <<26>> | <<26>>
def to_unicode(25), do: nil # <<25>> | <<25>>
def to_unicode(24), do: nil # <<24>> | <<24>>
def to_unicode(23), do: nil # <<23>> | <<23>>
def to_unicode(22), do: nil # <<22>> | <<22>>
def to_unicode(21), do: nil # <<21>> | <<21>>
def to_unicode(20), do: nil # <<20>> | <<20>>
def to_unicode(19), do: nil # <<19>> | <<19>>
def to_unicode(18), do: nil # <<18>> | <<18>>
def to_unicode(17), do: nil # <<17>> | <<17>>
def to_unicode(16), do: nil # <<16>> | <<16>>
def to_unicode(15), do: nil # <<15>> | <<15>>
def to_unicode(14), do: nil # <<14>> | <<14>>
def to_unicode(13), do: 13 # <<13>> | "\r"
def to_unicode(12), do: 12 # <<12>> | "\f"
def to_unicode(11), do: 11 # <<11>> | "\v"
def to_unicode(10), do: 10 # <<92, 110>> | "\\n"
def to_unicode(9), do: 9 # <<9>> | "\t"
def to_unicode(8), do: 8 # <<8>> | "\b"
def to_unicode(7), do: 7 # <<7>> | "\a"
def to_unicode(6), do: nil # <<6>> | <<6>>
def to_unicode(5), do: nil # <<5>> | <<5>>
def to_unicode(4), do: nil # <<4>> | <<4>>
def to_unicode(3), do: nil # <<3>> | <<3>>
def to_unicode(2), do: nil # <<2>> | <<2>>
def to_unicode(1), do: nil # <<1>> | <<1>>
def to_unicode(0), do: nil # <<0>> | <<0>>
end | 49.112403 | 57 | 0.518428 |
03c582ef6082789651e7a5b17bfe0d9326f67fd1 | 3,052 | ex | Elixir | lib/k8s/client/runner/base.ex | Overbryd/k8s | 7057601b1f191b47294133045c9e5b74bd9dd525 | [
"MIT"
] | null | null | null | lib/k8s/client/runner/base.ex | Overbryd/k8s | 7057601b1f191b47294133045c9e5b74bd9dd525 | [
"MIT"
] | null | null | null | lib/k8s/client/runner/base.ex | Overbryd/k8s | 7057601b1f191b47294133045c9e5b74bd9dd525 | [
"MIT"
] | null | null | null | defmodule K8s.Client.Runner.Base do
@moduledoc """
Base HTTP processor for `K8s.Client`
"""
@type result :: {:ok, map() | reference()} | {:error, atom} | {:error, binary()}
alias K8s.Cluster
alias K8s.Conf.RequestOptions
alias K8s.Operation
@doc """
Runs a `K8s.Operation`.
## Examples
*Note:* Examples assume a cluster was registered named "test-cluster", see `K8s.Cluster.register/2`.
Running a list pods operation:
```elixir
operation = K8s.Client.list("v1", "Pod", namespace: :all)
{:ok, %{"items" => pods}} = K8s.Client.run(operation, "test-cluster")
```
Running a dry-run of a create deployment operation:
```elixir
deployment = %{
"apiVersion" => "apps/v1",
"kind" => "Deployment",
"metadata" => %{
"labels" => %{
"app" => "nginx"
},
"name" => "nginx",
"namespace" => "test"
},
"spec" => %{
"replicas" => 2,
"selector" => %{
"matchLabels" => %{
"app" => "nginx"
}
},
"template" => %{
"metadata" => %{
"labels" => %{
"app" => "nginx"
}
},
"spec" => %{
"containers" => %{
"image" => "nginx",
"name" => "nginx"
}
}
}
}
}
operation = K8s.Client.create(deployment)
# opts is passed to HTTPoison as opts.
opts = [params: %{"dryRun" => "all"}]
:ok = K8s.Client.Runner.Base.run(operation, "test-cluster", opts)
```
"""
@spec run(Operation.t(), nil | binary | atom) :: result
def run(operation = %Operation{}, cluster_name \\ "default"),
do: run(operation, cluster_name, [])
@doc """
Run an operation and pass `opts` to HTTPoison.
See `run/2`
"""
@spec run(Operation.t(), binary | atom, keyword()) :: result
def run(operation = %Operation{}, cluster_name, opts) when is_list(opts) do
run(operation, cluster_name, operation.resource, opts)
end
@doc """
Run an operation with an alternative HTTP Body (map) and pass `opts` to HTTPoison.
See `run/2`
"""
@spec run(Operation.t(), binary | atom, map(), keyword()) :: result
def run(operation = %Operation{}, cluster_name, body, opts \\ []) do
case Cluster.url_for(operation, cluster_name) do
{:ok, url} ->
{:ok, conf} = Cluster.conf(cluster_name)
request_options = RequestOptions.generate(conf)
http_headers = K8s.http_provider().headers(request_options)
http_opts = Keyword.merge([ssl: request_options.ssl_options], opts)
case encode(body, operation.method) do
{:ok, http_body} ->
K8s.http_provider().request(operation.method, url, http_body, http_headers, http_opts)
{:error, error} ->
{:error, error}
end
{:error, error} ->
{:error, error}
end
end
@spec encode(any(), atom()) :: {:ok, binary} | {:error, any}
def encode(body, http_method) when http_method in [:put, :patch, :post] do
Jason.encode(body)
end
def encode(_, _), do: {:ok, ""}
end
| 26.310345 | 102 | 0.56291 |
03c5ad88ac40582305819cf11b0ad147aca241ed | 6,781 | ex | Elixir | plugins/one_wiki/lib/one_wiki/models/page.ex | smpallen99/ucx_ucc | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 11 | 2017-05-15T18:35:05.000Z | 2018-02-05T18:27:40.000Z | plugins/one_wiki/lib/one_wiki/models/page.ex | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 15 | 2017-11-27T10:38:05.000Z | 2018-02-09T20:42:08.000Z | plugins/one_wiki/lib/one_wiki/models/page.ex | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 4 | 2017-09-13T11:34:16.000Z | 2018-02-26T13:37:06.000Z | defmodule OneWiki.Page do
@moduledoc """
The Page context file.
"""
use OneModel, schema: OneWiki.Schema.Page
alias Ecto.Multi
alias InfinityOne.Accounts.User
alias OneWiki.Settings.Wiki, as: Settings
require Logger
def changeset(%User{} = user, params) do
changeset %@schema{}, user, params
end
def changeset(%@schema{} = struct, %User{} = user) do
changeset(struct, user, %{})
end
def changeset(struct, user, params) do
struct
|> @schema.changeset(params)
|> validate_permission(user)
end
@doc """
Create a new page.
Creates the database entry for the page. Also creates a file with the page
body in `priv/static/uploads/pages` directory. This directory is a git repo.
After writing the file, it is committed to the git repo, providing version
control of each page revision.
"""
def create(user, params) do
case create_transaction(user, params) |> @repo.transaction() do
{:ok, %{page: page}} -> {:ok, page}
{:error, _, reason} -> {:error, reason}
{:error, _, reason, _} -> {:error, reason}
end
end
defp create_transaction(user, params) do
changeset = changeset(user, params)
Multi.new()
|> Multi.insert(:page, changeset)
|> Multi.run(:create_file, &create_file(user, &1.page, changeset))
end
@doc """
Updates an existing page.
Updates the database record with the modified page. Runs the same git commands
as create/2 to commit the revisions in git.
"""
def update(user, page, params) do
case update_transaction(user, page, params) |> @repo.transaction() do
{:ok, %{page: page}} -> {:ok, page}
{:error, _, reason} -> {:error, reason}
{:error, _, reason, _} -> {:error, reason}
end
end
defp update_transaction(user, page, params) do
changeset = changeset(page, user, params)
Multi.new()
|> Multi.update(:page, changeset)
|> Multi.run(:update_file, &update_file(user, &1.page, changeset))
end
defp create_file(user, page, _changeset) do
if Settings.wiki_history_enabled do
repo = Git.new OneWiki.pages_path()
{path, message} = path_and_message(page, user, :added)
with :ok <- File.write(path, page.body),
{:ok, _} <- Git.add(repo, page.title),
{:ok, _} <- Git.commit(repo, ["-m", message]) do
{:ok, path}
else
true -> {:ok, path}
{:error, error} -> {:error, error}
other -> {:error, other}
end
else
{:ok, ""}
end
end
defp update_file(user, page, %{changes: %{title: _title}} = changeset) do
if Settings.wiki_history_enabled do
repo = Git.new OneWiki.pages_path()
{path, message} = path_and_message(page, user, :renamed)
old_path = Path.join(repo.path, changeset.data.title)
old_name = changeset.data.title
with :ok <- File.write(old_path, page.body),
{:ok, _} <- Git.mv(repo, [old_name, page.title]),
{:ok, _} <- Git.commit(repo, ["-am", message]) do
{:ok, path}
else
true -> {:ok, path}
{:error, error} -> {:error, error}
other -> {:error, other}
end
else
{:ok, ""}
end
end
defp update_file(user, page, _changeset) do
if Settings.wiki_history_enabled do
repo = Git.new OneWiki.pages_path()
{path, message} = path_and_message(page, user, :changed)
with :ok <- File.write(path, page.body),
{:ok, status} <- Git.status(repo),
false <- status =~ "nothing to commit",
{:ok, _} <- Git.add(repo, page.title),
{:ok, _} <- Git.commit(repo, ["-m", message]) do
{:ok, path}
else
true -> {:ok, path}
{:error, error} -> {:error, error}
other -> {:error, other}
end
else
{:ok, ""}
end
end
defp path_and_message(page, user, action) do
message = page.commit_message || "'#{page.title}' #{action} by @#{user.username}"
path = Path.join(OneWiki.pages_path(), page.title)
{path, message}
end
def delete(user, id) do
case delete_transaction(user, id) |> @repo.transaction() do
{:ok, %{delete: delete}} -> {:ok, delete}
{:error, _, reason} -> {:error, reason}
{:error, _, reason, _} -> {:error, reason}
end
end
defp delete_transaction(user, id) do
Multi.new()
|> Multi.run(:delete, fn _ -> run_delete(user, id) end)
|> Multi.run(:delete_file, &delete_file(user, &1.delete))
end
defp run_delete(user, page_id) do
page_id
|> get()
|> changeset(user)
|> delete()
end
defp delete_file(user, page) do
if Settings.wiki_history_enabled do
repo = Git.new OneWiki.pages_path()
message = "'#{page.title}' delete by @#{user.username}"
path = Path.join(OneWiki.pages_path(), page.id)
with :ok <- File.rm(path),
{:ok, _} <- Git.commit(repo, ["-am", message]) do
{:ok, path}
else
{:error, error} -> {:error, error}
other -> {:error, other}
end
else
{:ok, ""}
end
end
defp validate_permission(changeset, _user) do
changeset
end
def get_subscribed_for_user(user) do
user
|> @schema.subscribed_pages_query()
|> @repo.all()
end
def get_visible_subscribed_for_user(user) do
user
|> @schema.subscribed_pages_query()
|> where([p, s], s.hidden == false)
|> @repo.all()
end
def get_all_users(%@schema{} = page) do
page
|> @repo.preload([:users])
|> Map.get(:users)
end
def get_all_page_online_users(%@schema{} = page) do
page
|> get_all_page_users()
|> Enum.reject(&(&1.status == "offline"))
end
def get_all_page_users(%@schema{} = page) do
page
|> get_all_users()
|> Enum.map(fn user ->
user
|> struct(status: OneChat.PresenceAgent.get(user.id))
|> OneChat.Hooks.preload_user([])
end)
end
def get_page_offline_users(page) do
page
|> get_all_page_users
|> Enum.filter(&(&1.status == "offline"))
end
def get_pages_by_pattern(user_id, pattern, count \\ 5)
def get_pages_by_pattern(%{id: id}, pattern, count) do
get_pages_by_pattern(id, pattern, count)
end
def get_pages_by_pattern(user_id, pattern, count) do
user_id
|> get_authorized_pages
|> where([c], like(c.title, ^pattern))
|> order_by([c], asc: c.title)
|> limit(^count)
|> select([c], {c.id, c.title})
|> @repo.all
end
def get_all_pages_by_pattern(pattern, count \\ 8) do
@schema
|> where([c], like(fragment("LOWER(?)", c.title), ^pattern))
|> where([c], c.type in [0, 1])
|> order_by([c], asc: c.type)
|> limit(^count)
|> select([c], %{id: c.id, name: c.type})
|> @repo.all
end
def get_authorized_pages(_) do
list()
end
end
| 27.232932 | 85 | 0.597552 |
03c5cdc58ba1da2082189e4cec1c4289f7c5aa1b | 429 | exs | Elixir | test/playground_web/views/error_view_test.exs | EasterPeanut/phoenix-playground | 391e52c7cf805d8acabb265989c801923438c624 | [
"MIT"
] | null | null | null | test/playground_web/views/error_view_test.exs | EasterPeanut/phoenix-playground | 391e52c7cf805d8acabb265989c801923438c624 | [
"MIT"
] | null | null | null | test/playground_web/views/error_view_test.exs | EasterPeanut/phoenix-playground | 391e52c7cf805d8acabb265989c801923438c624 | [
"MIT"
] | null | null | null | defmodule PlaygroundWeb.ErrorViewTest do
use PlaygroundWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(PlaygroundWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(PlaygroundWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 28.6 | 95 | 0.741259 |
03c5d77925f702652eccc452310919125016116f | 38,426 | ex | Elixir | lib/nadia.ex | angordeyev/nadia | e57b45d1d73be195604e56f4e08fe7ce757518b9 | [
"MIT"
] | 386 | 2015-08-20T21:48:07.000Z | 2022-03-06T21:08:19.000Z | lib/nadia.ex | angordeyev/nadia | e57b45d1d73be195604e56f4e08fe7ce757518b9 | [
"MIT"
] | 146 | 2015-09-19T07:13:56.000Z | 2022-03-24T20:02:02.000Z | lib/nadia.ex | angordeyev/nadia | e57b45d1d73be195604e56f4e08fe7ce757518b9 | [
"MIT"
] | 107 | 2015-10-23T09:02:13.000Z | 2022-02-07T19:46:15.000Z | defmodule Nadia do
@moduledoc """
Provides access to Telegram Bot API.
## Reference
https://core.telegram.org/bots/api#available-methods
"""
alias Nadia.Model.{User, Message, Update, UserProfilePhotos, File, Error, WebhookInfo}
import Nadia.API
@behaviour Nadia.Behaviour
@doc """
A simple method for testing your bot's auth token. Requires no parameters.
Returns basic information about the bot in form of a User object.
"""
@spec get_me :: {:ok, User.t()} | {:error, Error.t()}
def get_me, do: request("getMe")
@doc """
Use this method to send text messages.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `text` - Text of the message to be sent
* `options` - orddict of options
Options:
* `:parse_mode` - Use `Markdown`, if you want Telegram apps to show bold, italic
and inline URLs in your bot's message
* `:disable_web_page_preview` - Disables link previews for links in this message
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_message(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_message(chat_id, text, options \\ []) do
request("sendMessage", [chat_id: chat_id, text: text] ++ options)
end
@doc """
Use this method to forward messages of any kind.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `from_chat_id` - Unique identifier for the chat where the original message was sent
or username of the target channel (in the format @channelusername)
* `:disable_notification` - Sends the message silently or without notification
* `message_id` - Unique message identifier
"""
@spec forward_message(integer | binary, integer | binary, integer) ::
{:ok, Message.t()} | {:error, Error.t()}
def forward_message(chat_id, from_chat_id, message_id) do
request(
"forwardMessage",
chat_id: chat_id,
from_chat_id: from_chat_id,
message_id: message_id
)
end
@doc """
Use this method to send photos.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `photo` - Photo to send. Either a `file_id` to resend a photo that is already on
the Telegram servers, or a `file_path` to upload a new photo
* `options` - orddict of options
Options:
* `:caption` - Photo caption (may also be used when resending photos by `file_id`)
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_photo(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_photo(chat_id, photo, options \\ []) do
request("sendPhoto", [chat_id: chat_id, photo: photo] ++ options, :photo)
end
@doc """
Use this method to send audio files, if you want Telegram clients to display
them in the music player. Your audio must be in the .mp3 format.
On success, the sent Message is returned.
Bots can currently send audio files of up to 50 MB in size, this limit may
be changed in the future.
For backward compatibility, when the fields title and performer are both
empty and the mime-type of the file to be sent is not audio/mpeg, the file
will be sent as a playable voice message. For this to work, the audio must be
in an .ogg file encoded with OPUS. This behavior will be phased out in the
future. For sending voice messages, use the sendVoice method instead.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `audio` - Audio to send. Either a `file_id` to resend an audio that is already on
the Telegram servers, or a `file_path` to upload a new audio
* `options` - orddict of options
Options:
* `:duration` - Duration of the audio in seconds
* `:performer` - Performer
* `:title` - Track name
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_audio(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_audio(chat_id, audio, options \\ []) do
request("sendAudio", [chat_id: chat_id, audio: audio] ++ options, :audio)
end
@doc """
Use this method to send general files.
On success, the sent Message is returned.
Bots can currently send files of any type of up to 50 MB in size, this limit
may be changed in the future.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `document` - File to send. Either a `file_id` to resend a file that is already on
the Telegram servers, or a `file_path` to upload a new file
* `options` - orddict of options
Options:
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_document(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_document(chat_id, document, options \\ []) do
request("sendDocument", [chat_id: chat_id, document: document] ++ options, :document)
end
@doc """
Use this method to send .webp stickers.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `sticker` - File to send. Either a `file_id` to resend a sticker that is already on
the Telegram servers, or a `file_path` to upload a new sticker
* `options` - orddict of options
Options:
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_sticker(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_sticker(chat_id, sticker, options \\ []) do
request("sendSticker", [chat_id: chat_id, sticker: sticker] ++ options, :sticker)
end
@doc """
Use this method to send video files, Telegram clients support mp4 videos
(other formats may be sent as Document).
On success, the sent Message is returned.
Bots can currently send video files of up to 50 MB in size, this limit may be
changed in the future.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `video` - Video to send. Either a `file_id` to resend a video that is already on
the Telegram servers, or a `file_path` to upload a new video
* `options` - orddict of options
Options:
* `:duration` - Duration of the video in seconds
* `:caption` - Video caption (may also be used when resending videos by `file_id`)
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_video(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_video(chat_id, video, options \\ []) do
request("sendVideo", [chat_id: chat_id, video: video] ++ options, :video)
end
@doc """
Use this method to send audio files, if you want Telegram clients to display
the file as a playable voice message. For this to work, your audio must be in
an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
On success, the sent Message is returned.
Bots can currently send voice messages of up to 50 MB in size, this limit may be
changed in the future.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `voice` - Audio to send. Either a `file_id` to resend an audio that is already on
the Telegram servers, or a `file_path` to upload a new audio
* `options` - orddict of options
Options:
* `:duration` - Duration of the audio in seconds
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_voice(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_voice(chat_id, voice, options \\ []) do
request("sendVoice", [chat_id: chat_id, voice: voice] ++ options, :voice)
end
@doc """
Use this method to send point on the map.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `latitude` - Latitude of location
* `longitude` - Longitude of location
* `options` - orddict of options
Options:
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. Instructions to hide keyboard or to
force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply`
"""
@spec send_location(integer | binary, float, float, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_location(chat_id, latitude, longitude, options \\ []) do
request(
"sendLocation",
[chat_id: chat_id, latitude: latitude, longitude: longitude] ++ options
)
end
@doc """
Use this method to send information about a venue.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `latitude` - Latitude of location
* `longitude` - Longitude of location
* `title` - Name of the venue
* `address` - Address of the venue
* `options` - orddict of options
Options:
* `:foursquare_id` - Foursquare identifier of the venue
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. A JSON-serialized object for
an inline keyboard, custom reply keyboard, instructions to hide reply keyboard
or to force a reply from the user. - `Nadia.Model.InlineKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardMarkup` or `Nadia.Model.ReplyKeyboardRemove` or
`Nadia.Model.ForceReply`
"""
@spec send_venue(integer | binary, float, float, binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_venue(chat_id, latitude, longitude, title, address, options \\ []) do
request(
"sendVenue",
[chat_id: chat_id, latitude: latitude, longitude: longitude, title: title, address: address] ++
options
)
end
@doc """
Use this method to send phone contacts.
On success, the sent Message is returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `phone_number` - Contact's phone number
* `first_name` - Contact's first name
* `options` - orddict of options
Options:
* `:last_name` - Contact's last name
* `:disable_notification` - Sends the message silently or without notification
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. A JSON-serialized object for
an inline keyboard, custom reply keyboard, instructions to hide reply keyboard
or to force a reply from the user. - `Nadia.Model.InlineKeyboardMarkup` or
`Nadia.Model.ReplyKeyboardMarkup` or `Nadia.Model.ReplyKeyboardRemove` or
`Nadia.Model.ForceReply`
"""
@spec send_contact(integer | binary, binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_contact(chat_id, phone_number, first_name, options \\ []) do
request(
"sendContact",
[chat_id: chat_id, phone_number: phone_number, first_name: first_name] ++ options
)
end
@doc """
Use this method when you need to tell the user that something is happening on
the bot's side. The status is set for 5 seconds or less (when a message
arrives from your bot, Telegram clients clear its typing status).
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `action` - Type of action to broadcast. Choose one, depending on what the user is
about to receive:
* `typing` for text messages
* `upload_photo` for photos
* `record_video` or `upload_video` for videos
* `record_audio` or `upload_audio` for audio files
* `upload_document` for general files
* `find_location` for location data
"""
@spec send_chat_action(integer | binary, binary) :: :ok | {:error, Error.t()}
def send_chat_action(chat_id, action) do
request("sendChatAction", chat_id: chat_id, action: action)
end
@doc """
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
On success, the sent Message is returned. Bots can currently send animation files of up
to 50 MB in size, this limit may be changed in the future.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `animation` - Animation to send. Pass a file_id as String to send an animation that
exists on the Telegram servers (recommended), pass an HTTP URL as a String for
Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data.
Options:
* `:duration` - Duration of sent animation in seconds
* `:width` - Animation width
* `:height` - Animation height
* `:thumb` - Thumbnail of the file sent; can be ignored if thumbnail generation for the file
is supported server-side. thumbnail should be in JPEG format and less than 200 kB in size.
* `:caption` - Animation caption (may also be used when resending animation by file_id), 0-1024 characters
* `:parse_mode` - Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width
text or inline URLs in the media caption.
* `:disable_notification` - Sends the message silently. Users will receive a notification with no sound.
* `:reply_to_message_id` - If the message is a reply, ID of the original message
* `:reply_markup` - Additional interface options. A JSON-serialized object for an inline keyboard,
custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
"""
@spec send_animation(integer | binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def send_animation(chat_id, animation, options \\ []) do
request("sendAnimation", [chat_id: chat_id, animation: animation] ++ options)
end
@doc """
Use this method to get a list of profile pictures for a user.
Returns a UserProfilePhotos object.
Args:
* `user_id` - Unique identifier of the target user
* `options` - orddict of options
Options:
* `:offset` - Sequential number of the first photo to be returned. By default, all
photos are returned
* `:limit` - Limits the number of photos to be retrieved. Values between 1—100 are
accepted. Defaults to 100
"""
@spec get_user_profile_photos(integer, [{atom, any}]) ::
{:ok, UserProfilePhotos.t()} | {:error, Error.t()}
def get_user_profile_photos(user_id, options \\ []) do
request("getUserProfilePhotos", [user_id: user_id] ++ options)
end
@doc """
Use this method to receive incoming updates using long polling.
An Array of Update objects is returned.
Args:
* `options` - orddict of options
Options:
* `:offset` - Identifier of the first update to be returned. Must be greater by one
than the highest among the identifiers of previously received updates. By default,
updates starting with the earliest unconfirmed update are returned. An update is
considered confirmed as soon as `get_updates` is called with an `offset` higher than
its `update_id`.
* `:limit` - Limits the number of updates to be retrieved. Values between 1—100 are
accepted. Defaults to 100
* `:timeout` - Timeout in seconds for long polling. Defaults to 0, i.e. usual short
polling
"""
@spec get_updates([{atom, any}]) :: {:ok, [Update.t()]} | {:error, Error.t()}
def get_updates(options \\ []), do: request("getUpdates", options)
@doc """
Use this method to specify a url and receive incoming updates via an outgoing
webhook. Whenever there is an update for the bot, we will send an HTTPS POST
request to the specified url, containing a JSON-serialized Update. In case of
an unsuccessful request, we will give up after a reasonable amount of attempts.
Args:
* `options` - orddict of options
Options:
* `:url` - HTTPS url to send updates to.
"""
@spec set_webhook([{atom, any}]) :: :ok | {:error, Error.t()}
def set_webhook(options \\ []), do: request("setWebhook", options)
@doc """
Use this method to remove webhook integration if you decide to switch back to `Nadia.get_updates/1`.
Returns `:ok` on success.
Requires no parameters.
"""
@spec delete_webhook() :: :ok | {:error, Error.t()}
def delete_webhook(), do: request("deleteWebhook")
@doc """
Use this method to get current webhook status. Requires no parameters.
On success, returns a `Nadia.Model.WebhookInfo.t()` object with webhook details.
If the bot is using getUpdates, will return an object with the url field empty.
"""
@spec get_webhook_info() :: {:ok, WebhookInfo.t()} | {:error, Error.t()}
def get_webhook_info(), do: request("getWebhookInfo")
@doc """
Use this method to get basic info about a file and prepare it for downloading.
For the moment, bots can download files of up to 20MB in size.
On success, a File object is returned.
The file can then be downloaded via the link
`https://api.telegram.org/file/bot<token>/<file_path>`, where <file_path> is taken
from the response. It is guaranteed that the link will be valid for at least 1 hour.
When the link expires, a new one can be requested by calling `get_file` again.
Args:
* `file_id` - File identifier to get info about
"""
@spec get_file(binary) :: {:ok, File.t()} | {:error, Error.t()}
def get_file(file_id), do: request("getFile", file_id: file_id)
@doc ~S"""
Use this method to get link for file for subsequent use.
This method is an extension of the `get_file` method.
iex> Nadia.get_file_link(%Nadia.Model.File{file_id: "BQADBQADBgADmEjsA1aqdSxtzvvVAg",
...> file_path: "document/file_10", file_size: 17680})
{:ok,
"https://api.telegram.org/file/bot#{Nadia.Config.token()}/document/file_10"}
"""
@spec get_file_link(File.t()) :: {:ok, binary} | {:error, Error.t()}
def get_file_link(file) do
{:ok, build_file_url(file.file_path)}
end
@doc """
Use this method to kick a user from a group or a supergroup. In the case of supergroups,
the user will not be able to return to the group on their own using invite links, etc.,
unless unbanned first. The bot must be an administrator in the group for this to work.
Returns True on success.
Note: This will method only work if the ‘All Members Are Admins’ setting is off in the
target group. Otherwise members may only be removed by the group's creator or by the
member that added them.
Args:
* `chat_id` - Unique identifier for the target group or username of the target supergroup
(in the format @supergroupusername)
* `user_id` - Unique identifier of the target user
"""
@spec kick_chat_member(integer | binary, integer) :: :ok | {:error, Error.t()}
def kick_chat_member(chat_id, user_id) do
request("kickChatMember", chat_id: chat_id, user_id: user_id)
end
@doc """
Use this method for your bot to leave a group, supergroup or channel.
Returns True on success.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target supergroup or
channel (in the format @supergroupusername)
"""
@spec leave_chat(integer | binary) :: :ok | {:error, Error.t()}
def leave_chat(chat_id) do
request("leaveChat", chat_id: chat_id)
end
@doc """
Use this method to unban a previously kicked user in a supergroup. The user will not
return to the group automatically, but will be able to join via link, etc. The bot
must be an administrator in the group for this to work. Returns True on success.
Args:
* `chat_id` - Unique identifier for the target group or username of the target supergroup
(in the format @supergroupusername)
* `user_id` - Unique identifier of the target user
"""
@spec unban_chat_member(integer | binary, integer) :: :ok | {:error, Error.t()}
def unban_chat_member(chat_id, user_id) do
request("unbanChatMember", chat_id: chat_id, user_id: user_id)
end
@doc """
Use this method to get up to date information about the chat (current name of
the user for one-on-one conversations, current username of a user, group or channel, etc.)
Returns a Chat object on success.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target supergroup or
channel (in the format @supergroupusername)
"""
@spec get_chat(integer | binary) :: {:ok, Chat.t()} | {:error, Error.t()}
def get_chat(chat_id) do
request("getChat", chat_id: chat_id)
end
@doc """
Use this method to get a list of administrators in a chat. On success, returns an Array of
ChatMember objects that contains information about all chat administrators except other bots.
If the chat is a group or a supergroup and no administrators were appointed, only the creator
will be returned.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target supergroup or
channel (in the format @channelusername)
"""
@spec get_chat_administrators(integer | binary) :: {:ok, [ChatMember.t()]} | {:error, Error.t()}
def get_chat_administrators(chat_id) do
request("getChatAdministrators", chat_id: chat_id)
end
@doc """
Use this method to get the number of members in a chat. Returns Int on success.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target supergroup or
channel (in the format @channelusername)
"""
@spec get_chat_members_count(integer | binary) :: {:ok, integer} | {:error, Error.t()}
def get_chat_members_count(chat_id) do
request("getChatMembersCount", chat_id: chat_id)
end
@doc """
Use this method to get information about a member of a chat.
Returns a ChatMember object on success.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target supergroup or
channel (in the format @channelusername)
* `user_id` - Unique identifier of the target user
"""
@spec get_chat_member(integer | binary, integer) :: {:ok, ChatMember.t()} | {:error, Error.t()}
def get_chat_member(chat_id, user_id) do
request("getChatMember", chat_id: chat_id, user_id: user_id)
end
@doc """
Use this method to send answers to callback queries sent from inline keyboards.
The answer will be displayed to the user as a notification at the top of the chat
screen or as an alert. On success, True is returned.
Args:
* `callback_query_id` - Unique identifier for the query to be answered
* `options` - orddict of options
Options:
* `:text` - Text of the notification. If not specified, nothing will be shown
to the user
* `:show_alert` - If true, an alert will be shown by the client instead of a
notification at the top of the chat screen. Defaults to false.
"""
@spec answer_callback_query(binary, [{atom, any}]) :: :ok | {:error, Error.t()}
def answer_callback_query(callback_query_id, options \\ []) do
request("answerCallbackQuery", [callback_query_id: callback_query_id] ++ options)
end
@doc """
Use this method to edit text messages sent by the bot or via the bot (for inline bots).
On success, the edited Message is returned
Args:
* `chat_id` - Required if inline_message_id is not specified. Unique identifier
for the target chat or username of the target channel (in the format @channelusername)
* `message_id` - Required if inline_message_id is not specified. Unique identifier of
the sent message
* `inline_message_id` - Required if `chat_id` and `message_id` are not specified.
Identifier of the inline message
* `text` - New text of the message
* `options` - orddict of options
Options:
* `:parse_mode` - Send Markdown or HTML, if you want Telegram apps to show bold, italic,
fixed-width text or inline URLs in your bot's message.
* `:disable_web_page_preview` - Disables link previews for links in this message
* `:reply_markup` - A JSON-serialized object for an inline
keyboard - `Nadia.Model.InlineKeyboardMarkup`
"""
@spec edit_message_text(integer | binary, integer, binary, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def edit_message_text(chat_id, message_id, inline_message_id, text, options \\ []) do
request(
"editMessageText",
[chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id, text: text] ++
options
)
end
@doc """
Use this method to delete message from a chat.
Bot should have admin permission to do that, and remember you can't delete messages that are more than
48 hours old.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `message_id` - Required if inline_message_id is not specified. Unique identifier of
the sent message
"""
@spec delete_message(integer | binary, integer) :: :ok | {:error, Error.t()}
def delete_message(chat_id, message_id) do
request(
"deleteMessage",
chat_id: chat_id,
message_id: message_id
)
end
@doc """
Use this method to edit captions of messages sent by the bot or via
the bot (for inline bots). On success, the edited Message is returned.
Args:
* `chat_id` - Required if inline_message_id is not specified. Unique identifier
for the target chat or username of the target channel (in the format @channelusername)
* `message_id` - Required if inline_message_id is not specified. Unique identifier of
the sent message
* `inline_message_id` - Required if `chat_id` and `message_id` are not specified.
Identifier of the inline message
* `options` - orddict of options
Options:
* `:caption` - New caption of the message
* `:reply_markup` - A JSON-serialized object for an inline
keyboard - `Nadia.Model.InlineKeyboardMarkup`
"""
@spec edit_message_caption(integer | binary, integer, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def edit_message_caption(chat_id, message_id, inline_message_id, options \\ []) do
request(
"editMessageCaption",
[chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id] ++ options
)
end
@doc """
Use this method to edit only the reply markup of messages sent by the bot or via
the bot (for inline bots). On success, the edited Message is returned.
Args:
* `chat_id` - Required if inline_message_id is not specified. Unique identifier
for the target chat or username of the target channel (in the format @channelusername)
* `message_id` - Required if inline_message_id is not specified. Unique identifier of
the sent message
* `inline_message_id` - Required if `chat_id` and `message_id` are not specified.
Identifier of the inline message
* `options` - orddict of options
Options:
* `:reply_markup` - A JSON-serialized object for an inline
keyboard - `Nadia.Model.InlineKeyboardMarkup`
"""
@spec edit_message_reply_markup(integer | binary, integer, binary, [{atom, any}]) ::
{:ok, Message.t()} | {:error, Error.t()}
def edit_message_reply_markup(chat_id, message_id, inline_message_id, options \\ []) do
request(
"editMessageReplyMarkup",
[chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id] ++ options
)
end
@doc """
Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results per query are allowed.
Args:
* `inline_query_id` - Unique identifier for the answered query
* `results` - An array of results for the inline query
* `options` - orddict of options
Options:
* `cache_time` - The maximum amount of time in seconds that the result of the inline
query may be cached on the server. Defaults to 300.
* `is_personal` - Pass True, if results may be cached on the server side only for
the user that sent the query. By default, results may be returned to any user who
sends the same query
* `next_offset` - Pass the offset that a client should send in the next query with
the same text to receive more results. Pass an empty string if there are no more
results or if you don‘t support pagination. Offset length can’t exceed 64 bytes.
* `switch_pm_text` - If passed, clients will display a button with specified text
that switches the user to a private chat with the bot and sends the bot a start
message with the parameter switch_pm_parameter.
* `switch_pm_parameter` - Parameter for the start message sent to the bot when user
presses the switch button.
"""
@spec answer_inline_query(binary, [Nadia.Model.InlineQueryResult.t()], [{atom, any}]) ::
:ok | {:error, Error.t()}
def answer_inline_query(inline_query_id, results, options \\ []) do
encoded_results =
results
|> Enum.map(fn result ->
for {k, v} <- Map.from_struct(result), v != nil, into: %{}, do: {k, v}
end)
|> Jason.encode!()
args = [inline_query_id: inline_query_id, results: encoded_results]
request("answerInlineQuery", args ++ options)
end
@doc """
Use this method to get a sticker set. On success, a StickerSet object is returned.
Args:
* `name` - Name of the sticker set
"""
@spec get_sticker_set(binary) :: {:ok, Nadia.Model.StickerSet.t()} | {:error, Error.t()}
def get_sticker_set(name) do
request("getStickerSet", name: name)
end
@doc """
Use this method to upload a .png file with a sticker for later use in
createNewStickerSet and addStickerToSet methods (can be used multiple times).
Returns the uploaded File on success.
Args:
* `user_id` - User identifier of sticker file owner
* `png_sticker` - Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
Either a `file_id` to resend a file that is already on the Telegram servers,
or a `file_path` to upload a new file from local, or a `HTTP URL` to get a file
from the internet.
"""
@spec upload_sticker_file(integer, binary) :: {:ok, File.t()} | {:error, Error.t()}
def upload_sticker_file(user_id, png_sticker) do
request("uploadStickerFile", [user_id: user_id, png_sticker: png_sticker], :png_sticker)
end
@doc """
Use this method to create new sticker set owned by a user. The bot will be able to
edit the created sticker set. Returns True on success.
Args:
* `user_id` - User identifier of created sticker set owner
* `name` - Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals).
Can contain only english letters, digits and underscores. Must begin with a letter,
can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username>
is case insensitive. 1-64 characters.
* `title` - Sticker set title, 1-64 characters
* `png_sticker` - Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
Either a `file_id` to resend a file that is already on the Telegram servers,
or a `file_path` to upload a new file from local, or a `HTTP URL` to get a file
from the internet.
* `emojis` - One or more emoji corresponding to the sticker
Options:
* `contains_masks` - Pass True, if a set of mask stickers should be created
* `mask_position` - A `Nadia.Model.MaskPosition` object for position where the mask
should be placed on faces
"""
@spec create_new_sticker_set(integer, binary, binary, binary, binary, [{atom, any}]) ::
:ok | {:error, Error.t()}
def create_new_sticker_set(user_id, name, title, png_sticker, emojis, options \\ []) do
request(
"createNewStickerSet",
[user_id: user_id, name: name, title: title, png_sticker: png_sticker, emojis: emojis] ++
options,
:png_sticker
)
end
@doc """
Use this method to add a new sticker to a set created by the bot. Returns True on success.
Args:
* `user_id` - User identifier of created sticker set owner
* `name` - Sticker set name
* `png_sticker` - Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
Either a `file_id` to resend a file that is already on the Telegram servers,
or a `file_path` to upload a new file from local, or a `HTTP URL` to get a file
from the internet.
* `emojis` - One or more emoji corresponding to the sticker
Options:
* `mask_position` - A `Nadia.Model.MaskPosition` object for position where the mask
should be placed on faces
"""
@spec add_sticker_to_set(integer, binary, binary, binary, [{atom, any}]) ::
:ok | {:error, Error.t()}
def add_sticker_to_set(user_id, name, png_sticker, emojis, options \\ []) do
request(
"addStickerToSet",
[user_id: user_id, name: name, png_sticker: png_sticker, emojis: emojis] ++ options,
:png_sticker
)
end
@doc """
Use this method to move a sticker in a set created by the bot to a specific position.
Returns True on success.
Args:
* `sticker` - File identifier of the sticker
* `position` - New sticker position in the set, zero-based
"""
@spec set_sticker_position_in_set(binary, integer) :: :ok | {:error, Error.t()}
def set_sticker_position_in_set(sticker, position) do
request("setStickerPositionInSet", sticker: sticker, position: position)
end
@doc """
Use this method to delete a sticker from a set created by the bot. Returns True on success.
Args:
* `sticker` - File identifier of the sticker
"""
@spec delete_sticker_from_set(binary) :: :ok | {:error, Error.t()}
def delete_sticker_from_set(sticker) do
request("deleteStickerFromSet", sticker: sticker)
end
@doc """
Use this method to pin a message in a group, a supergroup, or a channel. The bot must be an
administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right
in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
* `message_id` - Identifier of a message to pin
Options:
* `disable_notification` - Pass True, if it is not necessary to send a notification to all
chat members about the new pinned message. Notifications are always disabled in channels.
"""
@spec pin_chat_message(integer | binary, integer | binary, [{atom, any}]) ::
:ok | {:error, Error.t()}
def pin_chat_message(chat_id, message_id, options \\ []) do
request("pinChatMessage", [chat_id: chat_id, message_id: message_id] ++ options)
end
@doc """
Use this method to unpin a message in a group, a supergroup, or a channel. The bot must be an
administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in
the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.
Args:
* `chat_id` - Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
"""
@spec unpin_chat_message(integer | binary) :: :ok | {:error, Error.t()}
def unpin_chat_message(chat_id) do
request("unpinChatMessage", chat_id: chat_id)
end
end
| 42.648169 | 108 | 0.709051 |
03c5e70c37c4437c6dfda41ec9bee26cf1e48e6c | 1,959 | exs | Elixir | test/elx_k8s/cars_test.exs | adrianomota/elx-k8s | 27c0f5c3099137041043d05e754b2b5eb7e0c0f9 | [
"MIT"
] | null | null | null | test/elx_k8s/cars_test.exs | adrianomota/elx-k8s | 27c0f5c3099137041043d05e754b2b5eb7e0c0f9 | [
"MIT"
] | null | null | null | test/elx_k8s/cars_test.exs | adrianomota/elx-k8s | 27c0f5c3099137041043d05e754b2b5eb7e0c0f9 | [
"MIT"
] | null | null | null | defmodule ElxK8s.CarsTest do
use ElxK8s.DataCase
alias ElxK8s.Cars
describe "cars" do
alias ElxK8s.Cars.Car
@valid_attrs %{brand: "some brand", description: "some description"}
@update_attrs %{brand: "some updated brand", description: "some updated description"}
@invalid_attrs %{brand: nil, description: nil}
def car_fixture(attrs \\ %{}) do
{:ok, car} =
attrs
|> Enum.into(@valid_attrs)
|> Cars.create_car()
car
end
test "list_cars/0 returns all cars" do
car = car_fixture()
assert Cars.list_cars() == [car]
end
test "get_car!/1 returns the car with given id" do
car = car_fixture()
assert Cars.get_car!(car.id) == car
end
test "create_car/1 with valid data creates a car" do
assert {:ok, %Car{} = car} = Cars.create_car(@valid_attrs)
assert car.brand == "some brand"
assert car.description == "some description"
end
test "create_car/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Cars.create_car(@invalid_attrs)
end
test "update_car/2 with valid data updates the car" do
car = car_fixture()
assert {:ok, %Car{} = car} = Cars.update_car(car, @update_attrs)
assert car.brand == "some updated brand"
assert car.description == "some updated description"
end
test "update_car/2 with invalid data returns error changeset" do
car = car_fixture()
assert {:error, %Ecto.Changeset{}} = Cars.update_car(car, @invalid_attrs)
assert car == Cars.get_car!(car.id)
end
test "delete_car/1 deletes the car" do
car = car_fixture()
assert {:ok, %Car{}} = Cars.delete_car(car)
assert_raise Ecto.NoResultsError, fn -> Cars.get_car!(car.id) end
end
test "change_car/1 returns a car changeset" do
car = car_fixture()
assert %Ecto.Changeset{} = Cars.change_car(car)
end
end
end
| 29.238806 | 89 | 0.640123 |
03c5ebe83400f308328790dc2c8eb0fa77f03121 | 256 | ex | Elixir | lib/zappa/block_helpers/raw.ex | fireproofsocks/zappa | d89d983b73652e761861bd7c2c5d03a45fc4badd | [
"Apache-2.0"
] | 1 | 2021-08-23T21:48:14.000Z | 2021-08-23T21:48:14.000Z | lib/zappa/block_helpers/raw.ex | fireproofsocks/zappa | d89d983b73652e761861bd7c2c5d03a45fc4badd | [
"Apache-2.0"
] | null | null | null | lib/zappa/block_helpers/raw.ex | fireproofsocks/zappa | d89d983b73652e761861bd7c2c5d03a45fc4badd | [
"Apache-2.0"
] | null | null | null | defmodule Zappa.BlockHelpers.Raw do
@moduledoc false
# This module implements a simple "raw" helper, intended for use by the quadruple {{{{#raw}}}} ... {{{{/raw}}}} blocks
alias Zappa.Tag
def parse(tag) do
{:ok, tag.block_contents}
end
end
| 23.272727 | 120 | 0.671875 |
03c60728928e0faab4bcd1f531c32b30cecb09d8 | 768 | exs | Elixir | servers/exilp/apps/utils/mix.exs | cjimison/exilp | cb350c4dffe90d37607764e668e14e99bbad5428 | [
"MIT"
] | null | null | null | servers/exilp/apps/utils/mix.exs | cjimison/exilp | cb350c4dffe90d37607764e668e14e99bbad5428 | [
"MIT"
] | null | null | null | servers/exilp/apps/utils/mix.exs | cjimison/exilp | cb350c4dffe90d37607764e668e14e99bbad5428 | [
"MIT"
] | null | null | null | defmodule Utils.MixProject do
use Mix.Project
def project do
[
app: :utils,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
# {:sibling_app_in_umbrella, in_umbrella: true}
]
end
end
| 22.588235 | 88 | 0.565104 |
03c61bb92abc62d810dcc1f448870eeec75c8688 | 1,793 | ex | Elixir | lib/surface/formatter/phases/indent.ex | RudolfMan/surface | ee8c1546b77c91fe08e7360e64666c613bc5a900 | [
"MIT"
] | 468 | 2021-03-11T23:10:41.000Z | 2022-03-30T20:12:06.000Z | lib/surface/formatter/phases/indent.ex | RudolfMan/surface | ee8c1546b77c91fe08e7360e64666c613bc5a900 | [
"MIT"
] | 248 | 2021-03-12T07:39:37.000Z | 2022-03-31T13:36:44.000Z | lib/surface/formatter/phases/indent.ex | RudolfMan/surface | ee8c1546b77c91fe08e7360e64666c613bc5a900 | [
"MIT"
] | 46 | 2021-03-22T09:28:58.000Z | 2022-03-23T21:32:20.000Z | defmodule Surface.Formatter.Phases.Indent do
@moduledoc """
Adds indentation nodes (`:indent` and `:indent_one_less`) where appropriate.
`Surface.Formatter.Render.node/2` is responsible for adding the appropriate
level of indentation. It keeps track of the indentation level based on how
"nested" a node is. While running Formatter Phases, it's not necessary to
keep track of that detail.
`:indent_one_less` exists to notate the indentation that should occur before
a closing tag, which is one less than its children.
Relies on `Newlines` phase, which collapses :newline nodes to at most 2 in a row.
"""
@behaviour Surface.Formatter.Phase
alias Surface.Formatter.Phase
def run(nodes, _opts) do
# Add initial indent on start of first line
indent([:indent | nodes])
end
defp indent(nodes) do
# Deeply recurse through nodes and add indentation before newlines
nodes
|> add_indentation()
|> Phase.transform_element_children(&indent/1)
end
def add_indentation(nodes, accumulated \\ [])
def add_indentation([:newline, :newline | rest], accumulated) do
# Two newlines in a row; don't add indentation on the empty line
add_indentation(rest, accumulated ++ [:newline, :newline, :indent])
end
def add_indentation([:newline], accumulated) do
# The last child is a newline; add indentation for closing tag
add_indentation([], accumulated ++ [:newline, :indent_one_less])
end
def add_indentation([:newline | rest], accumulated) do
# Indent before the next child
add_indentation(rest, accumulated ++ [:newline, :indent])
end
def add_indentation([], accumulated) do
accumulated
end
def add_indentation([node | rest], accumulated) do
add_indentation(rest, accumulated ++ [node])
end
end
| 32.017857 | 83 | 0.723369 |
03c66f332fe6dd491bc87b5e4ef97d37a4207548 | 4,611 | ex | Elixir | lib/mail_slurp_api/api/template_controller.ex | sumup-bank/mailslurp-client-elixir | 87ccdedf2f0f4cd3e50f5781ffb088142e3cf4e8 | [
"MIT"
] | null | null | null | lib/mail_slurp_api/api/template_controller.ex | sumup-bank/mailslurp-client-elixir | 87ccdedf2f0f4cd3e50f5781ffb088142e3cf4e8 | [
"MIT"
] | null | null | null | lib/mail_slurp_api/api/template_controller.ex | sumup-bank/mailslurp-client-elixir | 87ccdedf2f0f4cd3e50f5781ffb088142e3cf4e8 | [
"MIT"
] | null | null | null | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule MailSlurpAPI.Api.TemplateController do
@moduledoc """
API calls for all endpoints tagged `TemplateController`.
"""
alias MailSlurpAPI.Connection
import MailSlurpAPI.RequestBuilder
@doc """
Create a Template
## Parameters
- connection (MailSlurpAPI.Connection): Connection to server
- create_template_options (CreateTemplateOptions): createTemplateOptions
- opts (KeywordList): [optional] Optional parameters
## Returns
{:ok, %MailSlurpAPI.Model.TemplateDto{}} on success
{:error, info} on failure
"""
@spec create_template(Tesla.Env.client, MailSlurpAPI.Model.CreateTemplateOptions.t, keyword()) :: {:ok, MailSlurpAPI.Model.TemplateDto.t} | {:error, Tesla.Env.t}
def create_template(connection, create_template_options, _opts \\ []) do
%{}
|> method(:post)
|> url("/templates")
|> add_param(:body, :body, create_template_options)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 201, %MailSlurpAPI.Model.TemplateDto{}},
{ 401, false},
{ 403, false},
{ 404, false}
])
end
@doc """
Delete Template
## Parameters
- connection (MailSlurpAPI.Connection): Connection to server
- template_id (String.t): TemplateId
- opts (KeywordList): [optional] Optional parameters
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec delete_template(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t}
def delete_template(connection, template_id, _opts \\ []) do
%{}
|> method(:delete)
|> url("/templates/#{template_id}")
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 204, false},
{ 401, false},
{ 403, false}
])
end
@doc """
Get all Templates in paginated format
## Parameters
- connection (MailSlurpAPI.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
- :page (integer()): Optional page index in inbox list pagination
- :size (integer()): Optional page size in inbox list pagination
- :sort (String.t): Optional createdAt sort direction ASC or DESC
## Returns
{:ok, %MailSlurpAPI.Model.PageTemplateProjection{}} on success
{:error, info} on failure
"""
@spec get_all_templates(Tesla.Env.client, keyword()) :: {:ok, MailSlurpAPI.Model.PageTemplateProjection.t} | {:error, Tesla.Env.t}
def get_all_templates(connection, opts \\ []) do
optional_params = %{
:"page" => :query,
:"size" => :query,
:"sort" => :query
}
%{}
|> method(:get)
|> url("/templates/paginated")
|> add_optional_params(optional_params, opts)
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, %MailSlurpAPI.Model.PageTemplateProjection{}},
{ 401, false},
{ 403, false},
{ 404, false}
])
end
@doc """
Get Template
## Parameters
- connection (MailSlurpAPI.Connection): Connection to server
- template_id (String.t): TemplateId
- opts (KeywordList): [optional] Optional parameters
## Returns
{:ok, %MailSlurpAPI.Model.TemplateDto{}} on success
{:error, info} on failure
"""
@spec get_template(Tesla.Env.client, String.t, keyword()) :: {:ok, MailSlurpAPI.Model.TemplateDto.t} | {:error, Tesla.Env.t}
def get_template(connection, template_id, _opts \\ []) do
%{}
|> method(:get)
|> url("/templates/#{template_id}")
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, %MailSlurpAPI.Model.TemplateDto{}},
{ 401, false},
{ 403, false},
{ 404, false}
])
end
@doc """
Get all Templates
## Parameters
- connection (MailSlurpAPI.Connection): Connection to server
- opts (KeywordList): [optional] Optional parameters
## Returns
{:ok, [%TemplateProjection{}, ...]} on success
{:error, info} on failure
"""
@spec get_templates(Tesla.Env.client, keyword()) :: {:ok, list(MailSlurpAPI.Model.TemplateProjection.t)} | {:error, Tesla.Env.t}
def get_templates(connection, _opts \\ []) do
%{}
|> method(:get)
|> url("/templates")
|> Enum.into([])
|> (&Connection.request(connection, &1)).()
|> evaluate_response([
{ 200, [%MailSlurpAPI.Model.TemplateProjection{}]},
{ 401, false},
{ 403, false},
{ 404, false}
])
end
end
| 28.639752 | 163 | 0.637606 |
03c67b3adf1521331d426ae8eb484cd7378d1ee3 | 1,990 | ex | Elixir | dev/support/seeds.ex | chinitadelrey/zero-to-graphql-using-phoenix | e5fbe4f9158aed2c5dfcd8c751e22b534fb09eb0 | [
"MIT"
] | null | null | null | dev/support/seeds.ex | chinitadelrey/zero-to-graphql-using-phoenix | e5fbe4f9158aed2c5dfcd8c751e22b534fb09eb0 | [
"MIT"
] | null | null | null | dev/support/seeds.ex | chinitadelrey/zero-to-graphql-using-phoenix | e5fbe4f9158aed2c5dfcd8c751e22b534fb09eb0 | [
"MIT"
] | null | null | null | defmodule ZeroPhoenix.Seeds do
alias ZeroPhoenix.Account.{Person, Friendship}
alias ZeroPhoenix.Repo
def run() do
#
# reset database
#
reset()
#
# people
#
me =
Repo.insert!(%Person{
first_name: "Conrad",
last_name: "Taylor",
email: "conradwt@gmail.com",
username: "conradwt"
})
dhh =
Repo.insert!(%Person{
first_name: "David",
last_name: "Heinemeier Hansson",
email: "dhh@37signals.com",
username: "dhh"
})
ezra =
Repo.insert!(%Person{
first_name: "Ezra",
last_name: "Zygmuntowicz",
email: "ezra@merbivore.com",
username: "ezra"
})
matz =
Repo.insert!(%Person{
first_name: "Yukihiro",
last_name: "Matsumoto",
email: "matz@heroku.com",
username: "matz"
})
#
# friendships
#
me
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: matz.id})
|> Repo.insert()
dhh
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: ezra.id})
|> Repo.insert()
dhh
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: matz.id})
|> Repo.insert()
ezra
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: dhh.id})
|> Repo.insert()
ezra
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: matz.id})
|> Repo.insert()
matz
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: me.id})
|> Repo.insert()
matz
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: ezra.id})
|> Repo.insert()
matz
|> Ecto.build_assoc(:friendships)
|> Friendship.changeset(%{friend_id: dhh.id})
|> Repo.insert()
:ok
end
def reset do
Friendship
|> Repo.delete_all()
Person
|> Repo.delete_all()
end
end
| 19.320388 | 50 | 0.567337 |
03c67f5e7068dd81a85a26ce69a9f126d29a2b55 | 3,339 | exs | Elixir | test/components/icon_test.exs | habitus-incorporated/ex_fontawesome | 6a691677bf484a2ce81bae871880db417acd501a | [
"MIT"
] | null | null | null | test/components/icon_test.exs | habitus-incorporated/ex_fontawesome | 6a691677bf484a2ce81bae871880db417acd501a | [
"MIT"
] | null | null | null | test/components/icon_test.exs | habitus-incorporated/ex_fontawesome | 6a691677bf484a2ce81bae871880db417acd501a | [
"MIT"
] | null | null | null | defmodule FontAwesome.Components.IconTest do
use FontAwesome.ConnCase, async: true
alias FontAwesome.Components.Icon
defmodule ViewWithIcon do
use Surface.LiveView
data aria_hidden, :boolean, default: false
def handle_event("toggle_aria_hidden", _, socket) do
{:noreply, assign(socket, :aria_hidden, !socket.assigns.aria_hidden)}
end
def render(assigns) do
~F"""
<Icon name="address-book" type="regular" opts={aria_hidden: @aria_hidden} />
"""
end
end
test "renders icon" do
html =
render_surface do
~F"""
<Icon name="address-book" type="regular" />
"""
end
assert html =~ "<svg"
end
test "renders icon with class" do
html =
render_surface do
~F"""
<Icon name="address-book" type="regular" class="h-4 w-4" />
"""
end
assert html =~ ~s(<svg class="h-4 w-4")
end
test "renders icon with opts" do
html =
render_surface do
~F"""
<Icon name="address-book" type="regular" opts={aria_hidden: true} />
"""
end
assert html =~ ~s(<svg aria-hidden="true")
end
test "class prop overrides opts prop" do
html =
render_surface do
~F"""
<Icon name="address-book" type="regular" class="hello" opts={class: "world"} />
"""
end
assert html =~ ~s(<svg class="hello")
end
test "raises if icon name does not exist" do
msg = ~s(icon "hello" with type "regular" does not exist.)
assert_raise ArgumentError, msg, fn ->
render_surface do
~F"""
<Icon name="hello" type="regular" />
"""
end
end
end
test "raises if type is missing" do
msg = ~s(type prop is required if default type is not configured.)
assert_raise ArgumentError, msg, fn ->
render_surface do
~F"""
<Icon name="hello" />
"""
end
end
end
test "raises if icon type does not exist" do
msg = ~s(expected type to be one of #{inspect(FontAwesome.types())}, got: "world")
assert_raise ArgumentError, msg, fn ->
render_surface do
~F"""
<Icon name="address-book" type="world" />
"""
end
end
end
test "updates when opts change", %{conn: conn} do
{:ok, view, html} = live_isolated(conn, ViewWithIcon)
assert html =~ ~s(<svg aria-hidden="false")
assert render_click(view, :toggle_aria_hidden) =~
~s(<svg aria-hidden="true")
assert render_click(view, :toggle_aria_hidden) =~
~s(<svg aria-hidden="false")
end
end
defmodule FontAwesome.Components.IconConfigTest do
use FontAwesome.ConnCase
alias FontAwesome.Components.Icon
test "renders icon with default type" do
Application.put_env(:ex_fontawesome, :type, "regular")
html =
render_surface do
~F"""
<Icon name="address-book" />
"""
end
assert html =~ "<svg"
end
test "raises if default icon type does not exist" do
Application.put_env(:ex_fontawesome, :type, "world")
msg = ~s(expected default type to be one of #{inspect(FontAwesome.types())}, got: "world")
assert_raise ArgumentError, msg, fn ->
render_surface do
~F"""
<Icon name="address-book" />
"""
end
end
end
end
| 22.714286 | 94 | 0.592692 |
03c6b5b32b1881609ca70e9e1d7a03c9e395049e | 909 | exs | Elixir | apps/dummy_nerves/mix.exs | CultivateHQ/cultivatarmobile | 09148467d8569138e9b692a7b726b7090b2af5d6 | [
"MIT"
] | 16 | 2016-09-14T16:57:33.000Z | 2017-11-11T16:31:14.000Z | apps/dummy_nerves/mix.exs | CultivateHQ/cultivatarmobile | 09148467d8569138e9b692a7b726b7090b2af5d6 | [
"MIT"
] | 5 | 2016-09-08T07:14:44.000Z | 2018-11-09T12:34:19.000Z | apps/dummy_nerves/mix.exs | CultivateHQ/cultivatarmobile | 09148467d8569138e9b692a7b726b7090b2af5d6 | [
"MIT"
] | null | null | null | defmodule DummyNerves.Mixfile do
use Mix.Project
def project do
[app: :dummy_nerves,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# To depend on another app inside the umbrella:
#
# {:myapp, in_umbrella: true}
#
# Type "mix help deps" for more examples and options
defp deps do
[]
end
end
| 22.170732 | 77 | 0.59626 |
03c7049eae39cfa5cd950e082d755018ecd308d7 | 5,559 | ex | Elixir | lib/phoenix/router/scope.ex | tgxworld/phoenix | 89b885591431170de73e372d9544d841bedca3db | [
"MIT"
] | 2 | 2020-07-24T08:34:36.000Z | 2021-02-08T03:21:49.000Z | lib/phoenix/router/scope.ex | tgxworld/phoenix | 89b885591431170de73e372d9544d841bedca3db | [
"MIT"
] | null | null | null | lib/phoenix/router/scope.ex | tgxworld/phoenix | 89b885591431170de73e372d9544d841bedca3db | [
"MIT"
] | null | null | null | defmodule Phoenix.Router.Scope do
alias Phoenix.Router.{Scope, Route}
@moduledoc false
@stack :phoenix_router_scopes
@pipes :phoenix_pipeline_scopes
@top :phoenix_top_scopes
defstruct path: [], alias: [], as: [], pipes: [], host: nil, private: %{}, assigns: %{}
@doc """
Initializes the scope.
"""
def init(module) do
Module.put_attribute(module, @stack, [])
Module.put_attribute(module, @top, %Scope{})
Module.put_attribute(module, @pipes, MapSet.new)
end
@doc """
Builds a route based on the top of the stack.
"""
def route(line, module, kind, verb, path, plug, plug_opts, opts) do
path = validate_path(path)
private = Keyword.get(opts, :private, %{})
assigns = Keyword.get(opts, :assigns, %{})
as = Keyword.get(opts, :as, Phoenix.Naming.resource_name(plug, "Controller"))
alias? = Keyword.get(opts, :alias, true)
if to_string(as) == "static" do
raise ArgumentError, "`static` is a reserved route prefix generated from #{inspect plug} or `:as` option"
end
{path, host, alias, as, pipes, private, assigns} =
join(module, path, plug, alias?, as, private, assigns)
Phoenix.Router.Route.build(line, kind, verb, path, host, alias, plug_opts, as, pipes, private, assigns)
end
@doc """
Validates a path is a string and contains a leading prefix.
"""
def validate_path("/" <> _ = path), do: path
def validate_path(path) when is_binary(path) do
IO.warn """
router paths should begin with a forward slash, got: #{inspect path}
#{Exception.format_stacktrace}
"""
"/" <> path
end
def validate_path(path) do
raise ArgumentError, "router paths must be strings, got: #{inspect path}"
end
@doc """
Defines the given pipeline.
"""
def pipeline(module, pipe) when is_atom(pipe) do
update_pipes module, &MapSet.put(&1, pipe)
end
@doc """
Appends the given pipes to the current scope pipe through.
"""
def pipe_through(module, new_pipes) do
new_pipes = List.wrap(new_pipes)
%{pipes: pipes} = top = get_top(module)
if pipe = Enum.find(new_pipes, & &1 in pipes) do
raise ArgumentError,
"duplicate pipe_through for #{inspect pipe}. " <>
"A plug may only be used once inside a scoped pipe_through"
end
put_top(module, %{top | pipes: pipes ++ new_pipes})
end
@doc """
Pushes a scope into the module stack.
"""
def push(module, path) when is_binary(path) do
push(module, path: path)
end
def push(module, opts) when is_list(opts) do
path =
if path = Keyword.get(opts, :path) do
path |> validate_path() |> String.split("/", trim: true)
else
[]
end
alias = Keyword.get(opts, :alias) |> List.wrap() |> Enum.map(&Atom.to_string/1)
as = Keyword.get(opts, :as) |> List.wrap()
host = Keyword.get(opts, :host)
private = Keyword.get(opts, :private, %{})
assigns = Keyword.get(opts, :assigns, %{})
top = get_top(module)
update_stack(module, fn stack -> [top | stack] end)
put_top(module, %Scope{
path: top.path ++ path,
alias: top.alias ++ alias,
as: top.as ++ as,
host: host || top.host,
pipes: top.pipes,
private: Map.merge(top.private, private),
assigns: Map.merge(top.assigns, assigns)
})
end
@doc """
Pops a scope from the module stack.
"""
def pop(module) do
update_stack(module, fn [top | stack] ->
put_top(module, top)
stack
end)
end
@doc """
Add a forward to the router.
"""
def register_forwards(module, path, plug) when is_atom(plug) do
plug = expand_alias(module, plug)
phoenix_forwards = Module.get_attribute(module, :phoenix_forwards)
path_segments = Route.forward_path_segments(path, plug, phoenix_forwards)
phoenix_forwards = Map.put(phoenix_forwards, plug, path_segments)
Module.put_attribute(module, :phoenix_forwards, phoenix_forwards)
plug
end
def register_forwards(_, _, plug) do
raise ArgumentError, "forward expects a module as the second argument, #{inspect plug} given"
end
@doc """
Expands the alias in the current router scope.
"""
def expand_alias(module, alias) do
join_alias(get_top(module), alias)
end
defp join(module, path, alias, alias?, as, private, assigns) do
top = get_top(module)
joined_alias =
if alias? do
join_alias(top, alias)
else
alias
end
{join_path(top, path), top.host, joined_alias, join_as(top, as), top.pipes,
Map.merge(top.private, private), Map.merge(top.assigns, assigns)}
end
defp join_path(top, path) do
"/" <> Enum.join(top.path ++ String.split(path, "/", trim: true), "/")
end
defp join_alias(top, alias) when is_atom(alias) do
Module.concat(top.alias ++ [alias])
end
defp join_as(_top, nil), do: nil
defp join_as(top, as) when is_atom(as) or is_binary(as), do: Enum.join(top.as ++ [as], "_")
defp get_top(module) do
get_attribute(module, @top)
end
defp update_stack(module, fun) do
update_attribute(module, @stack, fun)
end
defp update_pipes(module, fun) do
update_attribute(module, @pipes, fun)
end
defp put_top(module, value) do
Module.put_attribute(module, @top, value)
value
end
defp get_attribute(module, attr) do
Module.get_attribute(module, attr) ||
raise "Phoenix router scope was not initialized"
end
defp update_attribute(module, attr, fun) do
Module.put_attribute(module, attr, fun.(get_attribute(module, attr)))
end
end
| 28.362245 | 111 | 0.649038 |
03c70d2e72122b651ba9b8c6040bd59933fe99e7 | 64 | ex | Elixir | web/views/reflection_view.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | 48 | 2015-06-29T21:20:25.000Z | 2021-05-09T04:27:41.000Z | web/views/reflection_view.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | null | null | null | web/views/reflection_view.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | 15 | 2015-06-29T21:13:57.000Z | 2021-07-27T10:02:40.000Z | defmodule Survey.ReflectionView do
use Survey.Web, :view
end
| 12.8 | 34 | 0.78125 |
03c7420ff00d53925710af3d46d587029bf0e8dc | 4,688 | ex | Elixir | lib/twittertex.ex | tomtaylor/twittertex | 228a245a01f4770c33971c99817bcfed7ab5c6ad | [
"MIT"
] | 3 | 2016-03-26T14:42:23.000Z | 2022-03-01T19:02:42.000Z | lib/twittertex.ex | tomtaylor/twittertex | 228a245a01f4770c33971c99817bcfed7ab5c6ad | [
"MIT"
] | null | null | null | lib/twittertex.ex | tomtaylor/twittertex | 228a245a01f4770c33971c99817bcfed7ab5c6ad | [
"MIT"
] | null | null | null | defmodule Twittertex do
@moduledoc """
Twittertex formats the raw JSON of a tweet into HTML by reconstructing pretty
links and so on from the entities embedded.
"""
import Phoenix.HTML
import Phoenix.HTML.Link
@type opt :: {:link_opts, Keyword.t()}
@type opts :: [opt()]
@doc """
Formats a tweet (classic or extended) into HTML.
Returns a String of HTML.
"""
@spec format_tweet(%{}) :: String.t()
@spec format_tweet(%{}, opts()) :: String.t()
def format_tweet(tweet, opts \\ []) do
case tweet["text"] do
nil -> format_extended_tweet(tweet, opts)
_ -> format_classic_tweet(tweet, opts)
end
end
@doc """
Formats a classic (non-extended) tweet into HTML.
Returns a String of HTML.
"""
@spec format_classic_tweet(%{}) :: String.t()
@spec format_classic_tweet(%{}, opts()) :: String.t()
def format_classic_tweet(tweet, opts \\ []) do
text = tweet["text"]
format_tweet(tweet, text, opts)
end
@doc """
Formats an extended tweet into HTML.
Returns a String of HTML.
"""
@spec format_extended_tweet(%{}, opts()) :: String.t()
def format_extended_tweet(tweet, opts \\ []) do
text = tweet["full_text"]
format_tweet(tweet, text, opts)
end
defp format_tweet(tweet, text, opts) do
typed_entities = type_entities(tweet["entities"])
format_entities(text, typed_entities, opts) |> format_linebreaks()
end
defp format_linebreaks(text) do
text |> String.replace("\n", "<br />")
end
defp format_entities(text, [], _opts) do
text
end
defp format_entities(text, [{type, entity} | entities], opts) do
{text, position, offset} =
case type do
"urls" -> format_url_entity(text, entity, opts)
"user_mentions" -> format_user_mention(text, entity, opts)
"media" -> format_media_entity(text, entity, opts)
"hashtags" -> format_hashtag(text, entity, opts)
_ -> {text, 0, 0}
end
entities = adjust_indices(entities, position, offset)
format_entities(text, entities, opts)
end
defp format_user_mention(text, entity, opts) do
{start, finish} = extract_indices(entity)
username = Map.fetch!(entity, "screen_name")
link_opts = build_link_opts(opts, "https://twitter.com/#{username}")
l = link("@#{username}", link_opts) |> safe_to_string()
splice(text, start, finish, l)
end
defp format_hashtag(text, entity, opts) do
{start, finish} = extract_indices(entity)
hashtag = extract_hashtag(entity)
link_opts = build_link_opts(opts, "https://twitter.com/hashtag/#{hashtag}")
l = link("##{hashtag}", link_opts) |> safe_to_string()
splice(text, start, finish, l)
end
defp format_url_entity(text, entity, opts) do
{start, finish} = extract_indices(entity)
display_url = Map.fetch!(entity, "display_url")
expanded_url = Map.fetch!(entity, "expanded_url")
link_opts = build_link_opts(opts, expanded_url)
l = link(display_url, link_opts) |> safe_to_string()
splice(text, start, finish, l)
end
defp format_media_entity(text, entity, opts) do
format_url_entity(text, entity, opts)
end
defp splice(text, start, finish, new_text) do
length = finish - start
# For some reason Twitter actually uses codepoint indexes for indices, not
# graphemes.
codepoints = String.codepoints(text)
{remaining, suffix} = Enum.split(codepoints, finish)
{prefix, _} = Enum.split(remaining, start)
text = Enum.join(prefix ++ String.codepoints(new_text) ++ suffix)
offset = String.length(new_text) - length
{text, start, offset}
end
defp extract_indices(%{"indices" => [start, finish]}), do: {start, finish}
defp extract_indices(%{"start" => start, "end" => finish}), do: {start, finish}
defp extract_indices(_entity), do: nil
defp extract_hashtag(%{"text" => text}), do: text
defp extract_hashtag(%{"tag" => tag}), do: tag
defp extract_hashtag(_entity), do: throw(ArgumentError)
defp adjust_indices(entities, position, offset) do
Enum.map(entities, fn {type, entity} ->
entity =
case extract_indices(entity) do
nil ->
entity
{start, finish} ->
if start > position do
Map.put(entity, "indices", [start + offset, finish + offset])
else
entity
end
end
{type, entity}
end)
end
defp type_entities(entities) do
keys = Map.keys(entities)
Enum.flat_map(keys, fn k ->
Map.fetch!(entities, k) |> Enum.map(fn e -> {k, e} end)
end)
end
defp build_link_opts(opts, to) do
opts
|> Keyword.get(:link_opts, [])
|> Keyword.put(:to, to)
end
end
| 28.760736 | 81 | 0.645051 |
03c74363c3989e1e55e5bc75b96b0b2bfd2b2705 | 2,289 | ex | Elixir | clients/translate/lib/google_api/translate/v3/model/batch_document_input_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/translate/lib/google_api/translate/v3/model/batch_document_input_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/translate/lib/google_api/translate/v3/model/batch_document_input_config.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Translate.V3.Model.BatchDocumentInputConfig do
@moduledoc """
Input configuration for BatchTranslateDocument request.
## Attributes
* `gcsSource` (*type:* `GoogleApi.Translate.V3.Model.GcsSource.t`, *default:* `nil`) - Google Cloud Storage location for the source input. This can be a single file (for example, `gs://translation-test/input.docx`) or a wildcard (for example, `gs://translation-test/*`). File mime type is determined based on extension. Supported mime type includes: - `pdf`, application/pdf - `docx`, application/vnd.openxmlformats-officedocument.wordprocessingml.document - `pptx`, application/vnd.openxmlformats-officedocument.presentationml.presentation - `xlsx`, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet The max file size to support for `.docx`, `.pptx` and `.xlsx` is 100MB. The max file size to support for `.pdf` is 1GB and the max page limit is 1000 pages. The max file size to support for all input documents is 1GB.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:gcsSource => GoogleApi.Translate.V3.Model.GcsSource.t() | nil
}
field(:gcsSource, as: GoogleApi.Translate.V3.Model.GcsSource)
end
defimpl Poison.Decoder, for: GoogleApi.Translate.V3.Model.BatchDocumentInputConfig do
def decode(value, options) do
GoogleApi.Translate.V3.Model.BatchDocumentInputConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Translate.V3.Model.BatchDocumentInputConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 48.702128 | 838 | 0.761468 |
03c7486c2afa203ab4693bd17e01c8b58b1859e4 | 70 | ex | Elixir | lib/fireball/models/score.ex | Catharz/fireball | bb9f123c0d2d71b16eda01d3838565e6e762de20 | [
"MIT"
] | null | null | null | lib/fireball/models/score.ex | Catharz/fireball | bb9f123c0d2d71b16eda01d3838565e6e762de20 | [
"MIT"
] | null | null | null | lib/fireball/models/score.ex | Catharz/fireball | bb9f123c0d2d71b16eda01d3838565e6e762de20 | [
"MIT"
] | null | null | null | defmodule Score do
defstruct [:player, :kills, :deaths, :money]
end
| 17.5 | 46 | 0.714286 |
03c756324efd1befa63c6a5761dc1ef69a21aada | 1,572 | ex | Elixir | test/support/test_support.ex | Arti4ever/farmbot_os | a238c1d5ae78c08d1f5894cac41ed61035fb3266 | [
"MIT"
] | null | null | null | test/support/test_support.ex | Arti4ever/farmbot_os | a238c1d5ae78c08d1f5894cac41ed61035fb3266 | [
"MIT"
] | null | null | null | test/support/test_support.ex | Arti4ever/farmbot_os | a238c1d5ae78c08d1f5894cac41ed61035fb3266 | [
"MIT"
] | null | null | null | defmodule Helpers do
alias FarmbotCore.Asset.{Repo, Point}
@wait_time 180
# Base case: We have a pid
def wait_for(pid) when is_pid(pid), do: check_on_mbox(pid)
# Failure case: We failed to find a pid for a module.
def wait_for(nil), do: raise("Attempted to wait on bad module/pid")
# Edge case: We have a module and need to try finding its pid.
def wait_for(mod), do: wait_for(Process.whereis(mod))
# Enter recursive loop
defp check_on_mbox(pid) do
Process.sleep(@wait_time)
wait(pid, Process.info(pid, :message_queue_len))
end
# Exit recursive loop (mbox is clear)
defp wait(_, {:message_queue_len, 0}), do: Process.sleep(@wait_time * 3)
# Exit recursive loop (pid is dead)
defp wait(_, nil), do: Process.sleep(@wait_time * 3)
# Continue recursive loop
defp wait(pid, {:message_queue_len, _n}), do: check_on_mbox(pid)
defmacro expect_log(message) do
quote do
expect(FarmbotCore.LogExecutor, :execute, fn log ->
assert log.message == unquote(message)
end)
end
end
def delete_all_points(), do: Repo.delete_all(Point)
def create_point(%{id: id} = params) do
%Point{
id: id,
name: "point #{id}",
meta: %{},
plant_stage: "planted",
created_at: ~U[2222-12-10 02:22:22.222222Z],
pointer_type: "Plant",
pullout_direction: 2,
radius: 10.0,
tool_id: nil,
discarded_at: nil,
gantry_mounted: false,
x: 0.0,
y: 0.0,
z: 0.0
}
|> Map.merge(params)
|> Point.changeset()
|> Repo.insert!()
end
end
| 27.103448 | 74 | 0.640585 |
03c756e84c570187c0871f5fbdc926956e6b27c3 | 9,318 | exs | Elixir | lib/iex/test/iex/autocomplete_test.exs | xtian/elixir | c680eb1a3992309c272e8f808e15990ea5318d6e | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/autocomplete_test.exs | xtian/elixir | c680eb1a3992309c272e8f808e15990ea5318d6e | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/autocomplete_test.exs | xtian/elixir | c680eb1a3992309c272e8f808e15990ea5318d6e | [
"Apache-2.0"
] | null | null | null | Code.require_file "../test_helper.exs", __DIR__
defmodule IEx.AutocompleteTest do
use ExUnit.Case, async: true
setup do
evaluator = IEx.Server.start_evaluator([])
Process.put(:evaluator, evaluator)
:ok
end
defmodule MyServer do
def evaluator do
Process.get(:evaluator)
end
end
defp eval(line) do
ExUnit.CaptureIO.capture_io(fn ->
evaluator = MyServer.evaluator
Process.group_leader(evaluator, Process.group_leader)
send evaluator, {:eval, self(), line <> "\n", %IEx.State{}}
assert_receive {:evaled, _, _}
end)
end
defp expand(expr) do
IEx.Autocomplete.expand(Enum.reverse(expr), MyServer)
end
test "Erlang module completion" do
assert expand(':zl') == {:yes, 'ib', []}
end
test "Erlang module no completion" do
assert expand(':unknown') == {:no, '', []}
assert expand('Enum:') == {:no, '', []}
end
test "Erlang module multiple values completion" do
{:yes, '', list} = expand(':user')
assert 'user' in list
assert 'user_drv' in list
end
test "Erlang root completion" do
{:yes, '', list} = expand(':')
assert is_list(list)
assert 'lists' in list
end
test "Elixir proxy" do
{:yes, '', list} = expand('E')
assert 'Elixir' in list
end
test "Elixir completion" do
assert expand('En') == {:yes, 'um', []}
assert expand('Enumera') == {:yes, 'ble', []}
end
test "Elixir completion with self" do
assert expand('Enumerable') == {:yes, '.', []}
end
test "Elixir completion on modules from load path" do
assert expand('Str') == {:yes, [], ['Stream', 'String', 'StringIO']}
assert expand('Ma') == {:yes, '', ['Macro', 'Map', 'MapSet', 'MatchError']}
assert expand('Dic') == {:yes, 't', []}
assert expand('Ex') == {:yes, [], ['ExUnit', 'Exception']}
end
test "Elixir no completion for underscored functions with no doc" do
{:module, _, bytecode, _} =
defmodule Elixir.Sample do
def __foo__(), do: 0
@doc "Bar doc"
def __bar__(), do: 1
end
File.write!("Elixir.Sample.beam", bytecode)
assert Code.get_docs(Sample, :docs)
assert expand('Sample._') == {:yes, '_bar__', []}
after
File.rm("Elixir.Sample.beam")
:code.purge(Sample)
:code.delete(Sample)
end
test "Elixir no completion" do
assert expand('.') == {:no, '', []}
assert expand('Xyz') == {:no, '', []}
assert expand('x.Foo') == {:no, '', []}
end
test "Elixir root submodule completion" do
assert expand('Elixir.Acce') == {:yes, 'ss', []}
end
test "Elixir submodule completion" do
assert expand('String.Cha') == {:yes, 'rs', []}
end
test "Elixir submodule no completion" do
assert expand('IEx.Xyz') == {:no, '', []}
end
test "function completion" do
assert expand('System.ve') == {:yes, 'rsion', []}
assert expand(':ets.fun2') == {:yes, 'ms', []}
end
test "function completion with arity" do
assert expand('String.printable?') == {:yes, '', ['printable?/1']}
assert expand('String.printable?/') == {:yes, '', ['printable?/1']}
end
test "function completion using a variable bound to a module" do
eval("mod = String")
assert expand('mod.print') == {:yes, 'able?', []}
end
test "map atom key completion is supported" do
eval("map = %{foo: 1, bar_1: 23, bar_2: 14}")
assert expand('map.f') == {:yes, 'oo', []}
assert expand('map.b') == {:yes, 'ar_', []}
assert expand('map.bar_') == {:yes, '', ['bar_1', 'bar_2']}
assert expand('map.c') == {:no, '', []}
assert expand('map.') == {:yes, '', ['bar_1', 'bar_2', 'foo']}
assert expand('map.foo') == {:no, '', []}
end
test "nested map atom key completion is supported" do
eval("map = %{nested: %{deeply: %{foo: 1, bar_1: 23, bar_2: 14, mod: String, num: 1}}}")
assert expand('map.nested.deeply.f') == {:yes, 'oo', []}
assert expand('map.nested.deeply.b') == {:yes, 'ar_', []}
assert expand('map.nested.deeply.bar_') == {:yes, '', ['bar_1', 'bar_2']}
assert expand('map.nested.deeply.') == {:yes, '', ['bar_1', 'bar_2', 'foo', 'mod', 'num']}
assert expand('map.nested.deeply.mod.print') == {:yes, 'able?', []}
assert expand('map.nested') == {:yes, '.', []}
assert expand('map.nested.deeply') == {:yes, '.', []}
assert expand('map.nested.deeply.foo') == {:no, '', []}
assert expand('map.nested.deeply.c') == {:no, '', []}
assert expand('map.a.b.c.f') == {:no, '', []}
end
test "map string key completion is not supported" do
eval(~S(map = %{"foo" => 1}))
assert expand('map.f') == {:no, '', []}
end
test "autocompletion off a bound variable only works for modules and maps" do
eval("num = 5; map = %{nested: %{num: 23}}")
assert expand('num.print') == {:no, '', []}
assert expand('map.nested.num.f') == {:no, '', []}
assert expand('map.nested.num.key.f') == {:no, '', []}
end
test "autocompletion using access syntax does is not supported" do
eval("map = %{nested: %{deeply: %{num: 23}}}")
assert expand('map[:nested][:deeply].n') == {:no, '', []}
assert expand('map[:nested].deeply.n') == {:no, '', []}
assert expand('map.nested.[:deeply].n') == {:no, '', []}
end
test "autocompletion off of unbound variables is not supported" do
eval("num = 5")
assert expand('other_var.f') == {:no, '', []}
assert expand('a.b.c.d') == {:no, '', []}
end
test "macro completion" do
{:yes, '', list} = expand('Kernel.is_')
assert is_list(list)
end
test "imports completion" do
{:yes, '', list} = expand('')
assert is_list(list)
assert 'h/1' in list
assert 'unquote/1' in list
assert 'pwd/0' in list
end
test "kernel import completion" do
assert expand('defstru') == {:yes, 'ct', []}
assert expand('put_') == {:yes, '', ['put_elem/3', 'put_in/2', 'put_in/3']}
end
test "variable name completion" do
eval("numeral = 3; number = 3; nothing = nil")
assert expand('numb') == {:yes, 'er', []}
assert expand('num') == {:yes, '', ['number', 'numeral']}
assert expand('no') == {:yes, '', ['nothing', 'node/0', 'node/1', 'not/1']}
end
test "completion of manually imported functions and macros" do
eval("import Enum; import Supervisor, only: [count_children: 1]; import Protocol")
assert expand('take') == {:yes, '', ['take/2', 'take_every/2', 'take_random/2', 'take_while/2']}
assert expand('count') == {:yes, '', ['count/1', 'count/2', 'count_children/1']}
assert expand('der') == {:yes, 'ive', []}
end
defmacro define_var do
quote do: var!(my_var_1, Elixir) = 1
end
test "ignores quoted variables when performing variable completion" do
eval("require #{__MODULE__}; #{__MODULE__}.define_var(); my_var_2 = 2")
assert expand('my_var') == {:yes, '_2', []}
end
test "kernel special form completion" do
assert expand('unquote_spl') == {:yes, 'icing', []}
end
test "completion inside expression" do
assert expand('1 En') == {:yes, 'um', []}
assert expand('Test(En') == {:yes, 'um', []}
assert expand('Test :zl') == {:yes, 'ib', []}
assert expand('[:zl') == {:yes, 'ib', []}
assert expand('{:zl') == {:yes, 'ib', []}
end
test "ampersand completion" do
assert expand('&Enu') == {:yes, 'm', []}
assert expand('&Enum.a') == {:yes, [], ['all?/1', 'all?/2', 'any?/1', 'any?/2', 'at/2', 'at/3']}
assert expand('f = &Enum.a') == {:yes, [], ['all?/1', 'all?/2', 'any?/1', 'any?/2', 'at/2', 'at/3']}
end
defmodule SublevelTest.LevelA.LevelB do
end
test "Elixir completion sublevel" do
assert expand('IEx.AutocompleteTest.SublevelTest.') == {:yes, 'LevelA', []}
end
test "complete aliases of Elixir modules" do
eval("alias List, as: MyList")
assert expand('MyL') == {:yes, 'ist', []}
assert expand('MyList') == {:yes, '.', []}
assert expand('MyList.to_integer') == {:yes, [], ['to_integer/1', 'to_integer/2']}
end
test "complete aliases of Erlang modules" do
eval("alias :lists, as: EList")
assert expand('EL') == {:yes, 'ist', []}
assert expand('EList') == {:yes, '.', []}
assert expand('EList.map') == {:yes, [], ['map/2', 'mapfoldl/3', 'mapfoldr/3']}
end
test "completion for functions added when compiled module is reloaded" do
{:module, _, bytecode, _} =
defmodule Sample do
def foo(), do: 0
end
File.write!("Elixir.IEx.AutocompleteTest.Sample.beam", bytecode)
assert Code.get_docs(Sample, :docs)
assert expand('IEx.AutocompleteTest.Sample.foo') == {:yes, '', ['foo/0']}
Code.compiler_options(ignore_module_conflict: true)
defmodule Sample do
def foo(), do: 0
def foobar(), do: 0
end
assert expand('IEx.AutocompleteTest.Sample.foo') == {:yes, '', ['foo/0', 'foobar/0']}
after
File.rm("Elixir.IEx.AutocompleteTest.Sample.beam")
Code.compiler_options(ignore_module_conflict: false)
:code.purge(Sample)
:code.delete(Sample)
end
defmodule MyStruct do
defstruct [:my_val]
end
test "completion for struct names" do
assert expand('%IEx.AutocompleteTest.MyStr') == {:yes, 'uct', []}
end
test "completion for struct keys" do
eval("struct = %IEx.AutocompleteTest.MyStruct{}")
assert expand('struct.my') == {:yes, '_val', []}
end
end
| 32.354167 | 104 | 0.581992 |
03c7652bc0b00d37925c7fc68b5b92dc06b9b7d1 | 15,296 | exs | Elixir | test/webdriver/protocol_test.exs | bosko/elixir-webdriver | e7037312decab6646b2107b7345f2974b24a9d15 | [
"MIT"
] | 104 | 2015-02-11T02:57:53.000Z | 2022-01-12T14:28:12.000Z | test/webdriver/protocol_test.exs | bosko/elixir-webdriver | e7037312decab6646b2107b7345f2974b24a9d15 | [
"MIT"
] | 3 | 2015-07-23T18:48:11.000Z | 2016-10-12T14:28:43.000Z | test/webdriver/protocol_test.exs | bosko/elixir-webdriver | e7037312decab6646b2107b7345f2974b24a9d15 | [
"MIT"
] | 28 | 2015-01-09T22:05:27.000Z | 2021-04-29T13:55:13.000Z | Code.require_file "../test_helper.exs", __DIR__
defmodule WebDriverProtocolTest do
use ExUnit.Case, async: true
use Jazz
import Mock
alias WebDriver.Protocol
@config "http://127.0.0.1:8080"
@session_id ":session_id"
test "status" do
test_get &Protocol.status/1, "/status"
end
test "start_session" do
test_post &Protocol.start_session(&1,%{desiredCapabilities: []}), "/session", "{\"desiredCapabilities\":[]}"
end
test "sessions" do
test_get &Protocol.sessions/1, "/sessions"
end
test "session" do
test_get &Protocol.session(&1, @session_id), "/session/:session_id"
end
test "stop_session" do
test_delete &Protocol.stop_session(&1, @session_id), "/session/:session_id"
end
test "set_timeout" do
test_post &Protocol.set_timeout(&1, @session_id, %{type: "script", ms: 1000}),
"/session/:session_id/timeouts", "{\"type\":\"script\",\"ms\":1000}"
end
test "set_async_script_timeout" do
test_post &Protocol.set_async_script_timeout(&1, @session_id, %{ms: 1000}),
"/session/:session_id/timeouts/async_script",
"{\"ms\":1000}"
end
test "set_implicit_wait_timeout" do
test_post &Protocol.set_implicit_wait_timeout(&1, @session_id, %{ms: 1000}),
"/session/:session_id/timeouts/implicit_wait","{\"ms\":1000}"
end
test "window_handle" do
test_get &Protocol.window_handle(&1, @session_id), "/session/:session_id/window_handle"
end
test "window_handles" do
test_get &Protocol.window_handles(&1, @session_id), "/session/:session_id/window_handles"
end
test "url/3" do
test_post &Protocol.url(&1, @session_id, %{url: "http://google.com"}),
"/session/:session_id/url", "{\"url\":\"http://google.com\"}"
end
test "url/2" do
test_get &Protocol.url(&1, @session_id), "/session/:session_id/url"
end
test "forward" do
test_post &Protocol.forward(&1, @session_id), "/session/:session_id/forward", "{}"
end
test "back" do
test_post &Protocol.back(&1, @session_id), "/session/:session_id/back", "{}"
end
test "refresh" do
test_post &Protocol.refresh(&1, @session_id), "/session/:session_id/refresh", "{}"
end
test "execute" do
test_post &Protocol.execute(&1, @session_id, %{script: "alert('Hello world!')", args: []}),
"/session/:session_id/execute", "{\"script\":\"alert('Hello world!')\",\"args\":[]}"
end
test "execute_async" do
test_post &Protocol.execute_async(&1, @session_id, %{script: "alert('Hello world!')", args: []}),
"/session/:session_id/execute_async","{\"script\":\"alert('Hello world!')\",\"args\":[]}"
end
test "screenshot" do
test_get &Protocol.screenshot(&1, @session_id), "/session/:session_id/screenshot"
end
test "frame" do
test_post &Protocol.frame(&1, @session_id, %{id: "frame"}),
"/session/:session_id/frame","{\"id\":\"frame\"}"
end
test "window" do
test_post &Protocol.window(&1, @session_id, %{name: "window"}),
"/session/:session_id/window", "{\"name\":\"window\"}"
end
test "close_window" do
test_delete &Protocol.close_window(&1, @session_id), "/session/:session_id/window"
end
test "window_size/2" do
test_get &Protocol.window_size(&1, @session_id), "/session/:session_id/window/current/size"
end
test "window_size/3" do
test_get &Protocol.window_size(&1, @session_id, "window_handle"),
"/session/:session_id/window/window_handle/size"
end
test "window_size/4" do
test_post &Protocol.window_size(&1, @session_id, "window_handle", %{height: 240, width: 320}),
"/session/:session_id/window/window_handle/size", "{\"height\":240,\"width\":320}"
end
test "window_position/2" do
test_get &Protocol.window_position(&1, @session_id),
"/session/:session_id/window/current/position"
end
test "window_position/3" do
test_get &Protocol.window_position(&1, @session_id, "window_handle"),
"/session/:session_id/window/window_handle/position"
end
test "window_position/4" do
test_post &Protocol.window_position(&1, @session_id, "window_handle", %{x: 100, y: 200}),
"/session/:session_id/window/window_handle/position", "{\"x\":100,\"y\":200}"
end
test "maximize_window" do
test_post &Protocol.maximize_window(&1, @session_id, "window_handle"),
"/session/:session_id/window/window_handle/maximize", "{}"
end
test "cookies" do
test_get &Protocol.cookies(&1, @session_id), "/session/:session_id/cookie"
end
test "set_cookie" do
test_post &Protocol.set_cookie(&1, @session_id, %{cookie: %{key: "value"}}),
"/session/:session_id/cookie", "{\"cookie\":{\"key\":\"value\"}}"
end
test "delete cookies" do
test_delete &Protocol.delete_cookies(&1, @session_id), "/session/:session_id/cookie"
end
test "delete cookie" do
test_delete &Protocol.delete_cookie(&1, @session_id, "name"),
"/session/:session_id/cookie/name"
end
test "source" do
test_get &Protocol.source(&1, @session_id), "/session/:session_id/source"
end
test "title" do
test_get &Protocol.title(&1, @session_id), "/session/:session_id/title"
end
test "element/3" do
test_post &Protocol.element(&1, @session_id, %{using: "css selector", value: "special"}),
"/session/:session_id/element", "{\"using\":\"css selector\",\"value\":\"special\"}"
end
test "element/4" do
test_post &Protocol.element(&1, @session_id, ":element_id", %{using: "css selector", value: "special"}),
"/session/:session_id/element/:element_id/element",
"{\"using\":\"css selector\",\"value\":\"special\"}"
end
test "elements/3" do
test_post &Protocol.elements(&1, @session_id, %{using: "css selector", value: "special"}),
"/session/:session_id/elements",
"{\"using\":\"css selector\",\"value\":\"special\"}"
end
test "elements/4" do
test_post &Protocol.elements(&1, @session_id, ":element_id", %{using: "css selector", value: "special"}),
"/session/:session_id/element/:element_id/elements",
"{\"using\":\"css selector\",\"value\":\"special\"}"
end
test "active_element" do
test_get &Protocol.active_element(&1, @session_id), "/session/:session_id/element/active"
end
test "element_by_id" do
test_get &Protocol.element_by_id(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id"
end
test "click" do
test_post &Protocol.click(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/click", "{}"
end
test "submit" do
test_post &Protocol.submit(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/submit", "{}"
end
test "text" do
test_get &Protocol.text(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/text"
end
test "value" do
test_post &Protocol.value(&1, @session_id, ":element_id", %{value: ["a","b","c"]}),
"/session/:session_id/element/:element_id/value",
"{\"value\":[\"a\",\"b\",\"c\"]}"
end
test "keys" do
test_post &Protocol.keys(&1, @session_id, %{value: ["a","b","c"]}),
"/session/:session_id/keys",
"{\"value\":[\"a\",\"b\",\"c\"]}"
end
test "name" do
test_get &Protocol.name(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/name"
end
test "clear" do
test_post &Protocol.clear(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/clear", "{}"
end
test "selected" do
test_get &Protocol.selected(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/selected"
end
test "enabled" do
test_get &Protocol.enabled(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/enabled"
end
test "attribute" do
test_get &Protocol.attribute(&1, @session_id, ":element_id", "attribute_name"),
"/session/:session_id/element/:element_id/attribute/attribute_name"
end
test "equals" do
test_get &Protocol.equals(&1, @session_id, ":element_id", "other_id"),
"/session/:session_id/element/:element_id/equals/other_id"
end
test "displayed" do
test_get &Protocol.displayed(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/displayed"
end
test "location" do
test_get &Protocol.location(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/location"
end
test "location_in_view" do
test_get &Protocol.location_in_view(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/location_in_view"
end
test "size" do
test_get &Protocol.size(&1, @session_id, ":element_id"),
"/session/:session_id/element/:element_id/size"
end
test "css" do
test_get &Protocol.css(&1, @session_id, ":element_id", "property_name"),
"/session/:session_id/element/:element_id/css/property_name"
end
test "orientation/2" do
test_get &Protocol.orientation(&1, @session_id),
"/session/:session_id/orientation"
end
test "orientation/3" do
test_post &Protocol.orientation(&1, @session_id, %{orientation: "LANDSCAPE"}),
"/session/:session_id/orientation",
"{\"orientation\":\"LANDSCAPE\"}"
end
test "alert_text/2" do
test_get &Protocol.alert_text(&1, @session_id),
"/session/:session_id/alert_text"
end
test "alert_text/3" do
test_post &Protocol.alert_text(&1, @session_id, %{text: "Help!"}),
"/session/:session_id/alert_text",
"{\"text\":\"Help!\"}"
end
test "accept_alert" do
test_post &Protocol.accept_alert(&1, @session_id),
"/session/:session_id/accept_alert",
"{}"
end
test "dismiss_alert" do
test_post &Protocol.dismiss_alert(&1, @session_id),
"/session/:session_id/dismiss_alert",
"{}"
end
test "move_to" do
test_post &Protocol.move_to(&1, @session_id, %{element: "element_id", offsetx: 10, offsety: 20}),
"/session/:session_id/moveto",
"{\"element\":\"element_id\",\"offsetx\":10,\"offsety\":20}"
end
test "mouse_click/2" do
test_post &Protocol.mouse_click(&1, @session_id),
"/session/:session_id/click", "{}"
end
test "mouse_click/3" do
test_post &Protocol.mouse_click(&1, @session_id, %{button: 2}),
"/session/:session_id/click", "{\"button\":2}"
end
test "mouse_button_down/2" do
test_post &Protocol.mouse_button_down(&1, @session_id),
"/session/:session_id/buttondown", "{}"
end
test "mouse_button_down/3" do
test_post &Protocol.mouse_button_down(&1, @session_id, %{button: 1}),
"/session/:session_id/buttondown", "{\"button\":1}"
end
test "mouse_button_up/2" do
test_post &Protocol.mouse_button_up(&1, @session_id),
"/session/:session_id/buttonup", "{}"
end
test "mouse_button_up/3" do
test_post &Protocol.mouse_button_up(&1, @session_id, %{button: 1}),
"/session/:session_id/buttonup", "{\"button\":1}"
end
test "mouse_double_click/2" do
test_post &Protocol.mouse_double_click(&1, @session_id),
"/session/:session_id/doubleclick", "{}"
end
test "mouse_double_click/3" do
test_post &Protocol.mouse_double_click(&1, @session_id, %{button: 2}),
"/session/:session_id/doubleclick", "{\"button\":2}"
end
test "touch_click" do
test_post &Protocol.touch_click(&1, @session_id, %{element: "element_id"}),
"/session/:session_id/touch/click", "{\"element\":\"element_id\"}"
end
test "touch_down" do
test_post &Protocol.touch_down(&1, @session_id, %{x: 100, y: 200}),
"/session/:session_id/touch/down",
"{\"x\":100,\"y\":200}"
end
test "touch_up" do
test_post &Protocol.touch_up(&1, @session_id, %{x: 100, y: 200}),
"/session/:session_id/touch/up", "{\"x\":100,\"y\":200}"
end
test "touch_move" do
test_post &Protocol.touch_move(&1, @session_id, %{x: 100, y: 200}),
"/session/:session_id/touch/move", "{\"x\":100,\"y\":200}"
end
test "touch_scroll" do
test_post &Protocol.touch_scroll(&1, @session_id, %{element: "element_id", x: 100, y: 200}),
"/session/:session_id/touch/scroll",
"{\"element\":\"element_id\",\"x\":100,\"y\":200}"
end
test "touch_double_click" do
test_post &Protocol.touch_double_click(&1, @session_id, %{element: "element_id"}),
"/session/:session_id/touch/doubleclick",
"{\"element\":\"element_id\"}"
end
test "touch_long_click" do
test_post &Protocol.touch_long_click(&1, @session_id, %{element: "element_id"}),
"/session/:session_id/touch/longclick",
"{\"element\":\"element_id\"}"
end
test "touch_flick" do
test_post &Protocol.touch_flick(&1, @session_id, %{xSpeed: 10, ySpeed: 0}),
"/session/:session_id/touch/flick", "{\"xSpeed\":10,\"ySpeed\":0}"
end
test "geo_location/2" do
test_get &Protocol.geo_location(&1, @session_id),
"/session/:session_id/location"
end
test "geo_location/3" do
test_post &Protocol.geo_location(&1, @session_id, %{longitude: 23.34, lattitude: 40.3, altitude: 10.3}),
"/session/:session_id/location", "{\"longitude\":23.34,\"lattitude\":40.3,\"altitude\":10.3}"
end
## Test Harness Functions
# Mocks a response to a request.
# The response just echoes the request body.
def test_get command, path do
with_mock HTTPotion, [], [get: fn(url, options) -> get(url, options) end] do
{:ok, _response} = command.("http://127.0.0.1:8080")
assert_get path
end
end
def test_post command, path, options do
with_mock HTTPotion, [], [post: fn(url, options) -> post(url, options) end] do
{:ok, _response} = command.("http://127.0.0.1:8080")
assert_post path, options
end
end
def test_delete command, path do
with_mock HTTPotion, [], [delete: fn(url, options) -> delete(url, options) end] do
{:ok, _response} = command.("http://127.0.0.1:8080")
assert_delete path
end
end
def post(_url, options) do
body = Keyword.get(options, :body)
%HTTPotion.Response{ body: "{\"sessionId\": \"1234\", \"status\": 0, \"value\": #{JSON.encode! body}}",
status_code: 201, headers: []}
end
# Mocks a response to a GET request. Just returns an HTTPotion Response
def get(_url, _options) do
%HTTPotion.Response{ body: "{\"sessionId\": \"1234\", \"status\": 0, \"value\": #{JSON.encode!(%{})}}",
status_code: 200, headers: [] }
end
# Mocks a response to a DELETE request. Just returns an HTTPotion Response
def delete(_url, _options) do
%HTTPotion.Response{ body: "{\"sessionId\": \"1234\", \"status\": 0, \"value\": #{JSON.encode!(%{})}}",
status_code: 204, headers: [] }
end
defp assert_get path do
assert called HTTPotion.get("http://127.0.0.1:8080#{path}", :_)
end
defp assert_post path, body do
# Jazz shuffles map keys around.
b = JSON.decode!(body) |> JSON.encode!
assert called HTTPotion.post("http://127.0.0.1:8080#{path}", :_)
end
defp assert_delete path do
assert called HTTPotion.delete("http://127.0.0.1:8080#{path}", :_)
end
end
| 32.544681 | 112 | 0.640625 |
03c79bc587f08b4416a577448eaf27c748f39c6a | 174 | ex | Elixir | lib/transformer.ex | tarpdalton/consul_config_provider | e54595c2112eb02d7ea8c657d09aef445507fe32 | [
"MIT"
] | 6 | 2019-09-20T06:38:41.000Z | 2021-02-07T03:50:13.000Z | lib/transformer.ex | tarpdalton/consul_config_provider | e54595c2112eb02d7ea8c657d09aef445507fe32 | [
"MIT"
] | 1 | 2020-12-16T19:50:13.000Z | 2021-02-23T17:53:07.000Z | lib/transformer.ex | tarpdalton/consul_config_provider | e54595c2112eb02d7ea8c657d09aef445507fe32 | [
"MIT"
] | 3 | 2020-05-12T20:52:25.000Z | 2021-08-19T18:14:00.000Z | defmodule ConsulConfigProvider.Transformer do
@moduledoc "behaviour for transforming keyword values into any data types"
@callback transform(keyword()) :: keyword()
end
| 29 | 76 | 0.793103 |
03c7a8ac12bf77519af306cf6fbfdf383b3391ac | 1,827 | exs | Elixir | test/correios/cep/client_test.exs | lccezinha/correios-cep-elixir | fee32a9146167c13e169f682ed04837d9e9a525e | [
"Apache-2.0"
] | null | null | null | test/correios/cep/client_test.exs | lccezinha/correios-cep-elixir | fee32a9146167c13e169f682ed04837d9e9a525e | [
"Apache-2.0"
] | null | null | null | test/correios/cep/client_test.exs | lccezinha/correios-cep-elixir | fee32a9146167c13e169f682ed04837d9e9a525e | [
"Apache-2.0"
] | null | null | null | defmodule Correios.CEP.ClientTest do
use ExUnit.Case, async: true
alias Correios.CEP.Client, as: Subject
alias Correios.CEP.Test.Fixture
alias Plug.Conn
setup do
bypass = Bypass.open()
options = [url: "http://localhost:#{bypass.port}/correios/cep"]
{:ok, bypass: bypass, options: options}
end
describe "request/2" do
test "when response is 200 OK, returns OK and response body", %{
bypass: bypass,
options: options
} do
response_body = Fixture.response_body_ok()
assert_conn(bypass, 200, response_body)
assert Subject.request("54250-610", options) == {:ok, response_body}
end
test "when response is not 200 OK, returns error and response body", %{
bypass: bypass,
options: options
} do
response_body = Fixture.response_body_error()
assert_conn(bypass, 500, response_body)
assert Subject.request("54250-610", options) == {:error, response_body}
end
test "when the server is down, returns error and reason", %{
bypass: bypass,
options: options
} do
Bypass.down(bypass)
assert Subject.request("54250-610", options) == {:error, :econnrefused}
end
end
defp assert_conn(bypass, status_code, response_body) do
Bypass.expect_once(bypass, fn conn ->
assert conn.method == "POST"
assert conn.host == "localhost"
assert conn.request_path == "/correios/cep"
[
{"content-type", "text/xml; charset=utf-8"},
{"user-agent", "correios-cep-elixir/#{Mix.Project.config()[:version]}"}
]
|> Enum.each(fn header ->
assert header in conn.req_headers
end)
{:ok, body, _conn} = Conn.read_body(conn)
assert body == Fixture.request_body()
Conn.resp(conn, status_code, response_body)
end)
end
end
| 26.867647 | 79 | 0.642036 |
03c7ad27d3ea109433d36315cc3470255b11e912 | 85 | exs | Elixir | .formatter.exs | blakedietz/courtbot | b18d7eb84fd1405b359c8da980e1175bb1738841 | [
"ISC"
] | 6 | 2018-07-25T18:35:57.000Z | 2018-11-03T17:01:02.000Z | .formatter.exs | blakedietz/courtbot | b18d7eb84fd1405b359c8da980e1175bb1738841 | [
"ISC"
] | 19 | 2018-11-12T05:29:44.000Z | 2020-04-12T01:04:41.000Z | .formatter.exs | blakedietz/courtbot | b18d7eb84fd1405b359c8da980e1175bb1738841 | [
"ISC"
] | 1 | 2020-04-12T00:36:50.000Z | 2020-04-12T00:36:50.000Z | [
inputs: ["config/*.exs", "lib/**/*.{ex,exs}", "test/**/*.{ex,exs}", "mix.exs"]
]
| 21.25 | 80 | 0.447059 |
03c7e67523034f585470c72b90c13bb93c615cda | 1,717 | exs | Elixir | mix.exs | AltCampus/altstatus_backend | 70bf7a9d337e570f54002c3a7df264e88372adfa | [
"MIT"
] | 1 | 2020-01-20T18:17:59.000Z | 2020-01-20T18:17:59.000Z | mix.exs | AltCampus/altstatus_backend | 70bf7a9d337e570f54002c3a7df264e88372adfa | [
"MIT"
] | null | null | null | mix.exs | AltCampus/altstatus_backend | 70bf7a9d337e570f54002c3a7df264e88372adfa | [
"MIT"
] | 2 | 2018-09-09T08:05:24.000Z | 2018-09-09T08:35:18.000Z | defmodule Altstatus.Mixfile do
use Mix.Project
def project do
[
app: :altstatus,
version: "0.0.1",
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
start_permanent: Mix.env == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Altstatus.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.3.3"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:bcrypt_elixir, "~> 1.0"},
{:calendar, "~> 0.17.4"},
{:cors_plug, "~> 1.5"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]
]
end
end
| 26.415385 | 79 | 0.570763 |
03c800c0df8d98deb5bf048fadc081e77a15ffa9 | 31,668 | ex | Elixir | clients/area120_tables/lib/google_api/area120_tables/v1alpha1/api/tables.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/area120_tables/lib/google_api/area120_tables/v1alpha1/api/tables.ex | jamesvl/elixir-google-api | 6c87fb31d996f08fb42ce6066317e9d652a87acc | [
"Apache-2.0"
] | null | null | null | clients/area120_tables/lib/google_api/area120_tables/v1alpha1/api/tables.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.Area120Tables.V1alpha1.Api.Tables do
@moduledoc """
API calls for all endpoints tagged `Tables`.
"""
alias GoogleApi.Area120Tables.V1alpha1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Gets a table. Returns NOT_FOUND if the table does not exist.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The name of the table to retrieve. Format: tables/{table}
* `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.Area120Tables.V1alpha1.Model.Table{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.Table.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_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("/v1alpha1/{+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.Area120Tables.V1alpha1.Model.Table{}])
end
@doc """
Lists tables for the user.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `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").
* `:pageSize` (*type:* `integer()`) - The maximum number of tables to return. The service may return fewer than this value. If unspecified, at most 20 tables are returned. The maximum value is 100; values above 100 are coerced to 100.
* `:pageToken` (*type:* `String.t`) - A page token, received from a previous `ListTables` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListTables` must match the call that provided the page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.ListTablesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.ListTablesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_list(connection, 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,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/tables", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Area120Tables.V1alpha1.Model.ListTablesResponse{}]
)
end
@doc """
Creates multiple rows.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent table where the rows will be created. Format: tables/{table}
* `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.Area120Tables.V1alpha1.Model.BatchCreateRowsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.BatchCreateRowsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_batch_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.BatchCreateRowsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_batch_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,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1alpha1/{+parent}/rows:batchCreate", %{
"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.Area120Tables.V1alpha1.Model.BatchCreateRowsResponse{}]
)
end
@doc """
Deletes multiple rows.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent table shared by all rows being deleted. Format: tables/{table}
* `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.Area120Tables.V1alpha1.Model.BatchDeleteRowsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_batch_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_batch_delete(
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,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1alpha1/{+parent}/rows:batchDelete", %{
"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.Area120Tables.V1alpha1.Model.Empty{}])
end
@doc """
Updates multiple rows.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent table shared by all rows being updated. Format: tables/{table}
* `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.Area120Tables.V1alpha1.Model.BatchUpdateRowsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.BatchUpdateRowsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_batch_update(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.BatchUpdateRowsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_batch_update(
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,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1alpha1/{+parent}/rows:batchUpdate", %{
"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.Area120Tables.V1alpha1.Model.BatchUpdateRowsResponse{}]
)
end
@doc """
Creates a row.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent table where this row will be created. Format: tables/{table}
* `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").
* `:view` (*type:* `String.t`) - Optional. Column key to use for values in the row. Defaults to user entered name.
* `:body` (*type:* `GoogleApi.Area120Tables.V1alpha1.Model.Row.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.Row{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_create(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.Row.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_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,
:view => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1alpha1/{+parent}/rows", %{
"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.Area120Tables.V1alpha1.Model.Row{}])
end
@doc """
Deletes a row.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The name of the row to delete. Format: tables/{table}/rows/{row}
* `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.Area120Tables.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_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("/v1alpha1/{+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.Area120Tables.V1alpha1.Model.Empty{}])
end
@doc """
Gets a row. Returns NOT_FOUND if the row does not exist in the table.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The name of the row to retrieve. Format: tables/{table}/rows/{row}
* `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").
* `:view` (*type:* `String.t`) - Optional. Column key to use for values in the row. Defaults to user entered name.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.Row{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.Row.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_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,
:view => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/{+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.Area120Tables.V1alpha1.Model.Row{}])
end
@doc """
Lists rows in a table. Returns NOT_FOUND if the table does not exist.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The parent table. Format: tables/{table}
* `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").
* `:pageSize` (*type:* `integer()`) - The maximum number of rows to return. The service may return fewer than this value. If unspecified, at most 50 rows are returned. The maximum value is 1,000; values above 1,000 are coerced to 1,000.
* `:pageToken` (*type:* `String.t`) - A page token, received from a previous `ListRows` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListRows` must match the call that provided the page token.
* `:view` (*type:* `String.t`) - Optional. Column key to use for values in the row. Defaults to user entered name.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.ListRowsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.ListRowsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_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,
:pageSize => :query,
:pageToken => :query,
:view => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/{+parent}/rows", %{
"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.Area120Tables.V1alpha1.Model.ListRowsResponse{}]
)
end
@doc """
Updates a row.
## Parameters
* `connection` (*type:* `GoogleApi.Area120Tables.V1alpha1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource name of the row. Row names have the form `tables/{table}/rows/{row}`. The name is ignored when creating a row.
* `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`) - The list of fields to update.
* `:view` (*type:* `String.t`) - Optional. Column key to use for values in the row. Defaults to user entered name.
* `:body` (*type:* `GoogleApi.Area120Tables.V1alpha1.Model.Row.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Area120Tables.V1alpha1.Model.Row{}}` on success
* `{:error, info}` on failure
"""
@spec area120tables_tables_rows_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Area120Tables.V1alpha1.Model.Row.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def area120tables_tables_rows_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,
:view => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1alpha1/{+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.Area120Tables.V1alpha1.Model.Row{}])
end
end
| 46.502203 | 262 | 0.619111 |
03c8076eab0e0dd5f67c119d04ee19c8fcce4260 | 685 | exs | Elixir | config/prod.secret.exs | paniagua/abix | e88e4c7f233c8bdeca843e5c4508cf4d2e676788 | [
"MIT"
] | null | null | null | config/prod.secret.exs | paniagua/abix | e88e4c7f233c8bdeca843e5c4508cf4d2e676788 | [
"MIT"
] | null | null | null | config/prod.secret.exs | paniagua/abix | e88e4c7f233c8bdeca843e5c4508cf4d2e676788 | [
"MIT"
] | null | null | null | use Mix.Config
# In this file, we keep production configuration that
# you'll likely want to automate and keep away from
# your version control system.
#
# You should document the content of this
# file or create a script for recreating it, since it's
# kept out of version control and might be hard to recover
# or recreate for your teammates (or yourself later on).
config :abix, Abix.Endpoint,
secret_key_base: "WCjzpsiIUFvwl8RmGvNTC0+00yXtbZKp2PGbdHvGjnOLkx+JmY54KM1MABif3wtI"
# Configure your database
config :abix, Abix.Repo,
adapter: Ecto.Adapters.Postgres,
username: "messenger",
password: "salemove",
database: "messenger",
hostname: "postgres",
pool_size: 15
| 31.136364 | 85 | 0.766423 |
03c80be80580b120714d7e9ab097f48e24b1d608 | 1,989 | ex | Elixir | lib/crawly/pipelines/write_to_file.ex | jallum/crawly | dfe37b125f6b39637608576715b076d0877b1d8b | [
"Apache-2.0"
] | null | null | null | lib/crawly/pipelines/write_to_file.ex | jallum/crawly | dfe37b125f6b39637608576715b076d0877b1d8b | [
"Apache-2.0"
] | null | null | null | lib/crawly/pipelines/write_to_file.ex | jallum/crawly | dfe37b125f6b39637608576715b076d0877b1d8b | [
"Apache-2.0"
] | null | null | null | defmodule Crawly.Pipelines.WriteToFile do
@moduledoc """
Stores a given item into Filesystem
Pipeline Lifecycle:
1. When run (by `Crawly.Utils.pipe`), creates a file descriptor if not already created.
2. Performs the write operation
3. File descriptor is reused by passing it through the pipeline state with `:write_to_file_fd`
Note: `File.close` is not necessary due to the file descriptor being automatically closed upon the end of a the parent process.
Refer to https://github.com/oltarasenko/crawly/pull/19#discussion_r350599526 for relevant discussion.
"""
@behaviour Crawly.Pipeline
require Logger
@impl Crawly.Pipeline
def run(item, %{write_to_file_fd: fd} = state) do
:ok = write(fd, item)
{item, state}
end
# No active FD
def run(item, state) do
fd = open_fd(state.spider_name)
:ok = write(fd, item)
{item, Map.put(state, :write_to_file_fd, fd)}
end
defp open_fd(spider_name) do
config =
Application.get_env(
:crawly,
Crawly.Pipelines.WriteToFile,
Keyword.new()
)
folder = Keyword.get(config, :folder, System.tmp_dir!())
extension = Keyword.get(config, :extension, "jl")
filename = "#{inspect(spider_name)}.#{extension}"
# Open file descriptor to write items
{:ok, io_device} =
File.open(
Path.join([folder, filename]),
[
:binary,
:write,
:delayed_write,
:utf8
]
)
io_device
end
# Performs the write operation
@spec write(io, item) :: :ok
when io: File.io_device(),
item: any()
defp write(io, item) do
try do
IO.write(io, item)
IO.write(io, "\n")
catch
error, reason ->
stacktrace = :erlang.get_stacktrace()
Logger.error(
"Could not write item: #{inspect(error)}, reason: #{inspect(reason)}, stacktrace: #{
inspect(stacktrace)
}
"
)
end
end
end
| 25.177215 | 129 | 0.619407 |
03c822cee800f8098fa681a125466c138515e3e7 | 201 | exs | Elixir | .formatter.exs | lucab85/audioslides.io | cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9 | [
"MIT"
] | 17 | 2017-11-14T14:03:18.000Z | 2021-12-10T04:18:48.000Z | .formatter.exs | lucab85/audioslides.io | cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9 | [
"MIT"
] | 21 | 2017-11-19T13:38:07.000Z | 2022-02-10T00:11:14.000Z | .formatter.exs | lucab85/audioslides.io | cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9 | [
"MIT"
] | 2 | 2019-09-03T03:32:13.000Z | 2021-02-23T21:52:57.000Z | [
inputs: [
"mix.exs",
"{config,lib,test}/**/*.{ex,exs}"
],
line_length: 120,
locals_without_parens: [
resources: :*,
post: :*,
delete: :*,
get: :*,
field: :*
]
]
| 13.4 | 37 | 0.457711 |
03c83ba6e6a58f66249c104fdf82473dad2da49d | 1,884 | exs | Elixir | mix.exs | jjcarstens/circuits_gpio | 3c71f59654c27eadf5b52bd448b2b514c626876e | [
"Apache-2.0"
] | null | null | null | mix.exs | jjcarstens/circuits_gpio | 3c71f59654c27eadf5b52bd448b2b514c626876e | [
"Apache-2.0"
] | null | null | null | mix.exs | jjcarstens/circuits_gpio | 3c71f59654c27eadf5b52bd448b2b514c626876e | [
"Apache-2.0"
] | null | null | null | defmodule Circuits.GPIO.MixProject do
use Mix.Project
def project do
[
app: :circuits_gpio,
version: "0.1.0",
elixir: "~> 1.6",
description: description(),
package: package(),
source_url: "https://github.com/elixir-circuits/circuits_gpio",
compilers: [:elixir_make | Mix.compilers()],
make_targets: ["all"],
make_clean: ["clean"],
make_env: make_env(),
docs: [extras: ["README.md"]],
aliases: [docs: ["docs", ©_images/1], format: [&format_c/1, "format"]],
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
defp make_env() do
case System.get_env("ERL_EI_INCLUDE_DIR") do
nil ->
%{
"ERL_EI_INCLUDE_DIR" => "#{:code.root_dir()}/usr/include",
"ERL_EI_LIBDIR" => "#{:code.root_dir()}/usr/lib"
}
_ ->
%{}
end
end
def application, do: []
defp description do
"Elixir access to hardware GPIO interface."
end
defp package do
%{
files: [
"lib",
"src/*.[ch]",
"mix.exs",
"README.md",
"PORTING.md",
"LICENSE",
"Makefile"
],
licenses: ["Apache-2.0"],
links: %{"GitHub" => "https://github.com/elixir-circuits/circuits_gpio"}
}
end
defp deps do
[
{:elixir_make, "~> 0.4", runtime: false},
{:ex_doc, "~> 0.11", only: :dev, runtime: false}
]
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 format_c([]) do
astyle =
System.find_executable("astyle") ||
Mix.raise("""
Could not format C code since astyle is not available.
""")
System.cmd(astyle, ["-n", "src/*.c", "src/*.h"], into: IO.stream(:stdio, :line))
end
defp format_c(_args), do: true
end
| 22.97561 | 84 | 0.547771 |
03c8622074ac4323f73ea6138aabc5d5ec562c36 | 2,524 | ex | Elixir | lib/holidays/definitions/de.ex | assj/holidays | 158657e296179d858f173cff3656d3fcaf5c653d | [
"MIT"
] | 16 | 2016-01-11T16:18:38.000Z | 2022-02-24T09:41:05.000Z | lib/holidays/definitions/de.ex | assj/holidays | 158657e296179d858f173cff3656d3fcaf5c653d | [
"MIT"
] | 9 | 2016-08-14T01:26:16.000Z | 2021-02-08T01:00:35.000Z | lib/holidays/definitions/de.ex | assj/holidays | 158657e296179d858f173cff3656d3fcaf5c653d | [
"MIT"
] | 8 | 2017-06-08T09:23:46.000Z | 2021-08-17T19:03:05.000Z | defmodule Holidays.Definitions.De do
import Holidays.Define
# Ported from German holiday definitions in the Ruby Holiday gem.
#
# Updated: 2009-11-05.
# Sources:
# - http://en.wikipedia.org/wiki/Holidays_in_Germany
# - http://www.timeanddate.com/calendar/index.html?country=8
# - http://www.germany.info/relaunch/welcome/travel/holidays.html
@moduledoc """
German holiday definitions.
"""
def init() do
# Variable date:
holiday "Karfreitag",
%{regions: [:de],
function: {Holidays, :easter, [:year], -2}}
holiday "Ostermontag",
%{regions: [:de],
function: {Holidays, :easter, [:year], 1}}
holiday "Christi Himmelfahrt",
%{regions: [:de],
function: {Holidays, :easter, [:year], 39}}
holiday "Pfingstmontag",
%{regions: [:de],
function: {Holidays, :easter, [:year], 50}}
holiday "Fronleichnam",
%{regions: [:de_bw, :de_by, :de_he, :de_nw, :de_rp, :de_sl],
function: {Holidays, :easter, [:year], 60}}
# January:
holiday "Neujahrstag",
%{month: 1,
regions: [:de],
day: 1}
holiday "Heilige Drei Könige",
%{month: 1,
regions: [:de_bw, :de_by, :de_st],
day: 6}
# May:
holiday "Tag der Arbeit",
%{month: 5,
regions: [:de],
day: 1}
# August:
holiday "Mariä Himmelfahrt",
%{month: 8,
regions: [:de_by, :de_sl],
day: 15}
holiday "Friedensfest",
%{month: 8,
regions: [:de_by_aux],
day: 8}
# October:
holiday "Tag der Deutschen Einheit",
%{month: 10,
regions: [:de],
day: 3}
holiday "Reformationstag",
%{month: 10,
regions: [:de_bb, :de_mv, :de_sn, :de_st, :de_th],
day: 31}
# November:
holiday "Allerheiligen",
%{month: 11,
regions: [:de_bw, :de_by, :de_nw, :de_rp, :de_sl],
day: 1}
holiday "Buß- und Bettag",
%{month: 11,
regions: [:de_sn],
function: {Holidays.Definitions.De, :buss_und_bettag, [:year]}}
# December:
holiday "1. Weihnachtstag",
%{month: 12,
regions: [:de],
day: 25}
holiday "2. Weihnachtstag",
%{month: 12,
regions: [:de],
day: 26}
end
def buss_und_bettag(year) do
wday = rem(:calendar.day_of_the_week(year, 11, 23), 7)
if wday > 3 do
{year, 11, 23 - (wday - 3)}
else
{year, 11, 23 - (wday + 4)}
end
end
end
| 21.57265 | 71 | 0.537639 |
03c86fb570a9bcc5f581913d72b54916f91477aa | 646 | ex | Elixir | lib/atom_tweaks/repo.ex | amymariparker/atom-style-tweaks | 9f17b626e4a527d17d2da85ac575029b52fb6a25 | [
"MIT"
] | null | null | null | lib/atom_tweaks/repo.ex | amymariparker/atom-style-tweaks | 9f17b626e4a527d17d2da85ac575029b52fb6a25 | [
"MIT"
] | null | null | null | lib/atom_tweaks/repo.ex | amymariparker/atom-style-tweaks | 9f17b626e4a527d17d2da85ac575029b52fb6a25 | [
"MIT"
] | null | null | null | defmodule AtomTweaks.Repo do
@moduledoc """
Defines the Atom Tweaks database repository.
## Shared options
Almost all of the repository operations below accept the following options:
* `:timeout` - The time in milliseconds to wait for the query call to finish, `:infinity` will
wait indefinitely (default: 15000);
* `:pool_timeout` - The time in milliseconds to wait for calls to the pool to finish, `:infinity`
will wait indefinitely (default: 5000);
* `:log` - When false, does not log the query
Such cases will be explicitly documented as well as any extra options.
"""
use Ecto.Repo, otp_app: :atom_tweaks
end
| 34 | 99 | 0.726006 |
03c888ff8e6a30f6032ad72ca7f2770da655923a | 339 | exs | Elixir | test/koans/strings_koan_test.exs | josesrodriguez610/elixir-koans | 815d2a1d8b69161420558f5f32bd7d3f08275139 | [
"MIT"
] | null | null | null | test/koans/strings_koan_test.exs | josesrodriguez610/elixir-koans | 815d2a1d8b69161420558f5f32bd7d3f08275139 | [
"MIT"
] | null | null | null | test/koans/strings_koan_test.exs | josesrodriguez610/elixir-koans | 815d2a1d8b69161420558f5f32bd7d3f08275139 | [
"MIT"
] | null | null | null | defmodule StringTests do
use ExUnit.Case
import TestHarness
test "Strings"
answers = [
"hello",
"1 + 1 = 2",
"hello ",
"hello world",
"An incredible day",
"incredible",
"banana",
"banana",
"StringStringString",
"LISTEN"
]
test_all(Strings, answers)
end
end
| 15.409091 | 30 | 0.536873 |
03c89032fdd27076bdcab167b4aeab5ef5a8bf14 | 1,524 | ex | Elixir | rocketpay/lib/rocketpay_web/endpoint.ex | luizAzevedo/NextLevelWeek-4 | 986bcf919128456a7305a25a52f4becbf1915698 | [
"MIT"
] | 1 | 2021-02-25T03:49:59.000Z | 2021-02-25T03:49:59.000Z | rocketpay/lib/rocketpay_web/endpoint.ex | luizAzevedo/NextLevelWeek-4 | 986bcf919128456a7305a25a52f4becbf1915698 | [
"MIT"
] | null | null | null | rocketpay/lib/rocketpay_web/endpoint.ex | luizAzevedo/NextLevelWeek-4 | 986bcf919128456a7305a25a52f4becbf1915698 | [
"MIT"
] | null | null | null | defmodule RocketpayWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :rocketpay
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_rocketpay_key",
signing_salt: "j/L9OxAk"
]
socket "/socket", RocketpayWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :rocketpay,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :rocketpay
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug RocketpayWeb.Router
end
| 28.754717 | 97 | 0.716535 |
03c9139882ca3fabbff8ea19620a3bf374c2edd3 | 74 | exs | Elixir | test/test_helper.exs | ScapeGuru/osrs_api_proxy | 7d4cace8e5185ec60a324de274df225a58049b7a | [
"Apache-2.0"
] | null | null | null | test/test_helper.exs | ScapeGuru/osrs_api_proxy | 7d4cace8e5185ec60a324de274df225a58049b7a | [
"Apache-2.0"
] | 37 | 2021-04-19T23:56:46.000Z | 2022-02-28T15:14:04.000Z | test/test_helper.exs | ScapeGuru/osrs_api_proxy | 7d4cace8e5185ec60a324de274df225a58049b7a | [
"Apache-2.0"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(OsrsApiProxy.Repo, :manual)
| 24.666667 | 58 | 0.797297 |
03c941764cf23da99346fd661d2617f0becdf459 | 485 | ex | Elixir | play_web/lib/play_web/views/error_view.ex | axelson/scenic_asteroids | 20fb22af441028b0837016337c5e418c033ded29 | [
"BSD-3-Clause"
] | 31 | 2018-12-25T19:52:35.000Z | 2022-03-20T01:06:46.000Z | play_web/lib/play_web/views/error_view.ex | axelson/scenic_asteroids | 20fb22af441028b0837016337c5e418c033ded29 | [
"BSD-3-Clause"
] | 4 | 2018-12-23T18:34:20.000Z | 2021-05-10T04:05:45.000Z | play_web/lib/play_web/views/error_view.ex | axelson/scenic_asteroids | 20fb22af441028b0837016337c5e418c033ded29 | [
"BSD-3-Clause"
] | 2 | 2019-04-09T18:35:51.000Z | 2020-12-22T15:19:18.000Z | defmodule PlayWeb.ErrorView do
use PlayWeb, :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.529412 | 61 | 0.731959 |
03c974e792b7f4d7efca298e0b03ead2bc568a26 | 460 | ex | Elixir | extended_example/lib/demo/fulfillment_service/supervisor.ex | PJUllrich/event-sourcing-with-elixir | 7f70e6bc49d9d93f1d86513a1f358e41e07b8304 | [
"MIT"
] | 19 | 2020-10-08T14:05:30.000Z | 2022-03-18T08:43:11.000Z | extended_example/lib/demo/fulfillment_service/supervisor.ex | PJUllrich/event-sourcing-with-elixir | 7f70e6bc49d9d93f1d86513a1f358e41e07b8304 | [
"MIT"
] | null | null | null | extended_example/lib/demo/fulfillment_service/supervisor.ex | PJUllrich/event-sourcing-with-elixir | 7f70e6bc49d9d93f1d86513a1f358e41e07b8304 | [
"MIT"
] | 3 | 2021-02-19T08:31:58.000Z | 2021-12-09T05:28:55.000Z | defmodule FulfillmentService.Supervisor do
use Supervisor
def start_link(opts) do
Supervisor.start_link(__MODULE__, opts, name: __MODULE__)
end
def init(_args) do
children = [
FulfillmentService,
FulfillmentService.ShipmentRegisteredConsumer,
FulfillmentService.ShipmentDelegatedToVehicleConsumer,
FulfillmentService.VehicleOutForDeliveryConsumer
]
Supervisor.init(children, strategy: :one_for_one)
end
end
| 24.210526 | 61 | 0.765217 |
03c976caeef6bf6cae49e83cfd2661f53bb5c9f3 | 253 | ex | Elixir | lib/contento.ex | jackmarchant/contento-fork | 7da622f27fc2003583bdd9a5e2f76b8a16bf852a | [
"MIT"
] | null | null | null | lib/contento.ex | jackmarchant/contento-fork | 7da622f27fc2003583bdd9a5e2f76b8a16bf852a | [
"MIT"
] | null | null | null | lib/contento.ex | jackmarchant/contento-fork | 7da622f27fc2003583bdd9a5e2f76b8a16bf852a | [
"MIT"
] | 1 | 2020-11-21T20:12:01.000Z | 2020-11-21T20:12:01.000Z | defmodule Contento do
@moduledoc """
Contento keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 25.3 | 66 | 0.754941 |
03c980a60156bd8e41fda8a7b1b85c319dff0cf3 | 42,767 | exs | Elixir | test/icon/schema/loader_test.exs | alexdesousa/icon | 2b363582b129bc0485a39e9845d2a18eabd2f6d6 | [
"MIT"
] | 4 | 2022-01-27T09:10:05.000Z | 2022-03-09T04:38:13.000Z | test/icon/schema/loader_test.exs | alexdesousa/icon | 2b363582b129bc0485a39e9845d2a18eabd2f6d6 | [
"MIT"
] | null | null | null | test/icon/schema/loader_test.exs | alexdesousa/icon | 2b363582b129bc0485a39e9845d2a18eabd2f6d6 | [
"MIT"
] | null | null | null | defmodule Icon.Schema.LoaderTest do
use ExUnit.Case, async: true
import Icon.Schema, only: [list: 1, any: 2, enum: 1]
alias Icon.Schema
alias Icon.Schema.Error
alias Icon.Schema.Types.EventLog
describe "Icon.Schema.load/1" do
test "parameters can be a keyword list" do
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: :integer}
|> Schema.generate()
|> Schema.new(integer: "0x2a")
|> Schema.load()
end
test "adds error when required field is missing" do
assert %Schema{
errors: %{integer: "is required"},
is_valid?: false
} =
%{integer: {:integer, required: true}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "uses default when field is missing" do
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: {:integer, default: "0x2a"}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "expands default function when field is missing" do
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: {:integer, default: fn %Schema{} -> 42 end}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "keeps field when is nil and it's nullable" do
assert %Schema{
data: %{integer: nil},
is_valid?: true
} =
%{integer: {:integer, nullable: true}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "keeps field when is an empty binary and it's nullable" do
assert %Schema{
data: %{string: ""},
is_valid?: true
} =
%{string: {:string, nullable: true, default: ""}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "uses the provided value for a nullable field" do
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: {:integer, nullable: true}}
|> Schema.generate()
|> Schema.new(%{integer: 42})
|> Schema.load()
end
test "doesn't add an error when the missing field is required, but a default is provided" do
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: {:integer, default: "0x2a", required: true}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "add error when required field is empty string" do
params = %{"integer" => ""}
assert %Schema{
errors: %{integer: "is required"},
is_valid?: false
} =
%{integer: {:integer, required: true}}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "does not add error when non required field is empty string" do
params = %{"integer" => ""}
assert %Schema{
data: %{},
is_valid?: true
} =
%{integer: :integer}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "when default is an empty string ignores it" do
assert %Schema{
data: %{},
is_valid?: true
} =
%{integer: {:integer, default: ""}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "adds error when required field has a default that's an empty string" do
assert %Schema{
errors: %{integer: "is required"},
is_valid?: false
} =
%{integer: {:integer, default: "", required: true}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "when schema is missing, ignores them" do
assert %Schema{
data: %{},
is_valid?: true
} =
%{schema: %{integer: :integer}}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "when enum is missing, ignores it" do
assert %Schema{
data: %{},
is_valid?: true
} =
%{enum: enum([:call, :deploy, :message, :deposit])}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "when list is missing, ignores it" do
assert %Schema{
data: %{},
is_valid?: true
} =
%{list: list(:integer)}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "loads primitive type with options" do
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
{:integer, default: 42}
|> Schema.generate()
|> Schema.new(nil)
|> Schema.load()
end
test "loads $variable type" do
data = %{
"0" => "0x2a",
"1" => "0x54"
}
assert %Schema{
data: %{"0" => 42, "1" => 84},
is_valid?: true
} =
%{"$variable": :loop}
|> Schema.generate()
|> Schema.new(data)
|> Schema.load()
end
test "loads address type" do
address = "hxbe258ceb872e08851f1f59694dac2558708ece11"
assert %Schema{
data: %{"$__SCHEMA__": ^address},
is_valid?: true
} =
:address
|> Schema.generate()
|> Schema.new(address)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^address},
is_valid?: true
} =
Icon.Schema.Types.Address
|> Schema.generate()
|> Schema.new(address)
|> Schema.load()
end
test "loads address type in schema" do
address = "hxbe258ceb872e08851f1f59694dac2558708ece11"
params = %{"address" => address}
assert %Schema{
data: %{address: ^address},
is_valid?: true
} =
%{address: :address}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when address is invalid" do
params = %{"address" => "hx0"}
assert %Schema{
errors: %{address: "is invalid"},
is_valid?: false
} =
%{address: :address}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads primitive any type" do
data = "0x2a"
assert %Schema{
data: %{"$__SCHEMA__": ^data},
is_valid?: true
} =
:any
|> Schema.generate()
|> Schema.new(data)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^data},
is_valid?: true
} =
Icon.Schema.Types.Any
|> Schema.generate()
|> Schema.new(data)
|> Schema.load()
end
test "loads primitive any type in schema" do
data = "0x2a"
params = %{"any" => data}
assert %Schema{
data: %{any: ^data},
is_valid?: true
} =
%{any: :any}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads binary_data type" do
binary_data = "ICON 2.0"
assert %Schema{
data: %{"$__SCHEMA__": ^binary_data},
is_valid?: true
} =
:binary_data
|> Schema.generate()
|> Schema.new(binary_data)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^binary_data},
is_valid?: true
} =
Icon.Schema.Types.BinaryData
|> Schema.generate()
|> Schema.new(binary_data)
|> Schema.load()
end
test "loads binary_data type in schema" do
binary_data = "ICON 2.0"
params = %{"binary_data" => binary_data}
assert %Schema{
data: %{binary_data: ^binary_data},
is_valid?: true
} =
%{binary_data: :binary_data}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when binary data is invalid" do
params = %{"binary_data" => 42}
assert %Schema{
errors: %{binary_data: "is invalid"},
is_valid?: false
} =
%{binary_data: :binary_data}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads boolean type" do
boolean = "0x1"
assert %Schema{
data: %{"$__SCHEMA__": true},
is_valid?: true
} =
:boolean
|> Schema.generate()
|> Schema.new(boolean)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": true},
is_valid?: true
} =
Icon.Schema.Types.Boolean
|> Schema.generate()
|> Schema.new(boolean)
|> Schema.load()
end
test "loads boolean type in schema" do
boolean = "0x1"
params = %{"boolean" => boolean}
assert %Schema{
data: %{boolean: true},
is_valid?: true
} =
%{boolean: :boolean}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when boolean is invalid" do
params = %{"boolean" => "0x3"}
assert %Schema{
errors: %{boolean: "is invalid"},
is_valid?: false
} =
%{boolean: :boolean}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads eoa_address type" do
eoa_address = "hxbe258ceb872e08851f1f59694dac2558708ece11"
assert %Schema{
data: %{"$__SCHEMA__": ^eoa_address},
is_valid?: true
} =
:eoa_address
|> Schema.generate()
|> Schema.new(eoa_address)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^eoa_address},
is_valid?: true
} =
Icon.Schema.Types.EOA
|> Schema.generate()
|> Schema.new(eoa_address)
|> Schema.load()
end
test "loads eoa_address type in schema" do
eoa_address = "hxbe258ceb872e08851f1f59694dac2558708ece11"
params = %{"eoa_address" => eoa_address}
assert %Schema{
data: %{eoa_address: ^eoa_address},
is_valid?: true
} =
%{eoa_address: :eoa_address}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when eoa_address is invalid" do
params = %{"eoa_address" => "hx0"}
assert %Schema{
errors: %{eoa_address: "is invalid"},
is_valid?: false
} =
%{eoa_address: :eoa_address}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads error type" do
error = %{
"code" => -32_000,
"message" => "Server error",
"data" =>
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
}
assert %Schema{
data: %{
"$__SCHEMA__": %Error{
code: -32_000,
message: "Server error",
data:
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238",
reason: :server_error,
domain: :request
}
},
is_valid?: true
} =
:error
|> Schema.generate()
|> Schema.new(error)
|> Schema.load()
assert %Schema{
data: %{
"$__SCHEMA__": %Error{
code: -32_000,
message: "Server error",
data:
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238",
reason: :server_error,
domain: :request
}
},
is_valid?: true
} =
Icon.Schema.Error
|> Schema.generate()
|> Schema.new(error)
|> Schema.load()
end
test "loads error type in schema" do
params = %{
"error" => %{
"code" => -32_000,
"message" => "Server error",
"data" =>
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
}
}
assert %Schema{
data: %{
error: %Error{
code: -32_000,
message: "Server error",
data:
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238",
reason: :server_error,
domain: :request
}
},
is_valid?: true
} =
%{error: :error}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when error type is invalid" do
params = %{
"error" => %{
"code" => 1,
"message" => "Server error"
}
}
assert %Schema{
errors: %{error: "is invalid"},
is_valid?: false
} =
%{error: :error}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads event_log type" do
event_log = %{
"scoreAddress" => "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32",
"indexed" => [
"Transfer(Address,Address,int)",
"hxfd7e4560ba363f5aabd32caac7317feeee70ea57",
"hx2e243ad926ac48d15156756fce28314357d49d83"
],
"data" => [
"0x2a"
]
}
assert %Schema{
data: %{
"$__SCHEMA__": %EventLog{
header: "Transfer(Address,Address,int)",
name: "Transfer",
score_address: "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32",
indexed: [
"hxfd7e4560ba363f5aabd32caac7317feeee70ea57",
"hx2e243ad926ac48d15156756fce28314357d49d83"
],
data: [
42
]
}
},
is_valid?: true
} =
:event_log
|> Schema.generate()
|> Schema.new(event_log)
|> Schema.load()
assert %Schema{
data: %{
"$__SCHEMA__": %EventLog{
header: "Transfer(Address,Address,int)",
name: "Transfer",
score_address: "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32",
indexed: [
"hxfd7e4560ba363f5aabd32caac7317feeee70ea57",
"hx2e243ad926ac48d15156756fce28314357d49d83"
],
data: [
42
]
}
},
is_valid?: true
} =
Icon.Schema.Types.EventLog
|> Schema.generate()
|> Schema.new(event_log)
|> Schema.load()
end
test "loads event_log type in schema" do
params = %{
"event_log" => %{
"scoreAddress" => "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32",
"indexed" => [
"Transfer(Address,Address,int)",
"hxfd7e4560ba363f5aabd32caac7317feeee70ea57",
"hx2e243ad926ac48d15156756fce28314357d49d83"
],
"data" => [
"0x2a"
]
}
}
assert %Schema{
data: %{
event_log: %EventLog{
header: "Transfer(Address,Address,int)",
name: "Transfer",
score_address: "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32",
indexed: [
"hxfd7e4560ba363f5aabd32caac7317feeee70ea57",
"hx2e243ad926ac48d15156756fce28314357d49d83"
],
data: [
42
]
}
},
is_valid?: true
} =
%{event_log: :event_log}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when event_log is invalid" do
assert %Schema{
errors: %{event_log: "is invalid"},
is_valid?: false
} =
%{event_log: :event_log}
|> Schema.generate()
|> Schema.new(%{"event_log" => 42})
|> Schema.load()
end
test "loads hash type" do
hash =
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
assert %Schema{
data: %{"$__SCHEMA__": ^hash},
is_valid?: true
} =
:hash
|> Schema.generate()
|> Schema.new(hash)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^hash},
is_valid?: true
} =
Icon.Schema.Types.Hash
|> Schema.generate()
|> Schema.new(hash)
|> Schema.load()
end
test "loads hash type in schema" do
hash =
"0xc71303ef8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
params = %{"hash" => hash}
assert %Schema{
data: %{hash: ^hash},
is_valid?: true
} =
%{hash: :hash}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when hash is invalid" do
params = %{"hash" => "0x0"}
assert %Schema{
errors: %{hash: "is invalid"},
is_valid?: false
} =
%{hash: :hash}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads integer type" do
integer = "0x2a"
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
:integer
|> Schema.generate()
|> Schema.new(integer)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
Icon.Schema.Types.Integer
|> Schema.generate()
|> Schema.new(integer)
|> Schema.load()
end
test "loads integer type in schema" do
params = %{"integer" => "0x2a"}
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: :integer}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when integer is invalid" do
params = %{"integer" => "INVALID"}
assert %Schema{
errors: %{integer: "is invalid"},
is_valid?: false
} =
%{integer: :integer}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads loop type" do
loop = "0x2a"
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
:loop
|> Schema.generate()
|> Schema.new(loop)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
Icon.Schema.Types.Loop
|> Schema.generate()
|> Schema.new(loop)
|> Schema.load()
end
test "loads loop type in schema" do
params = %{"loop" => "0x2a"}
assert %Schema{
data: %{loop: 42},
is_valid?: true
} =
%{loop: :loop}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when loop is invalid" do
params = %{"loop" => "INVALID"}
assert %Schema{
errors: %{loop: "is invalid"},
is_valid?: false
} =
%{loop: :loop}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads pos_integer type" do
pos_integer = "0x2a"
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
:pos_integer
|> Schema.generate()
|> Schema.new(pos_integer)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": 42},
is_valid?: true
} =
Icon.Schema.Types.PosInteger
|> Schema.generate()
|> Schema.new(pos_integer)
|> Schema.load()
end
test "loads pos_integer type in schema" do
params = %{"pos_integer" => "0x2a"}
assert %Schema{
data: %{pos_integer: 42},
is_valid?: true
} =
%{pos_integer: :pos_integer}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when pos_integer is invalid" do
params = %{"pos_integer" => "-0x2a"}
assert %Schema{
errors: %{pos_integer: "is invalid"},
is_valid?: false
} =
%{pos_integer: :pos_integer}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads score_address type" do
score_address = "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32"
assert %Schema{
data: %{"$__SCHEMA__": ^score_address},
is_valid?: true
} =
:score_address
|> Schema.generate()
|> Schema.new(score_address)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^score_address},
is_valid?: true
} =
Icon.Schema.Types.SCORE
|> Schema.generate()
|> Schema.new(score_address)
|> Schema.load()
end
test "loads score_address type in schema" do
score_address = "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32"
params = %{"score_address" => score_address}
assert %Schema{
data: %{score_address: ^score_address},
is_valid?: true
} =
%{score_address: :score_address}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error score_address is invalid" do
params = %{"score_address" => "cx0"}
assert %Schema{
errors: %{score_address: "is invalid"},
is_valid?: false
} =
%{score_address: :score_address}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads signature type" do
signature =
"VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA="
assert %Schema{
data: %{"$__SCHEMA__": ^signature},
is_valid?: true
} =
:signature
|> Schema.generate()
|> Schema.new(signature)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^signature},
is_valid?: true
} =
Icon.Schema.Types.Signature
|> Schema.generate()
|> Schema.new(signature)
|> Schema.load()
end
test "loads signature type in schema" do
signature =
"VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA="
params = %{"signature" => signature}
assert %Schema{
data: %{signature: ^signature},
is_valid?: true
} =
%{signature: :signature}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when signature is invalid" do
params = %{"signature" => "INVALID"}
assert %Schema{
errors: %{signature: "is invalid"},
is_valid?: false
} =
%{signature: :signature}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads string type" do
string = "ICON 2.0"
assert %Schema{
data: %{"$__SCHEMA__": ^string},
is_valid?: true
} =
:string
|> Schema.generate()
|> Schema.new(string)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^string},
is_valid?: true
} =
Icon.Schema.Types.String
|> Schema.generate()
|> Schema.new(string)
|> Schema.load()
end
test "loads string type in schema" do
string = "ICON 2.0"
params = %{"string" => string}
assert %Schema{
data: %{string: ^string},
is_valid?: true
} =
%{string: :string}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when string is invalid" do
params = %{"string" => 42}
assert %Schema{
errors: %{string: "is invalid"},
is_valid?: false
} =
%{string: :string}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads timestamp type" do
timestamp = 1_639_653_259_594_958
expected = DateTime.from_unix!(timestamp, :microsecond)
assert %Schema{
data: %{"$__SCHEMA__": ^expected},
is_valid?: true
} =
:timestamp
|> Schema.generate()
|> Schema.new(timestamp)
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": ^expected},
is_valid?: true
} =
Icon.Schema.Types.Timestamp
|> Schema.generate()
|> Schema.new(timestamp)
|> Schema.load()
end
test "loads timestamp type in schema" do
timestamp = 1_639_653_259_594_958
params = %{"timestamp" => timestamp}
expected = DateTime.from_unix!(timestamp, :microsecond)
assert %Schema{
data: %{timestamp: ^expected},
is_valid?: true
} =
%{timestamp: :timestamp}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when timestamp is invalid" do
params = %{"timestamp" => -3_777_051_168_000_000_000}
assert %Schema{
errors: %{timestamp: "is invalid"},
is_valid?: false
} =
%{timestamp: :timestamp}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads enum type" do
assert %Schema{
data: %{"$__SCHEMA__": :call},
is_valid?: true
} =
[:call, :deploy, :message, :deposit]
|> enum()
|> Schema.generate()
|> Schema.new("call")
|> Schema.load()
assert %Schema{
data: %{"$__SCHEMA__": :call},
is_valid?: true
} =
[:call, :deploy, :message, :deposit]
|> enum()
|> Schema.generate()
|> Schema.new(:call)
|> Schema.load()
end
test "loads enum type in schema as string" do
params = %{"enum" => "call"}
assert %Schema{
data: %{enum: :call},
is_valid?: true
} =
%{enum: enum([:call, :deploy, :message, :deposit])}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads enum type in schema as atom" do
params = %{"enum" => :call}
assert %Schema{
data: %{enum: :call},
is_valid?: true
} =
%{enum: enum([:call, :deploy, :message, :deposit])}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "errors when enum type is incorrect" do
params = %{"enum" => "invalid"}
assert %Schema{
errors: %{enum: "is invalid"},
is_valid?: false
} =
%{enum: enum([:call, :deploy, :message, :deposit])}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "enum values should be atoms" do
values = ["call", "deploy", "message", "deposit"]
schema = %{data_type: {:enum, values}}
assert_raise ArgumentError, fn ->
Schema.generate(schema)
end
end
test "loads anonymous schema" do
params = %{"schema" => %{"integer" => "0x2a"}}
assert %Schema{
data: %{schema: %{integer: 42}},
is_valid?: true
} =
%{schema: %{integer: :integer}}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds anonymous schema errors" do
params = %{"schema" => %{"integer" => "INVALID"}}
assert %Schema{
errors: %{schema: %{integer: "is invalid"}},
is_valid?: false
} =
%{schema: %{integer: :integer}}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads a list" do
list = ["0x2a", "0x2b"]
assert %Schema{
data: %{"$__SCHEMA__": [42, 43]},
is_valid?: true
} =
:integer
|> list()
|> Schema.generate()
|> Schema.new(list)
|> Schema.load()
end
test "loads a list with primitive type in schemas" do
params = %{"list" => ["0x2a", "0x2b"]}
assert %Schema{
data: %{list: [42, 43]},
is_valid?: true
} =
%{list: list(:integer)}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads a list with enum type in schema" do
params = %{"list" => ["call", "deploy"]}
assert %Schema{
data: %{list: [:call, :deploy]},
is_valid?: true
} =
%{list: list(enum([:call, :deploy, :message, :deposit]))}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "raises when a list has any type" do
params = %{
"type" => "bool",
"list" => ["0x0", "0x1"]
}
schema = %{
type: enum([:int, :bool]),
list: list(any([int: :integer, boo: :boolean], :type))
}
assert_raise ArgumentError, fn ->
schema
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
end
test "adds error when list is invalid" do
params = %{"list" => ["0x2a", "INVALID"]}
assert %Schema{
errors: %{list: "is invalid"},
is_valid?: false
} =
%{list: list(:integer)}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "raises when any type is used outside a schema" do
assert_raise ArgumentError, fn ->
[score: :score_address, eoa: :eoa_address]
|> any(:type)
|> Schema.generate()
end
end
test "does nothing when field is not present and any is not required" do
assert %Schema{
data: %{},
errors: errors,
is_valid?: true
} =
%{
type: enum([:score, :eoa]),
address: any([score: :score_address, eoa: :eoa_address], :type)
}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
assert errors == %{}
end
test "errors when field is not present and any is required" do
assert %Schema{
errors: %{address: "is invalid"},
is_valid?: false
} =
%{
type: enum([:score, :eoa]),
address: {
any([score: :score_address, eoa: :eoa_address], :type),
required: true
}
}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "errors when field is nil" do
assert %Schema{
errors: %{address: "is invalid"},
is_valid?: false
} =
%{
address: any([score: :score_address, eoa: :eoa_address], nil)
}
|> Schema.generate()
|> Schema.new(%{})
|> Schema.load()
end
test "loads any type in schema" do
address = "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32"
params = %{
"type" => "score",
"address" => address
}
assert %Schema{
data: %{
type: :score,
address: ^address
},
is_valid?: true
} =
%{
type: enum([:score, :eoa]),
address: any([score: :score_address, eoa: :eoa_address], :type)
}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when any field is invalid" do
address = "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32"
params = %{
"type" => "invalid",
"address" => address
}
assert %Schema{
errors: %{
type: "is invalid",
address: "is invalid"
},
is_valid?: false
} =
%{
type: enum([:score, :eoa]),
address: any([score: :score_address, eoa: :eoa_address], :type)
}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "adds error when any field value is not found" do
address = "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32"
params = %{
"type" => "eoa",
"address" => address
}
assert %Schema{
errors: %{address: "is invalid"},
is_valid?: false
} =
%{
type: enum([:score, :eoa]),
address: any([score: :score_address, hash: :hash], :type)
}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads delegated module type in schema" do
defmodule Int do
use Icon.Schema.Type, delegate_to: Icon.Schema.Types.Integer
end
params = %{"integer" => "0x2a"}
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
%{integer: Int}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads module type in schema" do
defmodule Bool do
use Icon.Schema.Type
def load(0), do: {:ok, false}
def load(1), do: {:ok, true}
def load(_), do: :error
def dump(false), do: {:ok, 0}
def dump(true), do: {:ok, 1}
def dump(_), do: :error
end
params = %{"boolean" => 1}
assert %Schema{
data: %{boolean: true},
is_valid?: true
} =
%{boolean: Bool}
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
end
test "loads remote schema" do
defmodule Remote do
use Schema
defschema(%{integer: :integer})
end
assert %Schema{
data: %{schema: %{integer: 42}},
is_valid?: true
} =
%{schema: Remote}
|> Schema.generate()
|> Schema.new(%{schema: %{integer: "0x2a"}})
|> Schema.load()
assert %Schema{
data: %{integer: 42},
is_valid?: true
} =
Remote
|> Schema.generate()
|> Schema.new(integer: "0x2a")
|> Schema.load()
end
test "module type must be compiled" do
assert_raise ArgumentError, fn ->
Schema.generate(%{module: UnexistentModule})
end
assert_raise ArgumentError, fn ->
Schema.generate(UnexistentModule)
end
end
end
describe "apply/1" do
test "returns data when state is valid" do
assert {:ok, 42} =
:integer
|> Schema.generate()
|> Schema.new("0x2a")
|> Schema.load()
|> Schema.apply()
end
test "returns data when state is valid for a schema" do
assert {:ok, %{integer: 42}} =
%{integer: :integer}
|> Schema.generate()
|> Schema.new(integer: "0x2a")
|> Schema.load()
|> Schema.apply()
end
test "returns data in struct when state is valid in a schema" do
defmodule Inner do
use Schema
defschema(%{
loop: :loop
})
end
defmodule Outer do
use Schema
defschema(%{
required_integer: {:integer, required: true},
required_enum: {enum([:foo, :bar]), required: true},
required_list: {list(:boolean), required: true},
required_schema: {Icon.Schema.LoaderTest.Inner, required: true},
integer: :integer,
enum: enum([:foo, :bar]),
list: list(:boolean),
schema: Icon.Schema.LoaderTest.Inner,
anonymous: %{
boolean: :boolean
}
})
end
params = %{
"required_integer" => "0x2a",
"required_enum" => "foo",
"required_list" => ["0x1", "0x0"],
"required_schema" => %{
"loop" => "0x2a"
},
"integer" => "0x2b",
"enum" => "bar",
"list" => ["0x0", "0x1"],
"schema" => %{
"loop" => "0x2b"
},
"anonymous" => %{
"boolean" => "0x1"
}
}
assert {:ok,
%{
__struct__: Outer,
required_integer: 42,
required_enum: :foo,
required_list: [true, false],
required_schema: %{
__struct__: Inner,
loop: 42
},
integer: 43,
enum: :bar,
list: [false, true],
schema: %{
__struct__: Inner,
loop: 43
},
anonymous: %{
boolean: true
}
}} =
Outer
|> Schema.generate()
|> Schema.new(params)
|> Schema.load()
|> Schema.apply(into: Outer)
end
test "returns error when state is invalid" do
assert {
:error,
%Error{
code: -32_602,
reason: :invalid_params,
domain: :internal,
message: "integer is invalid"
}
} =
%{integer: :integer}
|> Schema.generate()
|> Schema.new(integer: "INVALID")
|> Schema.load()
|> Schema.apply()
end
end
end
| 28.229043 | 98 | 0.435055 |
03c99c1ffebc449d7f11f05520cdde53a1c3df28 | 981 | ex | Elixir | lib/guardian/plug/error_handler.ex | LaudateCorpus1/guardian | 23284f7bf91ad2cb50cc3f0f1c10df905a791891 | [
"MIT"
] | 3,135 | 2015-12-19T05:35:41.000Z | 2022-03-29T00:27:25.000Z | lib/guardian/plug/error_handler.ex | LaudateCorpus1/guardian | 23284f7bf91ad2cb50cc3f0f1c10df905a791891 | [
"MIT"
] | 536 | 2015-12-28T04:40:31.000Z | 2022-03-30T22:45:59.000Z | lib/guardian/plug/error_handler.ex | LaudateCorpus1/guardian | 23284f7bf91ad2cb50cc3f0f1c10df905a791891 | [
"MIT"
] | 451 | 2015-12-20T23:43:49.000Z | 2022-03-24T10:36:14.000Z | if Code.ensure_loaded?(Plug) do
defmodule Guardian.Plug.ErrorHandler do
@moduledoc """
Optional Behaviour for creating error handlers for `Guardian.Plug.Pipeline`.
### Error handler
When using plugs, you'll need to specify an error handler module.
The error_handler module requires an `auth_error` function that receives the conn,
the reason tuple and the options.
```elixir
defmodule MyApp.AuthErrorHandler do
@behaviour Guardian.Plug.ErrorHandler
@impl Guardian.Plug.ErrorHandler
def auth_error(conn, {type, reason}, opts) do
...
end
end
```
By default, Guardian will emit types of:
* `:unauthorized`
* `:invalid_token`
* `:already_authenticated`
* `:no_resource_found`
"""
@callback auth_error(
conn :: Plug.Conn.t(),
{type :: atom, reason :: atom},
opts :: Guardian.options()
) :: Plug.Conn.t()
end
end
| 25.153846 | 86 | 0.620795 |
03c9a9df5bc76aa2e14fd659eaad8a7953e135af | 536 | ex | Elixir | lib/pexels/collection.ex | factor18/pexels | c6655f7dd0e58a9a06b6b7a02e74b3f009cd7b01 | [
"MIT"
] | 5 | 2021-05-10T12:10:02.000Z | 2021-05-24T08:15:42.000Z | lib/pexels/collection.ex | factor18/pexels | c6655f7dd0e58a9a06b6b7a02e74b3f009cd7b01 | [
"MIT"
] | null | null | null | lib/pexels/collection.ex | factor18/pexels | c6655f7dd0e58a9a06b6b7a02e74b3f009cd7b01 | [
"MIT"
] | 1 | 2021-05-13T16:49:17.000Z | 2021-05-13T16:49:17.000Z | defmodule Pexels.Collection do
@moduledoc ~S"""
%Pexels.Collection {
description: nil,
id: "z40vgi2",
media_count: 3,
photos_count: 2,
private: false,
title: "Purple",
videos_count: 1
}
"""
use Accessible
use Construct do
field :id, :string
field :title, :string
field :description, :string, default: nil
field :private, :boolean
field :media_count, :integer
field :photos_count, :integer
field :videos_count, :integer
end
end
| 21.44 | 45 | 0.598881 |
03c9b4bafbac4a7830dc27d94359f22bf3e62a34 | 1,016 | exs | Elixir | test/paged_query_test.exs | fremantle-industries/paged_query | 73ee7a734f777aded90f2cd50979e577504b9abb | [
"MIT"
] | 1 | 2021-06-04T14:57:20.000Z | 2021-06-04T14:57:20.000Z | test/paged_query_test.exs | fremantle-industries/paged_query | 73ee7a734f777aded90f2cd50979e577504b9abb | [
"MIT"
] | 13 | 2021-08-01T15:03:37.000Z | 2022-03-01T15:01:58.000Z | test/paged_query_test.exs | fremantle-industries/paged_query | 73ee7a734f777aded90f2cd50979e577504b9abb | [
"MIT"
] | null | null | null | defmodule PagedQueryTest do
use PagedQuery.DataCase
import PagedQuery.Factory
doctest PagedQuery
test "returns a page_size of results by 0 indexed offset" do
blog_1 = insert(:blog)
blog_2 = insert(:blog)
blog_3 = insert(:blog)
assert TestRepo.aggregate(PagedQuery.Blog, :count) == 3
query = from(PagedQuery.Blog, order_by: [asc: :inserted_at])
page_1_blogs =
query
|> PagedQuery.call(0, 1)
|> TestRepo.all()
assert length(page_1_blogs) == 1
assert Enum.at(page_1_blogs, 0).id == blog_1.id
page_2_blogs =
query
|> PagedQuery.call(1, 1)
|> TestRepo.all()
assert length(page_2_blogs) == 1
assert Enum.at(page_2_blogs, 0).id == blog_2.id
page_3_blogs =
query
|> PagedQuery.call(2, 1)
|> TestRepo.all()
assert length(page_3_blogs) == 1
assert Enum.at(page_3_blogs, 0).id == blog_3.id
assert query
|> PagedQuery.call(0, 3)
|> TestRepo.aggregate(:count) == 3
end
end
| 23.090909 | 64 | 0.627953 |
03c9bf87b0d083e5c1fd8dfa7b448e5a2c2ebcf2 | 1,101 | exs | Elixir | test/absinthe/integration/execution/input_types/null/variable_to_type_non_null_T_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 4,101 | 2016-03-02T03:49:20.000Z | 2022-03-31T05:46:01.000Z | test/absinthe/integration/execution/input_types/null/variable_to_type_non_null_T_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 889 | 2016-03-02T16:06:59.000Z | 2022-03-31T20:24:12.000Z | test/absinthe/integration/execution/input_types/null/variable_to_type_non_null_T_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 564 | 2016-03-02T07:49:59.000Z | 2022-03-06T14:40:59.000Z | defmodule Elixir.Absinthe.Integration.Execution.InputTypes.Null.VariableToTypeNonNull_TTest do
use Absinthe.Case, async: true
@query """
query ($value: Int!) { times: objTimes(input: {base: $value}) }
"""
test "scenario #1" do
assert {:ok,
%{
errors: [
%{
message:
"Argument \"input\" has invalid value {base: $value}.\nIn field \"base\": Expected type \"Int!\", found $value.",
locations: [%{column: 40, line: 1}]
},
%{
message: "Variable \"value\": Expected non-null, found null.",
locations: [%{column: 8, line: 1}]
}
]
}} ==
Absinthe.run(
@query,
Absinthe.Fixtures.ObjectTimesSchema,
variables: %{"value" => nil}
)
end
test "scenario #2" do
assert {:ok, %{data: %{"times" => 16}}} ==
Absinthe.run(@query, Absinthe.Fixtures.ObjectTimesSchema, variables: %{"value" => 8})
end
end
| 31.457143 | 133 | 0.476839 |
03c9cd3c99c8c999f14b18cd469abc5cd9944d43 | 277 | ex | Elixir | lib/topshelf_web/views/layout_view.ex | Baradoy/topshelf | bd3d5f96b3d3840990231cf244cc5f14bd807997 | [
"MIT"
] | null | null | null | lib/topshelf_web/views/layout_view.ex | Baradoy/topshelf | bd3d5f96b3d3840990231cf244cc5f14bd807997 | [
"MIT"
] | null | null | null | lib/topshelf_web/views/layout_view.ex | Baradoy/topshelf | bd3d5f96b3d3840990231cf244cc5f14bd807997 | [
"MIT"
] | null | null | null | defmodule TopshelfWeb.LayoutView do
use TopshelfWeb, :view
# Phoenix LiveDashboard is available only in development by default,
# so we instruct Elixir to not warn if the dashboard route is missing.
@compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}}
end
| 34.625 | 72 | 0.776173 |
03c9e085cc32a10c81b934ba145368f750eb5da2 | 22 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_qualified_alias_operation_parsing_test_case/MatchedArrowOperation.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/matched_qualified_alias_operation_parsing_test_case/MatchedArrowOperation.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/matched_qualified_alias_operation_parsing_test_case/MatchedArrowOperation.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | One.Alias |> Two.Alias | 22 | 22 | 0.727273 |
03c9fed5622520022b6f360da2841c157e662b6b | 94 | ex | Elixir | frameworks/Elixir/phoenix/lib/hello/repo.ex | xsoheilalizadeh/FrameworkBenchmarks | 855527008f7488e4fd508d1e72dfa9953874a2c6 | [
"BSD-3-Clause"
] | 6 | 2020-01-26T08:05:12.000Z | 2020-02-18T17:35:26.000Z | frameworks/Elixir/phoenix/lib/hello/repo.ex | xsoheilalizadeh/FrameworkBenchmarks | 855527008f7488e4fd508d1e72dfa9953874a2c6 | [
"BSD-3-Clause"
] | 122 | 2021-04-16T02:04:24.000Z | 2022-01-13T20:17:26.000Z | frameworks/Elixir/phoenix/lib/hello/repo.ex | xsoheilalizadeh/FrameworkBenchmarks | 855527008f7488e4fd508d1e72dfa9953874a2c6 | [
"BSD-3-Clause"
] | 2 | 2018-03-22T00:37:28.000Z | 2018-03-22T00:56:57.000Z | defmodule Hello.Repo do
use Ecto.Repo, otp_app: :hello, adapter: Ecto.Adapters.Postgres
end
| 23.5 | 65 | 0.776596 |
03ca0ea8d0a61be1b463cfb8f861f322b0b7ca37 | 1,928 | exs | Elixir | elixir_tags/config/dev.exs | DinowSauron/Projeto-Next-Level-Week-7-Heat | fc20ed5ca61aff8af37a6120ce6fcffb9907357d | [
"MIT"
] | null | null | null | elixir_tags/config/dev.exs | DinowSauron/Projeto-Next-Level-Week-7-Heat | fc20ed5ca61aff8af37a6120ce6fcffb9907357d | [
"MIT"
] | null | null | null | elixir_tags/config/dev.exs | DinowSauron/Projeto-Next-Level-Week-7-Heat | fc20ed5ca61aff8af37a6120ce6fcffb9907357d | [
"MIT"
] | null | null | null | import Config
# Configure your database
config :elixir_tags, ElixirTags.Repo,
username: "postgres",
password: "789654",
database: "elixir_tags_dev",
hostname: "localhost",
port: 4500,
show_sensitive_data_on_connection_error: true,
pool_size: 10
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with esbuild to bundle .js and .css sources.
config :elixir_tags, ElixirTagsWeb.Endpoint,
# Binding to loopback ipv4 address prevents access from other machines.
# Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
http: [ip: {127, 0, 0, 1}, port: 4000],
check_origin: false,
code_reloader: true,
debug_errors: true,
secret_key_base: "1TGpcnSC48P0SXdrEZOUW4kaPyRIoIunX/dlwAfuwFgoUV3B//+X8lnJipPbVnAs",
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 31.096774 | 86 | 0.729253 |
03ca0fd7b451571df8ae6401816c33eb0f8a6439 | 1,662 | ex | Elixir | sample_server/lib/sample_server_web.ex | mjaric/finix | fb0dedfdfdd46927d3df239c7c45d7fe92c441c4 | [
"Apache-2.0"
] | 31 | 2019-03-26T15:26:21.000Z | 2022-02-16T14:33:13.000Z | sample_server/lib/sample_server_web.ex | mjaric/finix | fb0dedfdfdd46927d3df239c7c45d7fe92c441c4 | [
"Apache-2.0"
] | 3 | 2019-04-05T19:45:09.000Z | 2019-10-25T01:48:57.000Z | sample_server/lib/sample_server_web.ex | mjaric/finix | fb0dedfdfdd46927d3df239c7c45d7fe92c441c4 | [
"Apache-2.0"
] | 5 | 2019-03-27T14:16:28.000Z | 2022-02-18T12:01:46.000Z | defmodule SampleServerWeb 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 SampleServerWeb, :controller
use SampleServerWeb, :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: SampleServerWeb
import Plug.Conn
import SampleServerWeb.Router.Helpers
import SampleServerWeb.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "lib/sample_server_web/templates",
namespace: SampleServerWeb
# 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 SampleServerWeb.Router.Helpers
import SampleServerWeb.ErrorHelpers
import SampleServerWeb.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 SampleServerWeb.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.441176 | 69 | 0.697954 |
03ca2e96e0b681e94ecf136bf2625055224574a6 | 753 | exs | Elixir | test/blockchain_test.exs | Zac-Garby/ultradark_core | 639f269e9a416ea034df78ac1c24703a23457840 | [
"MIT"
] | 1 | 2018-06-28T20:34:05.000Z | 2018-06-28T20:34:05.000Z | test/blockchain_test.exs | Zac-Garby/ultradark_core | 639f269e9a416ea034df78ac1c24703a23457840 | [
"MIT"
] | null | null | null | test/blockchain_test.exs | Zac-Garby/ultradark_core | 639f269e9a416ea034df78ac1c24703a23457840 | [
"MIT"
] | null | null | null | defmodule BlockchainTest do
alias UltraDark.Blockchain
alias UltraDark.Blockchain.Block
use ExUnit.Case, async: true
setup _ do
on_exit(fn ->
File.rm_rf!(".chaindata")
File.rm_rf!(".utxo")
end)
end
test "can initialize a chain" do
chain = Blockchain.initialize()
assert [_ | _] = chain
end
test "can add block to chain" do
chain = Blockchain.initialize()
block =
List.first(chain)
|> Block.initialize()
|> Block.mine()
assert [block | chain] == Blockchain.add_block(chain, block)
end
test "properly recalculates difficulty" do
{chain, _} = Code.eval_file("test/fixtures/chain.exs")
assert Blockchain.recalculate_difficulty(chain) == 4.529592161075461
end
end
| 22.147059 | 72 | 0.664011 |
03ca41fef960405245316d75bb89d19bef2231cd | 1,892 | exs | Elixir | test/error_test.exs | supersimple/error | 28822a2c493a7ba0de9bf1a8286f79501589831e | [
"MIT"
] | null | null | null | test/error_test.exs | supersimple/error | 28822a2c493a7ba0de9bf1a8286f79501589831e | [
"MIT"
] | null | null | null | test/error_test.exs | supersimple/error | 28822a2c493a7ba0de9bf1a8286f79501589831e | [
"MIT"
] | null | null | null | defmodule ErrorTest do
use ExUnit.Case, async: true
alias Error
test "a domain error can be created with reason" do
assert Error.domain(:reason) == %Error{
kind: :domain,
reason: :reason,
details: %{}
}
end
test "a domain error can be created with reason and details" do
assert Error.domain(:reason, %{extra: :info}) == %Error{
kind: :domain,
reason: :reason,
details: %{extra: :info}
}
end
test "an infra error can be created with reason" do
assert Error.infra(:db_down) == %Error{
kind: :infra,
reason: :db_down,
details: %{}
}
end
test "an infra error can be created with reason and details" do
assert Error.infra(:db_down, %{retried_count: 5}) == %Error{
kind: :infra,
reason: :db_down,
details: %{retried_count: 5}
}
end
test "error kind can be accessed" do
error = Error.domain(:r, %{})
assert Error.kind(error) == :domain
end
test "error reason can be accessed" do
error = Error.domain(:a, %{c: :d})
assert Error.reason(error) == :a
end
test "error details can be accessed when set explicitly" do
error = Error.domain(:i, %{k: :l})
assert Error.details(error) == %{k: :l}
end
test "default error details can be accessed" do
error = Error.domain(:m)
assert Error.details(error) == %{}
end
test "details can be mapped over" do
error = Error.domain(:m, %{a: :b, c: :d})
error = Error.map_details(error, fn d -> Map.put(d, :e, :f) end)
assert Error.details(error) == %{a: :b, c: :d, e: :f}
end
test "it can be converted to map" do
error = Error.infra(:x, %{y: :z, a: "b"})
assert Error.to_map(error) == %{kind: :infra, reason: :x, details: %{y: :z, a: "b"}}
end
end
| 27.42029 | 88 | 0.563953 |
03ca5ed539ca0ba8cc0bc9d7557d5e90ff8b7770 | 6,181 | ex | Elixir | lib/strava/activity.ex | jsparling/strava | a3511520428dffd7ef9230a81f9a31533e3a052e | [
"MIT"
] | null | null | null | lib/strava/activity.ex | jsparling/strava | a3511520428dffd7ef9230a81f9a31533e3a052e | [
"MIT"
] | null | null | null | lib/strava/activity.ex | jsparling/strava | a3511520428dffd7ef9230a81f9a31533e3a052e | [
"MIT"
] | null | null | null | defmodule Strava.Activity do
@moduledoc """
Activities are the base object for Strava runs, rides, swims etc.
More info: https://strava.github.io/api/v3/activities/
"""
import Strava.Util, only: [parse_date: 1]
@type t :: %__MODULE__{
id: integer,
resource_state: integer,
external_id: String.t,
upload_id: integer,
athlete: Strava.Athlete.Meta.t,
name: String.t,
description: String.t,
distance: float,
moving_time: integer,
elapsed_time: integer,
total_elevation_gain: float,
elev_high: float,
elev_low: float,
type: String.t,
start_date: NaiveDateTime.t | String.t,
start_date_local: NaiveDateTime.t | String.t,
timezone: String.t,
start_latlng: list(number),
end_latlng: list(number),
achievement_count: integer,
kudos_count: integer,
comment_count: integer,
athlete_count: integer,
photo_count: integer,
total_photo_count: integer,
photos: Strava.Activity.Photo.Summary.t | nil,
map: map,
trainer: boolean,
commute: boolean,
manual: boolean,
private: boolean,
device_name: String.t,
embed_token: String.t,
flagged: boolean,
workout_type: integer,
gear_id: String.t,
gear: map,
average_speed: float,
max_speed: float,
average_cadence: float,
average_temp: float,
average_watts: float,
max_watts: integer,
weighted_average_watts: integer,
kilojoules: float,
device_watts: boolean,
has_heartrate: boolean,
average_heartrate: float,
max_heartrate: integer,
calories: float,
suffer_score: integer,
has_kudoed: boolean,
segment_efforts: list(Strava.SegmentEffort.t) | nil,
splits_metric: list(map),
splits_standard: list(map),
best_efforts: list(map)
}
defstruct [
:id,
:resource_state,
:external_id,
:upload_id,
:athlete,
:name,
:description,
:distance,
:moving_time,
:elapsed_time,
:total_elevation_gain,
:elev_high,
:elev_low,
:type,
:start_date,
:start_date_local,
:timezone,
:start_latlng,
:end_latlng,
:achievement_count,
:kudos_count,
:comment_count,
:athlete_count,
:photo_count,
:total_photo_count,
:photos,
:map,
:trainer,
:commute,
:manual,
:private,
:device_name,
:embed_token,
:flagged,
:workout_type,
:gear_id,
:gear,
:average_speed,
:max_speed,
:average_cadence,
:average_temp,
:average_watts,
:max_watts,
:weighted_average_watts,
:kilojoules,
:device_watts,
:has_heartrate,
:average_heartrate,
:max_heartrate,
:calories,
:suffer_score,
:has_kudoed,
:segment_efforts,
:splits_metric,
:splits_standard,
:best_efforts
]
defmodule Meta do
@type t :: %__MODULE__{
id: integer,
resource_state: integer
}
defstruct [
:id,
:resource_state
]
end
@doc """
Retrieve details about a specific activity.
## Example
Strava.Activity.retrieve(746805584)
Strava.Activity.retrieve(746805584, %{include_all_efforts: true})
More info: https://strava.github.io/api/v3/activities/#get-details
"""
@spec retrieve(integer, map, Strava.Client.t) :: Strava.Activity.t
def retrieve(id, filters \\ %{}, client \\ Strava.Client.new) do
"activities/#{id}?#{Strava.Util.query_string_no_pagination(filters)}"
|> Strava.request(client, as: %Strava.Activity{})
|> parse
end
@doc """
Retrieve a list of activities for the authenticated user. Pagination is supported.
## Example
activities = Strava.Activity.list_athlete_activities(%Strava.Pagination{per_page: 200, page: 1})
activities = Strava.Activity.list_athlete_activities(%Strava.Pagination{per_page: 200, page: 1}, Strava.Client.new("<access_token>>"))
activities = Strava.Activity.list_athlete_activities(%Strava.Pagination{per_page: 200, page: 1}, {before: "2017-04-20T00:00:12Z"})
More info: https://strava.github.io/api/v3/activities/#get-activities
"""
@spec list_athlete_activities(Strava.Pagination.t, map, Strava.Client.t) :: list(Strava.Activity.t)
def list_athlete_activities(pagination, filters \\ %{}, client \\ Strava.Client.new) do
"athlete/activities?#{Strava.Util.query_string(pagination, filters)}"
|> Strava.request(client, as: [%Strava.Activity{}])
|> Enum.map(&Strava.Activity.parse/1)
end
@doc """
Parse the athlete, dates, photos and segment efforts in the activity
"""
@spec parse(Strava.Activity.t) :: Strava.Activity.t
def parse(%Strava.Activity{} = activity) do
activity
|> parse_athlete
|> parse_dates
|> parse_photos
|> parse_segment_efforts
end
@spec parse_athlete(Strava.Activity.t) :: Strava.Activity.t
defp parse_athlete(%Strava.Activity{athlete: athlete} = activity) do
%Strava.Activity{activity |
athlete: struct(Strava.Athlete.Meta, athlete)
}
end
@spec parse_dates(Strava.Activity.t) :: Strava.Activity.t
defp parse_dates(%Strava.Activity{start_date: start_date, start_date_local: start_date_local} = activity) do
%Strava.Activity{activity |
start_date: parse_date(start_date),
start_date_local: parse_date(start_date_local)
}
end
@spec parse_photos(Strava.Activity.t) :: Strava.Activity.t
defp parse_photos(activity)
defp parse_photos(%Strava.Activity{photos: nil} = activity), do: activity
defp parse_photos(%Strava.Activity{photos: photos} = activity) do
%Strava.Activity{activity |
photos: Strava.Activity.Photo.Summary.parse(struct(Strava.Activity.Photo.Summary, photos))
}
end
@spec parse_segment_efforts(Strava.Activity.t) :: Strava.Activity.t
defp parse_segment_efforts(activity)
defp parse_segment_efforts(%Strava.Activity{segment_efforts: nil} = activity), do: activity
defp parse_segment_efforts(%Strava.Activity{segment_efforts: segment_efforts} = activity) do
%Strava.Activity{activity |
segment_efforts: Enum.map(segment_efforts, fn segment_effort ->
Strava.SegmentEffort.parse(struct(Strava.SegmentEffort, segment_effort))
end)
}
end
end
| 27.717489 | 140 | 0.686135 |
03ca789301cc4524bf91b88e2d09655e29ac41a0 | 2,538 | exs | Elixir | apps/engine/test/engine/ethereum/event/coordinator_test.exs | omgnetwork/omg-childchain-v2 | 31cc9cf9e42718fc3b9bd6668f24a627cac80b4f | [
"Apache-2.0"
] | 4 | 2020-11-30T17:38:57.000Z | 2021-01-23T21:29:41.000Z | apps/engine/test/engine/ethereum/event/coordinator_test.exs | omgnetwork/omg-childchain-v2 | 31cc9cf9e42718fc3b9bd6668f24a627cac80b4f | [
"Apache-2.0"
] | 24 | 2020-11-30T17:32:48.000Z | 2021-02-22T06:25:22.000Z | apps/engine/test/engine/ethereum/event/coordinator_test.exs | omgnetwork/omg-childchain-v2 | 31cc9cf9e42718fc3b9bd6668f24a627cac80b4f | [
"Apache-2.0"
] | null | null | null | defmodule Engine.Ethereum.Event.CoordinatorTest do
use ExUnit.Case, async: true
alias Engine.Ethereum.Event.Coordinator.Core
alias Engine.Ethereum.Event.Coordinator.Setup
setup do
{_args, config_services} = Setup.coordinator_setup(1, 1)
init = Core.init(config_services, 10)
pid =
config_services
|> Map.keys()
|> Enum.with_index(1)
|> Enum.into(%{}, fn {key, idx} -> {key, :c.pid(0, idx, 0)} end)
{:ok, %{state: initial_check_in(init, Map.keys(config_services), pid), pid: pid}}
end
test "syncs services correctly", %{state: state, pid: pid} do
# NOTE: this assumes some finality margines embedded in `config/test.exs`. Consider refactoring if these
# needs to change and break this test, instead of modifying this test!
# start - only depositor and getter allowed to move
assert %{sync_height: 9, root_chain_height: 9} = Core.get_synced_info(state, pid[:depositor])
assert %{sync_height: 0, root_chain_height: 9} = Core.get_synced_info(state, pid[:standard_exiter])
assert %{sync_height: 0, root_chain_height: 9} = Core.get_synced_info(state, pid[:in_flight_exiter])
# depositor advances
assert {:ok, state} = Core.check_in(state, pid[:depositor], 10, :depositor)
assert %{sync_height: 9, root_chain_height: 9} = Core.get_synced_info(state, pid[:standard_exiter])
assert %{sync_height: 9, root_chain_height: 9} = Core.get_synced_info(state, pid[:in_flight_exiter])
# in_flight_exit advances
assert %{sync_height: 0, root_chain_height: 9} = Core.get_synced_info(state, pid[:piggybacker])
assert {:ok, state} = Core.check_in(state, pid[:in_flight_exiter], 10, :in_flight_exiter)
assert %{sync_height: 9, root_chain_height: 9} = Core.get_synced_info(state, pid[:piggybacker])
# root chain advances
assert {:ok, state} = Core.update_root_chain_height(state, 100)
assert %{sync_height: 99, root_chain_height: 99} = Core.get_synced_info(state, pid[:depositor])
assert %{sync_height: 10, root_chain_height: 99} = Core.get_synced_info(state, pid[:standard_exiter])
assert %{sync_height: 10, root_chain_height: 99} = Core.get_synced_info(state, pid[:in_flight_exiter])
assert %{sync_height: 10, root_chain_height: 99} = Core.get_synced_info(state, pid[:piggybacker])
end
defp initial_check_in(state, services, pid) do
{:ok, state} =
Enum.reduce(services, {:ok, state}, fn service, {:ok, state} ->
Core.check_in(state, pid[service], 0, service)
end)
state
end
end
| 46.145455 | 108 | 0.704886 |
03ca868e84857075b767732f75520082a12441d0 | 483 | ex | Elixir | exercises/concept/language-list/lib/language_list.ex | kwchang0831/elixir | 1b21ae1ca610de97db79e76db890503ba75ce466 | [
"MIT"
] | null | null | null | exercises/concept/language-list/lib/language_list.ex | kwchang0831/elixir | 1b21ae1ca610de97db79e76db890503ba75ce466 | [
"MIT"
] | null | null | null | exercises/concept/language-list/lib/language_list.ex | kwchang0831/elixir | 1b21ae1ca610de97db79e76db890503ba75ce466 | [
"MIT"
] | null | null | null | defmodule LanguageList do
def new() do
# Please implement the new/0 function
end
def add(list, language) do
# Please implement the add/2 function
end
def remove(list) do
# Please implement the remove/1 function
end
def first(list) do
# Please implement the first/1 function
end
def count(list) do
# Please implement the count/1 function
end
def functional_list?(list) do
# Please implement the functional_list?/1 function
end
end
| 18.576923 | 54 | 0.699793 |
03cac148bd5b90585add479144481ee0fa355661 | 1,117 | exs | Elixir | config/config.exs | travisjeffery/stathat | 15c0bf61de4188b0128f83f367a8aa94b870e4b4 | [
"MIT"
] | null | null | null | config/config.exs | travisjeffery/stathat | 15c0bf61de4188b0128f83f367a8aa94b870e4b4 | [
"MIT"
] | null | null | null | config/config.exs | travisjeffery/stathat | 15c0bf61de4188b0128f83f367a8aa94b870e4b4 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :stathat, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:stathat, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.032258 | 73 | 0.751119 |
03cae2f2cb768f7641c6104c508207d997a63ecf | 2,433 | ex | Elixir | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/ssl_certs_insert_response.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/ssl_certs_insert_response.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/ssl_certs_insert_response.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.SQLAdmin.V1beta4.Model.SslCertsInsertResponse do
@moduledoc """
SslCert insert response.
## Attributes
* `clientCert` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.SslCertDetail.t`, *default:* `nil`) - The new client certificate and private key.
* `kind` (*type:* `String.t`, *default:* `nil`) - This is always *sql#sslCertsInsert*.
* `operation` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.Operation.t`, *default:* `nil`) - The operation to track the ssl certs insert request.
* `serverCaCert` (*type:* `GoogleApi.SQLAdmin.V1beta4.Model.SslCert.t`, *default:* `nil`) - The server Certificate Authority's certificate. If this is missing you can force a new one to be generated by calling resetSslConfig method on instances resource.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:clientCert => GoogleApi.SQLAdmin.V1beta4.Model.SslCertDetail.t() | nil,
:kind => String.t() | nil,
:operation => GoogleApi.SQLAdmin.V1beta4.Model.Operation.t() | nil,
:serverCaCert => GoogleApi.SQLAdmin.V1beta4.Model.SslCert.t() | nil
}
field(:clientCert, as: GoogleApi.SQLAdmin.V1beta4.Model.SslCertDetail)
field(:kind)
field(:operation, as: GoogleApi.SQLAdmin.V1beta4.Model.Operation)
field(:serverCaCert, as: GoogleApi.SQLAdmin.V1beta4.Model.SslCert)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.SslCertsInsertResponse do
def decode(value, options) do
GoogleApi.SQLAdmin.V1beta4.Model.SslCertsInsertResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.SslCertsInsertResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.446429 | 258 | 0.73695 |
03caf6237c01ffff912b343e593fa71ce22079cc | 1,204 | ex | Elixir | token_registry/lib/token_registry_web/live/blockchain_live/index.ex | canuckasaurus/archeio-solanaszn | 55dc8712cf0409d110ae342cbbc620745668a4df | [
"MIT"
] | 1 | 2021-12-18T16:17:19.000Z | 2021-12-18T16:17:19.000Z | token_registry/lib/token_registry_web/live/blockchain_live/index.ex | canuckasaurus/archeio-solanaszn | 55dc8712cf0409d110ae342cbbc620745668a4df | [
"MIT"
] | null | null | null | token_registry/lib/token_registry_web/live/blockchain_live/index.ex | canuckasaurus/archeio-solanaszn | 55dc8712cf0409d110ae342cbbc620745668a4df | [
"MIT"
] | null | null | null | defmodule TokenRegistryWeb.BlockchainLive.Index do
use TokenRegistryWeb, :live_view
alias TokenRegistry.Registry
alias TokenRegistry.Registry.Blockchain
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, :blockchains, list_blockchains())}
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Blockchain")
|> assign(:blockchain, Registry.get_blockchain!(id))
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Blockchain")
|> assign(:blockchain, %Blockchain{})
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Blockchains")
|> assign(:blockchain, nil)
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
blockchain = Registry.get_blockchain!(id)
{:ok, _} = Registry.delete_blockchain(blockchain)
{:noreply, assign(socket, :blockchains, list_blockchains())}
end
defp list_blockchains do
Registry.list_blockchains()
end
end
| 25.617021 | 72 | 0.697674 |
03cb1a6a64d4d9706713e206fdd18cc2e95dd993 | 1,038 | ex | Elixir | lib/citrine/job.ex | brndnmtthws/citrine | ff815f7ed921abbde658ca4ba7b6aea68b6c0f5f | [
"MIT"
] | 8 | 2020-08-06T03:08:31.000Z | 2021-12-15T08:41:59.000Z | lib/citrine/job.ex | brndnmtthws/citrine | ff815f7ed921abbde658ca4ba7b6aea68b6c0f5f | [
"MIT"
] | 1 | 2020-10-18T19:48:09.000Z | 2020-10-26T16:40:25.000Z | lib/citrine/job.ex | brndnmtthws/citrine | ff815f7ed921abbde658ca4ba7b6aea68b6c0f5f | [
"MIT"
] | 2 | 2020-10-23T12:28:21.000Z | 2021-01-09T20:44:37.000Z | defmodule Citrine.Job do
@typedoc """
The job task to run.
"""
@type task :: {module(), atom, [term()]} | {atom, [term()]} | (() -> any)
@typedoc """
A unique ID for this job.
"""
@type jobid :: String.t()
@typedoc """
Cron-based schedule specification.
"""
@type schedule :: String.t()
@type t :: %__MODULE__{
id: jobid(),
schedule: String.t(),
extended_syntax: boolean(),
task: task()
}
@enforce_keys [:id, :schedule, :task]
@doc """
Struct that describes a job. Must specify a unique `:id`, a `:schedule` using
cron syntax, and a task. If `:extended_syntax` is set to `true`, the schedule
will be parsed as extended cron syntax by `Crontab.CronExpression.Parser`.
## Example
iex(1)> job = %Citrine.Job{
...(1)> id: "my-job-id",
...(1)> schedule: "* * * * * *",
...(1)> task: fn -> nil end,
...(1)> extended_syntax: true
...(1)> }
"""
defstruct [:id, :schedule, :task, extended_syntax: false]
end
| 25.95 | 79 | 0.547206 |
03cb452d1254c6dbf8957fc6826a43d7c11f276b | 323 | exs | Elixir | priv/repo/migrations/20170926193403_create_pages.exs | reubenbrown13/website | 75d5d6bbf8f75d9837a3427c22060096604f5070 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170926193403_create_pages.exs | reubenbrown13/website | 75d5d6bbf8f75d9837a3427c22060096604f5070 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170926193403_create_pages.exs | reubenbrown13/website | 75d5d6bbf8f75d9837a3427c22060096604f5070 | [
"MIT"
] | 1 | 2020-11-21T20:12:01.000Z | 2020-11-21T20:12:01.000Z | defmodule Contento.Repo.Migrations.CreatePages do
use Ecto.Migration
def change do
create table(:pages) do
add :slug, :string
add :title, :string
add :content, :string
add :published, :boolean, default: false
add :published_at, :naive_datetime
timestamps()
end
end
end
| 17.944444 | 49 | 0.653251 |
03cb5dcb95a5ca3b8fe3cb54758792b843bfd8b1 | 785 | ex | Elixir | lib/ash_json_api/controllers/patch_relationship.ex | peillis/ash_json_api | f63ccacebc049eba8d37b8b58181fb46a4a0ea8c | [
"MIT"
] | null | null | null | lib/ash_json_api/controllers/patch_relationship.ex | peillis/ash_json_api | f63ccacebc049eba8d37b8b58181fb46a4a0ea8c | [
"MIT"
] | null | null | null | lib/ash_json_api/controllers/patch_relationship.ex | peillis/ash_json_api | f63ccacebc049eba8d37b8b58181fb46a4a0ea8c | [
"MIT"
] | null | null | null | defmodule AshJsonApi.Controllers.PatchRelationship do
@moduledoc false
alias AshJsonApi.Controllers.{Helpers, Response}
alias AshJsonApi.Request
def init(options) do
# initialize options
options
end
def call(conn, options) do
action = options[:action]
api = options[:api]
route = options[:route]
relationship = Ash.Resource.Info.relationship(options[:resource], route.relationship)
resource = relationship.destination
conn
|> Request.from(resource, action, api, route)
|> Helpers.fetch_record_from_path(options[:resource])
|> Helpers.replace_relationship(relationship.name)
|> Helpers.render_or_render_errors(conn, fn request ->
Response.render_many_relationship(conn, request, 200, relationship)
end)
end
end
| 29.074074 | 89 | 0.73121 |
03cb763ea2b1fe7a7b514957309688eacf56003a | 1,172 | ex | Elixir | lib/elixir/lib/agent/server.ex | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 19,291 | 2015-01-01T02:42:49.000Z | 2022-03-31T21:01:40.000Z | lib/elixir/lib/agent/server.ex | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 8,082 | 2015-01-01T04:16:23.000Z | 2022-03-31T22:08:02.000Z | lib/elixir/lib/agent/server.ex | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 3,472 | 2015-01-03T04:11:56.000Z | 2022-03-29T02:07:30.000Z | defmodule Agent.Server do
@moduledoc false
use GenServer
def init(fun) do
_ = initial_call(fun)
{:ok, run(fun, [])}
end
def handle_call({:get, fun}, _from, state) do
{:reply, run(fun, [state]), state}
end
def handle_call({:get_and_update, fun}, _from, state) do
case run(fun, [state]) do
{reply, state} -> {:reply, reply, state}
other -> {:stop, {:bad_return_value, other}, state}
end
end
def handle_call({:update, fun}, _from, state) do
{:reply, :ok, run(fun, [state])}
end
def handle_cast({:cast, fun}, state) do
{:noreply, run(fun, [state])}
end
def code_change(_old, state, fun) do
{:ok, run(fun, [state])}
end
defp initial_call(mfa) do
_ = Process.put(:"$initial_call", get_initial_call(mfa))
:ok
end
defp get_initial_call(fun) when is_function(fun, 0) do
{:module, module} = Function.info(fun, :module)
{:name, name} = Function.info(fun, :name)
{module, name, 0}
end
defp get_initial_call({mod, fun, args}) do
{mod, fun, length(args)}
end
defp run({m, f, a}, extra), do: apply(m, f, extra ++ a)
defp run(fun, extra), do: apply(fun, extra)
end
| 22.538462 | 60 | 0.612628 |
03cb920af108b47357ed27361224594330e7858b | 253 | ex | Elixir | lib/quiz_site.ex | rbgraham/quiz_site | 57ded7991e355e2cf9f5edecc823b67833ee0ceb | [
"MIT"
] | 2 | 2017-10-30T00:42:01.000Z | 2017-10-30T21:29:15.000Z | lib/quiz_site.ex | rbgraham/quiz_site | 57ded7991e355e2cf9f5edecc823b67833ee0ceb | [
"MIT"
] | null | null | null | lib/quiz_site.ex | rbgraham/quiz_site | 57ded7991e355e2cf9f5edecc823b67833ee0ceb | [
"MIT"
] | null | null | null | defmodule QuizSite do
@moduledoc """
QuizSite keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 25.3 | 66 | 0.754941 |
03cbe2588deeab55d8c4c46cc1b8ca129d00f30b | 181 | ex | Elixir | lib/delivery_web/controllers/welcome_controller.ex | joaoeliandro/delivery | f8f2ea20a0fa595ccd754a725cfadf35a8c89c69 | [
"MIT"
] | null | null | null | lib/delivery_web/controllers/welcome_controller.ex | joaoeliandro/delivery | f8f2ea20a0fa595ccd754a725cfadf35a8c89c69 | [
"MIT"
] | null | null | null | lib/delivery_web/controllers/welcome_controller.ex | joaoeliandro/delivery | f8f2ea20a0fa595ccd754a725cfadf35a8c89c69 | [
"MIT"
] | null | null | null | defmodule DeliveryWeb.WelcomeController do
use DeliveryWeb, :controller
def index(conn, params) do
conn
|> put_status(:ok)
|> json(%{message: "Welcome"})
end
end
| 18.1 | 42 | 0.679558 |
03cbe25d575db8ac45cd76bd35731b30a79d5e1a | 848 | exs | Elixir | config/test.exs | prashantpawar/kitteh-test | 8b5b9e8a080b495ea6f506597a1bb66be56de064 | [
"MIT"
] | null | null | null | config/test.exs | prashantpawar/kitteh-test | 8b5b9e8a080b495ea6f506597a1bb66be56de064 | [
"MIT"
] | null | null | null | config/test.exs | prashantpawar/kitteh-test | 8b5b9e8a080b495ea6f506597a1bb66be56de064 | [
"MIT"
] | null | null | null | use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :kitteh_test, KittehTest.Endpoint,
http: [port: 4001],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :kitteh_test, KittehTest.Repo,
adapter: Ecto.Adapters.Postgres,
hostname: System.get_env("PG_HOST") || "localhost",
username: System.get_env("PG_USER") || "postgres",
password: System.get_env("PG_PASS") || "postgres",
database: "kitteh_test_test",
pool: Ecto.Adapters.SQL.Sandbox
config :guardian, Guardian,
secret_key: "SOME FAKE LONG SECRET KEY THAT WORKS FOR TESTS 1234567890 1234567890"
config :kitteh_test, KittehTest.Endpoint,
secret_key_base: "SOME FAKE LONG SECRET KEY BASE THAT WORKS FOR TESTS 1234567890 1234567890"
| 32.615385 | 94 | 0.754717 |
03cc04d32febb685d4c89c33c5f556ebe0724b7d | 3,721 | ex | Elixir | clients/service_user/lib/google_api/service_user/v1/model/auth_provider.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_user/lib/google_api/service_user/v1/model/auth_provider.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_user/lib/google_api/service_user/v1/model/auth_provider.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.ServiceUser.V1.Model.AuthProvider do
@moduledoc """
Configuration for an authentication provider, including support for
[JSON Web Token
(JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32).
## Attributes
* `audiences` (*type:* `String.t`, *default:* `nil`) - The list of JWT
[audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
that are allowed to access. A JWT containing any of these audiences will
be accepted. When this setting is absent, only JWTs with audience
"https://Service_name/API_name"
will be accepted. For example, if no audiences are in the setting,
LibraryService API will only accept JWTs with the following audience
"https://library-example.googleapis.com/google.example.library.v1.LibraryService".
Example:
audiences: bookstore_android.apps.googleusercontent.com,
bookstore_web.apps.googleusercontent.com
* `authorizationUrl` (*type:* `String.t`, *default:* `nil`) - Redirect URL if JWT token is required but not present or is expired.
Implement authorizationUrl of securityDefinitions in OpenAPI spec.
* `id` (*type:* `String.t`, *default:* `nil`) - The unique identifier of the auth provider. It will be referred to by
`AuthRequirement.provider_id`.
Example: "bookstore_auth".
* `issuer` (*type:* `String.t`, *default:* `nil`) - Identifies the principal that issued the JWT. See
https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1
Usually a URL or an email address.
Example: https://securetoken.google.com
Example: 1234567-compute@developer.gserviceaccount.com
* `jwksUri` (*type:* `String.t`, *default:* `nil`) - URL of the provider's public key set to validate signature of the JWT. See
[OpenID
Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata).
Optional if the key set document:
- can be retrieved from
[OpenID
Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html of
the issuer.
- can be inferred from the email domain of the issuer (e.g. a Google
service account).
Example: https://www.googleapis.com/oauth2/v1/certs
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:audiences => String.t(),
:authorizationUrl => String.t(),
:id => String.t(),
:issuer => String.t(),
:jwksUri => String.t()
}
field(:audiences)
field(:authorizationUrl)
field(:id)
field(:issuer)
field(:jwksUri)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceUser.V1.Model.AuthProvider do
def decode(value, options) do
GoogleApi.ServiceUser.V1.Model.AuthProvider.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceUser.V1.Model.AuthProvider do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.010753 | 134 | 0.698468 |
03cc0b5e1f991fd62b1b622d153aa280bdf57a72 | 169,965 | ex | Elixir | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/api/projects.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/api/projects.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/api/projects.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudRun.V1alpha1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.CloudRun.V1alpha1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Lists information about the supported locations for this service.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. 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`) - 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.CloudRun.V1alpha1.Model.ListLocationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListLocationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_list(connection, projects_id, 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("/v1alpha1/projects/{projectsId}/locations", %{
"projectsId" => URI.encode(projects_id, &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.CloudRun.V1alpha1.Model.ListLocationsResponse{}]
)
end
@doc """
RPC to list authorized domains.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Name of the parent Application resource. Example: `apps/myapp`.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:pageSize` (*type:* `integer()`) - Maximum results to return per page.
* `:pageToken` (*type:* `String.t`) - Continuation token for fetching the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListAuthorizedDomainsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_authorizeddomains_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListAuthorizedDomainsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_authorizeddomains_list(
connection,
projects_id,
locations_id,
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,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/authorizeddomains",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListAuthorizedDomainsResponse{}]
)
end
@doc """
Creates a new cloudauditlogssource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number in which this cloudauditlogssource should
be created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudAuditLogsSource.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.CloudAuditLogsSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudauditlogssources_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudAuditLogsSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudauditlogssources_create(
connection,
projects_id,
locations_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudauditlogssources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.CloudAuditLogsSource{}]
)
end
@doc """
Rpc to delete a cloudauditlogssource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the cloudauditlogssource being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudauditlogssources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudauditlogssources_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudauditlogssources_delete(
connection,
projects_id,
locations_id,
cloudauditlogssources_id,
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,
:apiVersion => :query,
:kind => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudauditlogssources/{cloudauditlogssourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudauditlogssourcesId" =>
URI.encode(cloudauditlogssources_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a cloudauditlogssource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the cloudauditlogssource being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudauditlogssources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudAuditLogsSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudauditlogssources_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudAuditLogsSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudauditlogssources_get(
connection,
projects_id,
locations_id,
cloudauditlogssources_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudauditlogssources/{cloudauditlogssourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudauditlogssourcesId" =>
URI.encode(cloudauditlogssources_id, &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.CloudRun.V1alpha1.Model.CloudAuditLogsSource{}]
)
end
@doc """
Rpc to list cloudauditlogssources.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the cloudauditlogssources
should be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListCloudAuditLogsSourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudauditlogssources_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListCloudAuditLogsSourcesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudauditlogssources_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudauditlogssources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListCloudAuditLogsSourcesResponse{}]
)
end
@doc """
Creates a new cloudpubsubsource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number in which this cloudpubsubsource should
be created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudPubSubSource.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.CloudPubSubSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudpubsubsources_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudPubSubSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudpubsubsources_create(
connection,
projects_id,
locations_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudpubsubsources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.CloudPubSubSource{}])
end
@doc """
Rpc to delete a cloudpubsubsource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the cloudpubsubsource being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudpubsubsources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudpubsubsources_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudpubsubsources_delete(
connection,
projects_id,
locations_id,
cloudpubsubsources_id,
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,
:apiVersion => :query,
:kind => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudpubsubsources/{cloudpubsubsourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudpubsubsourcesId" => URI.encode(cloudpubsubsources_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a cloudpubsubsource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the cloudpubsubsource being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudpubsubsources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudPubSubSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudpubsubsources_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudPubSubSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudpubsubsources_get(
connection,
projects_id,
locations_id,
cloudpubsubsources_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudpubsubsources/{cloudpubsubsourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudpubsubsourcesId" => URI.encode(cloudpubsubsources_id, &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.CloudRun.V1alpha1.Model.CloudPubSubSource{}])
end
@doc """
Rpc to list cloudpubsubsources.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the cloudpubsubsources should
be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListCloudPubSubSourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudpubsubsources_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListCloudPubSubSourcesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudpubsubsources_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudpubsubsources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListCloudPubSubSourcesResponse{}]
)
end
@doc """
Creates a new cloudschedulersource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The project ID or project number in which this cloudschedulersource should
be created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudSchedulerSource.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.CloudSchedulerSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudschedulersources_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudSchedulerSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudschedulersources_create(
connection,
projects_id,
locations_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudschedulersources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.CloudSchedulerSource{}]
)
end
@doc """
Rpc to delete a cloudschedulersource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the cloudschedulersource being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudschedulersources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudschedulersources_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudschedulersources_delete(
connection,
projects_id,
locations_id,
cloudschedulersources_id,
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,
:apiVersion => :query,
:kind => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudschedulersources/{cloudschedulersourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudschedulersourcesId" =>
URI.encode(cloudschedulersources_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a cloudschedulersource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the cloudschedulersource being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudschedulersources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudSchedulerSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudschedulersources_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudSchedulerSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudschedulersources_get(
connection,
projects_id,
locations_id,
cloudschedulersources_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudschedulersources/{cloudschedulersourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudschedulersourcesId" =>
URI.encode(cloudschedulersources_id, &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.CloudRun.V1alpha1.Model.CloudSchedulerSource{}]
)
end
@doc """
Rpc to list cloudschedulersources.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The project ID or project number from which the cloudschedulersources
should be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListCloudSchedulerSourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudschedulersources_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListCloudSchedulerSourcesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudschedulersources_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudschedulersources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListCloudSchedulerSourcesResponse{}]
)
end
@doc """
Rpc to replace a cloudschedulersource.
Only the spec and metadata labels and annotations are modifiable. After
the Update request, Cloud Run will work to make the 'status'
match the requested 'spec'.
May provide metadata.resourceVersion to enforce update from last read for
optimistic concurrency control.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the cloudschedulersource being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudschedulersources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudSchedulerSource.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.CloudSchedulerSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudschedulersources_replace_cloud_scheduler_source(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudSchedulerSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudschedulersources_replace_cloud_scheduler_source(
connection,
projects_id,
locations_id,
cloudschedulersources_id,
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(:put)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudschedulersources/{cloudschedulersourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudschedulersourcesId" =>
URI.encode(cloudschedulersources_id, &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.CloudRun.V1alpha1.Model.CloudSchedulerSource{}]
)
end
@doc """
Creates a new cloudstoragesource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The project ID or project number in which this cloudstoragesource should
be created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudStorageSource.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.CloudStorageSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudstoragesources_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudStorageSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudstoragesources_create(
connection,
projects_id,
locations_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudstoragesources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.CloudStorageSource{}])
end
@doc """
Rpc to delete a cloudstoragesource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the cloudstoragesource being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudstoragesources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudstoragesources_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudstoragesources_delete(
connection,
projects_id,
locations_id,
cloudstoragesources_id,
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,
:apiVersion => :query,
:kind => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudstoragesources/{cloudstoragesourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudstoragesourcesId" => URI.encode(cloudstoragesources_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a cloudstoragesource.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the cloudstoragesource being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudstoragesources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudStorageSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudstoragesources_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudStorageSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudstoragesources_get(
connection,
projects_id,
locations_id,
cloudstoragesources_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudstoragesources/{cloudstoragesourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudstoragesourcesId" => URI.encode(cloudstoragesources_id, &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.CloudRun.V1alpha1.Model.CloudStorageSource{}])
end
@doc """
Rpc to list cloudstoragesources.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The project ID or project number from which the cloudstoragesources should
be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListCloudStorageSourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudstoragesources_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListCloudStorageSourcesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudstoragesources_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudstoragesources",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListCloudStorageSourcesResponse{}]
)
end
@doc """
Rpc to replace a cloudstoragesource.
Only the spec and metadata labels and annotations are modifiable. After
the Update request, Cloud Run will work to make the 'status'
match the requested 'spec'.
May provide metadata.resourceVersion to enforce update from last read for
optimistic concurrency control.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The name of the cloudstoragesource being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `cloudstoragesources_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.CloudStorageSource.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.CloudStorageSource{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_cloudstoragesources_replace_cloud_storage_source(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.CloudStorageSource.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_cloudstoragesources_replace_cloud_storage_source(
connection,
projects_id,
locations_id,
cloudstoragesources_id,
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(:put)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/cloudstoragesources/{cloudstoragesourcesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"cloudstoragesourcesId" => URI.encode(cloudstoragesources_id, &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.CloudRun.V1alpha1.Model.CloudStorageSource{}])
end
@doc """
Rpc to get information about a configuration.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the configuration being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `configurations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Configuration{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_configurations_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Configuration.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_configurations_get(
connection,
projects_id,
locations_id,
configurations_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/configurations/{configurationsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"configurationsId" => URI.encode(configurations_id, &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.CloudRun.V1alpha1.Model.Configuration{}])
end
@doc """
Rpc to list configurations.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the configurations should be
listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListConfigurationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_configurations_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListConfigurationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_configurations_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/projects/{projectsId}/locations/{locationsId}/configurations", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListConfigurationsResponse{}]
)
end
@doc """
Creates a new domain mapping.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number in which this domain mapping should be
created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.DomainMapping.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.DomainMapping{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_domainmappings_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.DomainMapping.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_domainmappings_create(
connection,
projects_id,
locations_id,
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("/v1alpha1/projects/{projectsId}/locations/{locationsId}/domainmappings", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.DomainMapping{}])
end
@doc """
Rpc to delete a domain mapping.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the domain mapping being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `domainmappings_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:orphanDependents` (*type:* `boolean()`) - Deprecated.
Specifies the cascade behavior on delete.
Cloud Run only supports cascading behavior, so this must be false.
This attribute is deprecated, and is now replaced with PropagationPolicy
See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_domainmappings_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_domainmappings_delete(
connection,
projects_id,
locations_id,
domainmappings_id,
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,
:apiVersion => :query,
:kind => :query,
:orphanDependents => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/domainmappings/{domainmappingsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"domainmappingsId" => URI.encode(domainmappings_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a domain mapping.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the domain mapping being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `domainmappings_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.DomainMapping{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_domainmappings_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.DomainMapping.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_domainmappings_get(
connection,
projects_id,
locations_id,
domainmappings_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/domainmappings/{domainmappingsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"domainmappingsId" => URI.encode(domainmappings_id, &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.CloudRun.V1alpha1.Model.DomainMapping{}])
end
@doc """
Rpc to list domain mappings.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the domain mappings should be
listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListDomainMappingsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_domainmappings_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListDomainMappingsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_domainmappings_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/projects/{projectsId}/locations/{locationsId}/domainmappings", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListDomainMappingsResponse{}]
)
end
@doc """
Rpc to delete a revision.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the revision being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `revisions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:orphanDependents` (*type:* `boolean()`) - Deprecated.
Specifies the cascade behavior on delete.
Cloud Run only supports cascading behavior, so this must be false.
This attribute is deprecated, and is now replaced with PropagationPolicy
See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_revisions_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_revisions_delete(
connection,
projects_id,
locations_id,
revisions_id,
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,
:apiVersion => :query,
:kind => :query,
:orphanDependents => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/revisions/{revisionsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"revisionsId" => URI.encode(revisions_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a revision.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the revision being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `revisions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Revision{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_revisions_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Revision.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_revisions_get(
connection,
projects_id,
locations_id,
revisions_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/revisions/{revisionsId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"revisionsId" => URI.encode(revisions_id, &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.CloudRun.V1alpha1.Model.Revision{}])
end
@doc """
Rpc to list revisions.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the revisions should be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListRevisionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_revisions_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListRevisionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_revisions_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/projects/{projectsId}/locations/{locationsId}/revisions", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListRevisionsResponse{}]
)
end
@doc """
Rpc to get information about a route.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the route being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `routes_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Route{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_routes_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Route.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_routes_get(
connection,
projects_id,
locations_id,
routes_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/routes/{routesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"routesId" => URI.encode(routes_id, &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.CloudRun.V1alpha1.Model.Route{}])
end
@doc """
Rpc to list routes.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the routes should be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListRoutesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_routes_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListRoutesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_routes_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/projects/{projectsId}/locations/{locationsId}/routes", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListRoutesResponse{}])
end
@doc """
Rpc to create a service.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number in which this service should be created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Service.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Service{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Service.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_create(
connection,
projects_id,
locations_id,
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("/v1alpha1/projects/{projectsId}/locations/{locationsId}/services", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.Service{}])
end
@doc """
Rpc to delete a service.
This will cause the Service to stop serving traffic and will delete the
child entities like Routes, Configurations and Revisions.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the service being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `services_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:orphanDependents` (*type:* `boolean()`) - Deprecated.
Specifies the cascade behavior on delete.
Cloud Run only supports cascading behavior, so this must be false.
This attribute is deprecated, and is now replaced with PropagationPolicy
See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_delete(
connection,
projects_id,
locations_id,
services_id,
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,
:apiVersion => :query,
:kind => :query,
:orphanDependents => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/services/{servicesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"servicesId" => URI.encode(services_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a service.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the service being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `services_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Service{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Service.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_get(
connection,
projects_id,
locations_id,
services_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/services/{servicesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"servicesId" => URI.encode(services_id, &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.CloudRun.V1alpha1.Model.Service{}])
end
@doc """
Get the IAM Access Control policy currently in effect for the given
Cloud Run service. This result does not include any inherited policies.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested.
See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `services_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_get_iam_policy(
connection,
projects_id,
locations_id,
services_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/services/{servicesId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"servicesId" => URI.encode(services_id, &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.CloudRun.V1alpha1.Model.Policy{}])
end
@doc """
Rpc to list services.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the services should be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListServicesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListServicesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/projects/{projectsId}/locations/{locationsId}/services", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListServicesResponse{}]
)
end
@doc """
Rpc to replace a service.
Only the spec and metadata labels and annotations are modifiable. After
the Update request, Cloud Run will work to make the 'status'
match the requested 'spec'.
May provide metadata.resourceVersion to enforce update from last read for
optimistic concurrency control.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the service being replaced. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `services_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Service.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Service{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_replace_service(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Service.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_replace_service(
connection,
projects_id,
locations_id,
services_id,
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(:put)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/services/{servicesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"servicesId" => URI.encode(services_id, &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.CloudRun.V1alpha1.Model.Service{}])
end
@doc """
Sets the IAM Access control policy for the specified Service. Overwrites
any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified.
See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `services_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_set_iam_policy(
connection,
projects_id,
locations_id,
services_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/services/{servicesId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"servicesId" => URI.encode(services_id, &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.CloudRun.V1alpha1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified Project.
There are no permissions required for making this API call.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested.
See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `services_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_services_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_services_test_iam_permissions(
connection,
projects_id,
locations_id,
services_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/services/{servicesId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"servicesId" => URI.encode(services_id, &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.CloudRun.V1alpha1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Creates a new trigger.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number in which this trigger should
be created.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Trigger.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Trigger{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_triggers_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Trigger.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_triggers_create(
connection,
projects_id,
locations_id,
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("/v1alpha1/projects/{projectsId}/locations/{locationsId}/triggers", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.Trigger{}])
end
@doc """
Rpc to delete a trigger.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the trigger being deleted. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `triggers_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:apiVersion` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:kind` (*type:* `String.t`) - Cloud Run currently ignores this parameter.
* `:propagationPolicy` (*type:* `String.t`) - Specifies the propagation policy of delete. Cloud Run currently ignores
this setting, and deletes in the background. Please see
kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
more information.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_triggers_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_triggers_delete(
connection,
projects_id,
locations_id,
triggers_id,
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,
:apiVersion => :query,
:kind => :query,
:propagationPolicy => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/triggers/{triggersId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"triggersId" => URI.encode(triggers_id, &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.CloudRun.V1alpha1.Model.Empty{}])
end
@doc """
Rpc to get information about a trigger.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the trigger being retrieved. If needed, replace
{namespace_id} with the project ID.
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `triggers_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.CloudRun.V1alpha1.Model.Trigger{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_triggers_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.Trigger.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_triggers_get(
connection,
projects_id,
locations_id,
triggers_id,
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(
"/v1alpha1/projects/{projectsId}/locations/{locationsId}/triggers/{triggersId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"triggersId" => URI.encode(triggers_id, &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.CloudRun.V1alpha1.Model.Trigger{}])
end
@doc """
Rpc to list triggers.
## Parameters
* `connection` (*type:* `GoogleApi.CloudRun.V1alpha1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The project ID or project number from which the triggers should
be listed.
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:continue` (*type:* `String.t`) - Optional. Encoded string to continue paging.
* `:fieldSelector` (*type:* `String.t`) - Allows to filter resources based on a specific value for a field name.
Send this in a query string format. i.e. 'metadata.name%3Dlorem'.
Not currently used by Cloud Run.
* `:includeUninitialized` (*type:* `boolean()`) - Not currently used by Cloud Run.
* `:labelSelector` (*type:* `String.t`) - Allows to filter resources based on a label. Supported operations are
=, !=, exists, in, and notIn.
* `:limit` (*type:* `integer()`) - The maximum number of records that should be returned.
* `:resourceVersion` (*type:* `String.t`) - The baseline resource version from which the list or watch operation should
start. Not currently used by Cloud Run.
* `:watch` (*type:* `boolean()`) - Flag that indicates that the client expects to watch this resource as well.
Not currently used by Cloud Run.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudRun.V1alpha1.Model.ListTriggersResponse{}}` on success
* `{:error, info}` on failure
"""
@spec run_projects_locations_triggers_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.CloudRun.V1alpha1.Model.ListTriggersResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def run_projects_locations_triggers_list(
connection,
projects_id,
locations_id,
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,
:continue => :query,
:fieldSelector => :query,
:includeUninitialized => :query,
:labelSelector => :query,
:limit => :query,
:resourceVersion => :query,
:watch => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1alpha1/projects/{projectsId}/locations/{locationsId}/triggers", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &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.CloudRun.V1alpha1.Model.ListTriggersResponse{}]
)
end
end
| 45.035771 | 196 | 0.613885 |
03cc42c5cc42c2fdee96dfc60aa502abbeadb697 | 2,964 | ex | Elixir | lib/shared_settings/setting.ex | kieraneglin/shared-settings-ex | 0b2f6e7c7b534ae58158fca01e61e7bd85a4147f | [
"Unlicense"
] | 2 | 2020-10-28T14:15:30.000Z | 2020-12-29T13:52:27.000Z | lib/shared_settings/setting.ex | kieraneglin/shared-settings-ex | 0b2f6e7c7b534ae58158fca01e61e7bd85a4147f | [
"Unlicense"
] | null | null | null | lib/shared_settings/setting.ex | kieraneglin/shared-settings-ex | 0b2f6e7c7b534ae58158fca01e61e7bd85a4147f | [
"Unlicense"
] | null | null | null | defmodule SharedSettings.Setting do
@moduledoc false
alias __MODULE__
alias SharedSettings.Config
alias SharedSettings.Utilities.Encryption
@enforce_keys [:name, :type, :value]
defstruct [:name, :type, :value, encrypted: false]
@type t :: %Setting{
name: String.t(),
type: String.t(),
value: String.t(),
encrypted: boolean()
}
def build(name, value, opts \\ []) do
encrypt = Keyword.get(opts, :encrypt, false)
case {encrypt, do_build(name, value)} do
{_, {:error, msg}} ->
{:error, msg}
{false, {:ok, setting}} ->
{:ok, setting}
{true, {:ok, setting}} ->
{:ok, encrypt_setting(setting)}
end
end
def restore(setting) do
case setting do
%Setting{encrypted: true} ->
setting
|> decrypt_setting()
|> do_restore()
_ ->
do_restore(setting)
end
end
defp do_build(name, value) when is_binary(value) do
{:ok, %Setting{name: name, type: "string", value: value}}
end
defp do_build(name, value) when is_integer(value) or is_float(value) do
{:ok, %Setting{name: name, type: "number", value: to_string(value)}}
end
defp do_build(name, value) when is_boolean(value) do
stringified_value = if value, do: "1", else: "0"
{:ok, %Setting{name: name, type: "boolean", value: stringified_value}}
end
defp do_build(name, value = %Range{}) do
first..last = value
stringified_value = "#{first},#{last}"
{:ok, %Setting{name: name, type: "range", value: stringified_value}}
end
defp do_build(_name, _value) do
{:error, :unsupported_type}
end
defp encrypt_setting(old_setting = %Setting{value: value}) do
{:ok, {iv, cipher_text}} = Encryption.encrypt(Config.encryption_key(), value)
encrypted_value = "#{Base.encode16(iv)}|#{Base.encode16(cipher_text)}"
%Setting{old_setting | value: encrypted_value, encrypted: true}
end
defp decrypt_setting(old_setting = %Setting{value: value, encrypted: true}) do
[iv, cipher_text] =
value
|> String.split("|")
|> Enum.map(&String.trim/1)
|> Enum.map(&Base.decode16!/1)
{:ok, plaintext_value} = Encryption.decrypt(Config.encryption_key(), iv, cipher_text)
%Setting{old_setting | value: plaintext_value, encrypted: false}
end
defp do_restore(%Setting{type: "string", value: value}) do
{:ok, value}
end
defp do_restore(%Setting{type: "number", value: value}) do
if String.contains?(value, ".") do
{:ok, String.to_float(value)}
else
{:ok, String.to_integer(value)}
end
end
defp do_restore(%Setting{type: "boolean", value: value}) do
case value do
"1" -> {:ok, true}
"0" -> {:ok, false}
end
end
defp do_restore(%Setting{type: "range", value: value}) do
[lower, upper] =
value
|> String.split(",")
|> Enum.map(&String.to_integer/1)
{:ok, lower..upper}
end
end
| 25.333333 | 89 | 0.616734 |
03cc956fd8095cbfb0aa1f363205924bccf23f11 | 3,207 | ex | Elixir | lib/ext/voice_controller.ex | sizumita/Bard | b2e5bb2d44b4a5700e38d56be7f6d88eff3f9218 | [
"MIT"
] | null | null | null | lib/ext/voice_controller.ex | sizumita/Bard | b2e5bb2d44b4a5700e38d56be7f6d88eff3f9218 | [
"MIT"
] | 1 | 2020-07-01T11:23:35.000Z | 2020-07-01T11:23:35.000Z | lib/ext/voice_controller.ex | sizumita/Bard | b2e5bb2d44b4a5700e38d56be7f6d88eff3f9218 | [
"MIT"
] | null | null | null | defmodule VoiceClientController do
alias Alchemy.Voice
def context(guild, message) do
state = Enum.find(guild.voice_states, fn vstate ->
vstate.user_id == message.author.id
end)
if state == nil do
{:error, "No state found"}
else
{:ok, state}
end
end
def has_state(guild) do
state = Enum.find(guild.voice_states, fn vstate ->
vstate.user_id == "727687910643466271"
end)
if state == nil do
false
else
true
end
end
def wait_for_front(guild, message_id) do
# Queue.add(:global.whereis_name("V"<>guild.id), message.id) してから
# :ok = VoiceClientController.wait_for_front(guild, message.id) をして
# 処理をする
pid = :global.whereis_name("V"<>guild.id)
:ok = Process.sleep(200)
case Voice.is_playing(guild.id) do
{:ok, true} ->
IO.puts "waiting...."
Voice.wait_for_end(guild.id)
_ -> :ignore
end
IO.puts "play..."
[head | tail] = Queue.list(pid)
if head == message_id do
IO.puts head
Queue.fetch(pid)
:ok
else
VoiceClientController.wait_for_front(guild, message_id)
end
end
defmodule Commands do
use Alchemy.Cogs
Cogs.def join do
case Cogs.guild() do
{:ok, guild} ->
case VoiceClientController.context(guild, message) do
{:ok, state} ->
case ChannelMap.fetch(:channels, guild.id) do
{:ok, _} -> Cogs.say "既に接続されています。切断してから再接続してください。"
:error ->
# TODO: ここで課金の確認
Voice.join(guild.id, state.channel_id)
Cogs.say "接続しました。"
{:ok, pid} = Queue.start_link()
:global.register_name("V"<>guild.id, pid)
ChannelMap.put(:channels, guild.id,
%{:text_id => message.channel_id, :voice_id => state.channel_id})
end
_ -> Cogs.say "ボイスチャンネルに接続しているユーザのみ可能です。"
end
_ -> Cogs.say "サーバー内で実行してください。"
end
end
Cogs.def leave do
case Cogs.guild() do
{:ok, guild} ->
case ChannelMap.fetch(:channels, guild.id) do
:error ->
Cogs.say "このサーバーでは接続されていません。"
{:ok, value} ->
if value.text_id != message.channel_id do
Cogs.say "このチャンネルは接続されていません。"
else
case VoiceClientController.context(guild, message) do
{:ok, state} ->
if state.channel_id == value.voice_id do
case Voice.is_playing(guild.id) do
{:ok, true} ->
Voice.stop_audio(guild.id)
_ -> :ignore
end
Voice.leave(guild.id)
ChannelMap.delete(:channels, guild.id)
Cogs.say "退出しました。"
else
Cogs.say "同じボイスチャンネルに接続しているユーザのみ可能です。"
end
_ -> Cogs.say "ボイスチャンネルに接続しているユーザのみ可能です。"
end
end
end
_ -> Cogs.say "サーバー内で実行してください。"
end
end
end
end
| 28.131579 | 85 | 0.5145 |
03cca98aafebfa8541f5313cdd40d47314357469 | 1,220 | ex | Elixir | test/support/conn_case.ex | remerle/asciinema-server | 895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57 | [
"Apache-2.0"
] | 893 | 2017-09-14T14:18:29.000Z | 2022-03-31T21:45:08.000Z | test/support/conn_case.ex | remerle/asciinema-server | 895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57 | [
"Apache-2.0"
] | 103 | 2017-09-29T22:15:33.000Z | 2022-03-27T21:47:43.000Z | test/support/conn_case.ex | remerle/asciinema-server | 895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57 | [
"Apache-2.0"
] | 152 | 2017-09-07T12:43:15.000Z | 2022-03-10T18:47:47.000Z | defmodule AsciinemaWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build and query models.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import AsciinemaWeb.Router.Helpers.Extra
import Asciinema.Fixtures
alias AsciinemaWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint AsciinemaWeb.Endpoint
def log_in(conn, user) do
assign(conn, :current_user, user)
end
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Asciinema.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Asciinema.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 25.957447 | 71 | 0.706557 |
03ccb7b150fdd81df1459cf03e15ed9458bbf142 | 13,281 | exs | Elixir | apps/core/test/services/users_test.exs | asamoal/plural | 5b336f27cb2d775560e35e5323192c42d62e72f5 | [
"Apache-2.0"
] | null | null | null | apps/core/test/services/users_test.exs | asamoal/plural | 5b336f27cb2d775560e35e5323192c42d62e72f5 | [
"Apache-2.0"
] | null | null | null | apps/core/test/services/users_test.exs | asamoal/plural | 5b336f27cb2d775560e35e5323192c42d62e72f5 | [
"Apache-2.0"
] | null | null | null | defmodule Core.Services.UsersTest do
use Core.SchemaCase, async: true
use Mimic
alias Core.Services.Users
alias Core.PubSub
describe "#create_user" do
test "Users can be created" do
{:ok, user} = Users.create_user(%{
name: "some user",
password: "superstrongpassword",
email: "something@example.com"
})
assert user.name == "some user"
assert user.email == "something@example.com"
assert user.password_hash
assert Timex.after?(user.email_confirm_by, Timex.now())
%{account: account} = Core.Repo.preload(user, [:account])
assert account.name == user.email
assert account.root_user_id == user.id
assert_receive {:event, %PubSub.UserCreated{item: ^user}}
end
test "if the email is on a mapped domain, the user will be added to the right account" do
mapping = insert(:domain_mapping, domain: "example.com")
{:ok, user} = Users.create_user(%{
name: "some user",
password: "superstrongpassword",
email: "something@example.com"
})
assert user.name == "some user"
assert user.email == "something@example.com"
assert user.account_id == mapping.account.id
end
end
describe "#create_publisher" do
test "Users can create publishers" do
account = insert(:account)
user = insert(:user, account: account)
{:ok, publisher} = Users.create_publisher(%{name: "somepublisher"}, user)
assert publisher.name == "somepublisher"
assert publisher.owner_id == user.id
assert publisher.account_id == account.id
end
end
describe "#update_user/2" do
test "Users can update themselves" do
{:ok, user} = Users.create_user(%{
name: "some user",
password: "superstrongpassword",
email: "something@example.com"
})
{:ok, updated} = Users.update_user(%{name: "real user"}, user)
assert updated.name == "real user"
assert_receive {:event, %PubSub.UserUpdated{item: ^updated}}
end
test "you cannot make yourself an admin" do
user = insert(:user)
{:ok, _} = Users.update_user(%{password: "superstrongpassword"}, user)
{:error, _} = Users.update_user(%{name: "real user", roles: %{admin: true}}, user)
end
end
describe "#update_user/3" do
test "admins can update users" do
{:ok, user} = Users.create_user(%{
name: "some user",
password: "superstrongpassword",
email: "something@example.com"
})
%{account: account} = Core.Repo.preload(user, [:account])
admin = insert(:user, account: account, roles: %{admin: true})
{:ok, updated} = Users.update_user(%{name: "real user", roles: %{admin: true}}, user.id, admin)
assert updated.name == "real user"
assert updated.roles.admin
assert_receive {:event, %PubSub.UserUpdated{item: ^updated, actor: actor}}
assert actor.id == admin.id
end
test "nonadmins cannot update users" do
{:ok, user} = Users.create_user(%{
name: "some user",
password: "superstrongpassword",
email: "something@example.com"
})
%{account: account} = Core.Repo.preload(user, [:account])
nonadmin = insert(:user, account: account)
{:error, _} = Users.update_user(%{name: "real user", roles: %{admin: true}}, user.id, nonadmin)
end
end
describe "#delete_user" do
setup [:setup_root_user]
test "root users can delete users in their accounts", %{account: account, user: user} do
other_user = insert(:user, account: account)
{:ok, del} = Users.delete_user(other_user.id, user)
refute refetch(del)
assert_receive {:event, %PubSub.UserDeleted{item: ^del, actor: ^user}}
end
test "Users with user management perms can delete users", %{account: account} do
user = insert(:user, account: account)
role = insert(:role, account: account, permissions: %{users: true})
insert(:role_binding, role: role, user: user)
other_user = insert(:user, account: account)
user = Core.Services.Rbac.preload(user)
{:ok, _} = Users.delete_user(other_user.id, user)
end
test "You cannot delete your own user", %{account: account} do
user = insert(:user, account: account)
role = insert(:role, account: account, permissions: %{users: true})
insert(:role_binding, role: role, user: user)
user = Core.Services.Rbac.preload(user)
{:error, _} = Users.delete_user(user.id, user)
end
test "You cannot delete an account's root user", %{account: account, user: root} do
user = insert(:user, account: account)
role = insert(:role, account: account, permissions: %{users: true})
insert(:role_binding, role: role, user: user)
user = Core.Services.Rbac.preload(user)
{:error, _} = Users.delete_user(root.id, user)
end
end
describe "#update_publisher" do
test "Users can update their own publisher" do
user = insert(:user)
publisher = insert(:publisher, owner: user)
{:ok, updated} = Users.update_publisher(%{name: "publisher"}, user)
assert updated.id == publisher.id
assert updated.name == "publisher"
end
end
describe "#login_method" do
test "if the login method is passwordless, it will create a passwordless login record" do
user = insert(:user, login_method: :passwordless)
{:ok, %{login_method: :passwordless, token: token}} = Users.login_method(user.email)
assert_receive {:event, %PubSub.PasswordlessLoginCreated{item: item}}
assert item.user_id == user.id
assert item.token
assert Users.get_login_token(token)
end
test "if the email is on an sso-enabled domain, it will return an sso login method" do
insert(:domain_mapping, domain: "example.com", enable_sso: true)
{:ok, %{login_method: :sso, authorize_url: url}} = Users.login_method("someone@example.com")
assert is_binary(url)
end
test "if the user doesn't exist, it will return an error" do
{:error, :not_found} = Users.login_method("some@email.com")
end
end
describe "#login_user" do
test "You can log in by password" do
{:ok, user} = Users.create_user(%{
name: "some user",
email: "someone@example.com",
password: "verystrongpassword"
})
{:ok, login} = Users.login_user(user.email, "verystrongpassword")
assert login.id == user.id
{:error, :invalid_password} = Users.login_user(user.email, "incorrectpassword")
end
end
describe "#passwordless_login/1" do
test "it will return the user if valid" do
token = insert(:login_token)
login = insert(:passwordless_login, login_token: token, user: token.user)
{:ok, user} = Users.passwordless_login(login.token)
assert user.id == login.user_id
refute refetch(login)
assert refetch(token).active
end
test "it will return an error if there is no login record" do
{:error, _} = Users.passwordless_login("bogus")
end
end
describe "#poll_login_token" do
test "if the token is active, it will return the associated user" do
token = insert(:login_token, active: true)
{:ok, user} = Users.poll_login_token(token.token)
assert user.id == token.user_id
end
test "if the token is inactive, it will error" do
token = insert(:login_token)
{:error, :inactive} = Users.poll_login_token(token.token)
end
test "if the token doesn't exist, it will error" do
{:error, :not_found} = Users.poll_login_token("bogus")
end
end
describe "#create_persisted_token/1" do
test "A user can create a persisted token for themselves" do
user = insert(:user)
{:ok, %{token: "plrl-" <> _} = token} = Users.create_persisted_token(user)
assert token.token
assert token.user_id == user.id
assert Users.get_persisted_token(token.token)
end
end
describe "#delete_persisted_token" do
test "A user can delete their tokens" do
user = insert(:user)
token = insert(:persisted_token, user: user)
{:ok, del} = Users.delete_persisted_token(token.id, user)
assert del.id == token.id
refute refetch(token)
end
test "Users cannot delete other's tokens" do
user = insert(:user)
token = insert(:persisted_token)
{:error, _} = Users.delete_persisted_token(token.id, user)
end
end
describe "#upsert_webhook/2" do
test "It can create a new webhook for a url" do
user = insert(:user)
url = "https://www.example.com"
{:ok, webhook} = Users.upsert_webhook(url, user)
assert webhook.user_id == user.id
assert webhook.url == url
assert webhook.secret
end
test "It will echo an existing webhook" do
%{user: user} = webhook = insert(:webhook)
{:ok, upserted} = Users.upsert_webhook(webhook.url, user)
assert upserted.secret == webhook.secret
assert upserted.url == webhook.url
assert upserted.user_id == user.id
end
end
describe "#create_reset_token/1" do
test "it can create a pwd reset token" do
user = insert(:user)
{:ok, reset} = Users.create_reset_token(%{
email: user.email,
type: :password
})
assert reset.user.id == user.id
assert reset.type == :password
assert reset.external_id
assert_receive {:event, %PubSub.ResetTokenCreated{item: ^reset}}
end
test "it will fail on invalid emails" do
{:error, :not_found} = Users.create_reset_token(%{
email: "invalid@email.com",
type: :password
})
end
end
describe "#realize_reset_token/2" do
test "it can realize a reset token" do
token = insert(:reset_token)
{:ok, user} = Users.realize_reset_token(token, %{password: "a long password"})
assert user.id == token.user.id
{:ok, _} = Users.login_user(user.email, "a long password")
end
test "it will confirm an email for email tokens" do
user = insert(:user)
token = insert(:reset_token, type: :email, user: user)
{:ok, reset} = Users.realize_reset_token(token, %{})
assert reset.id == token.user.id
assert reset.email_confirmed
assert_receive {:event, %PubSub.EmailConfirmed{item: ^reset}}
end
end
describe "#create_public_key/2" do
test "it can create a public key for a user" do
user = insert(:user)
{:ok, key} = Users.create_public_key(%{content: "bogus key", name: "example"}, user)
assert key.name == "example"
assert key.user_id == user.id
assert key.digest
end
end
describe "#delete_public_key/2" do
test "it can delete a user's public key" do
user = insert(:user)
key = insert(:public_key, user: user)
{:ok, _} = Users.delete_public_key(key.id, user)
refute refetch(key)
end
test "it cannot delete others' keys" do
user = insert(:user)
key = insert(:public_key)
{:error, _} = Users.delete_public_key(key.id, user)
end
end
describe "#device_login/0" do
test "it will create a login token and print a url" do
{:ok, login} = Users.device_login()
token = Users.get_login_token(login.device_token)
assert token
refute token.active
assert is_binary(login.login_url)
end
end
describe "#activate_login_token/2" do
test "it will set the login token to active" do
token = insert(:login_token)
user = insert(:user)
{:ok, active} = Users.activate_login_token(token.token, user)
assert active.active
assert active.user_id == user.id
end
end
describe "#get_eab_key/3" do
test "it will generate and persist an eab keypair for a user" do
user = insert(:user)
expect(HTTPoison, :post, fn _, _ ->
{:ok, %{status_code: 200, body: Jason.encode!(%{
success: 1,
eab_kid: "abc",
eab_hmac_key: "123"
})}}
end)
{:ok, eab} = Users.get_eab_key("cluster", :aws, user)
assert eab.cluster == "cluster"
assert eab.provider == :aws
assert eab.user_id == user.id
assert eab.key_id == "abc"
assert eab.hmac_key == "123"
end
end
describe "#delete_eab_key/2" do
test "a user can delete their eab creds" do
user = insert(:user)
eab = insert(:eab_credential, user: user)
{:ok, _} = Users.delete_eab_key(eab.id, user)
refute refetch(eab)
end
end
describe "#backfill_providers/0" do
test "it will set providers based on terraform installations" do
user = insert(:user)
insert(:terraform_installation,
installation: build(:installation, user: user),
version: build(:version, dependencies: %{providers: [:gcp]})
)
user2 = insert(:user)
insert(:terraform_installation,
installation: build(:installation, user: user2),
version: build(:version, dependencies: %{providers: [:aws]})
)
user3 = insert(:user)
Users.backfill_providers()
assert refetch(user).provider == :gcp
assert refetch(user2).provider == :aws
refute refetch(user3).provider
end
end
end
| 28.871739 | 101 | 0.634666 |
03ccd67194aab812d73a658cb78455a529761da3 | 16,857 | ex | Elixir | lib/aws/generated/qldb.ex | pecigonzalo/aws-elixir | b52181ebfb9e62349dc8e8067b7fbcd4f7a18c68 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/qldb.ex | pecigonzalo/aws-elixir | b52181ebfb9e62349dc8e8067b7fbcd4f7a18c68 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/qldb.ex | pecigonzalo/aws-elixir | b52181ebfb9e62349dc8e8067b7fbcd4f7a18c68 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.QLDB do
@moduledoc """
The control plane for Amazon QLDB
"""
alias AWS.Client
alias AWS.Request
def metadata do
%AWS.ServiceMetadata{
abbreviation: nil,
api_version: "2019-01-02",
content_type: "application/x-amz-json-1.1",
credential_scope: nil,
endpoint_prefix: "qldb",
global?: false,
protocol: "rest-json",
service_id: "QLDB",
signature_version: "v4",
signing_name: "qldb",
target_prefix: nil
}
end
@doc """
Ends a given Amazon QLDB journal stream.
Before a stream can be canceled, its current status must be `ACTIVE`.
You can't restart a stream after you cancel it. Canceled QLDB stream resources
are subject to a 7-day retention period, so they are automatically deleted after
this limit expires.
"""
def cancel_journal_kinesis_stream(
%Client{} = client,
ledger_name,
stream_id,
input,
options \\ []
) do
url_path =
"/ledgers/#{AWS.Util.encode_uri(ledger_name)}/journal-kinesis-streams/#{AWS.Util.encode_uri(stream_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Creates a new ledger in your Amazon Web Services account in the current Region.
"""
def create_ledger(%Client{} = client, input, options \\ []) do
url_path = "/ledgers"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Deletes a ledger and all of its contents.
This action is irreversible.
If deletion protection is enabled, you must first disable it before you can
delete the ledger. You can disable it by calling the `UpdateLedger` operation to
set the flag to `false`.
"""
def delete_ledger(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Returns detailed information about a given Amazon QLDB journal stream.
The output includes the Amazon Resource Name (ARN), stream name, current status,
creation time, and the parameters of the original stream creation request.
This action does not return any expired journal streams. For more information,
see [Expiration for terminal streams](https://docs.aws.amazon.com/qldb/latest/developerguide/streams.create.html#streams.create.states.expiration)
in the *Amazon QLDB Developer Guide*.
"""
def describe_journal_kinesis_stream(%Client{} = client, ledger_name, stream_id, options \\ []) do
url_path =
"/ledgers/#{AWS.Util.encode_uri(ledger_name)}/journal-kinesis-streams/#{AWS.Util.encode_uri(stream_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Returns information about a journal export job, including the ledger name,
export ID, creation time, current status, and the parameters of the original
export creation request.
This action does not return any expired export jobs. For more information, see
[Export job expiration](https://docs.aws.amazon.com/qldb/latest/developerguide/export-journal.request.html#export-journal.request.expiration)
in the *Amazon QLDB Developer Guide*.
If the export job with the given `ExportId` doesn't exist, then throws
`ResourceNotFoundException`.
If the ledger with the given `Name` doesn't exist, then throws
`ResourceNotFoundException`.
"""
def describe_journal_s3_export(%Client{} = client, export_id, name, options \\ []) do
url_path =
"/ledgers/#{AWS.Util.encode_uri(name)}/journal-s3-exports/#{AWS.Util.encode_uri(export_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Returns information about a ledger, including its state, permissions mode,
encryption at rest settings, and when it was created.
"""
def describe_ledger(%Client{} = client, name, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Exports journal contents within a date and time range from a ledger into a
specified Amazon Simple Storage Service (Amazon S3) bucket.
A journal export job can write the data objects in either the text or binary
representation of Amazon Ion format, or in *JSON Lines* text format.
In JSON Lines format, each journal block in the exported data object is a valid
JSON object that is delimited by a newline. You can use this format to easily
integrate JSON exports with analytics tools such as Glue and Amazon Athena
because these services can parse newline-delimited JSON automatically. For more
information about the format, see [JSON Lines](https://jsonlines.org/).
If the ledger with the given `Name` doesn't exist, then throws
`ResourceNotFoundException`.
If the ledger with the given `Name` is in `CREATING` status, then throws
`ResourcePreconditionNotMetException`.
You can initiate up to two concurrent journal export requests for each ledger.
Beyond this limit, journal export requests throw `LimitExceededException`.
"""
def export_journal_to_s3(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}/journal-s3-exports"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Returns a block object at a specified address in a journal.
Also returns a proof of the specified block for verification if
`DigestTipAddress` is provided.
For information about the data contents in a block, see [Journal contents](https://docs.aws.amazon.com/qldb/latest/developerguide/journal-contents.html)
in the *Amazon QLDB Developer Guide*.
If the specified ledger doesn't exist or is in `DELETING` status, then throws
`ResourceNotFoundException`.
If the specified ledger is in `CREATING` status, then throws
`ResourcePreconditionNotMetException`.
If no block exists with the specified address, then throws
`InvalidParameterException`.
"""
def get_block(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}/block"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Returns the digest of a ledger at the latest committed block in the journal.
The response includes a 256-bit hash value and a block address.
"""
def get_digest(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}/digest"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Returns a revision data object for a specified document ID and block address.
Also returns a proof of the specified revision for verification if
`DigestTipAddress` is provided.
"""
def get_revision(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}/revision"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Returns an array of all Amazon QLDB journal stream descriptors for a given
ledger.
The output of each stream descriptor includes the same details that are returned
by `DescribeJournalKinesisStream`.
This action does not return any expired journal streams. For more information,
see [Expiration for terminal streams](https://docs.aws.amazon.com/qldb/latest/developerguide/streams.create.html#streams.create.states.expiration)
in the *Amazon QLDB Developer Guide*.
This action returns a maximum of `MaxResults` items. It is paginated so that you
can retrieve all the items by calling `ListJournalKinesisStreamsForLedger`
multiple times.
"""
def list_journal_kinesis_streams_for_ledger(
%Client{} = client,
ledger_name,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/ledgers/#{AWS.Util.encode_uri(ledger_name)}/journal-kinesis-streams"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"next_token", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"max_results", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Returns an array of journal export job descriptions for all ledgers that are
associated with the current Amazon Web Services account and Region.
This action returns a maximum of `MaxResults` items, and is paginated so that
you can retrieve all the items by calling `ListJournalS3Exports` multiple times.
This action does not return any expired export jobs. For more information, see
[Export job expiration](https://docs.aws.amazon.com/qldb/latest/developerguide/export-journal.request.html#export-journal.request.expiration)
in the *Amazon QLDB Developer Guide*.
"""
def list_journal_s3_exports(
%Client{} = client,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/journal-s3-exports"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"next_token", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"max_results", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Returns an array of journal export job descriptions for a specified ledger.
This action returns a maximum of `MaxResults` items, and is paginated so that
you can retrieve all the items by calling `ListJournalS3ExportsForLedger`
multiple times.
This action does not return any expired export jobs. For more information, see
[Export job expiration](https://docs.aws.amazon.com/qldb/latest/developerguide/export-journal.request.html#export-journal.request.expiration)
in the *Amazon QLDB Developer Guide*.
"""
def list_journal_s3_exports_for_ledger(
%Client{} = client,
name,
max_results \\ nil,
next_token \\ nil,
options \\ []
) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}/journal-s3-exports"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"next_token", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"max_results", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Returns an array of ledger summaries that are associated with the current Amazon
Web Services account and Region.
This action returns a maximum of 100 items and is paginated so that you can
retrieve all the items by calling `ListLedgers` multiple times.
"""
def list_ledgers(%Client{} = client, max_results \\ nil, next_token \\ nil, options \\ []) do
url_path = "/ledgers"
headers = []
query_params = []
query_params =
if !is_nil(next_token) do
[{"next_token", next_token} | query_params]
else
query_params
end
query_params =
if !is_nil(max_results) do
[{"max_results", max_results} | query_params]
else
query_params
end
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Returns all tags for a specified Amazon QLDB resource.
"""
def list_tags_for_resource(%Client{} = client, resource_arn, options \\ []) do
url_path = "/tags/#{AWS.Util.encode_uri(resource_arn)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
nil
)
end
@doc """
Creates a journal stream for a given Amazon QLDB ledger.
The stream captures every document revision that is committed to the ledger's
journal and delivers the data to a specified Amazon Kinesis Data Streams
resource.
"""
def stream_journal_to_kinesis(%Client{} = client, ledger_name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(ledger_name)}/journal-kinesis-streams"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Adds one or more tags to a specified Amazon QLDB resource.
A resource can have up to 50 tags. If you try to create more than 50 tags for a
resource, your request fails and returns an error.
"""
def tag_resource(%Client{} = client, resource_arn, input, options \\ []) do
url_path = "/tags/#{AWS.Util.encode_uri(resource_arn)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Removes one or more tags from a specified Amazon QLDB resource.
You can specify up to 50 tag keys to remove.
"""
def untag_resource(%Client{} = client, resource_arn, input, options \\ []) do
url_path = "/tags/#{AWS.Util.encode_uri(resource_arn)}"
headers = []
{query_params, input} =
[
{"TagKeys", "tagKeys"}
]
|> Request.build_params(input)
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates properties on a ledger.
"""
def update_ledger(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:patch,
url_path,
query_params,
headers,
input,
options,
nil
)
end
@doc """
Updates the permissions mode of a ledger.
Before you switch to the `STANDARD` permissions mode, you must first create all
required IAM policies and table tags to avoid disruption to your users. To learn
more, see [Migrating to the standard permissions mode](https://docs.aws.amazon.com/qldb/latest/developerguide/ledger-management.basics.html#ledger-mgmt.basics.update-permissions.migrating)
in the *Amazon QLDB Developer Guide*.
"""
def update_ledger_permissions_mode(%Client{} = client, name, input, options \\ []) do
url_path = "/ledgers/#{AWS.Util.encode_uri(name)}/permissions-mode"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:patch,
url_path,
query_params,
headers,
input,
options,
nil
)
end
end
| 25.735878 | 190 | 0.646378 |
03ccdc2de08548aaee257ffefe05057333567714 | 1,216 | ex | Elixir | server/lib/taskerito_web/views/error_helpers.ex | jonatanklosko/taskerito | e9b9bfdd10f53a676c0c5eccbd54e4c8a1c2d8a1 | [
"MIT"
] | 5 | 2020-06-18T20:31:11.000Z | 2021-07-23T10:05:56.000Z | server/lib/taskerito_web/views/error_helpers.ex | jonatanklosko/taskerito | e9b9bfdd10f53a676c0c5eccbd54e4c8a1c2d8a1 | [
"MIT"
] | null | null | null | server/lib/taskerito_web/views/error_helpers.ex | jonatanklosko/taskerito | e9b9bfdd10f53a676c0c5eccbd54e4c8a1c2d8a1 | [
"MIT"
] | null | null | null | defmodule TaskeritoWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(TaskeritoWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(TaskeritoWeb.Gettext, "errors", msg, opts)
end
end
end
| 35.764706 | 78 | 0.672697 |
03ccdc4fd6235811ee2b00bd9dd4e54b018bbe2a | 2,027 | ex | Elixir | apps/admin_app/lib/admin_app_web/endpoint.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | 1 | 2021-04-08T22:29:19.000Z | 2021-04-08T22:29:19.000Z | apps/admin_app/lib/admin_app_web/endpoint.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | apps/admin_app/lib/admin_app_web/endpoint.ex | VeryBigThings/avia | 7ce5d5b244ae0dfddc30c09c17efe27f1718a4c9 | [
"MIT"
] | null | null | null | defmodule AdminAppWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :admin_app
use Sentry.Phoenix.Endpoint
alias Snitch.Core.Tools.MultiTenancy
socket("/socket", AdminAppWeb.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: :admin_app,
gzip: true,
only: ~w(css fonts images js favicon.png robots.txt)
)
# Serve the images saved in the upload folder.
plug(Plug.Static, at: "/uploads", from: Path.expand('./uploads'), gzip: false)
# 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: Phoenix.json_library()
)
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: "_admin_app_key",
signing_salt: "yum1FuJK"
)
plug(
MultiTenancy.Plug,
endpoint: __MODULE__
)
plug(AdminAppWeb.Router)
@doc """
Callback invoked for dynamically configuring the endpoint.
It receives the endpoint configuration and checks if
configuration should be loaded from the system environment.
"""
def init(_key, config) do
if config[:load_from_system_env] do
port =
System.get_env("ADMIN_PORT") ||
raise "expected the ADMIN_PORT environment variable to be set"
{:ok, Keyword.put(config, :http, [:inet6, port: port])}
else
{:ok, config}
end
end
end
| 25.3375 | 80 | 0.688209 |
03cd0a1ab8432336ff39dde370e7e96891107856 | 696 | ex | Elixir | lib/nerves/artifact/build_runner.ex | petermm/nerves | 173b0a424177f45f77db4206406d9c98f1d73e95 | [
"Apache-2.0"
] | 1,944 | 2016-01-25T14:04:50.000Z | 2022-03-30T13:25:53.000Z | lib/nerves/artifact/build_runner.ex | petermm/nerves | 173b0a424177f45f77db4206406d9c98f1d73e95 | [
"Apache-2.0"
] | 397 | 2016-05-19T21:17:51.000Z | 2022-03-30T18:02:49.000Z | lib/nerves/artifact/build_runner.ex | petermm/nerves | 173b0a424177f45f77db4206406d9c98f1d73e95 | [
"Apache-2.0"
] | 191 | 2016-01-30T01:56:25.000Z | 2022-03-30T17:58:57.000Z | defmodule Nerves.Artifact.BuildRunner do
@moduledoc """
Defines the Nerves build runner behaviour
A build runner is a module that can take package source and produce
artifacts.
"""
@type build_result :: {:ok, build_path :: String.t()} | {:error, reason :: term}
@type archive_result :: {:ok, path :: String.t()} | {:error, reason :: term}
@type clean_result :: :ok | {:error, reason :: term}
@callback build(package :: Nerves.Package.t(), toolchain :: atom, opts :: term) :: build_result
@callback archive(package :: Nerves.Package.t(), toolchain :: atom, opts :: term) ::
archive_result
@callback clean(package :: Nerves.Package.t()) :: clean_result
end
| 34.8 | 97 | 0.662356 |
03cd280d47150568d5dd4addf42bf39d4bcca1b1 | 7,299 | ex | Elixir | lib/backoffice/field.ex | NduatiK/backoffice_anchored | 2d03e86e3eb5db9dd36a7dfe5e286b0db1714853 | [
"MIT"
] | null | null | null | lib/backoffice/field.ex | NduatiK/backoffice_anchored | 2d03e86e3eb5db9dd36a7dfe5e286b0db1714853 | [
"MIT"
] | null | null | null | lib/backoffice/field.ex | NduatiK/backoffice_anchored | 2d03e86e3eb5db9dd36a7dfe5e286b0db1714853 | [
"MIT"
] | null | null | null | defmodule Backoffice.Field do
use Phoenix.HTML
import Phoenix.LiveView.Helpers
import Backoffice.ErrorHelper
def form_field(form, field, opts) do
type = Map.fetch!(opts, :type)
opts = Map.delete(opts, :type)
do_form_field(form, field, type, opts)
end
defp do_form_field(form, field, :integer, opts) do
text_input(form, field, build_opts(:integer, opts))
end
defp do_form_field(form, field, {:array, _type}, opts) do
opts = Enum.into(opts, %{})
value =
case input_value(form, field) do
"" -> ""
list when is_list(list) -> Enum.join(list, ",")
end
opts =
build_opts(
:string,
Map.merge(opts, %{
rows: 4,
value: value
})
)
text_input(form, field, opts)
end
defp do_form_field(form, field, :textarea, opts) do
opts =
build_opts(
:textarea,
Map.merge(opts, %{
rows: 4,
value: input_value(form, field)
})
)
textarea(form, field, opts)
end
defp do_form_field(form, field, {:parameterized, Ecto.Embedded, %{related: schema}}, _opts) do
inputs_for(form, field, fn fp ->
fields =
for {k, v} <- schema.__changeset__() do
{k, %{type: v}}
end
[
{:safe, "<div class=\"p-4 shadow rounded-md\">"},
Enum.map(fields, fn {field, %{type: type}} ->
[
{:safe, "<div class=\"mb-4\">"},
label(fp, field, build_opts(:label, %{})),
do_form_field(fp, field, type, build_opts(type, %{})),
error_tag(fp, field),
{:safe, "</div>"}
]
end),
{:safe, "</div>"}
]
end)
end
defp do_form_field(form, field, {:parameterized, Ecto.Enum, %{values: values}} = type, opts) do
options = values |> Enum.map(&Phoenix.Naming.humanize/1) |> Enum.zip(values)
select(form, field, options, build_opts(type, opts))
end
defp do_form_field(form, field, :map, opts) do
do_form_field(form, field, :textarea, opts)
end
defp do_form_field(form, field, :boolean, opts) do
checkbox(form, field, build_opts(:boolean, opts))
end
defp do_form_field(form, field, :component, opts) do
component = Map.fetch!(opts, :render)
opts = Map.merge(opts, %{value: input_value(form, field)})
live_component(_, component, opts)
end
defp do_form_field(form, field, :custom, opts) do
render = Map.fetch!(opts, :render)
render.(form, field)
end
defp do_form_field(form, field, {:embed, %{related: schema}}, opts) do
inputs_for(form, field, fn fp ->
fields =
for {k, v} <- schema.__changeset__() do
{k, %{type: v}}
end
[
{:safe, "<div class=\"p-2\">"},
Enum.map(fields, fn {field, %{type: type}} ->
[
{:safe, "<div class=\"mb-4\">"},
label(fp, field, build_opts(:label, opts)),
do_form_field(fp, field, type, build_opts(type, opts)),
error_tag(fp, field),
{:safe, "</div>"}
]
end),
{:safe, "</div>"}
]
end)
end
# TODO: Improve the rendering of `belongs_to.
# For example it would be good to render a link to the resource
# this means we likely have to:
# - require user to implement Backoffice for the target resource
# - find a way to get the target resource's attributes with just a `schema`/`resource` field.
# once we have that, we can think about how to link to that resource directly.
defp do_form_field(
form,
field,
{:assoc, %Ecto.Association.BelongsTo{related: _schema, related_key: _key}},
opts
) do
resource = input_value(form, field)
cond do
render = Map.get(opts, :render) ->
render.(resource)
key = Map.get(opts, :display, :id) ->
text_input(
form,
field,
build_opts(:default, value: resource[key], disabled: true)
)
end
end
defp do_form_field(
form,
field,
{:assoc, %Ecto.Association.Has{related: schema, related_key: key}},
opts
) do
inputs_for(form, field, fn fp ->
fields = schema.__schema__(:fields)
types = Enum.map(fields, &schema.__schema__(:type, &1))
fields =
for {k, v} <- Enum.zip(fields, types) do
{k, %{type: v}}
end
primary_key = schema.__schema__(:primary_key)
[
{:safe, "<div class=\"p-6 col-span-2 bg-gray-100 shadow-inner rounded-md\">"},
Enum.map(fields, fn {field, %{type: type}} ->
if field == key do
hidden_input(fp, field, value: form.data.id)
else
opts =
if field in primary_key,
do: Map.put(opts, :disabled, true),
else: opts
[
{:safe, "<div class=\"mb-4\">"},
label(fp, field, build_opts(:label, opts)),
do_form_field(fp, field, type, build_opts(type, opts)),
error_tag(fp, field),
{:safe, "</div>"}
]
end
end),
{:safe, "</div>"}
]
end)
end
defp do_form_field(form, field, type, opts) do
text_input(form, field, build_opts(type, opts))
end
defp build_opts(:label, opts) do
opts = Enum.into(opts, %{})
%{class: default_style(:label)}
|> Map.merge(opts)
|> Enum.into([])
end
defp build_opts(type, opts) do
opts = Enum.into(opts, %{})
class = type |> default_style() |> maybe_disabled(opts)
%{class: class}
|> Map.merge(opts)
|> Enum.into([])
end
def default_style(:label) do
"block text-sm font-medium leading-5 text-gray-700"
end
def default_style(:textarea) do
"mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md col-span-2"
end
def default_style({:embed, _}) do
"mt-2 mb-4 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md transition"
end
def default_style({:parameterized, Ecto.Enum, _}) do
"mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
end
def default_style(:select) do
"mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
end
def default_style(:map) do
default_style(:textarea)
end
def default_style(:datetime) do
"flex-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full min-w-0 rounded-none rounded-r-md sm:text-sm border-gray-300"
end
def default_style(:boolean) do
"focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded transition"
end
def default_style(:integer) do
default_style(:default)
end
def default_style(_type) do
"mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md transition"
end
defp maybe_disabled(class, %{disabled: true}) do
class <> " bg-gray-200"
end
defp maybe_disabled(class, _), do: class
end
| 27.858779 | 163 | 0.588026 |
03cd5105eaaa8beeea064af429871e3e83a97877 | 2,201 | ex | Elixir | lib/graphql/resolvers/lint.ex | suryatmodulus/accent | 6aaf34075c33f3d9d84d38237af4a39b594eb808 | [
"BSD-3-Clause"
] | null | null | null | lib/graphql/resolvers/lint.ex | suryatmodulus/accent | 6aaf34075c33f3d9d84d38237af4a39b594eb808 | [
"BSD-3-Clause"
] | null | null | null | lib/graphql/resolvers/lint.ex | suryatmodulus/accent | 6aaf34075c33f3d9d84d38237af4a39b594eb808 | [
"BSD-3-Clause"
] | null | null | null | defmodule Accent.GraphQL.Resolvers.Lint do
require Ecto.Query
import Absinthe.Resolution.Helpers, only: [batch: 3]
alias Accent.Scopes.Revision, as: RevisionScope
alias Accent.Scopes.Translation, as: TranslationScope
alias Accent.{
Language,
Plugs.GraphQLContext,
Repo,
Translation
}
@spec lint_translation(Translation.t(), map(), GraphQLContext.t()) :: {:ok, Paginated.t(Language.Entry.t())}
def lint_translation(translation, args, resolution) do
batch({__MODULE__, :preload_translations}, translation, fn batch_results ->
translation = Map.get(batch_results, translation.id)
lint_batched_translation(translation, args, resolution)
end)
end
def lint_batched_translation(translation, args, _) do
translation = overwrite_text_args(translation, args)
language_slug = translation.revision.slug || translation.revision.language.slug
entry = Translation.to_langue_entry(translation, translation.master_translation, translation.revision.master, language_slug)
[{_, messages}] = Accent.Lint.lint([entry])
{:ok, messages}
end
def preload_translations(_, translations = [translation | _]) do
translations = Repo.preload(translations, revision: :language)
project =
translation
|> Ecto.assoc(:project)
|> Repo.one()
master_revision =
project
|> Ecto.assoc(:revisions)
|> RevisionScope.master()
|> Repo.one()
master_translations =
Accent.Translation
|> TranslationScope.from_project(project.id)
|> TranslationScope.from_revision(master_revision.id)
|> TranslationScope.active()
|> Repo.all()
|> Enum.map(&{{&1.key, &1.document_id}, &1})
|> Enum.into(%{})
Enum.reduce(translations, %{}, fn translation, acc ->
master_translation = Map.get(master_translations, {translation.key, translation.document_id})
Map.put(acc, translation.id, %{translation | master_translation: master_translation})
end)
end
defp overwrite_text_args(translation, %{text: text}) when is_binary(text) do
%{translation | corrected_text: text}
end
defp overwrite_text_args(translation, _) do
translation
end
end
| 31.442857 | 128 | 0.703317 |
03cdb0d0015c7897bf73577643ae5693b24bddcb | 175 | exs | Elixir | priv/repo/migrations/20160215134700_create_payment_method.exs | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 356 | 2016-03-16T12:37:28.000Z | 2021-12-18T03:22:39.000Z | priv/repo/migrations/20160215134700_create_payment_method.exs | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 30 | 2016-03-16T09:19:10.000Z | 2021-01-12T08:10:52.000Z | priv/repo/migrations/20160215134700_create_payment_method.exs | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 72 | 2016-03-16T13:32:14.000Z | 2021-03-23T11:27:43.000Z | defmodule Nectar.Repo.Migrations.CreatePaymentMethod do
use Ecto.Migration
def change do
create table(:payment_methods) do
add :name, :string
end
end
end
| 17.5 | 55 | 0.725714 |
03cdc574d452524ae4ee9cf2dcd1734793907daf | 8,854 | exs | Elixir | test/elixir/test/view_multi_key_design_test.exs | frapa/couchdb | 6c28960f0fe2eec06aca7d58fd73f3c7cdbe1112 | [
"Apache-2.0"
] | 1 | 2022-01-14T20:52:55.000Z | 2022-01-14T20:52:55.000Z | test/elixir/test/view_multi_key_design_test.exs | frapa/couchdb | 6c28960f0fe2eec06aca7d58fd73f3c7cdbe1112 | [
"Apache-2.0"
] | 1 | 2021-07-28T02:13:39.000Z | 2021-07-28T02:13:39.000Z | test/elixir/test/view_multi_key_design_test.exs | frapa/couchdb | 6c28960f0fe2eec06aca7d58fd73f3c7cdbe1112 | [
"Apache-2.0"
] | null | null | null | defmodule ViewMultiKeyDesignTest do
use CouchTestCase
@moduletag :view_multi_key_design
@moduletag kind: :single_node
@keys [10, 15, 30, 37, 50]
@ddoc %{
_id: "_design/test",
language: "javascript",
views: %{
all_docs: %{
map: "function(doc) { emit(doc.integer, doc.string) }"
},
multi_emit: %{
map: "function(doc) {for(var i = 0 ; i < 3 ; i++) { emit(i, doc.integer) ; } }"
},
summate: %{
map: "function (doc) {emit(doc.integer, doc.integer)};",
reduce: "function (keys, values) { return sum(values); };"
}
}
}
setup_all do
db_name = random_db_name()
{:ok, _} = create_db(db_name)
on_exit(fn -> delete_db(db_name) end)
bulk_save(db_name, make_docs(0..99))
{:ok, _} = create_doc(db_name, @ddoc)
{:ok, [db_name: db_name]}
end
test "that missing keys work too", context do
db_name = context[:db_name]
keys = [101, 30, 15, 37, 50]
resp = view(db_name, "test/summate", [group: true], keys)
rows = resp.body["rows"]
assert length(rows) == length(keys) - 1
assert Enum.all?(rows, &Enum.member?(keys, &1["key"]))
assert Enum.all?(rows, &(&1["key"] == &1["value"]))
end
test "keys in POST body", context do
db_name = context[:db_name]
resp = view(db_name, "test/all_docs", nil, @keys)
rows = resp.body["rows"]
assert length(rows) == length(@keys)
assert Enum.all?(rows, &Enum.member?(@keys, &1["key"]))
assert Enum.all?(rows, &(&1["key"] == String.to_integer(&1["value"])))
end
test "keys in GET parameters", context do
db_name = context[:db_name]
resp = view(db_name, "test/all_docs", keys: :jiffy.encode(@keys))
rows = resp.body["rows"]
assert length(rows) == length(@keys)
assert Enum.all?(rows, &Enum.member?(@keys, &1["key"]))
assert Enum.all?(rows, &(&1["key"] == String.to_integer(&1["value"])))
end
test "empty keys", context do
db_name = context[:db_name]
resp = view(db_name, "test/all_docs", keys: :jiffy.encode([]))
assert resp.status_code == 200
rows = resp.body["rows"]
assert Enum.empty?(rows)
end
test "keys in POST body (group)", context do
db_name = context[:db_name]
resp = view(db_name, "test/summate", [group: true], @keys)
rows = resp.body["rows"]
assert length(rows) == length(@keys)
assert Enum.all?(rows, &Enum.member?(@keys, &1["key"]))
assert Enum.all?(rows, &(&1["key"] == &1["value"]))
end
test "keys in GET body (group)", context do
db_name = context[:db_name]
resp = view(db_name, "test/summate", group: true, keys: :jiffy.encode(@keys))
rows = resp.body["rows"]
assert length(rows) == length(@keys)
assert Enum.all?(rows, &Enum.member?(@keys, &1["key"]))
assert Enum.all?(rows, &(&1["key"] == &1["value"]))
end
test "POST - invalid parameter combinations get rejected ", context do
db_name = context[:db_name]
badargs = [[startkey: 0], [endkey: 0], [key: 0], [group_level: 2]]
Enum.each(badargs, fn args ->
resp =
Couch.post("/#{db_name}/_design/test/_view/all_docs",
query: args,
body: %{"keys" => @keys}
)
assert resp.status_code == 400
assert resp.body["error"] == "query_parse_error"
end)
resp =
Couch.post("/#{db_name}/_design/test/_view/summate",
query: nil,
body: %{"keys" => @keys}
)
assert resp.status_code == 400
assert resp.body["error"] == "query_parse_error"
end
test "GET - invalid parameter combinations get rejected ", context do
db_name = context[:db_name]
badargs = [
[startkey: 0, keys: :jiffy.encode(@keys)],
[endkey: 0, keys: :jiffy.encode(@keys)],
[key: 0, keys: :jiffy.encode(@keys)],
[group_level: 2, keys: :jiffy.encode(@keys)]
]
Enum.each(badargs, fn args ->
resp =
Couch.get("/#{db_name}/_design/test/_view/all_docs",
query: args
)
assert resp.status_code == 400
assert resp.body["error"] == "query_parse_error"
end)
resp =
Couch.get("/#{db_name}/_design/test/_view/summate",
query: [keys: :jiffy.encode(@keys)],
body: %{"keys" => @keys}
)
assert resp.status_code == 400
assert resp.body["error"] == "query_parse_error"
end
test "that a map & reduce containing func support keys when reduce=false", context do
db_name = context[:db_name]
resp = view(db_name, "test/summate", [reduce: false], @keys)
assert length(resp.body["rows"]) == 5
resp = view(db_name, "test/summate", reduce: false, keys: :jiffy.encode(@keys))
assert length(resp.body["rows"]) == 5
end
test "that limiting by startkey_docid and endkey_docid get applied", context do
db_name = context[:db_name]
exp_key = [0, 0, 0, 2, 2, 2]
exp_val = [21, 22, 23, 21, 22, 23]
resp =
view(db_name, "test/multi_emit", [startkey_docid: 21, endkey_docid: 23], [0, 2])
rows = resp.body["rows"]
rows_key = Enum.map(rows, & &1["key"])
assert rows_key == exp_key
rows_value = Enum.map(rows, & &1["value"])
assert rows_value == exp_val
resp =
view(db_name, "test/multi_emit",
startkey_docid: 21,
endkey_docid: 23,
keys: :jiffy.encode([0, 2])
)
rows = resp.body["rows"]
rows_key = Enum.map(rows, & &1["key"])
assert rows_key == exp_key
rows_value = Enum.map(rows, & &1["value"])
assert rows_value == exp_val
end
test "limit works", context do
db_name = context[:db_name]
resp = view(db_name, "test/all_docs", [limit: 1], @keys)
rows = resp.body["rows"]
assert length(rows) == 1
assert Enum.at(rows, 0)["key"] == 10
resp = view(db_name, "test/all_docs", limit: 1, keys: :jiffy.encode(@keys))
rows = resp.body["rows"]
assert length(rows) == 1
assert Enum.at(rows, 0)["key"] == 10
end
test "offset works", context do
db_name = context[:db_name]
resp = view(db_name, "test/multi_emit", [skip: 1], [0])
rows = resp.body["rows"]
assert length(rows) == 99
resp = view(db_name, "test/multi_emit", skip: 1, keys: :jiffy.encode([0]))
rows = resp.body["rows"]
assert length(rows) == 99
end
test "dir works", context do
db_name = context[:db_name]
resp = view(db_name, "test/multi_emit", [descending: true], [1])
rows = resp.body["rows"]
assert length(rows) == 100
resp = view(db_name, "test/multi_emit", descending: true, keys: :jiffy.encode([1]))
rows = resp.body["rows"]
assert length(rows) == 100
end
test "argument combinations", context do
db_name = context[:db_name]
resp = view(db_name, "test/multi_emit", [descending: true, skip: 3, limit: 2], [2])
rows = resp.body["rows"]
assert length(rows) == 2
resp =
view(db_name, "test/multi_emit",
descending: true,
skip: 3,
limit: 2,
keys: :jiffy.encode([2])
)
rows = resp.body["rows"]
assert length(rows) == 2
resp =
view(db_name, "test/multi_emit", [skip: 0, limit: 1, startkey_docid: "13"], [0])
rows = resp.body["rows"]
assert length(rows) == 1
assert Enum.at(rows, 0)["value"] == 13
resp =
view(db_name, "test/multi_emit", [skip: 2, limit: 3, startkey_docid: "13"], [0])
rows = resp.body["rows"]
assert length(rows) == 3
resp =
view(db_name, "test/multi_emit",
skip: 2,
limit: 3,
startkey_docid: "13",
keys: :jiffy.encode([0])
)
rows = resp.body["rows"]
assert length(rows) == 3
resp =
view(
db_name,
"test/multi_emit",
[skip: 1, limit: 5, startkey_docid: "25", endkey_docid: "27"],
[1]
)
rows = resp.body["rows"]
assert length(rows) == 2
assert Enum.at(rows, 0)["value"] == 26 or assert(Enum.at(rows, 0)["value"] == 27)
resp =
view(db_name, "test/multi_emit",
skip: 1,
limit: 5,
startkey_docid: "25",
endkey_docid: "27",
keys: :jiffy.encode([1])
)
rows = resp.body["rows"]
assert length(rows) == 2
assert Enum.at(rows, 0)["value"] == 26 or assert(Enum.at(rows, 0)["value"] == 27)
resp =
view(
db_name,
"test/multi_emit",
[skip: 1, limit: 5, startkey_docid: "28", endkey_docid: "26", descending: true],
[1]
)
rows = resp.body["rows"]
assert length(rows) == 2
assert Enum.at(rows, 0)["value"] == 26 or assert(Enum.at(rows, 0)["value"] == 27)
resp =
view(db_name, "test/multi_emit",
skip: 1,
limit: 5,
startkey_docid: "28",
endkey_docid: "26",
descending: true,
keys: :jiffy.encode([1])
)
rows = resp.body["rows"]
assert length(rows) == 2
end
end
| 27.66875 | 88 | 0.577818 |
03ce065244d79e0170b16c27530a05a59b02c89a | 20,341 | ex | Elixir | lib/ash/actions/side_load.ex | elbow-jason/ash | eb63bc9d4d24187ad07d9892088b4e55ad6258e4 | [
"MIT"
] | null | null | null | lib/ash/actions/side_load.ex | elbow-jason/ash | eb63bc9d4d24187ad07d9892088b4e55ad6258e4 | [
"MIT"
] | null | null | null | lib/ash/actions/side_load.ex | elbow-jason/ash | eb63bc9d4d24187ad07d9892088b4e55ad6258e4 | [
"MIT"
] | null | null | null | defmodule Ash.Actions.SideLoad do
@moduledoc false
alias Ash.Engine
alias Ash.Engine.Request
def requests(
query,
use_data_for_filter? \\ true,
root_data \\ [],
root_query \\ nil,
path \\ []
)
def requests(nil, _, _, _, _), do: []
def requests(%{side_load: []}, _, _, _root_query, _), do: []
def requests(
%{side_load: side_loads} = query,
use_data_for_filter?,
root_data,
root_query,
path
) do
root_query = root_query || query
side_loads
|> List.wrap()
|> Enum.flat_map(fn {relationship, further} ->
relationship = Ash.Resource.relationship(query.resource, relationship)
related_query =
case further do
%Ash.Query{} = query ->
Ash.Query.set_api(query, root_query.api)
further ->
relationship.destination
|> Ash.Query.new(root_query.api)
|> Ash.Query.load(further)
end
new_path = [relationship | path]
requests(related_query, use_data_for_filter?, root_data, root_query, new_path) ++
do_requests(
relationship,
related_query,
path,
root_query,
root_data,
use_data_for_filter?
)
end)
end
def attach_side_loads([%resource{} | _] = data, %{side_load: side_loads})
when is_list(data) do
side_loads
|> Enum.sort_by(fn {key, _value} ->
last_relationship = last_relationship!(resource, key)
# We want to do `many_to_many` last, so we know we've
# done their join assocs first. Pretty hacky
{length(key), last_relationship.type == :many_to_many}
end)
|> Enum.reduce(data, fn {key, value}, data ->
last_relationship = last_relationship!(resource, key)
lead_path = :lists.droplast(key)
case last_relationship do
%{type: :many_to_many} ->
attach_many_to_many_side_loads(
data,
lead_path,
last_relationship,
side_loads,
value
)
%{cardinality: :many} ->
attach_to_many_side_loads(value, last_relationship, data, lead_path)
%{cardinality: :one} ->
attach_to_one_side_loads(value, last_relationship, data, lead_path)
end
end)
end
def attach_side_loads(data, state) when not is_list(data) do
[data]
|> attach_side_loads(state)
|> List.first()
end
def attach_side_loads(data, _) do
data
end
defp attach_to_many_side_loads(value, last_relationship, data, lead_path) do
values = Enum.group_by(value, &Map.get(&1, last_relationship.destination_field))
map_or_update(data, lead_path, fn record ->
source_key = Map.get(record, last_relationship.source_field)
related_records = Map.get(values, source_key, [])
Map.put(record, last_relationship.name, related_records)
end)
end
defp attach_to_one_side_loads(value, last_relationship, data, lead_path) do
values =
Enum.into(value, %{}, fn item ->
{Map.get(item, last_relationship.destination_field), item}
end)
map_or_update(data, lead_path, fn record ->
source_key = Map.get(record, last_relationship.source_field)
related_record = Map.get(values, source_key)
Map.put(record, last_relationship.name, related_record)
end)
end
defp attach_many_to_many_side_loads(data, lead_path, last_relationship, side_loads, value) do
join_path = lead_path ++ [last_relationship.join_relationship]
join_data =
side_loads
|> Map.get(join_path, [])
map_or_update(data, lead_path, fn record ->
source_value = Map.get(record, last_relationship.source_field)
join_values =
join_data
|> Enum.filter(fn join_row ->
Map.get(join_row, last_relationship.source_field_on_join_table) ==
source_value
end)
|> Enum.map(&Map.get(&1, last_relationship.destination_field_on_join_table))
related_records =
value
|> Enum.filter(fn value ->
destination_value = Map.get(value, last_relationship.destination_field)
destination_value in join_values
end)
Map.put(record, last_relationship.name, related_records)
end)
end
defp map_or_update(nil, _, _), do: nil
defp map_or_update(record, [], func) when not is_list(record), do: func.(record)
defp map_or_update(records, [], func) do
Enum.map(records, fn record ->
if record do
func.(record)
else
nil
end
end)
end
defp map_or_update(records, [path | tail], func) do
map_or_update(records, [], fn record ->
Map.update!(record, path, &map_or_update(&1, tail, func))
end)
end
defp last_relationship!(resource, [last]) do
Ash.Resource.relationship(resource, last) || raise "Assumption Failed"
end
defp last_relationship!(resource, [first | rest]) do
relationship = Ash.Resource.relationship(resource, first) || raise "Assumption Failed"
last_relationship!(relationship.destination, rest)
end
defp do_requests(relationship, related_query, path, root_query, root_data, use_data_for_filter?) do
side_load_request =
side_load_request(
relationship,
related_query,
root_query,
path,
root_data,
use_data_for_filter?
)
case relationship.type do
:many_to_many ->
case join_assoc_request(
relationship,
related_query,
root_query,
path,
root_data,
use_data_for_filter?
) do
nil ->
[side_load_request]
request ->
[side_load_request, request]
end
_ ->
[side_load_request]
end
end
defp side_load_request(
relationship,
related_query,
root_query,
path,
root_data,
use_data_for_filter?
) do
request_path = [
:side_load,
Enum.reverse(Enum.map([relationship | path], &Map.get(&1, :name)))
]
dependencies =
case path do
[] ->
[request_path ++ [:authorization_filter]]
dependent_path ->
[
request_path ++ [:authorization_filter],
[:side_load, Enum.reverse(Enum.map(dependent_path, &Map.get(&1, :name))), :data]
]
end
dependencies =
if use_data_for_filter? do
[[:data, :data] | dependencies]
else
dependencies
end
dependencies =
if relationship.type == :many_to_many do
join_relationship = join_relationship(relationship)
[
[
:side_load,
Enum.map(join_relationship_path(path, join_relationship), & &1.name),
:data
]
| dependencies
]
else
dependencies
end
source =
[relationship | path]
|> Enum.reverse()
|> Enum.map_join(".", &Map.get(&1, :name))
Engine.Request.new(
action: Ash.Resource.primary_action!(relationship.destination, :read),
resource: relationship.destination,
name: "side_load #{source}",
api: related_query.api,
path: request_path,
query:
side_load_query(
relationship,
related_query,
path,
root_query,
use_data_for_filter?
),
data:
Request.resolve(dependencies, fn data ->
base_query =
case get_in(data, request_path ++ [:authorization_filter]) do
nil ->
related_query
authorization_filter ->
Ash.Query.filter(related_query, authorization_filter)
end
with {:ok, new_query} <-
true_side_load_query(
relationship,
base_query,
data,
path,
root_data,
use_data_for_filter?
),
{:ok, results} <-
run_actual_query(
root_data,
new_query,
data,
path,
use_data_for_filter?,
relationship
) do
{:ok, results}
else
{:error, error} -> {:error, error}
end
end)
)
end
defp join_relationship(relationship) do
Ash.Resource.relationship(relationship.source, relationship.join_relationship)
end
defp join_relationship_path(path, join_relationship) do
Enum.reverse([join_relationship | path])
end
defp join_assoc_request(
relationship,
related_query,
root_query,
path,
root_data,
use_data_for_filter?
) do
join_relationship = join_relationship(relationship)
join_relationship_name = join_relationship.name
case path do
[%{name: ^join_relationship_name} | _] ->
nil
path ->
join_relationship_path = join_relationship_path(path, join_relationship)
join_relationship_path_names = Enum.map(join_relationship_path, & &1.name)
dependencies =
if path == [] do
[[:side_load, join_relationship_path_names, :authorization_filter]]
else
[
[:side_load, join_relationship_path_names, :authorization_filter],
[:side_load, Enum.reverse(Enum.map(path, &Map.get(&1, :name))), :data]
]
end
dependencies =
if use_data_for_filter? do
[[:data, :data] | dependencies]
else
dependencies
end
related_query = Ash.Query.new(join_relationship.destination, related_query.api)
Request.new(
action: Ash.Resource.primary_action!(relationship.destination, :read),
resource: relationship.through,
name: "side_load join #{join_relationship.name}",
api: related_query.api,
path: [:side_load, join_relationship_path_names],
query:
side_load_query(
join_relationship,
related_query,
join_relationship_path,
root_query,
use_data_for_filter?
),
data:
Request.resolve(dependencies, fn data ->
base_query =
case get_in(data, [
:side_load,
join_relationship_path_names,
:authorization_filter
]) do
nil ->
related_query
authorization_filter ->
Ash.Query.filter(related_query, authorization_filter)
end
with {:ok, new_query} <-
true_side_load_query(
join_relationship,
base_query,
data,
path,
root_data,
use_data_for_filter?
),
{:ok, results} <-
run_actual_query(
root_data,
new_query,
data,
path,
use_data_for_filter?,
relationship
) do
{:ok, results}
else
{:error, error} -> {:error, error}
end
end)
)
end
end
defp run_actual_query(root_data, query, data, path, use_data?, relationship) do
offset? = is_nil(query.offset) || query.offset != 0
source_data =
case path do
[] when use_data? ->
get_in(data, [:data, :data])
[] ->
root_data
path ->
data
|> Map.get(:side_load, %{})
|> Map.get(path, %{})
|> Map.get(:data, [])
end
cond do
(query.limit ||
offset?) && relationship.type != :many_to_many &&
Ash.Resource.data_layer_can?(
relationship.source,
{:lateral_join, relationship.destination}
) ->
query
|> Ash.Query.set_datalayer_context(%{
lateral_join_source:
{source_data, relationship.source, relationship.source_field,
relationship.destination_field}
})
|> query.api.read()
(query.limit || offset?) && relationship.type != :many_to_many ->
artificial_limit_and_offset(query, relationship)
true ->
query.api.read(query)
end
end
defp artificial_limit_and_offset(query, relationship) do
case query.api.read(query) do
{:ok, results} ->
new_results =
results
|> Enum.group_by(fn record ->
Map.get(record, relationship.destination_key)
end)
|> Enum.flat_map(fn {_, group} ->
offset_records = Enum.drop(group, query.offset || 0)
if query.limit do
Enum.take(offset_records, query.limit)
else
offset_records
end
end)
{:ok, new_results}
{:error, error} ->
{:error, error}
end
end
defp side_load_query_with_reverse_path(
root_query,
related_query,
reverse_path,
root_data_filter
) do
case Ash.Filter.parse(root_query.resource, root_query.filter) do
{:ok, parsed} ->
root_filter = Ash.Filter.remove_aggregates(parsed)
related_query
|> Ash.Query.unset(:side_load)
|> Ash.Query.filter(
put_nested_relationship(
[],
reverse_path,
root_data_filter,
false
)
)
|> Ash.Query.filter(put_nested_relationship([], reverse_path, root_filter, false))
|> Ash.Query.filter(related_query.filter)
|> extract_errors()
{:error, error} ->
{:error, error}
end
end
defp side_load_query(
relationship,
related_query,
path,
root_query,
true
) do
Request.resolve([[:data, :data]], fn %{data: %{data: data}} ->
root_data_filter =
case data do
[] ->
false
[%resource{} = item] ->
item
|> Map.take(Ash.Resource.primary_key(resource))
|> Enum.to_list()
[%resource{} | _] = items ->
pkey = Ash.Resource.primary_key(resource)
[or: Enum.map(items, fn item -> item |> Map.take(pkey) |> Enum.to_list() end)]
end
case reverse_relationship_path(relationship, Enum.drop(path, 1)) do
{:ok, reverse_path} ->
side_load_query_with_reverse_path(
root_query,
related_query,
reverse_path,
root_data_filter
)
_ ->
relationship.destination
|> Ash.Query.new(related_query.api)
|> Ash.Query.filter(related_query.filter)
|> extract_errors()
end
end)
end
defp side_load_query(
relationship,
related_query,
path,
root_query,
false
) do
case reverse_relationship_path(relationship, path) do
{:ok, reverse_path} ->
case Ash.Filter.parse(root_query.resource, root_query.filter) do
{:ok, parsed} ->
root_filter = Ash.Filter.remove_aggregates(parsed)
related_query
|> Ash.Query.filter(
put_nested_relationship(
[],
reverse_path,
root_filter,
false
)
)
|> Ash.Query.unset(:side_load)
{:error, error} ->
{:error, error}
end
:error ->
related_query
|> Ash.Query.unset(:side_load)
end
end
defp extract_errors(%{errors: []} = item), do: {:ok, item}
defp extract_errors(%{errors: errors}), do: {:error, errors}
defp true_side_load_query(relationship, query, data, path, root_data, use_data?) do
{source_field, path} =
if relationship.type == :many_to_many do
join_relationship = join_relationship(relationship)
{relationship.destination_field_on_join_table,
join_relationship_path(path, join_relationship) |> Enum.map(& &1.name)}
else
{relationship.source_field, path |> Enum.reverse() |> Enum.map(& &1.name)}
end
source_data =
case path do
[] when use_data? ->
Map.get(data, :data)
[] ->
%{data: root_data}
path ->
data
|> Map.get(:side_load, %{})
|> Map.get(path, %{})
end
get_query(query, relationship, source_data, source_field)
end
defp get_query(query, relationship, source_data, source_field) do
offset? = is_nil(query.offset) || query.offset != 0
cond do
(query.limit ||
offset?) && relationship.type != :many_to_many &&
Ash.Resource.data_layer_can?(
relationship.source,
{:lateral_join, relationship.destination}
) ->
{:ok, Ash.Query.unset(query, :side_load)}
(query.limit || offset?) && relationship.type != :many_to_many ->
{:ok, Ash.Query.unset(query, [:side_load, :limit, :offset])}
true ->
related_data = Map.get(source_data || %{}, :data, [])
ids =
Enum.flat_map(related_data, fn data ->
data
|> Map.get(source_field)
|> List.wrap()
end)
filter_value =
case ids do
[id] ->
id
ids ->
[in: ids]
end
new_query =
query
|> Ash.Query.filter([{relationship.destination_field, filter_value}])
{:ok, new_query}
end
end
def reverse_relationship_path(relationship, prior_path, acc \\ [])
def reverse_relationship_path(relationship, [], acc) do
relationship.destination
|> Ash.Resource.relationships()
|> Enum.find(fn destination_relationship ->
reverse_relationship?(relationship, destination_relationship)
end)
|> case do
nil ->
:error
reverse ->
{:ok, Enum.reverse([reverse.name | acc])}
end
end
def reverse_relationship_path(relationship, [next_relationship | rest], acc) do
relationship.destination
|> Ash.Resource.relationships()
|> Enum.find(fn destination_relationship ->
reverse_relationship?(relationship, destination_relationship)
end)
|> case do
nil ->
:error
reverse ->
reverse_relationship_path(next_relationship, rest, [reverse.name | acc])
end
end
defp reverse_relationship?(rel, destination_rel) do
rel.source == destination_rel.destination &&
rel.source_field == destination_rel.destination_field &&
rel.destination_field == destination_rel.source_field &&
Map.fetch(rel, :source_field_on_join_table) ==
Map.fetch(destination_rel, :destination_field_on_join_table) &&
Map.fetch(rel, :destination_field_on_join_table) ==
Map.fetch(destination_rel, :source_field_on_join_table)
end
defp put_nested_relationship(request_filter, path, value, records?) when not is_list(value) do
put_nested_relationship(request_filter, path, [value], records?)
end
defp put_nested_relationship(request_filter, [rel | rest], values, records?) do
[
{rel, put_nested_relationship(request_filter, rest, values, records?)}
]
end
defp put_nested_relationship(request_filter, [], [{field, value}], _) do
[{field, value} | request_filter]
end
defp put_nested_relationship(request_filter, [], [{field, _} | _] = keys, _) do
[{field, [{:in, Enum.map(keys, &elem(&1, 1))}]} | request_filter]
end
defp put_nested_relationship(request_filter, [], [values], _) do
List.wrap(request_filter) ++ List.wrap(values)
end
defp put_nested_relationship(request_filter, [], values, _) do
Keyword.update(request_filter, :or, values, &Kernel.++(&1, values))
end
end
| 27.826265 | 101 | 0.565803 |
03ce2d4a1df1d4a46e91132e50c86e70ff383d01 | 28,155 | ex | Elixir | lib/codes/codes_t54.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_t54.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_t54.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_T54 do
alias IcdCode.ICDCode
def _T540X1A do
%ICDCode{full_code: "T540X1A",
category_code: "T54",
short_code: "0X1A",
full_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), initial encounter",
short_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), initial encounter",
category_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), initial encounter"
}
end
def _T540X1D do
%ICDCode{full_code: "T540X1D",
category_code: "T54",
short_code: "0X1D",
full_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), subsequent encounter",
short_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), subsequent encounter",
category_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), subsequent encounter"
}
end
def _T540X1S do
%ICDCode{full_code: "T540X1S",
category_code: "T54",
short_code: "0X1S",
full_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), sequela",
short_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), sequela",
category_name: "Toxic effect of phenol and phenol homologues, accidental (unintentional), sequela"
}
end
def _T540X2A do
%ICDCode{full_code: "T540X2A",
category_code: "T54",
short_code: "0X2A",
full_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, initial encounter",
short_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, initial encounter",
category_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, initial encounter"
}
end
def _T540X2D do
%ICDCode{full_code: "T540X2D",
category_code: "T54",
short_code: "0X2D",
full_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, subsequent encounter",
short_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, subsequent encounter",
category_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, subsequent encounter"
}
end
def _T540X2S do
%ICDCode{full_code: "T540X2S",
category_code: "T54",
short_code: "0X2S",
full_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, sequela",
short_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, sequela",
category_name: "Toxic effect of phenol and phenol homologues, intentional self-harm, sequela"
}
end
def _T540X3A do
%ICDCode{full_code: "T540X3A",
category_code: "T54",
short_code: "0X3A",
full_name: "Toxic effect of phenol and phenol homologues, assault, initial encounter",
short_name: "Toxic effect of phenol and phenol homologues, assault, initial encounter",
category_name: "Toxic effect of phenol and phenol homologues, assault, initial encounter"
}
end
def _T540X3D do
%ICDCode{full_code: "T540X3D",
category_code: "T54",
short_code: "0X3D",
full_name: "Toxic effect of phenol and phenol homologues, assault, subsequent encounter",
short_name: "Toxic effect of phenol and phenol homologues, assault, subsequent encounter",
category_name: "Toxic effect of phenol and phenol homologues, assault, subsequent encounter"
}
end
def _T540X3S do
%ICDCode{full_code: "T540X3S",
category_code: "T54",
short_code: "0X3S",
full_name: "Toxic effect of phenol and phenol homologues, assault, sequela",
short_name: "Toxic effect of phenol and phenol homologues, assault, sequela",
category_name: "Toxic effect of phenol and phenol homologues, assault, sequela"
}
end
def _T540X4A do
%ICDCode{full_code: "T540X4A",
category_code: "T54",
short_code: "0X4A",
full_name: "Toxic effect of phenol and phenol homologues, undetermined, initial encounter",
short_name: "Toxic effect of phenol and phenol homologues, undetermined, initial encounter",
category_name: "Toxic effect of phenol and phenol homologues, undetermined, initial encounter"
}
end
def _T540X4D do
%ICDCode{full_code: "T540X4D",
category_code: "T54",
short_code: "0X4D",
full_name: "Toxic effect of phenol and phenol homologues, undetermined, subsequent encounter",
short_name: "Toxic effect of phenol and phenol homologues, undetermined, subsequent encounter",
category_name: "Toxic effect of phenol and phenol homologues, undetermined, subsequent encounter"
}
end
def _T540X4S do
%ICDCode{full_code: "T540X4S",
category_code: "T54",
short_code: "0X4S",
full_name: "Toxic effect of phenol and phenol homologues, undetermined, sequela",
short_name: "Toxic effect of phenol and phenol homologues, undetermined, sequela",
category_name: "Toxic effect of phenol and phenol homologues, undetermined, sequela"
}
end
def _T541X1A do
%ICDCode{full_code: "T541X1A",
category_code: "T54",
short_code: "1X1A",
full_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), initial encounter",
short_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), initial encounter",
category_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), initial encounter"
}
end
def _T541X1D do
%ICDCode{full_code: "T541X1D",
category_code: "T54",
short_code: "1X1D",
full_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), subsequent encounter",
short_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), subsequent encounter",
category_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), subsequent encounter"
}
end
def _T541X1S do
%ICDCode{full_code: "T541X1S",
category_code: "T54",
short_code: "1X1S",
full_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), sequela",
short_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), sequela",
category_name: "Toxic effect of other corrosive organic compounds, accidental (unintentional), sequela"
}
end
def _T541X2A do
%ICDCode{full_code: "T541X2A",
category_code: "T54",
short_code: "1X2A",
full_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, initial encounter",
short_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, initial encounter",
category_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, initial encounter"
}
end
def _T541X2D do
%ICDCode{full_code: "T541X2D",
category_code: "T54",
short_code: "1X2D",
full_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, subsequent encounter",
short_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, subsequent encounter",
category_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, subsequent encounter"
}
end
def _T541X2S do
%ICDCode{full_code: "T541X2S",
category_code: "T54",
short_code: "1X2S",
full_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, sequela",
short_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, sequela",
category_name: "Toxic effect of other corrosive organic compounds, intentional self-harm, sequela"
}
end
def _T541X3A do
%ICDCode{full_code: "T541X3A",
category_code: "T54",
short_code: "1X3A",
full_name: "Toxic effect of other corrosive organic compounds, assault, initial encounter",
short_name: "Toxic effect of other corrosive organic compounds, assault, initial encounter",
category_name: "Toxic effect of other corrosive organic compounds, assault, initial encounter"
}
end
def _T541X3D do
%ICDCode{full_code: "T541X3D",
category_code: "T54",
short_code: "1X3D",
full_name: "Toxic effect of other corrosive organic compounds, assault, subsequent encounter",
short_name: "Toxic effect of other corrosive organic compounds, assault, subsequent encounter",
category_name: "Toxic effect of other corrosive organic compounds, assault, subsequent encounter"
}
end
def _T541X3S do
%ICDCode{full_code: "T541X3S",
category_code: "T54",
short_code: "1X3S",
full_name: "Toxic effect of other corrosive organic compounds, assault, sequela",
short_name: "Toxic effect of other corrosive organic compounds, assault, sequela",
category_name: "Toxic effect of other corrosive organic compounds, assault, sequela"
}
end
def _T541X4A do
%ICDCode{full_code: "T541X4A",
category_code: "T54",
short_code: "1X4A",
full_name: "Toxic effect of other corrosive organic compounds, undetermined, initial encounter",
short_name: "Toxic effect of other corrosive organic compounds, undetermined, initial encounter",
category_name: "Toxic effect of other corrosive organic compounds, undetermined, initial encounter"
}
end
def _T541X4D do
%ICDCode{full_code: "T541X4D",
category_code: "T54",
short_code: "1X4D",
full_name: "Toxic effect of other corrosive organic compounds, undetermined, subsequent encounter",
short_name: "Toxic effect of other corrosive organic compounds, undetermined, subsequent encounter",
category_name: "Toxic effect of other corrosive organic compounds, undetermined, subsequent encounter"
}
end
def _T541X4S do
%ICDCode{full_code: "T541X4S",
category_code: "T54",
short_code: "1X4S",
full_name: "Toxic effect of other corrosive organic compounds, undetermined, sequela",
short_name: "Toxic effect of other corrosive organic compounds, undetermined, sequela",
category_name: "Toxic effect of other corrosive organic compounds, undetermined, sequela"
}
end
def _T542X1A do
%ICDCode{full_code: "T542X1A",
category_code: "T54",
short_code: "2X1A",
full_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), initial encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), initial encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), initial encounter"
}
end
def _T542X1D do
%ICDCode{full_code: "T542X1D",
category_code: "T54",
short_code: "2X1D",
full_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), subsequent encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), subsequent encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), subsequent encounter"
}
end
def _T542X1S do
%ICDCode{full_code: "T542X1S",
category_code: "T54",
short_code: "2X1S",
full_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), sequela",
short_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), sequela",
category_name: "Toxic effect of corrosive acids and acid-like substances, accidental (unintentional), sequela"
}
end
def _T542X2A do
%ICDCode{full_code: "T542X2A",
category_code: "T54",
short_code: "2X2A",
full_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, initial encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, initial encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, initial encounter"
}
end
def _T542X2D do
%ICDCode{full_code: "T542X2D",
category_code: "T54",
short_code: "2X2D",
full_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, subsequent encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, subsequent encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, subsequent encounter"
}
end
def _T542X2S do
%ICDCode{full_code: "T542X2S",
category_code: "T54",
short_code: "2X2S",
full_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, sequela",
short_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, sequela",
category_name: "Toxic effect of corrosive acids and acid-like substances, intentional self-harm, sequela"
}
end
def _T542X3A do
%ICDCode{full_code: "T542X3A",
category_code: "T54",
short_code: "2X3A",
full_name: "Toxic effect of corrosive acids and acid-like substances, assault, initial encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, assault, initial encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, assault, initial encounter"
}
end
def _T542X3D do
%ICDCode{full_code: "T542X3D",
category_code: "T54",
short_code: "2X3D",
full_name: "Toxic effect of corrosive acids and acid-like substances, assault, subsequent encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, assault, subsequent encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, assault, subsequent encounter"
}
end
def _T542X3S do
%ICDCode{full_code: "T542X3S",
category_code: "T54",
short_code: "2X3S",
full_name: "Toxic effect of corrosive acids and acid-like substances, assault, sequela",
short_name: "Toxic effect of corrosive acids and acid-like substances, assault, sequela",
category_name: "Toxic effect of corrosive acids and acid-like substances, assault, sequela"
}
end
def _T542X4A do
%ICDCode{full_code: "T542X4A",
category_code: "T54",
short_code: "2X4A",
full_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, initial encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, initial encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, initial encounter"
}
end
def _T542X4D do
%ICDCode{full_code: "T542X4D",
category_code: "T54",
short_code: "2X4D",
full_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, subsequent encounter",
short_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, subsequent encounter",
category_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, subsequent encounter"
}
end
def _T542X4S do
%ICDCode{full_code: "T542X4S",
category_code: "T54",
short_code: "2X4S",
full_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, sequela",
short_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, sequela",
category_name: "Toxic effect of corrosive acids and acid-like substances, undetermined, sequela"
}
end
def _T543X1A do
%ICDCode{full_code: "T543X1A",
category_code: "T54",
short_code: "3X1A",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), initial encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), initial encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), initial encounter"
}
end
def _T543X1D do
%ICDCode{full_code: "T543X1D",
category_code: "T54",
short_code: "3X1D",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), subsequent encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), subsequent encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), subsequent encounter"
}
end
def _T543X1S do
%ICDCode{full_code: "T543X1S",
category_code: "T54",
short_code: "3X1S",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), sequela",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), sequela",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, accidental (unintentional), sequela"
}
end
def _T543X2A do
%ICDCode{full_code: "T543X2A",
category_code: "T54",
short_code: "3X2A",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, initial encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, initial encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, initial encounter"
}
end
def _T543X2D do
%ICDCode{full_code: "T543X2D",
category_code: "T54",
short_code: "3X2D",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, subsequent encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, subsequent encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, subsequent encounter"
}
end
def _T543X2S do
%ICDCode{full_code: "T543X2S",
category_code: "T54",
short_code: "3X2S",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, sequela",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, sequela",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, intentional self-harm, sequela"
}
end
def _T543X3A do
%ICDCode{full_code: "T543X3A",
category_code: "T54",
short_code: "3X3A",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, initial encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, initial encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, initial encounter"
}
end
def _T543X3D do
%ICDCode{full_code: "T543X3D",
category_code: "T54",
short_code: "3X3D",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, subsequent encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, subsequent encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, subsequent encounter"
}
end
def _T543X3S do
%ICDCode{full_code: "T543X3S",
category_code: "T54",
short_code: "3X3S",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, sequela",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, sequela",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, assault, sequela"
}
end
def _T543X4A do
%ICDCode{full_code: "T543X4A",
category_code: "T54",
short_code: "3X4A",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, initial encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, initial encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, initial encounter"
}
end
def _T543X4D do
%ICDCode{full_code: "T543X4D",
category_code: "T54",
short_code: "3X4D",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, subsequent encounter",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, subsequent encounter",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, subsequent encounter"
}
end
def _T543X4S do
%ICDCode{full_code: "T543X4S",
category_code: "T54",
short_code: "3X4S",
full_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, sequela",
short_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, sequela",
category_name: "Toxic effect of corrosive alkalis and alkali-like substances, undetermined, sequela"
}
end
def _T5491XA do
%ICDCode{full_code: "T5491XA",
category_code: "T54",
short_code: "91XA",
full_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), initial encounter",
short_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), initial encounter",
category_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), initial encounter"
}
end
def _T5491XD do
%ICDCode{full_code: "T5491XD",
category_code: "T54",
short_code: "91XD",
full_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), subsequent encounter",
short_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), subsequent encounter",
category_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), subsequent encounter"
}
end
def _T5491XS do
%ICDCode{full_code: "T5491XS",
category_code: "T54",
short_code: "91XS",
full_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), sequela",
short_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), sequela",
category_name: "Toxic effect of unspecified corrosive substance, accidental (unintentional), sequela"
}
end
def _T5492XA do
%ICDCode{full_code: "T5492XA",
category_code: "T54",
short_code: "92XA",
full_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, initial encounter",
short_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, initial encounter",
category_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, initial encounter"
}
end
def _T5492XD do
%ICDCode{full_code: "T5492XD",
category_code: "T54",
short_code: "92XD",
full_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, subsequent encounter",
short_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, subsequent encounter",
category_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, subsequent encounter"
}
end
def _T5492XS do
%ICDCode{full_code: "T5492XS",
category_code: "T54",
short_code: "92XS",
full_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, sequela",
short_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, sequela",
category_name: "Toxic effect of unspecified corrosive substance, intentional self-harm, sequela"
}
end
def _T5493XA do
%ICDCode{full_code: "T5493XA",
category_code: "T54",
short_code: "93XA",
full_name: "Toxic effect of unspecified corrosive substance, assault, initial encounter",
short_name: "Toxic effect of unspecified corrosive substance, assault, initial encounter",
category_name: "Toxic effect of unspecified corrosive substance, assault, initial encounter"
}
end
def _T5493XD do
%ICDCode{full_code: "T5493XD",
category_code: "T54",
short_code: "93XD",
full_name: "Toxic effect of unspecified corrosive substance, assault, subsequent encounter",
short_name: "Toxic effect of unspecified corrosive substance, assault, subsequent encounter",
category_name: "Toxic effect of unspecified corrosive substance, assault, subsequent encounter"
}
end
def _T5493XS do
%ICDCode{full_code: "T5493XS",
category_code: "T54",
short_code: "93XS",
full_name: "Toxic effect of unspecified corrosive substance, assault, sequela",
short_name: "Toxic effect of unspecified corrosive substance, assault, sequela",
category_name: "Toxic effect of unspecified corrosive substance, assault, sequela"
}
end
def _T5494XA do
%ICDCode{full_code: "T5494XA",
category_code: "T54",
short_code: "94XA",
full_name: "Toxic effect of unspecified corrosive substance, undetermined, initial encounter",
short_name: "Toxic effect of unspecified corrosive substance, undetermined, initial encounter",
category_name: "Toxic effect of unspecified corrosive substance, undetermined, initial encounter"
}
end
def _T5494XD do
%ICDCode{full_code: "T5494XD",
category_code: "T54",
short_code: "94XD",
full_name: "Toxic effect of unspecified corrosive substance, undetermined, subsequent encounter",
short_name: "Toxic effect of unspecified corrosive substance, undetermined, subsequent encounter",
category_name: "Toxic effect of unspecified corrosive substance, undetermined, subsequent encounter"
}
end
def _T5494XS do
%ICDCode{full_code: "T5494XS",
category_code: "T54",
short_code: "94XS",
full_name: "Toxic effect of unspecified corrosive substance, undetermined, sequela",
short_name: "Toxic effect of unspecified corrosive substance, undetermined, sequela",
category_name: "Toxic effect of unspecified corrosive substance, undetermined, sequela"
}
end
end
| 51.471664 | 137 | 0.689362 |
03ce7e6a7b293ab01b29c77f42f449204ee6acaa | 97 | ex | Elixir | lib/exnn.ex | zampino/exnn | 2be888df107644daab1aca7614fecb4940fe3c84 | [
"MIT"
] | 104 | 2015-06-18T18:54:25.000Z | 2021-11-04T15:07:02.000Z | lib/exnn.ex | nelyj/exnn | 2be888df107644daab1aca7614fecb4940fe3c84 | [
"MIT"
] | 3 | 2016-10-09T11:19:42.000Z | 2018-09-17T16:36:32.000Z | lib/exnn.ex | nelyj/exnn | 2be888df107644daab1aca7614fecb4940fe3c84 | [
"MIT"
] | 17 | 2016-03-08T19:02:51.000Z | 2019-04-27T16:40:52.000Z | defmodule EXNN do
@moduledoc """
## Elixir Evolutive Neural Networks à la G.Sher
"""
end
| 12.125 | 49 | 0.659794 |
03ce92660a81cfd0c0e099d0aa807944d90b7c31 | 83 | exs | Elixir | test/test_helper.exs | karabiner-inc/materia_commerce | e1abc1ac223ffd379360995d24a10021db036da1 | [
"Apache-2.0"
] | 1 | 2019-11-19T07:38:38.000Z | 2019-11-19T07:38:38.000Z | test/test_helper.exs | karabiner-inc/materia_commerce | e1abc1ac223ffd379360995d24a10021db036da1 | [
"Apache-2.0"
] | 31 | 2018-12-26T02:05:55.000Z | 2021-05-14T03:33:07.000Z | test/test_helper.exs | karabiner-inc/materia_commerce | e1abc1ac223ffd379360995d24a10021db036da1 | [
"Apache-2.0"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(MateriaCommerce.Test.Repo, :manual)
| 20.75 | 66 | 0.795181 |
03cea8f4774a40438a1c67d21cae1330961da97e | 2,040 | exs | Elixir | apps/legion_http/config/prod.exs | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 1 | 2021-01-04T11:06:12.000Z | 2021-01-04T11:06:12.000Z | apps/legion_http/config/prod.exs | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 3 | 2021-01-30T06:40:37.000Z | 2021-01-30T06:41:08.000Z | apps/legion_http/config/prod.exs | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | null | null | null | use Mix.Config
# For production, we often load configuration from external
# sources, such as your system environment. For this reason,
# you won't find the :http configuration below, but set inside
# Legion.HTTP.Endpoint.init/2 when load_from_system_env is
# true. Any dynamic configuration should be done there.
#
# Don't forget to configure the url host to something meaningful,
# Phoenix uses this information when generating URLs.
#
# Finally, we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the mix phx.digest task
# which you typically run after static files are built.
config :legion_http, Legion.HTTP.Endpoint,
load_from_system_env: true,
url: [port: System.get_env("PORT", "4000") |> Integer.parse() |> elem(0)],
cache_static_manifest: "priv/static/cache_manifest.json"
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :legion_http, Legion.HTTP.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [:inet6,
# port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :legion_http, Legion.HTTP.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :legion_http, Legion.HTTP.Endpoint, server: true
#
| 35.172414 | 76 | 0.714216 |
03cf0aed86d9d1eb41a2327db1d2523fdc49cdd8 | 29,003 | exs | Elixir | apps/language_server/test/providers/completion_test.exs | kianmeng/elixir-ls | 3d7d8c3ae9361af1090805551ce59a5c17d586e0 | [
"Apache-2.0"
] | null | null | null | apps/language_server/test/providers/completion_test.exs | kianmeng/elixir-ls | 3d7d8c3ae9361af1090805551ce59a5c17d586e0 | [
"Apache-2.0"
] | null | null | null | apps/language_server/test/providers/completion_test.exs | kianmeng/elixir-ls | 3d7d8c3ae9361af1090805551ce59a5c17d586e0 | [
"Apache-2.0"
] | null | null | null | defmodule ElixirLS.LanguageServer.Providers.CompletionTest do
use ExUnit.Case
require Logger
alias ElixirLS.LanguageServer.Providers.Completion
alias ElixirLS.Utils.TestUtils
@supports [
snippets_supported: true,
deprecated_supported: false,
tags_supported: [],
signature_help_supported: true,
locals_without_parens: MapSet.new()
]
@signature_command %{
"title" => "Trigger Parameter Hint",
"command" => "editor.action.triggerParameterHints"
}
setup context do
ElixirLS.LanguageServer.Build.load_all_modules()
unless context[:skip_server] do
server = ElixirLS.LanguageServer.Test.ServerTestHelpers.start_server()
{:ok, %{server: server}}
else
:ok
end
end
test "do is returned" do
text = """
defmodule MyModule do
require Logger
def fun do
# ^
end
end
"""
{line, char} = {3, 12}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [first_item | _items]}} =
Completion.completion(text, line, char, @supports)
assert first_item["label"] == "do"
end
test "returns all Logger completions on normal require" do
text = """
defmodule MyModule do
require Logger
def dummy_function() do
Logger.
# ^
end
end
"""
{line, char} = {4, 11}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
logger_labels =
["warn", "debug", "error", "info"]
|> Enum.map(&(&1 <> "/2"))
for lfn <- logger_labels do
assert(Enum.any?(items, fn %{"label" => label} -> label == lfn end))
end
end
test "returns all Logger completions on require with alias" do
text = """
defmodule MyModule do
require Logger, as: LAlias
def dummy_function() do
LAlias.
# ^
end
end
"""
{line, char} = {4, 11}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
logger_labels =
["warn", "debug", "error", "info"]
|> Enum.map(&(&1 <> "/2"))
for lfn <- logger_labels do
assert(Enum.any?(items, fn %{"label" => label} -> label == lfn end))
end
end
test "unless with snippets not supported does not return a completion" do
text = """
defmodule MyModule do
require Logger, as: LAlias
def dummy_function() do
unless
# ^
end
end
"""
{line, char} = {4, 10}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert length(items) == 1
{:ok, %{"items" => items}} =
Completion.completion(
text,
line,
char,
@supports |> Keyword.put(:snippets_supported, false)
)
assert length(items) == 0
end
test "completions of protocols are rendered as an interface" do
text = """
defmodule MyModule do
def dummy_function() do
ElixirLS.LanguageServer.Fixtures.ExampleP
# ^
end
end
"""
{line, char} = {2, 45}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
# 8 is interface
assert item["kind"] == 8
assert item["label"] == "ExampleProtocol (protocol)"
end
test "provides completions for protocol functions" do
text = """
defimpl ElixirLS.LanguageServer.Fixtures.ExampleProtocol, for: MyModule do
#^
end
"""
{line, char} = {1, 1}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
completions =
items
|> Enum.filter(&(&1["detail"] =~ "protocol function"))
|> Enum.map(& &1["label"])
assert completions == [
"def my_fun/2"
]
end
test "completions of behaviours are rendered as an interface" do
text = """
defmodule MyModule do
def dummy_function() do
ElixirLS.LanguageServer.Fixtures.ExampleB
# ^
end
end
"""
{line, char} = {2, 45}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert [item, _] = items
# 8 is interface
assert item["kind"] == 8
assert item["label"] == "ExampleBehaviour (behaviour)"
end
test "completions of exceptions are rendered as a struct" do
text = """
defmodule MyModule do
def dummy_function() do
ElixirLS.LanguageServer.Fixtures.ExampleE
# ^
end
end
"""
{line, char} = {2, 45}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert [item] = items
# 22 is struct
assert item["kind"] == 22
assert item["label"] == "ExampleException (exception)"
end
test "provides completions for callbacks without `def` before" do
text = """
defmodule MyModule do
@behaviour ElixirLS.LanguageServer.Fixtures.ExampleBehaviour
# ^
end
"""
{line, char} = {2, 2}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
first_completion =
items
|> Enum.filter(&(&1["detail"] =~ "callback"))
|> Enum.at(0)
assert first_completion["label"] =~ "def build_greeting"
assert first_completion["insertText"] == "def build_greeting(${1:name}) do\n\t$0\nend"
end
test "provides completions for callbacks with `def` before" do
text = """
defmodule MyModule do
@behaviour ElixirLS.LanguageServer.Fixtures.ExampleBehaviour
def
# ^
end
"""
{line, char} = {3, 5}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
first_completion =
items
|> Enum.filter(&(&1["detail"] =~ "callback"))
|> Enum.at(0)
assert first_completion["label"] =~ "def build_greeting"
end
test "returns module completions after pipe" do
text = """
defmodule MyModule do
NaiveDateTime.utc_now() |> Naiv
# ^
1..100
|> Enum.map(&Inte)
# ^
def my(%Naiv)
# ^
end
"""
{line, char} = {1, 33}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
completions =
items
|> Enum.filter(&(&1["detail"] =~ "struct"))
|> Enum.map(& &1["label"])
assert "NaiveDateTime (struct)" in completions
{line, char} = {4, 17}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
completions =
items
|> Enum.filter(&(&1["detail"] =~ "module"))
|> Enum.map(& &1["label"])
assert "Integer" in completions
{line, char} = {6, 12}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
completions =
items
|> Enum.filter(&(&1["detail"] =~ "struct"))
|> Enum.map(& &1["label"])
assert "NaiveDateTime (struct)" in completions
end
describe "deprecated" do
defp get_deprecated_completion_item(options) do
text = """
ElixirLS.LanguageServer.Fixtures.ExampleDeprecated
^
"""
{line, char} = {0, 50}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, options)
item
end
test "returns deprecated flag when supported" do
assert %{"deprecated" => true} = get_deprecated_completion_item(deprecated_supported: true)
end
test "returns deprecated completion tag when supported" do
assert %{"tags" => [1]} = get_deprecated_completion_item(tags_supported: [1])
end
test "returns no deprecated indicator when not supported" do
# deprecated and tags not supported
item = get_deprecated_completion_item([])
refute Map.has_key?(item, "deprecated")
refute Map.has_key?(item, "tags")
# tags supported but not deprecated tag
assert %{"tags" => []} = get_deprecated_completion_item(tags_supported: [2])
end
end
describe "structs and maps" do
test "completions of structs are rendered as a struct" do
text = """
defmodule MyModule do
def dummy_function() do
ElixirLS.LanguageServer.Fixtures.ExampleS
# ^
end
end
"""
{line, char} = {2, 45}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert [item] = items
# 22 is struct
assert item["kind"] == 22
assert item["label"] == "ExampleStruct (struct)"
end
test "returns struct fields in call syntax" do
text = """
defmodule MyModule do
defstruct [some: nil, other: 1]
def dummy_function(var = %MyModule{}) do
var.
# ^
end
end
"""
{line, char} = {4, 8}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert ["__struct__", "other", "some"] == items |> Enum.map(& &1["label"]) |> Enum.sort()
assert (items |> hd)["detail"] == "MyModule struct field"
end
test "returns map keys in call syntax" do
text = """
defmodule MyModule do
def dummy_function(var = %{some: nil, other: 1}) do
var.
# ^
end
end
"""
{line, char} = {2, 8}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert ["other", "some"] == items |> Enum.map(& &1["label"]) |> Enum.sort()
assert (items |> hd)["detail"] == "map key"
end
test "returns struct fields in update syntax" do
text = """
defmodule MyModule do
defstruct [some: nil, other: 1]
def dummy_function(var = %MyModule{}) do
%{var |
# ^
end
end
"""
{line, char} = {4, 11}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert ["__struct__", "other", "some"] ==
items |> Enum.filter(&(&1["kind"] == 5)) |> Enum.map(& &1["label"]) |> Enum.sort()
assert (items |> hd)["detail"] == "MyModule struct field"
end
test "returns map keys in update syntax" do
text = """
defmodule MyModule do
def dummy_function(var = %{some: nil, other: 1}) do
%{var |
# ^
end
end
"""
{line, char} = {2, 11}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert ["other", "some"] ==
items |> Enum.filter(&(&1["kind"] == 5)) |> Enum.map(& &1["label"]) |> Enum.sort()
assert (items |> hd)["detail"] == "map key"
end
test "returns struct fields in definition syntax" do
text = """
defmodule MyModule do
defstruct [some: nil, other: 1]
def dummy_function() do
%MyModule{}
# ^
end
end
"""
{line, char} = {4, 14}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, result} = Completion.completion(text, line, char, @supports)
assert result["isIncomplete"] == true
items = result["items"]
assert ["__struct__", "other", "some"] ==
items |> Enum.filter(&(&1["kind"] == 5)) |> Enum.map(& &1["label"]) |> Enum.sort()
assert (items |> hd)["detail"] == "MyModule struct field"
end
test "isIncomplete is false when there are no results" do
text = """
defmodule MyModule do
defstruct [some: nil, other: 1]
def dummy_function() do123
# ^
end
"""
{line, char} = {3, 28}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, result} = Completion.completion(text, line, char, @supports)
assert result["isIncomplete"] == false
assert result["items"] == []
end
end
describe "function completion" do
setup do
text = """
defmodule MyModule do
def add_2_numbers(a, b), do: a + b
def dummy_function() do
ad2n
# ^
end
end
"""
%{text: text, location: {4, 8}}
end
test "setting 'signature_after_complete'", context do
%{text: text, location: {line, char}} = context
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, signature_after_complete: true)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["command"] == @signature_command
opts = Keyword.merge(@supports, signature_after_complete: false)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["command"] == nil
end
test "without snippets nor signature support, complete with just the name", context do
%{text: text, location: {line, char}} = context
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, snippets_supported: false, signature_help_supported: false)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["insertText"] == "add_2_numbers"
assert item["command"] == nil
opts =
Keyword.merge(@supports,
snippets_supported: false,
locals_without_parens: MapSet.new(add_2_numbers: 2)
)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["insertText"] == "add_2_numbers "
assert item["command"] == @signature_command
end
test "with signature support and no snippets support, complete with the name and trigger signature",
context do
%{text: text, location: {line, char}} = context
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, snippets_supported: false)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["insertText"] == "add_2_numbers("
assert item["command"] == @signature_command
end
test "with snippets support and no signature support, complete with name and args",
context do
%{text: text, location: {line, char}} = context
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, signature_help_supported: false)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["insertText"] == "add_2_numbers(${1:a}, ${2:b})"
assert item["command"] == nil
end
test "with snippets/signature support, add placeholder between parens and trigger signature",
context do
%{text: text, location: {line, char}} = context
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
assert item["insertText"] == "add_2_numbers($1)$0"
assert item["command"] == @signature_command
end
test "with snippets/signature support, before valid arg, do not close parens" do
text = """
defmodule MyModule do
def add_2_numbers(a, b), do: a + b
def dummy_function() do
ad2n100
# ^
end
end
"""
{line, char} = {4, 8}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
assert item["insertText"] == "add_2_numbers("
assert item["command"] == @signature_command
end
test "function in :locals_without_parens doesn't complete with args if there's text after cursor" do
text = """
defmodule MyModule do
def add_2_numbers(a, b), do: a + b
def dummy_function() do
ad2n 100
# ^
end
end
"""
{line, char} = {4, 8}
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, locals_without_parens: MapSet.new(add_2_numbers: 2))
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, opts)
assert item["insertText"] == "add_2_numbers"
assert item["command"] == @signature_command
end
test "function with arity 0 does not triggers signature" do
text = """
defmodule MyModule do
def my_func(), do: false
def dummy_function() do
my
# ^
end
end
"""
{line, char} = {4, 6}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
assert item["insertText"] == "my_func()"
assert item["command"] == nil
end
test "without signature support, unused default arguments are removed from the snippet" do
text = """
defmodule MyModule do
alias ElixirLS.LanguageServer.Fixtures.ExampleDefaultArgs
def dummy_function() do
ExampleDefaultArgs.my
# ^
end
end
"""
{line, char} = {4, 25}
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, signature_help_supported: false)
{:ok, %{"items" => [item1, item2, item3]}} = Completion.completion(text, line, char, opts)
assert item1["label"] == "my_func/1"
assert item1["insertText"] == "my_func(${1:text})"
assert item2["label"] == "my_func/2"
assert item2["insertText"] == "my_func(${1:text}, ${2:opts1})"
assert item3["label"] == "my_func/3"
assert item3["insertText"] == "my_func(${1:text}, ${2:opts1}, ${3:opts2})"
end
test "when after a capture, derived functions from default arguments are listed and no signature is triggered" do
text = """
defmodule MyModule do
alias ElixirLS.LanguageServer.Fixtures.ExampleDefaultArgs
def dummy_function() do
&ExampleDefaultArgs.my
# ^
end
end
"""
{line, char} = {4, 26}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item1, item2, item3]}} =
Completion.completion(text, line, char, @supports)
assert item1["label"] == "my_func/1"
assert item1["insertText"] == "my_func${1:/1}$0"
assert item1["command"] == nil
assert item2["label"] == "my_func/2"
assert item2["insertText"] == "my_func${1:/2}$0"
assert item2["command"] == nil
assert item3["label"] == "my_func/3"
assert item3["insertText"] == "my_func${1:/3}$0"
assert item3["command"] == nil
opts = Keyword.merge(@supports, snippets_supported: false)
{:ok, %{"items" => [item1, item2, item3]}} = Completion.completion(text, line, char, opts)
assert item1["label"] == "my_func/1"
assert item1["insertText"] == "my_func/1"
assert item1["command"] == nil
assert item2["label"] == "my_func/2"
assert item2["insertText"] == "my_func/2"
assert item2["command"] == nil
assert item3["label"] == "my_func/3"
assert item3["insertText"] == "my_func/3"
assert item3["command"] == nil
end
test "with signature support, a function with default arguments generate just one suggestion" do
text = """
defmodule MyModule do
alias ElixirLS.LanguageServer.Fixtures.ExampleDefaultArgs
def dummy_function() do
ExampleDefaultArgs.my
# ^
end
end
"""
{line, char} = {4, 25}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
assert item["label"] == "my_func/3"
assert item["insertText"] == "my_func($1)$0"
assert item["command"] == @signature_command
end
test "with signature support, a function with a derived in locals_without_parens generate more than one suggestion" do
text = """
defmodule MyModule do
def timestamps, do: 1
def timestamps(a), do: a
def dummy_function() do
timestamps
# ^
end
end
"""
{line, char} = {5, 13}
TestUtils.assert_has_cursor_char(text, line, char)
opts = Keyword.merge(@supports, locals_without_parens: MapSet.new(timestamps: 0))
{:ok, %{"items" => [item_1, item_2]}} = Completion.completion(text, line, char, opts)
assert item_1["label"] == "timestamps/0"
assert item_2["label"] == "timestamps/1"
end
test "with signature support, a function with 1 default argument triggers signature" do
text = """
defmodule MyModule do
alias ElixirLS.LanguageServer.Fixtures.ExampleDefaultArgs
def dummy_function() do
ExampleDefaultArgs.func_with_1_arg
# ^
end
end
"""
{line, char} = {4, 38}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
assert item["label"] == "func_with_1_arg/1"
assert item["insertText"] == "func_with_1_arg($1)$0"
assert item["command"] == @signature_command
end
test "a function with 1 default argument after a pipe does not trigger signature" do
text = """
defmodule MyModule do
alias ElixirLS.LanguageServer.Fixtures.ExampleDefaultArgs
def dummy_function() do
[] |> ExampleDefaultArgs.func_with_1_arg
# ^
end
end
"""
{line, char} = {4, 44}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item]}} = Completion.completion(text, line, char, @supports)
assert item["label"] == "func_with_1_arg/1"
assert item["insertText"] == "func_with_1_arg()"
assert item["command"] == nil
end
test "the detail of a local function is visibility + type + signature" do
text = """
defmodule MyModule do
def my_func(text), do: true
defp my_func_priv(text), do: true
def dummy_function() do
my
# ^
end
end
"""
{line, char} = {5, 6}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [pub, priv]}} = Completion.completion(text, line, char, @supports)
assert pub["detail"] == "(function) my_func(text)"
assert priv["detail"] == "(function) my_func_priv(text)"
end
test "the detail of a remote function is origin + type + signature" do
text = """
defmodule RemoteMod do
def func(), do: true
end
defmodule MyModule do
def dummy_function() do
RemoteMod.
# ^
end
end
"""
{line, char} = {6, 14}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item | _]}} = Completion.completion(text, line, char, @supports)
assert item["detail"] == "(function) RemoteMod.func()"
end
test "documentation is the markdown of summary + formatted spec" do
text = """
defmodule MyModule do
def dummy_function() do
ElixirLS.LanguageServer.Fixtures.ExampleDocs.ad
# ^
end
end
"""
{line, char} = {2, 51}
TestUtils.assert_has_cursor_char(text, line, char)
{:ok, %{"items" => [item | _]}} = Completion.completion(text, line, char, @supports)
assert item["documentation"] == %{
:kind => "markdown",
"value" => """
The summary
```
@spec add(
a_big_name :: integer,
b_big_name :: integer
) :: integer
```
"""
}
end
end
describe "generic suggestions" do
test "moduledoc completion" do
text = """
defmodule MyModule do
@mod
# ^
end
"""
{line, char} = {1, 6}
TestUtils.assert_has_cursor_char(text, line, char)
assert {:ok, %{"items" => [first | _] = items}} =
Completion.completion(text, line, char, @supports)
labels = Enum.map(items, & &1["label"])
assert labels == [
~s(@moduledoc """"""),
"@moduledoc",
"@moduledoc false"
]
assert first == %{
"detail" => "module attribute snippet",
"documentation" => %{:kind => "markdown", "value" => "Documents a module"},
"filterText" => "moduledoc",
"insertText" => ~s(moduledoc """\n$0\n"""),
"insertTextFormat" => 2,
"kind" => 15,
"label" => ~s(@moduledoc """"""),
"sortText" => "00000000"
}
end
end
describe "function_snippets" do
test "return valid for record arg" do
opts = [
snippets_supported: true,
deprecated_supported: true,
tags_supported: [1],
signature_help_supported: true,
signature_after_complete: true,
pipe_before?: true,
capture_before?: false,
trigger_signature?: false,
locals_without_parens: MapSet.new(),
text_after_cursor: "",
with_parens?: true,
snippet: nil
]
assert "do_sth()" ==
Completion.function_snippet("do_sth", ["My.record(x: x0, y: y0)"], 1, opts)
end
end
describe "do not suggest 0 arity functions after pipe" do
test "moduledoc completion" do
text = """
defmodule MyModule do
def hello do
Date.today() |>
# ^
end
end
"""
{line, char} = {2, 20}
TestUtils.assert_has_cursor_char(text, line, char)
assert {:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
refute Enum.any?(items, fn i -> i["label"] == "make_ref/0" end)
end
end
describe "use the (arity - 1) version of snippets after pipe" do
test "case/2 snippet skips the condition argument" do
text = """
defmodule MyModule do
def hello do
[1, 2]
|> Enum.random()
|> ca
# ^
end
end
"""
{line, char} = {4, 9}
TestUtils.assert_has_cursor_char(text, line, char)
assert {:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert %{"insertText" => insert_text} = Enum.find(items, &match?(%{"label" => "case"}, &1))
assert insert_text =~ "case do\n\t"
end
test "unless/2 snippet skips the condition argument" do
text = """
defmodule MyModule do
def hello do
[1, 2]
|> Enum.random()
|> unl
# ^
end
end
"""
{line, char} = {4, 10}
TestUtils.assert_has_cursor_char(text, line, char)
assert {:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert %{"insertText" => insert_text} =
Enum.find(items, &match?(%{"label" => "unless"}, &1))
assert insert_text =~ "unless do\n\t"
end
test "if/2 snippet skips the condition argument" do
text = """
defmodule MyModule do
def hello do
[1, 2]
|> Enum.random()
|> if
# ^
end
end
"""
{line, char} = {4, 9}
TestUtils.assert_has_cursor_char(text, line, char)
assert {:ok, %{"items" => items}} = Completion.completion(text, line, char, @supports)
assert %{"insertText" => insert_text} = Enum.find(items, &match?(%{"label" => "if"}, &1))
assert insert_text =~ "if do\n\t"
end
end
end
| 28.213035 | 122 | 0.566459 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.