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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0892ced008945f91c8d4c4114c8bef0bcdfc53ed | 2,700 | ex | Elixir | test/example/bank_account.ex | slashdotdash/eventsourced | 8a1178141e3e18f56bf7b88f1966e4f095836558 | [
"MIT"
] | 109 | 2016-02-29T07:24:49.000Z | 2022-03-04T09:31:58.000Z | test/example/bank_account.ex | slashdotdash/domain_model | 8a1178141e3e18f56bf7b88f1966e4f095836558 | [
"MIT"
] | 1 | 2016-11-14T17:07:26.000Z | 2016-11-14T17:07:26.000Z | test/example/bank_account.ex | slashdotdash/eventsourced | 8a1178141e3e18f56bf7b88f1966e4f095836558 | [
"MIT"
] | 7 | 2016-03-08T00:37:51.000Z | 2019-10-20T20:31:56.000Z | defmodule BankAccount do
@moduledoc """
An example bank account aggregate root.
It demonstrates returning either an `{:ok, aggregate}` or `{:error, reason}` tuple from the public API functions on success or failure.
Following this approach allows strict pattern matching on success and failures.
An error indicates a domain business rule violation, such as attempting to open an account with a negative initial balance.
You cannot use the pipeline operation (`|>`) to chain the functions.
Use the `with` special form instead, as shown in the example below.
## Example usage
with account <- BankAccount.new("123"),
{:ok, account} <- BankAccount.open_account(account, "ACC123", 100),
{:ok, account} <- BankAccount.deposit(account, 50),
do: account
"""
use EventSourced.AggregateRoot, fields: [account_number: nil, balance: nil]
defmodule Events do
defmodule BankAccountOpened do
defstruct account_number: nil, initial_balance: nil
end
defmodule MoneyDeposited do
defstruct amount: nil, balance: nil
end
defmodule MoneyWithdrawn do
defstruct amount: nil, balance: nil
end
end
alias Events.{BankAccountOpened,MoneyDeposited,MoneyWithdrawn}
def open_account(%BankAccount{} = _account, _account_number, initial_balance) when initial_balance <= 0 do
{:error, :initial_balance_must_be_above_zero}
end
def open_account(%BankAccount{} = account, account_number, initial_balance) when initial_balance > 0 do
{:ok, update(account, %BankAccountOpened{account_number: account_number, initial_balance: initial_balance})}
end
def deposit(%BankAccount{} = account, amount) do
balance = account.state.balance + amount
{:ok, update(account, %MoneyDeposited{amount: amount, balance: balance})}
end
def withdraw(%BankAccount{state: %{balance: balance}}, amount) when amount > balance do
{:error, :not_enough_funds}
end
def withdraw(%BankAccount{} = account, amount) do
balance = account.state.balance - amount
{:ok, update(account, %MoneyWithdrawn{amount: amount, balance: balance})}
end
# state mutators
def apply(%BankAccount.State{} = state, %BankAccountOpened{} = account_opened) do
%BankAccount.State{state|
account_number: account_opened.account_number,
balance: account_opened.initial_balance
}
end
def apply(%BankAccount.State{} = state, %MoneyDeposited{} = money_deposited) do
%BankAccount.State{state |
balance: money_deposited.balance
}
end
def apply(%BankAccount.State{} = state, %MoneyWithdrawn{} = money_withdrawn) do
%BankAccount.State{state |
balance: money_withdrawn.balance
}
end
end
| 32.142857 | 137 | 0.722593 |
0893161bfc36c49c3328b29d61c4e5c065aa9a9b | 383 | exs | Elixir | apps/hefty/priv/repo/migrations/20190517104700_create_streaming_settings.exs | Cinderella-Man/crypto-streamer | b1e990d375f7143c5149930be991249f0d9c3ee3 | [
"MIT"
] | 49 | 2019-10-28T22:27:28.000Z | 2021-10-11T06:40:29.000Z | apps/hefty/priv/repo/migrations/20190517104700_create_streaming_settings.exs | Cinderella-Man/crypto-streamer | b1e990d375f7143c5149930be991249f0d9c3ee3 | [
"MIT"
] | 9 | 2019-08-30T13:15:36.000Z | 2019-10-10T21:25:14.000Z | apps/hefty/priv/repo/migrations/20190517104700_create_streaming_settings.exs | Cinderella-Man/crypto-streamer | b1e990d375f7143c5149930be991249f0d9c3ee3 | [
"MIT"
] | 7 | 2019-10-31T06:19:26.000Z | 2021-09-30T04:20:58.000Z | defmodule Hefty.Repo.Migrations.CreateStreamingSettings do
use Ecto.Migration
def change do
create table(:streaming_settings, primary_key: false) do
add(:id, :uuid, primary_key: true)
add(:symbol, :text, null: false)
add(:platform, :text, null: false, default: "Binance")
add(:enabled, :boolean, default: false)
timestamps()
end
end
end
| 25.533333 | 60 | 0.67624 |
089324f128a99c835b25990bbb2c62e4b4834189 | 1,170 | ex | Elixir | lib/serum/build/file_processor/template.ex | nallwhy/Serum | ed9f51a83e328789ccfca18d2a0397b45ac4be0f | [
"MIT"
] | null | null | null | lib/serum/build/file_processor/template.ex | nallwhy/Serum | ed9f51a83e328789ccfca18d2a0397b45ac4be0f | [
"MIT"
] | null | null | null | lib/serum/build/file_processor/template.ex | nallwhy/Serum | ed9f51a83e328789ccfca18d2a0397b45ac4be0f | [
"MIT"
] | null | null | null | defmodule Serum.Build.FileProcessor.Template do
@moduledoc false
require Serum.Result, as: Result
import Serum.IOProxy, only: [put_msg: 2]
alias Serum.Error
alias Serum.Template
alias Serum.Template.Compiler, as: TC
alias Serum.Template.Storage, as: TS
@spec compile_templates(map()) :: Result.t({})
def compile_templates(%{templates: templates, includes: includes}) do
put_msg(:info, "Compiling and loading templates...")
Result.run do
compile_and_load(includes, :include)
compile_and_load(templates, :template)
Result.return()
end
end
@spec compile_and_load([Serum.File.t()], Template.type()) :: Result.t([Template.t()])
defp compile_and_load(files, type) do
case TC.compile_files(files, type: type) do
{:ok, result} ->
TS.load(result, type)
result |> Enum.map(&elem(&1, 1)) |> expand_includes()
{:error, %Error{}} = error ->
error
end
end
@spec expand_includes([Template.t()]) :: Result.t([Template.t()])
defp expand_includes(templates) do
templates
|> Enum.map(&TC.Include.expand/1)
|> Result.aggregate("failed to expand includes:")
end
end
| 27.857143 | 87 | 0.665812 |
08935d7100e709940391bcbccebc3a640733fcb6 | 1,654 | ex | Elixir | lib/Discord/rate_limits.ex | Cohedrin/alchemy | 4e2bfe3c1ffd164141c06d181ad1aa987dfb0d72 | [
"MIT"
] | null | null | null | lib/Discord/rate_limits.ex | Cohedrin/alchemy | 4e2bfe3c1ffd164141c06d181ad1aa987dfb0d72 | [
"MIT"
] | null | null | null | lib/Discord/rate_limits.ex | Cohedrin/alchemy | 4e2bfe3c1ffd164141c06d181ad1aa987dfb0d72 | [
"MIT"
] | null | null | null | defmodule Alchemy.Discord.RateLimits do
@moduledoc false
# Used for parsing ratelimits out of headers
require Logger
defmodule RateInfo do
@moduledoc false
defstruct [:limit, :remaining, :reset_time]
end
# will only match if the ratelimits are present
defp parse_headers(%{"x-ratelimit-remaining" => remaining} = headers) do
{remaining, _} = Integer.parse(remaining)
{reset_time, _} = Float.parse(headers["x-ratelimit-reset"])
{limit, _} = Integer.parse(headers["x-ratelimit-limit"])
%RateInfo{limit: limit, remaining: remaining, reset_time: reset_time}
end
defp parse_headers(_none) do
nil
end
# status code empty
def rate_info(%{status_code: 204}) do
nil
end
def rate_info(%{status_code: 200, headers: h}) do
h |> Enum.into(%{}) |> parse_headers
end
# Used in the case of a 429 error, expected to "decide" what response to give
def rate_info(%{status_code: 429, headers: h, body: body}) do
body = Poison.Parser.parse!(body, %{})
timeout = body["retry_after"]
if body["global"] do
{:global, timeout}
else
{:local, timeout, h |> Enum.into(%{}) |> parse_headers}
end
end
# Used the first time a bucket is accessed during the program
# It makes it so that in the case of multiple processes getting sent at the same time
# to a virgin bucket, they'll have to wait for the first one to clear through,
# and get rate info.
def default_info do
now = DateTime.utc_now() |> DateTime.to_unix()
# 2 seconds should be enough to let the first one get a clean request
%RateInfo{limit: 1, remaining: 1, reset_time: now + 2}
end
end
| 30.62963 | 87 | 0.682588 |
08936b1c83d3b1eeabfe7a6dcd7ee702a9a9672c | 2,041 | ex | Elixir | clients/on_demand_scanning/lib/google_api/on_demand_scanning/v1/model/completeness.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/on_demand_scanning/lib/google_api/on_demand_scanning/v1/model/completeness.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/on_demand_scanning/lib/google_api/on_demand_scanning/v1/model/completeness.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.OnDemandScanning.V1.Model.Completeness do
@moduledoc """
Indicates that the builder claims certain fields in this message to be complete.
## Attributes
* `arguments` (*type:* `boolean()`, *default:* `nil`) - If true, the builder claims that recipe.arguments is complete, meaning that all external inputs are properly captured in the recipe.
* `environment` (*type:* `boolean()`, *default:* `nil`) - If true, the builder claims that recipe.environment is claimed to be complete.
* `materials` (*type:* `boolean()`, *default:* `nil`) - If true, the builder claims that materials are complete, usually through some controls to prevent network access. Sometimes called "hermetic".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:arguments => boolean() | nil,
:environment => boolean() | nil,
:materials => boolean() | nil
}
field(:arguments)
field(:environment)
field(:materials)
end
defimpl Poison.Decoder, for: GoogleApi.OnDemandScanning.V1.Model.Completeness do
def decode(value, options) do
GoogleApi.OnDemandScanning.V1.Model.Completeness.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.OnDemandScanning.V1.Model.Completeness do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.509434 | 202 | 0.728074 |
08937c64a548b686fd3394c9843f467fe0d14293 | 754 | ex | Elixir | test/support/channel_case.ex | ukisami/bot.messenger.fdl | 571d29795612a21a3be21ce9f8851afa5a7b387f | [
"MIT"
] | null | null | null | test/support/channel_case.ex | ukisami/bot.messenger.fdl | 571d29795612a21a3be21ce9f8851afa5a7b387f | [
"MIT"
] | null | null | null | test/support/channel_case.ex | ukisami/bot.messenger.fdl | 571d29795612a21a3be21ce9f8851afa5a7b387f | [
"MIT"
] | null | null | null | defmodule FdlMessengerBot.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
imports other functionality to make it easier
to build and query models.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint FdlMessengerBot.Endpoint
end
end
setup tags do
:ok
end
end
| 22.176471 | 56 | 0.724138 |
0893a4fb36462647a2d92c2759c5ed98c5b24268 | 287 | exs | Elixir | .dialyzer_ignore.exs | ex-security-advisory/api | 75674d42efd3b9f2406233e36244d5cb5f174971 | [
"MIT"
] | 5 | 2019-01-03T18:33:40.000Z | 2021-01-25T10:15:06.000Z | .dialyzer_ignore.exs | ex-security-advisory/api | 75674d42efd3b9f2406233e36244d5cb5f174971 | [
"MIT"
] | 15 | 2018-12-27T16:59:06.000Z | 2019-01-04T17:34:38.000Z | .dialyzer_ignore.exs | ex-security-advisory/api | 75674d42efd3b9f2406233e36244d5cb5f174971 | [
"MIT"
] | null | null | null | [
~r/pipeline\/1/,
{"", :unknown_type, 0},
{"apps/elixir_security_advisory/lib/elixir_security_advisory/vulnerabilities/database.ex"},
{"apps/elixir_security_advisory_api_v1/lib/elixir_security_advisory_api_v1/controllers/introduction_controller.ex",
:pattern_match_cov, 1}
]
| 35.875 | 117 | 0.787456 |
0893b0e95ac2ad0282fe04d641cad332689eb5ca | 168 | ex | Elixir | lib/one_word.ex | Bentheburrito/onewordstorybot | 2d75f3a59a952d141cfa4306fb14c902815cbff5 | [
"MIT"
] | null | null | null | lib/one_word.ex | Bentheburrito/onewordstorybot | 2d75f3a59a952d141cfa4306fb14c902815cbff5 | [
"MIT"
] | null | null | null | lib/one_word.ex | Bentheburrito/onewordstorybot | 2d75f3a59a952d141cfa4306fb14c902815cbff5 | [
"MIT"
] | null | null | null | defmodule OneWord do
use Application
# Application Entry Point
@impl true
def start(_type, _args) do
OneWord.Supervisor.start_link(name: BotSupervisor)
end
end
| 16.8 | 52 | 0.779762 |
0893b45c151fb9530968d638c9ce7041320d352c | 2,801 | ex | Elixir | lib/chat_api_web/controllers/forwarding_address_controller.ex | ZmagoD/papercups | dff9a5822b809edc4fd8ecf198566f9b14ab613f | [
"MIT"
] | 4,942 | 2020-07-20T22:35:28.000Z | 2022-03-31T15:38:51.000Z | lib/chat_api_web/controllers/forwarding_address_controller.ex | ZmagoD/papercups | dff9a5822b809edc4fd8ecf198566f9b14ab613f | [
"MIT"
] | 552 | 2020-07-22T01:39:04.000Z | 2022-02-01T00:26:35.000Z | lib/chat_api_web/controllers/forwarding_address_controller.ex | ZmagoD/papercups | dff9a5822b809edc4fd8ecf198566f9b14ab613f | [
"MIT"
] | 396 | 2020-07-22T19:27:48.000Z | 2022-03-31T05:25:24.000Z | defmodule ChatApiWeb.ForwardingAddressController do
use ChatApiWeb, :controller
alias ChatApi.ForwardingAddresses
alias ChatApi.ForwardingAddresses.ForwardingAddress
action_fallback(ChatApiWeb.FallbackController)
plug(:authorize when action in [:show, :update, :delete])
defp authorize(conn, _) do
id = conn.path_params["id"]
with %{account_id: account_id} <- conn.assigns.current_user,
%ForwardingAddress{account_id: ^account_id} = forwarding_address <-
ForwardingAddresses.get_forwarding_address!(id) do
assign(conn, :current_forwarding_address, forwarding_address)
else
_ -> ChatApiWeb.FallbackController.call(conn, {:error, :not_found}) |> halt()
end
end
@spec index(Plug.Conn.t(), map()) :: Plug.Conn.t()
def index(conn, params) do
with %{account_id: account_id} <- conn.assigns.current_user do
forwarding_addresses = ForwardingAddresses.list_forwarding_addresses(account_id, params)
render(conn, "index.json", forwarding_addresses: forwarding_addresses)
end
end
@spec create(Plug.Conn.t(), map()) :: Plug.Conn.t()
def create(conn, %{"forwarding_address" => forwarding_address_params}) do
with %{account_id: account_id} <- conn.assigns.current_user,
{:ok, %ForwardingAddress{} = forwarding_address} <-
%{
"forwarding_email_address" => ForwardingAddresses.generate_forwarding_email_address()
}
|> Map.merge(forwarding_address_params)
|> Map.merge(%{"account_id" => account_id})
|> ForwardingAddresses.create_forwarding_address() do
conn
|> put_status(:created)
|> put_resp_header(
"location",
Routes.forwarding_address_path(conn, :show, forwarding_address)
)
|> render("show.json", forwarding_address: forwarding_address)
end
end
@spec show(Plug.Conn.t(), map()) :: Plug.Conn.t()
def show(conn, %{"id" => _id}) do
render(conn, "show.json", forwarding_address: conn.assigns.current_forwarding_address)
end
@spec update(Plug.Conn.t(), map()) :: Plug.Conn.t()
def update(conn, %{"id" => _id, "forwarding_address" => forwarding_address_params}) do
with {:ok, %ForwardingAddress{} = forwarding_address} <-
ForwardingAddresses.update_forwarding_address(
conn.assigns.current_forwarding_address,
forwarding_address_params
) do
render(conn, "show.json", forwarding_address: forwarding_address)
end
end
@spec delete(Plug.Conn.t(), map()) :: Plug.Conn.t()
def delete(conn, %{"id" => _id}) do
with {:ok, %ForwardingAddress{}} <-
ForwardingAddresses.delete_forwarding_address(conn.assigns.current_forwarding_address) do
send_resp(conn, :no_content, "")
end
end
end
| 37.346667 | 100 | 0.681542 |
0893b4cd8f1a79b314e172c0e1544e7a6c9bffbe | 9,444 | ex | Elixir | lib/console/organizations/organizations.ex | mfalkvidd/console | 6427c82bc4f8619b5bb3a5940099a8bdd6167a9e | [
"Apache-2.0"
] | 1 | 2021-09-24T17:52:34.000Z | 2021-09-24T17:52:34.000Z | lib/console/organizations/organizations.ex | mfalkvidd/console | 6427c82bc4f8619b5bb3a5940099a8bdd6167a9e | [
"Apache-2.0"
] | null | null | null | lib/console/organizations/organizations.ex | mfalkvidd/console | 6427c82bc4f8619b5bb3a5940099a8bdd6167a9e | [
"Apache-2.0"
] | null | null | null | defmodule Console.Organizations do
import Ecto.Query, warn: false
alias Console.Repo
alias Console.Organizations.Organization
alias Console.Devices
alias Console.Organizations.Membership
alias Console.Organizations.Invitation
alias Console.Auth.User
alias Console.ApiKeys.ApiKey
def list_organizations do
query = from o in Organization,
select: %{id: o.id, name: o.name, role: "admin", dc_balance: o.dc_balance, inserted_at: o.inserted_at, app_eui: o.default_app_eui}
Repo.all(query)
end
def get_organizations(%{} = current_user) do
query = from o in Organization,
join: m in Membership, on: m.organization_id == o.id,
where: m.user_id == ^current_user.id,
select: %{id: o.id, name: o.name, role: m.role, dc_balance: o.dc_balance, inserted_at: o.inserted_at, app_eui: o.default_app_eui}
Repo.all(query)
end
def get_organizations_with_devices(%User{} = current_user) do
query = from o in Organization,
join: m in Membership, on: m.organization_id == o.id,
where: m.user_id == ^current_user.id,
select: %{id: o.id, name: o.name, role: m.role, dc_balance: o.dc_balance, inserted_at: o.inserted_at, active: o.active, received_free_dc: o.received_free_dc, webhook_key: o.webhook_key},
order_by: [asc: :name]
organizations = Repo.all(query)
organizations =
Enum.map(organizations, fn org ->
devices = Devices.get_devices(org.id)
inactive_devices = Enum.filter(devices, fn device -> !device.active end)
inactive_count = length(inactive_devices)
active_count = length(devices) - inactive_count
org
|> Map.put(:inactive_count, inactive_count)
|> Map.put(:active_count, active_count)
end)
organizations
end
def get_organization!(%User{} = current_user, id) do
if current_user.super do
Repo.get!(Organization, id)
else
query = from o in Organization,
join: m in Membership, on: m.organization_id == o.id,
where: m.user_id == ^current_user.id and o.id == ^id
Repo.one!(query)
end
end
def get_organization(%User{} = current_user, id) do
if current_user.super do
Repo.get(Organization, id)
else
query = from o in Organization,
join: m in Membership, on: m.organization_id == o.id,
where: m.user_id == ^current_user.id and o.id == ^id
Repo.one(query)
end
end
def get_organization_and_lock_for_dc(org_id) do
Organization
|> where([o], o.id == ^org_id)
|> lock("FOR UPDATE NOWAIT")
|> Repo.one()
end
def get_discovery_mode_org() do
Organization
|> where([o], o.name == "Discovery Mode (Helium)")
|> Repo.one()
end
def get_organization!(id) do
Repo.get!(Organization, id)
end
def get_organization(id) do
Repo.get(Organization, id)
end
def get_invitation!(id) do
Repo.get!(Invitation, id)
end
def get_membership!(id) do
Repo.get!(Membership, id)
end
def get_membership(id) do
Repo.get(Membership, id)
end
def get_membership!(%Organization{} = organization, id) do
Repo.get_by!(Membership, [id: id, organization_id: organization.id])
end
def get_membership!(%User{id: user_id}, %Organization{id: organization_id}) do
query = from m in Membership,
where: m.user_id == ^user_id and m.organization_id == ^organization_id
Repo.one(query)
end
def get_invitation!(%Organization{} = organization, id) do
Repo.get_by!(Invitation, [id: id, organization_id: organization.id])
end
def get_last_viewed_org_membership(%User{id: user_id}) do
query = from m in Membership,
where: m.user_id == ^user_id,
order_by: [desc: :updated_at]
Repo.all(query)
end
def get_administrators(%Organization{id: organization_id}) do
query = from m in Membership,
where: m.organization_id == ^organization_id and m.role == ^"admin"
Repo.all(query)
end
def get_memberships_by_organization_and_role(organization_id, roles) do
query = from m in Membership,
where: m.organization_id == ^organization_id and m.role in ^roles
Repo.all(query)
end
def get_current_organization(user, organization_id) do
if user.super do
organization = get_organization!(organization_id)
membership = %Membership{ role: "admin" }
%{membership: membership, organization: organization}
else
case get_organization(user, organization_id) do
%Organization{} = current_organization ->
current_membership = get_membership!(user, current_organization)
%{membership: current_membership, organization: current_organization}
_ ->
:forbidden
end
end
end
def create_organization(%{} = user, attrs \\ %{}) do
count = get_organizations(user) |> Enum.count()
if count > 499 do
{:error, :forbidden, "Maximum number of organizations reached"}
else
organization_changeset =
%Organization{}
|> Organization.create_changeset(attrs)
membership_fn = fn _repo, %{organization: organization} ->
%Membership{}
|> Membership.join_org_changeset(user, organization, "admin")
|> Repo.insert()
end
result =
Ecto.Multi.new()
|> Ecto.Multi.insert(:organization, organization_changeset)
|> Ecto.Multi.run(:membership, membership_fn)
|> Repo.transaction()
case result do
{:ok, %{organization: organization}} -> {:ok, organization}
{:error, :organization, %Ecto.Changeset{} = changeset, _} -> {:error, changeset}
end
end
end
def update_organization(%Organization{} = organization, attrs) do
organization
|> Organization.update_changeset(attrs)
|> Repo.update()
end
def update_organization!(%Organization{} = organization, attrs) do
organization
|> Organization.update_changeset(attrs)
|> Repo.update!()
end
def join_organization(%User{} = user, %Organization{} = organization, role \\ "read") do
%Membership{}
|> Membership.join_org_changeset(user, organization, role)
|> Repo.insert()
end
def fetch_assoc(%Organization{} = organization, assoc \\ [:channels, :users, :devices]) do
Repo.preload(organization, assoc)
end
def fetch_assoc_invitation(%Invitation{} = invitation, assoc \\ [:organization]) do
Repo.preload(invitation, assoc)
end
def fetch_assoc_membership(%Membership{} = membership, assoc \\ [:organization]) do
Repo.preload(membership, assoc)
end
def create_invitation(%User{} = inviter, %Organization{} = organization, attrs) do
attrs = Map.merge(attrs, %{"inviter_id" => inviter.id, "organization_id" => organization.id})
%Invitation{}
|> Invitation.create_changeset(attrs)
|> Repo.insert()
end
def mark_invitation_used(%Invitation{} = invitation) do
invitation
|> Invitation.used_changeset()
|> Repo.update()
end
def valid_invitation_token?(token) do
with %Invitation{} = invitation <- Repo.get_by(Invitation, token: token) do
{invitation.pending, invitation}
else nil -> {false, nil}
end
end
def valid_invitation_token_and_lock?(token) do
lock_query = Invitation
|> where([i], i.token == ^token)
|> lock("FOR UPDATE NOWAIT")
with %Invitation{} = invitation <- Repo.one(lock_query) do
{invitation.pending, invitation}
else nil -> {false, nil}
end
end
def update_membership(%Membership{} = membership, attrs) do
if "role" in attrs and attrs["role"] != "admin" do
Repo.transaction(fn ->
from(key in ApiKey, where: key.user_id == ^membership.user_id and key.organization_id == ^membership.organization_id)
|> Repo.delete_all()
membership
|> Membership.update_changeset(attrs)
|> Repo.update!()
end)
else
membership
|> Membership.update_changeset(attrs)
|> Repo.update()
end
end
def delete_invitation(%Invitation{} = invitation) do
Repo.delete(invitation)
end
def delete_membership(%Membership{} = membership) do
Repo.transaction(fn ->
from(key in ApiKey, where: key.user_id == ^membership.user_id and key.organization_id == ^membership.organization_id)
|> Repo.delete_all()
Repo.delete!(membership)
end)
end
def delete_organization(%Organization{} = organization) do
Repo.transaction(fn ->
from(key in ApiKey, where: key.organization_id == ^organization.id)
|> Repo.delete_all()
Repo.delete!(organization)
end)
end
def send_dc_to_org(amount, %Organization{} = from_org, %Organization{} = to_org) do
Repo.transaction(fn ->
locked_from_org = get_organization_and_lock_for_dc(from_org.id)
from_org_updated = update_organization!(locked_from_org, %{
"dc_balance" => locked_from_org.dc_balance - amount,
"dc_balance_nonce" => locked_from_org.dc_balance_nonce + 1
})
locked_to_org = get_organization_and_lock_for_dc(to_org.id)
locked_to_org_dc_balance =
case locked_to_org.dc_balance do
nil -> amount
_ -> locked_to_org.dc_balance + amount
end
to_org_updated = update_organization!(locked_to_org, %{
"dc_balance" => locked_to_org_dc_balance,
"dc_balance_nonce" => locked_to_org.dc_balance_nonce + 1
})
{:ok, from_org_updated, to_org_updated}
end)
end
end
| 30.762215 | 192 | 0.668255 |
0893e5425251bf4a6888c46aad1b3c1111361254 | 4,645 | ex | Elixir | lib/osr.ex | christopher-dG/osu-ex | ee1c4bc49e5c146a7bcd0d6b976a19d605d695ed | [
"MIT"
] | null | null | null | lib/osr.ex | christopher-dG/osu-ex | ee1c4bc49e5c146a7bcd0d6b976a19d605d695ed | [
"MIT"
] | null | null | null | lib/osr.ex | christopher-dG/osu-ex | ee1c4bc49e5c146a7bcd0d6b976a19d605d695ed | [
"MIT"
] | null | null | null | defmodule OsuEx.Osr do
@moduledoc "Parses and downloads .osr files."
alias OsuEx.API
import OsuEx.Parser
use Bitwise, only_operators: true
@doc "Parses a replay file. The argument can be either the file path or the contents."
@spec parse(binary) :: {:ok, map} | {:error, Exception.t()}
def parse(path_or_data) do
try do
{:ok, parse!(path_or_data)}
rescue
e -> {:error, e}
end
end
@doc "Same as `parse/1`, but raises exceptions."
@spec parse!(binary) :: map
def parse!(path_or_data) do
data = if(String.valid?(path_or_data), do: File.read!(path_or_data), else: path_or_data)
%{data_: data}
|> byte(:mode)
|> int(:version)
|> string(:beatmap_md5)
|> string(:player)
|> string(:replay_md5)
|> short(:n300)
|> short(:n100)
|> short(:n50)
|> short(:ngeki)
|> short(:nkatu)
|> short(:nmiss)
|> int(:score)
|> short(:combo)
|> bool(:perfect?)
|> int(:mods)
|> string(:life_bar)
|> datetime(:timestamp)
|> bytes(:replay_data)
|> long(:replay_id)
|> Map.delete(:data_)
end
@game_v 20_151_228
@doc "Downloads a replay file."
@spec download_replay(pos_integer, API.user_id(), keyword) :: {:ok, binary} | {:error, term}
def download_replay(beatmap, player, opts \\ []) do
mode = Keyword.get(opts, :m, 0)
mods = Keyword.get(opts, :mods)
scores_opts = [u: player, m: mode] ++ if(is_nil(mods), do: [], else: [mods: mods])
replay_opts = if(is_nil(mods), do: [], else: [mods: mods])
with {:ok, [%{replay_available: true} = score | _t]} <- API.get_scores(beatmap, scores_opts),
md5 when is_binary(md5) <-
Keyword.get_lazy(opts, :h, fn ->
case API.get_beatmap(beatmap) do
{:ok, %{file_md5: md5}} -> md5
{:ok, _} -> {:error, :no_md5}
{:error, reason} -> {:error, reason}
end
end),
{:ok, %{content: content}} <- API.get_replay(beatmap, player, mode, replay_opts),
{:ok, replay} <- Base.decode64(content) do
hash_data =
:md5
|> :crypto.hash("#{score.maxcombo}osu#{score.username}#{md5}#{score.score}#{score.rank}")
|> Base.encode16()
|> String.downcase()
osr =
[]
|> add_bytes(mode)
|> add_int(@game_v)
|> add_string(md5)
|> add_string(score.username)
|> add_string(hash_data)
|> add_short(score.count300)
|> add_short(score.count100)
|> add_short(score.count50)
|> add_short(score.countgeki)
|> add_short(score.countkatu)
|> add_short(score.countmiss)
|> add_int(score.score)
|> add_short(score.maxcombo)
|> add_bytes(score.perfect)
|> add_int(score.enabled_mods)
|> add_string("")
|> add_timestamp(score.date)
|> add_int(byte_size(replay))
|> add_bytes(replay)
|> add_long(score.score_id)
|> :binary.list_to_bin()
{:ok, osr}
else
{:ok, []} -> {:error, :score_not_found}
{:ok, %{error: reason}} -> {:error, reason}
{:ok, [%{replay_available: false}]} -> {:error, :replay_not_available}
{:ok, _} -> {:error, :invalid_replay}
:error -> {:error, :invalid_replay}
{:error, reason} -> {:error, reason}
other -> {:error, {:invalid, other}}
end
end
defp add_n_bytes(data, bs, n) do
s = n * 8
[data, <<bs::little-size(s)>>]
end
defp add_bytes(data, b) when is_boolean(b) do
add_bytes(data, if(b, do: 1, else: 0))
end
defp add_bytes(data, bs) do
[data, bs]
end
defp add_short(data, s) do
add_n_bytes(data, s, 2)
end
defp add_int(data, i) do
add_n_bytes(data, i, 4)
end
defp encode_uleb(i, acc \\ [])
defp encode_uleb(0, acc) do
acc
end
defp encode_uleb(i, acc) do
# https://en.wikipedia.org/wiki/LEB128#Encode_unsigned_integer
b = i &&& 0x7F
i = i >>> 7
b = if(i === 0, do: b, else: b ||| 0x80)
encode_uleb(i, [acc, b])
end
defp add_string(data, "") do
add_bytes(data, 0x00)
end
defp add_string(data, s) do
len =
s
|> String.length()
|> encode_uleb()
[data, 0x0B, len, s]
end
defp add_long(data, l) do
add_n_bytes(data, l, 8)
end
# https://github.com/worldwidewat/TicksToDateTime/blob/master/Web/Index.html
@epoch_ticks 621_355_968_000_000_000
@ticks_per_ms 10000
defp to_ticks(dt) do
DateTime.to_unix(dt, :millisecond) * @ticks_per_ms + @epoch_ticks
end
defp add_timestamp(data, dt) do
ticks = to_ticks(dt)
add_long(data, ticks)
end
end
| 26.542857 | 97 | 0.57718 |
0893e9eba33ee462a262d72e85a0a11e80378a4b | 5,915 | ex | Elixir | apps/broker/lib/collector/tx_collector/tx_collector.ex | iotaledger/chronicle | 73566e5613268e4b0c5951265ae4760cedb4051f | [
"Apache-2.0"
] | 19 | 2019-09-17T18:14:36.000Z | 2021-12-06T07:29:27.000Z | apps/broker/lib/collector/tx_collector/tx_collector.ex | iotaledger/chronicle | 73566e5613268e4b0c5951265ae4760cedb4051f | [
"Apache-2.0"
] | 5 | 2019-09-30T04:57:14.000Z | 2020-11-10T15:41:03.000Z | apps/broker/lib/collector/tx_collector/tx_collector.ex | iotaledger/chronicle | 73566e5613268e4b0c5951265ae4760cedb4051f | [
"Apache-2.0"
] | 2 | 2019-09-17T19:03:16.000Z | 2021-03-01T01:04:31.000Z | defmodule Broker.Collector.TxCollector do
@moduledoc """
Documentation for Broker.Collector.TxCollector.
This lightweight processor(consumer) is responsible to handle dispatched
flow of transactions from TxValidator(s) producer.
"""
use GenStage
require Logger
require Broker.Collector.Ring
alias Broker.Collector.Ring
alias Broker.Collector.TxCollector.Helper
@tx_ttl Application.get_env(:broker, :__TX_TTL__) || 30000 # 30 seconds
@bundle_ttl Application.get_env(:broker, :__BUNDLE_TTL__) || 30000 # 30 seconds
@spec start_link(Keyword.t) :: tuple
def start_link(args) do
name = :"tc#{args[:num]}"
GenStage.start_link(__MODULE__, Keyword.put(args, :name, name), name: name)
end
@spec init(Keyword.t) :: tuple
def init(args) do
# put name
Process.put(:name, args[:name])
p = args[:num]
subscribe_to = for n <- 0..args[:transaction_partitions]-1 do
{:"tv#{n}", partition: p}
end
{:consumer, %{}, subscribe_to: subscribe_to}
end
def handle_subscribe(:producer, _options, _from, state) do
Logger.info("TxCollector: #{Process.get(:name)} got subscribed_to Validator")
{:automatic, state}
end
@doc """
here we should handle the transaction flow,
first we check if the tx by hash if is already in the waiting list(map),
if so we send it to the corsponding bundle_collectors and then delete it from
the waiting map.
- otherwise we store it in the map, and send_self to delete it after interval.
"""
@spec handle_events(list, tuple, map) :: tuple
def handle_events(events, _from, state) do
# process events and return updated state.
state = process_events(events, state)
{:noreply, [], state}
end
@doc """
This receive request for tx from bundle_collector,
first it checks whether the tx is already in the map,
if so it sends the tx to pid_name, and delete it from the map.
else it appends the pid_name to the waiting list,
and send_self to delete the pid_name from the waiting map.
"""
def handle_cast({:tx?, hash, ref_id, pid_name}, state) do
# process_request
process_request(hash, ref_id, pid_name, state)
{:noreply, [], state}
end
# delete pid_name from b_collectors_list or delete the whole hash from state
# if counter = 1
# handler to remove request from state
def handle_info({:rm, hash}, state) do
state =
case Map.get(state, hash) do
{1,_} ->
Map.delete(state, hash)
{counter, [_| b_collectors_list]} ->
Map.put(state, hash, {counter-1, b_collectors_list})
_ ->
state
end
{:noreply, [], state}
end
def handle_info({:free, hash}, state) do
# detele the hash from the state
state = Map.delete(state, hash)
{:noreply, [], state}
end
def child_spec(args) do
%{
id: :"tc#{args[:num]}",
start: {__MODULE__, :start_link, [args]},
type: :worker,
restart: :permanent,
shutdown: 500
}
end
# start of private functions related to processing events
defp process_events([{hash, trytes, _}|tail], state) do
state = process_event(hash, trytes, state)
process_events(tail, state)
end
defp process_events([], state) do
state
end
defp process_event(hash, trytes, state) do
# we create a tx-object(struct)
tx_object = Helper.create_tx_object(hash, trytes)
# we process the tx_object.
process_tx_object(hash,tx_object,state)
end
# current_index: 0, is_head = true. so no processing is needed.
defp process_tx_object(hash, %{current_index: 0} = tx_object, state) do
# target a bundle_collector by tx_hash
pid_name = Ring.tx_bundle_collector?(hash)
# send this to a bundle_collector
GenStage.cast(pid_name, {:new, tx_object})
# return state
state
end
defp process_tx_object(hash, tx_object, state) do
# this means the tx is not a head.
# put tx_object in the state only if it's not in the waiting list.
# check whether already requested by bundle_collector(s) in the map.
case Map.put_new(state, hash, tx_object) do
%{^hash => {_, b_collectors_list}} ->
# send the tx_object to b_collectors_list and return updated state
for {ref_id, pid_name} <- b_collectors_list do
GenStage.cast(pid_name, {ref_id, tx_object})
end
# return updated state
Map.delete(state, hash)
new_state ->
# send_self to delete it after interval.
Process.send_after(self(), {:free, hash}, @tx_ttl)
new_state
end
end
# end of private functions related to processing events
# start of private functions related to processing :tx? request
defp process_request(hash, ref_id, pid_name, state) do
# fetch the tx-object/waiters(if any) from state
case Map.get(state, hash) do
tx_object when is_map(tx_object) ->
# send tx_object to pid_name with ref_id
GenStage.cast(pid_name, {ref_id, tx_object})
# delete it from state
Map.delete(state, hash)
{counter, b_collectors_list} ->
# this indicates we already have a prev requester who asked for the same hash.
# - increase the counter and append {ref_id, pid_name} to the end.
b_collectors = {counter+1, b_collectors_list++[{ref_id, pid_name}]}
# send_self to delete the b_collector from b_collectors_list or
# delete the whole request if counter=1. note: using @bundle_ttl
Process.send_after(self(), {:rm, hash}, @bundle_ttl)
# return updated state
Map.put(state, hash, b_collectors)
nil ->
# create a b_collector tuple.
b_collectors = {1, [{ref_id,pid_name}]}
# send_self to delete the request @bundle_ttl
Process.send_after(self(), {:rm, hash}, @bundle_ttl)
# add it to the state
Map.put(state, hash, b_collectors)
end
end
end
| 33.607955 | 86 | 0.667456 |
08942ab6d1252fa096930587cbb74f8e5b3d1a93 | 493 | ex | Elixir | lib/rocketpay_web/controllers/users_controller.ex | lucasliet/rocketpay-elixir | e0c202e2117b2aef72e7b4800c9322efa59c604a | [
"MIT"
] | null | null | null | lib/rocketpay_web/controllers/users_controller.ex | lucasliet/rocketpay-elixir | e0c202e2117b2aef72e7b4800c9322efa59c604a | [
"MIT"
] | null | null | null | lib/rocketpay_web/controllers/users_controller.ex | lucasliet/rocketpay-elixir | e0c202e2117b2aef72e7b4800c9322efa59c604a | [
"MIT"
] | null | null | null | defmodule RocketpayWeb.UsersController do
use RocketpayWeb, :controller
alias Rocketpay.User
def create(conn, params) do
params
|>Rocketpay.create_user
end
defp handle_response({:ok, %User{} = user}, conn) do
conn
|>put_status(:created)
|>render("create.json", user: user)
end
defp handle_response({:error, reason}, conn) do
conn
|>put_status(:bad_request)
|>put_view(RocketpayWeb.ErrorView)
|>render("400.json", result: reason)
end
end
| 20.541667 | 54 | 0.679513 |
08942db6a46383c56be144c40bb48d221be0f73a | 772 | ex | Elixir | lib/grizzly/zwave/commands/thermostat_setback_get.ex | jellybob/grizzly | 290bee04cb16acbb9dc996925f5c501697b7ac94 | [
"Apache-2.0"
] | 76 | 2019-09-04T16:56:58.000Z | 2022-03-29T06:54:36.000Z | lib/grizzly/zwave/commands/thermostat_setback_get.ex | jellybob/grizzly | 290bee04cb16acbb9dc996925f5c501697b7ac94 | [
"Apache-2.0"
] | 124 | 2019-09-05T14:01:24.000Z | 2022-02-28T22:58:14.000Z | lib/grizzly/zwave/commands/thermostat_setback_get.ex | jellybob/grizzly | 290bee04cb16acbb9dc996925f5c501697b7ac94 | [
"Apache-2.0"
] | 10 | 2019-10-23T19:25:45.000Z | 2021-11-17T13:21:20.000Z | defmodule Grizzly.ZWave.Commands.ThermostatSetbackGet do
@moduledoc """
This module implements command THERMOSTAT_SETBACK_GET of the command class
COMMAND_CLASS_THERMOSTAT_SETBACK.
This command is used to request the current setback state of the thermostat.
Params: - none -
"""
@behaviour Grizzly.ZWave.Command
alias Grizzly.ZWave.Command
alias Grizzly.ZWave.CommandClasses.ThermostatSetback
@impl true
def new(_opts \\ []) do
command = %Command{
name: :thermostat_setback_get,
command_byte: 0x02,
command_class: ThermostatSetback,
impl: __MODULE__
}
{:ok, command}
end
@impl true
def encode_params(_command) do
<<>>
end
@impl true
def decode_params(_binary) do
{:ok, []}
end
end
| 19.794872 | 78 | 0.702073 |
0894795359b2a6d1476db96384a98a197dab8a21 | 4,357 | ex | Elixir | clients/health_care/lib/google_api/health_care/v1beta1/model/hl7_v2_store.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/health_care/lib/google_api/health_care/v1beta1/model/hl7_v2_store.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/health_care/lib/google_api/health_care/v1beta1/model/hl7_v2_store.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.HealthCare.V1beta1.Model.Hl7V2Store do
@moduledoc """
Represents an HL7v2 store.
## Attributes
* `labels` (*type:* `map()`, *default:* `nil`) - User-supplied key-value pairs used to organize HL7v2 stores. Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes, and must conform to the following PCRE regular expression: \\p{Ll}\\p{Lo}{0,62} Label values are optional, must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes, and must conform to the following PCRE regular expression: [\\p{Ll}\\p{Lo}\\p{N}_-]{0,63} No more than 64 labels can be associated with a given store.
* `name` (*type:* `String.t`, *default:* `nil`) - Resource name of the HL7v2 store, of the form `projects/{project_id}/datasets/{dataset_id}/hl7V2Stores/{hl7v2_store_id}`.
* `notificationConfig` (*type:* `GoogleApi.HealthCare.V1beta1.Model.NotificationConfig.t`, *default:* `nil`) - The notification destination all messages (both Ingest & Create) are published on. Only the message name is sent as part of the notification. If this is unset, no notifications are sent. Supplied by the client.
* `notificationConfigs` (*type:* `list(GoogleApi.HealthCare.V1beta1.Model.Hl7V2NotificationConfig.t)`, *default:* `nil`) - A list of notification configs. Each configuration uses a filter to determine whether to publish a message (both Ingest & Create) on the corresponding notification destination. Only the message name is sent as part of the notification. Supplied by the client.
* `parserConfig` (*type:* `GoogleApi.HealthCare.V1beta1.Model.ParserConfig.t`, *default:* `nil`) - The configuration for the parser. It determines how the server parses the messages.
* `rejectDuplicateMessage` (*type:* `boolean()`, *default:* `nil`) - Determines whether to reject duplicate messages. A duplicate message is a message with the same raw bytes as a message that has already been ingested/created in this HL7v2 store. The default value is false, meaning that the store accepts the duplicate messages and it also returns the same ACK message in the IngestMessageResponse as has been returned previously. Note that only one resource is created in the store. When this field is set to true, CreateMessage/IngestMessage requests with a duplicate message will be rejected by the store, and IngestMessageErrorDetail returns a NACK message upon rejection.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:labels => map() | nil,
:name => String.t() | nil,
:notificationConfig => GoogleApi.HealthCare.V1beta1.Model.NotificationConfig.t() | nil,
:notificationConfigs =>
list(GoogleApi.HealthCare.V1beta1.Model.Hl7V2NotificationConfig.t()) | nil,
:parserConfig => GoogleApi.HealthCare.V1beta1.Model.ParserConfig.t() | nil,
:rejectDuplicateMessage => boolean() | nil
}
field(:labels, type: :map)
field(:name)
field(:notificationConfig, as: GoogleApi.HealthCare.V1beta1.Model.NotificationConfig)
field(:notificationConfigs,
as: GoogleApi.HealthCare.V1beta1.Model.Hl7V2NotificationConfig,
type: :list
)
field(:parserConfig, as: GoogleApi.HealthCare.V1beta1.Model.ParserConfig)
field(:rejectDuplicateMessage)
end
defimpl Poison.Decoder, for: GoogleApi.HealthCare.V1beta1.Model.Hl7V2Store do
def decode(value, options) do
GoogleApi.HealthCare.V1beta1.Model.Hl7V2Store.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.HealthCare.V1beta1.Model.Hl7V2Store do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 64.073529 | 682 | 0.747992 |
0894799e06f5252def158e679f13e045ac338bb7 | 2,239 | ex | Elixir | clients/games/lib/google_api/games/v1/model/event_record_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/event_record_request.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/event_record_request.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.Games.V1.Model.EventRecordRequest do
@moduledoc """
This is a JSON template for an event period update resource.
## Attributes
* `currentTimeMillis` (*type:* `String.t`, *default:* `nil`) - The current time when this update was sent, in milliseconds, since 1970 UTC (Unix Epoch).
* `kind` (*type:* `String.t`, *default:* `games#eventRecordRequest`) - Uniquely identifies the type of this resource. Value is always the fixed string games#eventRecordRequest.
* `requestId` (*type:* `String.t`, *default:* `nil`) - The request ID used to identify this attempt to record events.
* `timePeriods` (*type:* `list(GoogleApi.Games.V1.Model.EventPeriodUpdate.t)`, *default:* `nil`) - A list of the time period updates being made in this request.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:currentTimeMillis => String.t(),
:kind => String.t(),
:requestId => String.t(),
:timePeriods => list(GoogleApi.Games.V1.Model.EventPeriodUpdate.t())
}
field(:currentTimeMillis)
field(:kind)
field(:requestId)
field(:timePeriods, as: GoogleApi.Games.V1.Model.EventPeriodUpdate, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.EventRecordRequest do
def decode(value, options) do
GoogleApi.Games.V1.Model.EventRecordRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.EventRecordRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.982143 | 180 | 0.722197 |
0894fbfa3be457c3d14143b7d827a27d0d569e05 | 1,071 | ex | Elixir | skippy/dashboard/lib/dashboard_web/channels/user_socket.ex | mashbytes/baby_zoo | 4554890242a2493d17d9b1c1f4cc90d7ad1e637e | [
"MIT"
] | null | null | null | skippy/dashboard/lib/dashboard_web/channels/user_socket.ex | mashbytes/baby_zoo | 4554890242a2493d17d9b1c1f4cc90d7ad1e637e | [
"MIT"
] | 5 | 2020-07-17T23:35:42.000Z | 2021-05-10T07:00:10.000Z | skippy/dashboard/lib/dashboard_web/channels/user_socket.ex | mashbytes/baby_zoo | 4554890242a2493d17d9b1c1f4cc90d7ad1e637e | [
"MIT"
] | null | null | null | defmodule DashboardWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", DashboardWeb.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# DashboardWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31.5 | 84 | 0.698413 |
08951157232d0b1941ff3215307c72fe8c272398 | 2,572 | ex | Elixir | lib/task_bunny/job_runner.ex | smartrent/task_bunny | db0b91d966b54df75e0f60f9c788ffa044c1f37a | [
"MIT"
] | null | null | null | lib/task_bunny/job_runner.ex | smartrent/task_bunny | db0b91d966b54df75e0f60f9c788ffa044c1f37a | [
"MIT"
] | null | null | null | lib/task_bunny/job_runner.ex | smartrent/task_bunny | db0b91d966b54df75e0f60f9c788ffa044c1f37a | [
"MIT"
] | null | null | null | defmodule TaskBunny.JobRunner do
# Handles job invocation concerns.
#
# This module is private to TaskBunny and should not be accessed directly.
#
# JobRunner wraps up job execution and provides you abilities:
#
# - invoking jobs concurrently (unblocking job execution)
# - handling a job crashing
# - handling timeout
#
# ## Signal
#
# Once the job has finished it sends a message with a tuple consisted with:
#
# - atom indicating message type: :job_finished
# - result: :ok or {:error, details}
# - meta: meta data for the job
#
# After sending the messsage, JobRunner shuts down all processes it started.
#
@moduledoc false
require Logger
alias TaskBunny.JobError
alias TaskBunny.Message
@doc ~S"""
Invokes the given job with the given payload.
The job is run in a seperate process, which is killed after the job.timeout if the job has not finished yet.
A :error message is send to the :job_finished of the caller if the job times out.
"""
@spec invoke(map(), {any, any}) :: {:ok | :error, any}
def invoke(decoded, {_body, meta} = message) do
caller = self()
job = decoded["job"]
payload = decoded["payload"]
headers = Map.get(meta, :headers, [])
meta =
Map.merge(meta, %{
failures: Message.failed_count(decoded),
enqueued_at: Message.enqueued_at(headers)
})
timeout_error = {:error, JobError.handle_timeout(job, payload)}
timer =
Process.send_after(
caller,
{:job_finished, timeout_error, message},
job.timeout
)
pid =
spawn(fn ->
send(caller, {:job_finished, run_job(job, payload, meta), message})
Process.cancel_timer(timer)
end)
:timer.kill_after(job.timeout + 10, pid)
end
# Performs a job with the given payload.
# Any raises or throws in the perform are caught and turned into an :error tuple.
@spec run_job(atom, any, any) :: :ok | {:ok, any} | {:error, any}
defp run_job(job, payload, meta) do
case job.perform(payload, meta) do
:ok -> :ok
{:ok, something} -> {:ok, something}
error -> {:error, JobError.handle_return_value(job, payload, error)}
end
rescue
error ->
Logger.debug("TaskBunny.JobRunner - Runner rescued #{inspect(error)}")
{:error, JobError.handle_exception(job, payload, error, __STACKTRACE__)}
catch
_, reason ->
Logger.debug("TaskBunny.JobRunner - Runner caught reason: #{inspect(reason)}")
{:error, JobError.handle_exit(job, payload, reason, __STACKTRACE__)}
end
end
| 30.258824 | 110 | 0.657854 |
0895363b7e3236a07050e7d2d4899301b44838ab | 2,070 | ex | Elixir | clients/cloud_build/lib/google_api/cloud_build/v1/model/update_bitbucket_server_config_operation_metadata.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_build/lib/google_api/cloud_build/v1/model/update_bitbucket_server_config_operation_metadata.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_build/lib/google_api/cloud_build/v1/model/update_bitbucket_server_config_operation_metadata.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudBuild.V1.Model.UpdateBitbucketServerConfigOperationMetadata do
@moduledoc """
Metadata for `UpdateBitbucketServerConfig` operation.
## Attributes
* `bitbucketServerConfig` (*type:* `String.t`, *default:* `nil`) - The resource name of the BitbucketServerConfig to be updated. Format: `projects/{project}/locations/{location}/bitbucketServerConfigs/{id}`.
* `completeTime` (*type:* `DateTime.t`, *default:* `nil`) - Time the operation was completed.
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Time the operation was created.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:bitbucketServerConfig => String.t() | nil,
:completeTime => DateTime.t() | nil,
:createTime => DateTime.t() | nil
}
field(:bitbucketServerConfig)
field(:completeTime, as: DateTime)
field(:createTime, as: DateTime)
end
defimpl Poison.Decoder,
for: GoogleApi.CloudBuild.V1.Model.UpdateBitbucketServerConfigOperationMetadata do
def decode(value, options) do
GoogleApi.CloudBuild.V1.Model.UpdateBitbucketServerConfigOperationMetadata.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.CloudBuild.V1.Model.UpdateBitbucketServerConfigOperationMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.689655 | 211 | 0.733333 |
089556f4bd8884ccfdf0c7b211d11505c5d4072b | 1,458 | ex | Elixir | lib/joken/hooks/required_claims.ex | earv1/joken | 08c91b302cf885475b8a83496ac14a13e0ebefa7 | [
"Apache-2.0"
] | null | null | null | lib/joken/hooks/required_claims.ex | earv1/joken | 08c91b302cf885475b8a83496ac14a13e0ebefa7 | [
"Apache-2.0"
] | null | null | null | lib/joken/hooks/required_claims.ex | earv1/joken | 08c91b302cf885475b8a83496ac14a13e0ebefa7 | [
"Apache-2.0"
] | null | null | null | defmodule Joken.Hooks.RequiredClaims do
@moduledoc """
Hook to demand claims presence.
Adding this hook to your token configuration will allow to ensure some claims are present. It
adds an `after_validate/3` implementation that checks claims presence. Example:
defmodule MyToken do
use Joken.Config
add_hook Joken.Hooks.RequiredClaims, [:claim1, :claim2]
end
On missing claims it returns: `{:error, [message: "Invalid token", missing_claims: claims]}`.
"""
use Joken.Hooks
@impl Joken.Hooks
def after_validate([], _, _) do
raise "Missing required claims options"
end
def after_validate(opts, _, _) when not is_list(opts) do
raise "Options must be a list of claim keys"
end
def after_validate(required_claims, {:ok, claims} = result, input) do
required_claims = required_claims |> Enum.map(&map_keys/1) |> MapSet.new()
claims = claims |> Map.keys() |> MapSet.new()
required_claims
|> MapSet.subset?(claims)
|> case do
true ->
{:cont, result, input}
_ ->
diff = required_claims |> MapSet.difference(claims) |> MapSet.to_list()
{:halt, {:error, [message: "Invalid token", missing_claims: diff]}}
end
end
def after_validate(_, result, input), do: {:cont, result, input}
# will raise if not binary or atom
defp map_keys(key) when is_binary(key), do: key
defp map_keys(key) when is_atom(key), do: Atom.to_string(key)
end
| 29.755102 | 95 | 0.674211 |
089558b8c040f682d8f85b8c67532d28d448023b | 579 | ex | Elixir | elixir/lib/homework/users/user.ex | simmons-hayden/web-homework | de9e339f2c6e5c082ea1b3f14aeb54caf03752f1 | [
"MIT"
] | null | null | null | elixir/lib/homework/users/user.ex | simmons-hayden/web-homework | de9e339f2c6e5c082ea1b3f14aeb54caf03752f1 | [
"MIT"
] | null | null | null | elixir/lib/homework/users/user.ex | simmons-hayden/web-homework | de9e339f2c6e5c082ea1b3f14aeb54caf03752f1 | [
"MIT"
] | null | null | null | defmodule Homework.Users.User do
use Ecto.Schema
import Ecto.Changeset
alias Homework.Companies.Company
@primary_key {:id, :binary_id, autogenerate: true}
schema "users" do
field(:dob, :string)
field(:first_name, :string)
field(:last_name, :string)
belongs_to(:company, Company, type: :binary_id, foreign_key: :company_id)
timestamps()
end
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:first_name, :last_name, :dob, :company_id])
|> validate_required([:first_name, :last_name, :dob, :company_id])
end
end
| 23.16 | 77 | 0.685665 |
089583a844142651f2f2e4f8ded735ba3022154f | 553 | ex | Elixir | lib/server/server.ex | henriquetorquato/hermes | 6d98ecdffd6486c1f64e8e0c5827fd512c719296 | [
"MIT"
] | null | null | null | lib/server/server.ex | henriquetorquato/hermes | 6d98ecdffd6486c1f64e8e0c5827fd512c719296 | [
"MIT"
] | null | null | null | lib/server/server.ex | henriquetorquato/hermes | 6d98ecdffd6486c1f64e8e0c5827fd512c719296 | [
"MIT"
] | null | null | null | defmodule Server do
use Supervisor
def init(_) do
children = [
{Room.Manager, []},
{Server.Receiver, [name: :receiver, debug: [:trace]]}
]
Supervisor.init(children, strategy: :one_for_one)
end
def start do
Supervisor.start_link(__MODULE__, [], name: __MODULE__)
end
def join(roomname, user, username) do
room = Room.Manager.get_or_create roomname
Room.join room, user, username
end
def message(message) do
room = Room.Manager.get message.recipient
Room.broadcast room, message
end
end
| 19.75 | 59 | 0.670886 |
089598857451985ab3c3f28071dd3692a3f6e0a5 | 6,265 | exs | Elixir | test/absinthe/phase/execution/non_null_test.exs | arturs678/absinthe | 0d842c46e5d21399d66919cdaadfa8927fbca74d | [
"MIT"
] | 4,101 | 2016-03-02T03:49:20.000Z | 2022-03-31T05:46:01.000Z | test/absinthe/phase/execution/non_null_test.exs | arturs678/absinthe | 0d842c46e5d21399d66919cdaadfa8927fbca74d | [
"MIT"
] | 889 | 2016-03-02T16:06:59.000Z | 2022-03-31T20:24:12.000Z | test/absinthe/phase/execution/non_null_test.exs | arturs678/absinthe | 0d842c46e5d21399d66919cdaadfa8927fbca74d | [
"MIT"
] | 564 | 2016-03-02T07:49:59.000Z | 2022-03-06T14:40:59.000Z | defmodule Absinthe.Phase.Document.Execution.NonNullTest do
use Absinthe.Case, async: true
defmodule Schema do
use Absinthe.Schema
defp thing_resolver(_, %{make_null: make_null}, _) do
if make_null do
{:ok, nil}
else
{:ok, %{}}
end
end
defp thing_resolver(_, _, _) do
{:ok, %{}}
end
object :thing do
field :nullable, :thing do
arg :make_null, :boolean
resolve &thing_resolver/3
end
@desc """
A field declared to be non null.
It accepts an argument for testing that can be used to make it return null,
testing the null handling behaviour.
"""
field :non_null, non_null(:thing) do
arg :make_null, :boolean
resolve &thing_resolver/3
end
field :non_null_error_field, non_null(:string) do
resolve fn _, _ ->
{:error, "boom"}
end
end
end
query do
field :nullable, :thing do
arg :make_null, :boolean
resolve &thing_resolver/3
end
field :non_null_error_field, non_null(:string) do
resolve fn _, _ ->
{:error, "boom"}
end
end
field :nullable_list_of_nullable, list_of(:thing) do
resolve fn _, _ ->
{:ok, [%{}]}
end
end
field :nullable_list_of_non_null, list_of(non_null(:thing)) do
resolve fn _, _ ->
{:ok, [%{}]}
end
end
field :non_null_list_of_non_null, non_null(list_of(non_null(:thing))) do
resolve fn _, _ ->
{:ok, [%{}]}
end
end
@desc """
A field declared to be non null.
It accepts an argument for testing that can be used to make it return null,
testing the null handling behaviour.
"""
field :non_null, non_null(:thing) do
arg :make_null, :boolean
resolve &thing_resolver/3
end
end
end
test "getting a null value normally works fine" do
doc = """
{
nullable { nullable(makeNull: true) { __typename }}
}
"""
assert {:ok, %{data: %{"nullable" => %{"nullable" => nil}}}} == Absinthe.run(doc, Schema)
end
test "returning nil from a non null field makes the parent nullable null" do
doc = """
{
nullable { nullable { nonNull(makeNull: true) { __typename }}}
}
"""
data = %{"nullable" => %{"nullable" => nil}}
errors = [
%{
locations: [%{column: 25, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nullable", "nullable", "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "returning nil from a non null child of non nulls pushes nil all the way up to data" do
doc = """
{
nonNull { nonNull { nonNull(makeNull: true) { __typename }}}
}
"""
data = nil
errors = [
%{
locations: [%{column: 23, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nonNull", "nonNull", "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "error propagation to root field returns nil on data" do
doc = """
{
nullable { nullable { nonNullErrorField }}
}
"""
data = %{"nullable" => %{"nullable" => nil}}
errors = [
%{
locations: [%{column: 25, line: 2}],
message: "boom",
path: ["nullable", "nullable", "nonNullErrorField"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "returning an error from a non null field makes the parent nullable null" do
doc = """
{
nonNull { nonNull { nonNullErrorField }}
}
"""
result = Absinthe.run(doc, Schema)
errors = [
%{
locations: [%{column: 23, line: 2}],
message: "boom",
path: ["nonNull", "nonNull", "nonNullErrorField"]
}
]
assert {:ok, %{data: nil, errors: errors}} == result
end
test "returning an error from a non null field makes the parent nullable null at arbitrary depth" do
doc = """
{
nullable { nonNull { nonNull { nonNull { nonNull { nonNullErrorField }}}}}
}
"""
data = %{"nullable" => nil}
path = ["nullable", "nonNull", "nonNull", "nonNull", "nonNull", "nonNullErrorField"]
errors = [
%{locations: [%{column: 54, line: 2}], message: "boom", path: path}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
describe "lists" do
test "list of nullable things works when child has a null violation" do
doc = """
{
nullableListOfNullable { nonNull(makeNull: true) { __typename } }
}
"""
data = %{"nullableListOfNullable" => [nil]}
errors = [
%{
locations: [%{column: 28, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nullableListOfNullable", 0, "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "list of non null things works when child has a null violation" do
doc = """
{
nullableListOfNonNull { nonNull(makeNull: true) { __typename } }
}
"""
data = %{"nullableListOfNonNull" => nil}
errors = [
%{
locations: [%{column: 27, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nullableListOfNonNull", 0, "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
test "list of non null things works when child has a null violation and the root field is non null" do
doc = """
{
nonNullListOfNonNull { nonNull(makeNull: true) { __typename } }
}
"""
data = nil
errors = [
%{
locations: [%{column: 26, line: 2}],
message: "Cannot return null for non-nullable field",
path: ["nonNullListOfNonNull", 0, "nonNull"]
}
]
assert {:ok, %{data: data, errors: errors}} == Absinthe.run(doc, Schema)
end
end
end
| 24.568627 | 106 | 0.551796 |
0895a3b298fe0cbf2840ae80f7fd83a19d2d5c1b | 4,226 | ex | Elixir | lib/oban/query.ex | manusajith/oban | 0d7115fbf5e344878e0d2ac840ea8f84c2bcf26b | [
"MIT"
] | null | null | null | lib/oban/query.ex | manusajith/oban | 0d7115fbf5e344878e0d2ac840ea8f84c2bcf26b | [
"MIT"
] | null | null | null | lib/oban/query.ex | manusajith/oban | 0d7115fbf5e344878e0d2ac840ea8f84c2bcf26b | [
"MIT"
] | null | null | null | defmodule Oban.Query do
@moduledoc false
import Ecto.Query
import DateTime, only: [utc_now: 0]
alias Oban.Job
@type repo :: module()
# Taking a shared lock this way will always work, even if a lock has been taken by another
# connection.
defmacrop take_lock(id) do
quote do
fragment("pg_try_advisory_lock_shared(?)", unquote(id))
end
end
# Dropping a lock uses the same format as taking a lock. Only the session that originally took
# the lock can drop it, but we can't guarantee that the connection used to complete a job was
# the same connection that fetched the job. Therefore, not all locks will be released
# immediately after a job is finished. That's ok, as the locks are guaranteed to be released
# when the connection closes.
defmacrop drop_lock(id) do
quote do
fragment("pg_advisory_unlock_shared(?)", unquote(id))
end
end
@spec fetch_available_jobs(repo(), binary(), pos_integer()) :: {integer(), nil | [Job.t()]}
def fetch_available_jobs(repo, queue, demand) do
subquery =
Job
|> where([j], j.state == "available")
|> where([j], j.queue == ^queue)
|> where([j], j.scheduled_at <= ^utc_now())
|> lock("FOR UPDATE SKIP LOCKED")
|> limit(^demand)
|> order_by([j], asc: j.scheduled_at, asc: j.id)
|> select([j], %{id: j.id, lock: take_lock(j.id)})
query = from(j in Job, join: x in subquery(subquery), on: j.id == x.id, select: j)
repo.update_all(
query,
set: [state: "executing", attempted_at: utc_now()],
inc: [attempt: 1]
)
end
@spec stage_scheduled_jobs(repo(), binary()) :: {integer(), nil}
def stage_scheduled_jobs(repo, queue) do
Job
|> where([j], j.state in ["scheduled", "retryable"])
|> where([j], j.queue == ^queue)
|> where([j], j.scheduled_at <= ^utc_now())
|> repo.update_all(set: [state: "available"])
end
@spec rescue_orphaned_jobs(repo(), binary()) :: {integer(), nil}
def rescue_orphaned_jobs(repo, queue) do
Job
|> where([j], j.state == "executing")
|> where([j], j.queue == ^queue)
|> where([j], j.id not in fragment("SELECT objid FROM pg_locks WHERE locktype = 'advisory'"))
|> repo.update_all(set: [state: "available"])
end
@spec delete_truncated_jobs(repo(), pos_integer()) :: {integer(), nil}
def delete_truncated_jobs(repo, limit) do
subquery =
Job
|> where([j], j.state in ["completed", "discarded"])
|> offset(^limit)
|> order_by(desc: :id)
repo.delete_all(from(j in Job, join: x in subquery(subquery), on: j.id == x.id))
end
@spec delete_outdated_jobs(repo(), pos_integer()) :: {integer(), nil}
def delete_outdated_jobs(repo, seconds) do
outdated_at = DateTime.add(utc_now(), -seconds)
Job
|> where([j], j.state == "completed" and j.completed_at < ^outdated_at)
|> or_where([j], j.state == "discarded" and j.attempted_at < ^outdated_at)
|> repo.delete_all()
end
@spec complete_job(repo(), Job.t()) :: :ok
def complete_job(repo, %Job{id: id}) do
repo.update_all(select_for_update(id), set: [state: "completed", completed_at: utc_now()])
:ok
end
@spec discard_job(repo(), Job.t()) :: :ok
def discard_job(repo, %Job{id: id}) do
repo.update_all(select_for_update(id), set: [state: "discarded", completed_at: utc_now()])
:ok
end
@spec retry_job(repo(), Job.t(), binary()) :: :ok
def retry_job(repo, %Job{} = job, formatted_error) do
%Job{attempt: attempt, id: id, max_attempts: max_attempts} = job
updates =
if attempt >= max_attempts do
[state: "discarded", completed_at: utc_now()]
else
[state: "retryable", completed_at: utc_now(), scheduled_at: next_attempt_at(attempt)]
end
repo.update_all(
select_for_update(id),
set: updates,
push: [errors: %{attempt: attempt, at: utc_now(), error: formatted_error}]
)
end
# Helpers
defp next_attempt_at(attempt, base_offset \\ 15) do
offset = trunc(:math.pow(attempt, 4) + base_offset)
NaiveDateTime.add(utc_now(), offset, :second)
end
defp select_for_update(id) do
Job
|> where(id: ^id)
|> select(%{lock: drop_lock(^id)})
end
end
| 31.073529 | 97 | 0.636299 |
0895ac96be265f6b5d08ffb8232d4466f0e6c4ed | 876 | exs | Elixir | mix.exs | dekokun/elixir_editor | 4abef32a1174055a336fc440d516ac8c4e092799 | [
"MIT"
] | null | null | null | mix.exs | dekokun/elixir_editor | 4abef32a1174055a336fc440d516ac8c4e092799 | [
"MIT"
] | null | null | null | mix.exs | dekokun/elixir_editor | 4abef32a1174055a336fc440d516ac8c4e092799 | [
"MIT"
] | null | null | null | defmodule ElixirEditor.Mixfile do
use Mix.Project
def project do
[app: :elixir_editor,
version: "0.0.1",
elixir: "~> 1.0",
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: [:cowboy, :gproc],
mod: { ElixirEditor, [] },
env: [{:http_port, 8001}]
]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type `mix help deps` for more examples and options
defp deps do
[
{ :cowboy, "1.0.0" },
{:jiffy, github: "davisp/jiffy"},
{:gproc, github: "uwiger/gproc"}
]
end
end
| 21.365854 | 77 | 0.577626 |
0895e8c904ef8e37bfae7c24167cc2cebca4b935 | 1,057 | ex | Elixir | clients/digital_asset_links/lib/google_api/digital_asset_links/v1/connection.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/digital_asset_links/lib/google_api/digital_asset_links/v1/connection.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/digital_asset_links/lib/google_api/digital_asset_links/v1/connection.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.DigitalAssetLinks.V1.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.DigitalAssetLinks.V1.
"""
use GoogleApi.Gax.Connection,
scopes: [],
otp_app: :google_api_digital_asset_links,
base_url: "https://digitalassetlinks.googleapis.com"
end
| 36.448276 | 77 | 0.761589 |
0896016769e0e49edc8a690ef301202311b48f4b | 3,165 | ex | Elixir | clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/model/serving_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/model/serving_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/model/serving_config.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.FirebaseHosting.V1beta1.Model.ServingConfig do
@moduledoc """
The configuration for how incoming requests to a site should be routed and
processed before serving content. The patterns are matched and applied
according to a specific
[priority order](/docs/hosting/full-config#hosting_priority_order).
## Attributes
* `appAssociation` (*type:* `String.t`, *default:* `nil`) - How to handle well known App Association files.
* `cleanUrls` (*type:* `boolean()`, *default:* `nil`) - Defines whether to drop the file extension from uploaded files.
* `headers` (*type:* `list(GoogleApi.FirebaseHosting.V1beta1.Model.Header.t)`, *default:* `nil`) - A list of custom response headers that are added to the content if the
request URL path matches the glob.
* `redirects` (*type:* `list(GoogleApi.FirebaseHosting.V1beta1.Model.Redirect.t)`, *default:* `nil`) - A list of globs that will cause the response to redirect to another
location.
* `rewrites` (*type:* `list(GoogleApi.FirebaseHosting.V1beta1.Model.Rewrite.t)`, *default:* `nil`) - A list of rewrites that will act as if the service were given the
destination URL.
* `trailingSlashBehavior` (*type:* `String.t`, *default:* `nil`) - Defines how to handle a trailing slash in the URL path.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:appAssociation => String.t(),
:cleanUrls => boolean(),
:headers => list(GoogleApi.FirebaseHosting.V1beta1.Model.Header.t()),
:redirects => list(GoogleApi.FirebaseHosting.V1beta1.Model.Redirect.t()),
:rewrites => list(GoogleApi.FirebaseHosting.V1beta1.Model.Rewrite.t()),
:trailingSlashBehavior => String.t()
}
field(:appAssociation)
field(:cleanUrls)
field(:headers, as: GoogleApi.FirebaseHosting.V1beta1.Model.Header, type: :list)
field(:redirects, as: GoogleApi.FirebaseHosting.V1beta1.Model.Redirect, type: :list)
field(:rewrites, as: GoogleApi.FirebaseHosting.V1beta1.Model.Rewrite, type: :list)
field(:trailingSlashBehavior)
end
defimpl Poison.Decoder, for: GoogleApi.FirebaseHosting.V1beta1.Model.ServingConfig do
def decode(value, options) do
GoogleApi.FirebaseHosting.V1beta1.Model.ServingConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.FirebaseHosting.V1beta1.Model.ServingConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.544118 | 174 | 0.729542 |
0896754c3e809b34ff098d93193a888d046e8339 | 1,044 | ex | Elixir | lib/elirc_twitch_oauth_web.ex | rockerBOO/elirc_twitch_oauth_web | 1e4e62ceb57aac7efa68a09d3c9e87fa0f776203 | [
"MIT"
] | null | null | null | lib/elirc_twitch_oauth_web.ex | rockerBOO/elirc_twitch_oauth_web | 1e4e62ceb57aac7efa68a09d3c9e87fa0f776203 | [
"MIT"
] | null | null | null | lib/elirc_twitch_oauth_web.ex | rockerBOO/elirc_twitch_oauth_web | 1e4e62ceb57aac7efa68a09d3c9e87fa0f776203 | [
"MIT"
] | null | null | null | defmodule ElircTwitchOauthWeb do
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Start the endpoint when the application starts
supervisor(ElircTwitchOauthWeb.Endpoint, []),
# Start the Ecto repository
worker(ElircTwitchOauthWeb.Repo, []),
# Here you could define other workers and supervisors as children
# worker(ElircTwitchOauthWeb.Worker, [arg1, arg2, arg3]),
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: ElircTwitchOauthWeb.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
ElircTwitchOauthWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 33.677419 | 73 | 0.729885 |
08969c42120b0dd15ce2b29a7645508600b3a523 | 99,148 | ex | Elixir | clients/iam/lib/google_api/iam/v1/api/projects.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/iam/lib/google_api/iam/v1/api/projects.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/iam/lib/google_api/iam/v1/api/projects.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IAM.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.IAM.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Creates a new custom Role.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The `parent` parameter's value depends on the target resource for the request, namely [`projects`](/iam/reference/rest/v1/projects.roles) or [`organizations`](/iam/reference/rest/v1/organizations.roles). Each resource type's `parent` value format is described below: * [`projects.roles.create()`](/iam/reference/rest/v1/projects.roles/create): `projects/{PROJECT_ID}`. This method creates project-level [custom roles](/iam/docs/understanding-custom-roles). Example request URL: `https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles` * [`organizations.roles.create()`](/iam/reference/rest/v1/organizations.roles/create): `organizations/{ORGANIZATION_ID}`. This method creates organization-level [custom roles](/iam/docs/understanding-custom-roles). Example request URL: `https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles` Note: Wildcard (*) values are invalid; you must specify a complete project ID or organization ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.IAM.V1.Model.CreateRoleRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Role{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_roles_create(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.IAM.V1.Model.Role.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_roles_create(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,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/projects/{projectsId}/roles", %{
"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.IAM.V1.Model.Role{}])
end
@doc """
Deletes a custom Role. When you delete a custom role, the following changes occur immediately: * You cannot bind a member to the custom role in an IAM Policy. * Existing bindings to the custom role are not changed, but they have no effect. * By default, the response from ListRoles does not include the custom role. You have 7 days to undelete the custom role. After 7 days, the following changes occur: * The custom role is permanently deleted and cannot be recovered. * If an IAM policy contains a binding to the custom role, the binding is permanently removed.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The `name` parameter's value depends on the target resource for the request, namely [`projects`](/iam/reference/rest/v1/projects.roles) or [`organizations`](/iam/reference/rest/v1/organizations.roles). Each resource type's `name` value format is described below: * [`projects.roles.delete()`](/iam/reference/rest/v1/projects.roles/delete): `projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`. This method deletes only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the project level. Example request URL: `https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}` * [`organizations.roles.delete()`](/iam/reference/rest/v1/organizations.roles/delete): `organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`. This method deletes only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the organization level. Example request URL: `https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}` Note: Wildcard (*) values are invalid; you must specify a complete project ID or organization ID.
* `roles_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").
* `:etag` (*type:* `String.t`) - Used to perform a consistent read-modify-write.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Role{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_roles_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Role.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_roles_delete(
connection,
projects_id,
roles_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,
:etag => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/projects/{projectsId}/roles/{rolesId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"rolesId" => URI.encode(roles_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.Role{}])
end
@doc """
Gets the definition of a Role.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The `name` parameter's value depends on the target resource for the request, namely [`roles`](/iam/reference/rest/v1/roles), [`projects`](/iam/reference/rest/v1/projects.roles), or [`organizations`](/iam/reference/rest/v1/organizations.roles). Each resource type's `name` value format is described below: * [`roles.get()`](/iam/reference/rest/v1/roles/get): `roles/{ROLE_NAME}`. This method returns results from all [predefined roles](/iam/docs/understanding-roles#predefined_roles) in Cloud IAM. Example request URL: `https://iam.googleapis.com/v1/roles/{ROLE_NAME}` * [`projects.roles.get()`](/iam/reference/rest/v1/projects.roles/get): `projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`. This method returns only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the project level. Example request URL: `https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}` * [`organizations.roles.get()`](/iam/reference/rest/v1/organizations.roles/get): `organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`. This method returns only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the organization level. Example request URL: `https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}` Note: Wildcard (*) values are invalid; you must specify a complete project ID or organization ID.
* `roles_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.IAM.V1.Model.Role{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_roles_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.IAM.V1.Model.Role.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_roles_get(connection, projects_id, roles_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("/v1/projects/{projectsId}/roles/{rolesId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"rolesId" => URI.encode(roles_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.Role{}])
end
@doc """
Lists every predefined Role that IAM supports, or every custom role that is defined for an organization or project.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. The `parent` parameter's value depends on the target resource for the request, namely [`roles`](/iam/reference/rest/v1/roles), [`projects`](/iam/reference/rest/v1/projects.roles), or [`organizations`](/iam/reference/rest/v1/organizations.roles). Each resource type's `parent` value format is described below: * [`roles.list()`](/iam/reference/rest/v1/roles/list): An empty string. This method doesn't require a resource; it simply returns all [predefined roles](/iam/docs/understanding-roles#predefined_roles) in Cloud IAM. Example request URL: `https://iam.googleapis.com/v1/roles` * [`projects.roles.list()`](/iam/reference/rest/v1/projects.roles/list): `projects/{PROJECT_ID}`. This method lists all project-level [custom roles](/iam/docs/understanding-custom-roles). Example request URL: `https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles` * [`organizations.roles.list()`](/iam/reference/rest/v1/organizations.roles/list): `organizations/{ORGANIZATION_ID}`. This method lists all organization-level [custom roles](/iam/docs/understanding-custom-roles). Example request URL: `https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles` Note: Wildcard (*) values are invalid; you must specify a complete project ID or organization ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Optional limit on the number of roles to include in the response. The default is 300, and the maximum is 1,000.
* `:pageToken` (*type:* `String.t`) - Optional pagination token returned in an earlier ListRolesResponse.
* `:showDeleted` (*type:* `boolean()`) - Include Roles that have been deleted.
* `:view` (*type:* `String.t`) - Optional view for the returned Role objects. When `FULL` is specified, the `includedPermissions` field is returned, which includes a list of all permissions in the role. The default value is `BASIC`, which does not return the `includedPermissions` field.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ListRolesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_roles_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.IAM.V1.Model.ListRolesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_roles_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,
:pageSize => :query,
:pageToken => :query,
:showDeleted => :query,
:view => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectsId}/roles", %{
"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.IAM.V1.Model.ListRolesResponse{}])
end
@doc """
Updates the definition of a custom Role.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The `name` parameter's value depends on the target resource for the request, namely [`projects`](/iam/reference/rest/v1/projects.roles) or [`organizations`](/iam/reference/rest/v1/organizations.roles). Each resource type's `name` value format is described below: * [`projects.roles.patch()`](/iam/reference/rest/v1/projects.roles/patch): `projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`. This method updates only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the project level. Example request URL: `https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}` * [`organizations.roles.patch()`](/iam/reference/rest/v1/organizations.roles/patch): `organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`. This method updates only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the organization level. Example request URL: `https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}` Note: Wildcard (*) values are invalid; you must specify a complete project ID or organization ID.
* `roles_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").
* `:updateMask` (*type:* `String.t`) - A mask describing which fields in the Role have changed.
* `:body` (*type:* `GoogleApi.IAM.V1.Model.Role.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Role{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_roles_patch(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.IAM.V1.Model.Role.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_roles_patch(
connection,
projects_id,
roles_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,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/projects/{projectsId}/roles/{rolesId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"rolesId" => URI.encode(roles_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.Role{}])
end
@doc """
Undeletes a custom Role.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The `name` parameter's value depends on the target resource for the request, namely [`projects`](/iam/reference/rest/v1/projects.roles) or [`organizations`](/iam/reference/rest/v1/organizations.roles). Each resource type's `name` value format is described below: * [`projects.roles.undelete()`](/iam/reference/rest/v1/projects.roles/undelete): `projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`. This method undeletes only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the project level. Example request URL: `https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}` * [`organizations.roles.undelete()`](/iam/reference/rest/v1/organizations.roles/undelete): `organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`. This method undeletes only [custom roles](/iam/docs/understanding-custom-roles) that have been created at the organization level. Example request URL: `https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}` Note: Wildcard (*) values are invalid; you must specify a complete project ID or organization ID.
* `roles_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.IAM.V1.Model.UndeleteRoleRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Role{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_roles_undelete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Role.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_roles_undelete(
connection,
projects_id,
roles_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("/v1/projects/{projectsId}/roles/{rolesId}:undelete", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"rolesId" => URI.encode(roles_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.IAM.V1.Model.Role{}])
end
@doc """
Creates a ServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the project associated with the service accounts, such as `projects/my-project-123`.
* `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.IAM.V1.Model.CreateServiceAccountRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ServiceAccount{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_create(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccount.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_create(
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,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/projects/{projectsId}/serviceAccounts", %{
"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.IAM.V1.Model.ServiceAccount{}])
end
@doc """
Deletes a ServiceAccount. **Warning:** After you delete a service account, you might not be able to undelete it. If you know that you need to re-enable the service account in the future, use DisableServiceAccount instead. If you delete a service account, IAM permanently removes the service account 30 days later. Google Cloud cannot recover the service account after it is permanently removed, even if you file a support request. To help avoid unplanned outages, we recommend that you disable the service account before you delete it. Use DisableServiceAccount to disable the service account, then wait at least 24 hours and watch for unintended consequences. If there are no unintended consequences, you can delete the service account.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_service_accounts_delete(
connection,
projects_id,
service_accounts_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(:delete)
|> Request.url("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" =>
URI.encode(service_accounts_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.Empty{}])
end
@doc """
Disables a ServiceAccount immediately. If an application uses the service account to authenticate, that application can no longer call Google APIs or access Google Cloud resources. Existing access tokens for the service account are rejected, and requests for new access tokens will fail. To re-enable the service account, use EnableServiceAccount. After you re-enable the service account, its existing access tokens will be accepted, and you can request new access tokens. To help avoid unplanned outages, we recommend that you disable the service account before you delete it. Use this method to disable the service account, then wait at least 24 hours and watch for unintended consequences. If there are no unintended consequences, you can delete the service account with DeleteServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.DisableServiceAccountRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_disable(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_service_accounts_disable(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:disable", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.Empty{}])
end
@doc """
Enables a ServiceAccount that was disabled by DisableServiceAccount. If the service account is already enabled, then this method has no effect. If the service account was disabled by other means—for example, if Google disabled the service account because it was compromised—you cannot use this method to enable the service account.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.EnableServiceAccountRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_enable(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_service_accounts_enable(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:enable", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.Empty{}])
end
@doc """
Gets a ServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.ServiceAccount{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccount.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_get(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" =>
URI.encode(service_accounts_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.ServiceAccount{}])
end
@doc """
Gets the IAM policy that is attached to a ServiceAccount. This IAM policy specifies which members have access to the service account. This method does not tell you whether the service account has been granted any roles on other resources. To check whether a service account has role grants on a resource, use the `getIamPolicy` method for that resource. For example, to view the role grants for a project, call the Resource Manager API's [`projects.getIamPolicy`](https://cloud.google.com/resource-manager/reference/rest/v1/projects/getIamPolicy) method.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.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.
* `service_accounts_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. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_service_accounts_get_iam_policy(
connection,
projects_id,
service_accounts_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(:post)
|> Request.url(
"/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.Policy{}])
end
@doc """
Lists every ServiceAccount that belongs to a specific project.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the project associated with the service accounts, such as `projects/my-project-123`.
* `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()`) - Optional limit on the number of service accounts to include in the response. Further accounts can subsequently be obtained by including the ListServiceAccountsResponse.next_page_token in a subsequent request. The default is 20, and the maximum is 100.
* `:pageToken` (*type:* `String.t`) - Optional pagination token returned in an earlier ListServiceAccountsResponse.next_page_token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ListServiceAccountsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.IAM.V1.Model.ListServiceAccountsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_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,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectsId}/serviceAccounts", %{
"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.IAM.V1.Model.ListServiceAccountsResponse{}])
end
@doc """
Patches a ServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `serviceAccount.name`. The resource name of the service account. Use one of the following formats: * `projects/{PROJECT_ID}/serviceAccounts/{EMAIL_ADDRESS}` * `projects/{PROJECT_ID}/serviceAccounts/{UNIQUE_ID}` As an alternative, you can use the `-` wildcard character instead of the project ID: * `projects/-/serviceAccounts/{EMAIL_ADDRESS}` * `projects/-/serviceAccounts/{UNIQUE_ID}` When possible, avoid using the `-` wildcard character, because it can cause response messages to contain misleading error codes. For example, if you try to get the service account `projects/-/serviceAccounts/fake@example.com`, which does not exist, the response contains an HTTP `403 Forbidden` error instead of a `404 Not Found` error.
* `service_accounts_id` (*type:* `String.t`) - Part of `serviceAccount.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.IAM.V1.Model.PatchServiceAccountRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ServiceAccount{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccount.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_patch(
connection,
projects_id,
service_accounts_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(:patch)
|> Request.url("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" =>
URI.encode(service_accounts_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.ServiceAccount{}])
end
@doc """
Sets the IAM policy that is attached to a ServiceAccount. Use this method to grant or revoke access to the service account. For example, you could grant a member the ability to impersonate the service account. This method does not enable the service account to access other resources. To grant roles to a service account on a resource, follow these steps: 1. Call the resource's `getIamPolicy` method to get its current IAM policy. 2. Edit the policy so that it binds the service account to an IAM role for the resource. 3. Call the resource's `setIamPolicy` method to update its IAM policy. For detailed instructions, see [Granting roles to a service account for specific resources](https://cloud.google.com/iam/help/service-accounts/granting-access-to-service-accounts).
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.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.
* `service_accounts_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.IAM.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_service_accounts_set_iam_policy(
connection,
projects_id,
service_accounts_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(
"/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.Policy{}])
end
@doc """
**Note:** This method is deprecated and will stop working on July 1, 2021. Use the [`signBlob`](https://cloud.google.com/iam/help/rest-credentials/v1/projects.serviceAccounts/signBlob) method in the IAM Service Account Credentials API instead. If you currently use this method, see the [migration guide](https://cloud.google.com/iam/help/credentials/migrate-api) for instructions. Signs a blob using the system-managed private key for a ServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. Deprecated. [Migrate to Service Account Credentials API](https://cloud.google.com/iam/help/credentials/migrate-api). The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.SignBlobRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.SignBlobResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_sign_blob(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.SignBlobResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_sign_blob(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:signBlob", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.SignBlobResponse{}])
end
@doc """
**Note:** This method is deprecated and will stop working on July 1, 2021. Use the [`signJwt`](https://cloud.google.com/iam/help/rest-credentials/v1/projects.serviceAccounts/signJwt) method in the IAM Service Account Credentials API instead. If you currently use this method, see the [migration guide](https://cloud.google.com/iam/help/credentials/migrate-api) for instructions. Signs a JSON Web Token (JWT) using the system-managed private key for a ServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. Deprecated. [Migrate to Service Account Credentials API](https://cloud.google.com/iam/help/credentials/migrate-api). The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.SignJwtRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.SignJwtResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_sign_jwt(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.SignJwtResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_sign_jwt(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:signJwt", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.SignJwtResponse{}])
end
@doc """
Tests whether the caller has the specified permissions on a ServiceAccount.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.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.
* `service_accounts_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.IAM.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_test_iam_permissions(
connection,
projects_id,
service_accounts_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(
"/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.TestIamPermissionsResponse{}])
end
@doc """
Restores a deleted ServiceAccount. **Important:** It is not always possible to restore a deleted service account. Use this method only as a last resort. After you delete a service account, IAM permanently removes the service account 30 days later. There is no way to restore a deleted service account that has been permanently removed.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT_UNIQUE_ID}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account.
* `service_accounts_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.IAM.V1.Model.UndeleteServiceAccountRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.UndeleteServiceAccountResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_undelete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.UndeleteServiceAccountResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_undelete(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:undelete", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.UndeleteServiceAccountResponse{}])
end
@doc """
**Note:** We are in the process of deprecating this method. Use PatchServiceAccount instead. Updates a ServiceAccount. You can update only the `display_name` and `description` fields.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The resource name of the service account. Use one of the following formats: * `projects/{PROJECT_ID}/serviceAccounts/{EMAIL_ADDRESS}` * `projects/{PROJECT_ID}/serviceAccounts/{UNIQUE_ID}` As an alternative, you can use the `-` wildcard character instead of the project ID: * `projects/-/serviceAccounts/{EMAIL_ADDRESS}` * `projects/-/serviceAccounts/{UNIQUE_ID}` When possible, avoid using the `-` wildcard character, because it can cause response messages to contain misleading error codes. For example, if you try to get the service account `projects/-/serviceAccounts/fake@example.com`, which does not exist, the response contains an HTTP `403 Forbidden` error instead of a `404 Not Found` error.
* `service_accounts_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.IAM.V1.Model.ServiceAccount.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ServiceAccount{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_update(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccount.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_update(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" =>
URI.encode(service_accounts_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.ServiceAccount{}])
end
@doc """
Creates a ServiceAccountKey.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.CreateServiceAccountKeyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ServiceAccountKey{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_keys_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccountKey.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_keys_create(
connection,
projects_id,
service_accounts_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("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}/keys", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.ServiceAccountKey{}])
end
@doc """
Deletes a ServiceAccountKey. Deleting a service account key does not revoke short-lived credentials that have been issued based on the service account key.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the service account key in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `keys_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.IAM.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_keys_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.IAM.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def iam_projects_service_accounts_keys_delete(
connection,
projects_id,
service_accounts_id,
keys_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(:delete)
|> Request.url(
"/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}/keys/{keysId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_id, &URI.char_unreserved?/1),
"keysId" => URI.encode(keys_id, &(URI.char_unreserved?(&1) || &1 == ?/))
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.Empty{}])
end
@doc """
Gets a ServiceAccountKey.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the service account key in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `keys_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").
* `:publicKeyType` (*type:* `String.t`) - The output format of the public key requested. X509_PEM is the default output format.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ServiceAccountKey{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_keys_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccountKey.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_keys_get(
connection,
projects_id,
service_accounts_id,
keys_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,
:publicKeyType => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}/keys/{keysId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_id, &URI.char_unreserved?/1),
"keysId" => URI.encode(keys_id, &(URI.char_unreserved?(&1) || &1 == ?/))
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.IAM.V1.Model.ServiceAccountKey{}])
end
@doc """
Lists every ServiceAccountKey for a service account.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID`, will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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").
* `:keyTypes` (*type:* `list(String.t)`) - Filters the types of keys the user wants to include in the list response. Duplicate key types are not allowed. If no key type is provided, all keys are returned.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ListServiceAccountKeysResponse{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_keys_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ListServiceAccountKeysResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_keys_list(
connection,
projects_id,
service_accounts_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,
:keyTypes => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}/keys", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.ListServiceAccountKeysResponse{}])
end
@doc """
Creates a ServiceAccountKey, using a public key that you provide.
## Parameters
* `connection` (*type:* `GoogleApi.IAM.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The resource name of the service account in the following format: `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. Using `-` as a wildcard for the `PROJECT_ID` will infer the project from the account. The `ACCOUNT` value can be the `email` address or the `unique_id` of the service account.
* `service_accounts_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.IAM.V1.Model.UploadServiceAccountKeyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.IAM.V1.Model.ServiceAccountKey{}}` on success
* `{:error, info}` on failure
"""
@spec iam_projects_service_accounts_keys_upload(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.IAM.V1.Model.ServiceAccountKey.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def iam_projects_service_accounts_keys_upload(
connection,
projects_id,
service_accounts_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(
"/v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}/keys:upload",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"serviceAccountsId" => URI.encode(service_accounts_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.IAM.V1.Model.ServiceAccountKey{}])
end
end
| 53.855513 | 1,439 | 0.638601 |
0896a7d701b9c15e91b695cb208f4edd6f35fa90 | 10,321 | ex | Elixir | lib/cldr/datetime.ex | fertapric/cldr_dates_times | d1eff81c7a6e4d84484646465650d26d5dfc51db | [
"Apache-2.0"
] | null | null | null | lib/cldr/datetime.ex | fertapric/cldr_dates_times | d1eff81c7a6e4d84484646465650d26d5dfc51db | [
"Apache-2.0"
] | null | null | null | lib/cldr/datetime.ex | fertapric/cldr_dates_times | d1eff81c7a6e4d84484646465650d26d5dfc51db | [
"Apache-2.0"
] | null | null | null | defmodule Cldr.DateTime do
@moduledoc """
Provides localization and formatting of a `DateTime`
struct or any map with the keys `:year`, `:month`,
`:day`, `:calendar`, `:hour`, `:minute`, `:second` and optionally `:microsecond`.
`Cldr.DateTime` provides support for the built-in calendar
`Calendar.ISO` or any calendars defined with
[ex_cldr_calendars](https://hex.pm/packages/ex_cldr_calendars)
CLDR provides standard format strings for `DateTime` which
are reresented by the names `:short`, `:medium`, `:long`
and `:full`. This allows for locale-independent
formatting since each locale will define the underlying
format string as appropriate.
"""
alias Cldr.DateTime.Format
alias Cldr.LanguageTag
@style_types [:short, :medium, :long, :full]
@default_type :medium
defmodule Styles do
@moduledoc false
defstruct Module.get_attribute(Cldr.DateTime, :style_types)
end
@doc """
Formats a DateTime according to a format string
as defined in CLDR and described in [TR35](http://unicode.org/reports/tr35/tr35-dates.html)
## Arguments
* `datetime` is a `%DateTime{}` `or %NaiveDateTime{}`struct or any map that contains the keys
`:year`, `:month`, `:day`, `:calendar`. `:hour`, `:minute` and `:second` with optional
`:microsecond`.
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module. The default is `Cldr.default_backend/0`.
* `options` is a keyword list of options for formatting.
## Options
* `format:` `:short` | `:medium` | `:long` | `:full` or a format string or
any of the keys returned by `Cldr.DateTime.available_format_names`.
The default is `:medium`
* `locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `number_system:` a number system into which the formatted date digits should
be transliterated
* `era: :variant` will use a variant for the era is one is available in the locale.
In the "en" for example, the locale `era: :variant` will return "BCE" instead of "BC".
* `period: :variant` will use a variant for the time period and flexible time period if
one is available in the locale. For example, in the "en" locale `period: :variant` will
return "pm" instead of "PM"
## Returns
* `{:ok, formatted_datetime}` or
* `{:error, reason}`
## Examples
iex> {:ok, datetime} = DateTime.from_naive(~N[2000-01-01 23:59:59.0], "Etc/UTC")
iex> Cldr.DateTime.to_string datetime
{:ok, "Jan 1, 2000, 11:59:59 PM"}
iex> Cldr.DateTime.to_string datetime, MyApp.Cldr, locale: "en"
{:ok, "Jan 1, 2000, 11:59:59 PM"}
iex> Cldr.DateTime.to_string datetime, MyApp.Cldr, format: :long, locale: "en"
{:ok, "January 1, 2000 at 11:59:59 PM UTC"}
iex> Cldr.DateTime.to_string datetime, MyApp.Cldr, format: :hms, locale: "en"
{:ok, "23:59:59"}
iex> Cldr.DateTime.to_string datetime, MyApp.Cldr, format: :full, locale: "en"
{:ok, "Saturday, January 1, 2000 at 11:59:59 PM GMT"}
iex> Cldr.DateTime.to_string datetime, MyApp.Cldr, format: :full, locale: "fr"
{:ok, "samedi 1 janvier 2000 à 23:59:59 UTC"}
"""
@spec to_string(map, Cldr.backend() | Keyword.t(), Keyword.t()) ::
{:ok, String.t()} | {:error, {module, String.t()}}
def to_string(datetime, backend \\ Cldr.Date.default_backend(), options \\ [])
def to_string(%{calendar: Calendar.ISO} = datetime, backend, options) do
%{datetime | calendar: Cldr.Calendar.Gregorian}
|> to_string(backend, options)
end
def to_string(datetime, options, []) when is_list(options) do
to_string(datetime, Cldr.Date.default_backend(), options)
end
def to_string(%{calendar: calendar} = datetime, backend, options)
when is_atom(backend) and is_list(options) do
options = normalize_options(backend, options)
format_backend = Module.concat(backend, DateTime.Formatter)
number_system = Keyword.get(options, :number_system)
with {:ok, locale} <- Cldr.validate_locale(options[:locale], backend),
{:ok, cldr_calendar} <- type_from_calendar(calendar),
{:ok, _} <- Cldr.Number.validate_number_system(locale, number_system, backend),
{:ok, format_string} <- format_string(options[:format], locale, cldr_calendar, backend),
{:ok, formatted} <- format_backend.format(datetime, format_string, locale, options) do
{:ok, formatted}
end
rescue
e in [Cldr.DateTime.UnresolvedFormat] ->
{:error, {e.__struct__, e.message}}
end
def to_string(datetime, _backend, _options) do
error_return(datetime, [:year, :month, :day, :hour, :minute, :second, :calendar])
end
defp normalize_options(backend, []) do
{locale, _backend} = Cldr.locale_and_backend_from(nil, backend)
number_system = Cldr.Number.System.number_system_from_locale(locale, backend)
[locale: locale, number_system: number_system, format: @default_type]
end
defp normalize_options(backend, options) do
{locale, _backend} = Cldr.locale_and_backend_from(options[:locale], backend)
format = options[:format] || options[:style] || @default_type
locale_number_system = Cldr.Number.System.number_system_from_locale(locale, backend)
number_system = Keyword.get(options, :number_system, locale_number_system)
options
|> Keyword.put(:locale, locale)
|> Keyword.put(:format, format)
|> Keyword.delete(:style)
|> Keyword.put_new(:number_system, number_system)
end
@doc false
# Returns the CLDR calendar type for a calendar
def type_from_calendar(Cldr.Calendar.Gregorian = calendar) do
{:ok, calendar.cldr_calendar_type()}
end
def type_from_calendar(calendar) do
with {:ok, calendar} <- Cldr.Calendar.validate_calendar(calendar) do
{:ok, calendar.cldr_calendar_type()}
end
end
@doc """
Formats a DateTime according to a format string
as defined in CLDR and described in [TR35](http://unicode.org/reports/tr35/tr35-dates.html)
returning a formatted string or raising on error.
## Arguments
* `datetime` is a `%DateTime{}` `or %NaiveDateTime{}`struct or any map that contains the keys
`:year`, `:month`, `:day`, `:calendar`. `:hour`, `:minute` and `:second` with optional
`:microsecond`.
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module. The default is `Cldr.default_backend/0`.
* `options` is a keyword list of options for formatting.
## Options
* `format:` `:short` | `:medium` | `:long` | `:full` or a format string or
any of the keys returned by `Cldr.DateTime.available_format_names` or a format string.
The default is `:medium`
* `locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`
* `number_system:` a number system into which the formatted date digits should
be transliterated
* `era: :variant` will use a variant for the era is one is available in the locale.
In the "en" for example, the locale `era: :variant` will return "BCE" instead of "BC".
* `period: :variant` will use a variant for the time period and flexible time period if
one is available in the locale. For example, in the "en" locale `period: :variant` will
return "pm" instead of "PM"
## Returns
* `formatted_datetime` or
* raises an exception
## Examples
iex> {:ok, datetime} = DateTime.from_naive(~N[2000-01-01 23:59:59.0], "Etc/UTC")
iex> Cldr.DateTime.to_string! datetime, MyApp.Cldr, locale: "en"
"Jan 1, 2000, 11:59:59 PM"
iex> Cldr.DateTime.to_string! datetime, MyApp.Cldr, format: :long, locale: "en"
"January 1, 2000 at 11:59:59 PM UTC"
iex> Cldr.DateTime.to_string! datetime, MyApp.Cldr, format: :full, locale: "en"
"Saturday, January 1, 2000 at 11:59:59 PM GMT"
iex> Cldr.DateTime.to_string! datetime, MyApp.Cldr, format: :full, locale: "fr"
"samedi 1 janvier 2000 à 23:59:59 UTC"
"""
@spec to_string!(map, Cldr.backend() | Keyword.t(), Keyword.t()) :: String.t() | no_return
def to_string!(datetime, backend \\ Cldr.Date.default_backend(), options \\ [])
def to_string!(datetime, options, []) when is_list(options) do
to_string!(datetime, Cldr.Date.default_backend(), options)
end
def to_string!(datetime, backend, options) do
case to_string(datetime, backend, options) do
{:ok, string} -> string
{:error, {exception, message}} -> raise exception, message
end
end
# Standard format
defp format_string(style, %LanguageTag{cldr_locale_name: locale_name}, cldr_calendar, backend)
when style in @style_types do
with {:ok, styles} <- Format.date_time_formats(locale_name, cldr_calendar, backend) do
{:ok, Map.get(styles, style)}
end
end
# Look up for the format in :available_formats
defp format_string(style, %LanguageTag{cldr_locale_name: locale_name}, cldr_calendar, backend)
when is_atom(style) do
with {:ok, styles} <-
Format.date_time_available_formats(locale_name, cldr_calendar, backend),
format_string <- Map.get(styles, style) do
if format_string do
{:ok, format_string}
else
{:error,
{Cldr.DateTime.InvalidStyle,
"Invalid datetime style #{inspect(style)}. " <>
"The valid styles are #{inspect(styles)}."}}
end
end
end
# Format with a number system
defp format_string(%{number_system: number_system, format: style}, locale, calendar, backend) do
{:ok, format_string} = format_string(style, locale, calendar, backend)
{:ok, %{number_system: number_system, format: format_string}}
end
# Straight up format string
defp format_string(format_string, _locale, _calendar, _backend)
when is_binary(format_string) do
{:ok, format_string}
end
defp error_return(map, requirements) do
requirements =
requirements
|> Enum.map(&inspect/1)
|> Cldr.DateTime.Formatter.join_requirements()
{:error,
{ArgumentError,
"Invalid DateTime. DateTime is a map that contains at least #{requirements}. " <>
"Found: #{inspect(map)}"}}
end
end
| 37.530909 | 98 | 0.679295 |
089726e09c04a3c15692ff7f68b26e63a7ca5ea4 | 322 | exs | Elixir | test/loom_maps_test.exs | fribmendes/loom | b370f677f2a183db69337b34c7024410da08c548 | [
"Apache-2.0"
] | 206 | 2015-01-02T02:03:07.000Z | 2021-01-10T11:17:21.000Z | test/loom_maps_test.exs | fribmendes/loom | b370f677f2a183db69337b34c7024410da08c548 | [
"Apache-2.0"
] | 7 | 2015-06-17T20:14:17.000Z | 2017-05-30T12:10:28.000Z | test/loom_maps_test.exs | fribmendes/loom | b370f677f2a183db69337b34c7024410da08c548 | [
"Apache-2.0"
] | 16 | 2015-05-05T15:19:41.000Z | 2018-11-15T10:15:50.000Z | defmodule LoomMapsTest do
use ExUnit.Case
import Loom.TypedORMap
alias Loom.PNCounter, as: C
alias Loom.PNCounterMap, as: CMap
test "Basic definition..." do
defmap C
m = C.new |> C.inc(:a, 5) |> C.dec(:a, 3)
c = CMap.new |> CMap.put(:a, "omg", m)
assert 2 == CMap.get_value(c, "omg")
end
end
| 21.466667 | 45 | 0.618012 |
089728debf1975b4e72ee9fcde4307bda6592866 | 2,592 | ex | Elixir | lib/crawly/utils.ex | jallum/crawly | dfe37b125f6b39637608576715b076d0877b1d8b | [
"Apache-2.0"
] | null | null | null | lib/crawly/utils.ex | jallum/crawly | dfe37b125f6b39637608576715b076d0877b1d8b | [
"Apache-2.0"
] | null | null | null | lib/crawly/utils.ex | jallum/crawly | dfe37b125f6b39637608576715b076d0877b1d8b | [
"Apache-2.0"
] | null | null | null | defmodule Crawly.Utils do
@moduledoc ~S"""
Utility functions for Crawly
"""
require Logger
@doc """
A helper function which returns a Request structure for the given URL
"""
@spec request_from_url(binary()) :: Crawly.Request.t()
def request_from_url(url), do: %Crawly.Request{url: url, headers: []}
@doc """
A helper function which converts a list of URLS into a requests list.
"""
@spec requests_from_urls([binary()]) :: [Crawly.Request.t()]
def requests_from_urls(urls), do: Enum.map(urls, &request_from_url/1)
@doc """
A helper function which joins relative url with a base URL
"""
@spec build_absolute_url(binary(), binary()) :: binary()
def build_absolute_url(url, base_url) do
URI.merge(base_url, url) |> to_string()
end
@doc """
A helper function which joins relative url with a base URL for a list
"""
@spec build_absolute_urls([binary()], binary()) :: [binary()]
def build_absolute_urls(urls, base_url) do
Enum.map(urls, fn url -> URI.merge(base_url, url) |> to_string() end)
end
@doc """
Pipeline/Middleware helper
Executes a given list of pipelines on the given item, mimics filtermap
behavior (but probably in a more complex way). Takes an item and state and
passes it through a list of modules which implements a pipeline behavior,
executing the pipeline's run.
The pipe function must return boolean (false) or updated item.
In case if false is returned the item is not being processed by all descendant
pipelines, and dropped.
In case if a given pipeline crashes for the given item, it's result are being
ignored, and the item is being processed by all other descendant pipelines.
The state variable is used to persist the information accross multiple items.
"""
@spec pipe(pipelines, item, state) :: result
when pipelines: [Crawly.Pipeline.t()],
item: map(),
state: map(),
result: {new_item | false, new_state},
new_item: map(),
new_state: map()
def pipe([], item, state), do: {item, state}
def pipe(_, false, state), do: {false, state}
def pipe([pipeline | pipelines], item, state) do
{new_item, new_state} =
try do
{new_item, new_state} = pipeline.run(item, state)
{new_item, new_state}
catch
error, reason ->
Logger.error(
"Pipeline crash: #{pipeline}, error: #{inspect(error)}, reason: #{
inspect(reason)
}"
)
{item, state}
end
pipe(pipelines, new_item, new_state)
end
end
| 32 | 80 | 0.653549 |
08978fe982ecb168398c2a763d2b79ac95e373d1 | 1,941 | ex | Elixir | lib/shopify_api/app_server.ex | pixelunion-apps/elixir-shopifyapi | dcc22f8f9edeeb65daa7b9752f7d8896570b5bfb | [
"Apache-2.0"
] | 2 | 2021-11-11T17:40:44.000Z | 2021-11-29T12:11:19.000Z | lib/shopify_api/app_server.ex | pixelunion-apps/elixir-shopifyapi | dcc22f8f9edeeb65daa7b9752f7d8896570b5bfb | [
"Apache-2.0"
] | 17 | 2021-11-16T17:23:23.000Z | 2022-03-29T18:31:36.000Z | lib/shopify_api/app_server.ex | pixelunion-apps/elixir-shopifyapi | dcc22f8f9edeeb65daa7b9752f7d8896570b5bfb | [
"Apache-2.0"
] | null | null | null | defmodule ShopifyAPI.AppServer do
@moduledoc "Write-through cache for App structs."
use GenServer
alias ShopifyAPI.App
alias ShopifyAPI.Config
@table __MODULE__
def all do
@table
|> :ets.tab2list()
|> Map.new()
end
@spec count() :: integer()
def count, do: :ets.info(@table, :size)
@spec set(App.t()) :: :ok
def set(%App{name: name} = app), do: set(name, app)
@spec set(String.t(), App.t()) :: :ok
def set(name, %App{} = app) do
:ets.insert(@table, {name, app})
do_persist(app)
:ok
end
@spec get(String.t()) :: {:ok, App.t()} | :error
def get(name) do
case :ets.lookup(@table, name) do
[{^name, app}] -> {:ok, app}
[] -> :error
end
end
def get_by_client_id(client_id) do
case :ets.match_object(@table, {:_, %{client_id: client_id}}) do
[{_, app}] -> {:ok, app}
[] -> :error
end
end
## GenServer Callbacks
def start_link(_opts) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@impl GenServer
def init(:ok) do
create_table!()
for %App{} = app <- do_initialize(), do: set(app)
{:ok, :no_state}
end
## Private Helpers
defp create_table! do
:ets.new(@table, [
:set,
:public,
:named_table,
read_concurrency: true
])
end
# Calls a configured initializer to obtain a list of Apps.
defp do_initialize do
case Config.lookup(__MODULE__, :initializer) do
{module, function, args} -> apply(module, function, args)
{module, function} -> apply(module, function, [])
_ -> []
end
end
# Attempts to persist a App if a persistence callback is configured
defp do_persist(%App{name: name} = app) do
case Config.lookup(__MODULE__, :persistence) do
{module, function, args} -> apply(module, function, [name, app | args])
{module, function} -> apply(module, function, [name, app])
_ -> nil
end
end
end
| 22.310345 | 77 | 0.603812 |
0897aca4c9a35ac50d9c6edba9ff8867b1c30e9c | 1,157 | exs | Elixir | mix.exs | rsolovjov/expletive | 75bbd20cc701b1dc743b8e294b9fc0ee6ca3e27c | [
"Apache-2.0"
] | null | null | null | mix.exs | rsolovjov/expletive | 75bbd20cc701b1dc743b8e294b9fc0ee6ca3e27c | [
"Apache-2.0"
] | null | null | null | mix.exs | rsolovjov/expletive | 75bbd20cc701b1dc743b8e294b9fc0ee6ca3e27c | [
"Apache-2.0"
] | null | null | null | defmodule Expletive.Mixfile do
use Mix.Project
def project do
[app: :expletive,
version: "0.1.4",
elixir: "~> 1.0",
deps: deps(),
description: description(),
package: package(),
source_url: "https://github.com/xavier/expletive",
homepage_url: "https://github.com/xavier/expletive"]
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"}
#
# Type `mix help deps` for more examples and options
defp deps do
[{:earmark, "~> 0.1", only: :dev},
{:ex_doc, "0.6.0", only: :dev}]
end
defp description do
"Profanity detection and sanitization library"
end
defp package do
[
files: ["lib", "data", "priv", "mix.exs", "README*", "LICENSE*"],
contributors: ["Xavier Defrang"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/xavier/expletive"}
]
end
end
| 23.612245 | 77 | 0.605877 |
0897ed8ea1f832faced65fb7697818649d6508ff | 703 | ex | Elixir | lib/dispatch/absences/absences.ex | mirego/dispatch | 65f81e264e45676ece8a6dc5f203cf9f283d6ec7 | [
"BSD-3-Clause"
] | 21 | 2019-02-13T15:26:00.000Z | 2021-09-18T13:05:42.000Z | lib/dispatch/absences/absences.ex | mirego/dispatch | 65f81e264e45676ece8a6dc5f203cf9f283d6ec7 | [
"BSD-3-Clause"
] | 26 | 2019-02-13T18:42:44.000Z | 2021-09-16T15:40:05.000Z | lib/dispatch/absences/absences.ex | mirego/dispatch | 65f81e264e45676ece8a6dc5f203cf9f283d6ec7 | [
"BSD-3-Clause"
] | 2 | 2020-05-26T09:09:19.000Z | 2021-04-21T20:43:07.000Z | defmodule Dispatch.Absences do
alias Dispatch.Utils.Normalization
def absent_fullnames do
client().fetch_absents()
|> Enum.filter(&absent_right_now?/1)
|> Enum.map(&extract_fullname/1)
|> Enum.reject(&is_nil/1)
|> Enum.map(&Normalization.normalize/1)
end
defp absent_right_now?(%{start: starts, end: ends}), do: Timex.between?(Timex.now(), starts, ends, inclusive: true)
defp extract_fullname(%ExIcal.Event{summary: summary}) when is_binary(summary) do
summary
|> String.split(" - ")
|> List.last()
|> Normalization.normalize()
end
defp extract_fullname(_), do: nil
defp client, do: Application.get_env(:dispatch, Dispatch)[:absences_client]
end
| 28.12 | 117 | 0.697013 |
0898098a9c4e0646f6f58e860067615509790dab | 353 | exs | Elixir | priv/repo/seeds.exs | jeffersono7/jeffbank | b817b298ed2729fb0f458e19807b1503681ffb1d | [
"BSD-2-Clause"
] | null | null | null | priv/repo/seeds.exs | jeffersono7/jeffbank | b817b298ed2729fb0f458e19807b1503681ffb1d | [
"BSD-2-Clause"
] | null | null | null | priv/repo/seeds.exs | jeffersono7/jeffbank | b817b298ed2729fb0f458e19807b1503681ffb1d | [
"BSD-2-Clause"
] | 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:
#
# JeffBank.Repo.insert!(%JeffBank.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 29.416667 | 61 | 0.708215 |
0898215bb4c76bdbf3b58e0fc3a2220d092e9017 | 3,609 | ex | Elixir | lib/hexpm/ecto/changeset.ex | optikfluffel/hexpm | 3b6c5f314ef5706d5d3c99830f39acba34867049 | [
"Apache-2.0"
] | null | null | null | lib/hexpm/ecto/changeset.ex | optikfluffel/hexpm | 3b6c5f314ef5706d5d3c99830f39acba34867049 | [
"Apache-2.0"
] | null | null | null | lib/hexpm/ecto/changeset.ex | optikfluffel/hexpm | 3b6c5f314ef5706d5d3c99830f39acba34867049 | [
"Apache-2.0"
] | null | null | null | defmodule Hexpm.Changeset do
@moduledoc """
Ecto changeset helpers.
"""
import Ecto.Changeset
@doc """
Checks if a version is valid semver.
"""
def validate_version(changeset, field) do
validate_change(changeset, field, fn
_, %Version{build: nil} ->
[]
_, %Version{} ->
[{field, "build number not allowed"}]
end)
end
def validate_list_required(changeset, field, opts \\ []) do
validate_change(changeset, field, fn
_, [] ->
[{field, Keyword.get(opts, :message, "can't be blank")}]
_, list when is_list(list) ->
[]
end)
end
def validate_requirement(changeset, field, opts) do
validate_change(changeset, field, fn key, req ->
cond do
is_nil(req) ->
[{key, "invalid requirement: #{inspect(req)}, use \">= 0.0.0\" instead"}]
not valid_requirement?(req) ->
[{key, "invalid requirement: #{inspect(req)}"}]
String.contains?(req, "!=") ->
[{key, "invalid requirement: #{inspect(req)}, != is not allowed in requirements"}]
String.contains?(req, "-") and not Keyword.fetch!(opts, :allow_pre) ->
[
{key,
"invalid requirement: #{inspect(req)}, unstable requirements are not allowed for stable releases"}
]
true ->
[]
end
end)
end
defp valid_requirement?(req) do
is_binary(req) and match?({:ok, _}, Version.parse_requirement(req))
end
def validate_verified_email_exists(changeset, field, opts) do
validate_change(changeset, field, fn _, email ->
case Hexpm.Repo.get_by(Hexpm.Accounts.Email, email: email, verified: true) do
nil ->
[]
_ ->
[{field, opts[:message]}]
end
end)
end
def validate_repository(changeset, field, opts) do
validate_change(changeset, field, fn key, dependency_repository ->
organization = Keyword.fetch!(opts, :repository)
if dependency_repository in ["hexpm", organization.name] do
[]
else
[{key, {repository_error(organization, dependency_repository), []}}]
end
end)
end
defp repository_error(%{id: 1}, dependency_repository) do
"dependencies can only belong to public repository \"hexpm\", " <>
"got: #{inspect(dependency_repository)}"
end
defp repository_error(%{name: name}, dependency_repository) do
"dependencies can only belong to public repository \"hexpm\" " <>
"or current repository #{inspect(name)}, got: #{inspect(dependency_repository)}"
end
def validate_password(changeset, field, hash, opts \\ []) do
error_param = "#{field}_current"
error_field = String.to_atom(error_param)
errors =
case Map.fetch(changeset.params, error_param) do
{:ok, value} ->
hash = default_hash(hash)
if Bcrypt.verify_pass(value, hash),
do: [],
else: [{error_field, {"is invalid", []}}]
:error ->
[{error_field, {"can't be blank", []}}]
end
%{
changeset
| validations: [{:password, opts} | changeset.validations],
errors: errors ++ changeset.errors,
valid?: changeset.valid? and errors == []
}
end
@default_password Bcrypt.hash_pwd_salt("password")
defp default_hash(nil), do: @default_password
defp default_hash(""), do: @default_password
defp default_hash(password), do: password
def put_default_embed(changeset, key, value) do
if get_change(changeset, key) do
changeset
else
put_embed(changeset, key, value)
end
end
end
| 27.340909 | 111 | 0.610973 |
08984639ebc10f3221f8ba16adfde0477971b7b5 | 495 | ex | Elixir | lib/conductor_web/views/error_view.ex | meltingice/conductor | 630440adc1081a0991d3dba17ced775a9dd05055 | [
"MIT"
] | null | null | null | lib/conductor_web/views/error_view.ex | meltingice/conductor | 630440adc1081a0991d3dba17ced775a9dd05055 | [
"MIT"
] | 2 | 2021-03-10T20:23:26.000Z | 2021-05-11T15:56:49.000Z | lib/conductor_web/views/error_view.ex | meltingice/conductor | 630440adc1081a0991d3dba17ced775a9dd05055 | [
"MIT"
] | 1 | 2020-06-05T02:34:58.000Z | 2020-06-05T02:34:58.000Z | defmodule ConductorWeb.ErrorView do
use ConductorWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 29.117647 | 61 | 0.737374 |
089899ee0512384753fecbe2d1af1cdae0f92d3e | 2,322 | ex | Elixir | lib/aws/generated/api_gateway_management_api.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/api_gateway_management_api.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/api_gateway_management_api.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"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.ApiGatewayManagementApi do
@moduledoc """
The Amazon API Gateway Management API allows you to directly manage runtime
aspects of your deployed APIs.
To use it, you must explicitly set the SDK's endpoint to point to the endpoint
of your deployed API. The endpoint will be of the form
https://{api-id}.execute-api.{region}.amazonaws.com/{stage}, or will be the
endpoint corresponding to your API's custom domain and base path, if applicable.
"""
alias AWS.Client
alias AWS.Request
def metadata do
%AWS.ServiceMetadata{
abbreviation: nil,
api_version: "2018-11-29",
content_type: "application/x-amz-json-1.1",
credential_scope: nil,
endpoint_prefix: "execute-api",
global?: false,
protocol: "rest-json",
service_id: "ApiGatewayManagementApi",
signature_version: "v4",
signing_name: "execute-api",
target_prefix: nil
}
end
@doc """
Delete the connection with the provided id.
"""
def delete_connection(%Client{} = client, connection_id, input, options \\ []) do
url_path = "/@connections/#{URI.encode(connection_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:delete,
url_path,
query_params,
headers,
input,
options,
204
)
end
@doc """
Get information about the connection with the provided id.
"""
def get_connection(%Client{} = client, connection_id, options \\ []) do
url_path = "/@connections/#{URI.encode(connection_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:get,
url_path,
query_params,
headers,
nil,
options,
200
)
end
@doc """
Sends the provided data to the specified connection.
"""
def post_to_connection(%Client{} = client, connection_id, input, options \\ []) do
url_path = "/@connections/#{URI.encode(connection_id)}"
headers = []
query_params = []
Request.request_rest(
client,
metadata(),
:post,
url_path,
query_params,
headers,
input,
options,
200
)
end
end
| 23.938144 | 84 | 0.632214 |
0898a5b6e54be4a6c6b5549b481fcd913469992a | 815 | ex | Elixir | apps/customer/lib/customer/web/controllers/auth_controller.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 102 | 2017-05-21T18:24:04.000Z | 2022-03-10T12:53:20.000Z | apps/customer/lib/customer/web/controllers/auth_controller.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 2 | 2017-05-21T01:53:30.000Z | 2017-12-01T00:27:06.000Z | apps/customer/lib/customer/web/controllers/auth_controller.ex | JaiMali/job_search-1 | 5fe1afcd80aa5d55b92befed2780cd6721837c88 | [
"MIT"
] | 18 | 2017-05-22T09:51:36.000Z | 2021-09-24T00:57:01.000Z | defmodule Customer.Web.AuthController do
@moduledoc """
Auth controller responsible for handling Ueberauth response on login
"""
use Customer.Web, :controller
plug Ueberauth
alias Customer.Auth.Authorizer
def callback(%{assigns: %{ueberauth_failure: _fails}} = conn, _params, _current_user, _claims) do
conn
|> render("callback.json", %{error: "Failed to authenticate."})
end
def callback(%{assigns: %{ueberauth_auth: auth}} = conn, _params, current_user, _claims) do
case Authorizer.get_or_insert(auth, current_user) do
{:ok, user} ->
{:ok, jwt, _full_claims} = Guardian.encode_and_sign(user, :api)
conn
|> render("callback.html", token: jwt)
{:error, reason} ->
conn
|> render("callback.html", error: reason)
end
end
end
| 29.107143 | 99 | 0.665031 |
0898ed2360e2714272e3222e2aa990648a23ce90 | 1,532 | ex | Elixir | clients/app_engine/lib/google_api/app_engine/v1/model/volume.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/app_engine/lib/google_api/app_engine/v1/model/volume.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/app_engine/lib/google_api/app_engine/v1/model/volume.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.AppEngine.V1.Model.Volume do
@moduledoc """
Volumes mounted within the app container. Only applicable for VM runtimes.
## Attributes
- name (String): Unique name for the volume. Defaults to: `null`.
- sizeGb (Float): Volume size in gigabytes. Defaults to: `null`.
- volumeType (String): Underlying volume type, e.g. 'tmpfs'. Defaults to: `null`.
"""
defstruct [
:"name",
:"sizeGb",
:"volumeType"
]
end
defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.Volume do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.Volume do
def encode(value, options) do
GoogleApi.AppEngine.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 30.64 | 91 | 0.734334 |
0898f13afa16e94c0b5842788db7974402876136 | 799 | exs | Elixir | example/test/web/channels/room_channel_test.exs | chazsconi/elm-phoenix | 584ecbbe95913ba40f607eb47781a46ffb5c3c96 | [
"BSD-3-Clause"
] | 196 | 2016-09-18T14:42:33.000Z | 2022-02-27T08:21:24.000Z | example/test/web/channels/room_channel_test.exs | chazsconi/elm-phoenix | 584ecbbe95913ba40f607eb47781a46ffb5c3c96 | [
"BSD-3-Clause"
] | 45 | 2016-09-24T18:34:17.000Z | 2020-05-30T13:38:27.000Z | example/test/web/channels/room_channel_test.exs | chazsconi/elm-phoenix | 584ecbbe95913ba40f607eb47781a46ffb5c3c96 | [
"BSD-3-Clause"
] | 30 | 2016-10-04T13:18:14.000Z | 2020-05-06T09:19:34.000Z | defmodule ElmPhoenix.Web.RoomChannelTest do
use ElmPhoenix.Web.ChannelCase
alias ElmPhoenix.Web.RoomChannel
setup do
{:ok, _, socket} =
socket("user_id", %{some: :assign})
|> subscribe_and_join(RoomChannel, "room:lobby")
{:ok, socket: socket}
end
test "ping replies with status ok", %{socket: socket} do
ref = push socket, "ping", %{"hello" => "there"}
assert_reply ref, :ok, %{"hello" => "there"}
end
test "shout broadcasts to room:lobby", %{socket: socket} do
push socket, "shout", %{"hello" => "all"}
assert_broadcast "shout", %{"hello" => "all"}
end
test "broadcasts are pushed to the client", %{socket: socket} do
broadcast_from! socket, "broadcast", %{"some" => "data"}
assert_push "broadcast", %{"some" => "data"}
end
end
| 27.551724 | 66 | 0.63204 |
089920fdb18621b1fcd7b291c9cf49d02f64ba79 | 1,918 | ex | Elixir | lib/ex_doc/formatter/html/search_items.ex | Dalgona/ex_doc | 814627067175bfe894461cc3f235ee1d9b71b487 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | lib/ex_doc/formatter/html/search_items.ex | Dalgona/ex_doc | 814627067175bfe894461cc3f235ee1d9b71b487 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | lib/ex_doc/formatter/html/search_items.ex | Dalgona/ex_doc | 814627067175bfe894461cc3f235ee1d9b71b487 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | defmodule ExDoc.Formatter.HTML.SearchItems do
@moduledoc false
alias ExDoc.Formatter.HTML
def create(nodes, extras) do
items = Enum.flat_map(nodes, &module_node/1) ++ Enum.flat_map(extras, &extra/1)
["searchNodes=[", Enum.intersperse(items, ?,), "]"]
end
@h2_split_regex ~r/<h2.*?>/
@header_body_regex ~r/(?<header>.*)<\/h2>(?<body>.*)/s
defp extra(%{id: id, title: title, content: content}) do
[intro | sections] = Regex.split(@h2_split_regex, content)
intro_json_item = encode("#{id}.html", title, :extras, intro)
section_json_items =
sections
|> Enum.map(&Regex.named_captures(@header_body_regex, &1))
|> Enum.map(&extra_section(title, &1["header"], &1["body"], id))
[intro_json_item | section_json_items]
end
defp extra_section(title, header, body, id) do
header = HTML.strip_tags(header)
encode(
"#{id}.html##{HTML.text_to_id(header)}",
"#{title} - #{header}",
:extras,
body
)
end
defp module_node(node = %ExDoc.ModuleNode{id: id, type: type, rendered_doc: doc}) do
module = encode("#{id}.html", id, type, doc)
functions = Enum.map(node.docs, &node_child(&1, id))
types = Enum.map(node.typespecs, &node_child(&1, id))
[module] ++ functions ++ types
end
defp node_child(%{id: id, type: type, rendered_doc: doc}, module) do
encode(
"#{module}.html##{HTML.link_id(id, type)}",
"#{module}.#{id}",
type,
doc
)
end
defp encode(ref, title, type, doc) do
[
"{\"ref\":",
[?", ref, ?"],
",\"title\":",
[?", title, ?"],
",\"type\":",
[?", Atom.to_string(type), ?"],
",\"doc\":",
clean_doc(doc),
"}"
]
end
defp clean_doc(doc) do
doc
|> Kernel.||("")
|> HTML.strip_tags()
|> String.replace(~r/\s+/, " ")
|> String.trim()
|> inspect(printable_limit: :infinity)
end
end
| 25.918919 | 86 | 0.573514 |
08993fa1a0287137e050ba2ae1cdedfde4dd04c7 | 1,926 | exs | Elixir | .formatter.exs | rktjmp/temple | 6fe46cbb4998477d76147fa95c9fd9c7841545ef | [
"MIT"
] | null | null | null | .formatter.exs | rktjmp/temple | 6fe46cbb4998477d76147fa95c9fd9c7841545ef | [
"MIT"
] | null | null | null | .formatter.exs | rktjmp/temple | 6fe46cbb4998477d76147fa95c9fd9c7841545ef | [
"MIT"
] | null | null | null | locals_without_parens = ~w[
temple c
html head title style script
noscript template
body section nav article aside h1 h2 h3 h4 h5 h6
header footer address main
p pre blockquote ol ul li dl dt dd figure figcaption div
a em strong small s cite q dfn abbr data time code var samp kbd
sub sup i b u mark ruby rt rp bdi bdo span
ins del
iframe object video audio canvas
map svg math
table caption colgroup tbody thead tfoot tr td th
form fieldset legend label button select datalist optgroup
option text_area output progress meter
details summary menuitem menu
meta link base
area br col embed hr img input keygen param source track wbr
txt partial
animate animateMotion animateTransform circle clipPath
color-profile defs desc discard ellipse feBlend
feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow
feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset
fePointLight feSpecularLighting feSpotLight feTile feTurbulence filter foreignObject g hatch hatchpath image line linearGradient
marker mask mesh meshgradient meshpatch meshrow metadata mpath path pattern polygon
polyline radialGradient rect set solidcolor stop svg switch symbol text
textPath tspan unknown use view
form_for inputs_for
checkbox color_input checkbox color_input date_input date_select datetime_local_input
datetime_select email_input file_input hidden_input number_input password_input range_input
search_input telephone_input textarea text_input time_input time_select url_input
reset submit phx_label radio_button multiple_select select phx_link phx_button
]a |> Enum.map(fn e -> {e, :*} end)
[
inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"],
locals_without_parens: locals_without_parens,
export: [locals_without_parens: locals_without_parens]
]
| 45.857143 | 130 | 0.813084 |
089946883cf39ce650e93cb6667974d803e2c91f | 61 | ex | Elixir | lib/bosque_web/views/layout_view.ex | prio101/bosque | 3b9d0a789a4c33dce829d5cab9d198145f28b8fd | [
"MIT"
] | null | null | null | lib/bosque_web/views/layout_view.ex | prio101/bosque | 3b9d0a789a4c33dce829d5cab9d198145f28b8fd | [
"MIT"
] | null | null | null | lib/bosque_web/views/layout_view.ex | prio101/bosque | 3b9d0a789a4c33dce829d5cab9d198145f28b8fd | [
"MIT"
] | null | null | null | defmodule BosqueWeb.LayoutView do
use BosqueWeb, :view
end
| 15.25 | 33 | 0.803279 |
089957e0c52e44f15b7fedf548570c589ffe5512 | 5,950 | exs | Elixir | test/adapter_test.exs | jaydeesimon/spandex_datadog | 466760b132cecc2011a28902f1b148fa125dafba | [
"MIT"
] | 1 | 2021-06-24T04:42:16.000Z | 2021-06-24T04:42:16.000Z | test/adapter_test.exs | jaydeesimon/spandex_datadog | 466760b132cecc2011a28902f1b148fa125dafba | [
"MIT"
] | null | null | null | test/adapter_test.exs | jaydeesimon/spandex_datadog | 466760b132cecc2011a28902f1b148fa125dafba | [
"MIT"
] | 1 | 2021-03-09T18:43:22.000Z | 2021-03-09T18:43:22.000Z | defmodule SpandexDatadog.Test.AdapterTest do
use ExUnit.Case, async: true
alias Spandex.SpanContext
alias SpandexDatadog.{
Adapter,
Test.TracedModule,
Test.Util
}
test "a complete trace sends spans" do
TracedModule.trace_one_thing()
spans = Util.sent_spans()
Enum.each(spans, fn span ->
assert span.service == :spandex_test
assert span.meta.env == "test"
end)
end
test "a trace can specify additional attributes" do
TracedModule.trace_with_special_name()
assert(Util.find_span("special_name").service == :special_service)
end
test "a span can specify additional attributes" do
TracedModule.trace_with_special_name()
assert(Util.find_span("special_name_span").service == :special_span_service)
end
test "a complete trace sends a top level span" do
TracedModule.trace_one_thing()
span = Util.find_span("trace_one_thing/0")
refute is_nil(span)
assert span.service == :spandex_test
assert span.meta.env == "test"
end
test "a complete trace sends the internal spans as well" do
TracedModule.trace_one_thing()
assert(Util.find_span("do_one_thing/0") != nil)
end
test "the parent_id for a child span is correct" do
TracedModule.trace_one_thing()
assert(Util.find_span("trace_one_thing/0").span_id == Util.find_span("do_one_thing/0").parent_id)
end
test "a span is correctly notated as an error if an excepton occurs" do
Util.can_fail(fn -> TracedModule.trace_one_error() end)
assert(Util.find_span("trace_one_error/0").error == 1)
end
test "spans all the way up are correctly notated as an error" do
Util.can_fail(fn -> TracedModule.error_two_deep() end)
assert(Util.find_span("error_two_deep/0").error == 1)
assert(Util.find_span("error_one_deep/0").error == 1)
end
test "successul sibling spans are not marked as failures when sibling fails" do
Util.can_fail(fn -> TracedModule.two_fail_one_succeeds() end)
assert(Util.find_span("error_one_deep/0", 0).error == 1)
assert(Util.find_span("do_one_thing/0").error == 0)
assert(Util.find_span("error_one_deep/0", 1).error == 1)
end
describe "distributed_context/2 with Plug.Conn" do
test "returns a SpanContext struct" do
conn =
:get
|> Plug.Test.conn("/")
|> Plug.Conn.put_req_header("x-datadog-trace-id", "123")
|> Plug.Conn.put_req_header("x-datadog-parent-id", "456")
|> Plug.Conn.put_req_header("x-datadog-sampling-priority", "2")
assert {:ok, %SpanContext{} = span_context} = Adapter.distributed_context(conn, [])
assert span_context.trace_id == 123
assert span_context.parent_id == 456
assert span_context.priority == 2
end
test "priority defaults to 1 (i.e. we currently assume all distributed traces should be kept)" do
conn =
:get
|> Plug.Test.conn("/")
|> Plug.Conn.put_req_header("x-datadog-trace-id", "123")
|> Plug.Conn.put_req_header("x-datadog-parent-id", "456")
assert {:ok, %SpanContext{priority: 1}} = Adapter.distributed_context(conn, [])
end
test "returns an error when it cannot detect both a Trace ID and a Span ID" do
conn = Plug.Test.conn(:get, "/")
assert {:error, :no_distributed_trace} = Adapter.distributed_context(conn, [])
end
end
describe "distributed_context/2 with Spandex.headers()" do
test "returns a SpanContext struct when headers is a list" do
headers = [{"x-datadog-trace-id", "123"}, {"x-datadog-parent-id", "456"}, {"x-datadog-sampling-priority", "2"}]
assert {:ok, %SpanContext{} = span_context} = Adapter.distributed_context(headers, [])
assert span_context.trace_id == 123
assert span_context.parent_id == 456
assert span_context.priority == 2
end
test "returns a SpanContext struct when headers is a map" do
headers = %{
"x-datadog-trace-id" => "123",
"x-datadog-parent-id" => "456",
"x-datadog-sampling-priority" => "2"
}
assert {:ok, %SpanContext{} = span_context} = Adapter.distributed_context(headers, [])
assert span_context.trace_id == 123
assert span_context.parent_id == 456
assert span_context.priority == 2
end
test "priority defaults to 1 (i.e. we currently assume all distributed traces should be kept)" do
headers = %{
"x-datadog-trace-id" => "123",
"x-datadog-parent-id" => "456"
}
assert {:ok, %SpanContext{priority: 1}} = Adapter.distributed_context(headers, [])
end
test "returns an error when it cannot detect both a Trace ID and a Span ID" do
headers = %{}
assert {:error, :no_distributed_trace} = Adapter.distributed_context(headers, [])
end
end
describe "inject_context/3" do
test "Prepends distributed tracing headers to an existing list of headers" do
span_context = %SpanContext{trace_id: 123, parent_id: 456, priority: 10}
headers = [{"header1", "value1"}, {"header2", "value2"}]
result = Adapter.inject_context(headers, span_context, [])
assert result == [
{"x-datadog-trace-id", "123"},
{"x-datadog-parent-id", "456"},
{"x-datadog-sampling-priority", "10"},
{"header1", "value1"},
{"header2", "value2"}
]
end
test "Merges distributed tracing headers with an existing map of headers" do
span_context = %SpanContext{trace_id: 123, parent_id: 456, priority: 10}
headers = %{"header1" => "value1", "header2" => "value2"}
result = Adapter.inject_context(headers, span_context, [])
assert result == %{
"x-datadog-trace-id" => "123",
"x-datadog-parent-id" => "456",
"x-datadog-sampling-priority" => "10",
"header1" => "value1",
"header2" => "value2"
}
end
end
end
| 33.615819 | 117 | 0.64605 |
0899783bca3e6dcadc2e34cd565a7144ae9d8095 | 627 | ex | Elixir | lib/open_submissions_web/controllers/fallback_controller.ex | csfalcione/open-submissions-api | b7af153ebe9c1a9bd487f7fc30a25007bdf2b9c3 | [
"MIT"
] | 7 | 2019-02-11T14:31:24.000Z | 2021-12-28T08:15:00.000Z | lib/open_submissions_web/controllers/fallback_controller.ex | tblount/open-submissions-api | fb7395175e8079a659bc65ff7c5a7f1f4fc4b422 | [
"MIT"
] | null | null | null | lib/open_submissions_web/controllers/fallback_controller.ex | tblount/open-submissions-api | fb7395175e8079a659bc65ff7c5a7f1f4fc4b422 | [
"MIT"
] | 2 | 2019-02-11T14:31:37.000Z | 2021-12-28T08:15:01.000Z | defmodule OpenSubmissionsWeb.FallbackController do
@moduledoc """
Translates controller action results into valid `Plug.Conn` responses.
See `Phoenix.Controller.action_fallback/1` for more details.
"""
use OpenSubmissionsWeb, :controller
def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
conn
|> put_status(:unprocessable_entity)
|> put_view(OpenSubmissionsWeb.ChangesetView)
|> render("error.json", changeset: changeset)
end
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(OpenSubmissionsWeb.ErrorView)
|> render(:"404")
end
end
| 27.26087 | 72 | 0.709729 |
089998cb3972244c4a2969aace6f46c559abfafd | 262 | exs | Elixir | priv/repo/migrations/20210425174238_add_subject_to_conversations_and_messages.exs | ZmagoD/papercups | dff9a5822b809edc4fd8ecf198566f9b14ab613f | [
"MIT"
] | 4,942 | 2020-07-20T22:35:28.000Z | 2022-03-31T15:38:51.000Z | priv/repo/migrations/20210425174238_add_subject_to_conversations_and_messages.exs | ZmagoD/papercups | dff9a5822b809edc4fd8ecf198566f9b14ab613f | [
"MIT"
] | 552 | 2020-07-22T01:39:04.000Z | 2022-02-01T00:26:35.000Z | priv/repo/migrations/20210425174238_add_subject_to_conversations_and_messages.exs | ZmagoD/papercups | dff9a5822b809edc4fd8ecf198566f9b14ab613f | [
"MIT"
] | 396 | 2020-07-22T19:27:48.000Z | 2022-03-31T05:25:24.000Z | defmodule ChatApi.Repo.Migrations.AddSubjectToConversationsAndMessages do
use Ecto.Migration
def change do
alter table(:conversations) do
add(:subject, :string)
end
alter table(:messages) do
add(:subject, :string)
end
end
end
| 18.714286 | 73 | 0.70229 |
0899fb372dbc580de9d475bc5fc54000551879a2 | 1,682 | ex | Elixir | lib/commodity_api/socket.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | 7 | 2019-04-11T21:12:49.000Z | 2021-04-14T12:56:42.000Z | lib/commodity_api/socket.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | null | null | null | lib/commodity_api/socket.ex | akdilsiz/commodity-cloud | 08c366c9fc95fbb3565131672db4cc52f8b870c9 | [
"Apache-2.0"
] | 2 | 2019-06-06T18:05:33.000Z | 2019-07-16T08:49:45.000Z |
##
# Copyright 2018 Abdulkadir DILSIZ
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
defmodule Commodity.Api.Socket do
use Phoenix.Socket
## Channels
# channel "room:*", Commodity.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# Commodity.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 33.64 | 83 | 0.703329 |
089a16d380a0e73a7b19ff18ccb8fea4e5a1dedc | 1,869 | ex | Elixir | lib/user/presence.ex | Lechindianer/ex_pnut | 99164b73e9b60bfccb90574dd1a6f418a7bd96ed | [
"ISC"
] | 2 | 2019-07-12T04:07:34.000Z | 2019-11-26T01:08:14.000Z | lib/user/presence.ex | Lechindianer/ex_pnut | 99164b73e9b60bfccb90574dd1a6f418a7bd96ed | [
"ISC"
] | null | null | null | lib/user/presence.ex | Lechindianer/ex_pnut | 99164b73e9b60bfccb90574dd1a6f418a7bd96ed | [
"ISC"
] | 1 | 2019-11-26T01:18:54.000Z | 2019-11-26T01:18:54.000Z | defmodule ExPnut.User.Presence do
import ExPnut.Helper.HTTP
alias ExPnut.User.UserParams
@moduledoc """
A user's presence is the recent status of that user. Each updated presence lasts for 15 minutes, or until another
status is given. Users who do not have a current status show up as "offline".
A user's status can be updated on any authenticated call by simply including the update_presence query parameter
with a status for its value. If this method is attempted, the response's meta.updated_presence key will be set and
true. If it fails to update, it will be false.
Endpoints:
- Get present users
- Get a user's presence
- Update the authenticated user's presence
[https://pnut.io/docs/api/resources/users/presence](https://pnut.io/docs/api/resources/users/presence)
"""
@doc """
Retrieve all users' presence statuses that are not "offline".
"""
def get_presence(client, %UserParams{} = user_params \\ %UserParams{}) do
get(client, "/presence", user_params)
end
@doc """
Retrieve a user's presence.
If the user has never set a presence, "last_seen_at" will not be set.
"""
def get_user_presence(client, user_id, %UserParams{} = user_params \\ %UserParams{}) do
get(client, "/users/#{user_id}/presence", user_params)
end
@doc """
Update a user's presence.
If the "update_presence" query parameter is set on this call, it will override this call. It will not occur twice.
## Parameters
- presence: A string up to 100 unicode characters. If not set, or if it is set to 1, it will be updated to "online".
A value of "offline" or 0 will delete the user's presence and remove them from the list of users online.
"""
def set_presence(client, presence, %UserParams{} = user_params \\ %UserParams{}) do
put(client, "/users/me/presence", "presence=#{presence}", user_params)
end
end
| 36.647059 | 118 | 0.718566 |
089a54c86efcc0ddab4cf7ee093fca0900b1eed8 | 836 | exs | Elixir | test/encoding_uri_test.exs | shanelep/aws_auth | 5fde3711d7958e7144a16006f48462109233e777 | [
"MIT"
] | null | null | null | test/encoding_uri_test.exs | shanelep/aws_auth | 5fde3711d7958e7144a16006f48462109233e777 | [
"MIT"
] | null | null | null | test/encoding_uri_test.exs | shanelep/aws_auth | 5fde3711d7958e7144a16006f48462109233e777 | [
"MIT"
] | null | null | null | defmodule AWSAuth.Encoding.URITest do
use ExUnit.Case
# doctest AWSAuth.Encoding.URI
import AWSAuth.Encoding.URI
test "unescaped characters" do
Enum.each(?a..?z, &(assert char_unescaped?(&1) ))
Enum.each(?A..?Z, &(assert char_unescaped?(&1) ))
Enum.each(?0..?9, &(assert char_unescaped?(&1) ))
Enum.each('-._~', &(assert char_unescaped?(&1) ))
Enum.each(' /', &(refute char_unescaped?(&1)))
end
test "path encoding" do
assert encode_path("/some/path") == "/some/path"
assert encode_path("/some/path/with/sp ce") == "/some/path/with/sp%20ce"
end
test "uri component encoding" do
assert encode_component("component/with/slash") == "component%2Fwith%2Fslash"
assert encode_component("component~with-others._ !\"#$%&@") == "component~with-others._%20%21%22%23%24%25%26%40"
end
end
| 30.962963 | 116 | 0.660287 |
089a70a4577a5aa3b40e6dce1f30bd1867e39f5a | 10,885 | ex | Elixir | lib/pow/ecto/schema/changeset.ex | Immortalin/pow | 96e8e2e58a09c98b52967f3e67ebe847ca763dd8 | [
"MIT"
] | null | null | null | lib/pow/ecto/schema/changeset.ex | Immortalin/pow | 96e8e2e58a09c98b52967f3e67ebe847ca763dd8 | [
"MIT"
] | null | null | null | lib/pow/ecto/schema/changeset.ex | Immortalin/pow | 96e8e2e58a09c98b52967f3e67ebe847ca763dd8 | [
"MIT"
] | null | null | null | defmodule Pow.Ecto.Schema.Changeset do
@moduledoc """
Handles changesets methods for Pow schema.
These methods should never be called directly, but instead the methods
build in macros in `Pow.Ecto.Schema` should be used. This is to ensure
that only compile time configuration is used.
## Configuration options
* `:password_min_length` - minimum password length, defaults to 10
* `:password_max_length` - maximum password length, defaults to 4096
* `:password_hash_methods` - the password hash and verify methods to use,
defaults to:
{&Pow.Ecto.Schema.Password.pbkdf2_hash/1,
&Pow.Ecto.Schema.Password.pbkdf2_verify/2}
* `:email_validator` - the email validation method, defaults to:
&Pow.Ecto.Schema.Changeset.validate_email/1
The method should either return `:ok`, `:error`, or `{:error, reason}`.
"""
alias Ecto.Changeset
alias Pow.{Config, Ecto.Schema, Ecto.Schema.Password}
@password_min_length 10
@password_max_length 4096
@doc """
Validates the user id field.
The user id field is always required. It will be treated as case insensitive,
and it's required to be unique. If the user id field is `:email`, the value
will be validated as an e-mail address too.
"""
@spec user_id_field_changeset(Ecto.Schema.t() | Changeset.t(), map(), Config.t()) :: Changeset.t()
def user_id_field_changeset(user_or_changeset, params, config) do
user_id_field =
case user_or_changeset do
%Changeset{data: %struct{}} -> struct.pow_user_id_field()
%struct{} -> struct.pow_user_id_field()
end
user_or_changeset
|> Changeset.cast(params, [user_id_field])
|> Changeset.update_change(user_id_field, &Schema.normalize_user_id_field_value/1)
|> maybe_validate_email_format(user_id_field, config)
|> Changeset.validate_required([user_id_field])
|> Changeset.unique_constraint(user_id_field)
end
@doc """
Validates the password field.
Calls `confirm_password_changeset/3` and `new_password_changeset/3`.
"""
@spec password_changeset(Ecto.Schema.t() | Changeset.t(), map(), Config.t()) :: Changeset.t()
def password_changeset(user_or_changeset, params, config) do
user_or_changeset
|> confirm_password_changeset(params, config)
|> new_password_changeset(params, config)
end
@doc """
Validates the password field.
A password hash is generated by using `:password_hash_methods` in the
configuration. The password is always required if the password hash is nil,
and it's required to be between `:password_min_length` to
`:password_max_length` characters long.
The password hash is only generated if the changeset is valid, but always
required.
"""
@spec new_password_changeset(Ecto.Schema.t() | Changeset.t(), map(), Config.t()) :: Changeset.t()
def new_password_changeset(user_or_changeset, params, config) do
user_or_changeset
|> Changeset.cast(params, [:password])
|> maybe_require_password()
|> maybe_validate_password(config)
|> maybe_put_password_hash(config)
|> Changeset.validate_required([:password_hash])
end
@doc """
Validates the confirm password field.
Requires `password` and `confirm_password` params to be equal.
"""
@spec confirm_password_changeset(Ecto.Schema.t() | Changeset.t(), map(), Config.t()) :: Changeset.t()
def confirm_password_changeset(user_or_changeset, params, _config) do
user_or_changeset
|> Changeset.cast(params, [:password, :confirm_password])
|> maybe_validate_confirm_password()
end
@doc """
Validates the current password field.
It's only required to provide a current password if the `password_hash`
value exists in the data struct.
"""
@spec current_password_changeset(Ecto.Schema.t() | Changeset.t(), map(), Config.t()) :: Changeset.t()
def current_password_changeset(user_or_changeset, params, config) do
user_or_changeset
|> reset_current_password_field()
|> Changeset.cast(params, [:current_password])
|> maybe_validate_current_password(config)
end
defp reset_current_password_field(%{data: user} = changeset) do
%{changeset | data: reset_current_password_field(user)}
end
defp reset_current_password_field(user) do
%{user | current_password: nil}
end
defp maybe_validate_email_format(changeset, :email, config) do
validate_method = email_validator(config)
Changeset.validate_change(changeset, :email, fn :email, email ->
case validate_method.(email) do
:ok -> []
:error -> [email: {"has invalid format", validator: validate_method}]
{:error, reason} -> [email: {"has invalid format", validator: validate_method, reason: reason}]
end
end)
end
defp maybe_validate_email_format(changeset, _type, _config), do: changeset
defp maybe_validate_current_password(%{data: %{password_hash: nil}} = changeset, _config),
do: changeset
defp maybe_validate_current_password(changeset, config) do
changeset = Changeset.validate_required(changeset, [:current_password])
case changeset.valid? do
true -> validate_current_password(changeset, config)
false -> changeset
end
end
defp validate_current_password(%{data: user, changes: %{current_password: password}} = changeset, config) do
user
|> verify_password(password, config)
|> case do
true -> changeset
_ -> Changeset.add_error(changeset, :current_password, "is invalid")
end
end
@doc """
Verifies a password in a struct.
The password will be verified by using the `:password_hash_methods` in the
configuration.
To prevent timing attacks, a blank password will be passed to the hash method
in the `:password_hash_methods` configuration option if the `:password_hash`
is nil.
"""
@spec verify_password(Ecto.Schema.t(), binary(), Config.t()) :: boolean()
def verify_password(%{password_hash: nil}, _password, config) do
config
|> password_hash_method()
|> apply([""])
false
end
def verify_password(%{password_hash: password_hash}, password, config) do
config
|> password_verify_method()
|> apply([password, password_hash])
end
defp maybe_require_password(%{data: %{password_hash: nil}} = changeset) do
Changeset.validate_required(changeset, [:password])
end
defp maybe_require_password(changeset), do: changeset
defp maybe_validate_password(changeset, config) do
changeset
|> Changeset.get_change(:password)
|> case do
nil -> changeset
_ -> validate_password(changeset, config)
end
end
defp validate_password(changeset, config) do
password_min_length = Config.get(config, :password_min_length, @password_min_length)
password_max_length = Config.get(config, :password_max_length, @password_max_length)
Changeset.validate_length(changeset, :password, min: password_min_length, max: password_max_length)
end
defp maybe_validate_confirm_password(changeset) do
changeset
|> Changeset.get_change(:password)
|> case do
nil -> changeset
password -> validate_confirm_password(changeset, password)
end
end
defp validate_confirm_password(changeset, password) do
confirm_password = Changeset.get_change(changeset, :confirm_password)
case password do
^confirm_password -> changeset
_ -> Changeset.add_error(changeset, :confirm_password, "not same as password")
end
end
defp maybe_put_password_hash(%Changeset{valid?: true, changes: %{password: password}} = changeset, config) do
Changeset.put_change(changeset, :password_hash, hash_password(password, config))
end
defp maybe_put_password_hash(changeset, _config), do: changeset
defp hash_password(password, config) do
config
|> password_hash_method()
|> apply([password])
end
defp password_hash_method(config) do
{password_hash_method, _} = password_hash_methods(config)
password_hash_method
end
defp password_verify_method(config) do
{_, password_verify_method} = password_hash_methods(config)
password_verify_method
end
defp password_hash_methods(config) do
Config.get(config, :password_hash_methods, {&Password.pbkdf2_hash/1, &Password.pbkdf2_verify/2})
end
defp email_validator(config) do
Config.get(config, :email_validator, &__MODULE__.validate_email/1)
end
@doc """
Validates an e-mail.
This implementation has the following rules:
- Split into local-part and domain at last `@` occurance
- Local-part should;
- be at most 64 octets
- separate quoted and unquoted content with a single dot
- only have letters, digits, and the following characters outside quoted
content:
```text
!#$%&'*+-/=?^_`{|}~.
```
- not have any consecutive dots outside quoted content
- Domain should;
- be at most 255 octets
- only have letters, digits, hyphen, and dots
Unicode characters are permitted in both local-part and domain.
"""
@spec validate_email(binary()) :: :ok | {:error, any()}
def validate_email(email) do
[domain | rest] =
email
|> String.split("@")
|> Enum.reverse()
local_part =
rest
|> Enum.reverse()
|> Enum.join("@")
cond do
String.length(local_part) > 64 -> {:error, "local-part too long"}
String.length(domain) > 255 -> {:error, "domain too long"}
local_part == "" -> {:error, "invalid format"}
true -> validate_email(local_part, domain)
end
end
defp validate_email(local_part, domain) do
sanitized_local_part = remove_quotes_from_local_part(local_part)
cond do
local_part_only_quoted?(local_part) ->
validate_domain(domain)
local_part_consective_dots?(sanitized_local_part) ->
{:error, "consective dots in local-part"}
local_part_valid_characters?(sanitized_local_part) ->
validate_domain(domain)
true ->
{:error, "invalid characters in local-part"}
end
end
defp remove_quotes_from_local_part(local_part),
do: Regex.replace(~r/(^\".*\"$)|(^\".*\"\.)|(\.\".*\"$)?/, local_part, "")
defp local_part_only_quoted?(local_part), do: local_part =~ ~r/^"[^\"]+"$/
defp local_part_consective_dots?(local_part), do: local_part =~ ~r/\.\./
defp local_part_valid_characters?(sanitized_local_part),
do: sanitized_local_part =~ ~r<^[\p{L}0-9!#$%&'*+-/=?^_`{|}~\.]+$>u
defp validate_domain(domain) do
cond do
String.first(domain) == "-" -> {:error, "domain begins with hyphen"}
String.last(domain) == "-" -> {:error, "domain ends with hyphen"}
domain =~ ~r/^[\p{L}0-9-\.]+$/u -> :ok
true -> {:error, "invalid characters in domain"}
end
end
end
| 33.492308 | 111 | 0.68994 |
089a7bef88f2a9547dfc5d4a6bf51b064a4c2aca | 3,300 | ex | Elixir | lib/credo/execution/task.ex | isaacsanders/credo | 5623570bb2e3944345f1bf11819ca613533b5e10 | [
"MIT"
] | null | null | null | lib/credo/execution/task.ex | isaacsanders/credo | 5623570bb2e3944345f1bf11819ca613533b5e10 | [
"MIT"
] | null | null | null | lib/credo/execution/task.ex | isaacsanders/credo | 5623570bb2e3944345f1bf11819ca613533b5e10 | [
"MIT"
] | 1 | 2020-06-30T16:32:44.000Z | 2020-06-30T16:32:44.000Z | defmodule Credo.Execution.Task do
@type t :: module
@callback call(exec :: Credo.Execution.t(), opts :: Keyword.t()) :: Credo.Execution.t()
require Logger
alias Credo.Execution
alias Credo.Execution.ExecutionTiming
defmacro __using__(_opts \\ []) do
quote do
@behaviour Credo.Execution.Task
import Credo.Execution
alias Credo.Execution
def call(%Execution{halted: false} = exec, opts) do
exec
end
def error(exec, _opts) do
IO.warn("Execution halted during #{__MODULE__}!")
exec
end
defoverridable call: 2
defoverridable error: 2
end
end
@doc """
Runs a given `task` if the `Execution` wasn't halted and ensures that the
result is also an `Execution` struct.
"""
def run(task, exec, opts \\ [])
def run(task, %Credo.Execution{debug: true} = exec, opts) do
run_with_timing(task, exec, opts)
end
def run(task, exec, opts) do
do_run(task, exec, opts)
end
defp do_run(task, %Credo.Execution{halted: false} = exec, opts) do
old_parent_task = exec.parent_task
old_current_task = exec.current_task
exec = Execution.set_parent_and_current_task(exec, exec.current_task, task)
case task.call(exec, opts) do
%Execution{halted: false} = exec ->
exec
|> Execution.set_parent_and_current_task(old_parent_task, old_current_task)
%Execution{halted: true} = exec ->
exec
|> task.error(opts)
|> Execution.set_parent_and_current_task(old_parent_task, old_current_task)
value ->
# TODO: improve message
IO.warn("Expected task to return %Credo.Execution{}, got: #{inspect(exec)}")
value
end
end
defp do_run(_task, %Execution{} = exec, _opts) do
exec
end
defp do_run(_task, exec, _opts) do
IO.warn(
"Expected second parameter of Task.run/3 to match %Credo.Execution{}, " <>
"got: #{inspect(exec)}"
)
exec
end
#
defp run_with_timing(task, exec, opts) do
context_tuple = {:task, exec, task, opts}
log(:call_start, context_tuple)
{started_at, time, exec} = ExecutionTiming.run(&do_run/3, [task, exec, opts])
log(:call_end, context_tuple, time)
ExecutionTiming.append(exec, [task: task, parent_task: exec.parent_task], started_at, time)
exec
end
defp log(:call_start, {:task_group, _exec, task_group, _opts}) do
Logger.info("Calling #{task_group} ...")
end
defp log(:call_start, {:task, _exec, task, _opts}) do
Logger.info("Calling #{task} ...")
end
defp log(:call_start, context_tuple) do
Logger.info("Calling #{inspect(context_tuple)} ...")
end
defp log(:call_end, {:task_group, _exec, task_group, _opts}, time) do
Logger.info("Finished #{task_group} in #{format_time(time)} ...")
end
defp log(:call_end, {:task, _exec, task, _opts}, time) do
Logger.info("Finished #{task} in #{format_time(time)} ...")
end
defp log(:call_end, context_tuple, time) do
Logger.info("Finished #{inspect(context_tuple)} in #{format_time(time)} ...")
end
defp format_time(time) do
cond do
time > 1_000_000 ->
"#{div(time, 1_000_000)}s"
time > 1_000 ->
"#{div(time, 1_000)}ms"
true ->
"#{time}μs"
end
end
end
| 24.087591 | 95 | 0.637273 |
089a83771fc95a56dfa76f5284bb785d42951d93 | 391 | exs | Elixir | config/dev.exs | uberbrodt/eventstore | 2bcdc7f8bcea6af87a08a4c719141f780e7a4fc4 | [
"MIT"
] | null | null | null | config/dev.exs | uberbrodt/eventstore | 2bcdc7f8bcea6af87a08a4c719141f780e7a4fc4 | [
"MIT"
] | 1 | 2018-08-23T16:47:17.000Z | 2018-08-23T19:56:42.000Z | config/dev.exs | uberbrodt/eventstore | 2bcdc7f8bcea6af87a08a4c719141f780e7a4fc4 | [
"MIT"
] | 1 | 2018-07-30T18:25:06.000Z | 2018-07-30T18:25:06.000Z | use Mix.Config
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
config :mix_test_watch, clear: true
config :eventstore, EventStore.Storage,
serializer: EventStore.TermSerializer,
username: "postgres",
password: "postgres",
database: "eventstore_dev",
hostname: "localhost",
pool_size: 10,
pool_overflow: 5
| 24.4375 | 60 | 0.746803 |
089adbd1399aed9c71bc06e1a623fb3cd4c2da67 | 555 | ex | Elixir | lib/mix/tasks/nerves.release.init.ex | tverlaan/nerves | 515b9b7730a1b2934ac051b0e7075cd7987b6c4a | [
"Apache-2.0"
] | 1 | 2019-06-12T17:34:10.000Z | 2019-06-12T17:34:10.000Z | lib/mix/tasks/nerves.release.init.ex | opencollective/nerves | 81f5d30de283e77f3720a87fa1435619f0da12de | [
"Apache-2.0"
] | null | null | null | lib/mix/tasks/nerves.release.init.ex | opencollective/nerves | 81f5d30de283e77f3720a87fa1435619f0da12de | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Nerves.Release.Init do
use Mix.Task
@moduledoc """
Prepares a new project for use with releases.
By default, this forwards the call to
mix release.init --template /path/to/nerves/release_template.eex
For more information on additional args, reference
mix help release.init
"""
@spec run(OptionParser.argv) :: no_return
def run(args) do
template_path = Path.join(["#{:code.priv_dir(:nerves)}", "templates", "release.eex"])
Mix.Task.run("release.init", args ++ ["--template", template_path])
end
end
| 29.210526 | 89 | 0.702703 |
089ae4f10a75b1c459e5c2239f7c573b3b53b59c | 13,107 | ex | Elixir | lib/elixir/lib/inspect.ex | guilleiguaran/elixir | 952052869ff7af0e293d2a7160b1aebc68fc46be | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/inspect.ex | guilleiguaran/elixir | 952052869ff7af0e293d2a7160b1aebc68fc46be | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/inspect.ex | guilleiguaran/elixir | 952052869ff7af0e293d2a7160b1aebc68fc46be | [
"Apache-2.0"
] | null | null | null | import Kernel, except: [inspect: 1]
import Inspect.Algebra
defrecord Inspect.Opts, raw: false, limit: 50, pretty: false, width: 80
defprotocol Inspect do
@moduledoc """
The `Inspect` protocol is responsible for converting any Elixir
data structure into an algebra document. This document is then
formatted, either in pretty printing format or a regular one.
The `inspect/2` function receives the entity to be inspected
followed by the inspecting options, represented by the record
`Inspect.Opts`.
Inspection is done using the functions available in
`Inspect.Algebra` and by calling `Kernel.inspect/2` recursively
passing the `Inspect.Opts` as an argument. When `Kernel.inspect/2`
receives an `Inspect.Opts` record as the second argument, it returns
the underlying algebra document instead of the formatted string.
## Examples
Many times, inspecting a structure can be implemented in function
of existing entities. For example, here is `HashSet`'s `inspect`
implementation:
defimpl Inspect, for: HashSet do
import Inspect.Algebra
def inspect(dict, opts) do
concat ["#HashSet<", Kernel.inspect(HashSet.to_list(dict), opts), ">"]
end
end
The `concat` function comes from `Inspect.Algebra` and it
concatenates algebra documents together. In the example above,
it is concatenating the string `"HashSet<"` (all strings are
valid algebra documents that keep their formatting when pretty
printed), the document returned by `Kernel.inspect/2` and the
other string `">"`.
Since regular strings are valid entities in an algebra document,
an implementation of inspect may simply return a string,
although that will devoid it of any pretty-printing.
## Error handling
In case there is an error while your structure is being inspected,
Elixir will automatically default to the raw inspecting. You can
however access the underlying error by invoking the Inspect
implementation directly. For example, to test Inspect.HashSet above,
you just need to do:
Inspect.HashSet.inspect(HashSet.new, Inspect.Opts.new)
"""
def inspect(thing, opts)
end
defimpl Inspect, for: Atom do
require Macro
@doc """
Represents the atom as an Elixir term. The atoms `false`, `true`
and `nil` are simply quoted. Modules are properly represented
as modules using the dot notation.
Notice that in Elixir, all operators can be represented using
literal atoms (`:+`, `:-`, etc).
## Examples
iex> inspect(:foo)
":foo"
iex> inspect(nil)
"nil"
iex> inspect(Foo.Bar)
"Foo.Bar"
"""
def inspect(atom, _opts) do
inspect(atom)
end
def inspect(false), do: "false"
def inspect(true), do: "true"
def inspect(nil), do: "nil"
def inspect(:""), do: ":\"\""
def inspect(Elixir), do: "Elixir"
def inspect(atom) do
binary = atom_to_binary(atom)
cond do
valid_atom_identifier?(binary) ->
":" <> binary
valid_ref_identifier?(binary) ->
"Elixir." <> rest = binary
rest
atom in [:{}, :[], :<<>>] ->
":" <> binary
atom in Macro.binary_ops or atom in Macro.unary_ops ->
":" <> binary
true ->
<< ?:, ?", Inspect.BitString.escape(binary, ?") :: binary, ?" >>
end
end
# Detect if atom is an atom alias (Elixir.Foo.Bar.Baz)
defp valid_ref_identifier?("Elixir" <> rest) do
valid_ref_piece?(rest)
end
defp valid_ref_identifier?(_), do: false
defp valid_ref_piece?(<<?., h, t :: binary>>) when h in ?A..?Z do
valid_ref_piece? valid_identifier?(t)
end
defp valid_ref_piece?(<<>>), do: true
defp valid_ref_piece?(_), do: false
# Detect if atom
defp valid_atom_identifier?(<<h, t :: binary>>) when h in ?a..?z or h in ?A..?Z or h == ?_ do
case valid_identifier?(t) do
<<>> -> true
<<??>> -> true
<<?!>> -> true
_ -> false
end
end
defp valid_atom_identifier?(_), do: false
defp valid_identifier?(<<h, t :: binary>>)
when h in ?a..?z
when h in ?A..?Z
when h in ?0..?9
when h == ?_ do
valid_identifier? t
end
defp valid_identifier?(other), do: other
end
defimpl Inspect, for: BitString do
@doc %S"""
Represents a string as itself escaping all necessary
characters. Binaries that contain non-printable characters
are printed using the bitstring syntax.
## Examples
iex> inspect("bar")
"\"bar\""
iex> inspect("f\"oo")
"\"f\\\"oo\""
iex> inspect(<<0,1,2>>)
"<<0, 1, 2>>"
"""
def inspect(thing, opts) when is_binary(thing) do
if String.printable?(thing) do
<< ?", escape(thing, ?") :: binary, ?" >>
else
inspect_bitstring(thing, opts)
end
end
def inspect(thing, opts) do
inspect_bitstring(thing, opts)
end
## Escaping
@doc false
def escape(other, char) do
escape(other, char, <<>>)
end
defp escape(<< char, t :: binary >>, char, binary) do
escape(t, char, << binary :: binary, ?\\, char >>)
end
defp escape(<<?#, ?{, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?#, ?{ >>)
end
defp escape(<<?\a, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?a >>)
end
defp escape(<<?\b, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?b >>)
end
defp escape(<<?\d, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?d >>)
end
defp escape(<<?\e, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?e >>)
end
defp escape(<<?\f, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?f >>)
end
defp escape(<<?\n, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?n >>)
end
defp escape(<<?\r, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?r >>)
end
defp escape(<<?\\, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?\\ >>)
end
defp escape(<<?\t, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?t >>)
end
defp escape(<<?\v, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, ?\\, ?v >>)
end
defp escape(<<h, t :: binary>>, char, binary) do
escape(t, char, << binary :: binary, h >>)
end
defp escape(<<>>, _char, binary), do: binary
## Bitstrings
defp inspect_bitstring(bitstring, Inspect.Opts[] = opts) do
each_bit(bitstring, opts.limit, "<<") <> ">>"
end
defp each_bit(_, 0, acc) do
acc <> "..."
end
defp each_bit(<<h, t :: bitstring>>, counter, acc) when t != <<>> do
each_bit(t, decrement(counter), acc <> integer_to_binary(h) <> ", ")
end
defp each_bit(<<h :: size(8)>>, _counter, acc) do
acc <> integer_to_binary(h)
end
defp each_bit(<<>>, _counter, acc) do
acc
end
defp each_bit(bitstring, _counter, acc) do
size = bit_size(bitstring)
<<h :: size(size)>> = bitstring
acc <> integer_to_binary(h) <> "::size(" <> integer_to_binary(size) <> ")"
end
defp decrement(:infinity), do: :infinity
defp decrement(counter), do: counter - 1
end
defimpl Inspect, for: List do
@doc %S"""
Represents a list, checking if it can be printed or not.
If so, a single-quoted representation is returned,
otherwise the brackets syntax is used. Keywords are
printed in keywords syntax.
## Examples
iex> inspect('bar')
"'bar'"
iex> inspect([0|'bar'])
"[0, 98, 97, 114]"
iex> inspect([:foo,:bar])
"[:foo, :bar]"
"""
def inspect([], _opts), do: "[]"
def inspect(thing, Inspect.Opts[] = opts) do
cond do
:io_lib.printable_list(thing) ->
<< ?', Inspect.BitString.escape(String.from_char_list!(thing), ?') :: binary, ?' >>
keyword?(thing) && not opts.raw ->
surround_many("[", thing, "]", opts.limit, &keyword(&1, opts))
true ->
surround_many("[", thing, "]", opts.limit, &Kernel.inspect(&1, opts))
end
end
defp keyword({key, value}, opts) do
concat(
key_to_binary(key) <> ": ",
Kernel.inspect(value, opts)
)
end
defp key_to_binary(key) do
case Inspect.Atom.inspect(key) do
":" <> right -> right
other -> other
end
end
defp keyword?([{ key, _value } | rest]) when is_atom(key) do
case atom_to_list(key) do
'Elixir.' ++ _ -> false
_ -> keyword?(rest)
end
end
defp keyword?([]), do: true
defp keyword?(_other), do: false
end
defimpl Inspect, for: Tuple do
@doc """
Represents tuples. If the tuple represents a record,
it shows it nicely formatted using the access syntax.
## Examples
iex> inspect({1, 2, 3})
"{1, 2, 3}"
iex> inspect(ArgumentError.new)
"ArgumentError[message: \\\"argument error\\\"]"
"""
def inspect({}, _opts), do: "{}"
def inspect(tuple, opts) do
unless opts.raw do
record_inspect(tuple, opts)
end || surround_many("{", tuple_to_list(tuple), "}", opts.limit, &Kernel.inspect(&1, opts))
end
## Helpers
defp record_inspect(record, opts) do
[name|tail] = tuple_to_list(record)
if is_atom(name) && (fields = record_fields(name)) && (length(fields) == size(record) - 1) do
surround_record(name, fields, tail, opts)
end || surround_many("{", [name|tail], "}", opts.limit, &Kernel.inspect(&1, opts))
end
defp record_fields(name) do
case atom_to_binary(name) do
"Elixir." <> _ ->
try do
name.__record__(:fields)
rescue
_ -> nil
end
_ -> nil
end
end
defp surround_record(name, fields, tail, opts) do
concat(
Inspect.Atom.inspect(name, opts),
surround_many("[", zip_fields(fields, tail), "]", opts.limit, &keyword(&1, opts))
)
end
defp zip_fields([{ key, _ }|tk], [value|tv]) do
case atom_to_binary(key) do
"_" <> _ -> zip_fields(tk, tv)
key -> [{ key, value }|zip_fields(tk, tv)]
end
end
defp zip_fields([], []) do
[]
end
defp keyword({ k, v }, opts) do
concat(k <> ": ", Kernel.inspect(v, opts))
end
end
defimpl Inspect, for: Integer do
@doc """
Represents the integer as a string.
## Examples
iex> inspect(1)
"1"
"""
def inspect(thing, _opts) do
integer_to_binary(thing)
end
end
defimpl Inspect, for: Float do
@doc """
Floats are represented using the shortened, correctly rounded string
that converts to float when read back with `binary_to_float/1`. This
is done via the Erlang implementation of _Printing Floating-Point
Numbers Quickly and Accurately_ in Proceedings of the SIGPLAN '96
Conference on Programming Language Design and Implementation.
## Examples
iex> inspect(1.0)
"1.0"
"""
def inspect(thing, _opts) do
iolist_to_binary(:io_lib_format.fwrite_g(thing))
end
end
defimpl Inspect, for: Regex do
@doc %S"""
Represents the Regex using the `%r""` syntax.
## Examples
iex> inspect(%r/foo/m)
"%r\"foo\"m"
"""
def inspect(regex, opts) when size(regex) == 5 do
concat ["%r", Kernel.inspect(Regex.source(regex), opts), Regex.opts(regex)]
end
def inspect(other, opts) do
Kernel.inspect(other, opts.raw(true))
end
end
defimpl Inspect, for: Function do
def inspect(function, _opts) do
fun_info = :erlang.fun_info(function)
mod = fun_info[:module]
if fun_info[:type] == :external and fun_info[:env] == [] do
"&#{Inspect.Atom.inspect(mod)}.#{fun_info[:name]}/#{fun_info[:arity]}"
else
case atom_to_list(mod) do
'elixir_compiler_' ++ _ ->
if function_exported?(mod, :__RELATIVE__, 0) do
"#Function<#{uniq(fun_info)} in file:#{mod.__RELATIVE__}>"
else
default_inspect(mod, fun_info)
end
_ ->
default_inspect(mod, fun_info)
end
end
end
defp default_inspect(mod, fun_info) do
"#Function<#{uniq(fun_info)} in #{Inspect.Atom.inspect(mod)}.#{extract_name(fun_info[:name])}>"
end
defp extract_name(name) do
case :binary.split(atom_to_binary(name), "-", [:global]) do
["", name | _] -> name
_ -> name
end
end
defp uniq(fun_info) do
integer_to_binary(fun_info[:new_index]) <> "." <> integer_to_binary(fun_info[:uniq])
end
end
defimpl Inspect, for: PID do
def inspect(pid, _opts) do
"#PID" <> iolist_to_binary(:erlang.pid_to_list(pid))
end
end
defimpl Inspect, for: Port do
def inspect(port, _opts) do
iolist_to_binary :erlang.port_to_list(port)
end
end
defimpl Inspect, for: Reference do
def inspect(ref, _opts) do
'#Ref' ++ rest = :erlang.ref_to_list(ref)
"#Reference" <> iolist_to_binary(rest)
end
end
defimpl Inspect, for: HashDict do
def inspect(dict, opts) do
concat ["#HashDict<", Inspect.List.inspect(HashDict.to_list(dict), opts), ">"]
end
end
defimpl Inspect, for: HashSet do
def inspect(set, opts) do
concat ["#HashSet<", Inspect.List.inspect(HashSet.to_list(set), opts), ">"]
end
end
| 26.214 | 99 | 0.617227 |
089af3309b5a3aecdfe70d0c9aeddcfede6750f6 | 6,307 | exs | Elixir | test/single_product_web/controllers/user_auth_test.exs | manojsamanta/stripe-single-product | d0af1cede55ce6ac71100b9f4b5473919c16c884 | [
"MIT"
] | null | null | null | test/single_product_web/controllers/user_auth_test.exs | manojsamanta/stripe-single-product | d0af1cede55ce6ac71100b9f4b5473919c16c884 | [
"MIT"
] | null | null | null | test/single_product_web/controllers/user_auth_test.exs | manojsamanta/stripe-single-product | d0af1cede55ce6ac71100b9f4b5473919c16c884 | [
"MIT"
] | null | null | null | defmodule SingleProductWeb.UserAuthTest do
use SingleProductWeb.ConnCase, async: true
alias SingleProduct.Accounts
alias SingleProductWeb.UserAuth
import SingleProduct.AccountsFixtures
@remember_me_cookie "_single_product_web_user_remember_me"
setup %{conn: conn} do
conn =
conn
|> Map.replace!(:secret_key_base, SingleProductWeb.Endpoint.config(:secret_key_base))
|> init_test_session(%{})
%{user: user_fixture(), conn: conn}
end
describe "log_in_user/3" do
test "stores the user token in the session", %{conn: conn, user: user} do
conn = UserAuth.log_in_user(conn, user)
assert token = get_session(conn, :user_token)
assert get_session(conn, :live_socket_id) == "users_sessions:#{Base.url_encode64(token)}"
assert redirected_to(conn) == "/"
assert Accounts.get_user_by_session_token(token)
end
test "clears everything previously stored in the session", %{conn: conn, user: user} do
conn = conn |> put_session(:to_be_removed, "value") |> UserAuth.log_in_user(user)
refute get_session(conn, :to_be_removed)
end
test "redirects to the configured path", %{conn: conn, user: user} do
conn = conn |> put_session(:user_return_to, "/hello") |> UserAuth.log_in_user(user)
assert redirected_to(conn) == "/hello"
end
test "writes a cookie if remember_me is configured", %{conn: conn, user: user} do
conn = conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
assert get_session(conn, :user_token) == conn.cookies[@remember_me_cookie]
assert %{value: signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie]
assert signed_token != get_session(conn, :user_token)
assert max_age == 5_184_000
end
end
describe "logout_user/1" do
test "erases session and cookies", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
conn =
conn
|> put_session(:user_token, user_token)
|> put_req_cookie(@remember_me_cookie, user_token)
|> fetch_cookies()
|> UserAuth.log_out_user()
refute get_session(conn, :user_token)
refute conn.cookies[@remember_me_cookie]
assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie]
assert redirected_to(conn) == "/"
refute Accounts.get_user_by_session_token(user_token)
end
test "broadcasts to the given live_socket_id", %{conn: conn} do
live_socket_id = "users_sessions:abcdef-token"
SingleProductWeb.Endpoint.subscribe(live_socket_id)
conn
|> put_session(:live_socket_id, live_socket_id)
|> UserAuth.log_out_user()
assert_receive %Phoenix.Socket.Broadcast{
event: "disconnect",
topic: "users_sessions:abcdef-token"
}
end
test "works even if user is already logged out", %{conn: conn} do
conn = conn |> fetch_cookies() |> UserAuth.log_out_user()
refute get_session(conn, :user_token)
assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie]
assert redirected_to(conn) == "/"
end
end
describe "fetch_current_user/2" do
test "authenticates user from session", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
conn = conn |> put_session(:user_token, user_token) |> UserAuth.fetch_current_user([])
assert conn.assigns.current_user.id == user.id
end
test "authenticates user from cookies", %{conn: conn, user: user} do
logged_in_conn =
conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
user_token = logged_in_conn.cookies[@remember_me_cookie]
%{value: signed_token} = logged_in_conn.resp_cookies[@remember_me_cookie]
conn =
conn
|> put_req_cookie(@remember_me_cookie, signed_token)
|> UserAuth.fetch_current_user([])
assert get_session(conn, :user_token) == user_token
assert conn.assigns.current_user.id == user.id
end
test "does not authenticate if data is missing", %{conn: conn, user: user} do
_ = Accounts.generate_user_session_token(user)
conn = UserAuth.fetch_current_user(conn, [])
refute get_session(conn, :user_token)
refute conn.assigns.current_user
end
end
describe "redirect_if_user_is_authenticated/2" do
test "redirects if user is authenticated", %{conn: conn, user: user} do
conn = conn |> assign(:current_user, user) |> UserAuth.redirect_if_user_is_authenticated([])
assert conn.halted
assert redirected_to(conn) == "/"
end
test "does not redirect if user is not authenticated", %{conn: conn} do
conn = UserAuth.redirect_if_user_is_authenticated(conn, [])
refute conn.halted
refute conn.status
end
end
describe "require_authenticated_user/2" do
test "redirects if user is not authenticated", %{conn: conn} do
conn = conn |> fetch_flash() |> UserAuth.require_authenticated_user([])
assert conn.halted
assert redirected_to(conn) == Routes.user_session_path(conn, :new)
assert get_flash(conn, :error) == "You must log in to access this page."
end
test "stores the path to redirect to on GET", %{conn: conn} do
halted_conn =
%{conn | request_path: "/foo", query_string: ""}
|> fetch_flash()
|> UserAuth.require_authenticated_user([])
assert halted_conn.halted
assert get_session(halted_conn, :user_return_to) == "/foo"
halted_conn =
%{conn | request_path: "/foo", query_string: "bar=baz"}
|> fetch_flash()
|> UserAuth.require_authenticated_user([])
assert halted_conn.halted
assert get_session(halted_conn, :user_return_to) == "/foo?bar=baz"
halted_conn =
%{conn | request_path: "/foo?bar", method: "POST"}
|> fetch_flash()
|> UserAuth.require_authenticated_user([])
assert halted_conn.halted
refute get_session(halted_conn, :user_return_to)
end
test "does not redirect if user is authenticated", %{conn: conn, user: user} do
conn = conn |> assign(:current_user, user) |> UserAuth.require_authenticated_user([])
refute conn.halted
refute conn.status
end
end
end
| 36.247126 | 98 | 0.677184 |
089b35002584159c21ab269bd8c480292978f73a | 1,013 | ex | Elixir | lib/wabanex_web/router.ex | Sensacioles/ElixirNLWTogether2021 | 97f72b4fda4367693755dedabf7ee86b63978221 | [
"MIT"
] | null | null | null | lib/wabanex_web/router.ex | Sensacioles/ElixirNLWTogether2021 | 97f72b4fda4367693755dedabf7ee86b63978221 | [
"MIT"
] | null | null | null | lib/wabanex_web/router.ex | Sensacioles/ElixirNLWTogether2021 | 97f72b4fda4367693755dedabf7ee86b63978221 | [
"MIT"
] | null | null | null | defmodule WabanexWeb.Router do
use WabanexWeb, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/api", WabanexWeb do
pipe_through :api
get "/", IMCController, :index
end
scope "/api" do
pipe_through :api
forward "/graphql", Absinthe.Plug, schema: WabanexWeb.Schema
forward "/graphiql", Absinthe.Plug.GraphiQL, schema: WabanexWeb.Schema
end
# Enables LiveDashboard only for development
#
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
if Mix.env() in [:dev, :test] do
import Phoenix.LiveDashboard.Router
scope "/" do
pipe_through [:fetch_session, :protect_from_forgery]
live_dashboard "/dashboard", metrics: WabanexWeb.Telemetry
end
end
end
| 28.942857 | 74 | 0.71076 |
089b44cfb887c7118a86b7ddc08e356906f45186 | 200 | exs | Elixir | test/solvent_web/controllers/page_controller_test.exs | pbremer/solvent | 76e4ec6e1230f25f55069c5702dbe628f35f0798 | [
"MIT"
] | null | null | null | test/solvent_web/controllers/page_controller_test.exs | pbremer/solvent | 76e4ec6e1230f25f55069c5702dbe628f35f0798 | [
"MIT"
] | 1 | 2021-03-10T11:08:45.000Z | 2021-03-10T11:08:45.000Z | test/solvent_web/controllers/page_controller_test.exs | pbremer/solvent | 76e4ec6e1230f25f55069c5702dbe628f35f0798 | [
"MIT"
] | null | null | null | defmodule SolventWeb.PageControllerTest do
use SolventWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, "/")
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 22.222222 | 60 | 0.68 |
089b67a559a1300bbd1c03fd238e5dc1bb1e08a0 | 2,326 | ex | Elixir | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/encrypt_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/encrypt_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/cloud_kms/lib/google_api/cloud_kms/v1/model/encrypt_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.CloudKMS.V1.Model.EncryptRequest do
@moduledoc """
Request message for KeyManagementService.Encrypt.
## Attributes
* `additionalAuthenticatedData` (*type:* `String.t`, *default:* `nil`) - Optional data that, if specified, must also be provided during decryption
through DecryptRequest.additional_authenticated_data.
The maximum size depends on the key version's
protection_level. For
SOFTWARE keys, the AAD must be no larger than
64KiB. For HSM keys, the combined length of the
plaintext and additional_authenticated_data fields must be no larger than
8KiB.
* `plaintext` (*type:* `String.t`, *default:* `nil`) - Required. The data to encrypt. Must be no larger than 64KiB.
The maximum size depends on the key version's
protection_level. For
SOFTWARE keys, the plaintext must be no larger
than 64KiB. For HSM keys, the combined length of the
plaintext and additional_authenticated_data fields must be no larger than
8KiB.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:additionalAuthenticatedData => String.t(),
:plaintext => String.t()
}
field(:additionalAuthenticatedData)
field(:plaintext)
end
defimpl Poison.Decoder, for: GoogleApi.CloudKMS.V1.Model.EncryptRequest do
def decode(value, options) do
GoogleApi.CloudKMS.V1.Model.EncryptRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudKMS.V1.Model.EncryptRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.784615 | 150 | 0.733018 |
089b7306741203a56cffadae94c76c0a641a4889 | 1,662 | ex | Elixir | lib/data_processor_web/controllers/field_controller.ex | DylanGuedes/batch_processor | 2f3122a5f1a31557a39fac67aa62e297c39e8bf5 | [
"Apache-2.0"
] | null | null | null | lib/data_processor_web/controllers/field_controller.ex | DylanGuedes/batch_processor | 2f3122a5f1a31557a39fac67aa62e297c39e8bf5 | [
"Apache-2.0"
] | 3 | 2018-08-17T13:42:45.000Z | 2018-08-17T17:05:11.000Z | lib/data_processor_web/controllers/field_controller.ex | DylanGuedes/batch_processor | 2f3122a5f1a31557a39fac67aa62e297c39e8bf5 | [
"Apache-2.0"
] | null | null | null | defmodule DataProcessorWeb.FieldController do
use DataProcessorWeb, :controller
alias DataProcessor.Repo
alias DataProcessor.InterSCity
alias DataProcessor.InterSCity.JobTemplate
def update_field(conn, %{"job_template_id" => id, "table" => t, "command" => "drop", "key" => k}) do
template = InterSCity.get_template!(id)
{:ok, old_table} = Map.fetch(template.params, t)
new_table = Map.delete(old_table, k)
new_params = template.params |> Map.put(t, new_table)
JobTemplate.changeset(template, %{params: new_params}) |> Repo.update!
redirect(conn, to: job_template_path(conn, :show, template, current_tab: t))
end
def update_field(conn, %{"table" => t, "command" => "update", "key" => k, "value" => v, "job_template_id" => id}) do
template = InterSCity.get_template!(id)
{:ok, old_table} = Map.fetch(template.params, t)
new_table = Map.put(old_table, k, v)
new_params = template.params |> Map.put(t, new_table)
JobTemplate.changeset(template, %{params: new_params}) |> Repo.update!
redirect(conn, to: job_template_path(conn, :show, template, current_tab: t))
end
def update_field(conn, %{"table" => t, "command" => "update", "strategy" => s, "path" => p, "job_template_id" => id}) do
template = InterSCity.get_template!(id)
{:ok, old_table} = Map.fetch(template.params, t)
new_table = Map.put(old_table, "strategy", s) |> Map.put("path", p)
new_params = template.params |> Map.put(t, new_table)
JobTemplate.changeset(template, %{params: new_params}) |> Repo.update!
redirect(conn, to: job_template_path(conn, :show, template, current_tab: "publish_strategy"))
end
end
| 47.485714 | 122 | 0.685319 |
089b7dc79d9f6376484326b1980cc5cd0be59c94 | 3,622 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/change_log.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/change_log.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/change_log.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V33.Model.ChangeLog do
@moduledoc """
Describes a change that a user has made to a resource.
## Attributes
* `accountId` (*type:* `String.t`, *default:* `nil`) - Account ID of the modified object.
* `action` (*type:* `String.t`, *default:* `nil`) - Action which caused the change.
* `changeTime` (*type:* `DateTime.t`, *default:* `nil`) -
* `fieldName` (*type:* `String.t`, *default:* `nil`) - Field name of the object which changed.
* `id` (*type:* `String.t`, *default:* `nil`) - ID of this change log.
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#changeLog".
* `newValue` (*type:* `String.t`, *default:* `nil`) - New value of the object field.
* `objectId` (*type:* `String.t`, *default:* `nil`) - ID of the object of this change log. The object could be a campaign, placement, ad, or other type.
* `objectType` (*type:* `String.t`, *default:* `nil`) - Object type of the change log.
* `oldValue` (*type:* `String.t`, *default:* `nil`) - Old value of the object field.
* `subaccountId` (*type:* `String.t`, *default:* `nil`) - Subaccount ID of the modified object.
* `transactionId` (*type:* `String.t`, *default:* `nil`) - Transaction ID of this change log. When a single API call results in many changes, each change will have a separate ID in the change log but will share the same transactionId.
* `userProfileId` (*type:* `String.t`, *default:* `nil`) - ID of the user who modified the object.
* `userProfileName` (*type:* `String.t`, *default:* `nil`) - User profile name of the user who modified the object.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountId => String.t(),
:action => String.t(),
:changeTime => DateTime.t(),
:fieldName => String.t(),
:id => String.t(),
:kind => String.t(),
:newValue => String.t(),
:objectId => String.t(),
:objectType => String.t(),
:oldValue => String.t(),
:subaccountId => String.t(),
:transactionId => String.t(),
:userProfileId => String.t(),
:userProfileName => String.t()
}
field(:accountId)
field(:action)
field(:changeTime, as: DateTime)
field(:fieldName)
field(:id)
field(:kind)
field(:newValue)
field(:objectId)
field(:objectType)
field(:oldValue)
field(:subaccountId)
field(:transactionId)
field(:userProfileId)
field(:userProfileName)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.ChangeLog do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.ChangeLog.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.ChangeLog do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.116279 | 238 | 0.657372 |
089b81d64de74333c3628d44f1b9581318c2dc49 | 2,213 | exs | Elixir | mix.exs | basbz/ecto | db14ad1d44448f47bb35259447b7c453237ddbd7 | [
"Apache-2.0"
] | null | null | null | mix.exs | basbz/ecto | db14ad1d44448f47bb35259447b7c453237ddbd7 | [
"Apache-2.0"
] | null | null | null | mix.exs | basbz/ecto | db14ad1d44448f47bb35259447b7c453237ddbd7 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.MixProject do
use Mix.Project
@version "3.1.4"
def project do
[
app: :ecto,
version: @version,
elixir: "~> 1.5",
deps: deps(),
consolidate_protocols: Mix.env() != :test,
# Hex
description: "A toolkit for data mapping and language integrated query for Elixir",
package: package(),
# Docs
name: "Ecto",
docs: docs()
]
end
def application do
[
extra_applications: [:logger, :crypto],
mod: {Ecto.Application, []}
]
end
defp deps do
[
{:decimal, "~> 1.6"},
{:jason, "~> 1.0", optional: true},
{:ex_doc, "~> 0.19", only: :docs}
]
end
defp package do
[
maintainers: ["Eric Meadows-Jönsson", "José Valim", "James Fish", "Michał Muskała"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/elixir-ecto/ecto"},
files:
~w(.formatter.exs mix.exs README.md CHANGELOG.md lib) ++
~w(integration_test/cases integration_test/support)
]
end
defp docs do
[
main: "Ecto",
source_ref: "v#{@version}",
canonical: "http://hexdocs.pm/ecto",
logo: "guides/images/e.png",
source_url: "https://github.com/elixir-ecto/ecto",
extras: [
"guides/Getting Started.md",
"guides/Testing with Ecto.md"
],
groups_for_modules: [
# Ecto,
# Ecto.Changeset,
# Ecto.Multi,
# Ecto.Query,
# Ecto.Repo,
# Ecto.Schema,
# Ecto.Schema.Metadata,
# Ecto.Type,
# Ecto.UUID,
# Mix.Ecto,
"Query APIs": [
Ecto.Query.API,
Ecto.Query.WindowAPI,
Ecto.Queryable,
Ecto.SubQuery
],
"Adapter specification": [
Ecto.Adapter,
Ecto.Adapter.Queryable,
Ecto.Adapter.Schema,
Ecto.Adapter.Storage,
Ecto.Adapter.Transaction
],
"Association structs": [
Ecto.Association.BelongsTo,
Ecto.Association.Has,
Ecto.Association.HasThrough,
Ecto.Association.ManyToMany,
Ecto.Association.NotLoaded
]
]
]
end
end
| 22.814433 | 90 | 0.532309 |
089b8f531f75c01f76cc52f6630427d2350914c3 | 3,945 | exs | Elixir | test/live_sup_web/controllers/user_reset_password_controller_test.exs | livesup-dev/livesup | eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446 | [
"Apache-2.0",
"MIT"
] | null | null | null | test/live_sup_web/controllers/user_reset_password_controller_test.exs | livesup-dev/livesup | eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446 | [
"Apache-2.0",
"MIT"
] | 3 | 2022-02-23T15:51:48.000Z | 2022-03-14T22:52:43.000Z | test/live_sup_web/controllers/user_reset_password_controller_test.exs | livesup-dev/livesup | eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446 | [
"Apache-2.0",
"MIT"
] | null | null | null | defmodule LiveSupWeb.UserResetPasswordControllerTest do
use LiveSupWeb.ConnCase, async: true
alias LiveSup.Core.Accounts
alias LiveSup.Repo
import LiveSup.Test.AccountsFixtures
setup do
%{user: user_fixture()}
end
describe "GET /users/reset_password" do
@describetag :controllers
test "renders the reset password page", %{conn: conn} do
conn = get(conn, Routes.user_reset_password_path(conn, :new))
response = html_response(conn, 200)
assert response =~ "Forgot your password?</h1>"
end
end
describe "POST /users/reset_password" do
@describetag :skip
@tag :capture_log
test "sends a new reset password token", %{conn: conn, user: user} do
conn =
post(conn, Routes.user_reset_password_path(conn, :create), %{
"user" => %{"email" => user.email}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "reset_password"
end
test "does not send reset password token if email is invalid", %{conn: conn} do
conn =
post(conn, Routes.user_reset_password_path(conn, :create), %{
"user" => %{"email" => "unknown@example.com"}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
assert Repo.all(Accounts.UserToken) == []
end
end
describe "GET /users/reset_password/:token" do
@describetag :skip
setup %{user: user} do
token =
extract_user_token(fn url ->
Accounts.deliver_user_reset_password_instructions(user, url)
end)
%{token: token}
end
test "renders reset password", %{conn: conn, token: token} do
conn = get(conn, Routes.user_reset_password_path(conn, :edit, token))
assert html_response(conn, 200) =~ "Reset password</h3>"
end
test "does not render reset password with invalid token", %{conn: conn} do
conn = get(conn, Routes.user_reset_password_path(conn, :edit, "oops"))
assert redirected_to(conn) == "/"
assert get_flash(conn, :error) =~ "Reset password link is invalid or it has expired"
end
end
describe "PUT /users/reset_password/:token" do
@describetag :skip
setup %{user: user} do
token =
extract_user_token(fn url ->
Accounts.deliver_user_reset_password_instructions(user, url)
end)
%{token: token}
end
test "resets password once", %{conn: conn, user: user, token: token} do
conn =
put(conn, Routes.user_reset_password_path(conn, :update, token), %{
"user" => %{
"password" => "new valid password",
"password_confirmation" => "new valid password"
}
})
assert redirected_to(conn) == Routes.user_session_path(conn, :new)
refute get_session(conn, :user_token)
assert get_flash(conn, :info) =~ "Password reset successfully"
assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
end
test "does not reset password on invalid data", %{conn: conn, token: token} do
conn =
put(conn, Routes.user_reset_password_path(conn, :update, token), %{
"user" => %{
"password" => "too short",
"password_confirmation" => "does not match"
}
})
response = html_response(conn, 200)
assert response =~ "Reset password</h3>"
assert response =~ "should be at least 12 character(s)"
assert response =~ "does not match password"
end
test "does not reset password with invalid token", %{conn: conn} do
conn = put(conn, Routes.user_reset_password_path(conn, :update, "oops"))
assert redirected_to(conn) == "/"
assert get_flash(conn, :error) =~ "Reset password link is invalid or it has expired"
end
end
end
| 33.432203 | 91 | 0.635995 |
089ba5028bcb96fab4b128746125fe87dad5689b | 17,274 | ex | Elixir | lib/utils/keys.ex | aeternity/aepp-sdk-elixir | a001b0eb264665623c9b05de25a71d1f13990679 | [
"0BSD"
] | 19 | 2019-04-16T07:27:53.000Z | 2022-01-22T21:35:02.000Z | lib/utils/keys.ex | aeternity/aepp-sdk-elixir | a001b0eb264665623c9b05de25a71d1f13990679 | [
"0BSD"
] | 131 | 2019-04-05T13:01:37.000Z | 2020-07-09T14:53:34.000Z | lib/utils/keys.ex | aeternity/aepp-sdk-elixir | a001b0eb264665623c9b05de25a71d1f13990679 | [
"0BSD"
] | 5 | 2019-04-11T19:21:42.000Z | 2022-03-06T09:08:34.000Z | defmodule AeppSDK.Utils.Keys do
@moduledoc """
Key generation, handling, encoding and crypto.
"""
alias AeppSDK.Utils.Encoding
alias Argon2.Base, as: Argon2Base
@prefix_bits 24
@random_salt_bytes 16
@random_nonce_bytes 24
@default_hash_params %{
m_cost: 16,
parallelism: 1,
t_cost: 3,
format: :raw_hash,
argon2_type: 2
}
# 2^ 16 = 65_536, 2^18 = 262_144
@default_kdf_params %{
memlimit_kib: 65_536,
opslimit: 3,
salt: "",
parallelism: 1
}
@typedoc """
A base58c encoded public key.
"""
@type public_key :: Encoding.base58c()
@typedoc """
A hex encoded private key.
"""
@type secret_key :: Encoding.hex()
@type keypair :: %{public: public_key(), secret: secret_key()}
@typedoc """
An arbitrary binary message.
"""
@type message :: binary()
@type signature :: binary()
@typedoc """
An arbitrary string password.
"""
@type password :: String.t()
@doc """
Generate a Curve25519 keypair
## Example
iex> AeppSDK.Utils.Keys.generate_keypair()
%{
public: "ak_Q9DozPaq7fZ9WnB8SwNxuniaWwUmp1M7HsFTgCdJSsU2kKtC4",
secret: "227bdeedb4c3dd2b554ea6b448ac6788fbe66df1b4f87093a450bba748f296f5348bd07453735393e2ff8c03c65b4593f3bdd94f957a2e7cb314688b53441280"
}
"""
@spec generate_keypair :: keypair()
def generate_keypair do
%{public: binary_public_key, secret: binary_secret_key} = :enacl.sign_keypair()
%{
public: public_key_from_binary(binary_public_key),
secret: secret_key_from_binary(binary_secret_key)
}
end
@doc """
false
"""
def generate_peer_keypair do
%{public: peer_public_key, secret: peer_secret_key} = :enacl.sign_keypair()
public = :enacl.crypto_sign_ed25519_public_to_curve25519(peer_public_key)
secret = :enacl.crypto_sign_ed25519_secret_to_curve25519(peer_secret_key)
%{public: public, secret: secret}
end
@spec get_pubkey_from_secret_key(String.t()) :: String.t()
def get_pubkey_from_secret_key(secret_key) do
<<_::size(256), pubkey::size(256)>> = Base.decode16!(secret_key, case: :lower)
Encoding.prefix_encode_base58c("ak", :binary.encode_unsigned(pubkey))
end
@doc """
Create a new keystore
## Example
iex> secret = "227bdeedb4c3dd2b554ea6b448ac6788fbe66df1b4f87093a450bba748f296f5348bd07453735393e2ff8c03c65b4593f3bdd94f957a2e7cb314688b53441280"
iex> AeppSDK.Utils.Keys.new_keystore(secret, "1234")
:ok
"""
@spec new_keystore(String.t(), String.t(), list()) :: :ok | {:error, atom}
def new_keystore(secret_key, password, opts \\ []) do
%{year: year, month: month, day: day, hour: hour, minute: minute, second: second} =
DateTime.utc_now()
time = "#{year}-#{month}-#{day}-#{hour}-#{minute}-#{second}"
name = Keyword.get(opts, :name, time)
keystore = create_keystore(secret_key, password, name)
json = Poison.encode!(keystore)
{:ok, file} = File.open(name, [:read, :write])
IO.write(file, json)
File.close(file)
end
@doc """
Read the private key from the keystore
## Example:
iex> AeppSDK.Utils.Keys.read_keystore("2019-10-25-9-48-48", "1234")
"227bdeedb4c3dd2b554ea6b448ac6788fbe66df1b4f87093a450bba748f296f5348bd07453735393e2ff8c03c65b4593f3bdd94f957a2e7cb314688b53441280"
"""
@spec read_keystore(String.t(), String.t()) :: binary() | {:error, atom()}
def read_keystore(path, password) when is_binary(path) and is_binary(password) do
with {:ok, json_keystore} <- File.read(path),
{:ok, keystore} <- Poison.decode(json_keystore, keys: :atoms!),
params = process_params(keystore),
derived_key = derive_key_argon2(password, params.salt, params.kdf_params),
{:ok, secret} <-
decrypt(params.ciphertext, params.nonce, Base.decode16!(derived_key, case: :lower)) do
Base.encode16(secret, case: :lower)
else
{:error, _} = error ->
error
end
end
@doc """
Sign a binary message with the given private key
## Example
iex> message = "some message"
iex> secret_key = <<34, 123, 222, 237, 180, 195, 221, 43, 85, 78, 166, 180, 72, 172, 103, 136,251, 230, 109, 241, 180, 248, 112, 147, 164, 80, 187, 167, 72, 242, 150, 245,52, 139, 208, 116, 83, 115, 83, 147, 226, 255, 140, 3, 198, 91, 69, 147, 243,189, 217, 79, 149, 122, 46, 124, 179, 20, 104, 139, 83, 68, 18, 128>>
iex> AeppSDK.Utils.Keys.sign(message, secret_key)
<<94, 26, 208, 168, 230, 154, 158, 226, 188, 217, 155, 170, 157, 33, 100, 22,
247, 171, 91, 120, 249, 52, 147, 194, 188, 1, 14, 5, 15, 166, 232, 202, 97,
96, 32, 32, 227, 151, 158, 216, 22, 68, 219, 5, 169, 229, 117, 147, 179, 43,
172, 211, 243, 171, 234, 254, 210, 119, 105, 248, 154, 19, 202, 7>>
"""
@spec sign(binary(), binary()) :: signature()
def sign(message, secret_key), do: :enacl.sign_detached(message, secret_key)
@doc """
Prefixes a network ID string to a binary message and signs it with the given private key
## Example
iex> message = "some message"
iex> secret_key = <<34, 123, 222, 237, 180, 195, 221, 43, 85, 78, 166, 180, 72, 172, 103, 136,251, 230, 109, 241, 180, 248, 112, 147, 164, 80, 187, 167, 72, 242, 150, 245,52, 139, 208, 116, 83, 115, 83, 147, 226, 255, 140, 3, 198, 91, 69, 147, 243,189, 217, 79, 149, 122, 46, 124, 179, 20, 104, 139, 83, 68, 18, 128>>
iex> AeppSDK.Utils.Keys.sign(message, secret_key, "ae_uat")
<<15, 246, 136, 55, 63, 30, 144, 154, 249, 161, 243, 93, 52, 0, 218, 22, 43,
200, 145, 252, 247, 218, 197, 125, 177, 17, 60, 177, 212, 106, 249, 130, 42,
179, 233, 174, 116, 145, 154, 244, 80, 48, 142, 153, 170, 34, 199, 219, 248,
107, 115, 155, 254, 69, 37, 68, 68, 1, 174, 95, 102, 10, 6, 14>>
"""
@spec sign(binary(), binary(), String.t()) :: signature()
def sign(message, secret_key, network_id),
do: :enacl.sign_detached(network_id <> message, secret_key)
@doc """
Verify that a message has been signed by a private key corresponding to the given public key
## Example
iex> signature = <<94, 26, 208, 168, 230, 154, 158, 226, 188, 217, 155, 170, 157, 33, 100, 22, 247, 171, 91, 120, 249, 52, 147, 194, 188, 1, 14, 5, 15, 166, 232, 202, 97, 96, 32, 32, 227, 151, 158, 216, 22, 68, 219, 5, 169, 229, 117, 147, 179, 43, 172, 211, 243, 171, 234, 254, 210, 119, 105, 248, 154, 19, 202, 7>>
iex> message = "some message"
iex> public_key = <<52, 139, 208, 116, 83, 115, 83, 147, 226, 255, 140, 3, 198, 91, 69, 147, 243, 189, 217, 79, 149, 122, 46, 124, 179, 20, 104, 139, 83, 68, 18, 128>>
iex> AeppSDK.Utils.Keys.verify(signature, message, public_key)
{:ok, "some message"}
"""
@spec verify(message(), signature(), binary()) :: {:ok, message()} | {:error, atom()}
def verify(signature, message, public_key),
do: :enacl.sign_verify_detached(signature, message, public_key)
@doc """
Save a keypair at a given path with the specified file name. The keys are encrypted with the password and saved as separate files - `name` for the private and `{
name
}.pub` for the public key
## Example
iex> keypair = AeppSDK.Utils.Keys.generate_keypair()
iex> password = "some password"
iex> path = "./keys"
iex> name = "key"
iex> AeppSDK.Utils.Keys.save_keypair(keypair, password, path, name)
:ok
"""
@spec save_keypair(keypair(), password(), String.t(), String.t()) :: :ok | {:error, String.t()}
def save_keypair(%{public: public_key, secret: secret_key}, password, path, name) do
binary_public_key = public_key_to_binary(public_key)
binary_secret_key = secret_key_to_binary(secret_key)
public_key_path = Path.join(path, "#{name}.pub")
secret_key_path = Path.join(path, name)
case mkdir(path) do
:ok ->
case {File.write(public_key_path, encrypt_key(binary_public_key, password)),
File.write(secret_key_path, encrypt_key(binary_secret_key, password))} do
{:ok, :ok} ->
:ok
{{:error, public_key_reason}, {:error, secret_key_reason}} ->
{:error,
"Couldn't write public (#{Atom.to_string(public_key_reason)}) or private key (#{
Atom.to_string(secret_key_reason)
} in #{path})"}
{{:error, reason}, :ok} ->
{:error, "Couldn't write public key in #{path}: #{Atom.to_string(reason)}"}
{:ok, {:error, reason}} ->
{:error, "Couldn't write private key in #{path}: #{Atom.to_string(reason)}"}
end
{:error, reason} ->
{:error, "Couldn't create directory #{path}: #{Atom.to_string(reason)}"}
end
end
@doc """
Attempt to read a keypair from a given path with the specified file name. If found, the keys will be decrypted with the password
## Example
iex> password = "some password"
iex> path = "./keys"
iex> name = "key"
iex> AeppSDK.Utils.Keys.read_keypair(password, path, name)
{:ok,
%{
public: "ak_2vTCdFVAvgkYUDiVpydmByybqSYZHEB189QcfjmdcxRef2W2eb",
secret: "f9cebe874d90626bfcea1093e72f22e500a92e95052b88aaebd5d30346132cb1fd1096207d3e887091e3c11a953c0238be2f9d737e2076bf89866bb786bc0fbf"
}}
"""
@spec read_keypair(password(), String.t(), String.t()) ::
{:ok, keypair()} | {:error, String.t()}
def read_keypair(password, path, name) do
public_key_read = path |> Path.join("#{name}.pub") |> File.read()
secret_key_read = path |> Path.join("#{name}") |> File.read()
case {public_key_read, secret_key_read} do
{{:ok, encrypted_public_key}, {:ok, encrypted_secret_key}} ->
public_key = encrypted_public_key |> decrypt_key(password) |> public_key_from_binary()
secret_key = encrypted_secret_key |> decrypt_key(password) |> secret_key_from_binary()
{:ok, %{public: public_key, secret: secret_key}}
{{:error, public_key_reason}, {:error, secret_key_reason}} ->
{:error,
"Couldn't read public (reason: #{Atom.to_string(public_key_reason)}) or private key (reason: #{
Atom.to_string(secret_key_reason)
}) from #{path}"}
{{:error, reason}, {:ok, _}} ->
{:error, "Couldn't read public key from #{path}: #{Atom.to_string(reason)} "}
{{:ok, _}, {:error, reason}} ->
{:error, "Couldn't read private key from #{path}: #{Atom.to_string(reason)}"}
end
end
@doc """
Convert a base58check public key string to binary
## Example
iex> public_key = "ak_2vTCdFVAvgkYUDiVpydmByybqSYZHEB189QcfjmdcxRef2W2eb"
iex> AeppSDK.Utils.Keys.public_key_to_binary(public_key)
<<253, 16, 150, 32, 125, 62, 136, 112, 145, 227, 193, 26, 149, 60, 2, 56, 190, 47, 157, 115, 126, 32, 118, 191, 137, 134, 107, 183, 134, 188, 15, 191>>
```
"""
@spec public_key_to_binary(public_key()) :: binary()
def public_key_to_binary(public_key), do: Encoding.prefix_decode_base58c(public_key)
@doc """
Convert a base58check public key string to tuple of prefix and binary
## Example
iex> public_key = "ak_2vTCdFVAvgkYUDiVpydmByybqSYZHEB189QcfjmdcxRef2W2eb"
iex> AeppSDK.Utils.Keys.public_key_to_binary(public_key, :with_prefix)
{"ak_",
<<253, 16, 150, 32, 125, 62, 136, 112, 145, 227, 193, 26, 149, 60, 2, 56, 190,
47, 157, 115, 126, 32, 118, 191, 137, 134, 107, 183, 134, 188, 15, 191>>}
```
"""
@spec public_key_to_binary(public_key(), atom()) :: tuple()
def public_key_to_binary(<<prefix::@prefix_bits, _payload::binary>> = public_key, :with_prefix),
do: {<<prefix::@prefix_bits>>, Encoding.prefix_decode_base58c(public_key)}
@doc """
Convert a binary public key to a base58check string
## Example
iex> binary_public_key = <<253, 16, 150, 32, 125, 62, 136, 112, 145, 227, 193, 26, 149, 60, 2, 56, 190, 47, 157, 115, 126, 32, 118, 191, 137, 134, 107, 183, 134, 188, 15, 191>>
iex> AeppSDK.Utils.Keys.public_key_from_binary(binary_public_key)
"ak_2vTCdFVAvgkYUDiVpydmByybqSYZHEB189QcfjmdcxRef2W2eb"
"""
@spec public_key_from_binary(binary()) :: public_key()
def public_key_from_binary(binary_public_key),
do: Encoding.prefix_encode_base58c("ak", binary_public_key)
@doc """
Convert a hex string private key to binary
## Example
iex> secret_key = "f9cebe874d90626bfcea1093e72f22e500a92e95052b88aaebd5d30346132cb1fd1096207d3e887091e3c11a953c0238be2f9d737e2076bf89866bb786bc0fbf"
iex> AeppSDK.Utils.Keys.secret_key_to_binary(secret_key)
<<249, 206, 190, 135, 77, 144, 98, 107, 252, 234, 16, 147, 231, 47, 34, 229, 0,
169, 46, 149, 5, 43, 136, 170, 235, 213, 211, 3, 70, 19, 44, 177, 253, 16,
150, 32, 125, 62, 136, 112, 145, 227, 193, 26, 149, 60, 2, 56, 190, 47, 157,
115, 126, 32, 118, 191, 137, 134, 107, 183, 134, 188, 15, 191>>
"""
@spec secret_key_to_binary(secret_key()) :: binary()
def secret_key_to_binary(secret_key) do
Base.decode16!(secret_key, case: :lower)
end
@doc """
Convert a binary private key to a hex string
## Example
iex> binary_secret_key = <<249, 206, 190, 135, 77, 144, 98, 107, 252, 234, 16, 147, 231, 47, 34, 229, 0, 169, 46, 149, 5, 43, 136, 170, 235, 213, 211, 3, 70, 19, 44, 177, 253, 16, 150, 32, 125, 62, 136, 112, 145, 227, 193, 26, 149, 60, 2, 56, 190, 47, 157, 115, 126, 32, 118, 191, 137, 134, 107, 183, 134, 188, 15, 191>>
iex> AeppSDK.Utils.Keys.secret_key_from_binary(binary_secret_key)
"f9cebe874d90626bfcea1093e72f22e500a92e95052b88aaebd5d30346132cb1fd1096207d3e887091e3c11a953c0238be2f9d737e2076bf89866bb786bc0fbf"
"""
@spec secret_key_from_binary(binary()) :: secret_key()
def secret_key_from_binary(binary_secret_key) do
Base.encode16(binary_secret_key, case: :lower)
end
defp process_params(%{
crypto: %{
cipher_params: %{nonce: nonce},
ciphertext: ciphertext,
kdf: kdf,
kdf_params: %{
memlimit_kib: memlimit,
opslimit: opslimit,
parallelism: parallelism,
salt: salt
}
}
}) do
kdf_algorithm = process_param(kdf)
m_cost = memlimit |> :math.log2() |> round
t_cost = opslimit
decoded_salt = Base.decode16!(salt, case: :lower)
decoded_ciphertext = Base.decode16!(ciphertext, case: :lower)
decoded_nonce = Base.decode16!(nonce, case: :lower)
%{
kdf_params: %{
m_cost: m_cost,
t_cost: t_cost,
parallelism: parallelism,
argon2_type: kdf_algorithm
},
salt: decoded_salt,
ciphertext: decoded_ciphertext,
nonce: decoded_nonce
}
end
defp process_param("argon2d") do
0
end
defp process_param("argon2i") do
1
end
defp process_param("argon2id") do
2
end
defp encrypt(plaintext, nonce, derived_key) do
:enacl.secretbox(plaintext, nonce, derived_key)
end
defp decrypt(ciphertext, nonce, derived_key)
when is_binary(ciphertext) and byte_size(nonce) == 24 and byte_size(derived_key) == 32 do
:enacl.secretbox_open(ciphertext, nonce, derived_key)
end
defp decrypt(_, _, _) do
{:error, "#{__MODULE__}: Invalid data"}
end
defp create_keystore(secret_key, password, name)
when is_binary(secret_key) and is_binary(password) do
salt = :enacl.randombytes(@random_salt_bytes)
nonce = :enacl.randombytes(@random_nonce_bytes)
derived_key = derive_key_argon2(password, salt, @default_hash_params)
encrypted_key =
encrypt(secret_key_to_binary(secret_key), nonce, Base.decode16!(derived_key, case: :lower))
%{
public_key: get_pubkey_from_secret_key(secret_key),
crypto: %{
secret_type: "ed25519",
symmetric_alg: "xsalsa20-poly1305",
ciphertext: Base.encode16(encrypted_key, case: :lower),
cipher_params: %{
nonce: Base.encode16(nonce, case: :lower)
},
kdf: "argon2id",
kdf_params: %{@default_kdf_params | salt: Base.encode16(salt, case: :lower)}
},
id: UUID.uuid4(),
name: name,
version: 1
}
end
defp derive_key_argon2(
password,
salt,
%{
memlimit_kib: memlimit_kib,
opslimit: opslimit,
salt: salt,
parallelism: parallelism
}
) do
derive_key_argon2(password, salt, %{
m_cost: memlimit_kib |> :math.log2() |> round(),
parallelism: parallelism,
t_cost: opslimit
})
end
defp derive_key_argon2(password, salt, kdf_params) do
processed_kdf_params =
for kdf_param <- Map.keys(@default_hash_params), reduce: %{} do
acc ->
Map.put(
acc,
kdf_param,
Map.get(kdf_params, kdf_param, Map.get(@default_hash_params, kdf_param))
)
end
Argon2Base.hash_password(password, salt, Enum.into(processed_kdf_params, []))
end
defp mkdir(path) do
if File.exists?(path) do
:ok
else
File.mkdir(path)
end
end
defp encrypt_key(key, password), do: :crypto.block_encrypt(:aes_ecb, hash(password), key)
defp decrypt_key(encrypted, password),
do: :crypto.block_decrypt(:aes_ecb, hash(password), encrypted)
defp hash(binary), do: :crypto.hash(:sha256, binary)
end
| 37.38961 | 326 | 0.642411 |
089ba8b284ee354c3b0c7c3bb17d4599395072a8 | 2,404 | ex | Elixir | lib/oban/postgres_notifier.ex | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | lib/oban/postgres_notifier.ex | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | lib/oban/postgres_notifier.ex | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | defmodule Oban.PostgresNotifier do
@doc """
Postgres Listen/Notify based Notifier
## Caveats
The notifications system is built on PostgreSQL's `LISTEN/NOTIFY` functionality. Notifications
are only delivered **after a transaction completes** and are de-duplicated before publishing.
Typically, applications run Ecto in sandbox mode while testing, but sandbox mode wraps each test
in a separate transaction that's rolled back after the test completes. That means the
transaction is never committed, which prevents delivering any notifications.
To test using notifications you must run Ecto without sandbox mode enabled.
"""
@behaviour Oban.Notifier
use GenServer
alias Oban.{Config, Connection, Registry, Repo}
@mappings %{
gossip: "oban_gossip",
insert: "oban_insert",
signal: "oban_signal"
}
defmodule State do
@moduledoc false
@enforce_keys [:conf]
defstruct [:conf]
end
@impl Oban.Notifier
def start_link(opts) do
{name, opts} = Keyword.pop(opts, :name, __MODULE__)
GenServer.start_link(__MODULE__, opts, name: name)
end
@impl Oban.Notifier
def listen(server, channels) do
with %State{conf: conf} <- GenServer.call(server, :get_state) do
conf.name
|> Registry.via(Connection)
|> GenServer.call({:listen, to_full_channels(conf, channels)})
end
end
@impl Oban.Notifier
def unlisten(server, channels) do
with %State{conf: conf} <- GenServer.call(server, :get_state) do
conf.name
|> Registry.via(Connection)
|> GenServer.call({:unlisten, to_full_channels(conf, channels)})
end
end
@impl Oban.Notifier
def notify(server, channel, payload) do
with %State{conf: conf} <- GenServer.call(server, :get_state) do
full_channel = Map.fetch!(@mappings, channel)
Repo.query(
conf,
"SELECT pg_notify($1, payload) FROM json_array_elements_text($2::json) AS payload",
["#{conf.prefix}.#{full_channel}", payload]
)
:ok
end
end
@impl GenServer
def init(opts) do
{:ok, struct!(State, opts)}
end
@impl GenServer
def handle_call(:get_state, _from, %State{} = state) do
{:reply, state, state}
end
# Helpers
defp to_full_channels(%Config{prefix: prefix}, channels) do
@mappings
|> Map.take(channels)
|> Map.values()
|> Enum.map(&Enum.join([prefix, &1], "."))
end
end
| 25.574468 | 98 | 0.680116 |
089bc8d40c975250aa16749a98f9a386886f0491 | 9,019 | ex | Elixir | lib/absinthe/pipeline.ex | maartenvanvliet/absinthe | ebe820717200f53756e225b3dffbfefe924a94d3 | [
"MIT"
] | null | null | null | lib/absinthe/pipeline.ex | maartenvanvliet/absinthe | ebe820717200f53756e225b3dffbfefe924a94d3 | [
"MIT"
] | null | null | null | lib/absinthe/pipeline.ex | maartenvanvliet/absinthe | ebe820717200f53756e225b3dffbfefe924a94d3 | [
"MIT"
] | null | null | null | defmodule Absinthe.Pipeline do
@moduledoc """
Execute a pipeline of phases.
A pipeline is merely a list of phases. This module contains functions for building,
modifying, and executing pipelines of phases.
"""
alias Absinthe.Phase
require Logger
@type data_t :: any
@type phase_config_t :: Phase.t() | {Phase.t(), Keyword.t()}
@type t :: [phase_config_t | [phase_config_t]]
@spec run(data_t, t) :: {:ok, data_t, [Phase.t()]} | {:error, String.t(), [Phase.t()]}
def run(input, pipeline) do
pipeline
|> List.flatten()
|> run_phase(input)
end
@defaults [
adapter: Absinthe.Adapter.LanguageConventions,
operation_name: nil,
variables: %{},
context: %{},
root_value: %{},
validation_result_phase: Phase.Document.Validation.Result,
result_phase: Phase.Document.Result,
jump_phases: true
]
def options(overrides \\ []) do
Keyword.merge(@defaults, overrides)
end
@spec for_document(Absinthe.Schema.t()) :: t
@spec for_document(Absinthe.Schema.t(), Keyword.t()) :: t
def for_document(schema, options \\ []) do
options = options(Keyword.put(options, :schema, schema))
[
# Parse Document
{Phase.Parse, options},
# Convert to Blueprint
{Phase.Blueprint, options},
# Find Current Operation (if any)
{Phase.Document.Validation.ProvidedAnOperation, options},
{Phase.Document.CurrentOperation, options},
# Mark Fragment/Variable Usage
Phase.Document.Uses,
# Validate Document Structure
{Phase.Document.Validation.NoFragmentCycles, options},
Phase.Document.Validation.LoneAnonymousOperation,
Phase.Document.Validation.SelectedCurrentOperation,
Phase.Document.Validation.KnownFragmentNames,
Phase.Document.Validation.NoUndefinedVariables,
Phase.Document.Validation.NoUnusedVariables,
# TODO: uncomment in 1.5
# Phase.Document.Validation.NoUnusedFragments
Phase.Document.Validation.UniqueFragmentNames,
Phase.Document.Validation.UniqueOperationNames,
Phase.Document.Validation.UniqueVariableNames,
# Apply Input
{Phase.Document.Context, options},
{Phase.Document.Variables, options},
Phase.Document.Validation.ProvidedNonNullVariables,
Phase.Document.Arguments.Normalize,
# Map to Schema
{Phase.Schema, options},
# Ensure Types
Phase.Validation.KnownTypeNames,
# Process Arguments
Phase.Document.Arguments.CoerceEnums,
Phase.Document.Arguments.CoerceLists,
{Phase.Document.Arguments.Parse, options},
Phase.Document.MissingVariables,
Phase.Document.MissingLiterals,
Phase.Document.Arguments.FlagInvalid,
# Validate Full Document
Phase.Validation.KnownDirectives,
Phase.Document.Validation.ScalarLeafs,
Phase.Document.Validation.VariablesAreInputTypes,
Phase.Document.Validation.ArgumentsOfCorrectType,
Phase.Document.Validation.KnownArgumentNames,
Phase.Document.Validation.ProvidedNonNullArguments,
Phase.Document.Validation.UniqueArgumentNames,
Phase.Document.Validation.UniqueInputFieldNames,
Phase.Document.Validation.FieldsOnCorrectType,
Phase.Document.Validation.OnlyOneSubscription,
# Check Validation
{Phase.Document.Validation.Result, options},
# Prepare for Execution
Phase.Document.Arguments.Data,
# Apply Directives
Phase.Document.Directives,
# Analyse Complexity
{Phase.Document.Complexity.Analysis, options},
{Phase.Document.Complexity.Result, options},
# Execution
{Phase.Subscription.SubscribeSelf, options},
{Phase.Document.Execution.Resolution, options},
# Format Result
Phase.Document.Result
]
end
@defaults [
adapter: Absinthe.Adapter.LanguageConventions
]
@spec for_schema(nil | Absinthe.Schema.t()) :: t
@spec for_schema(nil | Absinthe.Schema.t(), Keyword.t()) :: t
def for_schema(prototype_schema, options \\ []) do
options =
@defaults
|> Keyword.merge(Keyword.put(options, :schema, prototype_schema))
[
Phase.Parse,
Phase.Blueprint,
{Phase.Schema, options},
Phase.Validation.KnownTypeNames,
Phase.Validation.KnownDirectives
]
end
@doc """
Return the part of a pipeline before a specific phase.
"""
@spec before(t, atom) :: t
def before(pipeline, phase) do
result =
List.flatten(pipeline)
|> Enum.take_while(&(!match_phase?(phase, &1)))
case result do
^pipeline ->
raise RuntimeError, "Could not find phase #{phase}"
_ ->
result
end
end
@doc """
Return the part of a pipeline after (and including) a specific phase.
"""
@spec from(t, atom) :: t
def from(pipeline, phase) do
result =
List.flatten(pipeline)
|> Enum.drop_while(&(!match_phase?(phase, &1)))
case result do
[] ->
raise RuntimeError, "Could not find phase #{phase}"
_ ->
result
end
end
@doc """
Replace a phase in a pipeline with another, supporting reusing the same
options.
## Examples
Replace a simple phase (without options):
iex> Pipeline.replace([A, B, C], B, X)
[A, X, C]
Replace a phase with options, retaining them:
iex> Pipeline.replace([A, {B, [name: "Thing"]}, C], B, X)
[A, {X, [name: "Thing"]}, C]
Replace a phase with options, overriding them:
iex> Pipeline.replace([A, {B, [name: "Thing"]}, C], B, {X, [name: "Nope"]})
[A, {X, [name: "Nope"]}, C]
"""
@spec replace(t, Phase.t(), phase_config_t) :: t
def replace(pipeline, phase, replacement) do
Enum.map(pipeline, fn candidate ->
case match_phase?(phase, candidate) do
true ->
case phase_invocation(candidate) do
{_, []} ->
replacement
{_, opts} ->
case is_atom(replacement) do
true ->
{replacement, opts}
false ->
replacement
end
end
false ->
candidate
end
end)
end
# Whether a phase configuration is for a given phase
@spec match_phase?(Phase.t(), phase_config_t) :: boolean
defp match_phase?(phase, phase), do: true
defp match_phase?(phase, {phase, _}), do: true
defp match_phase?(_, _), do: false
@doc """
Return the part of a pipeline up to and including a specific phase.
"""
@spec upto(t, atom) :: t
def upto(pipeline, phase) do
beginning = before(pipeline, phase)
item = get_in(pipeline, [Access.at(length(beginning))])
beginning ++ [item]
end
@spec without(t, Phase.t()) :: t
def without(pipeline, phase) do
pipeline
|> Enum.filter(&(not match_phase?(phase, &1)))
end
@spec insert_before(t, Phase.t(), phase_config_t | [phase_config_t]) :: t
def insert_before(pipeline, phase, additional) do
beginning = before(pipeline, phase)
beginning ++ List.wrap(additional) ++ (pipeline -- beginning)
end
@spec insert_after(t, Phase.t(), phase_config_t | [phase_config_t]) :: t
def insert_after(pipeline, phase, additional) do
beginning = upto(pipeline, phase)
beginning ++ List.wrap(additional) ++ (pipeline -- beginning)
end
@spec reject(t, Regex.t() | (Module.t() -> boolean)) :: t
def reject(pipeline, %Regex{} = pattern) do
reject(pipeline, fn phase ->
Regex.match?(pattern, Atom.to_string(phase))
end)
end
def reject(pipeline, fun) do
Enum.reject(pipeline, fn
{phase, _} -> fun.(phase)
phase -> fun.(phase)
end)
end
@spec run_phase(t, data_t, [Phase.t()]) ::
{:ok, data_t, [Phase.t()]} | {:error, String.t(), [Phase.t()]}
def run_phase(pipeline, input, done \\ [])
def run_phase([], input, done) do
{:ok, input, done}
end
def run_phase([phase_config | todo], input, done) do
{phase, options} = phase_invocation(phase_config)
case phase.run(input, options) do
{:ok, result} ->
run_phase(todo, result, [phase | done])
{:jump, result, destination_phase} when is_atom(destination_phase) ->
run_phase(from(todo, destination_phase), result, [phase | done])
{:insert, result, extra_pipeline} ->
run_phase(List.wrap(extra_pipeline) ++ todo, result, [phase | done])
{:swap, result, target, replacements} ->
todo
|> replace(target, replacements)
|> run_phase(result, [phase | done])
{:replace, result, final_pipeline} ->
run_phase(List.wrap(final_pipeline), result, [phase | done])
{:error, message} ->
{:error, message, [phase | done]}
_ ->
{:error, "Last phase did not return a valid result tuple.", [phase | done]}
end
end
@spec phase_invocation(phase_config_t) :: {Phase.t(), list}
defp phase_invocation({phase, options}) when is_list(options) do
{phase, options}
end
defp phase_invocation(phase) do
{phase, []}
end
end
| 29.187702 | 88 | 0.642976 |
089bea24e4297fbbe75b20cf7a863139019264a0 | 712 | exs | Elixir | test/test_helper.exs | nikneroz/mssql_ecto | d010b6c9c9041756353fc8184fa7e6368103cfac | [
"Apache-2.0"
] | null | null | null | test/test_helper.exs | nikneroz/mssql_ecto | d010b6c9c9041756353fc8184fa7e6368103cfac | [
"Apache-2.0"
] | null | null | null | test/test_helper.exs | nikneroz/mssql_ecto | d010b6c9c9041756353fc8184fa7e6368103cfac | [
"Apache-2.0"
] | null | null | null | Code.require_file("../deps/ecto/integration_test/support/types.exs", __DIR__)
ExUnit.start()
# ExUnit.configure(exclude: [skip: true])
defmodule MssqlEcto.Case do
use ExUnit.CaseTemplate
using _ do
quote do
import MssqlEcto.Case
alias MssqlEcto.Connection, as: SQL
end
end
def normalize(query, operation \\ :all, counter \\ 0) do
{query, _params, _key} =
Ecto.Query.Planner.prepare(query, operation, MssqlEcto, counter)
case Ecto.Query.Planner.normalize(query, operation, MssqlEcto, counter) do
# Ecto v2.2 onwards
{%Ecto.Query{} = query, _} ->
query
# Ecto v2.1 and previous
%Ecto.Query{} = query ->
query
end
end
end
| 23.733333 | 78 | 0.654494 |
089bfc3ba89f8a37d395bc2a1a697091aa7c72c2 | 29,090 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/global_network_endpoint_groups.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/global_network_endpoint_groups.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/global_network_endpoint_groups.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Api.GlobalNetworkEndpointGroups do
@moduledoc """
API calls for all endpoints tagged `GlobalNetworkEndpointGroups`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Attach a network endpoint to the specified network endpoint group.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `network_endpoint_group` (*type:* `String.t`) - The name of the network endpoint group where you are attaching network endpoints to. It should comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.GlobalNetworkEndpointGroupsAttachEndpointsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_attach_network_endpoints(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_attach_network_endpoints(
connection,
project,
network_endpoint_group,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/projects/{project}/global/networkEndpointGroups/{networkEndpointGroup}/attachNetworkEndpoints",
%{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"networkEndpointGroup" => URI.encode(network_endpoint_group, &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.Compute.V1.Model.Operation{}])
end
@doc """
Deletes the specified network endpoint group.Note that the NEG cannot be deleted if there are backend services referencing it.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `network_endpoint_group` (*type:* `String.t`) - The name of the network endpoint group to delete. It should comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_delete(
connection,
project,
network_endpoint_group,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/projects/{project}/global/networkEndpointGroups/{networkEndpointGroup}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"networkEndpointGroup" =>
URI.encode(network_endpoint_group, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Detach the network endpoint from the specified network endpoint group.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `network_endpoint_group` (*type:* `String.t`) - The name of the network endpoint group where you are removing network endpoints. It should comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.GlobalNetworkEndpointGroupsDetachEndpointsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_detach_network_endpoints(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_detach_network_endpoints(
connection,
project,
network_endpoint_group,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/projects/{project}/global/networkEndpointGroups/{networkEndpointGroup}/detachNetworkEndpoints",
%{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"networkEndpointGroup" => URI.encode(network_endpoint_group, &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.Compute.V1.Model.Operation{}])
end
@doc """
Returns the specified network endpoint group. Gets a list of available network endpoint groups by making a list() request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `network_endpoint_group` (*type:* `String.t`) - The name of the network endpoint group. It should comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.NetworkEndpointGroup{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.NetworkEndpointGroup.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_get(
connection,
project,
network_endpoint_group,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/projects/{project}/global/networkEndpointGroups/{networkEndpointGroup}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"networkEndpointGroup" =>
URI.encode(network_endpoint_group, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.NetworkEndpointGroup{}])
end
@doc """
Creates a network endpoint group in the specified project using the parameters that are included in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.NetworkEndpointGroup.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_insert(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_insert(
connection,
project,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/projects/{project}/global/networkEndpointGroups", %{
"project" => URI.encode(project, &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.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves the list of network endpoint groups that are located in the specified project.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by `name` or `creationTimestamp desc` is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
* `:returnPartialSuccess` (*type:* `boolean()`) - Opt-in for partial success behavior which provides partial results in case of failure. The default value is false.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.NetworkEndpointGroupList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.NetworkEndpointGroupList.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_list(
connection,
project,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:returnPartialSuccess => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/projects/{project}/global/networkEndpointGroups", %{
"project" => URI.encode(project, &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.Compute.V1.Model.NetworkEndpointGroupList{}])
end
@doc """
Lists the network endpoints in the specified network endpoint group.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `network_endpoint_group` (*type:* `String.t`) - The name of the network endpoint group from which you want to generate a list of included network endpoints. It should comply with RFC1035.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`.
For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`.
You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ```
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by `name` or `creationTimestamp desc` is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results.
* `:returnPartialSuccess` (*type:* `boolean()`) - Opt-in for partial success behavior which provides partial results in case of failure. The default value is false.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.NetworkEndpointGroupsListNetworkEndpoints{}}` on success
* `{:error, info}` on failure
"""
@spec compute_global_network_endpoint_groups_list_network_endpoints(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.NetworkEndpointGroupsListNetworkEndpoints.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def compute_global_network_endpoint_groups_list_network_endpoints(
connection,
project,
network_endpoint_group,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:returnPartialSuccess => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/projects/{project}/global/networkEndpointGroups/{networkEndpointGroup}/listNetworkEndpoints",
%{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"networkEndpointGroup" => URI.encode(network_endpoint_group, &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.Compute.V1.Model.NetworkEndpointGroupsListNetworkEndpoints{}]
)
end
end
| 51.486726 | 434 | 0.657236 |
089c0fde3e4414b77f45b57896f65e4410501a73 | 70 | exs | Elixir | apps/bbq_ui/test/views/page_view_test.exs | easco/ex_bbq | d736204bb124ea256907629f5025c3abaf08c0bb | [
"BSD-3-Clause"
] | 2 | 2016-09-22T13:32:35.000Z | 2017-02-17T20:26:50.000Z | apps/bbq_ui/test/views/page_view_test.exs | easco/ex_bbq | d736204bb124ea256907629f5025c3abaf08c0bb | [
"BSD-3-Clause"
] | null | null | null | apps/bbq_ui/test/views/page_view_test.exs | easco/ex_bbq | d736204bb124ea256907629f5025c3abaf08c0bb | [
"BSD-3-Clause"
] | null | null | null | defmodule BbqUi.PageViewTest do
use BbqUi.ConnCase, async: true
end
| 17.5 | 33 | 0.8 |
089c13b4b0b8bc4600e0350b2f0747a39bd2f3de | 351 | exs | Elixir | aoc21/test/day00_test.exs | sastels/advent-of-code-2021 | 7cefbb8bf08cce2c4a4e9517ecbaf49459a8671a | [
"MIT"
] | null | null | null | aoc21/test/day00_test.exs | sastels/advent-of-code-2021 | 7cefbb8bf08cce2c4a4e9517ecbaf49459a8671a | [
"MIT"
] | null | null | null | aoc21/test/day00_test.exs | sastels/advent-of-code-2021 | 7cefbb8bf08cce2c4a4e9517ecbaf49459a8671a | [
"MIT"
] | null | null | null | defmodule Day00Test do
use ExUnit.Case
# import Day00
setup do
{:ok,
contents: """
hi there
"""}
end
# @tag :skip
# test "part 1", %{contents: contents} do
# assert contents |> part_1() == nil
# end
# @tag :skip
# test "part 2", %{contents: contents} do
# assert contents |> part_2() == nil
# end
end
| 15.954545 | 43 | 0.552707 |
089c14506f1df76aa9fedce07e51e2ff9face093 | 303 | ex | Elixir | test/comb/math_test.ex | tallakt/comb | e6660924891d88d798494ab0c5adeefb29fae8b8 | [
"Apache-2.0"
] | 38 | 2016-02-24T09:19:23.000Z | 2022-02-15T14:33:35.000Z | test/comb/math_test.ex | tallakt/permutations | e6660924891d88d798494ab0c5adeefb29fae8b8 | [
"Apache-2.0"
] | 1 | 2018-01-07T11:42:07.000Z | 2018-01-07T11:42:59.000Z | test/comb/math_test.ex | tallakt/permutations | e6660924891d88d798494ab0c5adeefb29fae8b8 | [
"Apache-2.0"
] | 10 | 2015-11-09T09:52:55.000Z | 2020-10-19T05:07:00.000Z | defmodule Comb.MathTest do
use ExUnit.Case, async: true
doctest Comb.Math, import: true
import Comb.Math
test "first factorial numbers" do
assert (for n <- 0..4, do: factorial(n)) ==
[1, 1, 2, 6, 24]
end
test "factorial 31" do
8222838654177922817725562880000000
end
end
| 16.833333 | 47 | 0.663366 |
089c158b6c8aa0180282eca468eafba327653110 | 854 | exs | Elixir | test/assertions/enum/have_max_by_test.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | test/assertions/enum/have_max_by_test.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | test/assertions/enum/have_max_by_test.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | defmodule Enum.HaveMaxByTest do
use ExUnit.Case, async: true
defmodule SomeSpec do
use ESpec
let :range, do: 1..3
let :func, do: fn el -> 10 / el end
context "Success" do
it do: expect(range()).to(have_max_by(func(), 1))
it do: expect(range()).to_not(have_max_by(func(), 3))
end
context "Error" do
it do: expect(range()).to_not(have_max_by(func(), 1))
it do: expect(range()).to(have_max_by(func(), 2))
end
end
setup_all do
examples = ESpec.SuiteRunner.run_examples(SomeSpec.examples(), true)
{:ok, success: Enum.slice(examples, 0, 1), errors: Enum.slice(examples, 2, 3)}
end
test "Success", context do
Enum.each(context[:success], &assert(&1.status == :success))
end
test "Errors", context do
Enum.each(context[:errors], &assert(&1.status == :failure))
end
end
| 25.117647 | 82 | 0.63466 |
089c3b1d3f33676ba88373c0dabb78c5cf50d6c3 | 1,556 | ex | Elixir | implementations/elixir/ockam/ockam/lib/ockam/transport/portal/inlet_listener.ex | twittner/ockam | 96eadf99da42f7c35539c6e29010a657c579ccba | [
"Apache-2.0"
] | null | null | null | implementations/elixir/ockam/ockam/lib/ockam/transport/portal/inlet_listener.ex | twittner/ockam | 96eadf99da42f7c35539c6e29010a657c579ccba | [
"Apache-2.0"
] | null | null | null | implementations/elixir/ockam/ockam/lib/ockam/transport/portal/inlet_listener.ex | twittner/ockam | 96eadf99da42f7c35539c6e29010a657c579ccba | [
"Apache-2.0"
] | null | null | null | defmodule Ockam.Transport.Portal.InletListener do
@moduledoc """
GenServer implementing the Inlet TCP listener
It's a GenServer just to make it simple to be added
to a supervision tree.
"""
use GenServer
require Logger
@typedoc """
TCP listener options
- ip: t::inet.ip_address() - IP address to listen on
- port: t:integer() - port to listen on
- peer_route: route to outlet
"""
@type options :: Keyword.t()
def start_link(options) do
GenServer.start_link(__MODULE__, options)
end
@impl true
def init(options) do
ip = Keyword.get_lazy(options, :ip, &default_ip/0)
port = Keyword.get_lazy(options, :port, &default_port/0)
peer_route = options[:peer_route]
Logger.info("Starting inlet listener on #{inspect(ip)}:#{port}. Peer: #{inspect(peer_route)}")
{:ok, lsocket} =
:gen_tcp.listen(port, [:binary, {:active, false}, {:ip, ip}, {:reuseaddr, true}])
spawn_link(fn -> accept(lsocket, peer_route) end)
{:ok, %{listen_socket: lsocket, peer_route: peer_route}}
end
defp accept(lsocket, peer_route) do
{:ok, socket} = :gen_tcp.accept(lsocket)
{:ok, worker} = Ockam.Transport.Portal.InletWorker.create(peer_route: peer_route)
case Ockam.Node.whereis(worker) do
nil ->
raise "Worker #{inspect(worker)} not found"
pid ->
:ok = :gen_tcp.controlling_process(socket, pid)
GenServer.cast(pid, {:takeover, socket})
accept(lsocket, peer_route)
end
end
def default_ip, do: {0, 0, 0, 0}
def default_port, do: 3000
end
| 28.290909 | 98 | 0.664524 |
089c4779f0c138ac2b240e78c3f76566bf77cc21 | 4,235 | ex | Elixir | apps/site/lib/site_web/controllers/event_controller.ex | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 42 | 2019-05-29T16:05:30.000Z | 2021-08-09T16:03:37.000Z | apps/site/lib/site_web/controllers/event_controller.ex | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 872 | 2019-05-29T17:55:50.000Z | 2022-03-30T09:28:43.000Z | apps/site/lib/site_web/controllers/event_controller.ex | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 12 | 2019-07-01T18:33:21.000Z | 2022-03-10T02:13:57.000Z | defmodule SiteWeb.EventController do
@moduledoc "Handles fetching event data for event views"
use SiteWeb, :controller
alias CMS.{API, Page, Repo}
alias CMS.Page.Event
alias Plug.Conn
alias Site.IcalendarGenerator
alias SiteWeb.ControllerHelpers
alias SiteWeb.EventView
plug(SiteWeb.Plugs.YearMonth)
plug(:assign_events)
def index(conn, %{"calendar" => "true"}) do
render_events_hub_page(conn, true)
end
def index(conn, _params) do
render_events_hub_page(conn, false)
end
defp render_events_hub_page(conn, is_calendar_view_mode) do
conn
|> assign(:calendar_view, is_calendar_view_mode)
|> assign(:breadcrumbs, [Breadcrumb.build("Events")])
|> await_assign_all_default(__MODULE__)
|> render("index.html", conn: conn)
end
defp assign_events(conn, _opts) do
events_by_year =
for year <- year_options(conn), into: %{} do
{year, Repo.events_for_year(year)}
end
years_for_selection =
events_by_year
|> Enum.filter(fn {_year, events_for_that_year} -> Enum.count(events_for_that_year) > 0 end)
|> Enum.map(fn {year, _events_for_that_year} -> year end)
conn
|> assign(:years_for_selection, years_for_selection)
|> async_assign_default(
:events,
fn ->
Map.get(events_by_year, conn.assigns.year)
end,
[]
)
end
def show(conn, %{"path_params" => path}) do
case List.last(path) do
"icalendar" ->
redirect(conn, to: Path.join(["/events", "icalendar" | Enum.slice(path, 0..-2)]))
_ ->
conn.request_path
|> Repo.get_page(conn.query_params)
|> do_show(conn)
end
end
defp do_show(%Event{} = event, conn) do
show_event(conn, event)
end
defp do_show({:error, {:redirect, status, opts}}, conn) do
conn
|> put_status(status)
|> redirect(opts)
end
defp do_show(_404_or_mismatch, conn) do
render_404(conn)
end
@spec show_event(Conn.t(), Event.t()) :: Conn.t()
def show_event(conn, %Event{start_time: start_time} = event) do
conn
|> ControllerHelpers.unavailable_after_one_year(start_time)
|> assign_breadcrumbs(event)
|> put_view(EventView)
|> render("show.html", event: event)
end
@spec assign_breadcrumbs(Conn.t(), Event.t()) :: Conn.t()
defp assign_breadcrumbs(conn, event) do
conn
|> assign(:breadcrumbs, [
Breadcrumb.build("Events", event_path(conn, :index)),
Breadcrumb.build(event.title)
])
end
@spec icalendar(Conn.t(), map) :: Conn.t()
def icalendar(%{request_path: path} = conn, _) do
path
|> String.replace("/icalendar", "")
|> Repo.get_page(conn.query_params)
|> do_icalendar(conn)
end
@spec do_icalendar(Page.t() | {:error, API.error()}, Conn.t()) :: Conn.t()
defp do_icalendar(%Event{} = event, conn) do
conn
|> put_resp_content_type("text/calendar")
|> put_resp_header("content-disposition", "attachment; filename=#{filename(event.title)}.ics")
|> send_resp(200, IcalendarGenerator.to_ical(conn, event))
end
defp do_icalendar({:error, {:redirect, _status, [to: path]}}, conn) do
path
|> Repo.get_page(conn.query_params)
|> do_icalendar(conn)
end
defp do_icalendar(_, conn) do
render_404(conn)
end
@spec filename(String.t()) :: String.t()
defp filename(title) do
title
|> String.downcase()
|> String.replace(" ", "_")
|> decode_ampersand_html_entity
end
@spec decode_ampersand_html_entity(String.t()) :: String.t()
defp decode_ampersand_html_entity(string) do
String.replace(string, "&", "&")
end
@doc "Returns a list of years with which we can filter events.
Defaults to the current datetime if no assigns
"
@spec year_options(Plug.Conn.t()) :: %Range{:first => Calendar.year(), :last => Calendar.year()}
def year_options(%{assigns: %{date: %{year: year}}}) when is_integer(year) do
do_year_options(year)
end
def year_options(_) do
%{year: year} = Util.now()
do_year_options(year)
end
@spec do_year_options(Calendar.year()) :: %Range{
:first => Calendar.year(),
:last => Calendar.year()
}
defp do_year_options(year), do: Range.new(year - 4, year + 1)
end
| 27.322581 | 98 | 0.653365 |
089c510f841f3f84dcfa4ff85665fefba33650d9 | 108 | ex | Elixir | test/support/schemas.ex | DockYard/inquisitor | bf219f5659c113a6a76704c64002b0eb6fc49730 | [
"MIT"
] | 156 | 2016-02-07T03:29:43.000Z | 2022-02-25T23:07:00.000Z | test/support/schemas.ex | DockYard/inquisitor_jsonapi | 8dad9b0b59f617bf0882465b0cc8be255720e320 | [
"MIT"
] | 13 | 2016-06-24T02:10:28.000Z | 2020-07-04T07:53:34.000Z | test/support/schemas.ex | DockYard/inquisitor | bf219f5659c113a6a76704c64002b0eb6fc49730 | [
"MIT"
] | 20 | 2016-05-09T16:46:39.000Z | 2022-01-27T15:54:14.000Z | defmodule User do
use Ecto.Schema
schema "users" do
field :name
field :age, :integer
end
end
| 12 | 24 | 0.657407 |
089c90e567a4696b45fca1bfab2c3ced55ee364a | 130 | exs | Elixir | samples/nodes_wobserver/test/nodes_wobserver_test.exs | IanLuites/wobserver-elixirconf-2017 | 86a56a392a5877d2d9a51dc7fbd7e0d8b576c711 | [
"MIT"
] | 11 | 2017-05-05T12:28:35.000Z | 2020-02-26T09:16:10.000Z | samples/nodes_wobserver/test/nodes_wobserver_test.exs | IanLuites/wobserver-elixirconf-2017 | 86a56a392a5877d2d9a51dc7fbd7e0d8b576c711 | [
"MIT"
] | null | null | null | samples/nodes_wobserver/test/nodes_wobserver_test.exs | IanLuites/wobserver-elixirconf-2017 | 86a56a392a5877d2d9a51dc7fbd7e0d8b576c711 | [
"MIT"
] | null | null | null | defmodule NodesWobserverTest do
use ExUnit.Case
doctest NodesWobserver
test "the truth" do
assert 1 + 1 == 2
end
end
| 14.444444 | 31 | 0.707692 |
089c92f691837c482b36a2a7543dd1da77b03f52 | 2,997 | ex | Elixir | clients/analytics/lib/google_api/analytics/v3/api/metadata.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/analytics/lib/google_api/analytics/v3/api/metadata.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/analytics/lib/google_api/analytics/v3/api/metadata.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Analytics.V3.Api.Metadata do
@moduledoc """
API calls for all endpoints tagged `Metadata`.
"""
alias GoogleApi.Analytics.V3.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Lists all columns for a report type
## Parameters
- connection (GoogleApi.Analytics.V3.Connection): Connection to server
- report_type (String.t): Report type. Allowed Values: 'ga'. Where 'ga' corresponds to the Core Reporting API
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Analytics.V3.Model.Columns{}} on success
{:error, info} on failure
"""
@spec analytics_metadata_columns_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Analytics.V3.Model.Columns.t()} | {:error, Tesla.Env.t()}
def analytics_metadata_columns_list(connection, report_type, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/analytics/v3/metadata/{reportType}/columns", %{
"reportType" => URI.encode(report_type, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Analytics.V3.Model.Columns{}])
end
end
| 40.5 | 170 | 0.701702 |
089cbb681d63447ab6dfc033469f6ea18ce21b4c | 475 | ex | Elixir | lib/ex_notepad/supervisor.ex | kaiyote/ex_notepad | 0df1c3e9d56c9c4b6e9a3ca8a61e1e6c40e6a0b3 | [
"MIT"
] | null | null | null | lib/ex_notepad/supervisor.ex | kaiyote/ex_notepad | 0df1c3e9d56c9c4b6e9a3ca8a61e1e6c40e6a0b3 | [
"MIT"
] | null | null | null | lib/ex_notepad/supervisor.ex | kaiyote/ex_notepad | 0df1c3e9d56c9c4b6e9a3ca8a61e1e6c40e6a0b3 | [
"MIT"
] | null | null | null | defmodule ExNotepad.Supervisor do
@moduledoc false
use Supervisor
@spec start_link() :: {:ok, pid()} | :ignore | {:error, any()}
def start_link, do: Supervisor.start_link __MODULE__, []
@spec init([]) :: {:ok, {:supervisor.sup_flags(), [Supervisor.child_spec()]}}
def init([]) do
sup_flags = %{strategy: :one_for_one, intensity: 0, period: 5}
a_child = %{id: ExNotepad, start: {ExNotepad, :start_link, []}}
{:ok, {sup_flags, [a_child]}}
end
end
| 27.941176 | 79 | 0.64 |
089cf9ccba3ed76f382a6e9ded81b4f0d42f9953 | 98 | exs | Elixir | test/credo/backports/enum_test.exs | elixir-twister/credo | 619e0ec6e244c5e0c12eeeb58ed9de97e1571d99 | [
"MIT"
] | null | null | null | test/credo/backports/enum_test.exs | elixir-twister/credo | 619e0ec6e244c5e0c12eeeb58ed9de97e1571d99 | [
"MIT"
] | null | null | null | test/credo/backports/enum_test.exs | elixir-twister/credo | 619e0ec6e244c5e0c12eeeb58ed9de97e1571d99 | [
"MIT"
] | null | null | null | defmodule Credo.Backports.EnumTest do
use Credo.TestHelper
doctest Credo.Backports.Enum
end
| 14 | 37 | 0.806122 |
089cfade1c4a98ff2f9d0b96ee5d03024e9f9fda | 1,289 | ex | Elixir | frameworks/Elixir/plug/lib/framework_benchmarks/handlers/fortune.ex | xsoheilalizadeh/FrameworkBenchmarks | 855527008f7488e4fd508d1e72dfa9953874a2c6 | [
"BSD-3-Clause"
] | 5,300 | 2015-01-02T08:04:20.000Z | 2022-03-31T10:08:33.000Z | frameworks/Elixir/plug/lib/framework_benchmarks/handlers/fortune.ex | xsoheilalizadeh/FrameworkBenchmarks | 855527008f7488e4fd508d1e72dfa9953874a2c6 | [
"BSD-3-Clause"
] | 3,075 | 2015-01-01T05:11:45.000Z | 2022-03-31T23:56:33.000Z | frameworks/Elixir/plug/lib/framework_benchmarks/handlers/fortune.ex | xsoheilalizadeh/FrameworkBenchmarks | 855527008f7488e4fd508d1e72dfa9953874a2c6 | [
"BSD-3-Clause"
] | 2,151 | 2015-01-02T14:16:09.000Z | 2022-03-30T00:15:26.000Z | defmodule FrameworkBenchmarks.Handlers.Fortune do
@moduledoc """
This is the handle for the /fortunes route
"""
require EEx
@fortune_template """
<!DOCTYPE html>
<html>
<head><title>Fortunes</title></head>
<body>
<table>
<tr><th>id</th><th>message</th></tr>
<%= for item <- items do %>
<tr><td><%= item.id %></td><td><%= item.message %></td></tr>
<% end %>
</table>
</body>
</html>
"""
EEx.function_from_string(:defp, :generate_fortunes, @fortune_template, [:items])
@new_message "Additional fortune added at request time."
def handle(conn) do
fortunes =
FrameworkBenchmarks.Repo.all(FrameworkBenchmarks.Models.Fortune)
|> Enum.map(fn fortune ->
safe_result = Phoenix.HTML.html_escape(fortune.message)
%{id: fortune.id, message: Phoenix.HTML.safe_to_string(safe_result)}
end)
fortunes = [%{id: 0, message: @new_message}] ++ fortunes
fortunes =
fortunes
|> Enum.sort(fn %{message: first}, %{message: second}
when is_binary(first) and is_binary(second) ->
:ucol.compare(first, second) != 1
end)
conn
|> Plug.Conn.put_resp_content_type("text/html")
|> Plug.Conn.send_resp(200, generate_fortunes(fortunes))
end
end
| 26.306122 | 82 | 0.619085 |
089d0b52bf54c6a91b16cfe88cfc2c692ea26f86 | 1,862 | ex | Elixir | lib/darfey_web/views/media_view.ex | joonatank/darfey | 71ba0a41795bf97c35e940a4659dfbdf4805c46f | [
"MIT"
] | null | null | null | lib/darfey_web/views/media_view.ex | joonatank/darfey | 71ba0a41795bf97c35e940a4659dfbdf4805c46f | [
"MIT"
] | null | null | null | lib/darfey_web/views/media_view.ex | joonatank/darfey | 71ba0a41795bf97c35e940a4659dfbdf4805c46f | [
"MIT"
] | null | null | null | defmodule MediaFile do
defstruct [:type, :file, :thumb, :caption]
end
defmodule DarfeyWeb.MediaView do
@moduledoc """
MediaView module
"""
use DarfeyWeb, :view
require Logger
@doc """
Recursive function for creating list of image assets
@return List of MediaFiles
Tries to find a thumbnail file with {FILENAME}_thumb.{EXT}
where {FILENAME} is the orignal name, {EXT} is any extension (image)
If no thumbnail was found then
Assign the file as thumbnail
LOG: that the file doesn't have a thumbnail
"""
def get_image([file | files]) do
# Find a thumb file
# TODO
# Problem: if a video file has no thumbs the html img tag will not work
thumb = List.first(Path.wildcard(Path.rootname(file) <> "_thumb*"))
|| (Logger.warn "NO thumb #{inspect(file)}"; file)
# Only supports mp4 videos
# We need to create a list of supported video/image types and check against those
type_ =
if Path.extname(file) == ".mp4" do
"video"
else
"img"
end
Logger.debug "file: #{inspect{Path.basename(file)}} Image type : #{inspect(type_)} thumb: #{inspect(thumb)}"
[%MediaFile{type: type_, file: Path.basename(file), thumb: Path.basename(thumb), caption: "Problems"}] ++ get_image(files)
end
def get_image([]), do: []
@doc """
Get the images/videos from asset/images/media directory
@return List of MediaFiles
"""
def get_images() do
# Find all thumbs
# Use get_image to find the orignal file
# TODO
# Problem: If the file has non image/video extension
path = "assets/static/images/media/"
thumbs = Path.wildcard(path <> "*_thumb*")
all = Path.wildcard(path <> "*")
originals = MapSet.difference(Enum.into(all, MapSet.new), Enum.into(thumbs, MapSet.new))
|> MapSet.to_list
get_image(originals)
end
end
| 30.032258 | 126 | 0.657895 |
089d1f56f30fbc11beaacfc22d520dea65177f0f | 240 | ex | Elixir | examples/invoicing_app/lib/invoicing_app/analytics/customer_invoice_counter.ex | surgeventures/sea-elixir | a2f1b63c2c829713594997c08dc5bc5892edbf62 | [
"MIT"
] | 8 | 2018-11-27T09:59:27.000Z | 2021-06-03T17:51:53.000Z | examples/invoicing_app/lib/invoicing_app/analytics/customer_invoice_counter.ex | surgeventures/sea-elixir | a2f1b63c2c829713594997c08dc5bc5892edbf62 | [
"MIT"
] | 2 | 2019-03-19T13:38:10.000Z | 2019-03-20T12:28:39.000Z | examples/invoicing_app/lib/invoicing_app/analytics/customer_invoice_counter.ex | surgeventures/sea-elixir | a2f1b63c2c829713594997c08dc5bc5892edbf62 | [
"MIT"
] | 1 | 2021-10-07T12:49:57.000Z | 2021-10-07T12:49:57.000Z | defmodule InvoicingApp.Analytics.CustomerInvoiceCounter do
@moduledoc false
use Ecto.Schema
schema "analytics_customer_invoice_counters" do
field(:customer_id, :integer)
field(:invoice_count, :integer, default: 0)
end
end
| 21.818182 | 58 | 0.775 |
089d7da0c4c12b917571cec0a6847f8b9a533168 | 2,834 | ex | Elixir | lib/openflow/multipart/aggregate/request.ex | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 5 | 2019-05-25T02:25:13.000Z | 2020-10-06T17:00:03.000Z | lib/openflow/multipart/aggregate/request.ex | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 5 | 2018-03-29T14:42:10.000Z | 2019-11-19T07:03:09.000Z | lib/openflow/multipart/aggregate/request.ex | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 1 | 2019-03-30T20:48:27.000Z | 2019-03-30T20:48:27.000Z | defmodule Openflow.Multipart.Aggregate.Request do
defstruct(
version: 4,
xid: 0,
# virtual field
datapath_id: nil,
aux_id: nil,
flags: [],
table_id: :all,
out_port: :any,
out_group: :any,
cookie: 0,
cookie_mask: 0,
match: Openflow.Match.new()
)
alias __MODULE__
@type t :: %Request{
version: 4,
datapath_id: String.t(),
aux_id: 0..0xFF | nil,
xid: 0..0xFFFFFFFF,
table_id: 0..0xFF | :all | :max,
out_port: Openflow.Port.no(),
out_group: Openflow.GroupMod.id(),
cookie: 0..0xFFFFFFFFFFFFFFFF,
cookie_mask: 0..0xFFFFFFFFFFFFFFFF,
match: %Openflow.Match{fields: [map()], type: :oxm}
}
@spec ofp_type() :: 18
def ofp_type, do: 18
@spec new(
xid: 0..0xFFFFFFFF,
table_id: 0..0xFF | :all | :max,
out_port: Openflow.Port.no(),
out_group: Openflow.GroupMod.id(),
cookie: 0..0xFFFFFFFFFFFFFFFF,
cookie_mask: 0..0xFFFFFFFFFFFFFFFF,
match: %Openflow.Match{fields: [map()], type: :oxm}
) :: t()
def new(options \\ []) do
%Request{
xid: options[:xid] || 0,
table_id: options[:table_id] || :all,
out_port: options[:out_port] || :any,
out_group: options[:out_group] || :any,
cookie: options[:cookie] || 0,
cookie_mask: options[:cookie_mask] || 0,
match: options[:match] || Openflow.Match.new()
}
end
@spec read(<<_::256, _::_*8>>) :: t()
def read(<<
table_id_int::8,
_::size(3)-unit(8),
out_port_int::32,
out_group_int::32,
_::size(4)-unit(8),
cookie::64,
cookie_mask::64,
match_bin::bytes
>>) do
match =
match_bin
|> Openflow.Match.read()
|> Kernel.elem(0)
%Request{
table_id: Openflow.Utils.get_enum(table_id_int, :table_id),
out_port: Openflow.Utils.get_enum(out_port_int, :openflow13_port_no),
out_group: Openflow.Utils.get_enum(out_group_int, :group_id),
cookie: cookie,
cookie_mask: cookie_mask,
match: match
}
end
@spec to_binary(t()) :: <<_::256, _::_*8>>
def to_binary(
%Request{
table_id: table_id,
out_port: out_port,
out_group: out_group,
cookie: cookie,
cookie_mask: cookie_mask,
match: match
} = msg
) do
<<
Openflow.Multipart.Request.header(msg)::bytes,
Openflow.Utils.get_enum(table_id, :table_id)::8,
0::size(3)-unit(8),
Openflow.Utils.get_enum(out_port, :openflow13_port_no)::32,
Openflow.Utils.get_enum(out_group, :group_id)::32,
0::size(4)-unit(8),
cookie::64,
cookie_mask::64,
Openflow.Match.to_binary(match)::bytes
>>
end
end
| 26.735849 | 75 | 0.561397 |
089d841aae5ad640e99d8f43a713ae84cc77d886 | 794 | exs | Elixir | test/http/events_test.exs | rijavskii/ex_ari | 1fd5eabd9b4cb815e260867b0190a7fe635ee38a | [
"MIT"
] | 13 | 2020-04-17T16:48:00.000Z | 2022-03-25T19:16:51.000Z | test/http/events_test.exs | rijavskii/ex_ari | 1fd5eabd9b4cb815e260867b0190a7fe635ee38a | [
"MIT"
] | 1 | 2020-04-02T12:18:59.000Z | 2020-04-02T12:18:59.000Z | test/http/events_test.exs | rijavskii/ex_ari | 1fd5eabd9b4cb815e260867b0190a7fe635ee38a | [
"MIT"
] | 7 | 2020-04-28T19:45:50.000Z | 2022-03-25T21:42:03.000Z | defmodule ARI.HTTP.EventsTest do
use ExUnit.Case, async: true
require Logger
alias ARI.HTTP.Events
alias ARI.TestServer
@username "username1"
@password "password2"
setup_all do
host = "localhost"
{:ok, {_server_ref, <<"http://localhost:", port::binary>>}} = TestServer.start()
Events.start_link([host, String.to_integer(port), @username, @password])
[]
end
test "create" do
resp = Events.create("test-event", "test-app", ["channel:test-channel"], %{variables: %{}})
assert resp.json.path == "events" && resp.json.id == ["user", "test-event"] &&
resp.json.query_params.application == "test-app" &&
resp.json.query_params.source == "channel:test-channel" &&
resp.json.body_params.variables == %{}
end
end
| 26.466667 | 95 | 0.630982 |
089d8a1ba4b1cc56ad401e454b6b507d30d63d4d | 3,526 | exs | Elixir | lib/elixir/test/elixir/exception_test.exs | joearms/elixir | 9a0f8107bd8bbd089acb96fe0041d61a05e88a9b | [
"Apache-2.0"
] | 4 | 2016-04-05T05:51:36.000Z | 2019-10-31T06:46:35.000Z | lib/elixir/test/elixir/exception_test.exs | joearms/elixir | 9a0f8107bd8bbd089acb96fe0041d61a05e88a9b | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/exception_test.exs | joearms/elixir | 9a0f8107bd8bbd089acb96fe0041d61a05e88a9b | [
"Apache-2.0"
] | 5 | 2015-02-01T06:01:19.000Z | 2019-08-29T09:02:35.000Z | Code.require_file "test_helper.exs", __DIR__
defmodule Kernel.ExceptionTest do
use ExUnit.Case, async: true
test :is_exception do
assert is_exception(RuntimeError.new)
refute is_exception(empty_tuple)
refute is_exception(a_tuple)
refute is_exception(a_list)
end
test :format_stacktrace_entry_with_no_file_or_line do
assert Exception.format_stacktrace_entry({Foo, :bar, [1, 2, 3], []}) == "Foo.bar(1, 2, 3)"
assert Exception.format_stacktrace_entry({Foo, :bar, [], []}) == "Foo.bar()"
assert Exception.format_stacktrace_entry({Foo, :bar, 1, []}) == "Foo.bar/1"
end
test :format_stacktrace_entry_with_file_and_line do
assert Exception.format_stacktrace_entry({Foo, :bar, [], [file: 'file.ex', line: 10]}) == "file.ex:10: Foo.bar()"
assert Exception.format_stacktrace_entry({Foo, :bar, [1, 2, 3], [file: 'file.ex', line: 10]}) == "file.ex:10: Foo.bar(1, 2, 3)"
assert Exception.format_stacktrace_entry({Foo, :bar, 1, [file: 'file.ex', line: 10]}) == "file.ex:10: Foo.bar/1"
end
test :format_stacktrace_entry_with_file_and_line_and_cwd do
assert Exception.format_stacktrace_entry({Foo, :bar, [], [file: '/foo/file.ex', line: 10]}, "/foo") == "file.ex:10: Foo.bar()"
end
test :format_stacktrace_entry_with_file_no_line do
assert Exception.format_stacktrace_entry({Foo, :bar, [], [file: 'file.ex']}) == "file.ex: Foo.bar()"
assert Exception.format_stacktrace_entry({Foo, :bar, [], [file: 'file.ex', line: 0]}) == "file.ex: Foo.bar()"
assert Exception.format_stacktrace_entry({Foo, :bar, [1, 2, 3], [file: 'file.ex']}) == "file.ex: Foo.bar(1, 2, 3)"
assert Exception.format_stacktrace_entry({Foo, :bar, 1, [file: 'file.ex']}) == "file.ex: Foo.bar/1"
end
test :format_stacktrace_entry_with_fun do
assert Exception.format_stacktrace_entry({fn(x) -> x end, [1], []}) =~ %r"\(1\)"
assert Exception.format_stacktrace_entry({fn(x, y) -> { x, y } end, 2, []}) =~ %r"/2"
end
test :format_module_function_arity do
assert Exception.format_module_fun_arity Foo, nil, 1 == "Foo.nil/1"
assert Exception.format_module_fun_arity Foo, :bar, 1 == "Foo.bar/1"
assert Exception.format_module_fun_arity Foo, :bar, [] == "Foo.bar()"
assert Exception.format_module_fun_arity :foo, :bar, [1,2] == ":foo.bar(1, 2)"
end
test :format_module_function_arity_with_special_function_name do
assert Exception.format_module_fun_arity Foo, :"bar baz", 1 == "Foo.\"bar baz\"/1"
end
test :runtime_error_message do
assert RuntimeError.new.message == "runtime error"
assert RuntimeError.new(message: "exception").message == "exception"
end
test :argument_error_message do
assert ArgumentError.new.message == "argument error"
assert ArgumentError.new(message: "exception").message == "exception"
end
test :undefined_function_message do
assert UndefinedFunctionError.new.message == "undefined function"
assert UndefinedFunctionError.new(module: Foo, function: :bar, arity: 1).message == "undefined function: Foo.bar/1"
end
test :function_clause_message do
assert FunctionClauseError.new.message == "no function clause matches"
assert FunctionClauseError.new(module: Foo, function: :bar, arity: 1).message == "no function clause matching in Foo.bar/1"
end
test :erlang_error_message do
assert ErlangError.new(original: :sample).message == "erlang error: :sample"
end
defp empty_tuple, do: {}
defp a_tuple, do: { :foo, :bar, :baz }
defp a_list, do: [ :foo, :bar, :baz ]
end
| 44.075 | 131 | 0.693988 |
089daeda0c587687d169c130c94e6ffc4e845d19 | 819 | ex | Elixir | lib/ex_twiml/reserved_name_error.ex | postmates/ex_twiml | 9e2306723a206c5d1353977321901aad4715d63d | [
"MIT"
] | 35 | 2015-04-17T19:06:05.000Z | 2021-05-18T23:50:52.000Z | lib/ex_twiml/reserved_name_error.ex | tsloughter/ex_twiml | 693f9ac80f14b6d5717f45354cd99cab8a79512e | [
"MIT"
] | 9 | 2015-04-17T22:27:11.000Z | 2017-08-05T16:45:39.000Z | lib/ex_twiml/reserved_name_error.ex | tsloughter/ex_twiml | 693f9ac80f14b6d5717f45354cd99cab8a79512e | [
"MIT"
] | 11 | 2015-05-31T18:42:06.000Z | 2019-06-03T17:24:42.000Z | defmodule ExTwiml.ReservedNameError do
@moduledoc """
This error is thrown if you try to use TwiML verb name as a variable name
in your `twiml` block.
## Example
This code will raise the error, because `number` is a reserved name.
twiml do
Enum.each [1, 2], fn(number) ->
# ...
end
end
"""
defexception [:message]
@doc false
@spec exception(list) :: %__MODULE__{}
def exception([{name, context, _}, file_name]) do
file_name = Path.relative_to_cwd(file_name)
name = to_string(name)
message = ~s"""
"#{name}" is a reserved name in #{file_name}:#{context[:line]}, because it
is used to generate the <#{String.capitalize(name)} /> TwiML verb.
Please use a different variable name.
"""
%__MODULE__{message: message}
end
end
| 23.4 | 78 | 0.6337 |
089db3dc56f655fcbd1ae0ac1516b8e3383bf59e | 2,018 | exs | Elixir | elixir/frontend/config/prod.exs | honeycombio/example-greeting-service | 52365a5f2ae434d0b3a84b10889486184042cbc3 | [
"Apache-2.0"
] | 8 | 2020-12-29T17:44:16.000Z | 2021-11-18T22:18:42.000Z | elixir/frontend/config/prod.exs | honeycombio/example-greeting-service | 52365a5f2ae434d0b3a84b10889486184042cbc3 | [
"Apache-2.0"
] | 36 | 2021-04-08T14:30:02.000Z | 2022-03-30T22:06:44.000Z | elixir/frontend/config/prod.exs | honeycombio/example-greeting-service | 52365a5f2ae434d0b3a84b10889486184042cbc3 | [
"Apache-2.0"
] | 1 | 2021-04-05T10:52:23.000Z | 2021-04-05T10:52:23.000Z | use Mix.Config
# For production, don't forget to configure the url host
# to something meaningful, Phoenix uses this information
# when generating URLs.
#
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and
# before starting your production server.
config :frontend, FrontendWeb.Endpoint,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## 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 :frontend, FrontendWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH"),
# transport_options: [socket_opts: [:inet6]]
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https:
#
# config :frontend, FrontendWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# Finally import the config/prod.secret.exs which loads secrets
# and configuration from environment variables.
import_config "prod.secret.exs"
| 36.035714 | 66 | 0.71556 |
089de80a6d14448cd37c5134322dccb2ca9cea58 | 6,171 | ex | Elixir | lib/pow/plug.ex | jordelver/pow | 60235189155c87efbb40238ce5008340d470e995 | [
"MIT"
] | null | null | null | lib/pow/plug.ex | jordelver/pow | 60235189155c87efbb40238ce5008340d470e995 | [
"MIT"
] | null | null | null | lib/pow/plug.ex | jordelver/pow | 60235189155c87efbb40238ce5008340d470e995 | [
"MIT"
] | null | null | null | defmodule Pow.Plug do
@moduledoc """
Plug helper methods.
"""
alias Plug.Conn
alias Pow.{Config, Operations}
@private_config_key :pow_config
@doc """
Get the current user assigned to the conn.
The config is fetched from the conn. See `current_user/2` for more.
"""
@spec current_user(Conn.t()) :: map() | nil
def current_user(conn) do
current_user(conn, fetch_config(conn))
end
@doc """
Get the current user assigned to the conn.
This will fetch the user from the assigns map in the conn. The key is by
default `:current_user`, but it can be overridden with
`:current_user_assigns_key` configuration option.
"""
@spec current_user(Conn.t(), Config.t()) :: map() | nil
def current_user(%{assigns: assigns}, config) do
key = current_user_assigns_key(config)
Map.get(assigns, key)
end
@doc """
Assign an authenticated user to the connection.
This will assign the user to the conn. The key is by default `:current_user`,
but it can be overridden with `:current_user_assigns_key` configuration
option.
"""
@spec assign_current_user(Conn.t(), any(), Config.t()) :: Conn.t()
def assign_current_user(conn, user, config) do
key = current_user_assigns_key(config)
Conn.assign(conn, key, user)
end
defp current_user_assigns_key(config) do
Config.get(config, :current_user_assigns_key, :current_user)
end
@doc """
Put the provided config as a private key in the connection.
"""
@spec put_config(Conn.t(), Config.t()) :: Conn.t()
def put_config(conn, config) do
Conn.put_private(conn, @private_config_key, config)
end
@doc """
Fetch configuration from the private key in the connection.
It'll raise an error if configuration hasn't been set as a private key.
"""
@spec fetch_config(Conn.t()) :: Config.t()
def fetch_config(%{private: private}) do
private[@private_config_key] || no_config_error()
end
@doc """
Prepend namespace found in Plug Pow configuration to binary.
Will prepend `:otp_app` if exists in configuration.
"""
@spec prepend_with_namespace(Config.t(), binary()) :: binary()
def prepend_with_namespace(config, string) do
case fetch_namespace(config) do
nil -> string
namespace -> "#{namespace}_#{string}"
end
end
defp fetch_namespace(config), do: Config.get(config, :otp_app)
@doc """
Authenticates a user.
If successful, a new session will be created.
"""
@spec authenticate_user(Conn.t(), map()) :: {:ok | :error, Conn.t()}
def authenticate_user(conn, params) do
config = fetch_config(conn)
params
|> Operations.authenticate(config)
|> case do
nil -> {:error, conn}
user -> {:ok, get_plug(config).do_create(conn, user, config)}
end
end
@doc """
Clears the user authentication from the session.
"""
@spec clear_authenticated_user(Conn.t()) :: {:ok, Conn.t()}
def clear_authenticated_user(conn) do
config = fetch_config(conn)
{:ok, get_plug(config).do_delete(conn, config)}
end
@doc """
Creates a changeset from the current authenticated user.
"""
@spec change_user(Conn.t(), map()) :: map()
def change_user(conn, params \\ %{}) do
config = fetch_config(conn)
case current_user(conn, config) do
nil -> Operations.changeset(params, config)
user -> Operations.changeset(user, params, config)
end
end
@doc """
Creates a new user.
If successful, a new session will be created.
"""
@spec create_user(Conn.t(), map()) :: {:ok, map(), Conn.t()} | {:error, map(), Conn.t()}
def create_user(conn, params) do
config = fetch_config(conn)
params
|> Operations.create(config)
|> maybe_create_auth(conn, config)
end
@doc """
Updates the current authenticated user.
If successful, a new session will be created.
"""
@spec update_user(Conn.t(), map()) :: {:ok, map(), Conn.t()} | {:error, map(), Conn.t()}
def update_user(conn, params) do
config = fetch_config(conn)
conn
|> current_user(config)
|> Operations.update(params, config)
|> maybe_create_auth(conn, config)
end
@doc """
Deletes the current authenticated user.
If successful, the user authentication will be cleared from the session.
"""
@spec delete_user(Conn.t()) :: {:ok, map(), Conn.t()} | {:error, map(), Conn.t()}
def delete_user(conn) do
config = fetch_config(conn)
conn
|> current_user(config)
|> Operations.delete(config)
|> case do
{:ok, user} -> {:ok, user, get_plug(config).do_delete(conn, config)}
{:error, changeset} -> {:error, changeset, conn}
end
end
defp maybe_create_auth({:ok, user}, conn, config) do
{:ok, user, get_plug(config).do_create(conn, user, config)}
end
defp maybe_create_auth({:error, changeset}, conn, _config) do
{:error, changeset, conn}
end
# TODO: Remove by 1.1.0
@doc false
@deprecated "Use `get_plug/1` instead"
@spec get_mod(Config.t()) :: atom()
def get_mod(config), do: get_plug(config)
@spec get_plug(Config.t()) :: atom()
def get_plug(config) do
config[:plug] || no_plug_error()
end
@spec no_config_error :: no_return
defp no_config_error do
Config.raise_error("Pow configuration not found in connection. Please use a Pow plug that puts the Pow configuration in the plug connection.")
end
@spec no_plug_error :: no_return
defp no_plug_error do
Config.raise_error("Pow plug was not found in config. Please use a Pow plug that puts the `:plug` in the Pow configuration.")
end
@doc false
@spec __prevent_information_leak__(Conn.t(), any()) :: boolean()
def __prevent_information_leak__(%{private: %{pow_prevent_information_leak: false}}, _changeset), do: false
def __prevent_information_leak__(_conn, %{errors: errors}), do: unique_constraint_error?(errors, :email)
def __prevent_information_leak__(_conn, _any), do: true
defp unique_constraint_error?(errors, field) do
Enum.find_value(errors, false, fn
{^field, {_msg, [constraint: :unique, constraint_name: _name]}} -> true
_any -> false
end)
end
end
| 28.836449 | 146 | 0.666991 |
089df73cddc06d4b8448777271db7de564f52942 | 711 | exs | Elixir | early-chapters/mylist.exs | nespera/progr-elixir-1.6 | d8b5751d5106ce81e440e2ad0a28abb0d00b18a2 | [
"Apache-2.0"
] | null | null | null | early-chapters/mylist.exs | nespera/progr-elixir-1.6 | d8b5751d5106ce81e440e2ad0a28abb0d00b18a2 | [
"Apache-2.0"
] | null | null | null | early-chapters/mylist.exs | nespera/progr-elixir-1.6 | d8b5751d5106ce81e440e2ad0a28abb0d00b18a2 | [
"Apache-2.0"
] | null | null | null | defmodule MyList do
def mapsum(list, fun) do
mapsum(list, fun, 0)
end
def max([head | tail]) do
maxp(tail, head)
end
def caesar([], _offset), do: []
def caesar([head | tail], offset) do
[constrain(head + offset) | caesar(tail, offset)]
end
def span(from, to) when from > to, do: []
def span(from, to), do: [from | span(from + 1, to)]
defp constrain(char) when char > 122, do: constrain(char-26)
defp constrain(char), do: char
defp maxp([], best), do: best
defp maxp([head | tail], best) do
maxp(tail, max(head, best))
end
defp mapsum([], _, total), do: total
defp mapsum([head | tail], fun, total) do
mapsum(tail, fun, fun.(head) + total)
end
end | 20.911765 | 62 | 0.606188 |
089e2a7d96ccf4159abf6b387b64dbe7604e1239 | 1,739 | ex | Elixir | lib/mgp_web/controllers/user_reset_password_controller.ex | imprest/mgp | 61457315243d0e0c26713601b9930ca34a116a16 | [
"MIT"
] | null | null | null | lib/mgp_web/controllers/user_reset_password_controller.ex | imprest/mgp | 61457315243d0e0c26713601b9930ca34a116a16 | [
"MIT"
] | 2 | 2020-12-22T12:30:58.000Z | 2021-05-19T10:07:26.000Z | lib/mgp_web/controllers/user_reset_password_controller.ex | imprest/mgp | 61457315243d0e0c26713601b9930ca34a116a16 | [
"MIT"
] | null | null | null | defmodule MgpWeb.UserResetPasswordController do
use MgpWeb, :controller
alias Mgp.Accounts
plug :get_user_by_reset_password_token when action in [:edit, :update]
def new(conn, _params) do
render(conn, "new.html")
end
def create(conn, %{"user" => %{"email" => email}}) do
if user = Accounts.get_user_by_email(email) do
Accounts.deliver_user_reset_password_instructions(
user,
&Routes.user_reset_password_url(conn, :edit, &1)
)
end
# Regardless of the outcome, show an impartial success/error message.
conn
|> put_flash(
:info,
"If your email is in our system, you will receive instructions to reset your password shortly."
)
|> redirect(to: "/")
end
def edit(conn, _params) do
render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user))
end
# Do not log in the user after reset password to avoid a
# leaked token giving the user access to the account.
def update(conn, %{"user" => user_params}) do
case Accounts.reset_user_password(conn.assigns.user, user_params) do
{:ok, _} ->
conn
|> put_flash(:info, "Password reset successfully.")
|> redirect(to: Routes.user_session_path(conn, :new))
{:error, changeset} ->
render(conn, "edit.html", changeset: changeset)
end
end
defp get_user_by_reset_password_token(conn, _opts) do
%{"token" => token} = conn.params
if user = Accounts.get_user_by_reset_password_token(token) do
conn |> assign(:user, user) |> assign(:token, token)
else
conn
|> put_flash(:error, "Reset password link is invalid or it has expired.")
|> redirect(to: "/")
|> halt()
end
end
end
| 28.983333 | 101 | 0.658424 |
089e429936666700f00acef860f9eb1963f81e85 | 2,119 | exs | Elixir | mix.exs | wdiechmann/fish | b63fe109bbfc1cbe515ac31f9adcd9b57c6b21c8 | [
"MIT"
] | 1 | 2021-02-09T23:49:40.000Z | 2021-02-09T23:49:40.000Z | mix.exs | wdiechmann/fish | b63fe109bbfc1cbe515ac31f9adcd9b57c6b21c8 | [
"MIT"
] | null | null | null | mix.exs | wdiechmann/fish | b63fe109bbfc1cbe515ac31f9adcd9b57c6b21c8 | [
"MIT"
] | null | null | null | defmodule Fish.MixProject do
use Mix.Project
def project do
[
app: :fish,
version: "0.1.0",
elixir: "~> 1.7",
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: {Fish.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.5.1"},
{:phoenix_live_view, "~> 0.13.3"},
{:floki, ">= 0.0.0", only: :test},
{:phoenix_ecto, "~> 4.1"},
{:ecto_sql, "~> 3.4"},
{:myxql, ">= 0.0.0"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:phoenix_live_dashboard, "~> 0.2.6"},
{:telemetry_metrics, "~> 0.4"},
{:telemetry_poller, "~> 0.4"},
{:gettext, "~> 0.11"},
{:pow, "~> 1.0"},
{:jason, "~> 1.0"},
{:pow_assent, "~> 0.4.8"},
{:surface, "~> 0.1.0-alpha.2"},
# Optional, but recommended for SSL validation with :httpc adapter
{:certifi, "~> 2.4"},
{:ssl_verify_fun, "~> 1.1"},
{:plug_cowboy, "~> 2.0"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get", "ecto.setup", "cmd yarn --cwd ./assets add"],
"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
| 28.635135 | 84 | 0.560642 |
089e5362a8b8dc0dd0a7da786059d1b094274c6e | 2,326 | ex | Elixir | clients/cloud_scheduler/lib/google_api/cloud_scheduler/v1/model/status.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_scheduler/lib/google_api/cloud_scheduler/v1/model/status.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_scheduler/lib/google_api/cloud_scheduler/v1/model/status.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudScheduler.V1.Model.Status do
@moduledoc """
The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
## Attributes
* `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code.
* `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use.
* `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => integer(),
:details => list(map()),
:message => String.t()
}
field(:code)
field(:details, type: :list)
field(:message)
end
defimpl Poison.Decoder, for: GoogleApi.CloudScheduler.V1.Model.Status do
def decode(value, options) do
GoogleApi.CloudScheduler.V1.Model.Status.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudScheduler.V1.Model.Status do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.886792 | 427 | 0.72313 |
089e61646db42c34d93e8c8ab44f10b520a21367 | 472 | ex | Elixir | web/views/error_view.ex | nsarno/winter | a65a6aa61d2b1af39277338277f8b3f479643939 | [
"MIT"
] | 3 | 2015-08-24T11:44:19.000Z | 2016-10-01T21:37:05.000Z | web/views/error_view.ex | nsarno/winter | a65a6aa61d2b1af39277338277f8b3f479643939 | [
"MIT"
] | null | null | null | web/views/error_view.ex | nsarno/winter | a65a6aa61d2b1af39277338277f8b3f479643939 | [
"MIT"
] | null | null | null | defmodule Storm.ErrorView do
use Storm.Web, :view
def render("404.json", _assigns) do
%{error: "Page not found"}
end
def render("500.json", _assigns) do
%{error: "Server internal error"}
end
def render("401.json", _assigns) do
%{error: "Unauthorized request"}
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.json", assigns
end
end
| 21.454545 | 47 | 0.677966 |
089e664263a1108916d5b41be309b0dd26304ad3 | 1,625 | exs | Elixir | test/i18n_test.exs | kianmeng/not_qwerty123 | 9778ab77db866778ad7a5874be6f4cf2818a5933 | [
"MIT"
] | 39 | 2016-07-09T14:07:52.000Z | 2020-12-25T00:21:44.000Z | test/i18n_test.exs | kianmeng/not_qwerty123 | 9778ab77db866778ad7a5874be6f4cf2818a5933 | [
"MIT"
] | 13 | 2016-07-09T14:05:20.000Z | 2022-01-20T02:42:41.000Z | test/i18n_test.exs | kianmeng/not_qwerty123 | 9778ab77db866778ad7a5874be6f4cf2818a5933 | [
"MIT"
] | 11 | 2016-07-09T14:02:21.000Z | 2021-07-01T00:28:27.000Z | defmodule NotQwerty123.I18nTest do
use ExUnit.Case
import NotQwerty123.PasswordStrength
test "gettext returns English message for default locale" do
{:error, message} = strong_password?("4ghY&j2")
assert message =~ "password should be at least 8 characters long"
end
test "gettext returns Japanese message if locale is ja_JP" do
Gettext.put_locale(NotQwerty123.Gettext, "ja_JP")
{:error, message} = strong_password?("short")
assert message =~ "パスワードは8文字以上である必要があります。"
{:error, message} = strong_password?("p@55W0rD")
assert message =~ "入力されたパスワードは推測が容易で強度が不十分です。違うものを指定してください。"
end
test "gettext returns French message if locale is fr_FR" do
Gettext.put_locale(NotQwerty123.Gettext, "fr_FR")
{:error, message} = strong_password?("short")
assert message =~ "Le mot de passe doit contenir au moins 8 caractères."
end
test "gettext returns German message if locale is de_DE" do
Gettext.put_locale(NotQwerty123.Gettext, "de_DE")
{:error, message} = strong_password?("short")
assert message =~ "Das Kennwort sollte mindestens 8 Zeichen lang sein."
end
test "gettext returns Russian message if locale is ru_RU" do
Gettext.put_locale(NotQwerty123.Gettext, "ru_RU")
{:error, message} = strong_password?("short")
assert message =~ "Минимально допустимая длина пароля составляет 8."
end
test "gettext returns Spanish message if locale is es_ES" do
Gettext.put_locale(NotQwerty123.Gettext, "es_ES")
{:error, message} = strong_password?("short")
assert message =~ "La clave debe contener al menos 8 caracteres."
end
end
| 33.163265 | 76 | 0.724308 |
089ec523178259e110637a6c6d063dab7c439a93 | 625 | ex | Elixir | backend/lib/kjer_si_web/views/event_view.ex | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | 2 | 2019-11-02T21:28:34.000Z | 2019-11-28T18:01:08.000Z | backend/lib/kjer_si_web/views/event_view.ex | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | 17 | 2019-11-29T16:23:38.000Z | 2022-02-14T05:11:41.000Z | backend/lib/kjer_si_web/views/event_view.ex | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | null | null | null | defmodule KjerSiWeb.EventView do
use KjerSiWeb, :view
alias KjerSiWeb.EventView
def render("index.json", %{events: events}) do
%{data: render_many(events, EventView, "event.json")}
end
def render("show.json", %{event: event}) do
%{data: render_one(event, EventView, "event.json")}
end
def render("event.json", %{event: event}) do
%{
id: event.id,
name: event.name,
datetime: event.datetime,
description: event.description,
location: event.location,
max_attending: event.max_attending,
user_id: event.user_id,
room_id: event.room_id
}
end
end
| 24.038462 | 57 | 0.6512 |
089ee963988bb0142d40beb382df3091a66bbce4 | 68 | ex | Elixir | lib/first_app/repo.ex | seanreed1111/phoenix-first_app | 240d4d586a365392aa8c1fdf1a77986b7e7bd5f6 | [
"Apache-2.0"
] | null | null | null | lib/first_app/repo.ex | seanreed1111/phoenix-first_app | 240d4d586a365392aa8c1fdf1a77986b7e7bd5f6 | [
"Apache-2.0"
] | null | null | null | lib/first_app/repo.ex | seanreed1111/phoenix-first_app | 240d4d586a365392aa8c1fdf1a77986b7e7bd5f6 | [
"Apache-2.0"
] | null | null | null | defmodule FirstApp.Repo do
use Ecto.Repo, otp_app: :first_app
end
| 17 | 36 | 0.779412 |
089eff16381bc8fa2115babe49e380cb3313f7d4 | 351 | ex | Elixir | lib/spandex_newrelic/application.ex | MaethorNaur/spandex_newrelic | f5155d8e39c82b226bb916941161d3a72f7b9a7b | [
"MIT"
] | null | null | null | lib/spandex_newrelic/application.ex | MaethorNaur/spandex_newrelic | f5155d8e39c82b226bb916941161d3a72f7b9a7b | [
"MIT"
] | null | null | null | lib/spandex_newrelic/application.ex | MaethorNaur/spandex_newrelic | f5155d8e39c82b226bb916941161d3a72f7b9a7b | [
"MIT"
] | null | null | null | defmodule SpandexNewrelic.Application do
use Application
def start(_type, _args) do
children = [
%{
id: SpandexNewrelic.ApiServer,
start: {SpandexNewrelic.ApiServer, :start_link, []}
}
]
opts = [strategy: :one_for_one, name: SpandexNewrelic.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 21.9375 | 69 | 0.666667 |
089f0617e05d9bcd81e56809266fa36d4bf0be61 | 239 | exs | Elixir | priv/repo/migrations/20171014043419_change_body_field_type.exs | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | priv/repo/migrations/20171014043419_change_body_field_type.exs | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | priv/repo/migrations/20171014043419_change_body_field_type.exs | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | defmodule ElixirBlog.Repo.Migrations.ChangeBodyFieldType do
use Ecto.Migration
def change do
alter table("articles") do
modify :body, :text
end
alter table("comments") do
modify :body, :text
end
end
end
| 17.071429 | 59 | 0.67364 |
089f11c0e26ebfa277b5c2aaad6765c3626af107 | 1,780 | ex | Elixir | clients/text_to_speech/lib/google_api/text_to_speech/v1/model/synthesize_speech_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/text_to_speech/lib/google_api/text_to_speech/v1/model/synthesize_speech_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/text_to_speech/lib/google_api/text_to_speech/v1/model/synthesize_speech_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.TextToSpeech.V1.Model.SynthesizeSpeechResponse do
@moduledoc """
The message returned to the client by the `SynthesizeSpeech` method.
## Attributes
* `audioContent` (*type:* `String.t`, *default:* `nil`) - The audio data bytes encoded as specified in the request, including the header for encodings that are wrapped in containers (e.g. MP3, OGG_OPUS). For LINEAR16 audio, we include the WAV header. Note: as with all bytes fields, protobuffers use a pure binary representation, whereas JSON representations use base64.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:audioContent => String.t() | nil
}
field(:audioContent)
end
defimpl Poison.Decoder, for: GoogleApi.TextToSpeech.V1.Model.SynthesizeSpeechResponse do
def decode(value, options) do
GoogleApi.TextToSpeech.V1.Model.SynthesizeSpeechResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.TextToSpeech.V1.Model.SynthesizeSpeechResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.87234 | 374 | 0.75618 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.