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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c34c4efe8df33bb644b7a0fc9c8aa2f64268b9c | 295 | exs | Elixir | config/config.exs | code-shoily/lotus | d14958956103f2376d51974f40bcc7d7c59c2ad9 | [
"MIT"
] | null | null | null | config/config.exs | code-shoily/lotus | d14958956103f2376d51974f40bcc7d7c59c2ad9 | [
"MIT"
] | null | null | null | config/config.exs | code-shoily/lotus | d14958956103f2376d51974f40bcc7d7c59c2ad9 | [
"MIT"
] | null | null | null | import Config
config :phoenix, :json_library, Jason
config :esbuild,
version: "0.14.0",
default: [
args: ~w(js/app.js --bundle --target=es2016 --outdir=../priv/catalogue/assets),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
| 24.583333 | 83 | 0.630508 |
1c3507c17143148adff089dbe78079e590dc7264 | 74 | exs | Elixir | test/hub_web/views/layout_view_test.exs | Poeticode/hub | 39df28dd5f18fe61899b72f18935c1508dd166ee | [
"MIT"
] | null | null | null | test/hub_web/views/layout_view_test.exs | Poeticode/hub | 39df28dd5f18fe61899b72f18935c1508dd166ee | [
"MIT"
] | 5 | 2020-07-17T23:35:42.000Z | 2021-05-10T07:00:10.000Z | test/hub_web/views/layout_view_test.exs | Poeticode/hub | 39df28dd5f18fe61899b72f18935c1508dd166ee | [
"MIT"
] | null | null | null | defmodule HubWeb.LayoutViewTest do
use HubWeb.ConnCase, async: true
end
| 18.5 | 34 | 0.810811 |
1c354d62fa2c216118885f9a2a30ff6790a56efc | 1,727 | ex | Elixir | lib/weaver/absinthe/middleware/continue.ex | weaver-engine/weaver | b60a59673d7adb0ebfbb5f392d03fe09399054bc | [
"MIT"
] | null | null | null | lib/weaver/absinthe/middleware/continue.ex | weaver-engine/weaver | b60a59673d7adb0ebfbb5f392d03fe09399054bc | [
"MIT"
] | null | null | null | lib/weaver/absinthe/middleware/continue.ex | weaver-engine/weaver | b60a59673d7adb0ebfbb5f392d03fe09399054bc | [
"MIT"
] | null | null | null | defmodule Weaver.Absinthe.Middleware.Continue do
@moduledoc """
This plugin enables asynchronous execution of a field.
"""
# credo:disable-for-this-file Credo.Check.Consistency.ParameterPatternMatching
alias Weaver.{Marker, Ref, Step}
defstruct [
:prev_chunk_end,
next_chunk_start: :not_loaded,
refreshed: false,
count: 0
]
@type t() :: %__MODULE__{
prev_chunk_end: Marker.t() | nil | :not_loaded,
next_chunk_start: Marker.t() | nil | :not_loaded,
refreshed: boolean(),
count: non_neg_integer()
}
@behaviour Absinthe.Middleware
# call resolver function only if this is the resolution part for the current step
def call(%{state: :suspended, acc: %{resolution: path}, path: path} = res, fun) do
cache = res.context.cache
parent_ref = res.source && Ref.from(res.source)
[%Absinthe.Blueprint.Document.Field{name: field} | _] = path
Map.get(res.acc, __MODULE__, %__MODULE__{})
|> Step.load_markers(res.context, cache, parent_ref, field)
|> case do
%{prev_chunk_end: :not_loaded} ->
%{
res
| acc: Map.put(res.acc, __MODULE__, nil) |> Map.put(:meta, [])
}
|> Absinthe.Resolution.put_result({:ok, []})
step ->
resolved = fun.(step.prev_chunk_end)
{value, meta, next} = Step.process_resolved(resolved, step, cache, parent_ref, field)
%{
res
| acc: Map.put(res.acc, __MODULE__, next) |> Map.put(:meta, meta),
middleware: [{__MODULE__, fun} | res.middleware]
}
|> Absinthe.Resolution.put_result({:ok, value})
end
end
# ... skip otherwise
def call(res, _fun) do
res
end
end
| 28.311475 | 93 | 0.616097 |
1c355dcfd1bfc57c3b3ed996409872a4ba462ace | 1,139 | ex | Elixir | apps/database/lib/database/services/account/open.ex | fschuindt/amethyst | 0e8d60f83693b3bdb2c05d461cc3a74fa8b88b30 | [
"MIT"
] | 2 | 2018-06-23T11:43:34.000Z | 2019-01-07T10:52:42.000Z | apps/database/lib/database/services/account/open.ex | fschuindt/amethyst | 0e8d60f83693b3bdb2c05d461cc3a74fa8b88b30 | [
"MIT"
] | 1 | 2018-06-21T01:20:04.000Z | 2018-06-21T01:20:04.000Z | apps/database/lib/database/services/account/open.ex | fschuindt/amethyst | 0e8d60f83693b3bdb2c05d461cc3a74fa8b88b30 | [
"MIT"
] | 1 | 2018-06-30T21:40:51.000Z | 2018-06-30T21:40:51.000Z | defmodule DataBase.Services.Account.Open do
@moduledoc """
Acts as a service to **open** a new bank account.
"""
alias DataBase.Repos.AmethystRepo, as: Repo
alias DataBase.Schemas.Account, as: Acc
alias Decimal, as: D
@credit 1000
@doc """
Given a `t:DataBase.Schemas.Account.t/0`, registers it in the
database.
It also set a initial inbound movement of `1000.00` as a opening
credit and generates its API authentication token.
It's the standard way to open a new account.
"""
@spec perform(Acc.t) :: Acc.response_t()
def perform(%Acc{} = base_build) do
respond(Repo.transaction(fn ->
with build <- Acc.set_token(base_build),
{:ok, account} <- Acc.create(build),
{:ok, _credit} <- Acc.credit(account, credit()) do
{:ok, account}
else
_e ->
{:error, :failed_open_performance}
end
end))
end
@spec respond(any) :: Acc.response_t()
defp respond({:ok, transaction}), do: transaction
defp respond(_any), do: {:error, :database_failure}
@spec credit() :: D.t()
defp credit, do: D.new(@credit)
end
| 27.119048 | 66 | 0.627744 |
1c357c5f4b4196012a623e74d52ece883cf21500 | 3,305 | ex | Elixir | clients/run/lib/google_api/run/v1/model/expr.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/model/expr.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/model/expr.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.Run.V1.Model.Expr do
@moduledoc """
Represents a textual expression in the Common Expression Language (CEL)
syntax. CEL is a C-like expression language. The syntax and semantics of CEL
are documented at https://github.com/google/cel-spec.
Example (Comparison):
title: "Summary size limit"
description: "Determines if a summary is less than 100 chars"
expression: "document.summary.size() < 100"
Example (Equality):
title: "Requestor is owner"
description: "Determines if requestor is the document owner"
expression: "document.owner == request.auth.claims.email"
Example (Logic):
title: "Public documents"
description: "Determine whether the document should be publicly visible"
expression: "document.type != 'private' && document.type != 'internal'"
Example (Data Manipulation):
title: "Notification string"
description: "Create a notification string with a timestamp."
expression: "'New message received at ' + string(document.create_time)"
The exact variables and functions that may be referenced within an expression
are determined by the service that evaluates it. See the service
documentation for additional information.
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - Optional. Description of the expression. This is a longer text which
describes the expression, e.g. when hovered over it in a UI.
* `expression` (*type:* `String.t`, *default:* `nil`) - Textual representation of an expression in Common Expression Language
syntax.
* `location` (*type:* `String.t`, *default:* `nil`) - Optional. String indicating the location of the expression for error
reporting, e.g. a file name and a position in the file.
* `title` (*type:* `String.t`, *default:* `nil`) - Optional. Title for the expression, i.e. a short string describing
its purpose. This can be used e.g. in UIs which allow to enter the
expression.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t(),
:expression => String.t(),
:location => String.t(),
:title => String.t()
}
field(:description)
field(:expression)
field(:location)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.Run.V1.Model.Expr do
def decode(value, options) do
GoogleApi.Run.V1.Model.Expr.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Run.V1.Model.Expr do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.318681 | 129 | 0.704085 |
1c35ae3c10a62b9a1c8e9bc69fe4d1d5418de30d | 363 | exs | Elixir | priv/repo/migrations/20190717022653_create_post_tags.exs | vutuv/vutuv | 174706cdaf28cef24e1cc06bec0884c25f2412be | [
"MIT"
] | 309 | 2016-05-03T17:16:23.000Z | 2022-03-01T09:30:22.000Z | priv/repo/migrations/20190717022653_create_post_tags.exs | vutuv/vutuv | 174706cdaf28cef24e1cc06bec0884c25f2412be | [
"MIT"
] | 662 | 2016-04-27T07:45:18.000Z | 2022-01-05T07:29:19.000Z | priv/repo/migrations/20190717022653_create_post_tags.exs | vutuv/vutuv | 174706cdaf28cef24e1cc06bec0884c25f2412be | [
"MIT"
] | 40 | 2016-04-27T07:46:22.000Z | 2021-12-31T05:54:34.000Z | defmodule Vutuv.Repo.Migrations.CreatePostTags do
use Ecto.Migration
def change do
create table(:post_tags) do
add :post_id, references(:posts, on_delete: :delete_all)
add :tag_id, references(:tags, on_delete: :delete_all)
timestamps()
end
create unique_index(:post_tags, [:post_id, :tag_id], name: :post_id_tag_id)
end
end
| 24.2 | 79 | 0.705234 |
1c35df281569e9071c6ca7dcffe091100d56e783 | 2,277 | ex | Elixir | lib/univrse/alg/aes_gcm.ex | libitx/univrse | de50baebd257e73e869be4a2e87a60283d1c8001 | [
"Apache-2.0"
] | 5 | 2021-08-03T12:10:21.000Z | 2022-03-08T12:30:50.000Z | lib/univrse/alg/aes_gcm.ex | libitx/univrse | de50baebd257e73e869be4a2e87a60283d1c8001 | [
"Apache-2.0"
] | 1 | 2021-08-04T10:28:31.000Z | 2021-08-04T10:28:31.000Z | lib/univrse/alg/aes_gcm.ex | libitx/univrse | de50baebd257e73e869be4a2e87a60283d1c8001 | [
"Apache-2.0"
] | null | null | null | defmodule Univrse.Alg.AES_GCM do
@moduledoc """
AES_GCM algorithm module.
Sign and encrypt messages using AES-GCM symetric encryption.
"""
alias Univrse.Key
@doc """
Decrypts the cyphertext with the key using the specified algorithm.
Accepted options:
* `aad` - Ephemeral public key
* `iv` - Agreement PartyUInfo
* `tag` - Agreement PartyVInfo
"""
@spec decrypt(String.t, binary, Key.t, keyword) :: {:ok, binary} | {:error, any}
def decrypt(alg, encrypted, key, opts \\ [])
def decrypt(alg, encrypted, %Key{type: "oct", params: %{k: k}}, opts)
when (alg == "A128GCM" and byte_size(k) == 16)
or (alg == "A256GCM" and byte_size(k) == 32)
do
aad = Keyword.get(opts, :aad, "")
iv = Keyword.get(opts, :iv, "")
tag = Keyword.get(opts, :tag, "")
case :crypto.crypto_one_time_aead(cipher(alg), k, iv, encrypted, aad, tag, false) do
result when is_binary(result) ->
{:ok, result}
{:error, _, error} ->
{:error, error}
:error ->
{:error, "Decrypt error"}
end
end
def decrypt(_alg, _encrypted, _key, _opts),
do: {:error, :invalid_key}
@doc """
Encrypts the message with the key using the specified algorithm. Returns a
three part tuple containing the encrypted cyphertext and any headers to add to
the Recipient.
Accepted options:
* `aad` - Ephemeral public key
* `iv` - Agreement PartyUInfo
"""
@spec encrypt(String.t, binary, Key.t, keyword) :: {:ok, binary, map} | {:error, any}
def encrypt(alg, message, key, opts \\ [])
def encrypt(alg, message, %Key{type: "oct", params: %{k: k}}, opts)
when (alg == "A128GCM" and byte_size(k) == 16)
or (alg == "A256GCM" and byte_size(k) == 32)
do
aad = Keyword.get(opts, :aad, "")
iv = Keyword.get(opts, :iv, :crypto.strong_rand_bytes(12))
case :crypto.crypto_one_time_aead(cipher(alg), k, iv, message, aad, true) do
{encrypted, tag} ->
{:ok, encrypted, %{"iv" => iv, "tag" => tag}}
{:error, _, error} ->
{:error, error}
end
end
def encrypt(_alg, _message, _key, _opts),
do: {:error, :invalid_key}
# Returns the cipher for the given algorithm
defp cipher("A128GCM"), do: :aes_128_gcm
defp cipher("A256GCM"), do: :aes_256_gcm
end
| 28.111111 | 88 | 0.619675 |
1c35e230f1a93f193e983c9df1f6220494705d83 | 981 | exs | Elixir | api_server/config/config.exs | Spippolo/wheredafuckRU | 4ff399532ab4847a390bfb0ce193ec5732c04595 | [
"MIT"
] | null | null | null | api_server/config/config.exs | Spippolo/wheredafuckRU | 4ff399532ab4847a390bfb0ce193ec5732c04595 | [
"MIT"
] | null | null | null | api_server/config/config.exs | Spippolo/wheredafuckRU | 4ff399532ab4847a390bfb0ce193ec5732c04595 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# General application configuration
config :wheredafuckru_api,
ecto_repos: [WheredafuckruApi.Repo]
# Configures the endpoint
config :wheredafuckru_api, WheredafuckruApi.Endpoint,
url: [host: "localhost"],
secret_key_base: "b2tSx4rCA5USp3fSs7vBjIZ3HrPxRCFG1OrLJ2DAuMHSFWiGg56l5YilTV8UYXk7",
render_errors: [view: WheredafuckruApi.ErrorView, accepts: ~w(json)],
pubsub: [name: WheredafuckruApi.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 35.035714 | 86 | 0.776758 |
1c35f8460e0b70878214659c51b660e824fd6353 | 486 | exs | Elixir | exercitando.exs/exercitando.exs | leninaveira/random-repository | 86cdef5689935c722d60c130359b5624e549ed6d | [
"MIT"
] | 1 | 2020-12-22T03:52:06.000Z | 2020-12-22T03:52:06.000Z | exercitando.exs/exercitando.exs | leninaveira/random-repository | 86cdef5689935c722d60c130359b5624e549ed6d | [
"MIT"
] | null | null | null | exercitando.exs/exercitando.exs | leninaveira/random-repository | 86cdef5689935c722d60c130359b5624e549ed6d | [
"MIT"
] | null | null | null | defmodule ModuloNovo do
def naming_convetion) (variable, _ignora, long_variable) do
return {:ok, variable, long_variable}
end
end
d1 = [1,2,3]++[4,6]
d = [1,2,3,4,5,6]--[1,2]
i = 1 in d
true
iex(2)> 1===1.0
false
iex(3)> 1===!1.0
false
iex(4)> 1!===1.0
line_no = 50
if (line_no == 50) do
IO.puts "new-page\f"
line_no = 0
end
IO.puts line_no
sum = fn (a,b) -> a + b end
a = sum.(1,2)
IO.inspect a
mult = fn (a,b,c,...) -> a*b*c*... end
b = mult.(2,3,4,5,6)
IO.inspect b
| 16.2 | 61 | 0.584362 |
1c35fef6b967ac00b18f491502aa4ed228f7daad | 24 | exs | Elixir | index.exs | matiasdelgado/sfdx-cli | ef3f37f6cd18afb09732bb9f33595ece56c08766 | [
"MIT"
] | null | null | null | index.exs | matiasdelgado/sfdx-cli | ef3f37f6cd18afb09732bb9f33595ece56c08766 | [
"MIT"
] | 1 | 2021-05-11T05:35:21.000Z | 2021-05-11T05:35:21.000Z | index.exs | matiasdelgado/sfdx-cli | ef3f37f6cd18afb09732bb9f33595ece56c08766 | [
"MIT"
] | null | null | null | #!/usr/bin/env elixir
| 6 | 21 | 0.625 |
1c366409a2b7d1237c3ac2dc00526699f2f67ef1 | 75 | ex | Elixir | lib/voxpop/production.ex | zovafit/voxpop | 0af5903c010eb1164cabfd468719468cc909fcf0 | [
"MIT"
] | 10 | 2016-03-06T01:57:44.000Z | 2021-02-05T02:01:10.000Z | lib/voxpop/production.ex | zovafit/voxpop | 0af5903c010eb1164cabfd468719468cc909fcf0 | [
"MIT"
] | 5 | 2016-03-06T00:59:21.000Z | 2016-03-07T05:00:26.000Z | lib/voxpop/production.ex | zovafit/voxpop | 0af5903c010eb1164cabfd468719468cc909fcf0 | [
"MIT"
] | 3 | 2016-03-06T22:56:49.000Z | 2017-10-10T05:37:29.000Z | defprotocol Voxpop.Production do
def evaluate(production, registry)
end
| 15 | 36 | 0.813333 |
1c367679f7df2874fcb001431ea2f015344b15b7 | 882 | exs | Elixir | apps/forklift/config/test.exs | calebcarroll1/smartcitiesdata | b0f03496f6c592c82ba14aebf6c5996311cf3cd0 | [
"Apache-2.0"
] | 26 | 2019-09-20T23:54:45.000Z | 2020-08-20T14:23:32.000Z | apps/forklift/config/test.exs | calebcarroll1/smartcitiesdata | b0f03496f6c592c82ba14aebf6c5996311cf3cd0 | [
"Apache-2.0"
] | 757 | 2019-08-15T18:15:07.000Z | 2020-09-18T20:55:31.000Z | apps/forklift/config/test.exs | calebcarroll1/smartcitiesdata | b0f03496f6c592c82ba14aebf6c5996311cf3cd0 | [
"Apache-2.0"
] | 9 | 2019-11-12T16:43:46.000Z | 2020-03-25T16:23:16.000Z | use Mix.Config
config :logger, :level, :info
config :forklift,
data_reader: MockReader,
topic_writer: MockTopic,
table_writer: MockTable,
retry_count: 5,
retry_initial_delay: 10,
retry_max_wait: 500,
# To ensure that MessageWriter never starts while testing
message_processing_cadence: 1_000_000_000,
cache_processing_batch_size: 1_000,
user: "foobar",
topic_subscriber_config: [
begin_offset: :earliest,
offset_reset_policy: :reset_to_earliest,
max_bytes: 1_000_000,
min_bytes: 500_000,
max_wait_time: 10_000
]
config :forklift, :brook,
instance: :forklift,
driver: [
module: Brook.Driver.Test,
init_arg: []
],
handlers: [Forklift.Event.EventHandler],
storage: [
module: Brook.Storage.Ets,
init_arg: [
namespace: "forklift:view"
]
]
config :prestige, :session_opts, url: "http://127.0.0.1:8080"
| 22.615385 | 61 | 0.707483 |
1c369a189ce0ccce6bd6c1bcf4426237c065c7b7 | 786 | ex | Elixir | lib/mix/lib/mix/tasks/local.hex.ex | Tica2/elixir | 6cf1dcbfe4572fc75619f05e40c10fd0844083ef | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/local.hex.ex | Tica2/elixir | 6cf1dcbfe4572fc75619f05e40c10fd0844083ef | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/local.hex.ex | Tica2/elixir | 6cf1dcbfe4572fc75619f05e40c10fd0844083ef | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Local.Hex do
use Mix.Task
@hex_s3 "https://s3.amazonaws.com/s3.hex.pm"
@hex_list_url @hex_s3 <> "/installs/hex-1.x.csv"
@hex_archive_url @hex_s3 <> "/installs/[VERSION]/hex.ez"
@shortdoc "Install hex locally"
@moduledoc """
Install Hex locally.
mix local.hex
## Command line options
* `--force` - forces installation without a shell prompt; primarily
intended for automation in build systems like make
"""
@spec run(OptionParser.argv) :: boolean
def run(args) do
{version, sha512} = Mix.Local.find_matching_elixir_version_from_signed_csv!("Hex", @hex_list_url)
url = String.replace(@hex_archive_url, "[VERSION]", version)
Mix.Tasks.Archive.Install.run [url, "--sha512", sha512 | args]
end
end
| 29.111111 | 101 | 0.680662 |
1c369e409e1edc68208aafcaf4cf020f91d3ca42 | 1,061 | exs | Elixir | mix.exs | san650/html_party | 416698d562e8b30f400fec8961f4541320ed1b22 | [
"MIT"
] | 1 | 2018-04-24T13:33:33.000Z | 2018-04-24T13:33:33.000Z | mix.exs | san650/html_party | 416698d562e8b30f400fec8961f4541320ed1b22 | [
"MIT"
] | null | null | null | mix.exs | san650/html_party | 416698d562e8b30f400fec8961f4541320ed1b22 | [
"MIT"
] | null | null | null | defmodule HtmlParty.Mixfile do
use Mix.Project
def project do
[
app: :html_party,
description: description(),
version: "1.0.0",
elixir: "~> 1.5",
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package(),
source_url: "https://github.com/san650/html_party",
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# Test dependencies
{:phoenix_html, "~> 2.11", only: :test}
]
end
defp description do
"""
This library helps you write HTML using regular functions. It provides a small DSL that ensures that you write safe HTML.
"""
end
defp package do
[
files: ["lib", "mix.exs", "README*", "LICENSE*"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/san650/html_party"},
maintainers: ["Santiago Ferreira"],
name: :html_party,
]
end
end
| 22.104167 | 125 | 0.593779 |
1c36c6de25730dbe5bcbd3e850f16daf04fa583f | 1,448 | ex | Elixir | lib/cforum_web/views/admin/auditing_view.ex | campingrider/cforum_ex | cf27684c47d6dc26c9c37a946f1c729a79d27c70 | [
"MIT"
] | null | null | null | lib/cforum_web/views/admin/auditing_view.ex | campingrider/cforum_ex | cf27684c47d6dc26c9c37a946f1c729a79d27c70 | [
"MIT"
] | null | null | null | lib/cforum_web/views/admin/auditing_view.ex | campingrider/cforum_ex | cf27684c47d6dc26c9c37a946f1c729a79d27c70 | [
"MIT"
] | null | null | null | defmodule CforumWeb.Admin.AuditView do
use CforumWeb, :view
def page_title(:index, _), do: gettext("audit log")
def page_title(:show, _), do: gettext("audit log")
def page_heading(action, assigns), do: page_title(action, assigns)
def body_id(:index, _), do: "admin-audit-index"
def body_id(:show), do: "admin-audit-show"
def body_classes(:index, _), do: "admin audit index"
def body_classes(:show, _), do: "admin audit show"
def url_params(changeset) do
[
search:
[
from: Timex.lformat!(Ecto.Changeset.get_field(changeset, :from), "{YYYY}-{0M}-{0D}", "en"),
to: Timex.lformat!(Ecto.Changeset.get_field(changeset, :to), "{YYYY}-{0M}-{0D}", "en")
]
|> add_objects(Ecto.Changeset.get_field(changeset, :objects))
]
end
defp add_objects(opts, objects) when is_nil(objects) or objects == [], do: opts
defp add_objects(opts, objects), do: Keyword.put(opts, :objects, objects)
def is_object_checked?(changeset, type) do
objects = Ecto.Changeset.get_field(changeset, :objects)
Enum.find(objects, &(&1 == type)) != nil
end
def score_username(uid) do
user = Cforum.Accounts.Users.get_user(uid)
if user == nil, do: gettext("(unknown)"), else: user.username
end
alias Cforum.System.Auditing
import CforumWeb.AuditingViewL10n
def render_object(conn, %Auditing{relation: rel} = entry), do: render("#{rel}.html", conn: conn, entry: entry)
end
| 33.674419 | 112 | 0.667818 |
1c36f883224a4c415b1bba36b2f0eb186398abcc | 4,544 | ex | Elixir | lib/kamex/interpreter/builtins.ex | Ovyerus/kamex | c6ac49c19e5b75a8d41db38cf7ae63665de02587 | [
"MIT"
] | 14 | 2022-01-01T14:40:55.000Z | 2022-01-07T12:59:05.000Z | lib/kamex/interpreter/builtins.ex | Ovyerus/kamex | c6ac49c19e5b75a8d41db38cf7ae63665de02587 | [
"MIT"
] | null | null | null | lib/kamex/interpreter/builtins.ex | Ovyerus/kamex | c6ac49c19e5b75a8d41db38cf7ae63665de02587 | [
"MIT"
] | null | null | null | defmodule Kamex.Interpreter.Builtins do
@moduledoc false
import Kamex.Interpreter, only: [compute_expr: 2]
alias Kamex.Exceptions
require __MODULE__.{Fold, Lists, Math}
alias __MODULE__.{Fold, Lists, Math}
@tru 1
@fals 0
@falsey [[], @fals]
@num_tokens [:int, :float, :complex]
@supported %{
println: :println,
tack: :tack,
nth: :nth,
not: :not_,
fac: :fac,
map: :map,
filter: :filter,
count: :count,
every: :every,
"flat-map": :flat_map,
# seq and id are functionally the same since we're eager eval
id: :id,
seq: :id,
flatten: :flatten,
discard: :discard,
lift: :lift,
type: :type,
"to-string": :to_string,
"parse-num": :parse_num,
list_env: :list_env,
size: :size,
empty?: :empty?
}
defmacro mapping do
map_supported_to_mod = fn mod, {call_name, fn_name} -> {call_name, {fn_name, mod}} end
items =
[
Enum.map(@supported, &map_supported_to_mod.(__MODULE__, &1)),
Enum.map(Fold.supported(), &map_supported_to_mod.(Fold, &1)),
Enum.map(Lists.supported(), &map_supported_to_mod.(Lists, &1)),
Enum.map(Math.supported(), &map_supported_to_mod.(Math, &1))
]
|> Enum.map(&Enum.into(&1, %{}))
|> Enum.reduce(%{}, &Map.merge/2)
Macro.escape(items)
end
def builtin?(name), do: Map.get(mapping(), name)
def run(name, args, locals) do
args = Enum.map(args, &compute_expr(&1, locals))
{real_fn, mod} = Map.get(mapping(), name)
{apply(mod, real_fn, [args, locals]), locals}
end
# ---------------------------------------------------------------------------
def println([term], _) do
IO.puts(term)
term
end
def tack([nth], _) do
fn args_to_pick, _locals -> Enum.at(args_to_pick, nth) end
end
def nth([n, args], _), do: Enum.at(args, n)
# def not_([value], _), do: if(value in @falsey, do: @tru, else: @fals)
def not_([x], _) when x in @falsey, do: @tru
def not_([_], _), do: @fals
def fac([0], _), do: 1
def fac([num], _) when is_integer(num), do: num * fac([num - 1], nil)
def map([fun, arg], locals) when is_list(arg), do: map([fun | arg], locals)
def map([fun, str], locals) when is_binary(str), do: map([fun | String.codepoints(str)], locals)
def map([fun | args], locals), do: Enum.map(args, &compute_expr([fun, &1], locals))
def filter([fun, list], locals),
# Compare against 0 so that we don't have to do a second `not` check for `1`.
do: Enum.filter(list, fn item -> not_([compute_expr([fun, item], locals)], nil) == 0 end)
def count([fun, list], locals), do: Enum.count(filter([fun, list], locals))
def every([fun, list], locals),
do:
if(Enum.all?(list, fn item -> not_([compute_expr([fun, item], locals)], nil) == 0 end),
do: @tru,
else: @fals
)
def flat_map([fun, args], locals), do: Enum.flat_map(args, &compute_expr([fun, &1], locals))
def id([x], _), do: x
def flatten([l], _) when is_list(l), do: List.flatten(l)
def discard([], _), do: []
def lift([c, l], locals) when is_list(l), do: compute_expr([c | l], locals)
# TODO: iterate, scanterate
# def iterate(n, c, f | rest], _) when is_number(n) do
# rest = [f | rest]
# end
# TODO: need to better differentiate between callable/identifier, as atoms can be both. See what kamilalisp does
def type([x], _) when is_list(x), do: "list"
def type([x], _) when is_binary(x), do: "string"
def type([x], _) when is_integer(x), do: "integer"
def type([x], _) when is_number(x), do: "real"
def type([x], _) when is_atom(x), do: "identifier"
def type([x], _) when is_function(x), do: "callable"
def type([%Complex{}], _), do: "complex"
def type([%Tensor.Tensor{}], _), do: "matrix"
def to_string([x], _), do: to_string(x)
def parse_num([str], _) when is_binary(str) do
with {:ok, [token], _} <- :lexer.string(String.to_charlist(str)),
{type, _, _} when type in @num_tokens <- token do
Kamex.Parser.parse(token)
else
_ ->
raise Exceptions.IllegalTypeError, message: "parse_num: expected valid number string"
end
end
# TODO: eval, memo, parse, dyad, monad
def list_env([], locals), do: Map.keys(locals)
# TODO: import
def size([str], _) when is_binary(str), do: String.length(str)
def size([l], _) when is_list(l), do: length(l)
def empty?([x], _) when x == [] or x == "", do: true
def empty?([x], _) when is_list(x) or is_binary(x), do: false
# TODO: cmp-ex is gonna be a doozy
end
| 29.506494 | 114 | 0.59529 |
1c3723751bc65afaa9f94dd0d0d732c6f6365956 | 792 | exs | Elixir | test/pi_test.exs | versilov/pi | f81dc4b4a4b16920dfe9fc528533c7763813a1cd | [
"BSD-3-Clause"
] | 5 | 2021-03-05T09:03:31.000Z | 2021-03-20T04:45:09.000Z | test/pi_test.exs | versilov/pi | f81dc4b4a4b16920dfe9fc528533c7763813a1cd | [
"BSD-3-Clause"
] | null | null | null | test/pi_test.exs | versilov/pi | f81dc4b4a4b16920dfe9fc528533c7763813a1cd | [
"BSD-3-Clause"
] | null | null | null | defmodule PI.Test do
use ExUnit.Case, async: true
import ExUnit.CaptureIO, only: [capture_io: 1]
use PI
test "inspect with module, func, file & line number" do
object = %{some: "value", barcode: 123}
timestamp = PI.timestamp() |> String.replace(~r/\d{2}:\d{2}$/, "00:00")
expected =
"\n#{timestamp} \e[33m[test/pi_test.exs:#{__ENV__.line + 4}: PI.Test.test inspect with module, func, file & line number/1]\n\e[1m\e[37m\e[48;5;18mPI Label\e[0m: \e[93m%{\e[0m\e[36mbarcode:\e[0m \e[31m123\e[0m\e[93m,\e[0m \e[36msome:\e[0m \e[32m\"value\"\e[0m\e[93m}\e[0m\n"
result =
capture_io(fn ->
assert pi(object, "PI Label") == object
end)
|> String.replace(~r/^(\n\d{2}:)\d{2}:\d{2} /, "\\g{1}00:00 ")
assert result == expected
end
end
| 34.434783 | 279 | 0.602273 |
1c372d112cfaca4ad3c621906ffb75b618984565 | 111,603 | ex | Elixir | test/support/stellar/Stellar.XDR_generated.ex | revelrylabs/exdr | 4a3a5d65e2d0ba2daba32c5f648cbe401176e2e1 | [
"MIT"
] | 3 | 2020-01-12T03:16:38.000Z | 2020-09-06T03:37:03.000Z | test/support/stellar/Stellar.XDR_generated.ex | revelrylabs/exdr | 4a3a5d65e2d0ba2daba32c5f648cbe401176e2e1 | [
"MIT"
] | 7 | 2019-10-14T14:27:31.000Z | 2020-05-01T22:27:52.000Z | test/support/stellar/Stellar.XDR_generated.ex | revelrylabs/exdr | 4a3a5d65e2d0ba2daba32c5f648cbe401176e2e1 | [
"MIT"
] | 1 | 2020-02-06T23:19:24.000Z | 2020-02-06T23:19:24.000Z | defmodule Stellar.XDR do
@moduledoc """
Automatically generated on 2019-11-06T08:55:43-06:00
DO NOT EDIT or your changes may be overwritten
Target implementation: exdr at https://hex.pm/packages/exdr
"""
use XDR.Base
comment(~S"""
=== xdr source ============================================================
enum ErrorCode
{
ERR_MISC = 0, // Unspecific error
ERR_DATA = 1, // Malformed data
ERR_CONF = 2, // Misconfiguration error
ERR_AUTH = 3, // Authentication failure
ERR_LOAD = 4 // System overloaded
};
===========================================================================
""")
define_type("ErrorCode", Enum,
err_misc: 0,
err_datum: 1,
err_conf: 2,
err_auth: 3,
err_load: 4
)
comment(~S"""
=== xdr source ============================================================
struct Error
{
ErrorCode code;
string msg<100>;
};
===========================================================================
""")
define_type("Error", Struct,
code: "ErrorCode",
msg: build_type(XDR.Type.String, 100)
)
comment(~S"""
=== xdr source ============================================================
struct AuthCert
{
Curve25519Public pubkey;
uint64 expiration;
Signature sig;
};
===========================================================================
""")
define_type("AuthCert", Struct,
pubkey: "Curve25519Public",
expiration: "Uint64",
sig: "Signature"
)
comment(~S"""
=== xdr source ============================================================
struct Hello
{
uint32 ledgerVersion;
uint32 overlayVersion;
uint32 overlayMinVersion;
Hash networkID;
string versionStr<100>;
int listeningPort;
NodeID peerID;
AuthCert cert;
uint256 nonce;
};
===========================================================================
""")
define_type("Hello", Struct,
ledger_version: "Uint32",
overlay_version: "Uint32",
overlay_min_version: "Uint32",
network_id: "Hash",
version_str: build_type(XDR.Type.String, 100),
listening_port: build_type(Int),
peer_id: "NodeId",
cert: "AuthCert",
nonce: "Uint256"
)
comment(~S"""
=== xdr source ============================================================
struct Auth
{
// Empty message, just to confirm
// establishment of MAC keys.
int unused;
};
===========================================================================
""")
define_type("Auth", Struct, unused: build_type(Int))
comment(~S"""
=== xdr source ============================================================
enum IPAddrType
{
IPv4 = 0,
IPv6 = 1
};
===========================================================================
""")
define_type("IpAddrType", Enum,
i_pv4: 0,
i_pv6: 1
)
comment(~S"""
=== xdr source ============================================================
union switch (IPAddrType type)
{
case IPv4:
opaque ipv4[4];
case IPv6:
opaque ipv6[16];
}
===========================================================================
""")
define_type("PeerAddressIp", Union,
switch_type: "IpAddrType",
switch_name: :type,
switches: [
{:i_pv4, :ipv4},
{:i_pv6, :ipv6}
],
arms: [
ipv4: build_type(Opaque, 4),
ipv6: build_type(Opaque, 16)
]
)
comment(~S"""
=== xdr source ============================================================
struct PeerAddress
{
union switch (IPAddrType type)
{
case IPv4:
opaque ipv4[4];
case IPv6:
opaque ipv6[16];
}
ip;
uint32 port;
uint32 numFailures;
};
===========================================================================
""")
define_type("PeerAddress", Struct,
ip: "PeerAddressIp",
port: "Uint32",
num_failures: "Uint32"
)
comment(~S"""
=== xdr source ============================================================
enum MessageType
{
ERROR_MSG = 0,
AUTH = 2,
DONT_HAVE = 3,
GET_PEERS = 4, // gets a list of peers this guy knows about
PEERS = 5,
GET_TX_SET = 6, // gets a particular txset by hash
TX_SET = 7,
TRANSACTION = 8, // pass on a tx you have heard about
// SCP
GET_SCP_QUORUMSET = 9,
SCP_QUORUMSET = 10,
SCP_MESSAGE = 11,
GET_SCP_STATE = 12,
// new messages
HELLO = 13
};
===========================================================================
""")
define_type("MessageType", Enum,
error_msg: 0,
auth: 2,
dont_have: 3,
get_peer: 4,
peer: 5,
get_tx_set: 6,
tx_set: 7,
transaction: 8,
get_scp_quorumset: 9,
scp_quorumset: 10,
scp_message: 11,
get_scp_state: 12,
hello: 13
)
comment(~S"""
=== xdr source ============================================================
struct DontHave
{
MessageType type;
uint256 reqHash;
};
===========================================================================
""")
define_type("DontHave", Struct,
type: "MessageType",
req_hash: "Uint256"
)
comment(~S"""
=== xdr source ============================================================
union StellarMessage switch (MessageType type)
{
case ERROR_MSG:
Error error;
case HELLO:
Hello hello;
case AUTH:
Auth auth;
case DONT_HAVE:
DontHave dontHave;
case GET_PEERS:
void;
case PEERS:
PeerAddress peers<100>;
case GET_TX_SET:
uint256 txSetHash;
case TX_SET:
TransactionSet txSet;
case TRANSACTION:
TransactionEnvelope transaction;
// SCP
case GET_SCP_QUORUMSET:
uint256 qSetHash;
case SCP_QUORUMSET:
SCPQuorumSet qSet;
case SCP_MESSAGE:
StellarMessage envelope;
case GET_SCP_STATE:
uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest
};
===========================================================================
""")
define_type("StellarMessage", Union,
switch_type: "MessageType",
switch_name: :type,
switches: [
{:error_msg, :error},
{:hello, :hello},
{:auth, :auth},
{:dont_have, :dont_have},
{:get_peer, XDR.Type.Void},
{:peer, :peers},
{:get_tx_set, :tx_set_hash},
{:tx_set, :tx_set},
{:transaction, :transaction},
{:get_scp_quorumset, :q_set_hash},
{:scp_quorumset, :q_set},
{:scp_message, :envelope},
{:get_scp_state, :get_scp_ledger_seq}
],
arms: [
error: "Error",
hello: "Hello",
auth: "Auth",
dont_have: "DontHave",
peers: build_type(VariableArray, max_length: 100, type: "PeerAddress"),
tx_set_hash: "Uint256",
tx_set: "TransactionSet",
transaction: "TransactionEnvelope",
q_set_hash: "Uint256",
q_set: "ScpQuorumSet",
envelope: "StellarMessage",
get_scp_ledger_seq: "Uint32"
]
)
comment(~S"""
=== xdr source ============================================================
struct
{
uint64 sequence;
StellarMessage message;
HmacSha256Mac mac;
}
===========================================================================
""")
define_type("AuthenticatedMessageV0", Struct,
sequence: "Uint64",
message: "StellarMessage",
mac: "HmacSha256Mac"
)
comment(~S"""
=== xdr source ============================================================
union AuthenticatedMessage switch (uint32 v)
{
case 0:
struct
{
uint64 sequence;
StellarMessage message;
HmacSha256Mac mac;
} v0;
};
===========================================================================
""")
define_type("AuthenticatedMessage", Union,
switch_type: "Uint32",
switch_name: :v,
switches: [
{0, :v0}
],
arms: [
v0: "AuthenticatedMessageV0"
]
)
comment(~S"""
=== xdr source ============================================================
typedef opaque Hash[32];
===========================================================================
""")
define_type("Hash", Opaque, 32)
comment(~S"""
=== xdr source ============================================================
typedef opaque uint256[32];
===========================================================================
""")
define_type("Uint256", Opaque, 32)
comment(~S"""
=== xdr source ============================================================
typedef unsigned int uint32;
===========================================================================
""")
define_type("Uint32", UnsignedInt)
comment(~S"""
=== xdr source ============================================================
typedef int int32;
===========================================================================
""")
define_type("Int32", Int)
comment(~S"""
=== xdr source ============================================================
typedef unsigned hyper uint64;
===========================================================================
""")
define_type("Uint64", UnsignedHyperInt)
comment(~S"""
=== xdr source ============================================================
typedef hyper int64;
===========================================================================
""")
define_type("Int64", HyperInt)
comment(~S"""
=== xdr source ============================================================
enum CryptoKeyType
{
KEY_TYPE_ED25519 = 0,
KEY_TYPE_PRE_AUTH_TX = 1,
KEY_TYPE_HASH_X = 2
};
===========================================================================
""")
define_type("CryptoKeyType", Enum,
key_type_ed25519: 0,
key_type_pre_auth_tx: 1,
key_type_hash_x: 2
)
comment(~S"""
=== xdr source ============================================================
enum PublicKeyType
{
PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519
};
===========================================================================
""")
define_type("PublicKeyType", Enum, public_key_type_ed25519: 0)
comment(~S"""
=== xdr source ============================================================
enum SignerKeyType
{
SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519,
SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX,
SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X
};
===========================================================================
""")
define_type("SignerKeyType", Enum,
signer_key_type_ed25519: 0,
signer_key_type_pre_auth_tx: 1,
signer_key_type_hash_x: 2
)
comment(~S"""
=== xdr source ============================================================
union PublicKey switch (PublicKeyType type)
{
case PUBLIC_KEY_TYPE_ED25519:
uint256 ed25519;
};
===========================================================================
""")
define_type("PublicKey", Union,
switch_type: "PublicKeyType",
switch_name: :type,
switches: [
{:public_key_type_ed25519, :ed25519}
],
arms: [
ed25519: "Uint256"
]
)
comment(~S"""
=== xdr source ============================================================
union SignerKey switch (SignerKeyType type)
{
case SIGNER_KEY_TYPE_ED25519:
uint256 ed25519;
case SIGNER_KEY_TYPE_PRE_AUTH_TX:
/* SHA-256 Hash of TransactionSignaturePayload structure */
uint256 preAuthTx;
case SIGNER_KEY_TYPE_HASH_X:
/* Hash of random 256 bit preimage X */
uint256 hashX;
};
===========================================================================
""")
define_type("SignerKey", Union,
switch_type: "SignerKeyType",
switch_name: :type,
switches: [
{:signer_key_type_ed25519, :ed25519},
{:signer_key_type_pre_auth_tx, :pre_auth_tx},
{:signer_key_type_hash_x, :hash_x}
],
arms: [
ed25519: "Uint256",
pre_auth_tx: "Uint256",
hash_x: "Uint256"
]
)
comment(~S"""
=== xdr source ============================================================
typedef opaque Signature<64>;
===========================================================================
""")
define_type("Signature", VariableOpaque, 64)
comment(~S"""
=== xdr source ============================================================
typedef opaque SignatureHint[4];
===========================================================================
""")
define_type("SignatureHint", Opaque, 4)
comment(~S"""
=== xdr source ============================================================
typedef PublicKey NodeID;
===========================================================================
""")
define_type("NodeId", "PublicKey")
comment(~S"""
=== xdr source ============================================================
struct Curve25519Secret
{
opaque key[32];
};
===========================================================================
""")
define_type("Curve25519Secret", Struct, key: build_type(Opaque, 32))
comment(~S"""
=== xdr source ============================================================
struct Curve25519Public
{
opaque key[32];
};
===========================================================================
""")
define_type("Curve25519Public", Struct, key: build_type(Opaque, 32))
comment(~S"""
=== xdr source ============================================================
struct HmacSha256Key
{
opaque key[32];
};
===========================================================================
""")
define_type("HmacSha256Key", Struct, key: build_type(Opaque, 32))
comment(~S"""
=== xdr source ============================================================
struct HmacSha256Mac
{
opaque mac[32];
};
===========================================================================
""")
define_type("HmacSha256Mac", Struct, mac: build_type(Opaque, 32))
comment(~S"""
=== xdr source ============================================================
struct DecoratedSignature
{
SignatureHint hint; // last 4 bytes of the public key, used as a hint
Signature signature; // actual signature
};
===========================================================================
""")
define_type("DecoratedSignature", Struct,
hint: "SignatureHint",
signature: "Signature"
)
comment(~S"""
=== xdr source ============================================================
enum OperationType
{
CREATE_ACCOUNT = 0,
PAYMENT = 1,
PATH_PAYMENT = 2,
MANAGE_OFFER = 3,
CREATE_PASSIVE_OFFER = 4,
SET_OPTIONS = 5,
CHANGE_TRUST = 6,
ALLOW_TRUST = 7,
ACCOUNT_MERGE = 8,
INFLATION = 9,
MANAGE_DATA = 10,
BUMP_SEQUENCE = 11
};
===========================================================================
""")
define_type("OperationType", Enum,
create_account: 0,
payment: 1,
path_payment: 2,
manage_offer: 3,
create_passive_offer: 4,
set_option: 5,
change_trust: 6,
allow_trust: 7,
account_merge: 8,
inflation: 9,
manage_datum: 10,
bump_sequence: 11
)
comment(~S"""
=== xdr source ============================================================
struct CreateAccountOp
{
AccountID destination; // account to create
int64 startingBalance; // amount they end up with
};
===========================================================================
""")
define_type("CreateAccountOp", Struct,
destination: "AccountId",
starting_balance: "Int64"
)
comment(~S"""
=== xdr source ============================================================
struct PaymentOp
{
AccountID destination; // recipient of the payment
Asset asset; // what they end up with
int64 amount; // amount they end up with
};
===========================================================================
""")
define_type("PaymentOp", Struct,
destination: "AccountId",
asset: "Asset",
amount: "Int64"
)
comment(~S"""
=== xdr source ============================================================
struct PathPaymentOp
{
Asset sendAsset; // asset we pay with
int64 sendMax; // the maximum amount of sendAsset to
// send (excluding fees).
// The operation will fail if can't be met
AccountID destination; // recipient of the payment
Asset destAsset; // what they end up with
int64 destAmount; // amount they end up with
Asset path<5>; // additional hops it must go through to get there
};
===========================================================================
""")
define_type("PathPaymentOp", Struct,
send_asset: "Asset",
send_max: "Int64",
destination: "AccountId",
dest_asset: "Asset",
dest_amount: "Int64",
path: build_type(VariableArray, max_length: 5, type: "Asset")
)
comment(~S"""
=== xdr source ============================================================
struct ManageOfferOp
{
Asset selling;
Asset buying;
int64 amount; // amount being sold. if set to 0, delete the offer
Price price; // price of thing being sold in terms of what you are buying
// 0=create a new offer, otherwise edit an existing offer
uint64 offerID;
};
===========================================================================
""")
define_type("ManageOfferOp", Struct,
selling: "Asset",
buying: "Asset",
amount: "Int64",
price: "Price",
offer_id: "Uint64"
)
comment(~S"""
=== xdr source ============================================================
struct CreatePassiveOfferOp
{
Asset selling; // A
Asset buying; // B
int64 amount; // amount taker gets. if set to 0, delete the offer
Price price; // cost of A in terms of B
};
===========================================================================
""")
define_type("CreatePassiveOfferOp", Struct,
selling: "Asset",
buying: "Asset",
amount: "Int64",
price: "Price"
)
comment(~S"""
=== xdr source ============================================================
struct SetOptionsOp
{
AccountID* inflationDest; // sets the inflation destination
uint32* clearFlags; // which flags to clear
uint32* setFlags; // which flags to set
// account threshold manipulation
uint32* masterWeight; // weight of the master account
uint32* lowThreshold;
uint32* medThreshold;
uint32* highThreshold;
string32* homeDomain; // sets the home domain
// Add, update or remove a signer for the account
// signer is deleted if the weight is 0
Signer* signer;
};
===========================================================================
""")
define_type("SetOptionsOp", Struct,
inflation_dest: build_type(Optional, "AccountId"),
clear_flags: build_type(Optional, "Uint32"),
set_flags: build_type(Optional, "Uint32"),
master_weight: build_type(Optional, "Uint32"),
low_threshold: build_type(Optional, "Uint32"),
med_threshold: build_type(Optional, "Uint32"),
high_threshold: build_type(Optional, "Uint32"),
home_domain: build_type(Optional, "String32"),
signer: build_type(Optional, "Signer")
)
comment(~S"""
=== xdr source ============================================================
struct ChangeTrustOp
{
Asset line;
// if limit is set to 0, deletes the trust line
int64 limit;
};
===========================================================================
""")
define_type("ChangeTrustOp", Struct,
line: "Asset",
limit: "Int64"
)
comment(~S"""
=== xdr source ============================================================
union switch (AssetType type)
{
// ASSET_TYPE_NATIVE is not allowed
case ASSET_TYPE_CREDIT_ALPHANUM4:
opaque assetCode4[4];
case ASSET_TYPE_CREDIT_ALPHANUM12:
opaque assetCode12[12];
// add other asset types here in the future
}
===========================================================================
""")
define_type("AllowTrustOpAsset", Union,
switch_type: "AssetType",
switch_name: :type,
switches: [
{:asset_type_credit_alphanum4, :asset_code4},
{:asset_type_credit_alphanum12, :asset_code12}
],
arms: [
asset_code4: build_type(Opaque, 4),
asset_code12: build_type(Opaque, 12)
]
)
comment(~S"""
=== xdr source ============================================================
struct AllowTrustOp
{
AccountID trustor;
union switch (AssetType type)
{
// ASSET_TYPE_NATIVE is not allowed
case ASSET_TYPE_CREDIT_ALPHANUM4:
opaque assetCode4[4];
case ASSET_TYPE_CREDIT_ALPHANUM12:
opaque assetCode12[12];
// add other asset types here in the future
}
asset;
bool authorize;
};
===========================================================================
""")
define_type("AllowTrustOp", Struct,
trustor: "AccountId",
asset: "AllowTrustOpAsset",
authorize: build_type(Bool)
)
comment(~S"""
=== xdr source ============================================================
struct ManageDataOp
{
string64 dataName;
DataValue* dataValue; // set to null to clear
};
===========================================================================
""")
define_type("ManageDataOp", Struct,
data_name: "String64",
data_value: build_type(Optional, "DataValue")
)
comment(~S"""
=== xdr source ============================================================
struct BumpSequenceOp
{
SequenceNumber bumpTo;
};
===========================================================================
""")
define_type("BumpSequenceOp", Struct, bump_to: "SequenceNumber")
comment(~S"""
=== xdr source ============================================================
union switch (OperationType type)
{
case CREATE_ACCOUNT:
CreateAccountOp createAccountOp;
case PAYMENT:
PaymentOp paymentOp;
case PATH_PAYMENT:
PathPaymentOp pathPaymentOp;
case MANAGE_OFFER:
ManageOfferOp manageOfferOp;
case CREATE_PASSIVE_OFFER:
CreatePassiveOfferOp createPassiveOfferOp;
case SET_OPTIONS:
SetOptionsOp setOptionsOp;
case CHANGE_TRUST:
ChangeTrustOp changeTrustOp;
case ALLOW_TRUST:
AllowTrustOp allowTrustOp;
case ACCOUNT_MERGE:
AccountID destination;
case INFLATION:
void;
case MANAGE_DATA:
ManageDataOp manageDataOp;
case BUMP_SEQUENCE:
BumpSequenceOp bumpSequenceOp;
}
===========================================================================
""")
define_type("OperationBody", Union,
switch_type: "OperationType",
switch_name: :type,
switches: [
{:create_account, :create_account_op},
{:payment, :payment_op},
{:path_payment, :path_payment_op},
{:manage_offer, :manage_offer_op},
{:create_passive_offer, :create_passive_offer_op},
{:set_option, :set_options_op},
{:change_trust, :change_trust_op},
{:allow_trust, :allow_trust_op},
{:account_merge, :destination},
{:inflation, XDR.Type.Void},
{:manage_datum, :manage_data_op},
{:bump_sequence, :bump_sequence_op}
],
arms: [
create_account_op: "CreateAccountOp",
payment_op: "PaymentOp",
path_payment_op: "PathPaymentOp",
manage_offer_op: "ManageOfferOp",
create_passive_offer_op: "CreatePassiveOfferOp",
set_options_op: "SetOptionsOp",
change_trust_op: "ChangeTrustOp",
allow_trust_op: "AllowTrustOp",
destination: "AccountId",
manage_data_op: "ManageDataOp",
bump_sequence_op: "BumpSequenceOp"
]
)
comment(~S"""
=== xdr source ============================================================
struct Operation
{
// sourceAccount is the account used to run the operation
// if not set, the runtime defaults to "sourceAccount" specified at
// the transaction level
AccountID* sourceAccount;
union switch (OperationType type)
{
case CREATE_ACCOUNT:
CreateAccountOp createAccountOp;
case PAYMENT:
PaymentOp paymentOp;
case PATH_PAYMENT:
PathPaymentOp pathPaymentOp;
case MANAGE_OFFER:
ManageOfferOp manageOfferOp;
case CREATE_PASSIVE_OFFER:
CreatePassiveOfferOp createPassiveOfferOp;
case SET_OPTIONS:
SetOptionsOp setOptionsOp;
case CHANGE_TRUST:
ChangeTrustOp changeTrustOp;
case ALLOW_TRUST:
AllowTrustOp allowTrustOp;
case ACCOUNT_MERGE:
AccountID destination;
case INFLATION:
void;
case MANAGE_DATA:
ManageDataOp manageDataOp;
case BUMP_SEQUENCE:
BumpSequenceOp bumpSequenceOp;
}
body;
};
===========================================================================
""")
define_type("Operation", Struct,
source_account: build_type(Optional, "AccountId"),
body: "OperationBody"
)
comment(~S"""
=== xdr source ============================================================
enum MemoType
{
MEMO_NONE = 0,
MEMO_TEXT = 1,
MEMO_ID = 2,
MEMO_HASH = 3,
MEMO_RETURN = 4
};
===========================================================================
""")
define_type("MemoType", Enum,
memo_none: 0,
memo_text: 1,
memo_id: 2,
memo_hash: 3,
memo_return: 4
)
comment(~S"""
=== xdr source ============================================================
union Memo switch (MemoType type)
{
case MEMO_NONE:
void;
case MEMO_TEXT:
string text<28>;
case MEMO_ID:
uint64 id;
case MEMO_HASH:
Hash hash; // the hash of what to pull from the content server
case MEMO_RETURN:
Hash retHash; // the hash of the tx you are rejecting
};
===========================================================================
""")
define_type("Memo", Union,
switch_type: "MemoType",
switch_name: :type,
switches: [
{:memo_none, XDR.Type.Void},
{:memo_text, :text},
{:memo_id, :id},
{:memo_hash, :hash},
{:memo_return, :ret_hash}
],
arms: [
text: build_type(XDR.Type.String, 28),
id: "Uint64",
hash: "Hash",
ret_hash: "Hash"
]
)
comment(~S"""
=== xdr source ============================================================
struct TimeBounds
{
uint64 minTime;
uint64 maxTime; // 0 here means no maxTime
};
===========================================================================
""")
define_type("TimeBounds", Struct,
min_time: "Uint64",
max_time: "Uint64"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("TransactionExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct Transaction
{
// account used to run the transaction
AccountID sourceAccount;
// the fee the sourceAccount will pay
uint32 fee;
// sequence number to consume in the account
SequenceNumber seqNum;
// validity range (inclusive) for the last ledger close time
TimeBounds* timeBounds;
Memo memo;
Operation operations<100>;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("Transaction", Struct,
source_account: "AccountId",
fee: "Uint32",
seq_num: "SequenceNumber",
time_bounds: build_type(Optional, "TimeBounds"),
memo: "Memo",
operations: build_type(VariableArray, max_length: 100, type: "Operation"),
ext: "TransactionExt"
)
comment(~S"""
=== xdr source ============================================================
union switch (EnvelopeType type)
{
case ENVELOPE_TYPE_TX:
Transaction tx;
/* All other values of type are invalid */
}
===========================================================================
""")
define_type("TransactionSignaturePayloadTaggedTransaction", Union,
switch_type: "EnvelopeType",
switch_name: :type,
switches: [
{:envelope_type_tx, :tx}
],
arms: [
tx: "Transaction"
]
)
comment(~S"""
=== xdr source ============================================================
struct TransactionSignaturePayload
{
Hash networkId;
union switch (EnvelopeType type)
{
case ENVELOPE_TYPE_TX:
Transaction tx;
/* All other values of type are invalid */
}
taggedTransaction;
};
===========================================================================
""")
define_type("TransactionSignaturePayload", Struct,
network_id: "Hash",
tagged_transaction: "TransactionSignaturePayloadTaggedTransaction"
)
comment(~S"""
=== xdr source ============================================================
struct TransactionEnvelope
{
Transaction tx;
/* Each decorated signature is a signature over the SHA256 hash of
* a TransactionSignaturePayload */
DecoratedSignature signatures<20>;
};
===========================================================================
""")
define_type("TransactionEnvelope", Struct,
tx: "Transaction",
signatures: build_type(VariableArray, max_length: 20, type: "DecoratedSignature")
)
comment(~S"""
=== xdr source ============================================================
struct ClaimOfferAtom
{
// emitted to identify the offer
AccountID sellerID; // Account that owns the offer
uint64 offerID;
// amount and asset taken from the owner
Asset assetSold;
int64 amountSold;
// amount and asset sent to the owner
Asset assetBought;
int64 amountBought;
};
===========================================================================
""")
define_type("ClaimOfferAtom", Struct,
seller_id: "AccountId",
offer_id: "Uint64",
asset_sold: "Asset",
amount_sold: "Int64",
asset_bought: "Asset",
amount_bought: "Int64"
)
comment(~S"""
=== xdr source ============================================================
enum CreateAccountResultCode
{
// codes considered as "success" for the operation
CREATE_ACCOUNT_SUCCESS = 0, // account was created
// codes considered as "failure" for the operation
CREATE_ACCOUNT_MALFORMED = -1, // invalid destination
CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account
CREATE_ACCOUNT_LOW_RESERVE =
-3, // would create an account below the min reserve
CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists
};
===========================================================================
""")
define_type("CreateAccountResultCode", Enum,
create_account_success: 0,
create_account_malformed: -1,
create_account_underfunded: -2,
create_account_low_reserve: -3,
create_account_already_exist: -4
)
comment(~S"""
=== xdr source ============================================================
union CreateAccountResult switch (CreateAccountResultCode code)
{
case CREATE_ACCOUNT_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("CreateAccountResult", Union,
switch_type: "CreateAccountResultCode",
switch_name: :code,
switches: [
{:create_account_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum PaymentResultCode
{
// codes considered as "success" for the operation
PAYMENT_SUCCESS = 0, // payment successfuly completed
// codes considered as "failure" for the operation
PAYMENT_MALFORMED = -1, // bad input
PAYMENT_UNDERFUNDED = -2, // not enough funds in source account
PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account
PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer
PAYMENT_NO_DESTINATION = -5, // destination account does not exist
PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset
PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset
PAYMENT_LINE_FULL = -8, // destination would go above their limit
PAYMENT_NO_ISSUER = -9 // missing issuer on asset
};
===========================================================================
""")
define_type("PaymentResultCode", Enum,
payment_success: 0,
payment_malformed: -1,
payment_underfunded: -2,
payment_src_no_trust: -3,
payment_src_not_authorized: -4,
payment_no_destination: -5,
payment_no_trust: -6,
payment_not_authorized: -7,
payment_line_full: -8,
payment_no_issuer: -9
)
comment(~S"""
=== xdr source ============================================================
union PaymentResult switch (PaymentResultCode code)
{
case PAYMENT_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("PaymentResult", Union,
switch_type: "PaymentResultCode",
switch_name: :code,
switches: [
{:payment_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum PathPaymentResultCode
{
// codes considered as "success" for the operation
PATH_PAYMENT_SUCCESS = 0, // success
// codes considered as "failure" for the operation
PATH_PAYMENT_MALFORMED = -1, // bad input
PATH_PAYMENT_UNDERFUNDED = -2, // not enough funds in source account
PATH_PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account
PATH_PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer
PATH_PAYMENT_NO_DESTINATION = -5, // destination account does not exist
PATH_PAYMENT_NO_TRUST = -6, // dest missing a trust line for asset
PATH_PAYMENT_NOT_AUTHORIZED = -7, // dest not authorized to hold asset
PATH_PAYMENT_LINE_FULL = -8, // dest would go above their limit
PATH_PAYMENT_NO_ISSUER = -9, // missing issuer on one asset
PATH_PAYMENT_TOO_FEW_OFFERS = -10, // not enough offers to satisfy path
PATH_PAYMENT_OFFER_CROSS_SELF = -11, // would cross one of its own offers
PATH_PAYMENT_OVER_SENDMAX = -12 // could not satisfy sendmax
};
===========================================================================
""")
define_type("PathPaymentResultCode", Enum,
path_payment_success: 0,
path_payment_malformed: -1,
path_payment_underfunded: -2,
path_payment_src_no_trust: -3,
path_payment_src_not_authorized: -4,
path_payment_no_destination: -5,
path_payment_no_trust: -6,
path_payment_not_authorized: -7,
path_payment_line_full: -8,
path_payment_no_issuer: -9,
path_payment_too_few_offer: -10,
path_payment_offer_cross_self: -11,
path_payment_over_sendmax: -12
)
comment(~S"""
=== xdr source ============================================================
struct SimplePaymentResult
{
AccountID destination;
Asset asset;
int64 amount;
};
===========================================================================
""")
define_type("SimplePaymentResult", Struct,
destination: "AccountId",
asset: "Asset",
amount: "Int64"
)
comment(~S"""
=== xdr source ============================================================
struct
{
ClaimOfferAtom offers<>;
SimplePaymentResult last;
}
===========================================================================
""")
define_type("PathPaymentResultSuccess", Struct,
offers: build_type(VariableArray, max_length: 2_147_483_647, type: "ClaimOfferAtom"),
last: "SimplePaymentResult"
)
comment(~S"""
=== xdr source ============================================================
union PathPaymentResult switch (PathPaymentResultCode code)
{
case PATH_PAYMENT_SUCCESS:
struct
{
ClaimOfferAtom offers<>;
SimplePaymentResult last;
} success;
case PATH_PAYMENT_NO_ISSUER:
Asset noIssuer; // the asset that caused the error
default:
void;
};
===========================================================================
""")
define_type("PathPaymentResult", Union,
switch_type: "PathPaymentResultCode",
switch_name: :code,
switches: [
{:path_payment_success, :success},
{:path_payment_no_issuer, :no_issuer}
],
arms: [
success: "PathPaymentResultSuccess",
no_issuer: "Asset"
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum ManageOfferResultCode
{
// codes considered as "success" for the operation
MANAGE_OFFER_SUCCESS = 0,
// codes considered as "failure" for the operation
MANAGE_OFFER_MALFORMED = -1, // generated offer would be invalid
MANAGE_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling
MANAGE_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying
MANAGE_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell
MANAGE_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy
MANAGE_OFFER_LINE_FULL = -6, // can't receive more of what it's buying
MANAGE_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell
MANAGE_OFFER_CROSS_SELF = -8, // would cross an offer from the same user
MANAGE_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling
MANAGE_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying
// update errors
MANAGE_OFFER_NOT_FOUND = -11, // offerID does not match an existing offer
MANAGE_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer
};
===========================================================================
""")
define_type("ManageOfferResultCode", Enum,
manage_offer_success: 0,
manage_offer_malformed: -1,
manage_offer_sell_no_trust: -2,
manage_offer_buy_no_trust: -3,
manage_offer_sell_not_authorized: -4,
manage_offer_buy_not_authorized: -5,
manage_offer_line_full: -6,
manage_offer_underfunded: -7,
manage_offer_cross_self: -8,
manage_offer_sell_no_issuer: -9,
manage_offer_buy_no_issuer: -10,
manage_offer_not_found: -11,
manage_offer_low_reserve: -12
)
comment(~S"""
=== xdr source ============================================================
enum ManageOfferEffect
{
MANAGE_OFFER_CREATED = 0,
MANAGE_OFFER_UPDATED = 1,
MANAGE_OFFER_DELETED = 2
};
===========================================================================
""")
define_type("ManageOfferEffect", Enum,
manage_offer_created: 0,
manage_offer_updated: 1,
manage_offer_deleted: 2
)
comment(~S"""
=== xdr source ============================================================
union switch (ManageOfferEffect effect)
{
case MANAGE_OFFER_CREATED:
case MANAGE_OFFER_UPDATED:
OfferEntry offer;
default:
void;
}
===========================================================================
""")
define_type("ManageOfferSuccessResultOffer", Union,
switch_type: "ManageOfferEffect",
switch_name: :effect,
switches: [
{:manage_offer_created, :offer},
{:manage_offer_updated, :offer}
],
arms: [
offer: "OfferEntry"
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
struct ManageOfferSuccessResult
{
// offers that got claimed while creating this offer
ClaimOfferAtom offersClaimed<>;
union switch (ManageOfferEffect effect)
{
case MANAGE_OFFER_CREATED:
case MANAGE_OFFER_UPDATED:
OfferEntry offer;
default:
void;
}
offer;
};
===========================================================================
""")
define_type("ManageOfferSuccessResult", Struct,
offers_claimed: build_type(VariableArray, max_length: 2_147_483_647, type: "ClaimOfferAtom"),
offer: "ManageOfferSuccessResultOffer"
)
comment(~S"""
=== xdr source ============================================================
union ManageOfferResult switch (ManageOfferResultCode code)
{
case MANAGE_OFFER_SUCCESS:
ManageOfferSuccessResult success;
default:
void;
};
===========================================================================
""")
define_type("ManageOfferResult", Union,
switch_type: "ManageOfferResultCode",
switch_name: :code,
switches: [
{:manage_offer_success, :success}
],
arms: [
success: "ManageOfferSuccessResult"
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum SetOptionsResultCode
{
// codes considered as "success" for the operation
SET_OPTIONS_SUCCESS = 0,
// codes considered as "failure" for the operation
SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer
SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached
SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags
SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist
SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option
SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag
SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold
SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey
SET_OPTIONS_INVALID_HOME_DOMAIN = -9 // malformed home domain
};
===========================================================================
""")
define_type("SetOptionsResultCode", Enum,
set_options_success: 0,
set_options_low_reserve: -1,
set_options_too_many_signer: -2,
set_options_bad_flag: -3,
set_options_invalid_inflation: -4,
set_options_cant_change: -5,
set_options_unknown_flag: -6,
set_options_threshold_out_of_range: -7,
set_options_bad_signer: -8,
set_options_invalid_home_domain: -9
)
comment(~S"""
=== xdr source ============================================================
union SetOptionsResult switch (SetOptionsResultCode code)
{
case SET_OPTIONS_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("SetOptionsResult", Union,
switch_type: "SetOptionsResultCode",
switch_name: :code,
switches: [
{:set_options_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum ChangeTrustResultCode
{
// codes considered as "success" for the operation
CHANGE_TRUST_SUCCESS = 0,
// codes considered as "failure" for the operation
CHANGE_TRUST_MALFORMED = -1, // bad input
CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer
CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance
// cannot create with a limit of 0
CHANGE_TRUST_LOW_RESERVE =
-4, // not enough funds to create a new trust line,
CHANGE_TRUST_SELF_NOT_ALLOWED = -5 // trusting self is not allowed
};
===========================================================================
""")
define_type("ChangeTrustResultCode", Enum,
change_trust_success: 0,
change_trust_malformed: -1,
change_trust_no_issuer: -2,
change_trust_invalid_limit: -3,
change_trust_low_reserve: -4,
change_trust_self_not_allowed: -5
)
comment(~S"""
=== xdr source ============================================================
union ChangeTrustResult switch (ChangeTrustResultCode code)
{
case CHANGE_TRUST_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("ChangeTrustResult", Union,
switch_type: "ChangeTrustResultCode",
switch_name: :code,
switches: [
{:change_trust_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum AllowTrustResultCode
{
// codes considered as "success" for the operation
ALLOW_TRUST_SUCCESS = 0,
// codes considered as "failure" for the operation
ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM
ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline
// source account does not require trust
ALLOW_TRUST_TRUST_NOT_REQUIRED = -3,
ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust,
ALLOW_TRUST_SELF_NOT_ALLOWED = -5 // trusting self is not allowed
};
===========================================================================
""")
define_type("AllowTrustResultCode", Enum,
allow_trust_success: 0,
allow_trust_malformed: -1,
allow_trust_no_trust_line: -2,
allow_trust_trust_not_required: -3,
allow_trust_cant_revoke: -4,
allow_trust_self_not_allowed: -5
)
comment(~S"""
=== xdr source ============================================================
union AllowTrustResult switch (AllowTrustResultCode code)
{
case ALLOW_TRUST_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("AllowTrustResult", Union,
switch_type: "AllowTrustResultCode",
switch_name: :code,
switches: [
{:allow_trust_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum AccountMergeResultCode
{
// codes considered as "success" for the operation
ACCOUNT_MERGE_SUCCESS = 0,
// codes considered as "failure" for the operation
ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself
ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist
ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set
ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers
ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed
ACCOUNT_MERGE_DEST_FULL = -6 // can't add source balance to
// destination balance
};
===========================================================================
""")
define_type("AccountMergeResultCode", Enum,
account_merge_success: 0,
account_merge_malformed: -1,
account_merge_no_account: -2,
account_merge_immutable_set: -3,
account_merge_has_sub_entry: -4,
account_merge_seqnum_too_far: -5,
account_merge_dest_full: -6
)
comment(~S"""
=== xdr source ============================================================
union AccountMergeResult switch (AccountMergeResultCode code)
{
case ACCOUNT_MERGE_SUCCESS:
int64 sourceAccountBalance; // how much got transfered from source account
default:
void;
};
===========================================================================
""")
define_type("AccountMergeResult", Union,
switch_type: "AccountMergeResultCode",
switch_name: :code,
switches: [
{:account_merge_success, :source_account_balance}
],
arms: [
source_account_balance: "Int64"
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum InflationResultCode
{
// codes considered as "success" for the operation
INFLATION_SUCCESS = 0,
// codes considered as "failure" for the operation
INFLATION_NOT_TIME = -1
};
===========================================================================
""")
define_type("InflationResultCode", Enum,
inflation_success: 0,
inflation_not_time: -1
)
comment(~S"""
=== xdr source ============================================================
struct InflationPayout // or use PaymentResultAtom to limit types?
{
AccountID destination;
int64 amount;
};
===========================================================================
""")
define_type("InflationPayout", Struct,
destination: "AccountId",
amount: "Int64"
)
comment(~S"""
=== xdr source ============================================================
union InflationResult switch (InflationResultCode code)
{
case INFLATION_SUCCESS:
InflationPayout payouts<>;
default:
void;
};
===========================================================================
""")
define_type("InflationResult", Union,
switch_type: "InflationResultCode",
switch_name: :code,
switches: [
{:inflation_success, :payouts}
],
arms: [
payouts: build_type(VariableArray, max_length: 2_147_483_647, type: "InflationPayout")
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum ManageDataResultCode
{
// codes considered as "success" for the operation
MANAGE_DATA_SUCCESS = 0,
// codes considered as "failure" for the operation
MANAGE_DATA_NOT_SUPPORTED_YET =
-1, // The network hasn't moved to this protocol change yet
MANAGE_DATA_NAME_NOT_FOUND =
-2, // Trying to remove a Data Entry that isn't there
MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry
MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string
};
===========================================================================
""")
define_type("ManageDataResultCode", Enum,
manage_data_success: 0,
manage_data_not_supported_yet: -1,
manage_data_name_not_found: -2,
manage_data_low_reserve: -3,
manage_data_invalid_name: -4
)
comment(~S"""
=== xdr source ============================================================
union ManageDataResult switch (ManageDataResultCode code)
{
case MANAGE_DATA_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("ManageDataResult", Union,
switch_type: "ManageDataResultCode",
switch_name: :code,
switches: [
{:manage_data_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum BumpSequenceResultCode
{
// codes considered as "success" for the operation
BUMP_SEQUENCE_SUCCESS = 0,
// codes considered as "failure" for the operation
BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds
};
===========================================================================
""")
define_type("BumpSequenceResultCode", Enum,
bump_sequence_success: 0,
bump_sequence_bad_seq: -1
)
comment(~S"""
=== xdr source ============================================================
union BumpSequenceResult switch (BumpSequenceResultCode code)
{
case BUMP_SEQUENCE_SUCCESS:
void;
default:
void;
};
===========================================================================
""")
define_type("BumpSequenceResult", Union,
switch_type: "BumpSequenceResultCode",
switch_name: :code,
switches: [
{:bump_sequence_success, XDR.Type.Void}
],
arms: [],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum OperationResultCode
{
opINNER = 0, // inner object result is valid
opBAD_AUTH = -1, // too few valid signatures / wrong network
opNO_ACCOUNT = -2, // source account was not found
opNOT_SUPPORTED = -3 // operation not supported at this time
};
===========================================================================
""")
define_type("OperationResultCode", Enum,
op_inner: 0,
op_bad_auth: -1,
op_no_account: -2,
op_not_supported: -3
)
comment(~S"""
=== xdr source ============================================================
union switch (OperationType type)
{
case CREATE_ACCOUNT:
CreateAccountResult createAccountResult;
case PAYMENT:
PaymentResult paymentResult;
case PATH_PAYMENT:
PathPaymentResult pathPaymentResult;
case MANAGE_OFFER:
ManageOfferResult manageOfferResult;
case CREATE_PASSIVE_OFFER:
ManageOfferResult createPassiveOfferResult;
case SET_OPTIONS:
SetOptionsResult setOptionsResult;
case CHANGE_TRUST:
ChangeTrustResult changeTrustResult;
case ALLOW_TRUST:
AllowTrustResult allowTrustResult;
case ACCOUNT_MERGE:
AccountMergeResult accountMergeResult;
case INFLATION:
InflationResult inflationResult;
case MANAGE_DATA:
ManageDataResult manageDataResult;
case BUMP_SEQUENCE:
BumpSequenceResult bumpSeqResult;
}
===========================================================================
""")
define_type("OperationResultTr", Union,
switch_type: "OperationType",
switch_name: :type,
switches: [
{:create_account, :create_account_result},
{:payment, :payment_result},
{:path_payment, :path_payment_result},
{:manage_offer, :manage_offer_result},
{:create_passive_offer, :create_passive_offer_result},
{:set_option, :set_options_result},
{:change_trust, :change_trust_result},
{:allow_trust, :allow_trust_result},
{:account_merge, :account_merge_result},
{:inflation, :inflation_result},
{:manage_datum, :manage_data_result},
{:bump_sequence, :bump_seq_result}
],
arms: [
create_account_result: "CreateAccountResult",
payment_result: "PaymentResult",
path_payment_result: "PathPaymentResult",
manage_offer_result: "ManageOfferResult",
create_passive_offer_result: "ManageOfferResult",
set_options_result: "SetOptionsResult",
change_trust_result: "ChangeTrustResult",
allow_trust_result: "AllowTrustResult",
account_merge_result: "AccountMergeResult",
inflation_result: "InflationResult",
manage_data_result: "ManageDataResult",
bump_seq_result: "BumpSequenceResult"
]
)
comment(~S"""
=== xdr source ============================================================
union OperationResult switch (OperationResultCode code)
{
case opINNER:
union switch (OperationType type)
{
case CREATE_ACCOUNT:
CreateAccountResult createAccountResult;
case PAYMENT:
PaymentResult paymentResult;
case PATH_PAYMENT:
PathPaymentResult pathPaymentResult;
case MANAGE_OFFER:
ManageOfferResult manageOfferResult;
case CREATE_PASSIVE_OFFER:
ManageOfferResult createPassiveOfferResult;
case SET_OPTIONS:
SetOptionsResult setOptionsResult;
case CHANGE_TRUST:
ChangeTrustResult changeTrustResult;
case ALLOW_TRUST:
AllowTrustResult allowTrustResult;
case ACCOUNT_MERGE:
AccountMergeResult accountMergeResult;
case INFLATION:
InflationResult inflationResult;
case MANAGE_DATA:
ManageDataResult manageDataResult;
case BUMP_SEQUENCE:
BumpSequenceResult bumpSeqResult;
}
tr;
default:
void;
};
===========================================================================
""")
define_type("OperationResult", Union,
switch_type: "OperationResultCode",
switch_name: :code,
switches: [
{:op_inner, :tr}
],
arms: [
tr: "OperationResultTr"
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
enum TransactionResultCode
{
txSUCCESS = 0, // all operations succeeded
txFAILED = -1, // one of the operations failed (none were applied)
txTOO_EARLY = -2, // ledger closeTime before minTime
txTOO_LATE = -3, // ledger closeTime after maxTime
txMISSING_OPERATION = -4, // no operation was specified
txBAD_SEQ = -5, // sequence number does not match source account
txBAD_AUTH = -6, // too few valid signatures / wrong network
txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve
txNO_ACCOUNT = -8, // source account not found
txINSUFFICIENT_FEE = -9, // fee is too small
txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction
txINTERNAL_ERROR = -11 // an unknown error occured
};
===========================================================================
""")
define_type("TransactionResultCode", Enum,
tx_success: 0,
tx_failed: -1,
tx_too_early: -2,
tx_too_late: -3,
tx_missing_operation: -4,
tx_bad_seq: -5,
tx_bad_auth: -6,
tx_insufficient_balance: -7,
tx_no_account: -8,
tx_insufficient_fee: -9,
tx_bad_auth_extra: -10,
tx_internal_error: -11
)
comment(~S"""
=== xdr source ============================================================
union switch (TransactionResultCode code)
{
case txSUCCESS:
case txFAILED:
OperationResult results<>;
default:
void;
}
===========================================================================
""")
define_type("TransactionResultResult", Union,
switch_type: "TransactionResultCode",
switch_name: :code,
switches: [
{:tx_success, :results},
{:tx_failed, :results}
],
arms: [
results: build_type(VariableArray, max_length: 2_147_483_647, type: "OperationResult")
],
default_arm: XDR.Type.Void
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("TransactionResultExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct TransactionResult
{
int64 feeCharged; // actual fee charged for the transaction
union switch (TransactionResultCode code)
{
case txSUCCESS:
case txFAILED:
OperationResult results<>;
default:
void;
}
result;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("TransactionResult", Struct,
fee_charged: "Int64",
result: "TransactionResultResult",
ext: "TransactionResultExt"
)
comment(~S"""
=== xdr source ============================================================
typedef opaque Value<>;
===========================================================================
""")
define_type("Value", VariableOpaque)
comment(~S"""
=== xdr source ============================================================
struct SCPBallot
{
uint32 counter; // n
Value value; // x
};
===========================================================================
""")
define_type("ScpBallot", Struct,
counter: "Uint32",
value: "Value"
)
comment(~S"""
=== xdr source ============================================================
enum SCPStatementType
{
SCP_ST_PREPARE = 0,
SCP_ST_CONFIRM = 1,
SCP_ST_EXTERNALIZE = 2,
SCP_ST_NOMINATE = 3
};
===========================================================================
""")
define_type("ScpStatementType", Enum,
scp_st_prepare: 0,
scp_st_confirm: 1,
scp_st_externalize: 2,
scp_st_nominate: 3
)
comment(~S"""
=== xdr source ============================================================
struct SCPNomination
{
Hash quorumSetHash; // D
Value votes<>; // X
Value accepted<>; // Y
};
===========================================================================
""")
define_type("ScpNomination", Struct,
quorum_set_hash: "Hash",
votes: build_type(VariableArray, max_length: 2_147_483_647, type: "Value"),
accepted: build_type(VariableArray, max_length: 2_147_483_647, type: "Value")
)
comment(~S"""
=== xdr source ============================================================
struct
{
Hash quorumSetHash; // D
SCPBallot ballot; // b
SCPBallot* prepared; // p
SCPBallot* preparedPrime; // p'
uint32 nC; // c.n
uint32 nH; // h.n
}
===========================================================================
""")
define_type("ScpStatementPrepare", Struct,
quorum_set_hash: "Hash",
ballot: "ScpBallot",
prepared: build_type(Optional, "ScpBallot"),
prepared_prime: build_type(Optional, "ScpBallot"),
nc: "Uint32",
nh: "Uint32"
)
comment(~S"""
=== xdr source ============================================================
struct
{
SCPBallot ballot; // b
uint32 nPrepared; // p.n
uint32 nCommit; // c.n
uint32 nH; // h.n
Hash quorumSetHash; // D
}
===========================================================================
""")
define_type("ScpStatementConfirm", Struct,
ballot: "ScpBallot",
n_prepared: "Uint32",
n_commit: "Uint32",
nh: "Uint32",
quorum_set_hash: "Hash"
)
comment(~S"""
=== xdr source ============================================================
struct
{
SCPBallot commit; // c
uint32 nH; // h.n
Hash commitQuorumSetHash; // D used before EXTERNALIZE
}
===========================================================================
""")
define_type("ScpStatementExternalize", Struct,
commit: "ScpBallot",
nh: "Uint32",
commit_quorum_set_hash: "Hash"
)
comment(~S"""
=== xdr source ============================================================
union switch (SCPStatementType type)
{
case SCP_ST_PREPARE:
struct
{
Hash quorumSetHash; // D
SCPBallot ballot; // b
SCPBallot* prepared; // p
SCPBallot* preparedPrime; // p'
uint32 nC; // c.n
uint32 nH; // h.n
} prepare;
case SCP_ST_CONFIRM:
struct
{
SCPBallot ballot; // b
uint32 nPrepared; // p.n
uint32 nCommit; // c.n
uint32 nH; // h.n
Hash quorumSetHash; // D
} confirm;
case SCP_ST_EXTERNALIZE:
struct
{
SCPBallot commit; // c
uint32 nH; // h.n
Hash commitQuorumSetHash; // D used before EXTERNALIZE
} externalize;
case SCP_ST_NOMINATE:
SCPNomination nominate;
}
===========================================================================
""")
define_type("ScpStatementPledges", Union,
switch_type: "ScpStatementType",
switch_name: :type,
switches: [
{:scp_st_prepare, :prepare},
{:scp_st_confirm, :confirm},
{:scp_st_externalize, :externalize},
{:scp_st_nominate, :nominate}
],
arms: [
prepare: "ScpStatementPrepare",
confirm: "ScpStatementConfirm",
externalize: "ScpStatementExternalize",
nominate: "ScpNomination"
]
)
comment(~S"""
=== xdr source ============================================================
struct SCPStatement
{
NodeID nodeID; // v
uint64 slotIndex; // i
union switch (SCPStatementType type)
{
case SCP_ST_PREPARE:
struct
{
Hash quorumSetHash; // D
SCPBallot ballot; // b
SCPBallot* prepared; // p
SCPBallot* preparedPrime; // p'
uint32 nC; // c.n
uint32 nH; // h.n
} prepare;
case SCP_ST_CONFIRM:
struct
{
SCPBallot ballot; // b
uint32 nPrepared; // p.n
uint32 nCommit; // c.n
uint32 nH; // h.n
Hash quorumSetHash; // D
} confirm;
case SCP_ST_EXTERNALIZE:
struct
{
SCPBallot commit; // c
uint32 nH; // h.n
Hash commitQuorumSetHash; // D used before EXTERNALIZE
} externalize;
case SCP_ST_NOMINATE:
SCPNomination nominate;
}
pledges;
};
===========================================================================
""")
define_type("ScpStatement", Struct,
node_id: "NodeId",
slot_index: "Uint64",
pledges: "ScpStatementPledges"
)
comment(~S"""
=== xdr source ============================================================
struct SCPEnvelope
{
SCPStatement statement;
Signature signature;
};
===========================================================================
""")
define_type("ScpEnvelope", Struct,
statement: "ScpStatement",
signature: "Signature"
)
comment(~S"""
=== xdr source ============================================================
struct SCPQuorumSet
{
uint32 threshold;
PublicKey validators<>;
SCPQuorumSet innerSets<>;
};
===========================================================================
""")
define_type("ScpQuorumSet", Struct,
threshold: "Uint32",
validators: build_type(VariableArray, max_length: 2_147_483_647, type: "PublicKey"),
inner_sets: build_type(VariableArray, max_length: 2_147_483_647, type: "ScpQuorumSet")
)
comment(~S"""
=== xdr source ============================================================
typedef PublicKey AccountID;
===========================================================================
""")
define_type("AccountId", "PublicKey")
comment(~S"""
=== xdr source ============================================================
typedef opaque Thresholds[4];
===========================================================================
""")
define_type("Thresholds", Opaque, 4)
comment(~S"""
=== xdr source ============================================================
typedef string string32<32>;
===========================================================================
""")
define_type("String32", XDR.Type.String, 32)
comment(~S"""
=== xdr source ============================================================
typedef string string64<64>;
===========================================================================
""")
define_type("String64", XDR.Type.String, 64)
comment(~S"""
=== xdr source ============================================================
typedef int64 SequenceNumber;
===========================================================================
""")
define_type("SequenceNumber", "Int64")
comment(~S"""
=== xdr source ============================================================
typedef opaque DataValue<64>;
===========================================================================
""")
define_type("DataValue", VariableOpaque, 64)
comment(~S"""
=== xdr source ============================================================
enum AssetType
{
ASSET_TYPE_NATIVE = 0,
ASSET_TYPE_CREDIT_ALPHANUM4 = 1,
ASSET_TYPE_CREDIT_ALPHANUM12 = 2
};
===========================================================================
""")
define_type("AssetType", Enum,
asset_type_native: 0,
asset_type_credit_alphanum4: 1,
asset_type_credit_alphanum12: 2
)
comment(~S"""
=== xdr source ============================================================
struct
{
opaque assetCode[4]; // 1 to 4 characters
AccountID issuer;
}
===========================================================================
""")
define_type("AssetAlphaNum4", Struct,
asset_code: build_type(Opaque, 4),
issuer: "AccountId"
)
comment(~S"""
=== xdr source ============================================================
struct
{
opaque assetCode[12]; // 5 to 12 characters
AccountID issuer;
}
===========================================================================
""")
define_type("AssetAlphaNum12", Struct,
asset_code: build_type(Opaque, 12),
issuer: "AccountId"
)
comment(~S"""
=== xdr source ============================================================
union Asset switch (AssetType type)
{
case ASSET_TYPE_NATIVE: // Not credit
void;
case ASSET_TYPE_CREDIT_ALPHANUM4:
struct
{
opaque assetCode[4]; // 1 to 4 characters
AccountID issuer;
} alphaNum4;
case ASSET_TYPE_CREDIT_ALPHANUM12:
struct
{
opaque assetCode[12]; // 5 to 12 characters
AccountID issuer;
} alphaNum12;
// add other asset types here in the future
};
===========================================================================
""")
define_type("Asset", Union,
switch_type: "AssetType",
switch_name: :type,
switches: [
{:asset_type_native, XDR.Type.Void},
{:asset_type_credit_alphanum4, :alpha_num4},
{:asset_type_credit_alphanum12, :alpha_num12}
],
arms: [
alpha_num4: "AssetAlphaNum4",
alpha_num12: "AssetAlphaNum12"
]
)
comment(~S"""
=== xdr source ============================================================
struct Price
{
int32 n; // numerator
int32 d; // denominator
};
===========================================================================
""")
define_type("Price", Struct,
n: "Int32",
d: "Int32"
)
comment(~S"""
=== xdr source ============================================================
struct Liabilities
{
int64 buying;
int64 selling;
};
===========================================================================
""")
define_type("Liabilities", Struct,
buying: "Int64",
selling: "Int64"
)
comment(~S"""
=== xdr source ============================================================
enum ThresholdIndexes
{
THRESHOLD_MASTER_WEIGHT = 0,
THRESHOLD_LOW = 1,
THRESHOLD_MED = 2,
THRESHOLD_HIGH = 3
};
===========================================================================
""")
define_type("ThresholdIndices", Enum,
threshold_master_weight: 0,
threshold_low: 1,
threshold_med: 2,
threshold_high: 3
)
comment(~S"""
=== xdr source ============================================================
enum LedgerEntryType
{
ACCOUNT = 0,
TRUSTLINE = 1,
OFFER = 2,
DATA = 3
};
===========================================================================
""")
define_type("LedgerEntryType", Enum,
account: 0,
trustline: 1,
offer: 2,
datum: 3
)
comment(~S"""
=== xdr source ============================================================
struct Signer
{
SignerKey key;
uint32 weight; // really only need 1byte
};
===========================================================================
""")
define_type("Signer", Struct,
key: "SignerKey",
weight: "Uint32"
)
comment(~S"""
=== xdr source ============================================================
enum AccountFlags
{ // masks for each flag
// Flags set on issuer accounts
// TrustLines are created with authorized set to "false" requiring
// the issuer to set it for each TrustLine
AUTH_REQUIRED_FLAG = 0x1,
// If set, the authorized flag in TrustLines can be cleared
// otherwise, authorization cannot be revoked
AUTH_REVOCABLE_FLAG = 0x2,
// Once set, causes all AUTH_* flags to be read-only
AUTH_IMMUTABLE_FLAG = 0x4
};
===========================================================================
""")
define_type("AccountFlags", Enum,
auth_required_flag: 1,
auth_revocable_flag: 2,
auth_immutable_flag: 4
)
comment(~S"""
=== xdr source ============================================================
const MASK_ACCOUNT_FLAGS = 0x7;
===========================================================================
""")
define_type("MASK_ACCOUNT_FLAGS", Const, 0x7)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("AccountEntryV1Ext", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct
{
Liabilities liabilities;
union switch (int v)
{
case 0:
void;
}
ext;
}
===========================================================================
""")
define_type("AccountEntryV1", Struct,
liabilities: "Liabilities",
ext: "AccountEntryV1Ext"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
case 1:
struct
{
Liabilities liabilities;
union switch (int v)
{
case 0:
void;
}
ext;
} v1;
}
===========================================================================
""")
define_type("AccountEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void},
{1, :v1}
],
arms: [
v1: "AccountEntryV1"
]
)
comment(~S"""
=== xdr source ============================================================
struct AccountEntry
{
AccountID accountID; // master public key for this account
int64 balance; // in stroops
SequenceNumber seqNum; // last sequence number used for this account
uint32 numSubEntries; // number of sub-entries this account has
// drives the reserve
AccountID* inflationDest; // Account to vote for during inflation
uint32 flags; // see AccountFlags
string32 homeDomain; // can be used for reverse federation and memo lookup
// fields used for signatures
// thresholds stores unsigned bytes: [weight of master|low|medium|high]
Thresholds thresholds;
Signer signers<20>; // possible signers for this account
// reserved for future use
union switch (int v)
{
case 0:
void;
case 1:
struct
{
Liabilities liabilities;
union switch (int v)
{
case 0:
void;
}
ext;
} v1;
}
ext;
};
===========================================================================
""")
define_type("AccountEntry", Struct,
account_id: "AccountId",
balance: "Int64",
seq_num: "SequenceNumber",
num_sub_entries: "Uint32",
inflation_dest: build_type(Optional, "AccountId"),
flags: "Uint32",
home_domain: "String32",
thresholds: "Thresholds",
signers: build_type(VariableArray, max_length: 20, type: "Signer"),
ext: "AccountEntryExt"
)
comment(~S"""
=== xdr source ============================================================
enum TrustLineFlags
{
// issuer has authorized account to perform transactions with its credit
AUTHORIZED_FLAG = 1
};
===========================================================================
""")
define_type("TrustLineFlags", Enum, authorized_flag: 1)
comment(~S"""
=== xdr source ============================================================
const MASK_TRUSTLINE_FLAGS = 1;
===========================================================================
""")
define_type("MASK_TRUSTLINE_FLAGS", Const, 1)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("TrustLineEntryV1Ext", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct
{
Liabilities liabilities;
union switch (int v)
{
case 0:
void;
}
ext;
}
===========================================================================
""")
define_type("TrustLineEntryV1", Struct,
liabilities: "Liabilities",
ext: "TrustLineEntryV1Ext"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
case 1:
struct
{
Liabilities liabilities;
union switch (int v)
{
case 0:
void;
}
ext;
} v1;
}
===========================================================================
""")
define_type("TrustLineEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void},
{1, :v1}
],
arms: [
v1: "TrustLineEntryV1"
]
)
comment(~S"""
=== xdr source ============================================================
struct TrustLineEntry
{
AccountID accountID; // account this trustline belongs to
Asset asset; // type of asset (with issuer)
int64 balance; // how much of this asset the user has.
// Asset defines the unit for this;
int64 limit; // balance cannot be above this
uint32 flags; // see TrustLineFlags
// reserved for future use
union switch (int v)
{
case 0:
void;
case 1:
struct
{
Liabilities liabilities;
union switch (int v)
{
case 0:
void;
}
ext;
} v1;
}
ext;
};
===========================================================================
""")
define_type("TrustLineEntry", Struct,
account_id: "AccountId",
asset: "Asset",
balance: "Int64",
limit: "Int64",
flags: "Uint32",
ext: "TrustLineEntryExt"
)
comment(~S"""
=== xdr source ============================================================
enum OfferEntryFlags
{
// issuer has authorized account to perform transactions with its credit
PASSIVE_FLAG = 1
};
===========================================================================
""")
define_type("OfferEntryFlags", Enum, passive_flag: 1)
comment(~S"""
=== xdr source ============================================================
const MASK_OFFERENTRY_FLAGS = 1;
===========================================================================
""")
define_type("MASK_OFFERENTRY_FLAGS", Const, 1)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("OfferEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct OfferEntry
{
AccountID sellerID;
uint64 offerID;
Asset selling; // A
Asset buying; // B
int64 amount; // amount of A
/* price for this offer:
price of A in terms of B
price=AmountB/AmountA=priceNumerator/priceDenominator
price is after fees
*/
Price price;
uint32 flags; // see OfferEntryFlags
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("OfferEntry", Struct,
seller_id: "AccountId",
offer_id: "Uint64",
selling: "Asset",
buying: "Asset",
amount: "Int64",
price: "Price",
flags: "Uint32",
ext: "OfferEntryExt"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("DataEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct DataEntry
{
AccountID accountID; // account this data belongs to
string64 dataName;
DataValue dataValue;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("DataEntry", Struct,
account_id: "AccountId",
data_name: "String64",
data_value: "DataValue",
ext: "DataEntryExt"
)
comment(~S"""
=== xdr source ============================================================
union switch (LedgerEntryType type)
{
case ACCOUNT:
AccountEntry account;
case TRUSTLINE:
TrustLineEntry trustLine;
case OFFER:
OfferEntry offer;
case DATA:
DataEntry data;
}
===========================================================================
""")
define_type("LedgerEntryData", Union,
switch_type: "LedgerEntryType",
switch_name: :type,
switches: [
{:account, :account},
{:trustline, :trust_line},
{:offer, :offer},
{:datum, :data}
],
arms: [
account: "AccountEntry",
trust_line: "TrustLineEntry",
offer: "OfferEntry",
data: "DataEntry"
]
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("LedgerEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct LedgerEntry
{
uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed
union switch (LedgerEntryType type)
{
case ACCOUNT:
AccountEntry account;
case TRUSTLINE:
TrustLineEntry trustLine;
case OFFER:
OfferEntry offer;
case DATA:
DataEntry data;
}
data;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("LedgerEntry", Struct,
last_modified_ledger_seq: "Uint32",
data: "LedgerEntryData",
ext: "LedgerEntryExt"
)
comment(~S"""
=== xdr source ============================================================
enum EnvelopeType
{
ENVELOPE_TYPE_SCP = 1,
ENVELOPE_TYPE_TX = 2,
ENVELOPE_TYPE_AUTH = 3
};
===========================================================================
""")
define_type("EnvelopeType", Enum,
envelope_type_scp: 1,
envelope_type_tx: 2,
envelope_type_auth: 3
)
comment(~S"""
=== xdr source ============================================================
typedef opaque UpgradeType<128>;
===========================================================================
""")
define_type("UpgradeType", VariableOpaque, 128)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("StellarValueExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct StellarValue
{
Hash txSetHash; // transaction set to apply to previous ledger
uint64 closeTime; // network close time
// upgrades to apply to the previous ledger (usually empty)
// this is a vector of encoded 'LedgerUpgrade' so that nodes can drop
// unknown steps during consensus if needed.
// see notes below on 'LedgerUpgrade' for more detail
// max size is dictated by number of upgrade types (+ room for future)
UpgradeType upgrades<6>;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("StellarValue", Struct,
tx_set_hash: "Hash",
close_time: "Uint64",
upgrades: build_type(VariableArray, max_length: 6, type: "UpgradeType"),
ext: "StellarValueExt"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("LedgerHeaderExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct LedgerHeader
{
uint32 ledgerVersion; // the protocol version of the ledger
Hash previousLedgerHash; // hash of the previous ledger header
StellarValue scpValue; // what consensus agreed to
Hash txSetResultHash; // the TransactionResultSet that led to this ledger
Hash bucketListHash; // hash of the ledger state
uint32 ledgerSeq; // sequence number of this ledger
int64 totalCoins; // total number of stroops in existence.
// 10,000,000 stroops in 1 XLM
int64 feePool; // fees burned since last inflation run
uint32 inflationSeq; // inflation sequence number
uint64 idPool; // last used global ID, used for generating objects
uint32 baseFee; // base fee per operation in stroops
uint32 baseReserve; // account base reserve in stroops
uint32 maxTxSetSize; // maximum size a transaction set can be
Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back
// in time without walking the chain back ledger by ledger
// each slot contains the oldest ledger that is mod of
// either 50 5000 50000 or 500000 depending on index
// skipList[0] mod(50), skipList[1] mod(5000), etc
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("LedgerHeader", Struct,
ledger_version: "Uint32",
previous_ledger_hash: "Hash",
scp_value: "StellarValue",
tx_set_result_hash: "Hash",
bucket_list_hash: "Hash",
ledger_seq: "Uint32",
total_coins: "Int64",
fee_pool: "Int64",
inflation_seq: "Uint32",
id_pool: "Uint64",
base_fee: "Uint32",
base_reserve: "Uint32",
max_tx_set_size: "Uint32",
skip_list: build_type(Array, length: 4, type: "Hash"),
ext: "LedgerHeaderExt"
)
comment(~S"""
=== xdr source ============================================================
enum LedgerUpgradeType
{
LEDGER_UPGRADE_VERSION = 1,
LEDGER_UPGRADE_BASE_FEE = 2,
LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3,
LEDGER_UPGRADE_BASE_RESERVE = 4
};
===========================================================================
""")
define_type("LedgerUpgradeType", Enum,
ledger_upgrade_version: 1,
ledger_upgrade_base_fee: 2,
ledger_upgrade_max_tx_set_size: 3,
ledger_upgrade_base_reserve: 4
)
comment(~S"""
=== xdr source ============================================================
union LedgerUpgrade switch (LedgerUpgradeType type)
{
case LEDGER_UPGRADE_VERSION:
uint32 newLedgerVersion; // update ledgerVersion
case LEDGER_UPGRADE_BASE_FEE:
uint32 newBaseFee; // update baseFee
case LEDGER_UPGRADE_MAX_TX_SET_SIZE:
uint32 newMaxTxSetSize; // update maxTxSetSize
case LEDGER_UPGRADE_BASE_RESERVE:
uint32 newBaseReserve; // update baseReserve
};
===========================================================================
""")
define_type("LedgerUpgrade", Union,
switch_type: "LedgerUpgradeType",
switch_name: :type,
switches: [
{:ledger_upgrade_version, :new_ledger_version},
{:ledger_upgrade_base_fee, :new_base_fee},
{:ledger_upgrade_max_tx_set_size, :new_max_tx_set_size},
{:ledger_upgrade_base_reserve, :new_base_reserve}
],
arms: [
new_ledger_version: "Uint32",
new_base_fee: "Uint32",
new_max_tx_set_size: "Uint32",
new_base_reserve: "Uint32"
]
)
comment(~S"""
=== xdr source ============================================================
struct
{
AccountID accountID;
}
===========================================================================
""")
define_type("LedgerKeyAccount", Struct, account_id: "AccountId")
comment(~S"""
=== xdr source ============================================================
struct
{
AccountID accountID;
Asset asset;
}
===========================================================================
""")
define_type("LedgerKeyTrustLine", Struct,
account_id: "AccountId",
asset: "Asset"
)
comment(~S"""
=== xdr source ============================================================
struct
{
AccountID sellerID;
uint64 offerID;
}
===========================================================================
""")
define_type("LedgerKeyOffer", Struct,
seller_id: "AccountId",
offer_id: "Uint64"
)
comment(~S"""
=== xdr source ============================================================
struct
{
AccountID accountID;
string64 dataName;
}
===========================================================================
""")
define_type("LedgerKeyData", Struct,
account_id: "AccountId",
data_name: "String64"
)
comment(~S"""
=== xdr source ============================================================
union LedgerKey switch (LedgerEntryType type)
{
case ACCOUNT:
struct
{
AccountID accountID;
} account;
case TRUSTLINE:
struct
{
AccountID accountID;
Asset asset;
} trustLine;
case OFFER:
struct
{
AccountID sellerID;
uint64 offerID;
} offer;
case DATA:
struct
{
AccountID accountID;
string64 dataName;
} data;
};
===========================================================================
""")
define_type("LedgerKey", Union,
switch_type: "LedgerEntryType",
switch_name: :type,
switches: [
{:account, :account},
{:trustline, :trust_line},
{:offer, :offer},
{:datum, :data}
],
arms: [
account: "LedgerKeyAccount",
trust_line: "LedgerKeyTrustLine",
offer: "LedgerKeyOffer",
data: "LedgerKeyData"
]
)
comment(~S"""
=== xdr source ============================================================
enum BucketEntryType
{
LIVEENTRY = 0,
DEADENTRY = 1
};
===========================================================================
""")
define_type("BucketEntryType", Enum,
liveentry: 0,
deadentry: 1
)
comment(~S"""
=== xdr source ============================================================
union BucketEntry switch (BucketEntryType type)
{
case LIVEENTRY:
LedgerEntry liveEntry;
case DEADENTRY:
LedgerKey deadEntry;
};
===========================================================================
""")
define_type("BucketEntry", Union,
switch_type: "BucketEntryType",
switch_name: :type,
switches: [
{:liveentry, :live_entry},
{:deadentry, :dead_entry}
],
arms: [
live_entry: "LedgerEntry",
dead_entry: "LedgerKey"
]
)
comment(~S"""
=== xdr source ============================================================
struct TransactionSet
{
Hash previousLedgerHash;
TransactionEnvelope txs<>;
};
===========================================================================
""")
define_type("TransactionSet", Struct,
previous_ledger_hash: "Hash",
txes: build_type(VariableArray, max_length: 2_147_483_647, type: "TransactionEnvelope")
)
comment(~S"""
=== xdr source ============================================================
struct TransactionResultPair
{
Hash transactionHash;
TransactionResult result; // result for the transaction
};
===========================================================================
""")
define_type("TransactionResultPair", Struct,
transaction_hash: "Hash",
result: "TransactionResult"
)
comment(~S"""
=== xdr source ============================================================
struct TransactionResultSet
{
TransactionResultPair results<>;
};
===========================================================================
""")
define_type("TransactionResultSet", Struct,
results: build_type(VariableArray, max_length: 2_147_483_647, type: "TransactionResultPair")
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("TransactionHistoryEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct TransactionHistoryEntry
{
uint32 ledgerSeq;
TransactionSet txSet;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("TransactionHistoryEntry", Struct,
ledger_seq: "Uint32",
tx_set: "TransactionSet",
ext: "TransactionHistoryEntryExt"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("TransactionHistoryResultEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct TransactionHistoryResultEntry
{
uint32 ledgerSeq;
TransactionResultSet txResultSet;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("TransactionHistoryResultEntry", Struct,
ledger_seq: "Uint32",
tx_result_set: "TransactionResultSet",
ext: "TransactionHistoryResultEntryExt"
)
comment(~S"""
=== xdr source ============================================================
union switch (int v)
{
case 0:
void;
}
===========================================================================
""")
define_type("LedgerHeaderHistoryEntryExt", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, XDR.Type.Void}
],
arms: []
)
comment(~S"""
=== xdr source ============================================================
struct LedgerHeaderHistoryEntry
{
Hash hash;
LedgerHeader header;
// reserved for future use
union switch (int v)
{
case 0:
void;
}
ext;
};
===========================================================================
""")
define_type("LedgerHeaderHistoryEntry", Struct,
hash: "Hash",
header: "LedgerHeader",
ext: "LedgerHeaderHistoryEntryExt"
)
comment(~S"""
=== xdr source ============================================================
struct LedgerSCPMessages
{
uint32 ledgerSeq;
SCPEnvelope messages<>;
};
===========================================================================
""")
define_type("LedgerScpMessages", Struct,
ledger_seq: "Uint32",
messages: build_type(VariableArray, max_length: 2_147_483_647, type: "ScpEnvelope")
)
comment(~S"""
=== xdr source ============================================================
struct SCPHistoryEntryV0
{
SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages
LedgerSCPMessages ledgerMessages;
};
===========================================================================
""")
define_type("ScpHistoryEntryV0", Struct,
quorum_sets: build_type(VariableArray, max_length: 2_147_483_647, type: "ScpQuorumSet"),
ledger_messages: "LedgerScpMessages"
)
comment(~S"""
=== xdr source ============================================================
union SCPHistoryEntry switch (int v)
{
case 0:
SCPHistoryEntryV0 v0;
};
===========================================================================
""")
define_type("ScpHistoryEntry", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, :v0}
],
arms: [
v0: "ScpHistoryEntryV0"
]
)
comment(~S"""
=== xdr source ============================================================
enum LedgerEntryChangeType
{
LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger
LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger
LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger
LEDGER_ENTRY_STATE = 3 // value of the entry
};
===========================================================================
""")
define_type("LedgerEntryChangeType", Enum,
ledger_entry_created: 0,
ledger_entry_updated: 1,
ledger_entry_removed: 2,
ledger_entry_state: 3
)
comment(~S"""
=== xdr source ============================================================
union LedgerEntryChange switch (LedgerEntryChangeType type)
{
case LEDGER_ENTRY_CREATED:
LedgerEntry created;
case LEDGER_ENTRY_UPDATED:
LedgerEntry updated;
case LEDGER_ENTRY_REMOVED:
LedgerKey removed;
case LEDGER_ENTRY_STATE:
LedgerEntry state;
};
===========================================================================
""")
define_type("LedgerEntryChange", Union,
switch_type: "LedgerEntryChangeType",
switch_name: :type,
switches: [
{:ledger_entry_created, :created},
{:ledger_entry_updated, :updated},
{:ledger_entry_removed, :removed},
{:ledger_entry_state, :state}
],
arms: [
created: "LedgerEntry",
updated: "LedgerEntry",
removed: "LedgerKey",
state: "LedgerEntry"
]
)
comment(~S"""
=== xdr source ============================================================
typedef LedgerEntryChange LedgerEntryChanges<>;
===========================================================================
""")
define_type("LedgerEntryChanges", VariableArray,
max_length: 2_147_483_647,
type: "LedgerEntryChange"
)
comment(~S"""
=== xdr source ============================================================
struct OperationMeta
{
LedgerEntryChanges changes;
};
===========================================================================
""")
define_type("OperationMeta", Struct, changes: "LedgerEntryChanges")
comment(~S"""
=== xdr source ============================================================
struct TransactionMetaV1
{
LedgerEntryChanges txChanges; // tx level changes if any
OperationMeta operations<>; // meta for each operation
};
===========================================================================
""")
define_type("TransactionMetaV1", Struct,
tx_changes: "LedgerEntryChanges",
operations: build_type(VariableArray, max_length: 2_147_483_647, type: "OperationMeta")
)
comment(~S"""
=== xdr source ============================================================
union TransactionMeta switch (int v)
{
case 0:
OperationMeta operations<>;
case 1:
TransactionMetaV1 v1;
};
===========================================================================
""")
define_type("TransactionMeta", Union,
switch_type: build_type(Int),
switch_name: :v,
switches: [
{0, :operations},
{1, :v1}
],
arms: [
operations: build_type(VariableArray, max_length: 2_147_483_647, type: "OperationMeta"),
v1: "TransactionMetaV1"
]
)
end
| 27.015977 | 97 | 0.443097 |
1c376fa9abeaf67f3abd3b2ab3cc07b25066b8a1 | 2,100 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v28/model/conversions_batch_update_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v28/model/conversions_batch_update_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v28/model/conversions_batch_update_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"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.DFAReporting.V28.Model.ConversionsBatchUpdateResponse do
@moduledoc """
Update Conversions Response.
## Attributes
- hasFailures (boolean()): Indicates that some or all conversions failed to update. Defaults to: `null`.
- kind (String.t): Identifies what kind of resource this is. Value: the fixed string \"dfareporting#conversionsBatchUpdateResponse\". Defaults to: `null`.
- status ([ConversionStatus]): The update status of each conversion. Statuses are returned in the same order that conversions are updated. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:hasFailures => any(),
:kind => any(),
:status => list(GoogleApi.DFAReporting.V28.Model.ConversionStatus.t())
}
field(:hasFailures)
field(:kind)
field(:status, as: GoogleApi.DFAReporting.V28.Model.ConversionStatus, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V28.Model.ConversionsBatchUpdateResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V28.Model.ConversionsBatchUpdateResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V28.Model.ConversionsBatchUpdateResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.888889 | 166 | 0.751429 |
1c37760033320348a3f7f3644e18aa3447bcd263 | 1,990 | ex | Elixir | chat-api/web/controllers/api/room_controller.ex | antonpetkoff/smolltolk | 64c6d4a52e7624302ad87a072fc108fe4c1382ec | [
"MIT"
] | null | null | null | chat-api/web/controllers/api/room_controller.ex | antonpetkoff/smolltolk | 64c6d4a52e7624302ad87a072fc108fe4c1382ec | [
"MIT"
] | 3 | 2018-01-23T10:53:08.000Z | 2018-01-23T10:58:23.000Z | chat-api/web/controllers/api/room_controller.ex | antonpetkoff/smolltolk | 64c6d4a52e7624302ad87a072fc108fe4c1382ec | [
"MIT"
] | null | null | null | defmodule Chat.RoomController do
use Chat.Web, :controller
alias Chat.Room
plug Guardian.Plug.EnsureAuthenticated, handler: Chat.SessionController
def index(conn, params) do
page =
Chat.Room
|> order_by([asc: :id])
|> Chat.Repo.paginate(params)
render(conn, "index.json", page: page)
end
def create(conn, params) do
current_user = Guardian.Plug.current_resource(conn)
changeset = Room.changeset(%Room{}, params)
case Repo.insert(changeset) do
{:ok, room} ->
assoc_changeset = Chat.UserRoom.changeset(
%Chat.UserRoom{},
%{user_id: current_user.id, room_id: room.id}
)
Repo.insert(assoc_changeset)
conn
|> put_status(:created)
|> render("show.json", room: room)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Chat.ChangesetView, "error.json", changeset: changeset)
end
end
def update(conn, params) do
room = Repo.get!(Room, params["id"])
changeset = Room.changeset(room, params)
case Repo.update(changeset) do
{:ok, room} ->
conn
|> put_status(:ok)
|> render("show.json", %{room: room})
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Chat.ChangesetView, "error.json", changeset: changeset)
end
end
def join(conn, %{"id" => room_id}) do
current_user = Guardian.Plug.current_resource(conn)
room = Repo.get(Room, room_id)
changeset = Chat.UserRoom.changeset(
%Chat.UserRoom{},
%{room_id: room.id, user_id: current_user.id}
)
case Repo.insert(changeset) do
{:ok, _user_room} ->
conn
|> put_status(:created)
|> render("show.json", %{room: room})
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Chat.ChangesetView, "error.json", changeset: changeset)
end
end
end
| 26.184211 | 73 | 0.605025 |
1c379bd08ab40cc437dcb6af7259dcadec91359f | 232 | exs | Elixir | chapter3/challenges/mealcon/priv/repo/migrations/20210405213230_create_users_table.exs | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | 1 | 2021-07-23T19:48:27.000Z | 2021-07-23T19:48:27.000Z | chapter3/challenges/mealcon/priv/repo/migrations/20210405213230_create_users_table.exs | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | null | null | null | chapter3/challenges/mealcon/priv/repo/migrations/20210405213230_create_users_table.exs | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | null | null | null | defmodule Mealcon.Repo.Migrations.CreateUsersTable do
use Ecto.Migration
def change do
create table :users do
add :name, :string
add :cpf, :string
add :email, :string
timestamps()
end
end
end
| 16.571429 | 53 | 0.650862 |
1c37ab9aaf4cf53c56995f29c969e06b82b32f71 | 1,667 | exs | Elixir | mqtt/vernemq_iot_plugin/test/vernemq_mads_plugin_test.exs | arjun289/IoTMarketplaces | 5c569a62640fd5025f6a6ca3df2afb799a200423 | [
"Apache-2.0"
] | null | null | null | mqtt/vernemq_iot_plugin/test/vernemq_mads_plugin_test.exs | arjun289/IoTMarketplaces | 5c569a62640fd5025f6a6ca3df2afb799a200423 | [
"Apache-2.0"
] | null | null | null | mqtt/vernemq_iot_plugin/test/vernemq_mads_plugin_test.exs | arjun289/IoTMarketplaces | 5c569a62640fd5025f6a6ca3df2afb799a200423 | [
"Apache-2.0"
] | null | null | null | defmodule VernemqMadsPluginTest do
use ExUnit.Case
use AcqdatCore.DataCase
import AcqdatCore.Support.Factory
alias VernemqMadsPlugin.Account
alias AcqdatCore.Schema.IotManager.BrokerCredentials
alias AcqdatCore.Repo
test "authenticate a gateway client if correct uuid and password" do
gateway = insert(:gateway)
params = %{
entity_uuid: gateway.uuid,
access_token: gateway.access_token,
entity_type: "Gateway"
}
changeset = BrokerCredentials.changeset(%BrokerCredentials{}, params)
Repo.insert!(changeset)
result = Account.is_authenticated(gateway.uuid, gateway.access_token)
assert result == :ok
end
test "authenticate fails if gateway not found" do
result = Account.is_authenticated("xyz", "abc")
assert result == {:error, "Invalid Credentials"}
end
test "authenticate fails if credentials are wrong" do
gateway = insert(:gateway)
params = %{
entity_uuid: gateway.uuid,
access_token: gateway.access_token,
entity_type: "Gateway"
}
changeset = BrokerCredentials.changeset(%BrokerCredentials{}, params)
Repo.insert!(changeset)
result = Account.is_authenticated(gateway.uuid, "abc")
assert result == {:error, "Invalid Credentials"}
end
test "authenticate for a project" do
project = insert(:project)
access_token = "abc1234"
params = %{entity_uuid: project.uuid, access_token: access_token, entity_type: "Gateway"}
changeset = BrokerCredentials.changeset(%BrokerCredentials{}, params)
Repo.insert!(changeset)
result = Account.is_authenticated(project.uuid, access_token)
assert result == :ok
end
end
| 28.741379 | 93 | 0.718056 |
1c37bf2b265ad788a1f1aaf721f3908ab8089f5c | 2,096 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/multi_class_classification_metrics.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/big_query/lib/google_api/big_query/v2/model/multi_class_classification_metrics.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/big_query/lib/google_api/big_query/v2/model/multi_class_classification_metrics.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.BigQuery.V2.Model.MultiClassClassificationMetrics do
@moduledoc """
Evaluation metrics for multi-class classification/classifier models.
## Attributes
* `aggregateClassificationMetrics` (*type:* `GoogleApi.BigQuery.V2.Model.AggregateClassificationMetrics.t`, *default:* `nil`) - Aggregate classification metrics.
* `confusionMatrixList` (*type:* `list(GoogleApi.BigQuery.V2.Model.ConfusionMatrix.t)`, *default:* `nil`) - Confusion matrix at different thresholds.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:aggregateClassificationMetrics =>
GoogleApi.BigQuery.V2.Model.AggregateClassificationMetrics.t() | nil,
:confusionMatrixList => list(GoogleApi.BigQuery.V2.Model.ConfusionMatrix.t()) | nil
}
field(:aggregateClassificationMetrics,
as: GoogleApi.BigQuery.V2.Model.AggregateClassificationMetrics
)
field(:confusionMatrixList, as: GoogleApi.BigQuery.V2.Model.ConfusionMatrix, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.MultiClassClassificationMetrics do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.MultiClassClassificationMetrics.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.MultiClassClassificationMetrics do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.814815 | 165 | 0.762405 |
1c37cde3871226c34eaca81ea41fab8fc835f4ba | 608 | exs | Elixir | priv/repo/migrations/20210923114515_create_images.exs | audacioustux/philopets | 9380416937d635d4b1f5e13fa6f8b52ee603addf | [
"blessing"
] | null | null | null | priv/repo/migrations/20210923114515_create_images.exs | audacioustux/philopets | 9380416937d635d4b1f5e13fa6f8b52ee603addf | [
"blessing"
] | null | null | null | priv/repo/migrations/20210923114515_create_images.exs | audacioustux/philopets | 9380416937d635d4b1f5e13fa6f8b52ee603addf | [
"blessing"
] | null | null | null | defmodule Philopets.Repo.Migrations.CreateImages do
use Ecto.Migration
def change do
create table(:images, primary_key: false) do
# files are typically directly accessible if the name is known.
# uuid v1mc is far less random than v4
add(:id, :binary_id,
primary_key: true,
default: fragment("gen_random_uuid()")
)
add(:name, :string, null: false)
add(:size, :integer, null: false)
add(:profile_id, references(:profiles, on_delete: :delete_all), null: false)
timestamps()
end
create(index(:images, [:profile_id]))
end
end
| 27.636364 | 82 | 0.652961 |
1c37d05c15cdcb71fa8f0da515e7bfbb3f7581f4 | 10,104 | exs | Elixir | test/teslamate/vehicles/vehicle/suspend_logging_test.exs | Try2Fly/teslamate | 7ac8d5681231a494af288b0fb16adb1e775ffcec | [
"MIT"
] | null | null | null | test/teslamate/vehicles/vehicle/suspend_logging_test.exs | Try2Fly/teslamate | 7ac8d5681231a494af288b0fb16adb1e775ffcec | [
"MIT"
] | null | null | null | test/teslamate/vehicles/vehicle/suspend_logging_test.exs | Try2Fly/teslamate | 7ac8d5681231a494af288b0fb16adb1e775ffcec | [
"MIT"
] | null | null | null | defmodule TeslaMate.Vehicles.Vehicle.SuspendLoggingTest do
use TeslaMate.VehicleCase, async: true
alias TeslaMate.Vehicles.Vehicle
alias TeslaMate.Vehicles.Vehicle
test "immediately returns :ok if asleep", %{test: name} do
events = [
{:ok, %TeslaApi.Vehicle{state: "asleep"}}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :asleep}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :asleep}}}
assert :ok = Vehicle.suspend_logging(name)
refute_receive _
end
test "immediately returns :ok if offline", %{test: name} do
events = [
{:ok, %TeslaApi.Vehicle{state: "offline"}}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :offline}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :offline}}}
assert :ok = Vehicle.suspend_logging(name)
refute_receive _
end
test "immediately returns :ok if already suspending", %{test: name} do
events = [
{:ok, online_event()}
]
:ok = start_vehicle(name, events, settings: %{suspend_min: 1000})
assert_receive {:start_state, car_id, :online}
assert_receive {:insert_position, ^car_id, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert :ok = Vehicle.suspend_logging(name)
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :suspended}}}
assert :ok = Vehicle.suspend_logging(name)
refute_receive _
end
test "cannot be suspended if vehicle is preconditioning", %{test: name} do
not_supendable =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: true}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :preconditioning} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if user is present", %{test: name} do
not_supendable =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
vehicle_state: %{is_user_present: true}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :user_present} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if sentry mode is active", %{test: name} do
not_supendable =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
vehicle_state: %{sentry_mode: true}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :sentry_mode} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if vehicle is unlocked", %{test: name} do
not_supendable =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
vehicle_state: %{locked: false}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events, settings: %{req_not_unlocked: true})
assert_receive {:start_state, _, :online}
assert {:error, :unlocked} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if shift_state is D", %{test: name} do
not_supendable =
online_event(drive_state: %{timestamp: 0, shift_state: "D", latitude: 0.0, longitude: 0.0})
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :vehicle_not_parked} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if shift_state is R", %{test: name} do
not_supendable =
online_event(drive_state: %{timestamp: 0, shift_state: "R", latitude: 0.0, longitude: 0.0})
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :vehicle_not_parked} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if shift_state is N", %{test: name} do
not_supendable =
online_event(drive_state: %{timestamp: 0, shift_state: "N", latitude: 0.0, longitude: 0.0})
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :vehicle_not_parked} = Vehicle.suspend_logging(name)
end
test "cannot be suspended while driving", %{test: name} do
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, drive_event(0, "D", 0)}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :vehicle_not_parked} = Vehicle.suspend_logging(name)
end
test "cannot be suspended while updating", %{test: name} do
events = [
{:ok, online_event()},
{:ok, update_event("installing", "2019.8.4 530d1d3")}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert_receive {:start_update, _car_id}
assert {:error, :update_in_progress} = Vehicle.suspend_logging(name)
end
test "cannot be suspended while charing is not complete", %{test: name} do
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, charging_event(0, "Charging", 1.5)}
]
:ok = start_vehicle(name, events)
assert_receive {:start_state, _, :online}
assert {:error, :charging_in_progress} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if outside_temp is not nil", %{test: name} do
not_supendable =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{outside_temp: 20.0}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events, settings: %{req_no_temp_reading: true})
assert_receive {:start_state, _, :online}
assert {:error, :temp_reading} = Vehicle.suspend_logging(name)
end
test "cannot be suspended if inside_temp is not nil", %{test: name} do
not_supendable =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{inside_temp: 20.0}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, not_supendable}
]
:ok = start_vehicle(name, events, settings: %{req_no_temp_reading: true})
assert_receive {:start_state, _, :online}
assert {:error, :temp_reading} = Vehicle.suspend_logging(name)
end
test "suspends when charging is complete", %{test: name} do
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, charging_event(0, "Charging", 1.5)},
{:ok, charging_event(0, "Complete", 1.5)}
]
:ok = start_vehicle(name, events, settings: %{suspend_min: 1_000_000})
assert_receive {:start_state, car_id, :online}
assert_receive {:insert_position, ^car_id, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online, since: s0}}}
assert_receive {:start_charging_process, ^car_id, %{date: _, latitude: 0.0, longitude: 0.0},
[]}
assert_receive {:insert_charge, charging_id, %{date: _, charge_energy_added: 1.5}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :charging, since: s1}}}
assert DateTime.diff(s0, s1, :nanosecond) < 0
assert_receive {:insert_charge, ^charging_id, %{date: _, charge_energy_added: 1.5}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :charging_complete, since: s2}}}
assert_receive {:complete_charging_process, ^charging_id, []}
assert DateTime.diff(s1, s2, :nanosecond) < 0
assert :ok = Vehicle.suspend_logging(name)
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :suspended, since: s3}}}
assert DateTime.diff(s2, s3, :nanosecond) < 0
refute_receive _
end
test "is suspendable when idling", %{test: name} do
events = [
{:ok, online_event()}
]
:ok =
start_vehicle(name, events,
settings: %{
suspend_after_idle_min: 100,
suspend_min: 1000
}
)
assert_receive {:start_state, car_id, :online}
assert_receive {:insert_position, ^car_id, %{}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online, since: s0}}}
assert :ok = Vehicle.suspend_logging(name)
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :suspended, since: s1}}}
assert DateTime.diff(s0, s1, :nanosecond) < 0
refute_receive _
end
test "detects if vehicle was locked", %{
test: name
} do
unlocked =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
vehicle_state: %{locked: false}
)
locked =
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
vehicle_state: %{locked: true}
)
events = [
{:ok, %TeslaApi.Vehicle{state: "online"}},
{:ok, unlocked},
{:ok, unlocked},
{:ok, locked}
]
:ok =
start_vehicle(name, events,
settings: %{
suspend_after_idle_min: 100_000,
suspend_min: 1000
}
)
assert_receive {:start_state, car_id, :online}
assert_receive {:insert_position, ^car_id, %{}}
assert {:error, :unlocked} = Vehicle.suspend_logging(name)
assert_receive {:pubsub, {:broadcast, _, _, %Summary{locked: false, state: :online}}}
assert :ok = Vehicle.suspend_logging(name)
assert_receive {:pubsub, {:broadcast, _, _, %Summary{locked: true, state: :suspended}}}
refute_receive _
end
end
| 29.80531 | 97 | 0.63658 |
1c3811c892671cbc963ae599fc47fcd57558e380 | 789 | ex | Elixir | lib/etso/ets/table_structure.ex | phanmn/etso | 5b9929f6272b42c95f6fe16b12338335603e8d98 | [
"Apache-2.0"
] | 287 | 2019-08-30T21:19:09.000Z | 2022-03-19T04:34:00.000Z | lib/etso/ets/table_structure.ex | phanmn/etso | 5b9929f6272b42c95f6fe16b12338335603e8d98 | [
"Apache-2.0"
] | 17 | 2019-09-13T18:30:27.000Z | 2021-08-15T18:42:56.000Z | lib/etso/ets/table_structure.ex | phanmn/etso | 5b9929f6272b42c95f6fe16b12338335603e8d98 | [
"Apache-2.0"
] | 20 | 2019-09-08T15:29:32.000Z | 2022-03-20T08:51:28.000Z | defmodule Etso.ETS.TableStructure do
@moduledoc """
The ETS Table Structure module contains various convenience functions to aid the transformation
between Ecto Schemas (maps) and ETS entries (tuples). The primary key is moved to the head, in
accordance with ETS conventions. Composite primary keys can not be accepted, however.
"""
def field_names(schema) do
fields = schema.__schema__(:fields)
primary_key = schema.__schema__(:primary_key)
primary_key ++ (fields -- primary_key)
end
def fields_to_tuple(field_names, fields) do
field_names
|> Enum.map(&Keyword.get(fields, &1, nil))
|> List.to_tuple()
end
def entries_to_tuples(field_names, entries) do
for entry <- entries do
fields_to_tuple(field_names, entry)
end
end
end
| 30.346154 | 97 | 0.726236 |
1c38766133c0cd38bbd4b045aca92b4602422c89 | 72 | ex | Elixir | lib/chat_server/repo.ex | aswani521/chat_server | 9400a6137992a48e7bc2dd0aebf05ad56e430fe3 | [
"MIT"
] | null | null | null | lib/chat_server/repo.ex | aswani521/chat_server | 9400a6137992a48e7bc2dd0aebf05ad56e430fe3 | [
"MIT"
] | null | null | null | lib/chat_server/repo.ex | aswani521/chat_server | 9400a6137992a48e7bc2dd0aebf05ad56e430fe3 | [
"MIT"
] | null | null | null | defmodule ChatServer.Repo do
use Ecto.Repo, otp_app: :chat_server
end
| 18 | 38 | 0.791667 |
1c38951183a7f94bdb34265bdd5dbefe3a56144e | 1,541 | ex | Elixir | lib/phoenix/pubsub/rabbitmq_pub.ex | skunkwerks/phoenix_pubsub_rabbitmq | 3dc80ab94c27f6fe272c432d5cedf2cf682b7314 | [
"MIT"
] | null | null | null | lib/phoenix/pubsub/rabbitmq_pub.ex | skunkwerks/phoenix_pubsub_rabbitmq | 3dc80ab94c27f6fe272c432d5cedf2cf682b7314 | [
"MIT"
] | null | null | null | lib/phoenix/pubsub/rabbitmq_pub.ex | skunkwerks/phoenix_pubsub_rabbitmq | 3dc80ab94c27f6fe272c432d5cedf2cf682b7314 | [
"MIT"
] | 1 | 2020-12-22T05:38:26.000Z | 2020-12-22T05:38:26.000Z | defmodule Phoenix.PubSub.RabbitMQPub do
use GenServer
use AMQP
alias Phoenix.PubSub.RabbitMQ
@reconnect_after_ms 5_000
@moduledoc """
Worker for pooled publishers to RabbitMQ
"""
@doc """
Starts the server
"""
def start_link(conn_pool_name) do
GenServer.start_link(__MODULE__, [conn_pool_name])
end
@doc false
def init([conn_pool_name]) do
Process.flag(:trap_exit, true)
send(self(), :connect)
{:ok, %{status: :disconnected, chan: nil, conn_pool_name: conn_pool_name}}
end
def handle_call(:chan, _from, %{status: :connected, chan: chan} = status) do
{:reply, {:ok, chan}, status}
end
def handle_call(:chan, _from, %{status: :disconnected} = status) do
{:reply, {:error, :disconnected}, status}
end
def handle_info(:connect, %{status: :disconnected} = state) do
case RabbitMQ.with_conn(state.conn_pool_name, &Channel.open/1) do
{:ok, chan} ->
Process.monitor(chan.pid)
{:noreply, %{state | chan: chan, status: :connected}}
_ ->
:timer.send_after(@reconnect_after_ms, :connect)
{:noreply, %{state | chan: nil, status: :disconnected}}
end
end
def handle_info({:DOWN, _ref, :process, _pid, _reason}, state) do
:timer.send_after(@reconnect_after_ms, :connect)
{:noreply, %{state | status: :disconnected}}
end
def terminate(_reason, %{chan: chan, status: :connected}) do
try do
Channel.close(chan)
catch
_, _ -> :ok
end
end
def terminate(_reason, _state) do
:ok
end
end
| 24.460317 | 78 | 0.650876 |
1c3898f35d42d1cff973813936f286b4d6281f9c | 1,741 | ex | Elixir | chromoid_web/lib/chromoid/devices/device_token.ex | ConnorRigby/chromoid | 6424a9234227d18d7c287ded869caeb31511bb97 | [
"Apache-2.0"
] | 7 | 2020-11-18T11:29:20.000Z | 2022-01-16T03:16:14.000Z | chromoid_web/lib/chromoid/devices/device_token.ex | ConnorRigby/chromoid | 6424a9234227d18d7c287ded869caeb31511bb97 | [
"Apache-2.0"
] | null | null | null | chromoid_web/lib/chromoid/devices/device_token.ex | ConnorRigby/chromoid | 6424a9234227d18d7c287ded869caeb31511bb97 | [
"Apache-2.0"
] | 1 | 2021-01-06T15:40:46.000Z | 2021-01-06T15:40:46.000Z | defmodule Chromoid.Devices.DeviceToken do
use Ecto.Schema
import Ecto.Query
@hash_algorithm :sha256
@rand_size 32
# @reset_password_validity_in_days 1
# @confirm_validity_in_days 7
# @change_email_validity_in_days 7
@token_validity_in_days 60
schema "device_tokens" do
field :token, :binary
belongs_to :device, Chromoid.Devices.Device
timestamps(updated_at: false)
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the device found by the token.
"""
def verify_token_query(token) do
query =
from token in token_query(token),
join: device in assoc(token, :device),
where: token.inserted_at > ago(@token_validity_in_days, "day"),
select: device
{:ok, query}
end
@doc """
Builds a token with a hashed counter part.
The non-hashed token is sent to the device e-mail while the
hashed part is stored in the database, to avoid reconstruction.
The token is valid for a week as long as devices don't change
their email.
"""
def build_hashed_token(device) do
token = :crypto.strong_rand_bytes(@rand_size)
hashed_token = :crypto.hash(@hash_algorithm, token)
{Base.url_encode64(token, padding: false),
%Chromoid.Devices.DeviceToken{
token: hashed_token,
device_id: device.id
}}
end
@doc """
Returns the given token with the given context.
"""
def token_query(token) do
from Chromoid.Devices.DeviceToken, where: [token: ^token]
end
@doc """
Gets all tokens for the given device for the given contexts.
"""
def device_and_contexts_query(device) do
from t in Chromoid.Devices.DeviceToken, where: t.device_id == ^device.id
end
end
| 25.985075 | 76 | 0.703619 |
1c38b3816b0939ec3f6ea81062666decb90bfa0f | 3,817 | ex | Elixir | lib/paper_trail/version_queries.ex | mihailacusteanu/paper_trail | 928f1dc422c752f194176d0ebe1932224e749d37 | [
"MIT"
] | null | null | null | lib/paper_trail/version_queries.ex | mihailacusteanu/paper_trail | 928f1dc422c752f194176d0ebe1932224e749d37 | [
"MIT"
] | null | null | null | lib/paper_trail/version_queries.ex | mihailacusteanu/paper_trail | 928f1dc422c752f194176d0ebe1932224e749d37 | [
"MIT"
] | null | null | null | defmodule PaperTrail.VersionQueries do
import Ecto.Query
alias PaperTrail.Version
@repo PaperTrail.RepoClient.repo
@doc """
Gets all the versions of a record.
"""
@spec get_versions(record :: Ecto.Schema.t) :: Ecto.Query.t
def get_versions(record), do: get_versions(record, [])
@doc """
Gets all the versions of a record given a module and its id
"""
@spec get_versions(model :: module, id :: pos_integer) :: Ecto.Query.t
def get_versions(model, id) when is_atom(model) and is_integer(id), do: get_versions(model, id, [])
@doc """
Gets all the versions of a record.
A list of options is optional, so you can set for example the :prefix of the query,
wich allows you to change between different tenants.
# Usage example:
iex(1)> PaperTrail.VersionQueries.get_versions(record, [prefix: "tenant_id"])
"""
@spec get_versions(record :: Ecto.Schema.t, options :: []) :: Ecto.Query.t
def get_versions(record, options) when is_map(record) do
item_type = record.__struct__ |> Module.split |> List.last
version_query(item_type, record.id, options) |> @repo.all
end
@doc """
Gets all the versions of a record given a module and its id.
A list of options is optional, so you can set for example the :prefix of the query,
wich allows you to change between different tenants.
# Usage example:
iex(1)> PaperTrail.VersionQueries.get_versions(ModelName, id, [prefix: "tenant_id"])
"""
@spec get_versions(model :: module, id :: pos_integer, options :: []) :: Ecto.Query.t
def get_versions(model, id, options) do
item_type = model |> Module.split |> List.last
version_query(item_type, id, options) |> @repo.all
end
@doc """
Gets the last version of a record.
"""
@spec get_version(record :: Ecto.Schema.t) :: Ecto.Query.t
def get_version(record), do: get_version(record, [])
@doc """
Gets the last version of a record given its module reference and its id.
"""
@spec get_version(model :: module, id :: pos_integer) :: Ecto.Query.t
def get_version(model, id) when is_atom(model) and is_integer(id), do: get_version(model, id, [])
@doc """
Gets the last version of a record given its module reference and its id.
A list of options is optional, so you can set for example the :prefix of the query,
wich allows you to change between different tenants.
# Usage example:
iex(1)> PaperTrail.VersionQueries.get_version(ModelName, id, [prefix: "tenant_id"])
"""
@spec get_version(model :: module, id :: pos_integer, options :: []) :: Ecto.Query.t
def get_version(model, id, options) do
item_type = model |> Module.split |> List.last
last(version_query(item_type, id, options)) |> @repo.one
end
@doc """
Gets the last version of a record.
A list of options is optional, so you can set for example the :prefix of the query,
wich allows you to change between different tenants.
# Usage example:
iex(1)> PaperTrail.VersionQueries.get_version(record, [prefix: "tenant_id"])
"""
@spec get_version(record :: Ecto.Schema.t, options :: []) :: Ecto.Query.t
def get_version(record, options) when is_map(record) do
item_type = record.__struct__ |> Module.split |> List.last
last(version_query(item_type, record.id, options)) |> @repo.one
end
@doc """
Gets the current model record/struct of a version
"""
def get_current_model(version) do
@repo.get("Elixir." <> version.item_type |> String.to_existing_atom, version.item_id)
end
defp version_query(item_type, id) do
from v in Version, where: v.item_type == ^item_type and v.item_id == ^id
end
defp version_query(item_type, id, options) do
with opts <- Enum.into(options, %{}) do
version_query(item_type, id)
|> Ecto.Queryable.to_query()
|> Map.merge(opts)
end
end
end
| 34.387387 | 101 | 0.691381 |
1c38ecbbb4f3c651b8f4d422e35e170457f7c3c0 | 2,152 | ex | Elixir | lib/contracts_api/covenants.ex | gissandrogama/contracts_api | 13bcd292637d0e2bc4d2a6c05f5b3266e8bf28e1 | [
"MIT"
] | null | null | null | lib/contracts_api/covenants.ex | gissandrogama/contracts_api | 13bcd292637d0e2bc4d2a6c05f5b3266e8bf28e1 | [
"MIT"
] | 2 | 2021-03-16T06:43:04.000Z | 2021-03-16T06:54:55.000Z | lib/contracts_api/covenants.ex | gissandrogama/contracts_api | 13bcd292637d0e2bc4d2a6c05f5b3266e8bf28e1 | [
"MIT"
] | null | null | null | defmodule ContractsApi.Covenants do
@moduledoc """
Este modulo possui funções que persiste um contrato no banco.
Função `create_contract/1`
"""
import Ecto.Query
alias ContractsApi.Covenants.Contract
alias ContractsApi.Repo
@doc """
Função lista todos os contratos persistidas no banco de dados.
## Examples
iex> list_contracts()
[%Contract{}, ...]
"""
def list_contracts do
ContractsApi.Repo.all(
from c in ContractsApi.Covenants.Contract,
preload: [parts: [:physical_persons, legal_entytis: [:addresses]]]
)
end
@doc """
Função que insere um contrato no banco de dados. Essa função recebe um `map` com os campos e valores,
faz um parser para `Contract.changeset/2`, que valida as informações e retorna uma estrutura valida ou não.
## Paramentros da função
- name: `nome` do contrati
- file_pdf: url do arquivo anexado
- description: uma breve descrição do documento
- date: data de criação do contrato
## Examples
iex> create_contract(%{field: value})
{:ok, %ContractsApi.LegalEntytis.contracts{}}
iex> create_contract(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_contract(attrs \\ %{}) do
%Contract{}
|> Contract.changeset(attrs)
|> Repo.insert()
end
@doc """
Essa função busca um contrato pelo `id`.
## Paramentros da função
- id: `id` numero de indentificação do contrato
## Informações adcionais
- caso id estaja incorreto ou não exista é retornado um `nil`.
## Example empty lists
iex> contract = create_contract(%{date: "15/03/2021", description: "contrato estalece a locaçao de imovel para finz residenciais", file_pdf: "url_file", name: "contrato de aluguel de imovel"})
iex> get_contract!(contract.id)
{:ok, %ContractsApi.LegalEntytis.Contract{}}
"""
def get_contract!(id) do
query =
from c in ContractsApi.Covenants.Contract,
preload: [parts: [:physical_persons, legal_entytis: [:addresses]]]
Repo.get_by(query, id: id)
|> case do
nil -> {:error, :not_found}
contract -> {:ok, contract}
end
end
end
| 27.240506 | 199 | 0.670539 |
1c393c0f6db50ffb0f742a46c24a07f8aa1abf2a | 28,584 | exs | Elixir | test/bsv_rpc/transaction_test.exs | slashrsm/bsv_rpc | 6ac717f4aefcd26045ad15796e4129fdc6a01434 | [
"MIT"
] | 4 | 2019-09-25T05:52:02.000Z | 2020-08-13T21:09:42.000Z | test/bsv_rpc/transaction_test.exs | slashrsm/bsv_rpc | 6ac717f4aefcd26045ad15796e4129fdc6a01434 | [
"MIT"
] | null | null | null | test/bsv_rpc/transaction_test.exs | slashrsm/bsv_rpc | 6ac717f4aefcd26045ad15796e4129fdc6a01434 | [
"MIT"
] | null | null | null | defmodule BsvRpc.TransactionTest do
use ExUnit.Case
import Mock
doctest BsvRpc.Transaction
test "transaction with multiple inputs is converted to binary" do
tx_hex =
"010000004A9CDCE8E0A7BE8895354D8B07DA452AF5BBBCB53FF3D1A16E3A426D98FF181531000000008B483045022100AB43E9076AA976FB89AA66F38B261E9A2720CD4BFADC0ED3F4237C88288C597B02205E16E0F2100A6C30CDE079D339B2AC47CE8AE325DEBA1EF759F667728C7CAB580141045B34A80569593950E7E1EA8F88A3AC419DFF208205DADF095C31FE7CA36FC401B004DC7C03610C074584B852BB2B6479E30213CECF4917A10440FDD10DE6B267FFFFFFFFCA64A7E8BCB33C9E505E949F964DD4BD55C42BED6C2D113F210F1C1BEAA4E1F100000000484730440220102BB8F16D5C4137A2CBC17A1168C46D4902753BE8F3174FD7ED7145C362383B02204A730BE3E1CF4BD324268A1F1A7F823EF74F10B0E9FF58E2E7979E0889A684AC01FFFFFFFFCA85DE4CF78BEB83D12F7E00D5C2B6B90113699E2B4BB79C2CACB05D04E3F80C000000004948304502204214361DD4EA508C844AB96B3F0B3C45110BC8B6EB323D8ED6DEF93E187059CB022100C7C5854E4186ACFDA190C6E37EFE6C9D9D99B3FB60B15BD13F3AE3E87BFC60B901FFFFFFFFCB02D13A80B17CB40BB6F29A8EAE9BFBDF394D3F9601B96A683C742179C43534000000004A493046022100F0F7893D97D1A1B2203327F1F2FBB4D60053F6524507794650CB49EFACDD80CF0221008BBC2290342B0C9094BBF09510AB9480ABD890EFCC52D5E9B4FDB8BAB8A70DE701FFFFFFFFCB38858CD3826DBE47B06E70707F4476D862B2CB643BCC4CFE0214C68FA07BA50000000049483045022100F74F151343DC055B58F28C3D574CE95ABF6F0CF1B8B8C76C7DD4AEEDF90078F4022077AD5F7C6433104B2F39D67447D902D621C0CB5C8EA42370895FAA9693463EBE01FFFFFFFFCB853058E84D30B71C7BF4ABECD3AC39C3CDE8C1B5A917A6DE233E8A27FCC834000000004948304502201434B28594B7A54E0375234E326225628FBB0499992C9423A7EF4730B64793A3022100E67579BEDDD0097E727C740B47695D2248FD00F189403F17CE086FD105A3B5DB01FFFFFFFFCCF80D38F734907CD56FCAD175BC9011F5D41AE708EBA73FCFAD5DDF09A75678000000004A493046022100FF72F3BE59F709BECC1FA1FF4514C3C5D61B1867D46CB6D881C4C53928380A1A0221009D7A6F88EEDF871FFCB0FA20F5436840C776CACE5A5EA212283FB3F44D6B3A4D01FFFFFFFFCFAEEF7BDAB985B49E8DD17555AE0CFCCC9DAB643EF57902470217523FB83E48000000004847304402201E67D5161A135F5C2C461813DDEC46D2E1C7BA0F8C1E05574E6E11A4B3A812F50220756E3F7C4F690145B39E5985BDD0FD8C0F0C21C9E0EA4B567689476E1707A7C201FFFFFFFFCFE2DCD028BE157B8604AA9E1F6039BEAC5D2A9F6DF3920BF6457E0F4F6D9806000000004A493046022100CF0549ADECC556455AB5BF61D7A65D1E7D71E44CE0ADF9F2BBED946C61E7EC60022100BCDE91AEE7262DD5EC50D9C5DD82A82DBACA03A29B6D2D197A575DCCBA38E94801FFFFFFFFCFFC7133FF13E3D68DA52C9C171336F8C4DFA4A9A83291556A78B9EBD758E03D000000004A4930460221009A50EE3F526BCF34817A85C202B236C14185EA82F3DC2828FA5F65223680A708022100C9ACBA8620A9D57D88BC7DBFA8A121B5542D92B63E12B197A571F1802EB1530601FFFFFFFFD1C85D6F6C405B869B4C9A9EF55C88798E201BAF738812AB8D84F4731250B1E10000000049483045022100807E9D48150FE08DC518E75155BB3B8F04D2FBD1F59012389AE2B3878B82A8AE022078F9DF6BD876148141B3D7B82B38B4B2CDEF094C8AB162E5FE2DC177BCFCA64D01FFFFFFFFD2873120919BA1B2C78A04E814D96C7D8C1FB3C47FF0E8BD52711273431734DF0000000048473044022018FCB0B12987BBF3FF40DC29E729F9E6A842FF512FCED47E1E95B482B5A2C4ED0220727810E0EE1764A05A9828018B3909C44252E0EDDF5895A9BA22E06FEBBE2AFA01FFFFFFFFD3007277480171504A3A339B828C88A230BD895DF421575267F5A4F5BBB0E511000000008C493046022100EFF124E99FB9D39272F3D47F3D4AC28CDDD2E927C102BD1034FBEA9CD58F42E6022100E45C388D72B58DAD9F1CB5E86787824B37DDF5CFF8701B419C4A9583415B1EAC0141045B34A80569593950E7E1EA8F88A3AC419DFF208205DADF095C31FE7CA36FC401B004DC7C03610C074584B852BB2B6479E30213CECF4917A10440FDD10DE6B267FFFFFFFFD5BB1E6FC345FD545C2FA5CA9C51F49229C566052CA8033FF2F139F0322510EE0000000049483045022100F1EE8E4635471C9BB94557E3A7DB5B7635BCAB47108C7C0EED30500F2EA7CDF80220678B111C852E23FB0C096487098B40EC08BBAF887380042845A2338C7535B92001FFFFFFFFD770AF35002A9723E46F7709A473A51E5A03435FEA4C581B9D26F1A3DCB3EFFC000000004A493046022100F85681BDEE6F0BC373F229964997A3F9461158EE9C9B3D3CA886A893AB7A3A99022100971CAE746339647306AD3E1020E200AC642F56996B634E14A4BBF81E0981127001FFFFFFFFD7975746C1E3062D7762824B02C3F3711D6574CB9C939B7A775DF361FC3955DE0000000049483045022100F06164BAF12930F53E49F3541377502071F40CC6E5F04B7784241C6323A2DA81022008B18F104351F2104DF81023DF651A12C645688226FCD68A7C1A2AD95756D00A01FFFFFFFFD7BD3D009192FEECE5970BEEC1CC9AA93827A9A3C10DBC1F09418E92F610A397000000004847304402201B65434B05E4E654ED25F4FBF852294649EF4DACFF6B07CEE0D40DEAA753E0E502205C7FABD2480449127DCB6A4A25B24E843C3C636EDEF7FD9A05E6D1A2E37EF9B501FFFFFFFFD809725292B979FE00B18D7889A0023CC297759E2A8ACDFA17D1BF1D94B20C6300000000484730440220768519ABE4D029EB1DF8C4A3904299AA1890A52DC65FF17977F617F370E55BEE02202D92FF6CE7DE48DEC50A7904106FB31F33AB1F5D019C7940C5ED1AB0DF8F665101FFFFFFFFD884904C91C93EB210C9DE12F74E59660741D6B3D16ECF41001DFF66A92DB9A7000000004948304502205D55C41059FB7A56828EB2A54285E310E6CC904CA07896D3113764C596EA34EF022100BCDFEEA94EA15CF44FDCB0D824D80F52793C0915F3673E989FC28EA86B414C1401FFFFFFFFD8F1560900B263C89FD64DBED054E743BB834D3C028EA86E3418A17ADD48DFAD000000004A493046022100835AE082E3E1D5D4F3FB1D7F45FE2D27A0706E81BAF2E5BA44D12A2890752B5B022100E05A652770598DCCB3DE04620349A708CC3ACBEC3C83C168ADB02DD7801C28EB01FFFFFFFFDB0B0946CEB1AA08EA180CE891697BFE5A3038645EB46B95E7D784ADF1C61916000000004A493046022100F72374764265658EAB57B6B6B6680CFBC31FDB72930FEC37F41139D01A28955F022100A66549EDC1A75AAC7AFC0EFF6F93A9ECB6497D8F732B536AB71C02584A78C8AF01FFFFFFFFDB198FAA18FDE5D4F30B43D9C14CFF7B840C201D0022E3F805EB5DE7FB6059060000000049483045022017FAB63A25641B6BEB4239BF52BBDA8BE2BA1C090CC075A1332A9458B37EEFDD022100B034601631EF555859FE3A842CCFE59273DAB0494361F35D1CD641A0455F2F6701FFFFFFFFDB30E300E71E1127A999BE13195E6D220357D434669C94B92BA07F96CE65F5200000000049483045022100D384857C752FDA11EC47726CD1D414979991E8F5F6A21DFBBA04BD895F658A3102202D2AC7E22240CC4A94C0EFF3D900C800680EF92AE556499288BE24AAF870518E01FFFFFFFFDC4EDF1736358E38C69C72176B7126CB9A3CF751C7BA3F75E12CBAC508342BE6000000004A493046022100F961A53BCC28ADECACD2B500747A8DF6BDC6864DCFA9E83B18AF19C904D5B5F1022100A477E051EE9B4ABA7A2C23F9AD05CB230C213491FE9129D2A496139D0EFBC49201FFFFFFFFDCD0D03940D177BB3AB7B6F1B859F7469DC4695DCC1A1BB206BE79477B89034A00000000494830450221008ECE9B49580BA4E1F274C8A9E1B11B73B13B51644D49BD02AFDBC95CE157B141022071CA0FEF8A61D26F3C5D64CD2E5A38C8FC62050AA234AEF8F5B120352E80B25101FFFFFFFFDD54D8F06D748AD47E7BEA8ABDACB89708E9F8DD36190B4DE64EC3990D476B2C000000004A493046022100B11D5ED42A83B6BEF7FAB193897AA1104CC656398246FD1548798D9CA6D7D95C0221008DEDC2EE4F9042549734C3D3BB0B745231CDD02D323151FB5EF3C69EB96789B901FFFFFFFFDD621D9E711348E98349EFFE8A9997D4E5BAB45AD99853CDEB48A43A0430AA3900000000494830450220111DB279383219491F648C6A59260F00966E3D2FB84B4E6AC6E85D272DCBFFB5022100E32D9A475371CE94B98B6A5B3FDC4CCA5CC840AB1DC137BFE800C74176C7C40C01FFFFFFFFDD8ECE78AD86D1D368CDEB8C59B09A1E6470CC5ABDF7669E5C2D5DB3C090471D000000004847304402205B3DB2AC3D6A10BED97F3F3EF3C83AD1421009120B456597670B94BF1A4A181702207905C50CDC12A82338781F5B093F0F95A5A495B01035FCEDB414345128DA702401FFFFFFFFDDAF73230B098737CE80CA081D26DA02F25666FD8BB77077616E6F3FCEBD0693000000004A49304602210095EC3BA7088FA8222803B85672ECFEA666A7E851AF49CF420AA19775B8FF331A022100A9139DA820B69498ED7BF083C1A516E24ED780D5AC8EFB6F35332A0B43DACF0301FFFFFFFFDDC11DC17D717F175E1A683EB4B435D1ADB35992EB70244C3646BE80EB8272DD0000000049483045022100FB515756A05E5651A5B2E597158CD2BF0F81A759C15B38FA798F92A197DECB7502202CC50CB2073A1FF448586DED01C3BDAD34B5DBB1A4A9EEE6C02AD80DE047DE6701FFFFFFFFDF34BEC6F13DF98F91EDFBCC8B6E3A6A8A71EF040C6522B2A56030D546D87AF50000000049483045022100B28324E9031C3FE397A505D03C4ADBE6461F5C5AA58E2DE691545551F8B24183022070D565349DF87B34E9CBB628244A278D044162DBFB9C9F8746D1448634BF561401FFFFFFFFDF5AD4D603E79ED672B90B05BCA4C4A326508B743F189889BEEA3EF12C803AE4000000004A49304602210080690306B4C5B37CE3497D71A49334A46184508AEF5F7EC26D1ED2C6A81E94C9022100B7DC2B03C16A1139687795DEB73B257764531D5D60CCDD1FC18ACA54F0909B8D01FFFFFFFFE253F6EFE8D88E39AF4F45BC4D87BE7473AAF2B3BF1634D96BCF6B97554BADA3000000004A493046022100EA97E7C111ACD32D7EE497A227E32985D0482673760A6D9D477F38AB06B0B96F022100AC2B692E4B83ACBD12CC192CBF802A76BC6FE541DDDABB3DE34C38B90CE946ED01FFFFFFFFE2A95E7377B39F2F70BD42A6A5DB0F2A81DA9DD12AC89EE77D7EC2E9B2AFBEE6000000004948304502205A2A6F5F8641B99B64F60E6820B62A0EBB92E715F6735784F3C8F62356133B3502210081788972D45AA1CDF198236BB8C50C0720FFD448029F0FAE769249E184FCA3D701FFFFFFFFE4D252AA5064A79A3D94034E36BA11559634049B5CFEB049BD2E749C863ADF590000000048473044022044EE0785AF4965813DB1C10C7EC553BFA437E8724A62172BECF06C3C6BAE442A0220165D6C9681E9DD711146E1A24982CA0F1A3F7B4F75EED475377BE531F1D08FE701FFFFFFFFE4E6F3E455B6DE2FF41ACF4D38BF020D2985DA0C55F3F393264F1CBEB26038780000000049483045022100F31FA08D9BC223B82E8913425249E42E6A8A319A418F3F4A6173E0E4DA23B30402207B31D68597BF0807A4CBE74781E799BE0598C418F59D4E8C8BD2B8D5279FCB0A01FFFFFFFFE4E79CEDF60F92DD8E2BFF4A212BAE82EC2AB32A19D291F873A52A8404219044000000004847304402200DA8A460A3201ABAC60A7F075C866FAB087EBA23BEA4E0CCACC57B06FC349E4202203F6577F8BD7E1BD551EF86E961D84D46F16A1E0B1D4C4210484DF0CB09F3CC4B01FFFFFFFFE5F3F031E73AE0DE965D8DF6E2F9C0CF810C5B905310945A31DFCA7CA39D23D40000000049483045022100A28C32DE6EC4068592A2B41C05E12FA1BFAAC4D9A646E6512C820BC0A89EB0D402206FFF73AA7D11B65899A63022D44804CECE1A0669E033CF509523731C1CFD6D8C01FFFFFFFFE5F953A0F61F8FAF62D98AB6A6297B6522BAE1CB79BBA3177C8B67342F67E693000000004A493046022100E7BE1D671816A7A444203A35FC7F742F0805EC5D84B206A2276A4988089CE435022100A75A1CFAC94F6C62DA9982913FA1D733C8ED0CB5EEFF1FCA7048240C615E152D01FFFFFFFFE6CC6293CD211A4FE704E9844899EB3E1F600C126901F93170FA0A1B065CA0D200000000484730440220241E6AED01B510D1803B502574B826BCCFED1615A31FE31A287B310A7C234A17022033CE89B10B33C0055892B855DFA4B50A1C6022587794FFF8850B9FF61FC0DB6901FFFFFFFFE6FF18B6AB1F74CF4027121E58EB319CFBB673634BC2B0B4AAA9F8DEC53CFC8400000000484730440220445E33890C552D1D6191B4D686711B32E2316F51E44B210C87B232CD0574689B0220029D92FB60B2710973E097CC7BA52CEBF78635B2A24D3C6DA9BEE9BC24DE649401FFFFFFFFE72FBA813859FAACDE0D1F15DAD3DEE0A8DE3114052EC4DD573D26EB29091DA8000000004A493046022100959A01CE70461F18CC04BD1CF95B8AF540AB2E908C5257B099207308CF0118A2022100E38017660993FDD65AD7CAAC3CBCBCA95359E00B6AB261783E847EFCC1D8B5ED01FFFFFFFFE74EB34B26AB31D8A07C06CBA572BBF14154AE7D68AA5ECC2A981B50F5F3B67100000000494830450221008D7458EFBEC4331253D5357950A180A0BD983DE0B308242111BB148188C027CD022005C8E9012032D68DF232D899768063D0AC6636205A881657A35371917D7D708701FFFFFFFFEA0D6050E3B3743C50931DFAAA57B3B1889AC76975050132FC93727E7D5926650000000049483045022100CBEEABC774479AEBA630A72F334A98D228BBAD919A34D1CD01DF707AFBFB911702204E2D8E0C6BA60580A93B4846A1DFDFF0DC3023E26310672CA85AF4C4641400F401FFFFFFFFEA9D80887C4DBC68EBE4E7AFF3F42E4F641486C0E3B9D06BDAAEED39B9A6D5C90000000049483045022049F0C2B73C239A39EF7153A10B89EFDD343D47810209D83A42756161E8D193D4022100E71CED0887B71BE9FB375692517D31A5BA42547F9C4E883F635E4F132F23208501FFFFFFFFEB97DD4305C3FAA44499AC00FE5C8F335C5F3DC8A5793621AA2FCD15C637404B0000000048473044022078A9FC630E59DA0BBDE83B2B5E60668A68EB23DD12670A4A3A91DD626D98AED802203462875836DF62E038D8DF2DD1560E15979F07D806852CF4B5B2FDC93B42327E01FFFFFFFFEBA9D75F1627E1497C301CB796116AE641D34440237D7DBDA246E74A16DB280A0000000049483045022100FF55D0343060B2875CB34A26DD10621873E56952E3C45769B1B815E785734A2F02205D6E5F6A0309B93F670A32534CCCC9AD4D28BC1005CA8D49712194E59A69E7F701FFFFFFFFEBF07EA14CBA7FB299D7A71212AFB98A84A4FB3FF8DB42CDAAC3C46EE2F7D5A70000000049483045022100E26F18173150BB2BF0E5B2130B84C0BF0FC92706AE979B6F4552D3B1F74D6907022003C3E8AADFB4BD61D9BCD987B8AEF8773038A5112985AAE93786F9BE5149887501FFFFFFFFECDC5B53E2F1D880FD5510DF997323E0FA9A77EEF734DD34F4D2D4471D5E7BAA0000000049483045022054FE96102C590C71ED72BA884D5566DC19D05FD0F4C4B2356A2727CA8F70BC35022100FFB9EC17344AB8658021B9C5D1E9764008D61C5FF5D4F08778A33417F1A2DE8D01FFFFFFFFECE59E7CA8A10FA6C550F0F157B8AE7541A7C46287980B71EBBF32EC9FD86A0F00000000484730440220244B3A33967C8B633C73F8BE5796B27976723C15FB61A5D44D527FD581E7DF3D0220637B4C32434AC41BB7A72CF8CF604B463E55D624B3DACFCB46C20BE2179D3FB701FFFFFFFFED2095875649A6619EFEED6CC2734E0080ACDAF30EA190BF7DEC0724C1BD029E000000004A493046022100FF43C2EF0E270630F6C7FA230FA067C195867C3E13BC7EF825D041C0C8D55B7C022100EDAE02BEA39F69D643805AB8BEE2AF3E84450EDCE29A76F66225C67A2476C4F401FFFFFFFFEDFB27A0473501362827BE21FBB5B7A099F9A775B86EDA5D3FC886583D3539920000000049483045022100BFF29AC87FF41DBCB9CC8264927FB3E6FB075B7F275199EE1461540093A3BF32022066BE4DC056B1DB891A33BFD8F93EF656096CE9A5FF2FBF0E188541C13141EE1D01FFFFFFFFEE57CE53F0FFA6B6FAD84D3A8F482A92B605DBFA7E4BB872DF3D216A933B5A400000000049483045022100A589C67AF00412FC707D332EF654E2181C2ACDBC3C305E1F199B098A25C5A2270220776C1D75E9EBA7ED3D5EB8F4F1DEFA84A6229800AC19B4BB6245D313BED1B26A01FFFFFFFFEFB58708C9596916D1F3F3919D7BFB900EF37092FF4663BF60C471FD3B8FCFA0000000004847304402203A453E89FCBE52A4D5137A6DACCC9880FF160B76844F80BBE5BB7C8EA6472FB7022070FB6A06497F93EF73FCD83C641FB1B18B4343F4A4F91CA039E5FD6C50E33FCD01FFFFFFFFEFF2C490319560A844BB813ED78E82094547393473DD919B3C8EBAA05083337D00000000484730440220769BA8B826BB12C3E321911186F01706D43B4A769FA6BFE1A115D216FE494A890220164C8DA13F48345AFE37E0867975155C83646276C6FAC6B66CE30324F87B087501FFFFFFFFF281FE59D51C0BCC4ABAAC5B19A043F34B722B75D78659CFBF730490083DD9D100000000494830450221009C876B9421E0EA9193DAD73308799F7E958325198E577679CB27FB321D895BC60220571F8BB1773579915DF05991B6BE586FD18763B2CA1437D01CCF2704443F455E01FFFFFFFFF2C6ADB61451A99C4E72C165936E8724BFD403F4F4B24104820FA1D5E7A87B46000000004A493046022100EA78E3D438AE9BFD930D3C7D08D3B9FB5622774983D0D1E927C23EDD251807CB022100ADD43833D586EDA7A2BBE1D8D8CD39170276AAC9EE28A4790F66A36FE5D8690B01FFFFFFFFF4E086390D0340E8073D7C175FC21DE2C6725004C20B2CE144FE5F087CBD26460000000049483045022100DFFB11F832C6BC5CE87CA237E0798A1A990FD69DEA0D91C36987AEDB9E31C9F30220571F8EC38D26A9775273DCCD7CC71B53CB819F8DE538C51EAAA805B16714CAAA01FFFFFFFFF4EA8527EC471A522550C9B94E1441D686A9471421739C2498B3EB40C6685C8A000000004A493046022100CC57AEE9BC1D7EEB9D2BF0648036883816D9A837372F35C15A6AED1D81E353C20221009A0D3C2A242487AA3E81BAEA830C4E401DAA8A293346F0D0E8D0880B4A657AFA01FFFFFFFFF6F4064C44498F2074C98B39A4C3637617688616A03256C389435D5AB9020884000000004948304502206111B04FF00D86769B13A4F1CFCC2BB97F1922967B167DC76C42BF9821759DB7022100EF2B80A7C586A7BF2AED91CD1E57C828F85B9E56C8DA0FDA6C5AFC336F84E3D101FFFFFFFFF71DDF9B8266E537740DCF4EF501402970F44C83D52D36C9918725450FA665EB000000004847304402202F45C00324DF41CFFFC0F72BAF31B97F9F8A5461BB046F9FA41BD3A5D9D5F72D02201CADFA9CFA1D7265793020906E4CB716EC352BD9BED87DF75E7172900A4A13D201FFFFFFFFF772FE491B5B8F9DB3E7ACF989AE3CB6C805CDE1E8B437B6A50A6C7F40B229CE000000004A493046022100E9B2FF943EABAFBA5C4621FAA5E2CDE760FBCD365F58F46F1CFFA3D399FF43C0022100B8D4145E99A97FCBDF604EF6318FC211C8BAB5357697128E3AFB35B86DB5696301FFFFFFFFF7D0EF928F782C6590F1BCF47482CC9A37E32914D1CB195646F98039FBB3D5F8000000004A493046022100ECA9759FBC7BE7806AEC3E7A76786707C9CA9C6233F72D61B36EBCEA6A171C4F022100A8AB735A26A5669E95B3317E3EB055F84B141B936AFA8EC98B8E4CEAA03914C901FFFFFFFFF824BF0D535431386EAEBE2D6B783DAE0C7927656F75EA8072D851ADD140BCC9000000004948304502200A65AE91810E89499D5EDE10F02CE32B17F1BD7A73E8B4598535FFE5755874A4022100969BA2337CC7569AAE0ADD2A4E01386A4F9303388A483E40C669B5961846FDED01FFFFFFFFF86D6A31B28217A5AEF130C6B9B62802A68686A144408DDA51544BF52248515600000000494830450220371FC2A7115D4CB6A565B4E5C9F2ADFEF0D1A86C9E4882D02D633A954632AEBD022100E9E00146B6F11B36835C7AE29549E43570804B59FF5EFBCC637308B045B47BCD01FFFFFFFFF89CD618F2207BE265204D3395192E9A89A07C676424F1658EFD83EAE0655769000000004847304402205C3845FFE0C94BD687BF4D7B1CDA768C8CEC950FFE6A2B490AFC57A222022D9C022025144819035815D9304B95865A21CB272DEF88F6779706CE193A64AEE276AA9C01FFFFFFFFF9C9A09692125225D6F50C47F826DA1FF249CA686EC4796B4F4506F0523DB9DC000000004A493046022100F8E1B186A0DA0A7E6512810CF52209BAA2E52642E749B4A5B366ABD18666B018022100E67621A713064CECA95CB501D00A07E529E9BE469F482FC03828C65A30DE16CB01FFFFFFFFF9D8B76C7643AB980C66A54814BEB84D371F43B94BC76F5CD302D27E067210570000000049483045022100FA42041B5D73C8B299773C5006ADE152ACF2E67C1892A2A53325B442724C42E10220246780CEE7E8D121897E9F09C8222D37C0C26C9B032B41B7386890E526D694CF01FFFFFFFFFA28410FBD5DFD1771B2671E63F1ACD5146C72231D239C737749011FA8AA06EC000000004948304502203F41C1036DC1265A641039AD4914C4FA99D385E8DC8BAD222BC84DCDAFB418AA022100BD9611921120886FE3F2955E0DCFE88CA58934336FB54C70DA678A82775F356F01FFFFFFFFFB7E970C150F457E830480A9ECDC7D52B1F1E089814DD9F3E786DD9B63854CB20000000048473044022054EAE691DAB6EDFAB71583B69375121548EF6E994E0A1D385CA429A5633FA5C9022021CFC06D223864110D119A90DA3B11FEC09881C9255E7D06ED8C9B37A0BB739E01FFFFFFFFFBC596D8594AE6A007DDAA87EF0DB1F820076BC27342944E2DD8C6890B392D130000000049483045022100A7C042DED948E6079B2CC6D98DB02BBC79C2410D80E8CE712C880A7BED1DE71D02207CBC291DAAE75134204A10D8A12BFD4548D97ACCE0EFAB0AD3967AD57BEF87FC01FFFFFFFFFE1E9A8E1B22F0E81BEE126A92BA0B3BE4B16C137B94E6AC83876F488407BE230000000049483045022100EF00E4121F13F8B3D6EDDCC94AE1A9BF1C9AD2AC72D08F599F68D0C36036E1D702207B8FAE05518B7782659C35F9932EA114995E809CC07E39F4B1EC6526AF73D9EF01FFFFFFFFD316084E396DAE4DF68A22D7538E7B623B04602029CD5D7A957F89EE9FA7731C000000004A493046022100ADE700CA5D93559DF5A4986E8D9C43C33D6A4E204ECF785921279BB5419F62C7022100D101A7A5488F955E90EFD41E5293A6C87BB955EDFA94EAFE30796F8D2D95A76601FFFFFFFFB79ABD47EF890602A23E2A7EB8D12B6D448A8EABD907D2A58AE22C900EE2E4920000000049483045022100C7ED449F532F5BD236196C5075092C3C0E7307877AC4E8B446DE17F623412881022002EF45165A8BD0306AD24D080BAB804095C67C91DA2C48F8B3AF9F8E3170A8F801FFFFFFFF01007A5894750000001976A9147AA6DC533BC3D2BA2245643115C77EB3EAC121AB88AC00000000"
tx = BsvRpc.Transaction.create!(Base.decode16!(tx_hex))
tx_bin = BsvRpc.Transaction.to_binary(tx)
assert 8617 == byte_size(tx_bin)
<<start::binary-size(20), _skip1::binary-size(1000), middle::binary-size(20),
_skip2::binary-size(7557), finish::binary-size(20)>> = tx_bin
assert <<1, 0, 0, 0, 74, 156, 220, 232, 224, 167, 190, 136, 149, 53, 77, 139, 7, 218, 69, 42>> ==
start
assert <<73, 48, 70, 2, 33, 0, 207, 5, 73, 173, 236, 197, 86, 69, 90, 181, 191, 97, 215, 166>> ==
middle
assert <<210, 186, 34, 69, 100, 49, 21, 199, 126, 179, 234, 193, 33, 171, 136, 172, 0, 0, 0,
0>> == finish
assert "7DFF938918F07619ABD38E4510890396B1CEF4FBECA154FB7AAFBA8843295EA2" ==
Base.encode16(tx.hash)
end
test "transaction with multiple outputs is converted to binary" do
tx_hex =
"01000000018C40F3C4B631C09933492E65974A75DD144E8ED68DEF564431CEADA961E796A8010000006B483045022100FF1FCCC31B9E2261196E95DF20C8AA16F5EEE2D732A81789AE8D3AA4E561D6AB0220283508814372BD6121E9401C8D3DF5650A148924F71F2495438A618F6C761F84412103CF770689EB67BFDECDD4CEC105FE537C8D97C8FA4A87C6B5CA2AD2A0012E8B1CFFFFFFFF0260AE0A000000000017A914996CD7093EFB1C9776E238CEB0E4C47C5A36CAF587B4124000000000001976A91487565A68A79DBD3927C219C4F9E36E2864D3D2FA88AC00000000"
tx = BsvRpc.Transaction.create!(Base.decode16!(tx_hex))
tx_bin = BsvRpc.Transaction.to_binary(tx)
assert 224 == byte_size(tx_bin)
<<start::binary-size(20), _skip1::binary-size(82), middle::binary-size(20),
_skip2::binary-size(82), finish::binary-size(20)>> = tx_bin
assert <<1, 0, 0, 0, 1, 140, 64, 243, 196, 182, 49, 192, 153, 51, 73, 46, 101, 151, 74, 117>> ==
start
assert <<247, 31, 36, 149, 67, 138, 97, 143, 108, 118, 31, 132, 65, 33, 3, 207, 119, 6, 137,
235>> ==
middle
assert <<189, 57, 39, 194, 25, 196, 249, 227, 110, 40, 100, 211, 210, 250, 136, 172, 0, 0, 0,
0>> == finish
assert "3F18A5F830BD297F83439992672D7C99E2FF4E54BA7C2199043FD47F8B8D5BF4" ==
Base.encode16(tx.hash)
end
test "create a transaction with change" do
{:ok, to} = BsvRpc.Address.create("1wBQpttZsiMtrwgjp2NuGNEyBMPdnzCeA")
{:ok, change} = BsvRpc.Address.create("18v4ZTwZAkk7HKECkfutns1bfGVehaXNkW")
utxos = [
%BsvRpc.UTXO{
transaction:
Base.decode16!("4A5E1E4BAAB89F3A32518A88C31BC87F618F76673E2CC77AB2127B7AFDEDA33B"),
output: 0,
value: 5_000_000_000,
script_pubkey: <<>>
}
]
{:ok, tx} = BsvRpc.Transaction.send_to(to, 4_000_000_000, utxos, change)
assert 1 == tx.version
assert 0 == tx.locktime
[input | rest] = tx.inputs
assert [] == rest
assert 0 == input.previous_output
assert <<74, 94, 30, 75, 170, 184, 159, 58, 50, 81, 138, 136, 195, 27, 200, 127, 97, 143, 118,
103, 62, 44, 199, 122, 178, 18, 123, 122, 253, 237, 163,
59>> == input.previous_transaction
assert "" == input.script_sig
assert 0xFFFFFFFF == input.sequence
[output | [change_output | rest]] = tx.outputs
assert [] == rest
assert 4_000_000_000 == output.value
assert <<118, 169, 20, 10, 63, 39, 5, 95, 134, 238, 22, 182, 35, 80, 229, 135, 46, 13, 197, 9,
176, 72, 193, 136, 172>> == output.script_pubkey
assert 999_999_772 == change_output.value
assert <<118, 169, 20, 86, 209, 229, 225, 200, 165, 160, 64, 184, 37, 55, 2, 13, 124, 118,
184, 15, 15, 111, 242, 136, 172>> == change_output.script_pubkey
end
test "create a transaction without change" do
{:ok, to} = BsvRpc.Address.create("1wBQpttZsiMtrwgjp2NuGNEyBMPdnzCeA")
{:ok, change} = BsvRpc.Address.create("18v4ZTwZAkk7HKECkfutns1bfGVehaXNkW")
utxos = [
%BsvRpc.UTXO{
transaction:
Base.decode16!("4A5E1E4BAAB89F3A32518A88C31BC87F618F76673E2CC77AB2127B7AFDEDA33B"),
output: 0,
value: 5_000_000_000,
script_pubkey: <<>>
}
]
{:ok, tx} = BsvRpc.Transaction.send_to(to, 4_999_999_770, utxos, change)
assert 1 == tx.version
assert 0 == tx.locktime
[input | rest] = tx.inputs
assert [] == rest
assert 0 == input.previous_output
assert <<74, 94, 30, 75, 170, 184, 159, 58, 50, 81, 138, 136, 195, 27, 200, 127, 97, 143, 118,
103, 62, 44, 199, 122, 178, 18, 123, 122, 253, 237, 163,
59>> == input.previous_transaction
assert "" == input.script_sig
assert 0xFFFFFFFF == input.sequence
[output | rest] = tx.outputs
assert [] == rest
assert 4_999_999_770 == output.value
assert <<118, 169, 20, 10, 63, 39, 5, 95, 134, 238, 22, 182, 35, 80, 229, 135, 46, 13, 197, 9,
176, 72, 193, 136, 172>> == output.script_pubkey
end
test "create a transaction with insufficient funds" do
{:ok, to} = BsvRpc.Address.create("1wBQpttZsiMtrwgjp2NuGNEyBMPdnzCeA")
{:ok, change} = BsvRpc.Address.create("18v4ZTwZAkk7HKECkfutns1bfGVehaXNkW")
utxos = [
%BsvRpc.UTXO{
transaction:
Base.decode16!("4A5E1E4BAAB89F3A32518A88C31BC87F618F76673E2CC77AB2127B7AFDEDA33B"),
output: 0,
value: 5_000_000_000,
script_pubkey: <<>>
}
]
{:error, "Insufficient funds."} = BsvRpc.Transaction.send_to(to, 5_000_000_000, utxos, change)
end
test "create a transaction with custom fee" do
{:ok, to} = BsvRpc.Address.create("1wBQpttZsiMtrwgjp2NuGNEyBMPdnzCeA")
{:ok, change} = BsvRpc.Address.create("18v4ZTwZAkk7HKECkfutns1bfGVehaXNkW")
utxos = [
%BsvRpc.UTXO{
transaction:
Base.decode16!("4A5E1E4BAAB89F3A32518A88C31BC87F618F76673E2CC77AB2127B7AFDEDA33B"),
output: 0,
value: 5_000_000_000,
script_pubkey: <<>>
}
]
{:ok, tx} = BsvRpc.Transaction.send_to(to, 4_000_000_000, utxos, change, 2)
[output | [change_output | rest]] = tx.outputs
assert [] == rest
assert 4_000_000_000 == output.value
assert <<118, 169, 20, 10, 63, 39, 5, 95, 134, 238, 22, 182, 35, 80, 229, 135, 46, 13, 197, 9,
176, 72, 193, 136, 172>> == output.script_pubkey
assert 999_999_544 == change_output.value
assert <<118, 169, 20, 86, 209, 229, 225, 200, 165, 160, 64, 184, 37, 55, 2, 13, 124, 118,
184, 15, 15, 111, 242, 136, 172>> == change_output.script_pubkey
end
test_with_mock "fee is calculated correclty", _context, GenServer, [],
call: fn _module, _context ->
{:ok,
"01000000024fc9d5b1142f83a9778c2d0ff054c83d95b68bbb569020dab23dc76223304a0b010000006b483045022100a07d6a99d87b327574c4398248f4890a36dad4011b602b488d14aa2dbdbf2ace02204570a0f4d9075f34acb65c0caf62d7e1daca1d8311e6840778376b8a4c3e5e6f4121035773e636bc13ebe9f49dc077dce4c9c5e18168133123352d7957159f8e3a8d54ffffffff2ef1e20c17130d20660728f89e10ae8fdd4ddb83832034fa16268b3aa83d3ad4010000006b483045022100908e7ccd4ce12419cb3c618bbc7121eea0036aa6c4ac250b15a42eb84fb99d72022032b4ff69fd16007ed8be1299835e4581bfafe59d09e88521481dd718d35c0aee412103b350536efa8a004a50369a02ae1b04ebf5855456d35a18c4115b808057d168beffffffff02c0cf6a000000000017a914690f0f15d469ec9d6e7f4346d76fe94abac2803787f0071c05000000001976a91456198dbb2c1c991443cd6e297d36f93a927ca77f88ac00000000"}
end do
tx =
BsvRpc.Transaction.create_from_hex!(
"010000000114F6E0A8242018CEFA4236493377023331E5AB4E981729557A8AAC33A58AD372010000006A47304402202C2605D54CA2FCABA8A75456BEA39C2B2D7AE744F562D06990A449E5F5A3FEBE02200BD37B90DA97D0E69ED2B3F91D82E5D4344564CF5B699AD1AD7F232888C815FC4121037328F4FA4F446697A5984F9173928D5AE5A64CCD58576F3C73E4C794CA759ECCFFFFFFFF02E06735000000000017A914690F0F15D469EC9D6E7F4346D76FE94ABAC28037872D9FE604000000001976A914F249783130CC20934267803DB3C037A21FF9E2DD88AC00000000"
)
assert 227 == BsvRpc.Transaction.fee(tx)
end
test "transaction hash/id is calculated correctly" do
tx =
BsvRpc.Transaction.create_from_hex!(
"010000000117df7322b8435c240754d9d4b8230fb67efb94be8c811c58ae672fe41a621b92000000006a47304402203ef265114433aa660555ad06077477ca8fef2a25d60f2123d6302779bdd6fa590220236a0053eccf07d92789d4e3cd0cd6f1bdb58dd5c7f04b3b608180b0d3714a43412103dceb1793dddb6664db904be9958a3a511fcb50a0199659231d0c5f83f3ff9588ffffffff010000000000000000766a046d657461223135346a747746576d5946375346477a713631643679417275777071466b6173673840366435376338643532383433373935393063663638663862663132646330326532353139616137326365386634353637306438613232626664633232323064640b5465737420666f6c64657200000000"
)
|> Map.put(:hash, nil)
assert "F2F412D9C28472BCB40204DF8636C5154AEA737504A1865529BFE3D13D848F28" ==
BsvRpc.Transaction.id(tx)
end
test "number of keys should match inputs when signing" do
{:ok, k} =
ExtendedKey.from_string(
"xprv9s21ZrQH143K42Wyfo4GvDT1QBNSgq5sCBPXr4zaftZr2WKCrgEzdtniz5TvRgXA6V8hi2QrUMG3QTQnqovLp2UBAqsDcaxDUP3YCA61rJV"
)
|> BsvRpc.PrivateKey.create()
tx =
BsvRpc.Transaction.create_from_hex!(
"0100000001040800A41008F4C353626694DAC1EE5553FBD36B11AC5647528E29C7D6C89BE20000000000FFFFFFFF0200F90295000000001976A9141D7C7B4894BE23A6495B004157F3A1BBA173C52988AC0CF70295000000001976A9141D7C7B4894BE23A6495B004157F3A1BBA173C52988AC00000000"
)
utxo = %BsvRpc.UTXO{
script_pubkey: Base.decode16!("76A9141D7C7B4894BE23A6495B004157F3A1BBA173C52988AC"),
value: 5_000_000_000,
transaction: <<>>,
output: 0
}
assert {:error, "Number of keys must match number of transaction inputs."} ==
BsvRpc.Transaction.sign(tx, [k, k], [utxo])
assert_raise RuntimeError, fn -> BsvRpc.Transaction.sign!(tx, [k, k], [utxo]) end
end
test "number of utxos should match inputs when signing" do
{:ok, k} =
ExtendedKey.from_string(
"xprv9s21ZrQH143K42Wyfo4GvDT1QBNSgq5sCBPXr4zaftZr2WKCrgEzdtniz5TvRgXA6V8hi2QrUMG3QTQnqovLp2UBAqsDcaxDUP3YCA61rJV"
)
|> BsvRpc.PrivateKey.create()
tx =
BsvRpc.Transaction.create_from_hex!(
"0100000001040800A41008F4C353626694DAC1EE5553FBD36B11AC5647528E29C7D6C89BE20000000000FFFFFFFF0200F90295000000001976A9141D7C7B4894BE23A6495B004157F3A1BBA173C52988AC0CF70295000000001976A9141D7C7B4894BE23A6495B004157F3A1BBA173C52988AC00000000"
)
utxo = %BsvRpc.UTXO{
script_pubkey: Base.decode16!("76A9141D7C7B4894BE23A6495B004157F3A1BBA173C52988AC"),
value: 5_000_000_000,
transaction: <<>>,
output: 0
}
assert {:error, "Number of keys must match number of transaction inputs."} ==
BsvRpc.Transaction.sign(tx, [k, k], [utxo])
assert_raise RuntimeError, fn -> BsvRpc.Transaction.sign!(tx, [k], [utxo, utxo]) end
end
test "attempt to create with invalid blob" do
assert {:error, "Unable to create the transaction."} ==
BsvRpc.Transaction.create_from_hex("makes no sense")
assert {:error, "Invalid transaction structure."} ==
BsvRpc.Transaction.create_from_hex("010000")
assert {:error, "Unable to create the transaction."} ==
BsvRpc.Transaction.create(<<0, 0, 0, 1, 0>>)
end
end
| 107.05618 | 17,242 | 0.885915 |
1c393cdc8712cfbc7559fa64ebabc885e0ab550e | 535 | exs | Elixir | config/config.exs | sethforprivacy/farside | 720b049838d6af97c4f14faf454f3a9944f78a88 | [
"MIT"
] | null | null | null | config/config.exs | sethforprivacy/farside | 720b049838d6af97c4f14faf454f3a9944f78a88 | [
"MIT"
] | null | null | null | config/config.exs | sethforprivacy/farside | 720b049838d6af97c4f14faf454f3a9944f78a88 | [
"MIT"
] | null | null | null | import Config
config :farside,
port: 4001,
redis_conn: "redis://localhost:6379",
update_file: ".update-results",
service_prefix: "service-",
fallback_suffix: "-fallback",
previous_suffix: "-previous",
services_json: "services.json",
index: "index.eex",
headers: [
{"User-Agent", "Mozilla/5.0 (Linux x86_64; rv:94.0) Gecko/20100101 Firefox/94.0"},
{"Accept", "text/html"},
{"Accept-Language", "en-US,en;q=0.5"},
{"Accept-Encoding", "gzip, deflate, br"}
],
queries: [
"weather",
"time"
]
| 24.318182 | 86 | 0.628037 |
1c394d86eacd039111afb8b7c8922160a8684d54 | 1,513 | ex | Elixir | learn-phoenix/hello/lib/hello_web/endpoint.ex | atvaccaro/problems | 666b431b5489a5990a0f29d601c384c88e0e6132 | [
"MIT"
] | null | null | null | learn-phoenix/hello/lib/hello_web/endpoint.ex | atvaccaro/problems | 666b431b5489a5990a0f29d601c384c88e0e6132 | [
"MIT"
] | null | null | null | learn-phoenix/hello/lib/hello_web/endpoint.ex | atvaccaro/problems | 666b431b5489a5990a0f29d601c384c88e0e6132 | [
"MIT"
] | 1 | 2019-11-03T04:05:34.000Z | 2019-11-03T04:05:34.000Z | defmodule HelloWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :hello
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_hello_key",
signing_salt: "p14yT2is"
]
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :hello,
gzip: false,
only: ~w(assets fonts images favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :hello
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug HelloWeb.Router
end
| 29.666667 | 97 | 0.719101 |
1c39570a8497d22260ce6b955f44bb9cb41a630d | 391 | exs | Elixir | dave-course/fibcache_proj/kvcache/test/kvcache_test.exs | jordanhubbard/elixir-projects | dee341d672e83a45a17a4a85abd54a480f95c506 | [
"BSD-2-Clause"
] | null | null | null | dave-course/fibcache_proj/kvcache/test/kvcache_test.exs | jordanhubbard/elixir-projects | dee341d672e83a45a17a4a85abd54a480f95c506 | [
"BSD-2-Clause"
] | 1 | 2021-03-09T16:27:25.000Z | 2021-03-09T16:27:25.000Z | dave-course/fibcache_proj/kvcache/test/kvcache_test.exs | jordanhubbard/elixir-projects | dee341d672e83a45a17a4a85abd54a480f95c506 | [
"BSD-2-Clause"
] | null | null | null | defmodule KVCacheTest do
use ExUnit.Case
doctest KVCache
test "set a value successfully" do
assert KVCache.set(:testKey, "hi there") == "hi there"
end
test "get a value successfully" do
KVCache.set(:testKey, "hi there")
assert KVCache.get(:testKey) == "hi there"
end
test "unknown value returns nil" do
assert KVCache.get(:nonsenseValue) == nil
end
end
| 20.578947 | 58 | 0.680307 |
1c39573606a94dc92bff8cc454df07f4852ce9c9 | 1,879 | ex | Elixir | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_beta1_batch_create_producer_overrides_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_beta1_batch_create_producer_overrides_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_beta1_batch_create_producer_overrides_response.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.ServiceConsumerManagement.V1.Model.V1Beta1BatchCreateProducerOverridesResponse do
@moduledoc """
Response message for BatchCreateProducerOverrides
## Attributes
* `overrides` (*type:* `list(GoogleApi.ServiceConsumerManagement.V1.Model.V1Beta1QuotaOverride.t)`, *default:* `nil`) - The overrides that were created.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:overrides =>
list(GoogleApi.ServiceConsumerManagement.V1.Model.V1Beta1QuotaOverride.t())
}
field(
:overrides,
as: GoogleApi.ServiceConsumerManagement.V1.Model.V1Beta1QuotaOverride,
type: :list
)
end
defimpl Poison.Decoder,
for: GoogleApi.ServiceConsumerManagement.V1.Model.V1Beta1BatchCreateProducerOverridesResponse do
def decode(value, options) do
GoogleApi.ServiceConsumerManagement.V1.Model.V1Beta1BatchCreateProducerOverridesResponse.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.ServiceConsumerManagement.V1.Model.V1Beta1BatchCreateProducerOverridesResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.964912 | 156 | 0.76264 |
1c3960acc93f214572bcf82334787ab9c2c039e4 | 2,512 | ex | Elixir | insights/lib/insights_web/live/topology_live.ex | MillionIntegrals/elixir-mongodb-driver | 96c4cc3f21c4043323b8a9b33ad3a374760864c6 | [
"Apache-2.0"
] | null | null | null | insights/lib/insights_web/live/topology_live.ex | MillionIntegrals/elixir-mongodb-driver | 96c4cc3f21c4043323b8a9b33ad3a374760864c6 | [
"Apache-2.0"
] | null | null | null | insights/lib/insights_web/live/topology_live.ex | MillionIntegrals/elixir-mongodb-driver | 96c4cc3f21c4043323b8a9b33ad3a374760864c6 | [
"Apache-2.0"
] | null | null | null | defmodule InsightsWeb.TopologyLive do
use InsightsWeb, :live_view
alias Mongo.Monitor
alias Mongo.StreamingHelloMonitor
alias Mongo.Topology
require Logger
@impl true
def mount(_params, _session, socket) do
if connected?(socket) do
Phoenix.PubSub.subscribe(Insights.PubSub, "topology")
Phoenix.PubSub.subscribe(Insights.PubSub, "commands")
end
{:ok, reset_defaults(socket)}
end
@impl true
def render(assigns) do
Phoenix.View.render(InsightsWeb.TopologyView, "index.html", assigns)
end
@impl true
def handle_info(%Mongo.Events.ServerDescriptionChangedEvent{} = event, %{assigns: %{events: events}} = socket) do
event = event
|> Map.put(:time_stamp, DateTime.utc_now())
|> Map.put(:id, random_string(10))
events = [event | events] |> Enum.take(10)
socket = socket
|> set_topology(Topology.get_state(:mongo))
|> assign(events: events)
{:noreply, socket}
end
def handle_info(event, %{assigns: %{events: events}} = socket) do
event = event
|> Map.put(:time_stamp, DateTime.utc_now())
|> Map.put(:id, random_string(10))
events = [event | events] |> Enum.take(10)
{:noreply, assign(socket, events: events)}
end
def handle_event("show-events", _params, socket) do
{:noreply, assign(socket, tab: "events")}
end
def handle_event("show-details", _params, socket) do
{:noreply, assign(socket, tab: "details")}
end
def handle_event("select-event", %{"id" => event_id}, %{assigns: %{events: events}} = socket) do
{:noreply, assign(socket, event: Enum.find(events, fn %{id: id} -> event_id == id end))}
end
defp reset_defaults(socket) do
socket
|> set_topology(Topology.get_state(:mongo))
|> assign(events: [])
|> assign(tab: "details")
|> assign(event: nil)
end
def set_topology(socket, %{topology: %{servers: servers} = topology, monitors: monitors}) do
monitors = monitors
|> Enum.map(fn {address, pid} -> {address, Monitor.get_state(pid)} end)
|> Enum.into(%{})
socket
|> assign(topology: topology)
|> assign(servers: Map.values(servers))
|> assign(monitors: monitors)
end
def set_topology(socket, _other) do
socket
|> assign(topology: nil)
|> assign(servers: [])
|> assign(monitors: [])
end
def random_string(length) do
:crypto.strong_rand_bytes(length) |> Base.url_encode64 |> binary_part(0, length)
end
end
| 27.010753 | 115 | 0.639729 |
1c3962998afc4654dd99a82c6ae46a9cd7b4f2e0 | 4,850 | ex | Elixir | lib/bson/encoder.ex | rafamedina/mongodb | 65bd68adbc2753c38d927ad0ba804fe8e66d50d7 | [
"Apache-2.0"
] | 1 | 2019-01-24T09:02:56.000Z | 2019-01-24T09:02:56.000Z | lib/bson/encoder.ex | rafamedina/mongodb | 65bd68adbc2753c38d927ad0ba804fe8e66d50d7 | [
"Apache-2.0"
] | 1 | 2021-09-23T18:21:31.000Z | 2021-09-28T14:39:42.000Z | lib/bson/encoder.ex | rafamedina/mongodb | 65bd68adbc2753c38d927ad0ba804fe8e66d50d7 | [
"Apache-2.0"
] | null | null | null | defmodule BSON.Encoder do
@moduledoc false
use BSON.Utils
def encode(true),
do: 0x01
def encode(false),
do: 0x00
def encode(nil),
do: ""
def encode(:BSON_min),
do: ""
def encode(:BSON_max),
do: ""
def encode(%BSON.Binary{binary: binary, subtype: subtype}) do
subtype = subtype(subtype)
[<<IO.iodata_length(binary)::int32>>, subtype | binary]
end
def encode(%BSON.ObjectId{value: <<_::binary(12)>> = value}),
do: value
def encode(%DateTime{} = datetime) do
unix_ms = DateTime.to_unix(datetime, :milliseconds)
<<unix_ms::int64>>
end
def encode(%BSON.Regex{pattern: pattern, options: options}),
do: [cstring(pattern) | cstring(options)]
def encode(%BSON.JavaScript{code: code, scope: nil}),
do: encode(code)
def encode(%BSON.JavaScript{code: code, scope: scope}) do
iodata = [encode(code), document(scope)]
size = IO.iodata_length(iodata) + 4
[<<size::int32>> | iodata]
end
def encode(%BSON.Timestamp{value: epoch, ordinal: ordinal}),
do: <<ordinal::int32, epoch::int32>>
def encode([]) do
document([])
end
def encode([{_, _} | _] = value) do
document(value)
end
def encode(value) when is_list(value) do
array(value, 0)
|> document
end
def encode(value) when is_map(value),
do: document(value)
def encode(:inf),
do: <<0, 0, 0, 0, 0, 0, 240::little-integer-size(8), 127::little-integer-size(8)>>
def encode(:"-inf"),
do: <<0, 0, 0, 0, 0, 0, 240::little-integer-size(8), 255::little-integer-size(8)>>
def encode(:NaN),
do: <<0, 0, 0, 0, 0, 0, 248::little-integer-size(8), 127::little-integer-size(8)>>
def encode(value) when is_atom(value),
do: encode(Atom.to_string(value))
def encode(value) when is_binary(value),
do: [<<byte_size(value)+1::int32>>, value, 0x00]
def encode(value) when is_float(value),
do: <<value::little-float64>>
def encode(value) when is_int32(value),
do: <<value::int32>>
def encode(value) when is_int64(value),
do: <<value::int64>>
def document(doc) do
{_, iodata} =
Enum.reduce(doc, {:unknown, ""}, fn
{:__struct__, _value}, {:binary, _acc} ->
invalid_doc(doc)
{:__struct__, _value}, {_, acc} ->
{:atom, acc}
{key, _value}, {:binary, _acc} when is_atom(key) ->
invalid_doc(doc)
{key, _value}, {:atom, _acc} when is_binary(key) ->
invalid_doc(doc)
{key, value}, {_, acc} ->
{key_type, key} = key(key)
type = type(value)
value = encode(value)
{key_type, [acc, type, key, value]}
end)
[<<IO.iodata_length(iodata)+5::int32>>, iodata, 0x00]
end
defp cstring(string), do: [string, 0x00]
defp key(value) when is_atom(value),
do: {:atom, cstring(Atom.to_string(value))}
defp key(value) when is_binary(value),
do: {:binary, cstring(value)}
defp array([], _ix),
do: []
defp array([hd|tl], ix) when not is_tuple(hd),
do: [{Integer.to_string(ix), hd} | array(tl, ix+1)]
defp invalid_doc(doc) do
message = "invalid document containing atom and string keys: #{inspect doc}"
raise ArgumentError, message
end
defp type(%BSON.Binary{}), do: @type_binary
defp type(%BSON.ObjectId{}), do: @type_objectid
defp type(%DateTime{}), do: @type_datetime
defp type(%BSON.Regex{}), do: @type_regex
defp type(%BSON.JavaScript{scope: nil}), do: @type_js
defp type(%BSON.JavaScript{}), do: @type_js_scope
defp type(%BSON.Timestamp{}), do: @type_timestamp
defp type(nil), do: @type_null
defp type(:BSON_min), do: @type_min
defp type(:BSON_max), do: @type_max
defp type(:inf), do: @type_float
defp type(:"-inf"), do: @type_float
defp type(:NaN), do: @type_float
defp type(value) when is_boolean(value), do: @type_bool
defp type(value) when is_float(value), do: @type_float
defp type(value) when is_atom(value), do: @type_string
defp type(value) when is_binary(value), do: @type_string
defp type(value) when is_map(value), do: @type_document
defp type([{_,_}|_]), do: @type_document
defp type(value) when is_list(value), do: @type_array
defp type(value) when is_int32(value), do: @type_int32
defp type(value) when is_int64(value), do: @type_int64
defp subtype(:generic), do: 0x00
defp subtype(:function), do: 0x01
defp subtype(:binary_old), do: 0x02
defp subtype(:uuid_old), do: 0x03
defp subtype(:uuid), do: 0x04
defp subtype(:md5), do: 0x05
defp subtype(int) when is_integer(int) and int in 0x80..0xFF, do: 0x80
end
| 30.124224 | 86 | 0.595464 |
1c39be448836c3e66279dff7c956bac7455c2eaa | 3,189 | ex | Elixir | clients/games/lib/google_api/games/v1/model/network_diagnostics.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/network_diagnostics.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/network_diagnostics.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Games.V1.Model.NetworkDiagnostics do
@moduledoc """
This is a JSON template for network diagnostics reported for a client.
## Attributes
- androidNetworkSubtype (integer()): The Android network subtype. Defaults to: `null`.
- androidNetworkType (integer()): The Android network type. Defaults to: `null`.
- iosNetworkType (integer()): iOS network type as defined in Reachability.h. Defaults to: `null`.
- kind (String.t): Uniquely identifies the type of this resource. Value is always the fixed string games#networkDiagnostics. Defaults to: `null`.
- networkOperatorCode (String.t): The MCC+MNC code for the client's network connection. On Android: http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperator() On iOS, see: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html Defaults to: `null`.
- networkOperatorName (String.t): The name of the carrier of the client's network connection. On Android: http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName() On iOS: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName Defaults to: `null`.
- registrationLatencyMillis (integer()): The amount of time in milliseconds it took for the client to establish a connection with the XMPP server. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:androidNetworkSubtype => any(),
:androidNetworkType => any(),
:iosNetworkType => any(),
:kind => any(),
:networkOperatorCode => any(),
:networkOperatorName => any(),
:registrationLatencyMillis => any()
}
field(:androidNetworkSubtype)
field(:androidNetworkType)
field(:iosNetworkType)
field(:kind)
field(:networkOperatorCode)
field(:networkOperatorName)
field(:registrationLatencyMillis)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.NetworkDiagnostics do
def decode(value, options) do
GoogleApi.Games.V1.Model.NetworkDiagnostics.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.NetworkDiagnostics do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 48.318182 | 406 | 0.751646 |
1c39bf716550b64465240b1a3126e2b2604bfea2 | 251 | exs | Elixir | kousa/priv/repo/migrations/20210321141614_discord_login.exs | LeonardSSH/dogehouse | 584055ad407bc37fa35cdf36ebb271622e29d436 | [
"MIT"
] | 9 | 2021-03-17T03:56:18.000Z | 2021-09-24T22:45:14.000Z | kousa/priv/repo/migrations/20210321141614_discord_login.exs | ActuallyTomas/dogehouse | 8c3d2cd1d7e99e173f0658759467a391c4a90c4e | [
"MIT"
] | 12 | 2021-07-06T12:51:13.000Z | 2022-03-16T12:38:18.000Z | kousa/priv/repo/migrations/20210321141614_discord_login.exs | ActuallyTomas/dogehouse | 8c3d2cd1d7e99e173f0658759467a391c4a90c4e | [
"MIT"
] | 4 | 2021-07-15T20:33:50.000Z | 2022-03-27T12:46:47.000Z | defmodule Beef.Repo.Migrations.DiscordLogin do
use Ecto.Migration
def change do
alter table(:users) do
add :discordId, :string, null: true, default: nil
add :discordAccessToken, :string, null: true, default: nil
end
end
end
| 22.818182 | 64 | 0.697211 |
1c39c86e01f1e2be2b83559a47bc9a58e5d3e3c7 | 3,053 | ex | Elixir | elixir/lib/homework/merchants.ex | n7down/web-homework | 53a65cbd852fe0abd542ff1bd29ebbf450e87d5f | [
"MIT"
] | null | null | null | elixir/lib/homework/merchants.ex | n7down/web-homework | 53a65cbd852fe0abd542ff1bd29ebbf450e87d5f | [
"MIT"
] | null | null | null | elixir/lib/homework/merchants.ex | n7down/web-homework | 53a65cbd852fe0abd542ff1bd29ebbf450e87d5f | [
"MIT"
] | null | null | null | defmodule Homework.Merchants do
@moduledoc """
The Merchants context.
"""
import Ecto.Query, warn: false
alias Homework.Repo
alias Homework.Merchants.Merchant
@doc """
Returns the list of merchants.
## Examples
iex> list_merchants([])
[%Merchant{}, ...]
"""
def list_merchants(_args) do
Repo.all(Merchant)
end
@doc """
Gets a single merchant.
Raises `Ecto.NoResultsError` if the Merchant does not exist.
## Examples
iex> get_merchant!(123)
%Merchant{}
iex> get_merchant!(456)
** (Ecto.NoResultsError)
"""
def get_merchant!(id), do: Repo.get!(Merchant, id)
@doc """
Gets a single merchant by name.
Raises `Ecto.NoResultsError` if the Merchant does not exist.
## Examples
iex> get_merchant_by_last_name!(123)
%Merchant{}
iex> get_merchant_by_last_name!(456)
** (Ecto.NoResultsError)
"""
def get_merchant_by_name!(name) do
query = from(
m in Merchant,
where: m.name == ^name
)
Repo.one(query)
end
@doc """
Creates a merchant.
## Examples
iex> create_merchant(%{field: value})
{:ok, %Merchant{}}
iex> create_merchant(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_merchant(attrs \\ %{}) do
%Merchant{}
|> Merchant.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a merchant.
## Examples
iex> update_merchant(merchant, %{field: new_value})
{:ok, %Merchant{}}
iex> update_merchant(merchant, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_merchant(%Merchant{} = merchant, attrs) do
merchant
|> Merchant.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a merchant.
## Examples
iex> delete_merchant(merchant)
{:ok, %Merchant{}}
iex> delete_merchant(merchant)
{:error, %Ecto.Changeset{}}
"""
def delete_merchant(%Merchant{} = merchant) do
Repo.delete(merchant)
end
@doc """
Fuzzy search a merchant by name.
## Examples
iex> search_merchant(merchant_name)
{:ok, %Merchant{}}
iex> search_merchant(merchant)
{:error, %Ecto.Changeset{}}
"""
def search_merchant(name) do
query = from m in Merchant,
where: ilike(m.name, ^"%#{name}%")
Repo.all(query)
end
@doc """
Pageinate through all users ordered by the merchant name asc given the limit and skip values.
Returns the results and the total number of results.
"""
def pageinate(limit, skip) do
query = from m in Merchant,
select: m,
order_by: [asc: m.name],
limit: ^limit,
offset: ^skip
results = Repo.all(query)
%{results: results, total_rows: length(results)}
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking merchant changes.
## Examples
iex> change_merchant(merchant)
%Ecto.Changeset{data: %Merchant{}}
"""
def change_merchant(%Merchant{} = merchant, attrs \\ %{}) do
Merchant.changeset(merchant, attrs)
end
end
| 19.201258 | 95 | 0.61546 |
1c39d37e033290538130b62ce9d6d5ec0b8faf35 | 1,895 | ex | Elixir | elixir/otp_todo_app/lib/todo/cache.ex | raventid/coursera_learning | 115a03f08d30d8ba49f02c9692c289cbfb242358 | [
"MIT"
] | 1 | 2019-11-28T09:26:00.000Z | 2019-11-28T09:26:00.000Z | elixir/todo_app_with_metrics/lib/todo/cache.ex | raventid/coursera_learning | 115a03f08d30d8ba49f02c9692c289cbfb242358 | [
"MIT"
] | null | null | null | elixir/todo_app_with_metrics/lib/todo/cache.ex | raventid/coursera_learning | 115a03f08d30d8ba49f02c9692c289cbfb242358 | [
"MIT"
] | null | null | null | defmodule Todo.Cache do
use GenServer
# Rename this to start_link, so everyone
# understand that we are running with
# supervisor.
def start_link do
IO.puts("Starting supervised cache.")
DynamicSupervisor.start_link(
name: __MODULE__,
strategy: :one_for_one
)
end
def child_spec(_arg) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, []},
type: :supervisor
}
end
# FIXME: This is our bottleneck now.
# We always ask supervisor to start
# child. And it will always do this
# one by one.
# Let's change a bit the overall design
# will ask dynamic supervisor to start
# child and if will tell us is this child
# already exists or not and will give us
# PID of child.
def server_process(todo_list_name) do
case start_child(todo_list_name) do
{:ok, pid} -> pid
{:error, {:already_started, pid}} -> pid
end
end
# Helper for previous function.
defp start_child(todo_list_name) do
DynamicSupervisor.start_child(
__MODULE__,
{Todo.Server, todo_list_name}
)
end
# GenServer callbacks.
@impl GenServer
def init(_) do
{:ok, %{}}
end
@impl GenServer
def handle_call({:server_process, todo_list_name}, _, todo_servers) do
case Map.fetch(todo_servers, todo_list_name) do
{:ok, todo_server} ->
{:reply, todo_server, todo_servers}
:error ->
{:ok, new_server} = Todo.Server.start_link(todo_list_name)
{
:reply,
new_server,
Map.put(todo_servers, todo_list_name, new_server)
}
end
end
end
# FOR REPL:
# {:ok, cache_pid} = Todo.Cache.start
# Todo.Cache.server_process(cache_pid, "My list")
# Todo.Cache.server_process(cache_pid, "Another guy list")
# Supervisor.start_link([Todo.Cache], strategy: :one_for_one)
# bobs_list = Todo.Cache.server_process("Bob's list")
| 23.987342 | 72 | 0.659103 |
1c39f617b9197847f4d2c08ad79042dcc6e14c88 | 936 | ex | Elixir | apps/fz_http/lib/fz_http/oidc.ex | bhardwajRahul/firezone | 836bfda9e28350443f2093f810872f2bee7c6cdc | [
"Apache-2.0"
] | null | null | null | apps/fz_http/lib/fz_http/oidc.ex | bhardwajRahul/firezone | 836bfda9e28350443f2093f810872f2bee7c6cdc | [
"Apache-2.0"
] | null | null | null | apps/fz_http/lib/fz_http/oidc.ex | bhardwajRahul/firezone | 836bfda9e28350443f2093f810872f2bee7c6cdc | [
"Apache-2.0"
] | null | null | null | defmodule FzHttp.OIDC do
@moduledoc """
The OIDC context.
"""
import Ecto.Query, warn: false
alias FzHttp.{OIDC.Connection, Repo, Users.User}
def list_connections(%User{id: id}) do
Repo.all(from Connection, where: [user_id: ^id])
end
def get_connection!(user_id, provider) do
Repo.get_by!(Connection, user_id: user_id, provider: provider)
end
def get_connection(user_id, provider) do
Repo.get_by(Connection, user_id: user_id, provider: provider)
end
def create_connection(user_id, provider, refresh_token) do
%Connection{user_id: user_id}
|> Connection.changeset(%{provider: provider, refresh_token: refresh_token})
|> Repo.insert(
conflict_target: [:user_id, :provider],
on_conflict: {:replace, [:refresh_token]}
)
end
def update_connection(%Connection{} = connection, attrs) do
connection
|> Connection.changeset(attrs)
|> Repo.update()
end
end
| 25.297297 | 80 | 0.69765 |
1c3a08287dddf0040588cdf02c3b6100bc2e13b5 | 4,285 | ex | Elixir | lib/oli_web/views/delivery_view.ex | AnkitKadamATS/oli-torus | 3f9d5e8d568684b28d2ed65e17f796ae4c27c072 | [
"MIT"
] | null | null | null | lib/oli_web/views/delivery_view.ex | AnkitKadamATS/oli-torus | 3f9d5e8d568684b28d2ed65e17f796ae4c27c072 | [
"MIT"
] | null | null | null | lib/oli_web/views/delivery_view.ex | AnkitKadamATS/oli-torus | 3f9d5e8d568684b28d2ed65e17f796ae4c27c072 | [
"MIT"
] | 1 | 2021-10-30T05:58:19.000Z | 2021-10-30T05:58:19.000Z | defmodule OliWeb.DeliveryView do
use OliWeb, :view
alias Oli.Delivery.Sections.Section
alias Oli.Accounts.User
alias Lti_1p3.Tool.ContextRoles
alias Lti_1p3.Tool.PlatformRoles
def source_id(source) do
case Map.get(source, :type, nil) do
nil -> "publication:#{source.id}"
_ -> "product:#{source.id}"
end
end
defp is_preview_mode?(conn) do
conn.assigns[:preview_mode] == true
end
defp is_open_and_free_section?(conn) do
case conn.assigns[:section] do
%Section{open_and_free: open_and_free} ->
open_and_free
_ ->
false
end
end
defp is_independent_learner?(conn) do
case conn.assigns[:current_user] do
%User{independent_learner: independent_learner} ->
independent_learner
_ ->
false
end
end
def logo_link_path(conn) do
cond do
is_preview_mode?(conn) ->
"#"
is_open_and_free_section?(conn) or is_independent_learner?(conn) ->
Routes.delivery_path(conn, :open_and_free_index)
true ->
Routes.delivery_path(conn, :index)
end
end
def user_role_is_student(conn, user) do
case user_role(conn.assigns[:section], user) do
:open_and_free ->
true
:student ->
true
:other ->
true
_ ->
false
end
end
def user_role_text(conn, user) do
case user_role(conn.assigns[:section], user) do
:open_and_free ->
"Open and Free"
:administrator ->
"Administrator"
:instructor ->
"Instructor"
:student ->
"Student"
_ ->
""
end
end
def user_name(user) do
case user do
%{guest: true} ->
"Guest"
%{name: name} ->
name
_ ->
""
end
end
def user_role_color(conn, user) do
case user_role(conn.assigns[:section], user) do
:open_and_free ->
"#2C67C4"
:administrator ->
"#f39c12"
:instructor ->
"#2ecc71"
:student ->
"#3498db"
_ ->
""
end
end
@admin_roles [
PlatformRoles.get_role(:system_administrator),
PlatformRoles.get_role(:institution_administrator),
ContextRoles.get_role(:context_administrator)
]
@instructor_roles [
PlatformRoles.get_role(:institution_instructor),
ContextRoles.get_role(:context_instructor)
]
@student_roles [
PlatformRoles.get_role(:institution_student),
PlatformRoles.get_role(:institution_learner),
ContextRoles.get_role(:context_learner)
]
defp user_role(section, user) do
case section do
%Section{open_and_free: open_and_free, slug: section_slug} ->
cond do
open_and_free ->
:open_and_free
PlatformRoles.has_roles?(user, @admin_roles, :any) ||
ContextRoles.has_roles?(user, section_slug, @admin_roles, :any) ->
:administrator
PlatformRoles.has_roles?(user, @instructor_roles, :any) ||
ContextRoles.has_roles?(user, section_slug, @instructor_roles, :any) ->
:instructor
PlatformRoles.has_roles?(user, @student_roles, :any) ||
ContextRoles.has_roles?(user, section_slug, @student_roles, :any) ->
:student
true ->
:other
end
_ ->
cond do
user.guest ->
:open_and_free
PlatformRoles.has_roles?(user, @admin_roles, :any) ->
:administrator
PlatformRoles.has_roles?(user, @instructor_roles, :any) ->
:instructor
PlatformRoles.has_roles?(user, @student_roles, :any) ->
:student
true ->
:other
end
end
end
def account_linked?(user) do
user.author_id != nil
end
def user_icon(user) do
case user.picture do
nil ->
user_icon()
picture ->
~E"""
<div class="user-icon">
<img src="<%= picture %>" class="rounded-circle" />
</div>
"""
end
end
def user_icon() do
~E"""
<div class="user-icon">
<div class="user-img rounded-circle">
<span class="material-icons text-secondary">account_circle</span>
</div>
</div>
"""
end
end
| 20.600962 | 85 | 0.582497 |
1c3a1b94152c5260750f9b1d75edd240d786992a | 1,686 | ex | Elixir | ex_graphs_book/apps/native_graph/lib/native_graph/serializer.ex | NickMcG/ExGraphsBook | 89276d374dd21cc4605a4b1b5a05b177723680c2 | [
"Apache-2.0"
] | null | null | null | ex_graphs_book/apps/native_graph/lib/native_graph/serializer.ex | NickMcG/ExGraphsBook | 89276d374dd21cc4605a4b1b5a05b177723680c2 | [
"Apache-2.0"
] | null | null | null | ex_graphs_book/apps/native_graph/lib/native_graph/serializer.ex | NickMcG/ExGraphsBook | 89276d374dd21cc4605a4b1b5a05b177723680c2 | [
"Apache-2.0"
] | null | null | null | defmodule NativeGraph.Serializer do
@callback serialize(Graph.t()) :: {:ok, binary} | {:error, term}
defmacro __using__(_) do
quote do
@behaviour NativeGraph.Serializer
end
end
def get_vertex_label(%Graph{vertex_labels: vl}, id, v) do
case Map.get(vl, id) do
[] -> nil
label -> encode_label(label)
end
end
def get_vertex_string(%Graph{vertex_labels: vl}, id, v) do
encode_label(v)
end
def get_my_vertex_label(%Graph{vertex_labels: vl}, id, v) do
case Map.get(vl, id) do
[] -> [ encode_label(v), encode_label(v) ]
label -> [ encode_label(v), encode_label(label) ]
end
end
def encode_label([h | _] = label) when length(label) == 1, do: encode_label(h)
def encode_label(label) when is_binary(label), do: quoted(label)
def encode_label(label) when is_integer(label), do: Integer.to_string(label)
def encode_label(label) when is_float(label), do: Float.to_string(label)
def encode_label(label) when is_atom(label), do: quoted(Atom.to_string(label))
def encode_label(label), do: quoted("#{inspect(label)}")
def quoted(str) do
<<?", escape_quotes(str)::binary, ?">>
end
def escape_quotes(str) do
escape_quotes(str, "")
end
def escape_quotes(<<>>, acc), do: acc
def escape_quotes(<<?\\, ?\", rest::binary>>, acc) do
escape_quotes(rest, <<acc::binary, ?\\, ?\">>)
end
def escape_quotes(<<?\", rest::binary>>, acc) do
escape_quotes(rest, <<acc::binary, ?\\, ?\">>)
end
def escape_quotes(<<c::utf8, rest::binary>>, acc) do
escape_quotes(rest, <<acc::binary, c::utf8>>)
end
def indent(tabs), do: String.duplicate(" ", tabs * 4)
end
| 28.1 | 80 | 0.637011 |
1c3a24fd5fc4129a09eb0a0dde5b14a14e056271 | 288 | ex | Elixir | lib/csp_report_collector/repo.ex | eoinkelly/csp_report_collector | 12e965cb5c23add1f2dbe6745c605a9cf0b42d75 | [
"Apache-2.0"
] | 2 | 2018-12-03T17:17:52.000Z | 2022-02-01T13:26:20.000Z | lib/csp_report_collector/repo.ex | eoinkelly/csp_report_collector | 12e965cb5c23add1f2dbe6745c605a9cf0b42d75 | [
"Apache-2.0"
] | null | null | null | lib/csp_report_collector/repo.ex | eoinkelly/csp_report_collector | 12e965cb5c23add1f2dbe6745c605a9cf0b42d75 | [
"Apache-2.0"
] | null | null | null | defmodule CspReportCollector.Repo do
use Ecto.Repo, otp_app: :csp_report_collector
@doc """
Dynamically loads the repository url from the
DATABASE_URL environment variable.
"""
def init(_, opts) do
{:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
end
end
| 24 | 66 | 0.722222 |
1c3a3199d64e86cee417dd16b6cea636d30c7ce8 | 1,028 | ex | Elixir | lib/elixero/core_api/tax_rates.ex | philals/elixero | fd75fe4a6f0a93b1d2ff94adbb307d20f014d458 | [
"MIT"
] | 84 | 2016-11-09T01:15:17.000Z | 2022-01-06T02:55:35.000Z | lib/elixero/core_api/tax_rates.ex | philals/elixero | fd75fe4a6f0a93b1d2ff94adbb307d20f014d458 | [
"MIT"
] | 14 | 2017-03-10T04:16:07.000Z | 2021-11-10T16:39:19.000Z | lib/elixero/core_api/tax_rates.ex | philals/elixero | fd75fe4a6f0a93b1d2ff94adbb307d20f014d458 | [
"MIT"
] | 18 | 2017-03-11T21:12:15.000Z | 2022-02-22T20:07:10.000Z | defmodule EliXero.CoreApi.TaxRates do
@resource "taxrates"
@model_module EliXero.CoreApi.Models.TaxRates
def find(client) do
EliXero.CoreApi.Common.find(client, @resource)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
def find(client, identifier) do
EliXero.CoreApi.Common.find(client, @resource, identifier)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
def filter(client, filter) do
EliXero.CoreApi.Common.filter(client, @resource, filter)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
def create(client, tax_rates_map) do
EliXero.CoreApi.Common.create(client, @resource, tax_rates_map)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
def update(client, identifier, tax_rates_map) do
EliXero.CoreApi.Common.update(client, @resource, identifier, tax_rates_map)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
end | 35.448276 | 79 | 0.771401 |
1c3a4c5901e440f95a99aed633b10484749af6e9 | 1,908 | ex | Elixir | elixir/lib/homework_web/schemas/transactions_schema.ex | MitchellJeppson/DivvyPayHQ-web-homework | 01dc6a7ee0173c92633d93f7ba7e9162b1189985 | [
"MIT"
] | null | null | null | elixir/lib/homework_web/schemas/transactions_schema.ex | MitchellJeppson/DivvyPayHQ-web-homework | 01dc6a7ee0173c92633d93f7ba7e9162b1189985 | [
"MIT"
] | null | null | null | elixir/lib/homework_web/schemas/transactions_schema.ex | MitchellJeppson/DivvyPayHQ-web-homework | 01dc6a7ee0173c92633d93f7ba7e9162b1189985 | [
"MIT"
] | 1 | 2021-03-30T07:41:56.000Z | 2021-03-30T07:41:56.000Z | defmodule HomeworkWeb.Schemas.TransactionsSchema do
@moduledoc """
Defines the graphql schema for transactions.
"""
use Absinthe.Schema.Notation
alias HomeworkWeb.Resolvers.TransactionsResolver
object :transaction do
field(:id, non_null(:id))
field(:user_id, :id)
field(:amount, :integer)
field(:credit, :boolean)
field(:debit, :boolean)
field(:description, :string)
field(:merchant_id, :id)
field(:inserted_at, :naive_datetime)
field(:updated_at, :naive_datetime)
field(:company_id, :string)
field(:user, :user) do
resolve(&TransactionsResolver.user/3)
end
field(:merchant, :merchant) do
resolve(&TransactionsResolver.merchant/3)
end
end
object :transaction_mutations do
@desc "Create a new transaction"
field :create_transaction, :transaction do
arg(:user_id, non_null(:id))
arg(:merchant_id, non_null(:id))
@desc "amount is in cents"
arg(:amount, non_null(:integer))
arg(:credit, non_null(:boolean))
arg(:debit, non_null(:boolean))
arg(:description, non_null(:string))
arg(:company_id, non_null(:string))
resolve(&TransactionsResolver.create_transaction/3)
end
@desc "Update a new transaction"
field :update_transaction, :transaction do
arg(:id, non_null(:id))
arg(:user_id, non_null(:id))
arg(:merchant_id, non_null(:id))
@desc "amount is in cents"
arg(:amount, non_null(:integer))
arg(:credit, non_null(:boolean))
arg(:debit, non_null(:boolean))
arg(:description, non_null(:string))
arg(:company_id, non_null(:string))
resolve(&TransactionsResolver.update_transaction/3)
end
@desc "delete an existing transaction"
field :delete_transaction, :transaction do
arg(:id, non_null(:id))
resolve(&TransactionsResolver.delete_transaction/3)
end
end
end
| 28.058824 | 57 | 0.671384 |
1c3aa3be67002687f62f8da425098b8320ec45c2 | 7,676 | ex | Elixir | lib/groupher_server/delivery/delegates/notification.ex | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 240 | 2018-11-06T09:36:54.000Z | 2022-02-20T07:12:36.000Z | lib/groupher_server/delivery/delegates/notification.ex | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 363 | 2018-07-11T03:38:14.000Z | 2021-12-14T01:42:40.000Z | lib/groupher_server/delivery/delegates/notification.ex | mydearxym/mastani_server | f24034a4a5449200165cf4a547964a0961793eab | [
"Apache-2.0"
] | 22 | 2019-01-27T11:47:56.000Z | 2021-02-28T13:17:52.000Z | defmodule GroupherServer.Delivery.Delegate.Notification do
@moduledoc """
notification for upvote, comment, publish, collect, watch, follow an article or user
"""
import Ecto.Query, warn: false
import Helper.Utils,
only: [get_config: 2, done: 1, strip_struct: 1, atom_values_to_upcase: 1]
import ShortMaps
alias GroupherServer.{Accounts, Delivery, Repo}
alias Delivery.Model.Notification
alias Accounts.Model.User
alias Helper.ORM
alias Ecto.Multi
@notify_actions get_config(:general, :nofity_actions)
@notify_group_interval_hour get_config(:general, :notify_group_interval_hour)
@cut_from_users_count 3
def handle(%{action: action, user_id: user_id} = attrs, %User{} = from_user) do
with true <- action in @notify_actions,
true <- is_valid?(attrs),
true <- user_id !== from_user.id do
Multi.new()
|> Multi.run(:upsert_notifications, fn _, _ ->
from_user =
from_user
|> Map.take([:login, :nickname])
|> Map.put(:user_id, from_user.id)
case find_exist_notify(attrs, :latest_peroid) do
{:ok, notify} -> merge_notification(notify, from_user)
{:error, _} -> create_notification(attrs, from_user)
end
end)
|> Multi.run(:update_user_mailbox_status, fn _, %{upsert_notifications: nofity} ->
Accounts.update_mailbox_status(nofity.user_id)
end)
|> Repo.transaction()
|> result()
else
false -> {:error, "invalid args for notification"}
error -> error
end
end
@doc "revoke action in notification in all history"
def revoke(attrs, %User{} = from_user) do
attrs = attrs |> Map.put(:from_user, from_user)
with {:ok, notifications} <- find_exist_notify(attrs, :all) do
Multi.new()
|> Multi.run(:revoke_notifications, fn _, _ ->
Enum.each(notifications, fn notify ->
case length(notify.from_users) == 1 do
# 只有一就删除记录
true ->
ORM.delete(notify)
# 如果是多人集合就在 from_users 中删除该用户
false ->
from_users = Enum.reject(notify.from_users, &(&1.login == from_user.login))
notify |> ORM.update_embed(:from_users, from_users)
end
end)
|> done
end)
|> Multi.run(:update_user_mailbox_status, fn _, _ ->
Enum.each(notifications, &Accounts.update_mailbox_status(&1.user_id)) |> done
end)
|> Repo.transaction()
|> result()
else
false -> {:ok, :pass}
{:error, _} -> {:ok, :pass}
end
end
def paged_notifications(%User{} = user, %{page: page, size: size} = filter) do
read = Map.get(filter, :read, false)
Notification
|> where([n], n.user_id == ^user.id and n.read == ^read)
|> ORM.paginator(~m(page size)a)
|> cut_from_users_ifneed
|> done
end
# @cut_from_users_count
defp cut_from_users_ifneed(%{entries: entries} = paged_contents) do
entries =
Enum.map(entries, fn notify ->
from_users = Enum.slice(notify.from_users, 0, @cut_from_users_count)
notify |> Map.put(:from_users, from_users)
end)
paged_contents |> Map.put(:entries, entries)
end
# 注意这里并不是准确的 count, 因为可能有短时间内 merge 到一起的通知
def unread_count(user_id) do
Notification
|> where([n], n.user_id == ^user_id and n.read == false)
|> ORM.count()
end
@doc "mark notification in ids as readed"
def mark_read(ids, %User{} = user) when is_list(ids) do
Notification
|> where([m], m.id in ^ids and m.user_id == ^user.id and m.read == false)
|> ORM.mark_read_all()
end
@doc "mark all related notifications as readed"
def mark_read_all(%User{} = user) do
Notification
|> where([m], m.user_id == ^user.id and m.read == false)
|> ORM.mark_read_all()
end
# 如果在临近时间段内有类似操作,直接将这次的操作人添加到 from_users 中即可
# 避免对统一操作的大量重复消息提醒,体验不好
defp merge_notification(notify, from_user) do
cur_from_users = notify.from_users |> Enum.map(&strip_struct(&1))
from_users = ([from_user] ++ cur_from_users) |> Enum.uniq()
notify
|> ORM.update_embed(:from_users, from_users, %{from_users_count: length(from_users)})
end
# 创建通知
defp create_notification(attrs, from_user) do
attrs = attrs |> Map.merge(%{from_users_count: 1}) |> atom_values_to_upcase
%Notification{}
|> Ecto.Changeset.change(attrs)
|> Ecto.Changeset.put_embed(:from_users, [from_user])
|> Repo.insert()
end
defp find_exist_notify(%{action: :follow} = attrs, opt) do
do_find_exist_notify(Notification, attrs, opt)
end
defp find_exist_notify(%{comment_id: comment_id} = attrs, opt)
when not is_nil(comment_id) do
~m(thread article_id comment_id)a = atom_values_to_upcase(attrs)
Notification
|> where(
[n],
n.thread == ^thread and n.article_id == ^article_id and n.comment_id == ^comment_id
)
|> do_find_exist_notify(attrs, opt)
end
defp find_exist_notify(attrs, opt) do
~m(thread article_id)a = atom_values_to_upcase(attrs)
Notification
|> where([n], n.thread == ^thread and n.article_id == ^article_id)
|> do_find_exist_notify(attrs, opt)
end
# find exist notification, in latest peroid
# 在最近的时期内,找到一个存在的通知
@spec do_find_exist_notify(Ecto.Queryable.t(), Map.t(), Atom.t()) ::
{Atom.t(), Notification.t()}
defp do_find_exist_notify(queryable, attrs, :latest_peroid) do
~m(user_id action)a = atom_values_to_upcase(attrs)
queryable
|> where([n], n.inserted_at >= ^interval_threshold_time() and n.user_id == ^user_id)
|> where([n], n.action == ^action and n.read == false)
|> Repo.one()
|> done
end
# find exist notifications, in all history
# 在所有通知中,找到多个存在的通知
@spec do_find_exist_notify(Ecto.Queryable.t(), Map.t(), Atom.t()) ::
{Atom.t(), [Notification.t()]}
defp do_find_exist_notify(queryable, attrs, _opt) do
~m(user_id action from_user)a = atom_values_to_upcase(attrs)
queryable = queryable |> where([n], n.user_id == ^user_id and n.action == ^action)
# select login in from_users
# see https://stackoverflow.com/questions/51267155/in-postgresql-how-can-i-select-rows-where-a-jsonb-array-contains-objects
# see https://elixirforum.com/t/writing-queries-with-multiple-from-clauses/28646/2?u=mydearxym
from(n in queryable,
cross_join: fu in fragment("jsonb_array_elements(?)", n.from_users),
where: fragment("?->>'login' = ?", fu, ^from_user.login)
)
|> Repo.all()
|> done
end
defp is_valid?(%{action: :follow} = attrs), do: attrs |> all_exist?([:user_id])
defp is_valid?(%{action: :upvote} = attrs) do
attrs |> all_exist?([:article_id, :thread, :title, :user_id])
end
defp is_valid?(%{action: :collect} = attrs) do
attrs |> all_exist?([:article_id, :thread, :title, :user_id])
end
defp is_valid?(%{action: :comment} = attrs) do
attrs |> all_exist?([:article_id, :thread, :title, :comment_id, :user_id])
end
defp is_valid?(%{action: :reply} = attrs) do
attrs |> all_exist?([:article_id, :thread, :title, :comment_id, :user_id])
end
defp is_valid?(_), do: false
# 确保 key 存在,并且不为 nil
defp all_exist?(attrs, keys) when is_map(attrs) and is_list(keys) do
Enum.all?(keys, &(Map.has_key?(attrs, &1) and not is_nil(attrs[&1])))
end
# 此时间段内的相似通知会被 merge
defp interval_threshold_time() do
Timex.shift(Timex.now(), hours: -@notify_group_interval_hour)
end
defp result({:ok, %{upsert_notifications: result}}), do: {:ok, result}
defp result({:ok, %{revoke_notifications: result}}), do: {:ok, result}
defp result({:error, _, result, _steps}), do: {:error, result}
end
| 32.525424 | 127 | 0.65073 |
1c3aad6b48440e1472ab77ba74e3b976dd43bd1c | 74 | exs | Elixir | test/sibt_web/views/page_view_test.exs | amacgregor/sibt | 9819a9de4735612ee59de00f71ca1a6dfa275860 | [
"MIT"
] | null | null | null | test/sibt_web/views/page_view_test.exs | amacgregor/sibt | 9819a9de4735612ee59de00f71ca1a6dfa275860 | [
"MIT"
] | 2 | 2020-07-18T02:22:22.000Z | 2021-03-09T15:46:44.000Z | test/sibt_web/views/page_view_test.exs | amacgregor/shouldibuildthat | 572b0ba95f93f6ea0dc7b250baaa1bc90efd521b | [
"MIT"
] | null | null | null | defmodule SibtWeb.PageViewTest do
use SibtWeb.ConnCase, async: true
end
| 18.5 | 35 | 0.810811 |
1c3ae1535a295be038cd7a3fe98f11854646ce82 | 84 | exs | Elixir | test/views/page_view_test.exs | davidgrupp/Bucket-Island | 674bf0f8029a22b56fc245d8927561dca2d3cd0a | [
"Apache-2.0"
] | 1 | 2017-09-03T17:41:28.000Z | 2017-09-03T17:41:28.000Z | test/views/page_view_test.exs | davidgrupp/Bucket-Island | 674bf0f8029a22b56fc245d8927561dca2d3cd0a | [
"Apache-2.0"
] | null | null | null | test/views/page_view_test.exs | davidgrupp/Bucket-Island | 674bf0f8029a22b56fc245d8927561dca2d3cd0a | [
"Apache-2.0"
] | null | null | null | defmodule BucketIsland.PageViewTest do
use BucketIsland.ConnCase, async: true
end
| 21 | 40 | 0.833333 |
1c3b14e3d44f6ce95ce1739c49c7c70e8441c477 | 394 | exs | Elixir | mix.exs | ayonix/zxcvbn-ex | ce5f1a9f5ca3b7b17c895fc237e12cdede85da38 | [
"MIT"
] | 2 | 2018-10-09T20:17:08.000Z | 2018-10-18T23:30:49.000Z | mix.exs | ayonix/zxcvbn-ex | ce5f1a9f5ca3b7b17c895fc237e12cdede85da38 | [
"MIT"
] | 13 | 2018-10-06T08:03:23.000Z | 2019-10-02T18:50:43.000Z | mix.exs | ayonix/zxcvbn-ex | ce5f1a9f5ca3b7b17c895fc237e12cdede85da38 | [
"MIT"
] | 7 | 2018-10-06T10:14:41.000Z | 2019-10-01T09:29:44.000Z | defmodule Zxcvbn.MixProject do
use Mix.Project
def project do
[
app: :zxcvbn,
version: "0.1.0",
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[
{:credo, "~> 0.10.2", only: [:dev, :test], runtime: false}
]
end
end
| 15.153846 | 64 | 0.522843 |
1c3b2b9992d1cb7d60167bd9ca639ad33d7ecfb3 | 213 | ex | Elixir | lib/absinthe/execution/resolution/enum.ex | scrogson/absinthe | aa7e9c83dc10603c72f80e09a60d12495bc1c6b7 | [
"Unlicense"
] | 1 | 2019-05-07T15:05:52.000Z | 2019-05-07T15:05:52.000Z | lib/absinthe/execution/resolution/enum.ex | scrogson/absinthe | aa7e9c83dc10603c72f80e09a60d12495bc1c6b7 | [
"Unlicense"
] | null | null | null | lib/absinthe/execution/resolution/enum.ex | scrogson/absinthe | aa7e9c83dc10603c72f80e09a60d12495bc1c6b7 | [
"Unlicense"
] | null | null | null | defimpl Absinthe.Execution.Resolution, for: Absinthe.Type.Enum do
def resolve(enum, %{resolution: %{target: target}} = execution) do
{:ok, Absinthe.Type.Enum.serialize!(enum, target), execution}
end
end
| 26.625 | 68 | 0.723005 |
1c3b41e323be3b54fecf0b3a39671354104241ae | 295 | exs | Elixir | test/dogma/util/lines_test.exs | lpil/dogma | e0f55c27ec3053be0313ac93f3d036437ee590a1 | [
"MIT"
] | 558 | 2015-06-21T18:20:59.000Z | 2021-12-30T16:25:47.000Z | test/dogma/util/lines_test.exs | lpil/dogma | e0f55c27ec3053be0313ac93f3d036437ee590a1 | [
"MIT"
] | 252 | 2015-06-19T13:00:47.000Z | 2021-04-21T08:04:16.000Z | test/dogma/util/lines_test.exs | lpil/dogma | e0f55c27ec3053be0313ac93f3d036437ee590a1 | [
"MIT"
] | 79 | 2015-06-21T14:18:30.000Z | 2021-12-30T16:26:09.000Z | defmodule Dogma.Util.LinesTest do
use ExUnit.Case, async: true
alias Dogma.Util.Lines
test "split a string into lines" do
result = """
Hello,
world!
""" |> Lines.get
expected = [
{1, "Hello,"},
{2, "world!"},
]
assert result == expected
end
end
| 16.388889 | 37 | 0.566102 |
1c3b4aa78db8ca362b05e7f640e388b6f50a1d14 | 104 | ex | Elixir | lib/hello_web/views/layout_view.ex | krzysztofmo/hello | 8d317fd168bec46de698268e6ffce752c9fa4c94 | [
"MIT"
] | null | null | null | lib/hello_web/views/layout_view.ex | krzysztofmo/hello | 8d317fd168bec46de698268e6ffce752c9fa4c94 | [
"MIT"
] | null | null | null | lib/hello_web/views/layout_view.ex | krzysztofmo/hello | 8d317fd168bec46de698268e6ffce752c9fa4c94 | [
"MIT"
] | null | null | null | defmodule HelloWeb.LayoutView do
use HelloWeb, :view
def node_name() do
Node.self()
end
end
| 11.555556 | 32 | 0.692308 |
1c3b4bc820e228d935094f68c18efbf4d65d96e2 | 60 | ex | Elixir | web/views/session_view.ex | NorifumiKawamoto/ginjyo | 8e28438db4675bb55ba090614c6834190adb61b1 | [
"MIT"
] | null | null | null | web/views/session_view.ex | NorifumiKawamoto/ginjyo | 8e28438db4675bb55ba090614c6834190adb61b1 | [
"MIT"
] | null | null | null | web/views/session_view.ex | NorifumiKawamoto/ginjyo | 8e28438db4675bb55ba090614c6834190adb61b1 | [
"MIT"
] | null | null | null | defmodule Ginjyo.SessionView do
use Ginjyo.Web, :view
end
| 15 | 31 | 0.783333 |
1c3b5bf77d5fd23fe85f113f531290e82bd86d82 | 364 | exs | Elixir | test/wallaby/phantom/driver/configuration_test.exs | schnittchen/wallaby | 30be89cc78087e53e5b47a86043c2bbe8566bbf4 | [
"MIT"
] | null | null | null | test/wallaby/phantom/driver/configuration_test.exs | schnittchen/wallaby | 30be89cc78087e53e5b47a86043c2bbe8566bbf4 | [
"MIT"
] | null | null | null | test/wallaby/phantom/driver/configuration_test.exs | schnittchen/wallaby | 30be89cc78087e53e5b47a86043c2bbe8566bbf4 | [
"MIT"
] | null | null | null | defmodule Wallaby.Phantom.Driver.ConfigurationTest do
use Wallaby.SessionCase, async: false
test "js errors can be disabled", %{session: session} do
Application.put_env(:wallaby, :js_errors, false)
session
|> visit("/errors.html")
|> click_button("Throw an Error")
|> assert
Application.put_env(:wallaby, :js_errors, true)
end
end
| 24.266667 | 58 | 0.700549 |
1c3b65e7699f236591a824a9e41ff6fafcea002a | 246 | ex | Elixir | apps/proxy/lib/supervisor.ex | nicolasbaer/thirsty_throttler | 04d68f94d97fa2a661e6c00898b3b140cdba9b4a | [
"Apache-2.0"
] | null | null | null | apps/proxy/lib/supervisor.ex | nicolasbaer/thirsty_throttler | 04d68f94d97fa2a661e6c00898b3b140cdba9b4a | [
"Apache-2.0"
] | null | null | null | apps/proxy/lib/supervisor.ex | nicolasbaer/thirsty_throttler | 04d68f94d97fa2a661e6c00898b3b140cdba9b4a | [
"Apache-2.0"
] | null | null | null | defmodule Proxy.Supervisor do
use Supervisor
def start_link(_) do
{:ok, _sup} = Supervisor.start_link(__MODULE__, [], name: :supervisor)
end
def init(_) do
processes = []
{:ok, {{:one_for_one, 10, 10}, processes}}
end
end | 18.923077 | 74 | 0.646341 |
1c3b9d59f0b1f0d812ceebc36e6ae2c9fed84c32 | 84 | exs | Elixir | test/lab42_html_test.exs | RobertDober/lab42_html | 8ec0bbce73e5e99964ec50e00d7d56c30b50b1fd | [
"Apache-2.0"
] | null | null | null | test/lab42_html_test.exs | RobertDober/lab42_html | 8ec0bbce73e5e99964ec50e00d7d56c30b50b1fd | [
"Apache-2.0"
] | 2 | 2019-10-14T08:50:28.000Z | 2019-10-16T11:09:08.000Z | test/lab42_html_test.exs | RobertDober/lab42_html | 8ec0bbce73e5e99964ec50e00d7d56c30b50b1fd | [
"Apache-2.0"
] | null | null | null | defmodule Lab42HtmlTest do
use ExUnit.Case
doctest Lab42.Html, import: true
end
| 16.8 | 34 | 0.785714 |
1c3be96a8bae5cd179ac89aaed674a636d87274b | 62,425 | ex | Elixir | clients/translate/lib/google_api/translate/v3/api/projects.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/translate/lib/google_api/translate/v3/api/projects.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/translate/lib/google_api/translate/v3/api/projects.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Translate.V3.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.Translate.V3.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Detects the language of text within a request.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Project or location to make a call. Must refer to a caller's
project.
Format: `projects/{project-number-or-id}/locations/{location-id}` or
`projects/{project-number-or-id}`.
For global calls, use `projects/{project-number-or-id}/locations/global` or
`projects/{project-number-or-id}`.
Only models within the same region (has same location-id) can be used.
Otherwise an INVALID_ARGUMENT (400) error is returned.
* `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.Translate.V3.Model.DetectLanguageRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.DetectLanguageResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_detect_language(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Translate.V3.Model.DetectLanguageResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_detect_language(connection, parent, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+parent}:detectLanguage", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.DetectLanguageResponse{}])
end
@doc """
Returns a list of supported languages for translation.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Project or location to make a call. Must refer to a caller's
project.
Format: `projects/{project-number-or-id}` or
`projects/{project-number-or-id}/locations/{location-id}`.
For global calls, use `projects/{project-number-or-id}/locations/global` or
`projects/{project-number-or-id}`.
Non-global location is required for AutoML models.
Only models within the same region (have same location-id) can be used,
otherwise an INVALID_ARGUMENT (400) error is returned.
* `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").
* `:displayLanguageCode` (*type:* `String.t`) - Optional. The language to use to return localized, human readable names
of supported languages. If missing, then display names are not returned
in a response.
* `:model` (*type:* `String.t`) - Optional. Get supported languages of this model.
The format depends on model type:
- AutoML Translation models:
`projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`
- General (built-in) models:
`projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`,
`projects/{project-number-or-id}/locations/{location-id}/models/general/base`
Returns languages supported by the specified model.
If missing, we get supported languages of Google general base (PBMT) model.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.SupportedLanguages{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_get_supported_languages(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.SupportedLanguages.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_get_supported_languages(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:displayLanguageCode => :query,
:model => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+parent}/supportedLanguages", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.SupportedLanguages{}])
end
@doc """
Translates input text and returns translated text.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Project or location to make a call. Must refer to a caller's
project.
Format: `projects/{project-number-or-id}` or
`projects/{project-number-or-id}/locations/{location-id}`.
For global calls, use `projects/{project-number-or-id}/locations/global` or
`projects/{project-number-or-id}`.
Non-global location is required for requests using AutoML models or
custom glossaries.
Models and glossaries must be within the same region (have same
location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
* `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.Translate.V3.Model.TranslateTextRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.TranslateTextResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_translate_text(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Translate.V3.Model.TranslateTextResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_translate_text(connection, parent, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+parent}:translateText", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.TranslateTextResponse{}])
end
@doc """
Translates a large volume of text in asynchronous batch mode.
This function provides real-time output as the inputs are being processed.
If caller cancels a request, the partial results (for an input file, it's
all or nothing) may still be available on the specified output location.
This call returns immediately and you can
use google.longrunning.Operation.name to poll the status of the call.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Location to make a call. Must refer to a caller's project.
Format: `projects/{project-number-or-id}/locations/{location-id}`.
The `global` location is not supported for batch translation.
Only AutoML Translation models or glossaries within the same region (have
the same location-id) can be used, otherwise an INVALID_ARGUMENT (400)
error is returned.
* `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.Translate.V3.Model.BatchTranslateTextRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_batch_translate_text(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_batch_translate_text(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+parent}:batchTranslateText", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Operation{}])
end
@doc """
Detects the language of text within a request.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Project or location to make a call. Must refer to a caller's
project.
Format: `projects/{project-number-or-id}/locations/{location-id}` or
`projects/{project-number-or-id}`.
For global calls, use `projects/{project-number-or-id}/locations/global` or
`projects/{project-number-or-id}`.
Only models within the same region (has same location-id) can be used.
Otherwise an INVALID_ARGUMENT (400) error is returned.
* `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.Translate.V3.Model.DetectLanguageRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.DetectLanguageResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_detect_language(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.DetectLanguageResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_detect_language(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+parent}:detectLanguage", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.DetectLanguageResponse{}])
end
@doc """
Gets information about a location.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name for the location.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Location{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Translate.V3.Model.Location.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Location{}])
end
@doc """
Returns a list of supported languages for translation.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Project or location to make a call. Must refer to a caller's
project.
Format: `projects/{project-number-or-id}` or
`projects/{project-number-or-id}/locations/{location-id}`.
For global calls, use `projects/{project-number-or-id}/locations/global` or
`projects/{project-number-or-id}`.
Non-global location is required for AutoML models.
Only models within the same region (have same location-id) can be used,
otherwise an INVALID_ARGUMENT (400) error is returned.
* `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").
* `:displayLanguageCode` (*type:* `String.t`) - Optional. The language to use to return localized, human readable names
of supported languages. If missing, then display names are not returned
in a response.
* `:model` (*type:* `String.t`) - Optional. Get supported languages of this model.
The format depends on model type:
- AutoML Translation models:
`projects/{project-number-or-id}/locations/{location-id}/models/{model-id}`
- General (built-in) models:
`projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`,
`projects/{project-number-or-id}/locations/{location-id}/models/general/base`
Returns languages supported by the specified model.
If missing, we get supported languages of Google general base (PBMT) model.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.SupportedLanguages{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_get_supported_languages(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.SupportedLanguages.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_get_supported_languages(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:displayLanguageCode => :query,
:model => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+parent}/supportedLanguages", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.SupportedLanguages{}])
end
@doc """
Lists information about the supported locations for this service.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.ListLocationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Translate.V3.Model.ListLocationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_list(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+name}/locations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.ListLocationsResponse{}])
end
@doc """
Translates input text and returns translated text.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Project or location to make a call. Must refer to a caller's
project.
Format: `projects/{project-number-or-id}` or
`projects/{project-number-or-id}/locations/{location-id}`.
For global calls, use `projects/{project-number-or-id}/locations/global` or
`projects/{project-number-or-id}`.
Non-global location is required for requests using AutoML models or
custom glossaries.
Models and glossaries must be within the same region (have same
location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
* `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.Translate.V3.Model.TranslateTextRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.TranslateTextResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_translate_text(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.TranslateTextResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_translate_text(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+parent}:translateText", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.TranslateTextResponse{}])
end
@doc """
Creates a glossary and returns the long-running operation. Returns
NOT_FOUND, if the project doesn't exist.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The project name.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.Translate.V3.Model.Glossary.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_glossaries_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_glossaries_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+parent}/glossaries", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Operation{}])
end
@doc """
Deletes a glossary, or cancels glossary construction
if the glossary isn't created yet.
Returns NOT_FOUND, if the glossary doesn't exist.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The name of the glossary to delete.
* `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.Translate.V3.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_glossaries_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_glossaries_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v3/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Operation{}])
end
@doc """
Gets a glossary. Returns NOT_FOUND, if the glossary doesn't
exist.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. The name of the glossary to retrieve.
* `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.Translate.V3.Model.Glossary{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_glossaries_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Glossary.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_glossaries_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Glossary{}])
end
@doc """
Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't
exist.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The name of the project from which to list all of the glossaries.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Optional. Filter specifying constraints of a list operation.
Filtering is not supported yet, and the parameter currently has no effect.
If missing, no filtering is performed.
* `:pageSize` (*type:* `integer()`) - Optional. Requested page size. The server may return fewer glossaries than
requested. If unspecified, the server picks an appropriate default.
* `:pageToken` (*type:* `String.t`) - Optional. A token identifying a page of results the server should return.
Typically, this is the value of [ListGlossariesResponse.next_page_token]
returned from the previous call to `ListGlossaries` method.
The first page is returned if `page_token`is empty or missing.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.ListGlossariesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_glossaries_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.ListGlossariesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_glossaries_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+parent}/glossaries", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.ListGlossariesResponse{}])
end
@doc """
Starts asynchronous cancellation on a long-running operation. The server
makes a best effort to cancel the operation, but success is not
guaranteed. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`. Clients can use
Operations.GetOperation or
other methods to check whether the cancellation succeeded or whether the
operation completed despite cancellation. On successful cancellation,
the operation is not deleted; instead, it becomes an operation with
an Operation.error value with a google.rpc.Status.code of 1,
corresponding to `Code.CANCELLED`.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be cancelled.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.Translate.V3.Model.CancelOperationRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_operations_cancel(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def translate_projects_locations_operations_cancel(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+name}:cancel", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Empty{}])
end
@doc """
Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to be deleted.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_operations_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def translate_projects_locations_operations_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v3/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Empty{}])
end
@doc """
Gets the latest state of a long-running operation. Clients can use this
method to poll the operation result at intervals as recommended by the API
service.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_operations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_operations_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Operation{}])
end
@doc """
Lists operations that match the specified filter in the request. If the
server doesn't support this method, it returns `UNIMPLEMENTED`.
NOTE: the `name` binding allows API services to override the binding
to use different resource name schemes, such as `users/*/operations`. To
override the binding, API services can add a binding such as
`"/v1/{name=users/*}/operations"` to their service configuration.
For backwards compatibility, the default name includes the operations
collection id, however overriding users must ensure the name binding
is the parent resource, without the operations collection id.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation's parent resource.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.ListOperationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_operations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.ListOperationsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_operations_list(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v3/{+name}/operations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.ListOperationsResponse{}])
end
@doc """
Waits for the specified long-running operation until it is done or reaches
at most a specified timeout, returning the latest state. If the operation
is already done, the latest state is immediately returned. If the timeout
specified is greater than the default HTTP/RPC timeout, the HTTP/RPC
timeout is used. If the server does not support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`.
Note that this method is on a best-effort basis. It may return the latest
state before the specified timeout (including immediately), meaning even an
immediate response is no guarantee that the operation is done.
## Parameters
* `connection` (*type:* `GoogleApi.Translate.V3.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The name of the operation resource to wait on.
* `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.Translate.V3.Model.WaitOperationRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Translate.V3.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec translate_projects_locations_operations_wait(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Translate.V3.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def translate_projects_locations_operations_wait(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v3/{+name}:wait", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Translate.V3.Model.Operation{}])
end
end
| 43.837781 | 196 | 0.618791 |
1c3bf31056ee06a2048311926d72f0a977eedb16 | 1,844 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/date_range.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/date_range.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/v34/model/date_range.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.V34.Model.DateRange do
@moduledoc """
Represents a date range.
## Attributes
* `endDate` (*type:* `Date.t`, *default:* `nil`) -
* `kind` (*type:* `String.t`, *default:* `nil`) - The kind of resource this is, in this case dfareporting#dateRange.
* `relativeDateRange` (*type:* `String.t`, *default:* `nil`) - The date range relative to the date of when the report is run.
* `startDate` (*type:* `Date.t`, *default:* `nil`) -
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:endDate => Date.t(),
:kind => String.t(),
:relativeDateRange => String.t(),
:startDate => Date.t()
}
field(:endDate, as: Date)
field(:kind)
field(:relativeDateRange)
field(:startDate, as: Date)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.DateRange do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.DateRange.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.DateRange do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.928571 | 129 | 0.694143 |
1c3c01096ba50851581374cc3ad1285c8b6dfad6 | 274 | ex | Elixir | lib/plumbapius/coverage/coverage_tracker.ex | kuznetsov-v-spb/plumbapius | bd5f6b597417b5a28d7e9abb9bb3ef7b020c3f10 | [
"Apache-2.0"
] | null | null | null | lib/plumbapius/coverage/coverage_tracker.ex | kuznetsov-v-spb/plumbapius | bd5f6b597417b5a28d7e9abb9bb3ef7b020c3f10 | [
"Apache-2.0"
] | null | null | null | lib/plumbapius/coverage/coverage_tracker.ex | kuznetsov-v-spb/plumbapius | bd5f6b597417b5a28d7e9abb9bb3ef7b020c3f10 | [
"Apache-2.0"
] | null | null | null | defmodule Plumbapius.Coverage.CoverageTracker do
alias Plumbapius.Request
alias Plumbapius.Response
@type t :: module()
@type interaction :: {Request.Schema.t(), Response.Schema.t()}
@callback response_covered(Request.Schema.t(), Response.Schema.t()) :: :ok
end
| 27.4 | 76 | 0.737226 |
1c3c1bcd46a42fcc2c55d13565df1620a4b9622a | 1,262 | ex | Elixir | lib/elixir_xml_to_map.ex | szTheory/elixir-xml-to-map | f8d3023240e29152b242750a41c4dfad2478972a | [
"Apache-2.0"
] | null | null | null | lib/elixir_xml_to_map.ex | szTheory/elixir-xml-to-map | f8d3023240e29152b242750a41c4dfad2478972a | [
"Apache-2.0"
] | null | null | null | lib/elixir_xml_to_map.ex | szTheory/elixir-xml-to-map | f8d3023240e29152b242750a41c4dfad2478972a | [
"Apache-2.0"
] | null | null | null | defmodule XmlToMap do
@moduledoc """
Simple convenience module for getting a map out of an XML string.
"""
alias XmlToMap.NaiveMap
@doc """
naive_map(xml) utility is inspired by Rails Hash.from_xml()
but is "naive" in that it is convenient (requires no setup)
but carries the same drawbacks. For example no validation over
what should be a collection. If and only if nodes are repeated
at the same level will they become a list. If a node has attributes
we'll prepend a "-" in front of them and merge them into the map and
take the node value and nest that inside "#content" key.
"""
def naive_map(xml) do
# can't handle xmlns, if left in will prepend every output map
# key with the xmlns value in curly braces
xml = String.replace(xml, ~r/(\sxmlns="\S+")|(xmlns:ns2="\S+")/, "")
tree = get_generic_data_structure(xml)
NaiveMap.parse(tree)
end
# erlsom simple_form returns a kind of tree:
# Result = {ok, Element, Tail},
# where Element = {Tag, Attributes, Content},
# Tag is a string
# Attributes = [{AttributeName, Value}],
# Content is a list of Elements and/or strings.
def get_generic_data_structure(xml) do
{:ok, element, _tail} = :erlsom.simple_form(xml)
element
end
end
| 32.358974 | 72 | 0.694136 |
1c3c236a5fda125eff8ec467c5715e5f7579587d | 2,447 | ex | Elixir | lib/excel.ex | imahiro-t/smallex | 5fbc7080fde7f63b3440d8325f45d61f5d1b5bc3 | [
"Apache-2.0"
] | 7 | 2020-01-13T21:17:28.000Z | 2021-11-15T12:10:55.000Z | lib/excel.ex | data-maestro/smallex | 5fbc7080fde7f63b3440d8325f45d61f5d1b5bc3 | [
"Apache-2.0"
] | 26 | 2021-02-25T09:22:28.000Z | 2021-06-11T02:59:11.000Z | lib/excel.ex | data-maestro/smallex | 5fbc7080fde7f63b3440d8325f45d61f5d1b5bc3 | [
"Apache-2.0"
] | 2 | 2018-01-02T17:59:40.000Z | 2018-01-12T17:16:02.000Z | defmodule Excel do
@moduledoc """
Excel library.
"""
@doc """
Load map
## Parameters
- `path` : Excel(.xlsx) file path
- `sheet_number` : Sheet number (0-origin)
## Examples
iex> Excel.load_map( "test/test.xlsx", "sheet1" )
[
%{ "age" => "49", "id" => "1", "name" => "John Smith" },
%{ "age" => "45", "id" => "2", "name" => "Zakk Wylde" },
%{ "age" => "44", "id" => "3", "name" => "piacere" }
]
iex> Excel.load_map( "test/test.xlsx", 0 )
[
%{ "age" => "49", "id" => "1", "name" => "John Smith" },
%{ "age" => "45", "id" => "2", "name" => "Zakk Wylde" },
%{ "age" => "44", "id" => "3", "name" => "piacere" }
]
iex> Excel.load_map( "test/test.xlsx", 1 )
[
%{ "id" => "1", "lots" => "30", "name" => "River" },
%{ "id" => "2", "lots" => "34", "name" => "Soil" }
]
"""
def load_map( path, sheet_name ) when is_binary( sheet_name ) do
sheet_number = sheet_names( path )
|> Enum.find_index( &( &1 == sheet_name ) )
load_map( path, sheet_number )
end
def load_map( path, sheet_number ) do
path
|> Excelion.parse!( sheet_number, 1 )
|> MapList.first_columns_after_rows
end
@doc """
Load
## Parameters
- `path` : Excel(.xlsx) file path
- `sheet_number` : Sheet number (0-origin)
## Examples
iex> Excel.load( "test/test.xlsx", "sheet1" )
%{
"columns" => [ "id", "name", "age" ],
"rows" =>
[
[ "1", "John Smith", "49" ],
[ "2", "Zakk Wylde", "45" ],
[ "3", "piacere", "44" ],
]
}
iex> Excel.load( "test/test.xlsx", 0 )
%{
"columns" => [ "id", "name", "age" ],
"rows" =>
[
[ "1", "John Smith", "49" ],
[ "2", "Zakk Wylde", "45" ],
[ "3", "piacere", "44" ],
]
}
iex> Excel.load( "test/test.xlsx", 1 )
%{
"columns" => [ "id", "name", "lots" ],
"rows" =>
[
[ "1", "River", "30" ],
[ "2", "Soil", "34" ],
]
}
"""
def load( path, sheet_name ) when is_binary( sheet_name ) do
sheet_number = sheet_names( path )
|> Enum.find_index( &( &1 == sheet_name ) )
load( path, sheet_number )
end
def load( path, sheet_number ) when is_number( sheet_number ) do
path
|> Excelion.parse!( sheet_number, 1 )
|> Lst.separate( "columns", "rows" )
end
@doc """
Get sheet names
## Examples
iex> Excel.sheet_names( "test/test.xlsx" )
[ "sheet1", "sheet2" ]
"""
def sheet_names( path ) do
path
|> Excelion.get_worksheet_names
|> Tpl.ok
end
end
| 23.084906 | 65 | 0.50756 |
1c3c852fdf29b8a0f71fc127e5da8e9e9fa3ce0a | 3,990 | exs | Elixir | test/custom_extensions_test.exs | ivan/postgrex | dd377695fbe469bc3823116b9e4e8f498996b9a3 | [
"Apache-2.0"
] | null | null | null | test/custom_extensions_test.exs | ivan/postgrex | dd377695fbe469bc3823116b9e4e8f498996b9a3 | [
"Apache-2.0"
] | null | null | null | test/custom_extensions_test.exs | ivan/postgrex | dd377695fbe469bc3823116b9e4e8f498996b9a3 | [
"Apache-2.0"
] | null | null | null | defmodule CustomExtensionsTest do
use ExUnit.Case, async: true
import Postgrex.TestHelper
import ExUnit.CaptureLog
alias Postgrex, as: P
@types CustomExtensionsTypes
defmodule BinaryExtension do
@behaviour Postgrex.Extension
def init([]),
do: []
def matching([]),
do: [send: "int4send"]
def format([]),
do: :binary
def encode([]) do
quote do
int ->
<<4::int32, int+1::int32>>
end
end
def decode([]) do
quote do
<<4::int32, int::int32>> -> int + 1
end
end
end
defmodule TextExtension do
@behaviour Postgrex.Extension
def init([]),
do: {}
def matching({}),
do: [send: "float8send", send: "oidsend"]
def format({}),
do: :text
def encode({}) do
quote do
value ->
[<<byte_size(value)::int32>> | value]
end
end
def decode({}) do
quote do
<<len::int32, binary::binary-size(len)>> ->
binary
end
end
end
defmodule BadExtension do
@behaviour Postgrex.Extension
def init([]),
do: []
def matching([]),
do: [send: "boolsend"]
def format([]),
do: :binary
def encode([]) do
quote do
_ ->
raise "encode"
end
end
def decode([]) do
quote do
<<1::int32, _>> ->
raise "decode"
end
end
end
setup_all do
on_exit(fn ->
:code.delete(@types)
:code.purge(@types)
end)
extensions = [BinaryExtension, TextExtension, BadExtension]
opts = [decode_binary: :reference, null: :custom]
Postgrex.TypeModule.define(@types, extensions, opts)
:ok
end
setup do
opts = [database: "postgrex_test", backoff_type: :stop, types: @types]
{:ok, pid} = P.start_link(opts)
{:ok, [pid: pid, options: opts]}
end
test "encode and decode", context do
assert [[44]] = query("SELECT $1::int4", [42])
assert [[[44]]] = query("SELECT $1::int4[]", [[42]])
end
test "encode and decode unknown type", context do
assert [["23"]] =
query("SELECT $1::oid", ["23"])
end
test "encode and decode pushes error to client", context do
Process.flag(:trap_exit, true)
assert_raise RuntimeError, "encode", fn ->
query("SELECT $1::boolean", [true])
end
assert capture_log(fn() ->
assert_raise RuntimeError, "decode", fn ->
query("SELECT true", [])
end
pid = context[:pid]
assert_receive {:EXIT, ^pid, {%DBConnection.ConnectionError{}, _}}
end) =~ "(RuntimeError) decode"
end
test "raise when executing prepared query on connection with different types", context do
query = prepare("S42", "SELECT 42")
opts = [types: Postgrex.DefaultTypes] ++ context[:options]
{:ok, pid2} = Postgrex.start_link(opts)
assert_raise ArgumentError, ~r"invalid types for the connection",
fn() -> Postgrex.execute(pid2, query, []) end
end
test "raise when streaming prepared query on connection with different types", context do
query = prepare("S42", "SELECT 42")
opts = [types: Postgrex.DefaultTypes] ++ context[:options]
{:ok, pid2} = Postgrex.start_link(opts)
Postgrex.transaction(pid2, fn(conn) ->
assert_raise ArgumentError, ~r"invalid types for the connection",
fn() -> stream(query, []) |> Enum.take(1) end
end)
end
test "raise when streaming prepared COPY FROM on connection with different types", context do
query = prepare("copy", "COPY uniques FROM STDIN")
opts = [types: Postgrex.DefaultTypes] ++ context[:options]
{:ok, pid2} = Postgrex.start_link(opts)
Postgrex.transaction(pid2, fn(conn) ->
assert_raise ArgumentError, ~r"invalid types for the connection",
fn() -> Enum.into(["1\n"], stream(query, [])) end
end)
end
test "dont decode text format", context do
assert [["123.45"]] = query("SELECT 123.45::float8", [])
end
end
| 23.333333 | 95 | 0.592481 |
1c3cb3c732928e5789c62b4a0e2f1fddb6b3cb98 | 1,465 | exs | Elixir | mix.exs | gumabe/metatags | e4098c26c7ef255412c1563c81493925d1e799dd | [
"MIT"
] | null | null | null | mix.exs | gumabe/metatags | e4098c26c7ef255412c1563c81493925d1e799dd | [
"MIT"
] | null | null | null | mix.exs | gumabe/metatags | e4098c26c7ef255412c1563c81493925d1e799dd | [
"MIT"
] | null | null | null | defmodule Metatags.Mixfile do
use Mix.Project
@version "0.3.0"
@description """
Metatags provides an easy to work with API to set default and
page specific metatags on a page.
"""
def project do
[
app: :metatags,
version: @version,
elixir: "~> 1.4",
deps: deps(),
description: @description,
package: package(),
test_coverage: [
tool: ExCoveralls
],
preferred_cli_env: [
credo: :test,
dialyzer: :test,
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
docs: docs()
]
end
defp deps do
[
{:phoenix_html, "~> 2.9"},
{:ex_doc, "~> 0.16", only: :dev},
{:credo, ">= 0.0.0", only: :test, runtime: false},
{:excoveralls, ">= 0.0.0", only: :test, runtime: false},
{:dialyxir, "~> 0.5", only: :test, runtime: false}
]
end
defp package do
[
name: :metatags,
description: @description,
files: ["lib", "mix.exs", "README.md", "LICENSE", "CHANGELOG.md"],
maintainers: ["johan Tell"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/johantell/metatags"}
]
end
defp docs do
[
main: "readme",
extras: [
"README.md",
"CHANGELOG.md"
],
source_ref: "v#{@version}",
source_url: "https://github.com/johantell/metatags"
]
end
end
| 21.865672 | 72 | 0.530375 |
1c3cd49a35b765b034d5ce4fa53f4d95c4c4bd1b | 651 | exs | Elixir | config/test.exs | seent-app/seent | 6071a0f90f1cb5345faa0c9e476d3c64310a7be9 | [
"0BSD"
] | null | null | null | config/test.exs | seent-app/seent | 6071a0f90f1cb5345faa0c9e476d3c64310a7be9 | [
"0BSD"
] | 1 | 2020-07-04T17:19:38.000Z | 2020-07-04T17:19:38.000Z | config/test.exs | seent-app/seent | 6071a0f90f1cb5345faa0c9e476d3c64310a7be9 | [
"0BSD"
] | null | null | null | use Mix.Config
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :seent, Seent.Repo,
username: "postgres",
password: "postgres",
database: "seent_test#{System.get_env("MIX_TEST_PARTITION")}",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :seent, SeentWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 28.304348 | 64 | 0.745008 |
1c3ce4e0c56c35aa31787dfa76a6eb07fd7a82de | 693 | exs | Elixir | config/travis.exs | edgar971/built_with_elixir | 9837f986d33e83524167b68fc44ee36e84387747 | [
"MIT"
] | 8 | 2018-04-15T19:01:14.000Z | 2018-11-19T16:13:56.000Z | config/travis.exs | edgar971/built_with_elixir | 9837f986d33e83524167b68fc44ee36e84387747 | [
"MIT"
] | 8 | 2018-04-14T03:32:12.000Z | 2018-05-15T04:28:27.000Z | config/travis.exs | edgar971/built_with_elixir | 9837f986d33e83524167b68fc44ee36e84387747 | [
"MIT"
] | null | null | null | use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :built_with_elixir, BuiltWithElixirWeb.Endpoint,
http: [port: 4001],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :built_with_elixir, BuiltWithElixir.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "",
database: "built_with_elixir_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
config :cloudini,
name: "wadfdfd",
api_key: "2222",
api_secret: "2222",
stub_requests: true
# Stubs
config :built_with_elixir, :cloudini, CloudiniStub
| 23.896552 | 56 | 0.744589 |
1c3cefc068cffa677da5156fa2b41870cf90f16d | 1,879 | ex | Elixir | apps/omg_status/lib/omg_status/release_tasks/set_logger.ex | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 177 | 2018-08-24T03:51:02.000Z | 2020-05-30T13:29:25.000Z | apps/omg_status/lib/omg_status/release_tasks/set_logger.ex | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 1,042 | 2018-08-25T00:52:39.000Z | 2020-06-01T05:15:17.000Z | apps/omg_status/lib/omg_status/release_tasks/set_logger.ex | omisego/elixir-omg | 2c68973d8f29033d137f63a6e060f12e2a7dcd59 | [
"Apache-2.0"
] | 47 | 2018-08-24T12:06:33.000Z | 2020-04-28T11:49:25.000Z | # Copyright 2019-2019 OMG Network Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule OMG.Status.ReleaseTasks.SetLogger do
@moduledoc false
@behaviour Config.Provider
require Logger
@app :logger
@default_backend Ink
def init(args) do
args
end
def load(config, _args) do
_ = on_load()
logger_backends = Application.get_env(@app, :backends, persistent: true)
logger_backend = get_logger_backend()
remove =
case logger_backend do
:console -> Ink
_ -> :console
end
backends = logger_backends |> Kernel.--([remove]) |> Enum.concat([logger_backend]) |> Enum.uniq()
Config.Reader.merge(config, logger: [backends: backends])
end
defp get_logger_backend() do
logger =
"LOGGER_BACKEND"
|> get_env()
|> validate_string(@default_backend)
_ = Logger.info("CONFIGURATION: App: #{@app} Key: LOGGER_BACKEND Value: #{inspect(logger)}.")
logger
end
defp get_env(key), do: System.get_env(key)
defp validate_string(nil, default), do: default
defp validate_string(value, default), do: do_validate_string(String.upcase(value), default)
defp do_validate_string("CONSOLE", _default), do: :console
defp do_validate_string("INK", _default), do: Ink
defp do_validate_string(_, default), do: default
defp on_load() do
_ = Application.load(:logger)
end
end
| 29.359375 | 101 | 0.708356 |
1c3cfe89cfe2114dde55de70987a7e0a6167ba28 | 491 | ex | Elixir | lib/sobelow/ci/os.ex | kianmeng/sobelow | 40c5f12ed6801c1f9cca13201f7f6ff31c8a7660 | [
"Apache-2.0"
] | null | null | null | lib/sobelow/ci/os.ex | kianmeng/sobelow | 40c5f12ed6801c1f9cca13201f7f6ff31c8a7660 | [
"Apache-2.0"
] | null | null | null | lib/sobelow/ci/os.ex | kianmeng/sobelow | 40c5f12ed6801c1f9cca13201f7f6ff31c8a7660 | [
"Apache-2.0"
] | null | null | null | defmodule Sobelow.CI.OS do
use Sobelow.Finding
@finding_type "Command Injection in `:os.cmd`"
def run(fun, meta_file) do
confidence = if !meta_file.is_controller?, do: :low
Finding.init(@finding_type, meta_file.filename, confidence)
|> Finding.multi_from_def(fun, parse_def(fun))
|> Enum.each(&Print.add_finding(&1))
end
def parse_def(fun) do
Parse.get_erlang_fun_vars_and_meta(fun, 0, :cmd, :os)
end
def details() do
Sobelow.CI.details()
end
end
| 23.380952 | 63 | 0.698574 |
1c3d149bc92c1e9b176bf2ec2742e90b3c9fda01 | 725 | ex | Elixir | web/gettext.ex | Gronex/wishlist_manager | be240ebc85a737f31bd64bc913a2c3716827fd26 | [
"MIT"
] | null | null | null | web/gettext.ex | Gronex/wishlist_manager | be240ebc85a737f31bd64bc913a2c3716827fd26 | [
"MIT"
] | 7 | 2015-12-30T19:43:10.000Z | 2016-01-04T14:38:38.000Z | web/gettext.ex | Gronex/wishlist_manager | be240ebc85a737f31bd64bc913a2c3716827fd26 | [
"MIT"
] | null | null | null | defmodule WishlistManager.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](http://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import WishlistManager.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](http://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :wishlist_manager
end
| 29 | 71 | 0.688276 |
1c3d2389953d173a4eaa998e9b9b599b68e18c22 | 818 | ex | Elixir | lib/still/preprocessor/url_fingerprinting.ex | fmterrorf/still | fd316bcc38cdf618444dbd36ec9d259fe5256a3e | [
"0BSD"
] | 2 | 2021-02-15T07:55:38.000Z | 2021-03-05T18:04:53.000Z | lib/still/preprocessor/url_fingerprinting.ex | mrmicahcooper/still | ba785b0b068d998d0343f73a1fd1795edbe9831c | [
"0BSD"
] | null | null | null | lib/still/preprocessor/url_fingerprinting.ex | mrmicahcooper/still | ba785b0b068d998d0343f73a1fd1795edbe9831c | [
"0BSD"
] | null | null | null | defmodule Still.Preprocessor.URLFingerprinting do
@moduledoc """
Creates a hash based on the content of the file and generates a fingerprint
to replace the output file.
"""
alias Still.Preprocessor
import Still.Utils, only: [config: 2]
use Preprocessor
@impl true
def render(%{output_file: nil} = file) do
file
end
@impl true
def render(file) do
if enabled?() do
do_render(file)
else
file
end
end
defp do_render(%{content: content, output_file: output_file} = file) do
hash =
:crypto.hash(:md5, content)
|> Base.url_encode64()
ext =
output_file
|> Path.extname()
%{file | output_file: String.replace_suffix(output_file, ext, "-#{hash}#{ext}")}
end
def enabled? do
config(:url_fingerprinting, false)
end
end
| 19.023256 | 84 | 0.651589 |
1c3d2df3c620df21371c4eb52b95a7f1adcc5134 | 21,022 | ex | Elixir | lib/mix/lib/mix/project.ex | farhadi/elixir | 0a37064fd5b67639afb845ff321d6c8ee61e5ee5 | [
"Apache-2.0"
] | 1 | 2021-07-11T16:52:47.000Z | 2021-07-11T16:52:47.000Z | lib/mix/lib/mix/project.ex | farhadi/elixir | 0a37064fd5b67639afb845ff321d6c8ee61e5ee5 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/project.ex | farhadi/elixir | 0a37064fd5b67639afb845ff321d6c8ee61e5ee5 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Project do
@moduledoc """
Defines and manipulates Mix projects.
A Mix project is defined by calling `use Mix.Project` in a module, usually
placed in `mix.exs`:
defmodule MyApp.MixProject do
use Mix.Project
def project do
[
app: :my_app,
version: "1.0.0"
]
end
end
## Configuration
In order to configure Mix, the module that `use`s `Mix.Project` should export
a `project/0` function that returns a keyword list representing configuration
for the project.
This configuration can be read using `Mix.Project.config/0`. Note that
`config/0` won't fail if a project is not defined; this allows many Mix tasks
to work without a project.
If a task requires a project to be defined or needs to access a
special function within the project, the task can call `Mix.Project.get!/0`
which fails with `Mix.NoProjectError` in the case a project is not
defined.
There isn't a comprehensive list of all the options that can be returned by
`project/0` since many Mix tasks define their own options that they read from
this configuration. For example, look at the "Configuration" section in the
documentation for the `Mix.Tasks.Compile` task.
These are a few options that are not used by just one Mix task (and will thus
be documented here):
* `:build_per_environment` - if `true`, builds will be *per-environment*. If
`false`, builds will go in `_build/shared` regardless of the Mix
environment. Defaults to `true`.
* `:aliases` - a list of task aliases. For more information, check out the
"Aliases" section in the documentation for the `Mix` module. Defaults to
`[]`.
* `:config_path` - a string representing the path of the main config
file. See `config_files/0` for more information. Defaults to
`"config/config.exs"`.
* `:default_task` - a string representing the default task to be run by
`mix` when no task is specified. Defaults to `"run"`.
* `:deps` - a list of dependencies of this project. Refer to the
documentation for the `Mix.Tasks.Deps` task for more information. Defaults
to `[]`.
* `:deps_path` - directory where dependencies are stored. Also see
`deps_path/1`. Defaults to `"deps"`.
* `:lockfile` - the name of the lockfile used by the `mix deps.*` family of
tasks. Defaults to `"mix.lock"`.
* `:preferred_cli_env` - a keyword list of `{task, env}` tuples where `task`
is the task name as an atom (for example, `:"deps.get"`) and `env` is the
preferred environment (for example, `:test`). This option overrides what
specified by the tasks with the `@preferred_cli_env` attribute (see the
docs for `Mix.Task`). Defaults to `[]`.
For more options, keep an eye on the documentation for single Mix tasks; good
examples are the `Mix.Tasks.Compile` task and all the specific compiler tasks
(such as `Mix.Tasks.Compile.Elixir` or `Mix.Tasks.Compile.Erlang`).
Note that sometimes the same configuration option is mentioned in the
documentation for different tasks; this is just because it's common for many
tasks to read and use the same configuration option (for example,
`:erlc_paths` is used by `mix compile.erlang`, `mix compile.yecc`, and other
tasks).
## Erlang projects
Mix can be used to manage Erlang projects that don't have any Elixir code. To
ensure Mix tasks work correctly for an Erlang project, `language: :erlang` has
to be part of the configuration returned by `project/0`. This setting also
makes sure Elixir is not added as a dependency to the generated `.app` file or
to the escript generated with `mix escript.build`, and so on.
"""
@doc false
defmacro __using__(_) do
quote do
@after_compile Mix.Project
end
end
# Invoked after each Mix.Project is compiled.
@doc false
def __after_compile__(env, _binary) do
push(env.module, env.file)
end
# Push a project onto the project stack.
# Only the top of the stack can be accessed.
@doc false
def push(atom, file \\ nil, app \\ nil) when is_atom(atom) do
file = file || (atom && List.to_string(atom.__info__(:compile)[:source]))
config = Keyword.merge([app: app] ++ default_config(), get_project_config(atom))
case Mix.ProjectStack.push(atom, config, file) do
:ok ->
:ok
{:error, other} when is_binary(other) ->
Mix.raise(
"Trying to load #{inspect(atom)} from #{inspect(file)}" <>
" but another project with the same name was already defined at #{inspect(other)}"
)
end
end
# Pops a project from the stack.
@doc false
def pop do
Mix.ProjectStack.pop()
end
# The configuration that is pushed down to dependencies.
@doc false
def deps_config(config \\ config()) do
[
build_embedded: config[:build_embedded],
build_per_environment: config[:build_per_environment],
consolidate_protocols: false,
deps_path: deps_path(config),
env_path: build_path(config)
]
end
@doc """
Retrieves the current project if there is one.
If there is no current project, `nil` is returned. This
may happen in cases there is no `mix.exs` in the current
directory.
If you expect a project to be defined, i.e., it is a
requirement of the current task, you should call
`get!/0` instead.
"""
@spec get() :: module | nil
def get do
case Mix.ProjectStack.peek() do
%{name: name} -> name
_ -> nil
end
end
@doc """
Same as `get/0`, but raises an exception if there is no current project.
This is usually called by tasks that need additional
functions on the project to be defined. Since such
tasks usually depend on a project being defined, this
function raises a `Mix.NoProjectError` exception in
case no project is available.
"""
@spec get!() :: module
def get! do
get() || raise Mix.NoProjectError, []
end
@doc """
Returns the project configuration.
If there is no project defined, it still returns a keyword
list with default values. This allows many Mix tasks to work
without the need for an underlying project.
Note this configuration is cached once the project is
pushed onto the stack. Calling it multiple times won't
cause it to be recomputed.
Do not use `Mix.Project.config/0` to find the runtime configuration.
Use it only to configure aspects of your project (like
compilation directories) and not your application runtime.
"""
@spec config() :: keyword
def config do
case Mix.ProjectStack.peek() do
%{config: config} -> config
_ -> default_config()
end
end
@doc """
Returns a list of project configuration files for this project.
This function is usually used in compilation tasks to trigger
a full recompilation whenever such configuration files change.
It returns the `mix.exs` file, the lock manifest, and all config
files in the `config` directory that do not start with a trailing
period (for example, `.my_config.exs`).
"""
@spec config_files() :: [Path.t()]
def config_files do
[Mix.Tasks.WillRecompile.manifest() | Mix.ProjectStack.config_files()]
end
@doc """
Returns the latest modification time from config files.
This function is usually used in compilation tasks to trigger
a full recompilation whenever such configuration files change.
For this reason, the mtime is cached to avoid file system lookups.
"""
@doc since: "1.7.0"
@spec config_mtime() :: posix_mtime when posix_mtime: integer()
def config_mtime do
Mix.Tasks.WillRecompile.manifest()
|> Mix.Utils.last_modified()
|> max(Mix.ProjectStack.config_mtime())
end
@doc """
Returns `true` if `config` is the configuration for an umbrella project.
When called with no arguments, tells whether the current project is
an umbrella project.
"""
@spec umbrella?() :: boolean
def umbrella?(config \\ config()) do
config[:apps_path] != nil
end
@doc """
Returns a map with the umbrella child applications paths.
These paths are based on the `:apps_path` and `:apps` configurations.
If the given project configuration identifies an umbrella project, the return
value is a map of `app => path` where `app` is a child app of the umbrella and
`path` is its path relative to the root of the umbrella project.
If the given project configuration does not identify an umbrella project,
`nil` is returned.
## Examples
Mix.Project.apps_paths()
#=> %{my_app1: "apps/my_app1", my_app2: "apps/my_app2"}
"""
@doc since: "1.4.0"
@spec apps_paths() :: %{optional(atom) => Path.t()} | nil
def apps_paths(config \\ config()) do
if apps_path = config[:apps_path] do
key = {:apps_paths, Mix.Project.get!()}
if cache = Mix.ProjectStack.read_cache(key) do
cache
else
cache = config[:apps] |> umbrella_apps(apps_path) |> to_apps_paths(apps_path)
Mix.ProjectStack.write_cache(key, cache)
end
end
end
defp umbrella_apps(nil, apps_path) do
case File.ls(apps_path) do
{:ok, apps} -> Enum.map(apps, &String.to_atom/1)
{:error, _} -> []
end
end
defp umbrella_apps(apps, _apps_path) when is_list(apps) do
apps
end
defp to_apps_paths(apps, apps_path) do
for app <- apps,
path = path_with_mix_exs_otherwise_warn(app, apps_path),
do: {app, path},
into: %{}
end
defp path_with_mix_exs_otherwise_warn(app, apps_path) do
path = Path.join(apps_path, Atom.to_string(app))
cond do
File.regular?(Path.join(path, "mix.exs")) ->
path
File.dir?(path) ->
Mix.shell().error(
"warning: path #{inspect(Path.relative_to_cwd(path))} is a directory but " <>
"it has no mix.exs. Mix won't consider this directory as part of your " <>
"umbrella application. Please add a \"mix.exs\" or set the \":apps\" key " <>
"in your umbrella configuration with all relevant apps names as atoms"
)
nil
true ->
# If it is a stray file, we just ignore it.
nil
end
end
@doc ~S"""
Runs the given `fun` inside the given project.
This function changes the current working directory and
loads the project at the given directory onto the project
stack.
A `post_config` can be passed that will be merged into
the project configuration.
`fun` is called with the module name of the given `Mix.Project`.
The return value of this function is the return value of `fun`.
## Examples
Mix.Project.in_project(:my_app, "/path/to/my_app", fn module ->
"Mix project is: #{inspect module}"
end)
#=> "Mix project is: MyApp.MixProject"
"""
@spec in_project(atom, Path.t(), keyword, (module -> result)) :: result when result: term
def in_project(app, path, post_config \\ [], fun)
def in_project(app, ".", post_config, fun) when is_atom(app) do
cached =
try do
load_project(app, post_config)
rescue
any ->
Mix.shell().error("Error while loading project #{inspect(app)} at #{File.cwd!()}")
reraise any, __STACKTRACE__
end
try do
fun.(cached)
after
Mix.Project.pop()
end
end
def in_project(app, path, post_config, fun) when is_atom(app) do
File.cd!(path, fn ->
in_project(app, ".", post_config, fun)
end)
end
@doc """
Returns the path where dependencies are stored for the given project.
If no configuration is given, the one for the current project is used.
The returned path will be expanded.
## Examples
Mix.Project.deps_path()
#=> "/path/to/project/deps"
"""
@spec deps_path(keyword) :: Path.t()
def deps_path(config \\ config()) do
Path.expand(config[:deps_path])
end
@doc """
Returns the full path of all dependencies as a map.
## Options
* `:depth` - only return dependencies to the depth level,
a depth of 1 will only return top-level dependencies
* `:parents` - starts the dependency traversal from the
given parents instead of the application root
## Examples
Mix.Project.deps_paths()
#=> %{foo: "deps/foo", bar: "custom/path/dep"}
"""
@spec deps_paths(keyword) :: %{optional(atom) => Path.t()}
def deps_paths(opts \\ []) do
all_deps = Mix.Dep.cached()
parents = opts[:parents]
depth = opts[:depth]
if parents || depth do
parent_filter = if parents, do: &(&1.app in parents), else: & &1.top_level
all_deps
|> Enum.filter(parent_filter)
|> deps_to_paths_map()
|> deps_paths_depth(all_deps, 1, depth || :infinity)
else
deps_to_paths_map(all_deps)
end
end
defp deps_to_paths_map(deps) do
for %{app: app, opts: opts} <- deps,
do: {app, opts[:dest]},
into: %{}
end
defp deps_paths_depth(deps, _all_deps, depth, depth) do
deps
end
defp deps_paths_depth(parents, all_deps, depth, target_depth) do
children =
for parent_dep <- all_deps,
Map.has_key?(parents, parent_dep.app),
%{app: app, opts: opts} <- parent_dep.deps,
do: {app, opts[:dest]},
into: %{}
case Map.merge(parents, children) do
^parents -> parents
new_parents -> deps_paths_depth(new_parents, all_deps, depth + 1, target_depth)
end
end
@doc """
Clears the dependency for the current environment.
Useful when dependencies need to be reloaded due to change of global state.
"""
@doc since: "1.7.0"
@spec clear_deps_cache() :: :ok
def clear_deps_cache() do
Mix.Dep.clear_cached()
:ok
end
@doc """
Returns the build path for the given project.
If no configuration is given, the one for the current project is used.
The returned path will be expanded.
## Examples
Mix.Project.build_path()
#=> "/path/to/project/_build/shared"
If `:build_per_environment` is set to `true`, it will create a new build per
environment:
Mix.env()
#=> :dev
Mix.Project.build_path()
#=> "/path/to/project/_build/dev"
"""
@spec build_path(keyword) :: Path.t()
def build_path(config \\ config()) do
System.get_env("MIX_BUILD_PATH") || config[:env_path] || env_path(config)
end
defp env_path(config) do
dir = config[:build_path] || "_build"
subdir = build_target() <> build_per_environment(config)
Path.expand(dir <> "/" <> subdir)
end
defp build_target do
case Mix.target() do
:host -> ""
other -> "#{other}_"
end
end
defp build_per_environment(config) do
case config[:build_per_environment] do
true ->
Atom.to_string(Mix.env())
false ->
"shared"
other ->
Mix.raise("The :build_per_environment option should be a boolean, got: #{inspect(other)}")
end
end
@doc """
Returns the path where manifests are stored.
By default they are stored in the app path inside
the build directory. Umbrella applications have
the manifest path set to the root of the build directory.
Directories may be changed in future releases.
The returned path will be expanded.
## Examples
Mix.Project.manifest_path()
#=> "/path/to/project/_build/shared/lib/app/.mix"
"""
@spec manifest_path(keyword) :: Path.t()
def manifest_path(config \\ config()) do
app_path =
config[:app_path] ||
if app = config[:app] do
Path.join([build_path(config), "lib", Atom.to_string(app)])
else
build_path(config)
end
Path.join(app_path, ".mix")
end
@doc """
Returns the application path inside the build.
The returned path will be expanded.
## Examples
Mix.Project.app_path()
#=> "/path/to/project/_build/shared/lib/app"
"""
@spec app_path(keyword) :: Path.t()
def app_path(config \\ config()) do
config[:app_path] ||
cond do
app = config[:app] ->
Path.join([build_path(config), "lib", Atom.to_string(app)])
config[:apps_path] ->
raise "trying to access Mix.Project.app_path for an umbrella project but umbrellas have no app"
true ->
Mix.raise(
"Cannot access build without an application name, " <>
"please ensure you are in a directory with a mix.exs file and it defines " <>
"an :app name under the project configuration"
)
end
end
@doc """
Returns the paths the given project compiles to.
If no configuration is given, the one for the current project will be used.
The returned path will be expanded.
## Examples
Mix.Project.compile_path()
#=> "/path/to/project/_build/dev/lib/app/ebin"
"""
@spec compile_path(keyword) :: Path.t()
def compile_path(config \\ config()) do
Path.join(app_path(config), "ebin")
end
@doc """
Returns the path where protocol consolidations are stored.
The returned path will be expanded.
## Examples
Mix.Project.consolidation_path()
#=> "/path/to/project/_build/dev/lib/my_app/consolidated"
Inside umbrellas:
Mix.Project.consolidation_path()
#=> "/path/to/project/_build/dev/consolidated"
"""
def consolidation_path(config \\ config()) do
if umbrella?(config) do
Path.join(build_path(config), "consolidated")
else
Path.join(app_path(config), "consolidated")
end
end
@doc """
Compiles the given project.
"""
@spec compile([term], keyword) :: term
def compile(args, _config \\ []) do
Mix.Task.run("compile", args)
end
@doc """
Builds the project structure for the given application.
## Options
* `:symlink_ebin` - symlink ebin instead of copying it
"""
@spec build_structure(keyword, keyword) :: :ok
def build_structure(config \\ config(), opts \\ []) do
app = app_path(config)
File.mkdir_p!(app)
source = Path.expand("ebin")
target = Path.join(app, "ebin")
_ =
cond do
opts[:symlink_ebin] ->
_ = symlink_or_copy(config, source, target)
match?({:ok, _}, :file.read_link(target)) ->
_ = File.rm_rf!(target)
File.mkdir_p!(target)
true ->
File.mkdir_p!(target)
end
_ = symlink_or_copy(config, Path.expand("include"), Path.join(app, "include"))
_ = symlink_or_copy(config, Path.expand("priv"), Path.join(app, "priv"))
:ok
end
defp symlink_or_copy(config, source, target) do
if config[:build_embedded] do
if File.exists?(source) do
File.rm_rf!(target)
File.cp_r!(source, target)
end
else
Mix.Utils.symlink_or_copy(source, target)
end
end
@doc """
Ensures the project structure for the given project exists.
In case it does exist, it is a no-op. Otherwise, it is built.
"""
@spec ensure_structure(keyword, keyword) :: :ok
def ensure_structure(config \\ config(), opts \\ []) do
if File.exists?(app_path(config)) do
:ok
else
build_structure(config, opts)
end
end
@deprecated "Use Mix.Project.compile_path/1 instead"
def load_paths(config \\ config()) do
if umbrella?(config) do
[]
else
[compile_path(config)]
end
end
# Loads mix.exs in the current directory or loads the project from the
# mixfile cache and pushes the project onto the project stack.
defp load_project(app, post_config) do
Mix.ProjectStack.post_config(post_config)
if cached = Mix.ProjectStack.read_cache({:app, app}) do
{project, file} = cached
push(project, file, app)
project
else
file = Path.expand("mix.exs")
old_proj = get()
{new_proj, file} =
if File.regular?(file) do
try do
Code.compiler_options(relative_paths: false)
_ = Code.compile_file(file)
get()
else
^old_proj -> Mix.raise("Could not find a Mix project at #{file}")
new_proj -> {new_proj, file}
after
Code.compiler_options(relative_paths: true)
end
else
push(nil, file, app)
{nil, "nofile"}
end
Mix.ProjectStack.write_cache({:app, app}, {new_proj, file})
new_proj
end
end
defp default_config do
[
aliases: [],
build_embedded: false,
build_per_environment: true,
build_scm: Mix.SCM.Path,
config_path: "config/config.exs",
consolidate_protocols: true,
default_task: "run",
deps: [],
deps_path: "deps",
elixirc_paths: ["lib"],
erlc_paths: ["src"],
erlc_include_path: "include",
erlc_options: [:debug_info],
lockfile: "mix.lock",
preferred_cli_env: [],
start_permanent: false
]
end
@private_config [:app_path, :build_scm, :env_path]
defp get_project_config(nil), do: []
defp get_project_config(atom), do: atom.project |> Keyword.drop(@private_config)
end
| 28.523745 | 105 | 0.65089 |
1c3d31ba496876b190ee6af721965ca54d887dd5 | 1,698 | exs | Elixir | installer/templates/phx_umbrella/apps/app_name_web/config/dev.exs | grigor-aramyan/phoenix | d377b2e8d90753f9ec02972532e20f6878da86ad | [
"MIT"
] | null | null | null | installer/templates/phx_umbrella/apps/app_name_web/config/dev.exs | grigor-aramyan/phoenix | d377b2e8d90753f9ec02972532e20f6878da86ad | [
"MIT"
] | null | null | null | installer/templates/phx_umbrella/apps/app_name_web/config/dev.exs | grigor-aramyan/phoenix | d377b2e8d90753f9ec02972532e20f6878da86ad | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :<%= web_app_name %>, <%= endpoint_module %>,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: <%= if webpack do %>[node: ["node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin",
cd: Path.expand("../assets", __DIR__)]]<% else %>[]<% end %>
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
<%= if html do %># Watch static and templates for browser reloading.
config :<%= web_app_name %>, <%= endpoint_module %>,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/<%= web_app_name %>/views/.*(ex)$},
~r{lib/<%= web_app_name %>/templates/.*(eex)$}
]
]
<% end %>
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 35.375 | 170 | 0.659011 |
1c3d33fd83a28a37ae1567760ea69476b5bfae23 | 2,683 | exs | Elixir | test/phoenix/live_dashboard/pages/request_logger_page_test.exs | uumo/phoenix_live_dashboard | cd07929341d9dca0f85b58c624c62d63cf7c2f07 | [
"MIT"
] | 1 | 2020-11-04T16:17:32.000Z | 2020-11-04T16:17:32.000Z | test/phoenix/live_dashboard/pages/request_logger_page_test.exs | uumo/phoenix_live_dashboard | cd07929341d9dca0f85b58c624c62d63cf7c2f07 | [
"MIT"
] | null | null | null | test/phoenix/live_dashboard/pages/request_logger_page_test.exs | uumo/phoenix_live_dashboard | cd07929341d9dca0f85b58c624c62d63cf7c2f07 | [
"MIT"
] | 1 | 2020-11-16T14:01:08.000Z | 2020-11-16T14:01:08.000Z | defmodule Phoenix.LiveDashboard.RequestLoggerPageTest do
use ExUnit.Case, async: true
require Logger
import Phoenix.ConnTest
import Phoenix.LiveViewTest
alias Phoenix.LiveDashboard.RequestLogger
alias Phoenix.LiveDashboardTest.PubSub
@endpoint Phoenix.LiveDashboardTest.Endpoint
test "menu_link/2" do
assert :skip =
Phoenix.LiveDashboard.RequestLoggerPage.menu_link(%{}, %{dashboard_running?: false})
link = "https://hexdocs.pm/phoenix_live_dashboard/request_logger.html"
assert {:disabled, "Request Logger", ^link} =
Phoenix.LiveDashboard.RequestLoggerPage.menu_link(
%{"request_logger" => nil},
%{dashboard: true}
)
assert {:ok, "Request Logger"} =
Phoenix.LiveDashboard.RequestLoggerPage.menu_link(
%{"request_logger" => {"param", "cookie"}},
%{dashboard: true}
)
end
test "redirects to stream" do
{:error, {:live_redirect, %{to: "/dashboard/request_logger?stream=" <> _}}} =
live(build_conn(), "/dashboard/request_logger")
end
test "redirects to stream keeping host" do
{:error, {:live_redirect, %{to: "/dashboard/nonode%40nohost/request_logger?stream=" <> _}}} =
live(build_conn(), "/dashboard/nonode@nohost/request_logger")
end
@tag :capture_log
test "receives log messages on stream" do
{:ok, live, _} = live(build_conn(), "/dashboard/request_logger?stream=sample")
assert render(live) =~ "request_logger_param_key="
assert render(live) =~ "Enable cookie"
Logger.error("hello world", logger_pubsub_backend: {PubSub, RequestLogger.topic("sample")})
Logger.flush()
# Guarantees the message above has been processed
_ = render(live)
# Guarantees the stream has arrived
assert render(live) =~ ~s|[error] hello world\n</pre>|
end
test "does not include cookie domain by default" do
{:ok, live, _} = live(build_conn(), "/dashboard/request_logger?stream=sample")
refute render(live) =~ "data-cookie-domain"
end
test "includes cookie domain when configured" do
{:ok, live, _} = live(build_conn(), "/config/nonode@nohost/request_logger?stream=sample")
assert render(live) =~ "data-cookie-domain=\"my.domain\""
end
test "includes cookie domain from parent" do
url = "/parent_cookie_domain/nonode@nohost/request_logger?stream=sample"
{:ok, live, _} = live(%{build_conn() | host: "localhost"}, url)
assert render(live) =~ "data-cookie-domain=\"localhost\""
{:ok, live, _} = live(%{build_conn() | host: "foo.example.com"}, url)
assert render(live) =~ "data-cookie-domain=\"example.com\""
end
end
| 35.302632 | 97 | 0.668654 |
1c3d41557910766bd5e3bc56a51c811f307e138d | 313 | ex | Elixir | lib/stranger/notification/supervisor.ex | cazrin/stranger | 887dfe52c8b934cf6fd0d598d64c3735da96d4e1 | [
"MIT"
] | 50 | 2016-01-24T11:45:47.000Z | 2016-08-26T20:20:20.000Z | lib/stranger/notification/supervisor.ex | dnlgrv/stranger | 887dfe52c8b934cf6fd0d598d64c3735da96d4e1 | [
"MIT"
] | 1 | 2016-01-24T20:21:19.000Z | 2016-01-28T11:26:10.000Z | lib/stranger/notification/supervisor.ex | dnlgrv/stranger | 887dfe52c8b934cf6fd0d598d64c3735da96d4e1 | [
"MIT"
] | 3 | 2017-03-17T12:46:09.000Z | 2021-01-14T19:41:01.000Z | defmodule Stranger.Notification.Supervisor do
@moduledoc false
use Supervisor
def start_link do
Supervisor.start_link(__MODULE__, :ok, name: __MODULE__)
end
def init(:ok) do
children = [
worker(Stranger.Notification, [])
]
supervise(children, strategy: :one_for_one)
end
end
| 17.388889 | 60 | 0.699681 |
1c3d5f359420823c59b0052374a1bd866fce1247 | 2,047 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/audience_segment_group.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/audience_segment_group.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/audience_segment_group.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Model.AudienceSegmentGroup do
@moduledoc """
Audience Segment Group.
## Attributes
* `audienceSegments` (*type:* `list(GoogleApi.DFAReporting.V34.Model.AudienceSegment.t)`, *default:* `nil`) - Audience segments assigned to this group. The number of segments must be between 2 and 100.
* `id` (*type:* `String.t`, *default:* `nil`) - ID of this audience segment group. This is a read-only, auto-generated field.
* `name` (*type:* `String.t`, *default:* `nil`) - Name of this audience segment group. This is a required field and must be less than 65 characters long.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:audienceSegments => list(GoogleApi.DFAReporting.V34.Model.AudienceSegment.t()),
:id => String.t(),
:name => String.t()
}
field(:audienceSegments, as: GoogleApi.DFAReporting.V34.Model.AudienceSegment, type: :list)
field(:id)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.AudienceSegmentGroup do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.AudienceSegmentGroup.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.AudienceSegmentGroup do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.622642 | 205 | 0.730337 |
1c3d63744182dce6c7864d5e906dda1db6938922 | 67 | exs | Elixir | dummy/test/test_helper.exs | zgohr/turbo_ecto | 2467be3f0923193349c08d18061efbc952523b21 | [
"MIT"
] | 4 | 2019-01-23T14:10:31.000Z | 2019-05-14T15:41:11.000Z | dummy/test/test_helper.exs | zgohr/turbo_ecto | 2467be3f0923193349c08d18061efbc952523b21 | [
"MIT"
] | 35 | 2019-02-19T02:11:33.000Z | 2021-09-01T07:09:42.000Z | dummy/test/test_helper.exs | zgohr/turbo_ecto | 2467be3f0923193349c08d18061efbc952523b21 | [
"MIT"
] | 4 | 2019-11-03T16:11:39.000Z | 2022-03-05T14:34:23.000Z | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Dummy.Repo, :manual)
| 22.333333 | 51 | 0.776119 |
1c3d99a8b3778b2e8e484dfd7bedf734a357c760 | 200 | ex | Elixir | firmware/lib/firmware.ex | Jwsonic/cliff_swallow | 6ea69bcb10a844e10dd002a309eb4f48d0f0d1b8 | [
"MIT"
] | 25 | 2018-11-03T19:36:12.000Z | 2021-11-17T13:09:06.000Z | firmware/lib/firmware.ex | Jwsonic/cliff_swallow | 6ea69bcb10a844e10dd002a309eb4f48d0f0d1b8 | [
"MIT"
] | 4 | 2019-01-16T14:06:47.000Z | 2021-09-01T18:59:02.000Z | firmware/lib/firmware.ex | Jwsonic/cliff_swallow | 6ea69bcb10a844e10dd002a309eb4f48d0f0d1b8 | [
"MIT"
] | 8 | 2018-12-25T23:00:51.000Z | 2020-12-22T15:10:21.000Z | defmodule Firmware do
@moduledoc """
Documentation for Firmware.
"""
@doc """
Hello world.
## Examples
iex> Firmware.hello
:world
"""
def hello do
:world
end
end
| 10.526316 | 29 | 0.575 |
1c3da1d198f80ee5b31be18c7a9b85d62d2d2cfd | 2,482 | ex | Elixir | apps/tai/lib/tai/venue_adapters/binance/create_order.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/venue_adapters/binance/create_order.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | 78 | 2020-10-12T06:21:43.000Z | 2022-03-28T09:02:00.000Z | apps/tai/lib/tai/venue_adapters/binance/create_order.ex | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | null | null | null | defmodule Tai.VenueAdapters.Binance.CreateOrder do
@moduledoc """
Create orders for the Binance adapter
"""
alias Tai.VenueAdapters.Binance.OrderStatus
alias Tai.Orders
@limit "LIMIT"
def create_order(%Tai.Orders.Order{side: side, type: :limit} = order, credentials) do
venue_time_in_force = order.time_in_force |> to_venue_time_in_force
venue_side = side |> Atom.to_string() |> String.upcase()
credentials = struct!(ExBinance.Credentials, credentials)
%ExBinance.Rest.Requests.CreateOrderRequest{
new_client_order_id: order.client_id,
symbol: order.venue_product_symbol,
side: venue_side,
type: @limit,
quantity: order.qty,
quote_order_qty: order.qty,
price: order.price,
time_in_force: venue_time_in_force
}
|> ExBinance.Private.create_order(credentials)
|> parse_response(order)
end
defp to_venue_time_in_force(:gtc), do: "GTC"
defp to_venue_time_in_force(:fok), do: "FOK"
defp to_venue_time_in_force(:ioc), do: "IOC"
defp parse_response({:ok, %ExBinance.Rest.Responses.CreateOrderResponse{} = binance_response}, _) do
received_at = Tai.Time.monotonic_time()
venue_order_id = binance_response.order_id |> Integer.to_string()
status = binance_response.status |> OrderStatus.from_venue()
original_size = binance_response.orig_qty |> Decimal.new() |> Decimal.normalize()
cumulative_qty = binance_response.executed_qty |> Decimal.new() |> Decimal.normalize()
leaves_qty = calc_leaves_qty(status, original_size, cumulative_qty)
venue_timestamp = binance_response.transact_time |> DateTime.from_unix!(:millisecond)
response = %Orders.Responses.Create{
id: venue_order_id,
status: status,
original_size: original_size,
leaves_qty: leaves_qty,
cumulative_qty: cumulative_qty,
venue_timestamp: venue_timestamp,
received_at: received_at
}
{:ok, response}
end
defp parse_response({:error, :timeout} = error, _), do: error
defp parse_response({:error, :connect_timeout} = error, _), do: error
defp parse_response({:error, {:insufficient_balance, _}}, _),
do: {:error, :insufficient_balance}
defp parse_response({:error, reason}, _), do: {:error, {:unhandled, reason}}
defp calc_leaves_qty(:filled, _, _), do: Decimal.new(0)
defp calc_leaves_qty(:expired, _, _), do: Decimal.new(0)
defp calc_leaves_qty(:open, orig_qty, cum_qty), do: orig_qty |> Decimal.sub(cum_qty)
end
| 36.5 | 102 | 0.714343 |
1c3dac6090d0da699b2937fe0eb418b695e7f9cc | 1,004 | exs | Elixir | mix.exs | davejlong/logger_2k17 | 923e9b673dc201b61f287590ac97452a4c17d014 | [
"MIT"
] | 1 | 2017-03-10T06:59:47.000Z | 2017-03-10T06:59:47.000Z | mix.exs | davejlong/logger_2k17 | 923e9b673dc201b61f287590ac97452a4c17d014 | [
"MIT"
] | null | null | null | mix.exs | davejlong/logger_2k17 | 923e9b673dc201b61f287590ac97452a4c17d014 | [
"MIT"
] | null | null | null | defmodule Logger2k17.Mixfile do
use Mix.Project
def project do
[app: :logger_2k17,
version: "0.1.0",
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps(),
description: description(),
package: package()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
# Specify extra applications you'll use from Erlang/Elixir
[extra_applications: [:logger]]
end
defp deps do
[]
end
defp description do
"""
Finally a logger module for 2k17. Replaces Logger with a new and fresh
module with meaningful methods like `fyi` and `omg` instead of `info` and
`error`.
"""
end
defp package do
[name: :logger_2k17,
files: ["lib", "mix.exs", "*.md", "LICENSE.txt"],
maintainers: ["Dave Long"],
licenses: ["MIT"],
links: %{github: "https://github.com/davejlong/logger_2k17"}
]
end
end
| 22.818182 | 77 | 0.62749 |
1c3db14527540ace6d82a1411f4116a11864f269 | 1,123 | exs | Elixir | elixir/set1/challenge4/config/config.exs | sdball/matasano-crypto-challenges | c539a605b4f709c7c202216ecedd7355e6b4a1b9 | [
"MIT"
] | null | null | null | elixir/set1/challenge4/config/config.exs | sdball/matasano-crypto-challenges | c539a605b4f709c7c202216ecedd7355e6b4a1b9 | [
"MIT"
] | null | null | null | elixir/set1/challenge4/config/config.exs | sdball/matasano-crypto-challenges | c539a605b4f709c7c202216ecedd7355e6b4a1b9 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :challenge4, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:challenge4, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.225806 | 73 | 0.752449 |
1c3e12a499f46b65d4d8672966b80da8f37c9a53 | 5,483 | exs | Elixir | test/actions/load_test.exs | MrFlorius/ash | 247abbb8333d252da5440a58ddf4f1b7f184342f | [
"MIT"
] | null | null | null | test/actions/load_test.exs | MrFlorius/ash | 247abbb8333d252da5440a58ddf4f1b7f184342f | [
"MIT"
] | null | null | null | test/actions/load_test.exs | MrFlorius/ash | 247abbb8333d252da5440a58ddf4f1b7f184342f | [
"MIT"
] | null | null | null | defmodule Ash.Test.Actions.LoadTest do
@moduledoc false
use ExUnit.Case, async: false
import Ash.Changeset
require Ash.Query
defmodule Author do
@moduledoc false
use Ash.Resource,
data_layer: Ash.DataLayer.Ets,
authorizers: [
Ash.Test.Authorizer
]
ets do
private?(true)
end
actions do
read :read
create :create
end
attributes do
uuid_primary_key :id
attribute :name, :string
end
relationships do
has_many :posts, Ash.Test.Actions.LoadTest.Post, destination_field: :author_id
has_one :latest_post, Ash.Test.Actions.LoadTest.Post,
destination_field: :author_id,
sort: [inserted_at: :desc]
end
end
defmodule Post do
@moduledoc false
use Ash.Resource, data_layer: Ash.DataLayer.Ets
ets do
private?(true)
end
actions do
read :read
create :create
end
attributes do
uuid_primary_key :id
attribute :title, :string
attribute :contents, :string
timestamps()
end
relationships do
belongs_to :author, Author
many_to_many :categories, Ash.Test.Actions.LoadTest.Category,
through: Ash.Test.Actions.LoadTest.PostCategory,
destination_field_on_join_table: :category_id,
source_field_on_join_table: :post_id
end
end
defmodule PostCategory do
@moduledoc false
use Ash.Resource, data_layer: Ash.DataLayer.Ets
ets do
private?(true)
end
actions do
read :read
create :create
end
relationships do
belongs_to :post, Post, primary_key?: true, required?: true
belongs_to :category, Ash.Test.Actions.LoadTest.Category,
primary_key?: true,
required?: true
end
end
defmodule Category do
@moduledoc false
use Ash.Resource, data_layer: Ash.DataLayer.Ets
ets do
private?(true)
end
actions do
read :read
create :create
end
attributes do
uuid_primary_key :id
attribute :name, :string
end
relationships do
many_to_many :posts, Post,
through: PostCategory,
destination_field_on_join_table: :post_id,
source_field_on_join_table: :category_id
end
end
defmodule Api do
@moduledoc false
use Ash.Api
resources do
resource(Author)
resource(Post)
resource(Category)
resource(PostCategory)
end
end
setup do
start_supervised(
{Ash.Test.Authorizer,
strict_check: :authorized,
check: {:error, Ash.Error.Forbidden.exception([])},
strict_check_context: [:query]}
)
:ok
end
describe "loads" do
test "it allows loading related data" do
author =
Author
|> new(%{name: "zerg"})
|> Api.create!()
post1 =
Post
|> new(%{title: "post1"})
|> replace_relationship(:author, author)
|> Api.create!()
post2 =
Post
|> new(%{title: "post2"})
|> replace_relationship(:author, author)
|> Api.create!()
[author] =
Author
|> Ash.Query.load(posts: [:author])
|> Ash.Query.filter(posts.id == ^post1.id)
|> Api.read!(authorize?: true)
assert Enum.sort(Enum.map(author.posts, &Map.get(&1, :id))) ==
Enum.sort([post1.id, post2.id])
for post <- author.posts do
assert post.author.id == author.id
end
end
test "it allows loading many to many relationships" do
category1 =
Category
|> new(%{name: "lame"})
|> Api.create!()
category2 =
Category
|> new(%{name: "cool"})
|> Api.create!()
post =
Post
|> new(%{title: "post1"})
|> replace_relationship(:categories, [category1, category2])
|> Api.create!()
[post] =
Post
|> Ash.Query.load(:categories)
|> Ash.Query.filter(id == ^post.id)
|> Api.read!(authorize?: true)
assert [%{id: id1}, %{id: id2}] = post.categories
assert Enum.sort([category1.id, category2.id]) == Enum.sort([id1, id2])
end
test "it allows loading nested many to many relationships" do
category1 =
Category
|> new(%{name: "lame"})
|> Api.create!()
category2 =
Category
|> new(%{name: "cool"})
|> Api.create!()
post =
Post
|> new(%{title: "post1"})
|> replace_relationship(:categories, [category1, category2])
|> Api.create!()
[post] =
Post
|> Ash.Query.load(categories: :posts)
|> Ash.Query.filter(id == ^post.id)
|> Api.read!(authorize?: true)
post_id = post.id
assert [%{posts: [%{id: ^post_id}]}, %{posts: [%{id: ^post_id}]}] = post.categories
end
test "it loads sorted relationships in the proper order" do
author =
Author
|> new(%{name: "zerg"})
|> Api.create!()
_post1 =
Post
|> new(%{title: "post1"})
|> replace_relationship(:author, author)
|> Api.create!()
:timer.sleep(2)
post2 =
Post
|> new(%{title: "post2"})
|> replace_relationship(:author, author)
|> Api.create!()
[author] =
Author
|> Ash.Query.load(:latest_post)
|> Api.read!()
assert author.latest_post.id == post2.id
end
end
end
| 21.251938 | 89 | 0.568302 |
1c3e1451ad74917fb000ef36015ab1fae9786c4f | 1,962 | exs | Elixir | examples/example-phx-1_3/config/dev.exs | devshane/thesis-phoenix | afe22a25542f91e15cfffb1e93ff8d833a64c25b | [
"MIT"
] | 681 | 2016-06-21T20:49:21.000Z | 2022-02-19T04:08:38.000Z | examples/example-phx-1_3/config/dev.exs | devshane/thesis-phoenix | afe22a25542f91e15cfffb1e93ff8d833a64c25b | [
"MIT"
] | 125 | 2016-06-21T21:14:49.000Z | 2020-12-12T20:15:48.000Z | examples/example-phx-1_3/config/dev.exs | devshane/thesis-phoenix | afe22a25542f91e15cfffb1e93ff8d833a64c25b | [
"MIT"
] | 76 | 2016-09-06T03:40:55.000Z | 2022-01-20T21:29:22.000Z | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :example_phx, ExamplePhxWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
cd: Path.expand("../assets", __DIR__)]]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :example_phx, ExamplePhxWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/example_phx_web/views/.*(ex)$},
~r{lib/example_phx_web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :example_phx, ExamplePhx.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "example_phx_dev",
hostname: "localhost",
pool_size: 10
| 33.254237 | 170 | 0.707951 |
1c3e35f502b4e5df9de4975da30516354c5fc898 | 2,727 | ex | Elixir | lib/thin_notion_api/databases.ex | CodingZeal/thin_notion_api | e1f4081348300ab6c48adae8ebb4b2995cde59d1 | [
"MIT"
] | 1 | 2022-01-15T00:50:09.000Z | 2022-01-15T00:50:09.000Z | lib/thin_notion_api/databases.ex | CodingZeal/thin_notion_api | e1f4081348300ab6c48adae8ebb4b2995cde59d1 | [
"MIT"
] | null | null | null | lib/thin_notion_api/databases.ex | CodingZeal/thin_notion_api | e1f4081348300ab6c48adae8ebb4b2995cde59d1 | [
"MIT"
] | null | null | null | defmodule ThinNotionApi.Databases do
@moduledoc """
Module for interacting with the Notion Databases.
"""
import ThinNotionApi.Base
alias ThinNotionApi.{Properties, Types}
@spec retrieve_database(String.t()) :: Types.Response.t()
@doc """
Retrieves a Database object using the ID specified.
## Examples
iex> ThinNotionApi.Databases.retrieve_database(database_id)
{:ok, %{...}}
"""
def retrieve_database(database_id) do
get("databases/" <> database_id)
end
@spec query_database(String.t(), Types.DatabaseQueryParams.t() | %{}) :: Types.Response.t()
@doc """
Gets a list of Pages contained in the database, filtered and ordered according to the filter conditions and sort criteria provided in the request. The response may contain fewer than page_size of results.
## Examples:
iex> ThinNotionApi.Databases.query_database(database_id)
{:ok, %{...}}
iex> ThinNotionApi.Databases.query_database("a4ef92b2a7984bae82114817678cd2f4", %{ "page_size" => 1})
{:ok, %{...}}
"""
def query_database(database_id, body_params \\ %{}) do
post("databases/" <> database_id <> "/query", body_params)
end
@doc """
Gets a list of Pages contained in the database, filtered and ordered according to the filter conditions and sort criteria provided in the request. The response may contain fewer than page_size of results.
## Examples:
iex> ThinNotionApi.Databases.create_database!("9b4a624d5a18482ab2187e54166edda7", "New Database")
{:ok, %{...}}
"""
@spec create_database!(String.t(), String.t(), map()) :: Types.Response.t()
def create_database!(
parent_id,
title,
properties \\ %{
Name: %{
title: %{}
}
}
) do
body_params =
%{}
|> set_parent(parent_id)
|> Properties.set_title(title)
|> Properties.set_database_properties(properties)
post("databases", body_params)
end
@spec update_database!(String.t(), String.t(), map()) :: Types.Response.t()
@doc """
Updates an existing database as specified by the parameters.
## Examples:
iex> ThinNotionApi.Databases.update_database!(database_id, "New New Database Name")
{:ok, %{...}}
"""
def update_database!(
database_id,
title,
properties \\ %{
Name: %{
title: %{}
}
}
) do
body_params =
%{}
|> Properties.set_title(title)
|> Properties.set_database_properties(properties)
patch("databases/#{database_id}", body_params)
end
defp set_parent(map, parent_id) do
Map.put(map, :parent, %{
type: "page_id",
page_id: parent_id
})
end
end
| 27.826531 | 206 | 0.636597 |
1c3e3b616b7e1db8a127c76a3a269fffa713f45f | 213 | exs | Elixir | 09-application/example.exs | Markcial/essence | fcfc62a189c2cee1f07813d583edfaec2fb0167e | [
"MIT"
] | 2 | 2017-02-14T20:33:52.000Z | 2017-03-02T15:21:44.000Z | 09-application/example.exs | Markcial/essence | fcfc62a189c2cee1f07813d583edfaec2fb0167e | [
"MIT"
] | null | null | null | 09-application/example.exs | Markcial/essence | fcfc62a189c2cee1f07813d583edfaec2fb0167e | [
"MIT"
] | 1 | 2018-06-22T02:34:15.000Z | 2018-06-22T02:34:15.000Z |
Tasker.Client.add(fn -> File.ls(".") end)
{:ok, files} = Tasker.Client.run :first
IO.inspect files
Tasker.Client.add(fn -> IO.puts "first" end)
IO.inspect Tasker.Client.list
IO.inspect Tasker.Client.run :first
| 21.3 | 44 | 0.713615 |
1c3e47eb3ed5e6e598c9393d26834c7fe23743bb | 346 | exs | Elixir | peep_blog_api/priv/repo/seeds.exs | ultimatemonty/embloginator | b1b25374d56899e054e6df73a3841d388d095d83 | [
"MIT"
] | null | null | null | peep_blog_api/priv/repo/seeds.exs | ultimatemonty/embloginator | b1b25374d56899e054e6df73a3841d388d095d83 | [
"MIT"
] | null | null | null | peep_blog_api/priv/repo/seeds.exs | ultimatemonty/embloginator | b1b25374d56899e054e6df73a3841d388d095d83 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# PeepBlogApi.Repo.insert!(%SomeModel{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 28.833333 | 61 | 0.705202 |
1c3e4e80f06952188516d9ee13b7d01505e600e7 | 1,690 | ex | Elixir | clients/analytics/lib/google_api/analytics/v3/model/mcf_data_rows_conversion_path_value.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/analytics/lib/google_api/analytics/v3/model/mcf_data_rows_conversion_path_value.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/analytics/lib/google_api/analytics/v3/model/mcf_data_rows_conversion_path_value.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.Analytics.V3.Model.McfDataRowsConversionPathValue do
@moduledoc """
## Attributes
* `interactionType` (*type:* `String.t`, *default:* `nil`) - Type of an interaction on conversion path. Such as CLICK, IMPRESSION etc.
* `nodeValue` (*type:* `String.t`, *default:* `nil`) - Node value of an interaction on conversion path. Such as source, medium etc.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:interactionType => String.t() | nil,
:nodeValue => String.t() | nil
}
field(:interactionType)
field(:nodeValue)
end
defimpl Poison.Decoder, for: GoogleApi.Analytics.V3.Model.McfDataRowsConversionPathValue do
def decode(value, options) do
GoogleApi.Analytics.V3.Model.McfDataRowsConversionPathValue.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Analytics.V3.Model.McfDataRowsConversionPathValue do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.8 | 138 | 0.734911 |
1c3e58c38b4d9f2265d0ee02abd53a1007bb51be | 2,408 | ex | Elixir | lib/envio/backends/slack.ex | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | 12 | 2018-07-25T08:38:05.000Z | 2020-05-16T07:29:11.000Z | lib/envio/backends/slack.ex | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | 6 | 2018-07-26T17:09:44.000Z | 2021-10-19T06:39:44.000Z | lib/envio/backends/slack.ex | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | null | null | null | defmodule Envio.Slack do
@moduledoc false
alias Envio.Utils
@behaviour Envio.Backend
@spec format(%{required(:atom) => term()}) :: binary()
defp format(%{} = message) do
with {title, message} <- Map.pop(message, :title),
{text, message} <- Map.pop(message, :text),
{body, message} <- Map.pop(message, :message),
{level, message} <- Map.pop(message, :level, :info),
{icon, message} <- Map.pop(message, :icon, slack_icon(level)) do
fields =
message
|> Iteraptor.to_flatmap()
|> Enum.map(fn {k, v} ->
v = Utils.smart_to_binary(v)
%{
title: k,
value: v,
short: String.length(v) < 32
}
end)
pretext = [text, body] |> Enum.reject(&is_nil/1) |> Enum.join("\n")
attachments =
%{
color: slack_color(level),
fields: fields,
mrkdwn_in: ["title", "text", "pretext"]
}
|> Map.merge(if text || body, do: %{pretext: "```\n" <> pretext <> "\n```"}, else: %{})
fallback =
[title, text, body]
|> Enum.reject(&is_nil/1)
|> Enum.map(&Utils.smart_to_binary/1)
|> Enum.join("\n")
%{
emoji_icon: icon,
fallback: fallback,
mrkdwn: true,
attachments: [attachments]
}
|> Map.merge(if title, do: %{description: title}, else: %{})
|> Jason.encode!()
end
end
@impl Envio.Backend
def on_envio(%{} = message, meta) do
case meta do
%{hook_url: hook_url} ->
json =
message
|> format()
|> :erlang.binary_to_list()
:httpc.request(:post, {to_charlist(hook_url), [], 'application/json', json}, [], [])
_ ->
{:error, :no_hook_url_in_envio}
end
end
#############################################################################
defp slack_icon(:debug), do: ":speaker:"
defp slack_icon(:info), do: ":information_source:"
defp slack_icon(:warn), do: ":warning:"
defp slack_icon(:error), do: ":exclamation:"
defp slack_icon(level) when is_binary(level),
do: level |> String.to_existing_atom() |> slack_icon()
defp slack_icon(_), do: slack_icon(:info)
defp slack_color(:debug), do: "#AAAAAA"
defp slack_color(:info), do: "good"
defp slack_color(:warn), do: "#FF9900"
defp slack_color(:error), do: "danger"
end
| 27.363636 | 95 | 0.526163 |
1c3ec57e1e3e70da7e767f2e213e05e9b83702bb | 1,573 | ex | Elixir | lib/spider_man/producer/producer.ex | kianmeng/spider_man | 48941f42e901d03f7c6cc1f8aaf6f8a35d576614 | [
"Apache-2.0"
] | null | null | null | lib/spider_man/producer/producer.ex | kianmeng/spider_man | 48941f42e901d03f7c6cc1f8aaf6f8a35d576614 | [
"Apache-2.0"
] | null | null | null | lib/spider_man/producer/producer.ex | kianmeng/spider_man | 48941f42e901d03f7c6cc1f8aaf6f8a35d576614 | [
"Apache-2.0"
] | null | null | null | defmodule SpiderMan.Producer do
@moduledoc false
@type producer :: {module, keyword}
@callback producer_settings(arg :: term, options) :: {producer, options} when options: keyword
@optional_callbacks producer_settings: 2
def process_name(spider, component), do: :"#{spider}.#{Module.split(component) |> List.last()}"
def producer_status(broadway), do: call_producer(broadway, :status)
def call_producer(nil, _msg), do: :ok
def call_producer(broadway, msg) do
[producer_name] = Broadway.producer_names(broadway)
GenStage.call(producer_name, msg)
end
def prepare_for_start_producer(false), do: false
def prepare_for_start_producer(options),
do: prepare_for_start_producer(options[:producer], options)
defp prepare_for_start_producer(producer, options) when is_atom(producer) do
prepare_for_start_producer({producer, nil}, options)
end
defp prepare_for_start_producer({producer, arg}, options) when is_atom(producer) do
{producer, options} =
with {:module, _} <- Code.ensure_loaded(producer),
true <- function_exported?(producer, :producer_settings, 2) do
producer.producer_settings(arg, options)
else
{:error, _} -> raise "Producer module: #{inspect(producer)} undefined."
_ -> options
end
producer =
case Keyword.get(options, :rate_limiting) do
rate_limiting when is_list(rate_limiting) ->
[{:rate_limiting, rate_limiting} | producer]
_ ->
producer
end
Keyword.put(options, :producer, producer)
end
end
| 31.46 | 97 | 0.699301 |
1c3eddcbb1b4cc6b700afe3655447c8e0aaff310 | 2,003 | exs | Elixir | test/ecto/query/builder/group_by_test.exs | larryweya/ecto | d0d1fd43f0f97856a119184163167a7e79574923 | [
"Apache-2.0"
] | 1 | 2019-07-25T17:42:33.000Z | 2019-07-25T17:42:33.000Z | test/ecto/query/builder/group_by_test.exs | larryweya/ecto | d0d1fd43f0f97856a119184163167a7e79574923 | [
"Apache-2.0"
] | null | null | null | test/ecto/query/builder/group_by_test.exs | larryweya/ecto | d0d1fd43f0f97856a119184163167a7e79574923 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Query.Builder.GroupByTest do
use ExUnit.Case, async: true
import Ecto.Query.Builder.GroupBy
doctest Ecto.Query.Builder.GroupBy
import Ecto.Query
describe "escape" do
test "handles expressions and params" do
assert {Macro.escape(quote do [&0.y] end), {[], :acc}} ==
escape(:group_by, quote do x.y end, {[], :acc}, [x: 0], __ENV__)
assert {Macro.escape(quote do [&0.x, &1.y] end), {[], :acc}} ==
escape(:group_by, quote do [x.x, y.y] end, {[], :acc}, [x: 0, y: 1], __ENV__)
import Kernel, except: [>: 2]
assert {Macro.escape(quote do [1 > 2] end), {[], :acc}} ==
escape(:group_by, quote do 1 > 2 end, {[], :acc}, [], __ENV__)
end
test "raises on unbound variables" do
message = ~r"unbound variable `x` in query"
assert_raise Ecto.Query.CompileError, message, fn ->
escape(:group_by, quote do x.y end, {[], :acc}, [], __ENV__)
end
end
end
describe "at runtime" do
test "accepts a field or a list of fields" do
key = :title
assert group_by("q", [q], ^key).group_bys == group_by("q", [q], [q.title]).group_bys
assert group_by("q", [q], [^key]).group_bys == group_by("q", [q], [q.title]).group_bys
end
test "accepts dynamics" do
key = dynamic([p], p.title)
assert group_by("q", [q], ^key).group_bys == group_by("q", [q], [q.title]).group_bys
assert group_by("q", [q], ^[key]).group_bys == group_by("q", [q], [q.title]).group_bys
end
test "raises when no a field or a list of fields" do
message = "expected a field as an atom in `group_by`, got: `\"temp\"`"
assert_raise ArgumentError, message, fn ->
temp = "temp"
group_by("posts", [p], [^temp])
end
message = "expected a list of fields and dynamics in `group_by`, got: `\"temp\"`"
assert_raise ArgumentError, message, fn ->
temp = "temp"
group_by("posts", [p], ^temp)
end
end
end
end
| 34.534483 | 92 | 0.579131 |
1c3ee039c1346c895c036ea3a30d35a1c8db3c14 | 3,058 | ex | Elixir | clients/dns/lib/google_api/dns/v1/api/projects.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/api/projects.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/api/projects.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"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.DNS.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.DNS.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Fetch the representation of an existing Project.
## Parameters
- connection (GoogleApi.DNS.V1.Connection): Connection to server
- project (String.t): Identifies the project addressed by this request.
- 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.
- :clientOperationId (String.t): For mutating operation requests only. An optional identifier specified by the client. Must be unique for operation resources in the Operations collection.
## Returns
{:ok, %GoogleApi.DNS.V1.Model.Project{}} on success
{:error, info} on failure
"""
@spec dns_projects_get(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.DNS.V1.Model.Project.t()} | {:error, Tesla.Env.t()}
def dns_projects_get(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:clientOperationId => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}", %{
"project" => URI.encode_www_form(project)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DNS.V1.Model.Project{}])
end
end
| 40.236842 | 191 | 0.700131 |
1c3f2dfc9a80ebb18421fc7715b35d4b59d4b3d8 | 1,071 | exs | Elixir | test/http_parser/response_test.exs | minhajuddin/http_parser | c5aba3cde237bc66d9d88e1248ad052c8a488a67 | [
"MIT"
] | null | null | null | test/http_parser/response_test.exs | minhajuddin/http_parser | c5aba3cde237bc66d9d88e1248ad052c8a488a67 | [
"MIT"
] | null | null | null | test/http_parser/response_test.exs | minhajuddin/http_parser | c5aba3cde237bc66d9d88e1248ad052c8a488a67 | [
"MIT"
] | null | null | null | defmodule HttpParserTest do
use ExUnit.Case
doctest HttpParser
alias HttpParser.Response
describe "parse" do
setup do
{:ok, resp} =
Response.parse("HTTP/1.1 200 OK\r\nContent-Length: 6\r\nContent-Type: text/plain; charset=utf-8\r\nServer: Microsoft-IIS/8.0\r\nDate: Mon, 09 Oct 2017 12:59:28 GMT\r\n\r\nAwesome Danny")
{:ok, resp: resp}
end
test "parses status_code", %{resp: resp} do
assert resp.status_code == 200
end
test "parses status_text", %{resp: resp} do
assert resp.status_text == "OK"
end
test "parses http version", %{resp: resp} do
assert resp.http_version == :http1_1
end
test "parses headers", %{resp: resp} do
assert resp.headers |> Enum.sort == [
{"Content-Length", "6"},
{"Content-Type", "text/plain; charset=utf-8"},
{"Server", "Microsoft-IIS/8.0"},
{"Date", "Mon, 09 Oct 2017 12:59:28 GMT"},
] |> Enum.sort
end
test "parses body", %{resp: resp} do
assert resp.body == "Awesome Danny"
end
end
end
| 25.5 | 194 | 0.604108 |
1c3f30adfc15c72c033e7d9f7f9212187afbc559 | 2,476 | exs | Elixir | backend/test/edgehog_web/schema/mutation/create_hardware_type_test.exs | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 14 | 2021-12-02T16:31:16.000Z | 2022-03-18T17:40:44.000Z | backend/test/edgehog_web/schema/mutation/create_hardware_type_test.exs | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 77 | 2021-11-03T15:14:41.000Z | 2022-03-30T14:13:32.000Z | backend/test/edgehog_web/schema/mutation/create_hardware_type_test.exs | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 7 | 2021-11-03T10:58:37.000Z | 2022-02-28T14:00:03.000Z | #
# This file is part of Edgehog.
#
# Copyright 2021 SECO Mind Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
defmodule EdgehogWeb.Schema.Mutation.CreateHardwareTypeTest do
use EdgehogWeb.ConnCase
alias Edgehog.Devices
alias Edgehog.Devices.HardwareType
describe "createHardwareType field" do
@query """
mutation CreateHardwareType($input: CreateHardwareTypeInput!) {
createHardwareType(input: $input) {
hardwareType {
id
name
handle
partNumbers
}
}
}
"""
test "creates hardware type with valid data", %{conn: conn, api_path: api_path} do
name = "Foobar"
handle = "foobar"
part_number = "12345/X"
variables = %{
input: %{
name: name,
handle: handle,
part_numbers: [part_number]
}
}
conn = post(conn, api_path, query: @query, variables: variables)
assert %{
"data" => %{
"createHardwareType" => %{
"hardwareType" => %{
"id" => id,
"name" => ^name,
"handle" => ^handle,
"partNumbers" => [^part_number]
}
}
}
} = assert(json_response(conn, 200))
{:ok, %{type: :hardware_type, id: db_id}} =
Absinthe.Relay.Node.from_global_id(id, EdgehogWeb.Schema)
assert {:ok, %HardwareType{name: ^name, handle: ^handle}} =
Devices.fetch_hardware_type(db_id)
end
test "fails with invalid data", %{conn: conn, api_path: api_path} do
variables = %{
input: %{
name: nil,
handle: nil,
part_numbers: []
}
}
conn = post(conn, api_path, query: @query, variables: variables)
assert %{"errors" => _} = assert(json_response(conn, 200))
end
end
end
| 27.511111 | 86 | 0.577544 |
1c3f45c9813ef5ad141aa0e0d40c1c2bf932c468 | 553 | ex | Elixir | lib/radiator/task/worker_supervisor.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 92 | 2019-01-03T11:46:23.000Z | 2022-02-19T21:28:44.000Z | lib/radiator/task/worker_supervisor.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 350 | 2019-04-11T07:55:51.000Z | 2021-08-03T11:19:05.000Z | lib/radiator/task/worker_supervisor.ex | bhtabor/radiator | 39c137a18d36d6f418f9d1ffb7aa2c99011d66cf | [
"MIT"
] | 10 | 2019-04-18T12:47:27.000Z | 2022-01-25T20:49:15.000Z | defmodule Radiator.Task.WorkerSupervisor do
@moduledoc false
use DynamicSupervisor
alias Radiator.Task.TaskWorker
def start_link(opts \\ []),
do: DynamicSupervisor.start_link(__MODULE__, [], [name: __MODULE__] ++ opts)
@impl true
def init(_init_arg), do: DynamicSupervisor.init(strategy: :one_for_one)
def start_task_worker(worker_fn, title, id) do
spec = {TaskWorker, {worker_fn, title, id}}
DynamicSupervisor.start_child(
__MODULE__,
spec
)
|> IO.inspect(pretty: true, label: "start_task")
end
end
| 24.043478 | 80 | 0.705244 |
1c3f48c94e6296ff2d64b1aa26135ed10fc96828 | 12,869 | exs | Elixir | test/groupher_server/cms/article_community/meetup_test.exs | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 240 | 2018-11-06T09:36:54.000Z | 2022-02-20T07:12:36.000Z | test/groupher_server/cms/article_community/meetup_test.exs | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 363 | 2018-07-11T03:38:14.000Z | 2021-12-14T01:42:40.000Z | test/groupher_server/cms/article_community/meetup_test.exs | mydearxym/mastani_server | f24034a4a5449200165cf4a547964a0961793eab | [
"Apache-2.0"
] | 22 | 2019-01-27T11:47:56.000Z | 2021-02-28T13:17:52.000Z | defmodule GroupherServer.Test.CMS.ArticleCommunity.Meetup do
use GroupherServer.TestTools
alias Helper.ORM
alias GroupherServer.CMS
alias CMS.Model.Meetup
setup do
{:ok, user} = db_insert(:user)
{:ok, user2} = db_insert(:user)
{:ok, meetup} = db_insert(:meetup)
{:ok, community} = db_insert(:community)
{:ok, community2} = db_insert(:community)
{:ok, community3} = db_insert(:community)
meetup_attrs = mock_attrs(:meetup, %{community_id: community.id})
{:ok, ~m(user user2 community community2 community3 meetup meetup_attrs)a}
end
describe "[article mirror/move]" do
test "created meetup has origial community info", ~m(user community meetup_attrs)a do
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :original_community)
assert meetup.original_community_id == community.id
end
test "meetup can be move to other community", ~m(user community community2 meetup_attrs)a do
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
assert meetup.original_community_id == community.id
{:ok, _} = CMS.move_article(:meetup, meetup.id, community2.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: [:original_community, :communities])
assert meetup.original_community.id == community2.id
assert exist_in?(community2, meetup.communities)
end
test "tags should be clean after meetup move to other community",
~m(user community community2 meetup_attrs)a do
article_tag_attrs = mock_attrs(:article_tag)
article_tag_attrs2 = mock_attrs(:article_tag)
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, article_tag} = CMS.create_article_tag(community, :meetup, article_tag_attrs, user)
{:ok, article_tag2} = CMS.create_article_tag(community, :meetup, article_tag_attrs2, user)
{:ok, _meetup} = CMS.set_article_tag(:meetup, meetup.id, article_tag.id)
{:ok, meetup} = CMS.set_article_tag(:meetup, meetup.id, article_tag2.id)
assert meetup.article_tags |> length == 2
assert meetup.original_community_id == community.id
{:ok, _} = CMS.move_article(:meetup, meetup.id, community2.id)
{:ok, meetup} =
ORM.find(Meetup, meetup.id, preload: [:original_community, :communities, :article_tags])
assert meetup.article_tags |> length == 0
assert meetup.original_community.id == community2.id
assert exist_in?(community2, meetup.communities)
end
test "meetup move to other community with new tag",
~m(user community community2 meetup_attrs)a do
article_tag_attrs0 = mock_attrs(:article_tag)
article_tag_attrs = mock_attrs(:article_tag)
article_tag_attrs2 = mock_attrs(:article_tag)
{:ok, article_tag0} = CMS.create_article_tag(community, :meetup, article_tag_attrs0, user)
{:ok, article_tag} = CMS.create_article_tag(community2, :meetup, article_tag_attrs, user)
{:ok, article_tag2} = CMS.create_article_tag(community2, :meetup, article_tag_attrs2, user)
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, _} = CMS.set_article_tag(:meetup, meetup.id, article_tag0.id)
{:ok, _} = CMS.set_article_tag(:meetup, meetup.id, article_tag.id)
{:ok, _} = CMS.set_article_tag(:meetup, meetup.id, article_tag2.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: [:article_tags])
assert meetup.article_tags |> length == 3
{:ok, _} =
CMS.move_article(:meetup, meetup.id, community2.id, [article_tag.id, article_tag2.id])
{:ok, meetup} =
ORM.find(Meetup, meetup.id, preload: [:original_community, :communities, :article_tags])
assert meetup.original_community.id == community2.id
assert meetup.article_tags |> length == 2
assert not exist_in?(article_tag0, meetup.article_tags)
assert exist_in?(article_tag, meetup.article_tags)
assert exist_in?(article_tag2, meetup.article_tags)
end
test "meetup can be mirror to other community", ~m(user community community2 meetup_attrs)a do
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :communities)
assert meetup.communities |> length == 1
assert exist_in?(community, meetup.communities)
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community2.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :communities)
assert meetup.communities |> length == 2
assert exist_in?(community, meetup.communities)
assert exist_in?(community2, meetup.communities)
end
test "meetup can be mirror to other community with tags",
~m(user community community2 meetup_attrs)a do
article_tag_attrs = mock_attrs(:article_tag)
article_tag_attrs2 = mock_attrs(:article_tag)
{:ok, article_tag} = CMS.create_article_tag(community2, :meetup, article_tag_attrs, user)
{:ok, article_tag2} = CMS.create_article_tag(community2, :meetup, article_tag_attrs2, user)
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, _} =
CMS.mirror_article(:meetup, meetup.id, community2.id, [article_tag.id, article_tag2.id])
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :article_tags)
assert meetup.article_tags |> length == 2
assert exist_in?(article_tag, meetup.article_tags)
assert exist_in?(article_tag2, meetup.article_tags)
end
test "meetup can be unmirror from community",
~m(user community community2 community3 meetup_attrs)a do
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community2.id)
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community3.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :communities)
assert meetup.communities |> length == 3
{:ok, _} = CMS.unmirror_article(:meetup, meetup.id, community3.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :communities)
assert meetup.communities |> length == 2
assert not exist_in?(community3, meetup.communities)
end
test "meetup can be unmirror from community with tags",
~m(user community community2 community3 meetup_attrs)a do
article_tag_attrs2 = mock_attrs(:article_tag)
article_tag_attrs3 = mock_attrs(:article_tag)
{:ok, article_tag2} = CMS.create_article_tag(community2, :meetup, article_tag_attrs2, user)
{:ok, article_tag3} = CMS.create_article_tag(community3, :meetup, article_tag_attrs3, user)
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community2.id, [article_tag2.id])
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community3.id, [article_tag3.id])
{:ok, _} = CMS.unmirror_article(:meetup, meetup.id, community3.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :article_tags)
assert exist_in?(article_tag2, meetup.article_tags)
assert not exist_in?(article_tag3, meetup.article_tags)
end
test "meetup can not unmirror from original community",
~m(user community community2 community3 meetup_attrs)a do
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community2.id)
{:ok, _} = CMS.mirror_article(:meetup, meetup.id, community3.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: :communities)
assert meetup.communities |> length == 3
{:error, reason} = CMS.unmirror_article(:meetup, meetup.id, community.id)
assert reason |> is_error?(:mirror_article)
end
test "meetup can be mirror to home", ~m(community meetup_attrs user)a do
{:ok, home_community} = db_insert(:community, %{raw: "home"})
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
assert meetup.original_community_id == community.id
{:ok, _} = CMS.mirror_to_home(:meetup, meetup.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: [:original_community, :communities])
assert meetup.original_community_id == community.id
assert meetup.communities |> length == 2
assert exist_in?(community, meetup.communities)
assert exist_in?(home_community, meetup.communities)
filter = %{page: 1, size: 10, community: community.raw}
{:ok, paged_articles} = CMS.paged_articles(:meetup, filter)
assert exist_in?(meetup, paged_articles.entries)
assert paged_articles.total_count === 1
filter = %{page: 1, size: 10, community: home_community.raw}
{:ok, paged_articles} = CMS.paged_articles(:meetup, filter)
assert exist_in?(meetup, paged_articles.entries)
assert paged_articles.total_count === 1
end
test "meetup can be mirror to home with tags", ~m(community meetup_attrs user)a do
{:ok, home_community} = db_insert(:community, %{raw: "home"})
article_tag_attrs0 = mock_attrs(:article_tag)
article_tag_attrs = mock_attrs(:article_tag)
{:ok, article_tag0} =
CMS.create_article_tag(home_community, :meetup, article_tag_attrs0, user)
{:ok, article_tag} =
CMS.create_article_tag(home_community, :meetup, article_tag_attrs, user)
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
assert meetup.original_community_id == community.id
{:ok, _} = CMS.mirror_to_home(:meetup, meetup.id, [article_tag0.id, article_tag.id])
{:ok, meetup} =
ORM.find(Meetup, meetup.id, preload: [:original_community, :communities, :article_tags])
assert meetup.original_community_id == community.id
assert meetup.communities |> length == 2
assert exist_in?(community, meetup.communities)
assert exist_in?(home_community, meetup.communities)
assert meetup.article_tags |> length == 2
assert exist_in?(article_tag0, meetup.article_tags)
assert exist_in?(article_tag, meetup.article_tags)
filter = %{page: 1, size: 10, community: community.raw}
{:ok, paged_articles} = CMS.paged_articles(:meetup, filter)
assert exist_in?(meetup, paged_articles.entries)
assert paged_articles.total_count === 1
filter = %{page: 1, size: 10, community: home_community.raw}
{:ok, paged_articles} = CMS.paged_articles(:meetup, filter)
assert exist_in?(meetup, paged_articles.entries)
assert paged_articles.total_count === 1
end
test "meetup can be move to blackhole", ~m(community meetup_attrs user)a do
{:ok, blackhole_community} = db_insert(:community, %{raw: "blackhole"})
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
assert meetup.original_community_id == community.id
{:ok, _} = CMS.move_to_blackhole(:meetup, meetup.id)
{:ok, meetup} = ORM.find(Meetup, meetup.id, preload: [:original_community, :communities])
assert meetup.original_community.id == blackhole_community.id
assert meetup.communities |> length == 1
assert exist_in?(blackhole_community, meetup.communities)
filter = %{page: 1, size: 10, community: blackhole_community.raw}
{:ok, paged_articles} = CMS.paged_articles(:meetup, filter)
assert exist_in?(meetup, paged_articles.entries)
assert paged_articles.total_count === 1
end
test "meetup can be move to blackhole with tags", ~m(community meetup_attrs user)a do
{:ok, blackhole_community} = db_insert(:community, %{raw: "blackhole"})
article_tag_attrs0 = mock_attrs(:article_tag)
article_tag_attrs = mock_attrs(:article_tag)
{:ok, article_tag0} =
CMS.create_article_tag(blackhole_community, :meetup, article_tag_attrs0, user)
{:ok, article_tag} =
CMS.create_article_tag(blackhole_community, :meetup, article_tag_attrs, user)
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, _} = CMS.set_article_tag(:meetup, meetup.id, article_tag0.id)
assert meetup.original_community_id == community.id
{:ok, _} = CMS.move_to_blackhole(:meetup, meetup.id, [article_tag.id])
{:ok, meetup} =
ORM.find(Meetup, meetup.id, preload: [:original_community, :communities, :article_tags])
assert meetup.original_community.id == blackhole_community.id
assert meetup.communities |> length == 1
assert meetup.article_tags |> length == 1
assert exist_in?(blackhole_community, meetup.communities)
assert exist_in?(article_tag, meetup.article_tags)
end
end
end
| 42.471947 | 98 | 0.692672 |
1c3f581847b2aebb0ec14cfa199b7200d41c5d26 | 3,032 | ex | Elixir | lib/asciinema_web/controllers/user_controller.ex | AnotherKamila/asciinema-server | cafdba3c0461eb77ca0d1b66de07aa943b91f700 | [
"Apache-2.0"
] | null | null | null | lib/asciinema_web/controllers/user_controller.ex | AnotherKamila/asciinema-server | cafdba3c0461eb77ca0d1b66de07aa943b91f700 | [
"Apache-2.0"
] | null | null | null | lib/asciinema_web/controllers/user_controller.ex | AnotherKamila/asciinema-server | cafdba3c0461eb77ca0d1b66de07aa943b91f700 | [
"Apache-2.0"
] | null | null | null | defmodule AsciinemaWeb.UserController do
use AsciinemaWeb, :controller
alias Asciinema.Accounts
alias Asciinema.Authorization, as: Authz
alias Asciinema.Asciicasts
alias AsciinemaWeb.Auth
plug :require_current_user when action in [:edit, :update]
def new(conn, %{"t" => signup_token}) do
conn
|> put_session(:signup_token, signup_token)
|> redirect(to: users_path(conn, :new))
end
def new(conn, _params) do
render(conn, "new.html")
end
def create(conn, _params) do
signup_token = get_session(conn, :signup_token)
conn = delete_session(conn, :signup_token)
case Accounts.verify_signup_token(signup_token) do
{:ok, user} ->
conn
|> Auth.log_in(user)
|> put_flash(:info, "Welcome to asciinema!")
|> redirect(to: "/username/new")
{:error, :token_invalid} ->
conn
|> put_flash(:error, "Invalid sign-up link.")
|> redirect(to: login_path(conn, :new))
{:error, :token_expired} ->
conn
|> put_flash(:error, "This sign-up link has expired, sorry.")
|> redirect(to: login_path(conn, :new))
{:error, :email_taken} ->
conn
|> put_flash(:error, "You already signed up with this email.")
|> redirect(to: login_path(conn, :new))
end
end
def show(conn, params) do
current_user = conn.assigns.current_user
user =
case params do
%{"username" => username} ->
Accounts.find_user_by_username!(username)
%{"id" => id} ->
Accounts.get_user!(id)
end
user_is_self = !!(current_user && (current_user.id == user.id))
asciicasts =
case user_is_self do
true -> Accounts.asciicasts(user, :all)
false -> Accounts.asciicasts(user, :public)
end
asciicast_count = Asciicasts.count_asciicasts(asciicasts)
page = Asciicasts.paginate_asciicasts(asciicasts, :date, params["page"], 15)
conn
|> put_layout(:app2)
|> assign(:page_title, "#{user.username}'s profile")
|> assign(:main_class, "")
|> render(
"show.html",
user: user,
user_is_self: user_is_self,
asciicast_count: asciicast_count,
page: page,
show_edit_link: Authz.can?(current_user, :update, user)
)
end
def edit(conn, _params) do
user = conn.assigns.current_user
changeset = Accounts.change_user(user)
render_edit_form(conn, user, changeset)
end
def update(conn, %{"user" => user_params}) do
user = conn.assigns.current_user
case Accounts.update_user(user, user_params) do
{:ok, user} ->
conn
|> put_flash(:info, "Account settings saved.")
|> redirect(to: profile_path(conn, user))
{:error, %Ecto.Changeset{} = changeset} ->
render_edit_form(conn, user, changeset)
end
end
defp render_edit_form(conn, user, changeset) do
api_tokens = Accounts.list_api_tokens(user)
render(conn, "edit.html",
changeset: changeset,
api_tokens: api_tokens)
end
end
| 27.816514 | 80 | 0.630937 |
1c3f61fea2825de7bd9e2e907fc0b355211d0099 | 24,788 | exs | Elixir | test/rig_inbound_gateway/rig/proxy_test.exs | steveoliver/reactive-interaction-gateway | 59b6dc994fd0f098bed19b7bf1e699513ac87167 | [
"Apache-2.0"
] | 518 | 2017-11-09T13:10:49.000Z | 2022-03-28T14:29:50.000Z | test/rig_inbound_gateway/rig/proxy_test.exs | steveoliver/reactive-interaction-gateway | 59b6dc994fd0f098bed19b7bf1e699513ac87167 | [
"Apache-2.0"
] | 270 | 2017-11-10T00:11:34.000Z | 2022-02-27T13:08:16.000Z | test/rig_inbound_gateway/rig/proxy_test.exs | steveoliver/reactive-interaction-gateway | 59b6dc994fd0f098bed19b7bf1e699513ac87167 | [
"Apache-2.0"
] | 67 | 2017-12-19T20:16:37.000Z | 2022-03-31T10:43:04.000Z | defmodule RigInboundGateway.ProxyTest do
@moduledoc false
use ExUnit.Case, async: false
use RigApi.ConnCase
import RigInboundGateway.Proxy,
only: [
list_apis: 1,
get_api: 2,
add_api: 3,
replace_api: 4,
update_api: 3,
deactivate_api: 2,
handle_join_api: 3
]
import ExUnit.CaptureLog
alias RigInboundGateway.Proxy
alias RigInboundGateway.ProxyConfig
require Logger
@invalid_config_id "invalid-config"
setup [:with_tracker_mock_proxy]
defp test_proxy_exit(ctx, error) do
Process.flag(:trap_exit, true)
assert capture_log(fn ->
catch_exit do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
proxy |> list_apis
end
end) =~
error
assert_received({:EXIT, _proxy, :ReverseProxyConfigurationError})
end
describe "validations" do
test "should exit the process when api doesn't have required top level properties 'id', 'name', 'proxy' and 'version_data'",
ctx do
ProxyConfig.set_proxy_config()
test_proxy_exit(
ctx,
"[{\"api\", [{:error, \"id\", :by, \"must be string\"}, {:error, \"id\", :length, \"must have a length of at least 1\"}, {:error, \"name\", :by, \"must be string\"}, {:error, \"name\", :length, \"must have a length of at least 1\"}, {:error, \"proxy\", :presence, \"must be present\"}, {:error, \"version_data\", :presence, \"must be present\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when 'proxy' doesn't have required properties 'target_url' and 'port'",
ctx do
proxy = %{
"id" => "invalid_proxy",
"name" => "invalid_proxy",
"proxy" => %{},
"version_data" => %{
"default" => %{
"endpoints" => []
}
}
}
ProxyConfig.set_proxy_config(proxy)
test_proxy_exit(
ctx,
"[{\"api\", [{:error, \"proxy\", :presence, \"must be present\"}, {:error, \"target_url\", :by, \"must be string\"}, {:error, \"target_url\", :length, \"must have a length of at least 1\"}, {:error, \"port\", :by, \"must be integer\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when 'version_data' doesn't have any version",
ctx do
proxy = %{
"id" => "invalid_proxy",
"name" => "invalid_proxy",
"proxy" => %{
"port" => 3000,
"target_url" => "http://localhost"
},
"version_data" => %{}
}
ProxyConfig.set_proxy_config(proxy)
test_proxy_exit(
ctx,
"[{:error, \"version_data\", :presence, \"must be present\"}, {:error, \"version_data\", :presence, \"must have at least one version, e.g. default\"}]"
)
ProxyConfig.restore()
end
test "should exit the process when 'default' version doesn't have 'endpoints' property or is not an list",
ctx do
# missing "endpoints" property
proxy = %{
"id" => "invalid_proxy",
"name" => "invalid_proxy",
"proxy" => %{
"port" => 3000,
"target_url" => "http://localhost"
},
"version_data" => %{
"default" => %{}
}
}
ProxyConfig.set_proxy_config(proxy)
test_proxy_exit(
ctx,
"[{\"api\", [{:error, \"endpoints\", :by, \"must be list\"}]}]"
)
# "endpoints" not list
proxy = %{
"id" => "invalid_proxy",
"name" => "invalid_proxy",
"proxy" => %{
"port" => 3000,
"target_url" => "http://localhost"
},
"version_data" => %{
"default" => %{
"endpoints" => %{}
}
}
}
ProxyConfig.set_proxy_config(proxy)
test_proxy_exit(
ctx,
"[{\"api\", [{:error, \"endpoints\", :by, \"must be list\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when 'endpoint' doesn't have required properties 'id', 'method' and 'path' or 'path_regex'",
ctx do
endpoints = [
%{}
]
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints)
test_proxy_exit(
ctx,
"[{\"invalid-config/\", [{:error, \"id\", :by, \"must be string\"}, {:error, \"id\", :length, \"must have a length of at least 1\"}, {:error, \"path_regex\", :by, \"must be string\"}, {:error, \"path_regex\", :length, \"must have a length of at least 1\"}, {:error, \"method\", :by, \"must be string\"}, {:error, \"method\", :length, \"must have a length of at least 1\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when 'path_regex' is set, but incorrect",
ctx do
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => ""
}
]
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints)
test_proxy_exit(
ctx,
"[{\"invalid-config/invalid-config1\", [{:error, \"path_regex\", :length, \"must have a length of at least 1\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when target is set to kafka or kinesis, but topic is not",
ctx do
# kinesis topic not set
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo",
"target" => "kinesis"
}
]
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints)
test_proxy_exit(
ctx,
"[{\"invalid-config/invalid-config1\", [{:error, \"topic\", :presence, \"must be present\"}]}]"
)
ProxyConfig.restore()
# kafka topic not set
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo",
"target" => "kafka"
}
]
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints)
test_proxy_exit(
ctx,
"[{\"invalid-config/invalid-config1\", [{:error, \"topic\", :presence, \"must be present\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when schema is set, but target is not kafka or kinesis", ctx do
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo",
"schema" => "some-avro-schema"
}
]
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints)
test_proxy_exit(
ctx,
"[{\"invalid-config/invalid-config1\", [{:error, \"target\", :presence, \"must be present\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when secured is set, but auth_type is not jwt", ctx do
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo",
"secured" => true
}
]
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints)
test_proxy_exit(
ctx,
"[{\"invalid-config/invalid-config1\", [{:error, \"auth_type\", :inclusion, \"must be one of [\\\"jwt\\\"]\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when use_header is set, but header_name is not", ctx do
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo"
}
]
auth = %{"use_header" => true}
auth_type = "jwt"
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints, auth, auth_type)
test_proxy_exit(
ctx,
"[{\"invalid-config\", [{:error, \"header_name\", :presence, \"must be present\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when use_query is set, but query_name is not", ctx do
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo"
}
]
auth = %{"use_query" => true}
auth_type = "jwt"
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints, auth, auth_type)
test_proxy_exit(
ctx,
"[{\"invalid-config\", [{:error, \"query_name\", :presence, \"must be present\"}]}]"
)
ProxyConfig.restore()
end
test "should exit the process when auth is set, but auth_type is not", ctx do
endpoints = [
%{
"id" => @invalid_config_id <> "1",
"method" => "GET",
"path_regex" => "/foo"
}
]
auth = %{"use_query" => true, "query_name" => "test"}
ProxyConfig.set_proxy_config(@invalid_config_id, endpoints, auth)
test_proxy_exit(
ctx,
"[{\"invalid-config\", [{:error, \"auth_type\", :inclusion, \"must be one of [\\\"jwt\\\"]\"}]}]"
)
ProxyConfig.restore()
end
end
describe "list_apis" do
test "should return API definitions when the configuration is passed as a JSON file.", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
assert proxy |> list_apis |> length == 2
assert ctx.tracker |> Stubr.called_once?(:list_by_node)
end
test "should return API definitions when the configuration is passed as a JSON string.",
ctx do
id = "config-by-json-string"
endpoints = [
%{
"id" => id <> "1",
"method" => "GET",
"secured" => false,
"path_regex" => "/foo"
},
%{
"id" => id <> "2",
"method" => "GET",
"path_regex" => "/foo/([^/]+)/bar/([^/]+)"
}
]
ProxyConfig.set_proxy_config(id, endpoints)
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
apis = Proxy.list_apis(proxy)
assert [{^id, _api}] = apis
ProxyConfig.restore()
end
end
describe "get_api" do
test "should return nil for non-existent API definition", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
assert proxy |> get_api("random-service")
assert ctx.tracker |> Stubr.called_once?(:find_by_node)
end
end
describe "add_api" do
test "should start tracking new API and add default values for optional data", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
refute proxy |> get_api("incomplete-service")
assert ctx.tracker |> Stubr.called_twice?(:track)
assert ctx.tracker |> Stubr.called_once?(:find_by_node)
incomplete_api = %{
"id" => "incomplete-service",
"name" => "incomplete-service",
"proxy" => %{"port" => 7070, "target_url" => "API_HOST"},
"version_data" => %{}
}
{:ok, _response} = proxy |> add_api("incomplete-service", incomplete_api)
{_id, api} = proxy |> get_api("incomplete-service")
has_required_keys =
["active", "auth_type", "auth", "node_name", "ref_number", "timestamp", "versioned"]
|> Enum.all?(fn key -> Map.has_key?(api, key) end)
assert has_required_keys
assert ctx.tracker |> Stubr.called_thrice?(:track)
assert ctx.tracker |> Stubr.called_twice?(:find_by_node)
end
test "should start tracking new API and not override optional data if present", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
refute proxy |> get_api("new-service")
assert ctx.tracker |> Stubr.called_twice?(:track)
assert ctx.tracker |> Stubr.called_once?(:find_by_node)
{:ok, _response} = proxy |> add_api("new-service", @mock_api)
{_id, api} = proxy |> get_api("new-service")
has_equal_values =
@mock_api
|> Map.keys()
|> Enum.all?(fn key -> @mock_api[key] == api[key] end)
assert has_equal_values
assert ctx.tracker |> Stubr.called_thrice?(:track)
assert ctx.tracker |> Stubr.called_twice?(:find_by_node)
end
test "with existing ID should return error", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
{:error, :already_tracked} = proxy |> add_api("random-service", @mock_api)
assert ctx.tracker |> Stubr.called_thrice?(:track)
end
test "should set default auth values for service", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
refute proxy |> get_api("incomplete-service")
assert ctx.tracker |> Stubr.called_twice?(:track)
assert ctx.tracker |> Stubr.called_once?(:find_by_node)
api_config = %{
"id" => "incomplete-service",
"name" => "incomplete-service",
"proxy" => %{"port" => 7070, "target_url" => "API_HOST"},
"version_data" => %{},
"auth_type" => "none"
}
expected_auth_values = %{
"use_header" => false,
"header_name" => "",
"use_query" => false,
"query_name" => ""
}
{:ok, _response} = proxy |> add_api("incomplete-service", api_config)
{_id, api} = proxy |> get_api("incomplete-service")
assert api["auth"] == expected_auth_values
assert ctx.tracker |> Stubr.called_thrice?(:track)
assert ctx.tracker |> Stubr.called_twice?(:find_by_node)
end
test "should set header auth values if auth_type is jwt", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
refute proxy |> get_api("incomplete-service")
assert ctx.tracker |> Stubr.called_twice?(:track)
assert ctx.tracker |> Stubr.called_once?(:find_by_node)
api_config = %{
"id" => "incomplete-service",
"name" => "incomplete-service",
"proxy" => %{"port" => 7070, "target_url" => "API_HOST"},
"version_data" => %{},
"auth_type" => "jwt"
}
expected_auth_values = %{
"use_header" => true,
"header_name" => "Authorization",
"use_query" => false,
"query_name" => ""
}
{:ok, _response} = proxy |> add_api("incomplete-service", api_config)
{_id, api} = proxy |> get_api("incomplete-service")
assert api["auth"] == expected_auth_values
assert ctx.tracker |> Stubr.called_thrice?(:track)
assert ctx.tracker |> Stubr.called_twice?(:find_by_node)
end
test "should not override user defined query auth values when auth_type is jwt", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
refute proxy |> get_api("incomplete-service")
assert ctx.tracker |> Stubr.called_twice?(:track)
assert ctx.tracker |> Stubr.called_once?(:find_by_node)
api_config = %{
"id" => "incomplete-service",
"name" => "incomplete-service",
"proxy" => %{"port" => 7070, "target_url" => "API_HOST"},
"version_data" => %{},
"auth_type" => "jwt",
"auth" => %{
"use_query" => true,
"query_name" => "token"
}
}
{:ok, _response} = proxy |> add_api("incomplete-service", api_config)
{_id, api} = proxy |> get_api("incomplete-service")
assert api["auth"]["use_query"]
assert api["auth"]["query_name"] == "token"
# auth type set to jwt should still set the appropiate auth values
assert api["auth"]["use_header"]
assert api["auth"]["header_name"] == "Authorization"
assert ctx.tracker |> Stubr.called_thrice?(:track)
assert ctx.tracker |> Stubr.called_twice?(:find_by_node)
end
end
describe "replace_api" do
test "should replace deactivated API with new one", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
proxy |> deactivate_api("random-service")
{_id, deactivated_api} = proxy |> get_api("random-service")
assert deactivated_api["active"] == false
assert ctx.tracker |> Stubr.called_once?(:update)
proxy |> replace_api("random-service", deactivated_api, @mock_api)
{_id, replaced_api} = proxy |> get_api("random-service")
assert replaced_api["active"] == true
assert ctx.tracker |> Stubr.called_twice?(:update)
end
end
describe "update_api" do
test "should update existing API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
{_id, existing_api} = proxy |> get_api("random-service")
assert existing_api["name"] == "random-service"
refute ctx.tracker |> Stubr.called?(:update)
updated_existing_api = existing_api |> Map.put("name", "updated-service")
proxy |> update_api("random-service", updated_existing_api)
{_id, new_api} = proxy |> get_api("random-service")
assert new_api["name"] == "updated-service"
assert ctx.tracker |> Stubr.called_once?(:update)
end
end
describe "deactivate_api" do
test "should deactivate API ", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
{_id, current_api} = proxy |> get_api("random-service")
assert current_api["active"] == true
refute ctx.tracker |> Stubr.called?(:update)
proxy |> deactivate_api("random-service")
{_id, deactivated_api} = proxy |> get_api("random-service")
assert deactivated_api["active"] == false
assert ctx.tracker |> Stubr.called_once?(:update)
end
end
describe "handle_join_api" do
test "should track new API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
proxy |> handle_join_api("new-service", @mock_api)
:timer.sleep(25)
assert proxy |> get_api("new-service")
refute ctx.tracker |> Stubr.called?(:update)
end
end
describe "handle_join_api receiving existing API" do
test "should skip API when it has out of date ref_number", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
older_api =
proxy
|> get_api("random-service")
|> elem(1)
|> Map.put("ref_number", -1)
proxy |> handle_join_api("random-service", older_api)
{_id, current_api} = proxy |> get_api("random-service")
:timer.sleep(25)
assert current_api["ref_number"] == 0
refute ctx.tracker |> Stubr.called?(:update)
end
test "should update API when it has more recent ref_number", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
newer_api =
proxy
|> get_api("random-service")
|> elem(1)
|> Map.put("ref_number", 1)
refute ctx.tracker |> Stubr.called?(:update)
proxy |> handle_join_api("random-service", newer_api)
{_id, current_api} = proxy |> get_api("random-service")
:timer.sleep(25)
assert current_api["ref_number"] == 1
assert ctx.tracker |> Stubr.called_once?(:update)
end
test "with same ref_number and equal data should skip API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
{_id, equal_api} = proxy |> get_api("random-service")
proxy |> handle_join_api("random-service", equal_api)
{_id, current_api} = proxy |> get_api("random-service")
:timer.sleep(25)
assert current_api["ref_number"] == 0
refute ctx.tracker |> Stubr.called?(:update)
end
end
describe "handle_join_api receiving existing API with same ref_number and different data" do
test "on less than 1/2 nodes should skip API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
node2_api = @mock_api |> Map.put("node_name", :node2@node2)
node3_api = @mock_api |> Map.put("node_name", :node3@node3)
proxy |> add_api("new-service", @mock_api)
proxy |> add_api("new-service", node2_api)
proxy |> add_api("new-service", node3_api)
different_api =
@mock_api
|> Map.put("ref_number", 0)
|> Map.put("name", "new_name")
proxy |> handle_join_api("new-service", different_api)
:timer.sleep(25)
refute ctx.tracker |> Stubr.called?(:update)
end
test "on more than 1/2 nodes should update API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
different_api =
@mock_api
|> Map.put("name", "new_name")
|> Map.put("ref_number", 0)
node2_api = different_api |> Map.put("node_name", :node2@node2)
node3_api = different_api |> Map.put("node_name", :node3@node3)
proxy |> add_api("new-service", @mock_api)
ctx.tracker.track("new-service", node2_api)
ctx.tracker.track("new-service", node3_api)
refute ctx.tracker |> Stubr.called?(:update)
proxy |> handle_join_api("new-service", different_api)
{_id, current_api} = proxy |> get_api("new-service")
:timer.sleep(25)
assert current_api["ref_number"] == 0
assert current_api["name"] == "new_name"
assert ctx.tracker |> Stubr.called_once?(:update)
end
test "on exactly 1/2 nodes, but old timestamp should skip API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
old_timestamp = Timex.now() |> Timex.shift(minutes: -3)
different_api =
@mock_api
|> Map.put("ref_number", 0)
|> Map.put("name", "new_name")
|> Map.put("node_name", :differentnode@differenthost)
|> Map.put("timestamp", old_timestamp)
proxy |> add_api("new-service", @mock_api)
proxy |> add_api("new-service", different_api)
proxy |> handle_join_api("new-service", different_api)
:timer.sleep(25)
refute ctx.tracker |> Stubr.called?(:update)
end
test "on exactly 1/2 nodes and newer timestamp should update API", ctx do
{:ok, proxy} = Proxy.start_link(ctx.tracker, name: nil)
new_timestamp = Timex.now() |> Timex.shift(minutes: +3)
different_api =
@mock_api
|> Map.put("ref_number", 0)
|> Map.put("name", "new_name")
|> Map.put("node_name", :differentnode@differenthost)
|> Map.put("timestamp", new_timestamp)
proxy |> add_api("new-service", @mock_api)
ctx.tracker.track("new-service", different_api)
refute ctx.tracker |> Stubr.called?(:update)
proxy |> handle_join_api("new-service", different_api)
:timer.sleep(25)
assert ctx.tracker |> Stubr.called_once?(:update)
end
end
defp with_tracker_mock_proxy(_ctx) do
{:ok, agent} = Agent.start_link(fn -> [] end)
tracker =
Stubr.stub!(
[
track: fn id, api ->
Logger.debug(fn -> "Tracker Stub :track id=#{inspect(id)} api=#{inspect(api)}" end)
# Mimic the "cannot track more than once" behaviour:
already_tracked? =
Agent.get(agent, fn list ->
list
|> Enum.find(fn {key, meta} ->
key == id && meta["node_name"] == api["node_name"]
end)
end) != nil
if already_tracked? do
{:error, :already_tracked}
else
Agent.update(agent, fn list ->
api_with_ref = api |> Map.put(:phx_ref, "some_phx_ref")
[{id, api_with_ref} | list]
end)
{:ok, 'some_phx_ref'}
end
end,
update: fn id, api ->
Logger.debug(fn -> "Tracker Stub :update id=#{inspect(id)} api=#{inspect(api)}" end)
Agent.update(agent, fn list ->
list
|> Enum.filter(fn {key, meta} ->
key != id || meta["node_name"] != :nonode@nohost
end)
|> Enum.concat([{id, api}])
end)
{:ok, 'some_phx_ref'}
end,
list_all: fn ->
Logger.debug("Tracker Stub :list")
Agent.get(agent, fn list -> list end)
end,
list_by_node: fn node_name ->
Logger.debug("Tracker Stub :list")
Agent.get(agent, fn list ->
list |> Enum.filter(fn {_key, meta} -> meta["node_name"] == node_name end)
end)
end,
# was _node_name
find_by_node: fn id, node_name ->
Logger.debug(fn -> "Tracker Stub :find id=#{inspect(id)}" end)
Agent.get(agent, fn list ->
list
|> Enum.find(fn {key, meta} ->
key == id && meta["node_name"] == node_name
end)
end)
end,
find_all: fn id ->
Logger.debug(fn -> "Tracker Stub :find_all id=#{inspect(id)}" end)
Agent.get(agent, fn list -> list |> Enum.filter(fn {key, _meta} -> key == id end) end)
end
],
behaviour: RigInboundGateway.ApiProxy.Tracker.TrackerBehaviour,
call_info: true
)
[tracker: tracker]
end
end
| 30.452088 | 383 | 0.567775 |
1c3f63a4533437205c340e20aaea7a8bc1b0362c | 596 | exs | Elixir | 6453_06_03_Code/application-deck/mix.exs | PacktPublishing/Advanced-Elixir-and-OTP | 952fe654f1f91ec186a41d5ff4f09672ef5e7221 | [
"MIT"
] | 1 | 2021-10-01T22:06:12.000Z | 2021-10-01T22:06:12.000Z | 6453_06_03_Code/application-deck/mix.exs | PacktPublishing/Advanced-Elixir-and-OTP | 952fe654f1f91ec186a41d5ff4f09672ef5e7221 | [
"MIT"
] | null | null | null | 6453_06_03_Code/application-deck/mix.exs | PacktPublishing/Advanced-Elixir-and-OTP | 952fe654f1f91ec186a41d5ff4f09672ef5e7221 | [
"MIT"
] | 1 | 2020-06-10T10:40:37.000Z | 2020-06-10T10:40:37.000Z | defmodule Deck.Mixfile do
use Mix.Project
def project do
[
app: :deck,
version: "0.1.0",
elixir: "~> 1.5",
start_permanent: Mix.env == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Deck.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
| 19.866667 | 88 | 0.567114 |
1c3f712db79b25101e3d4e58880e921228671b95 | 5,622 | ex | Elixir | deps/comeonin/lib/comeonin.ex | Abninho92/RocketseatNLW2021-Rocketpay | 3e492bf582148202a215f6a26e6c0890ed9a0e23 | [
"MIT"
] | 986 | 2016-06-29T09:47:32.000Z | 2022-03-22T00:05:20.000Z | deps/comeonin/lib/comeonin.ex | gleidsonduarte/rocketseat-rocketpay-phoenix-elixir-postgres | 300e0b34e0179380f56a8c6cae707722d9c4d8d0 | [
"MIT"
] | 75 | 2016-06-29T20:25:31.000Z | 2022-01-20T04:31:57.000Z | deps/comeonin/lib/comeonin.ex | gleidsonduarte/rocketseat-rocketpay-phoenix-elixir-postgres | 300e0b34e0179380f56a8c6cae707722d9c4d8d0 | [
"MIT"
] | 54 | 2016-06-30T06:22:09.000Z | 2021-08-07T02:53:40.000Z | defmodule Comeonin do
@moduledoc """
Defines a behaviour for higher-level password hashing functions.
"""
@type opts :: keyword
@type password :: binary
@type user_struct :: map | nil
@doc """
Hashes a password and returns the password hash in a map.
"""
@callback add_hash(password, opts) :: map
@doc """
Checks the password by comparing its hash with the password hash found
in a user struct, or map.
The first argument to `check_pass/3` should be a user struct, a regular
map, or nil.
"""
@callback check_pass(user_struct, password, opts) :: {:ok, map} | {:error, String.t()}
@doc """
Runs the password hash function, but always returns false.
This function is intended to make it more difficult for any potential
attacker to find valid usernames by using timing attacks. This function
is only useful if it is used as part of a policy of hiding usernames.
"""
@callback no_user_verify(opts) :: false
defmacro __using__(_) do
quote do
@behaviour Comeonin
@behaviour Comeonin.PasswordHash
@doc """
Hashes a password, using `hash_pwd_salt/2`, and returns the password hash in a map.
This is a convenience function that is especially useful when used with
Ecto changesets.
## Options
In addition to the `:hash_key` option show below, this function also takes
options that are then passed on to the `hash_pwd_salt/2` function in this
module.
See the documentation for `hash_pwd_salt/2` for further details.
* `:hash_key` - the password hash identifier
* the default is `:password_hash`
## Example with Ecto
The `put_pass_hash` function below is an example of how you can use
`add_hash` to add the password hash to the Ecto changeset.
defp put_pass_hash(%Ecto.Changeset{valid?: true, changes:
%{password: password}} = changeset) do
change(changeset, add_hash(password))
end
defp put_pass_hash(changeset), do: changeset
This function will return a changeset with `%{password_hash: password_hash}`
added to the `changes` map.
"""
@impl Comeonin
def add_hash(password, opts \\ []) do
hash_key = opts[:hash_key] || :password_hash
%{hash_key => hash_pwd_salt(password, opts)}
end
@doc """
Checks the password, using `verify_pass/2`, by comparing the hash with
the password hash found in a user struct, or map.
This is a convenience function that takes a user struct, or map, as input
and seamlessly handles the cases where no user is found.
## Options
* `:hash_key` - the password hash identifier
* this does not need to be set if the key is `:password_hash` or `:encrypted_password`
* `:hide_user` - run the `no_user_verify/1` function if no user is found
* the default is true
## Example
The following is an example of using this function to verify a user's
password:
def verify_user(%{"password" => password} = params) do
params
|> Accounts.get_by()
|> check_pass(password)
end
The `Accounts.get_by` function in this example takes the user parameters
(for example, email and password) as input and returns a user struct or nil.
"""
@impl Comeonin
def check_pass(user, password, opts \\ [])
def check_pass(nil, _password, opts) do
unless opts[:hide_user] == false, do: no_user_verify(opts)
{:error, "invalid user-identifier"}
end
def check_pass(user, password, opts) when is_binary(password) do
case get_hash(user, opts[:hash_key]) do
{:ok, hash} ->
if verify_pass(password, hash), do: {:ok, user}, else: {:error, "invalid password"}
_ ->
{:error, "no password hash found in the user struct"}
end
end
def check_pass(_, _, _) do
{:error, "password is not a string"}
end
defp get_hash(%{password_hash: hash}, nil), do: {:ok, hash}
defp get_hash(%{encrypted_password: hash}, nil), do: {:ok, hash}
defp get_hash(_, nil), do: nil
defp get_hash(user, hash_key) do
if hash = Map.get(user, hash_key), do: {:ok, hash}
end
@doc """
Runs the password hash function, but always returns false.
This function is intended to make it more difficult for any potential
attacker to find valid usernames by using timing attacks. This function
is only useful if it is used as part of a policy of hiding usernames.
## Options
This function should be called with the same options as those used by
`hash_pwd_salt/2`.
## Hiding usernames
In addition to keeping passwords secret, hiding the precise username
can help make online attacks more difficult. An attacker would then
have to guess a username / password combination, rather than just
a password, to gain access.
This does not mean that the username should be kept completely secret.
Adding a short numerical suffix to a user's name, for example, would be
sufficient to increase the attacker's work considerably.
If you are implementing a policy of hiding usernames, it is important
to make sure that the username is not revealed by any other part of
your application.
"""
@impl Comeonin
def no_user_verify(opts \\ []) do
hash_pwd_salt("", opts)
false
end
defoverridable Comeonin
end
end
end
| 32.877193 | 96 | 0.649769 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.