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
0396358cbece17cd210bd953d46c0500c4e264f2
2,078
ex
Elixir
lib/ash_thrift.ex
arisechurch/ash_thrift
96416cbb34d543758c52813b1137959b309eb602
[ "MIT" ]
null
null
null
lib/ash_thrift.ex
arisechurch/ash_thrift
96416cbb34d543758c52813b1137959b309eb602
[ "MIT" ]
null
null
null
lib/ash_thrift.ex
arisechurch/ash_thrift
96416cbb34d543758c52813b1137959b309eb602
[ "MIT" ]
null
null
null
defmodule AshThrift do defmodule Namespace do @type t :: %__MODULE__{ language: atom(), name: String.t() } defstruct [:language, :name] end defmodule Field do @type t :: %__MODULE__{ id: non_neg_integer(), attribute: atom(), optional: boolean() } defstruct [:id, :attribute, :optional] end defmodule Struct do @type t :: %__MODULE__{ name: String.t(), fields: Field.t() } defstruct [:name, :fields] end @doc """ Builds an Ash resource from a thrift struct """ @spec into( data :: map(), resource :: module(), variant :: String.t(), dest :: map() ) :: term() def into(data, resource, variant, dest \\ nil) def into(data, resource, variant, nil), do: into(data, resource, variant, struct(resource)) def into(data, resource, variant, dest) do Ash.Dsl.Extension.get_persisted(resource, :thrift, %{}) |> Map.get(variant, []) |> Enum.reduce(dest, fn {_field, %Ash.Resource.Attribute{ name: name, type: type }}, acc -> value = AshThrift.Conversion.parse(type, Map.get(data, name)) Map.put(acc, name, value) end) end @doc """ Dumps an Ash resource to a thrift struct """ @spec dump(resource :: struct(), variant :: String.t(), thrift_struct :: map()) :: struct() def dump(resource, variant, dest \\ %{}) do Ash.Dsl.Extension.get_persisted(resource.__struct__, :thrift, %{}) |> Map.get(variant, []) |> Enum.reduce(dest, fn {_field, %Ash.Resource.Attribute{ name: name, type: type }}, acc -> value = AshThrift.Conversion.value(type, Map.get(resource, name)) Map.put(acc, name, value) end) end end
27.342105
93
0.493263
03964578f65ae33636c1792fe199bac96b0f0025
9,114
exs
Elixir
test/tesla_test.exs
brenomaia/tesla
c1e0f2d031eb87a207db33333b8d4afc58384e87
[ "MIT" ]
1
2022-01-22T16:59:48.000Z
2022-01-22T16:59:48.000Z
test/tesla_test.exs
brenomaia/tesla
c1e0f2d031eb87a207db33333b8d4afc58384e87
[ "MIT" ]
null
null
null
test/tesla_test.exs
brenomaia/tesla
c1e0f2d031eb87a207db33333b8d4afc58384e87
[ "MIT" ]
1
2021-09-26T18:49:44.000Z
2021-09-26T18:49:44.000Z
defmodule TeslaTest do use ExUnit.Case doctest Tesla require Tesla @url "http://localhost:#{Application.get_env(:httparrot, :http_port)}" describe "Adapters" do defmodule ModuleAdapter do def call(env, opts) do {:ok, Map.put(env, :url, env.url <> "/module/" <> opts[:with])} end end defmodule EmptyClient do use Tesla end defmodule ModuleAdapterClient do use Tesla adapter ModuleAdapter, with: "someopt" end defmodule FunAdapterClient do use Tesla adapter fn env -> {:ok, Map.put(env, :url, env.url <> "/anon")} end end defmodule OptsAdapter do def call(env, opts) do {:ok, %{env | body: Tesla.Adapter.opts(env, opts)}} end end defmodule OptsClient do use Tesla adapter OptsAdapter, static: :always end setup do # clean config Application.delete_env(:tesla, EmptyClient) Application.delete_env(:tesla, ModuleAdapterClient) :ok end test "defauilt adapter" do assert Tesla.effective_adapter(EmptyClient) == {Tesla.Adapter.Httpc, :call, [[]]} end test "use adapter override from config" do Application.put_env(:tesla, EmptyClient, adapter: Tesla.Mock) assert Tesla.effective_adapter(EmptyClient) == {Tesla.Mock, :call, [[]]} end test "prefer config over module setting" do Application.put_env(:tesla, ModuleAdapterClient, adapter: Tesla.Mock) assert Tesla.effective_adapter(ModuleAdapterClient) == {Tesla.Mock, :call, [[]]} end test "execute module adapter" do assert {:ok, response} = ModuleAdapterClient.request(url: "test") assert response.url == "test/module/someopt" end test "execute anonymous function adapter" do assert {:ok, response} = FunAdapterClient.request(url: "test") assert response.url == "test/anon" end test "pass only :adapter opts to adapter" do assert {:ok, env} = OptsClient.get("/") assert env.body == [static: :always] assert {:ok, env} = OptsClient.get("/", opts: [ignore: :me]) assert env.body == [static: :always] assert {:ok, env} = OptsClient.get("/", opts: [adapter: [include: :me]]) assert env.body == [static: :always, include: :me] assert {:ok, env} = OptsClient.get("/", opts: [adapter: [static: :override]]) assert env.body == [static: :override] end end describe "Middleware" do defmodule AppendOne do @behaviour Tesla.Middleware def call(env, next, _opts) do env |> Map.put(:url, "#{env.url}/1") |> Tesla.run(next) end end defmodule AppendWith do @behaviour Tesla.Middleware def call(env, next, opts) do env |> Map.update!(:url, fn url -> url <> "/MB" <> opts[:with] end) |> Tesla.run(next) |> case do {:ok, env} -> {:ok, Map.update!(env, :url, fn url -> url <> "/MA" <> opts[:with] end)} error -> error end end end defmodule AppendClient do use Tesla plug AppendOne plug AppendWith, with: "1" plug AppendWith, with: "2" adapter fn env -> {:ok, env} end end test "execute middleware top down" do assert {:ok, response} = AppendClient.get("one") assert response.url == "one/1/MB1/MB2/MA2/MA1" end end describe "Dynamic client" do defmodule DynamicClient do use Tesla adapter fn env -> if String.ends_with?(env.url, "/cached") do {:ok, %{env | body: "cached", status: 304}} else Tesla.run_default_adapter(env) end end def help(client \\ %Tesla.Client{}) do get(client, "/help") end end test "override adapter - Tesla.client" do client = Tesla.client([], fn env -> {:ok, %{env | body: "new"}} end) assert {:ok, %{body: "new"}} = DynamicClient.help(client) end test "statically override adapter" do assert {:ok, %{status: 200}} = DynamicClient.get(@url <> "/ip") assert {:ok, %{status: 304}} = DynamicClient.get(@url <> "/cached") end end describe "request API" do defmodule SimpleClient do use Tesla adapter fn %{url: "/error"} -> {:error, :generic} env -> {:ok, env} end end test "basic request" do assert {:ok, response} = SimpleClient.request(url: "/", method: :post, query: [page: 1], body: "data") assert response.method == :post assert response.url == "/" assert response.query == [page: 1] assert response.body == "data" end test "shortcut function" do assert {:ok, response} = SimpleClient.get("/get") assert response.method == :get assert response.url == "/get" end test "shortcut function with body" do assert {:ok, response} = SimpleClient.post("/post", "some-data") assert response.method == :post assert response.url == "/post" assert response.body == "some-data" end test "better errors when given nil opts" do assert_raise FunctionClauseError, fn -> SimpleClient.get("/", nil) end end test "return error tuple for normal functions" do assert {:error, :generic} = SimpleClient.get("/error") end test "raise for bang variants" do assert_raise Tesla.Error, ~r//, fn -> SimpleClient.get!("/error") end end end alias Tesla.Env import Tesla describe "get_headers/2" do test "none matching" do env = %Env{headers: [{"server", "Cowboy"}]} assert get_headers(env, "cookie") == [] end test "multiple matches matching" do env = %Env{headers: [{"cookie", "chocolate"}, {"cookie", "biscuits"}]} assert get_headers(env, "cookie") == ["chocolate", "biscuits"] end end describe "put_header/3" do test "add new header" do env = %Env{} env = put_header(env, "server", "Cowboy") assert get_header(env, "server") == "Cowboy" end test "override existing header" do env = %Env{headers: [{"server", "Cowboy"}]} env = put_header(env, "server", "nginx") assert get_header(env, "server") == "nginx" end end describe "put_headers/2" do test "add headers to env existing header" do env = %Env{} assert get_header(env, "server") == nil env = Tesla.put_headers(env, [{"server", "Cowboy"}, {"content-length", "100"}]) assert get_header(env, "server") == "Cowboy" assert get_header(env, "content-length") == "100" env = Tesla.put_headers(env, [{"server", "nginx"}, {"content-type", "text/plain"}]) assert get_header(env, "server") == "Cowboy" assert get_header(env, "content-length") == "100" assert get_header(env, "content-type") == "text/plain" end test "add multiple headers with the same name" do env = %Env{} env = Tesla.put_headers(env, [{"cookie", "chocolate"}, {"cookie", "biscuits"}]) assert get_headers(env, "cookie") == ["chocolate", "biscuits"] end end describe "delete_header/2" do test "delete all headers with given name" do env = %Env{headers: [{"cookie", "chocolate"}, {"server", "Cowboy"}, {"cookie", "biscuits"}]} env = delete_header(env, "cookie") assert get_header(env, "cookie") == nil assert get_header(env, "server") == "Cowboy" end end describe "build_url/2" do setup do {:ok, url: "http://api.example.com"} end test "returns URL with query params from keyword list", %{url: url} do query_params = [user: 3, page: 2] assert build_url(url, query_params) === url <> "?user=3&page=2" end test "returns URL with query params from nested keyword list", %{url: url} do query_params = [nested: [more_nested: [argument: 1]]] assert build_url(url, query_params) === url <> "?nested%5Bmore_nested%5D%5Bargument%5D=1" end test "returns URL with query params from tuple list", %{url: url} do query_params = [{"user", 3}, {"page", 2}] assert build_url(url, query_params) === url <> "?user=3&page=2" end test "returns URL with query params from nested tuple list", %{url: url} do query_params = [{"nested", [{"more_nested", [{"argument", 1}]}]}] assert build_url(url, query_params) === url <> "?nested%5Bmore_nested%5D%5Bargument%5D=1" end test "returns URL with new query params concated from keyword list", %{url: url} do url_with_param = url <> "?user=4" query_params = [page: 2, status: true] assert build_url(url_with_param, query_params) === url <> "?user=4&page=2&status=true" end test "returns normal URL when query list is empty", %{url: url} do assert build_url(url, []) == url end test "returns error when passing wrong params" do wrong_url = 2 wrong_query = :test assert_raise FunctionClauseError, fn -> build_url(wrong_url, wrong_query) end end end end
28.304348
98
0.596555
03966842e16018d9641d858a55ff6fc28b78660a
2,764
exs
Elixir
27-frank-2.exs
lbiru/30-days-of-elixir
8472b6bf4a2f0a12dc6aea930abde2d50867b460
[ "MIT" ]
3,040
2015-01-01T00:26:22.000Z
2022-03-17T04:10:43.000Z
27-frank-2.exs
tifazxy/30-days-of-elixir
1d3e5cc1580ecbfdf9bd8eafed6ed68cb681404a
[ "MIT" ]
29
2015-01-03T02:36:47.000Z
2019-05-20T13:01:52.000Z
27-frank-2.exs
tifazxy/30-days-of-elixir
1d3e5cc1580ecbfdf9bd8eafed6ed68cb681404a
[ "MIT" ]
520
2015-01-01T09:43:36.000Z
2022-03-19T00:02:22.000Z
# A micro web DSL library called "Frank" # The motivation was mainly to learn about macros. # # This version is only slightly better than the last... # It still does not support paths with regex match :-( # # Improvements over the last version are: # * define methods as `def handle(path, data)` instead of `def path(data)` # * used @before_compile callback to set a default handler method require Record defmodule Frank do @moduledoc """ Frank is a micro web library that provides a DSL for defining routes. defmodule MyApp do use Frank get "/foo" do response 200, "foo!" end end Frank.sing(MyApp) To run: $ iex 27-frank-2.exs ... then point your browser to http://localhost:3000 """ Record.defrecord :mod, Record.extract(:mod, from_lib: "inets/include/httpd.hrl") @doc """ Start the web server given the app module. """ def sing(module) do :inets.start() options = [server_name: 'frank', server_root: '/tmp', document_root: '/tmp', port: 3000, modules: [module]] {:ok, _pid} = :inets.start :httpd, options IO.puts "running on port 3000" end defmodule Path do defmacro get(path, contents) do contents = Macro.escape(Keyword.get(contents, :do)) quote bind_quoted: binding do def handle(unquote(path), data) do unquote(contents) end end end defmacro __before_compile__(_env) do quote do def handle(_, data) do IO.puts 'here default!' response(404, 'not defined') end end end def redirect(path, code \\ 302) do body = ['redirecting you to <a href="', path, '">', path, '</a>'] response code, body, [location: path] end def sanitize(content) do content = Regex.replace(~r/&/, content, "\\&amp;") content = Regex.replace(~r/</, content, "\\&lt;") content = Regex.replace(~r/>/, content, "\\&gt;") content end def response(code, body, headers \\ []) do if is_binary(body) do body = :erlang.bitstring_to_list(body) end headers = [code: code, content_length: Integer.to_char_list(IO.iodata_length(body))] ++ headers {:proceed, [response: {:response, headers, body}]} end end defmacro __using__(_opts) do quote do import Frank.Path def unquote(:do)(data) do name = Frank.mod(data, :request_uri) IO.puts "calling #{name}" handle(:erlang.list_to_bitstring(name), data) end @before_compile Path end end end defmodule Test do use Frank get "/" do response 200, "<a href='/foo'>go to foo</a>" end get "/foo" do response 200, "foo!" end end Frank.sing(Test)
24.245614
111
0.611071
0396779fe7fb1519215d110ab62757cdc335d559
1,706
ex
Elixir
lib/online_editor_web/endpoint.ex
zzats/online-editor
2532315b40c974fe766e960e0b0933773907906d
[ "MIT" ]
null
null
null
lib/online_editor_web/endpoint.ex
zzats/online-editor
2532315b40c974fe766e960e0b0933773907906d
[ "MIT" ]
null
null
null
lib/online_editor_web/endpoint.ex
zzats/online-editor
2532315b40c974fe766e960e0b0933773907906d
[ "MIT" ]
null
null
null
defmodule OnlineEditorWeb.Endpoint do use Phoenix.Endpoint, otp_app: :online_editor socket "/socket", OnlineEditorWeb.UserSocket # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :online_editor, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt *.json) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head # The session will be stored in the cookie and signed, # this means its contents can be read but not tampered with. # Set :encryption_salt if you would also like to encrypt it. plug Plug.Session, store: :cookie, key: "_online_editor_key", signing_salt: "lk54hjWx" plug OnlineEditorWeb.Router @doc """ Callback invoked for dynamically configuring the endpoint. It receives the endpoint configuration and checks if configuration should be loaded from the system environment. """ def init(_key, config) do if config[:load_from_system_env] do port = System.get_env("PORT") || raise "expected the PORT environment variable to be set" {:ok, Keyword.put(config, :http, [:inet6, port: port])} else {:ok, config} end end end
29.413793
95
0.712778
039677ee053c1f12d778b9fa6fb30ab8823fef9a
4,260
ex
Elixir
lib/level/resolvers/post_connection.ex
denismitr/level
0b01b0e46c252510dd50b3558d987c6f1e0b1da9
[ "Apache-2.0" ]
1
2019-06-11T20:20:32.000Z
2019-06-11T20:20:32.000Z
lib/level/resolvers/post_connection.ex
denismitr/level
0b01b0e46c252510dd50b3558d987c6f1e0b1da9
[ "Apache-2.0" ]
null
null
null
lib/level/resolvers/post_connection.ex
denismitr/level
0b01b0e46c252510dd50b3558d987c6f1e0b1da9
[ "Apache-2.0" ]
null
null
null
defmodule Level.Resolvers.PostConnection do @moduledoc """ A paginated connection for fetching a user's mentioned posts. """ import Ecto.Query, warn: false alias Level.Pagination alias Level.Pagination.Args alias Level.Posts alias Level.Schemas.Group alias Level.Schemas.Space defstruct first: nil, last: nil, before: nil, after: nil, filter: %{ following_state: :all, inbox_state: :all, state: :all }, order_by: %{ field: :posted_at, direction: :desc } @type t :: %__MODULE__{ first: integer() | nil, last: integer() | nil, before: String.t() | nil, after: String.t() | nil, filter: %{ following_state: :is_following | :all, inbox_state: :unread | :read | :dismissed | :undismissed | :all, state: :open | :closed | :all }, order_by: %{ field: :posted_at | :last_pinged_at | :last_activity_at, direction: :asc | :desc } } @doc """ Executes a paginated query for posts. """ @spec get(Space.t() | Group.t(), map(), map()) :: {:ok, Pagination.Result.t()} | {:error, String.t()} def get(parent, args, %{context: %{current_user: user}}) do base_query = user |> build_base_query(parent) |> apply_activity(args) |> apply_following_state(args) |> apply_inbox_state(args) |> apply_state(args) pagination_args = args |> process_args() |> Args.build() query = from(p in subquery(base_query)) Pagination.fetch_result(query, pagination_args) end defp build_base_query(user, %Space{id: space_id}) do from [p, su, g, gu] in Posts.posts_base_query(user), where: p.space_id == ^space_id end defp build_base_query(user, %Group{id: group_id}) do from [p, su, g, gu] in Posts.posts_base_query(user), where: g.id == ^group_id end defp process_args(%{order_by: %{field: :posted_at} = order_by} = args) do %{args | order_by: %{order_by | field: :inserted_at}} end defp process_args(args), do: args defp apply_activity(base_query, %{order_by: %{field: :last_activity_at}}) do from [p, su, g, gu] in base_query, left_join: pl in assoc(p, :post_logs), group_by: p.id, select_merge: %{last_activity_at: max(pl.occurred_at)} end defp apply_activity(base_query, _), do: base_query defp apply_following_state(base_query, %{filter: %{following_state: :is_following}}) do from [p, su, g, gu] in base_query, left_join: pu in assoc(p, :post_users), on: pu.space_user_id == su.id, where: not is_nil(gu.id) or pu.subscription_state == "SUBSCRIBED", group_by: p.id end defp apply_following_state(base_query, _), do: base_query defp apply_inbox_state(base_query, %{filter: %{inbox_state: :unread}}) do from [p, su, g, gu] in base_query, join: pu in assoc(p, :post_users), on: pu.space_user_id == su.id and pu.inbox_state == "UNREAD" end defp apply_inbox_state(base_query, %{filter: %{inbox_state: :read}}) do from [p, su, g, gu] in base_query, join: pu in assoc(p, :post_users), on: pu.space_user_id == su.id and pu.inbox_state == "READ" end defp apply_inbox_state(base_query, %{filter: %{inbox_state: :undismissed}}) do from [p, su, g, gu] in base_query, join: pu in assoc(p, :post_users), on: pu.space_user_id == su.id and (pu.inbox_state == "UNREAD" or pu.inbox_state == "READ") end defp apply_inbox_state(base_query, %{filter: %{inbox_state: :dismissed}}) do from [p, su, g, gu] in base_query, join: pu in assoc(p, :post_users), on: pu.space_user_id == su.id and pu.inbox_state == "DISMISSED" end defp apply_inbox_state(base_query, _), do: base_query defp apply_state(base_query, %{filter: %{state: :open}}) do from [p, su, g, gu] in base_query, where: p.state == "OPEN" end defp apply_state(base_query, %{filter: %{state: :closed}}) do from [p, su, g, gu] in base_query, where: p.state == "CLOSED" end defp apply_state(base_query, _), do: base_query end
30.869565
96
0.610329
0396c4c34d34490b3ad77ab22742597a7c48c429
1,116
ex
Elixir
lib/queuerbackend_web/controllers/queue_controller.ex
ayushpandey8439/QueuerBackend
36195b98e02ee8af2b8ba95b9a73547887efb9ce
[ "MIT" ]
null
null
null
lib/queuerbackend_web/controllers/queue_controller.ex
ayushpandey8439/QueuerBackend
36195b98e02ee8af2b8ba95b9a73547887efb9ce
[ "MIT" ]
null
null
null
lib/queuerbackend_web/controllers/queue_controller.ex
ayushpandey8439/QueuerBackend
36195b98e02ee8af2b8ba95b9a73547887efb9ce
[ "MIT" ]
null
null
null
import Ecto.Query import Jason defmodule QueuerbackendWeb.QueueController do use QueuerbackendWeb, :controller alias Queuerbackend.{Repo,Queue} @spec index(Plug.Conn.t(), any) :: Plug.Conn.t() def index(conn, _params) do fieldMap = [:name , :head, :queuers] query = from q in Queue, select: map( q , ^fieldMap) responseData = Repo.all(query) IO.inspect(responseData) json(conn,%{status: "200",response: responseData }) end def create(conn, params) do query = from(q in Queue, where: [name: ^conn.params["name"]],select: fragment("count(*)")) [count] = Repo.all(query) if count==0 do changeset = Queue.changeset(%Queue{},%{name: params["name"], maxLength: params["maxLength"] , head: params["head"], queuers: String.split(params["queuers"],",")}) IO.inspect(changeset) if changeset.valid? do Repo.insert(changeset) json(conn, %{status: "200", response: "Inserted"}) else json(conn, %{status: "400", error: "Schema Mismatch"}) end else json(conn, %{status: "400", error: "Queue Exists"}) end end end
31.885714
168
0.638889
0396e028f61422a7822e3f998f610e29dac9bbe4
1,558
exs
Elixir
test/constructs/for_test.exs
EddyLane/surface
1f13259cbdf81b5a4740ee13349a48f8b6c54bb5
[ "MIT" ]
1
2020-12-29T10:43:19.000Z
2020-12-29T10:43:19.000Z
test/constructs/for_test.exs
EddyLane/surface
1f13259cbdf81b5a4740ee13349a48f8b6c54bb5
[ "MIT" ]
null
null
null
test/constructs/for_test.exs
EddyLane/surface
1f13259cbdf81b5a4740ee13349a48f8b6c54bb5
[ "MIT" ]
null
null
null
defmodule Surface.Constructs.ForTest do use Surface.ConnCase, async: true defmodule ListProp do use Surface.Component prop prop, :list def render(assigns) do ~H""" List?: {{ is_list(@prop) }} <span :for={{ v <- @prop }}>value: {{inspect(v)}}</span> """ end end test "iterates over the provided list" do alias Surface.Constructs.For html = render_surface do ~H""" <For each={{ fruit <- ["apples", "bananas", "oranges"] }}> <span>{{ fruit }}</span> </For> """ end assert html =~ """ <span>apples</span> <span>bananas</span> <span>oranges</span> """ end test "parser error message contains the correct line" do code = quote do ~H""" <For each={{ fruit <- ["apples", "bananas", "oranges"] }}> <span>The inner content </For> """ end message = ~S(code:2: expected closing tag for "span") assert_raise(Surface.Compiler.ParseError, message, fn -> compile_surface(code) end) end test "compile error message contains the correct line" do code = quote do ~H""" <For each={{ fruit <- ["apples", "bananas", "oranges"] }}> <ListProp prop="some string" /> </For> """ end message = ~S(code:2: invalid value for property "prop". Expected a :list, got: "some string".) assert_raise(CompileError, message, fn -> compile_surface(code) end) end end
22.257143
98
0.537869
0397339468b1cc5cfc3391f190770965b4e72a98
1,088
exs
Elixir
clients/network_connectivity/test/test_helper.exs
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/network_connectivity/test/test_helper.exs
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/network_connectivity/test/test_helper.exs
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. ExUnit.start() defmodule GoogleApi.NetworkConnectivity.TestHelper do defmacro __using__(opts) do quote do use ExUnit.Case, unquote(opts) import GoogleApi.NetworkConnectivity.TestHelper end end def for_scope(scopes) when is_list(scopes), do: for_scope(Enum.join(scopes, " ")) def for_scope(scope) do {:ok, token} = Goth.Token.for_scope(scope) token.token end end
30.222222
83
0.744485
03974cb68e62c0e46f2614252b89430554b679ea
66
ex
Elixir
lib/tnd_web/views/user_reset_password_view.ex
tndrpg/tnd
a9a348ed7ce2f3d8f55046559f9551e2607f3236
[ "0BSD" ]
null
null
null
lib/tnd_web/views/user_reset_password_view.ex
tndrpg/tnd
a9a348ed7ce2f3d8f55046559f9551e2607f3236
[ "0BSD" ]
1
2021-05-11T14:31:58.000Z
2021-05-11T14:31:58.000Z
lib/tnd_web/views/user_reset_password_view.ex
tndrpg/tnd
a9a348ed7ce2f3d8f55046559f9551e2607f3236
[ "0BSD" ]
null
null
null
defmodule TndWeb.UserResetPasswordView do use TndWeb, :view end
16.5
41
0.818182
03974eca72d2930a9e1331c5ea7fa3b59d657b98
1,164
ex
Elixir
lib/events_api/doings/event.ex
gissandrogama/events
1b21b151a336ae5eef8bf1d68f2a792194f21be3
[ "MIT" ]
null
null
null
lib/events_api/doings/event.ex
gissandrogama/events
1b21b151a336ae5eef8bf1d68f2a792194f21be3
[ "MIT" ]
4
2021-02-10T22:04:56.000Z
2021-02-12T22:01:42.000Z
lib/events_api/doings/event.ex
gissandrogama/events
1b21b151a336ae5eef8bf1d68f2a792194f21be3
[ "MIT" ]
1
2021-03-22T13:48:48.000Z
2021-03-22T13:48:48.000Z
defmodule EventsApi.Doings.Event do @moduledoc """ Modulo de schema da tabela `events`, ele possui função que valida as informações de um `map`. """ use Ecto.Schema import Ecto.Changeset alias EventsApi.Accounts.User @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id schema "events" do field :andress, :string field :date_finish, :string field :date_initial, :string field :description, :string field :end_time, :string field :place, :string field :start_time, :string field :title, :string field :url_img, :string belongs_to :user, User timestamps() end @doc false def changeset(event, attrs) do event |> cast(attrs, [ :title, :date_initial, :date_finish, :description, :start_time, :end_time, :place, :andress, :url_img, :user_id ]) |> foreign_key_constraint(:user_id) |> validate_required([ :title, :date_initial, :date_finish, :description, :start_time, :end_time, :place, :andress, :url_img, :user_id ]) end end
20.785714
95
0.615979
03975666ae52ab278d7e2e20a559ea8a5cec7dfb
1,087
exs
Elixir
factories/wood.exs
jdfrens/calctorio
40418e3f7e562c0ade2a672434589727949e0439
[ "MIT" ]
null
null
null
factories/wood.exs
jdfrens/calctorio
40418e3f7e562c0ade2a672434589727949e0439
[ "MIT" ]
null
null
null
factories/wood.exs
jdfrens/calctorio
40418e3f7e562c0ade2a672434589727949e0439
[ "MIT" ]
null
null
null
alias Calctorio.{AssemblyLine, Machine, Recipe} defmodule WoodAssemblyLine do def foo do %AssemblyLine{ root: wood_to_tar_and_petroleum(), lines: [ %AssemblyLine{root: tar_to_solid_fuel()}, %AssemblyLine{root: petroleum_to_solid_fuel()} ] } end def m(recipe) do %Machine{recipe: recipe} end def s(machine, multiplier) do %{machine | speed: multiplier} end def p(machine, multiplier) do %{machine | productivity: multiplier} end def wood_to_tar_and_petroleum do %Recipe{ inputs: [wood: 1], outputs: [tar: 1, petroleum: 30], time: 3 } |> m() |> s(8.75) end def tar_to_solid_fuel do %Recipe{ inputs: [tar: 1], outputs: [solid_fuel: 1], time: 5 } |> m() |> s(8.75) end def petroleum_to_solid_fuel do %Recipe{ inputs: [petroleum: 20], outputs: [solid_fuel: 1], time: 3 } |> m() |> p(1.20) |> s(6.75) end end WoodAssemblyLine.foo() |> AssemblyLine.ratioize() |> AssemblyLine.report() |> IO.puts()
17.532258
54
0.584177
039760cecffdccbe52485d3565e9272dd4d9c029
1,835
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/list_products_in_product_set_response.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/list_products_in_product_set_response.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/list_products_in_product_set_response.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 &quot;License&quot;); # 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 &quot;AS IS&quot; 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.Vision.V1.Model.ListProductsInProductSetResponse do @moduledoc """ Response message for the &#x60;ListProductsInProductSet&#x60; method. ## Attributes - nextPageToken (String.t): Token to retrieve the next page of results, or empty if there are no more results in the list. Defaults to: `null`. - products ([Product]): The list of Products. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :nextPageToken => any(), :products => list(GoogleApi.Vision.V1.Model.Product.t()) } field(:nextPageToken) field(:products, as: GoogleApi.Vision.V1.Model.Product, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.ListProductsInProductSetResponse do def decode(value, options) do GoogleApi.Vision.V1.Model.ListProductsInProductSetResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.ListProductsInProductSetResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.980392
145
0.747684
03976b0282e2b936ead7180c85bb88ba4be28125
5,645
exs
Elixir
test/sanbase/alerts/wallet_movement/trigger_eth_wallet_test.exs
santiment/sanbase2
9ef6e2dd1e377744a6d2bba570ea6bd477a1db31
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
test/sanbase/alerts/wallet_movement/trigger_eth_wallet_test.exs
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
test/sanbase/alerts/wallet_movement/trigger_eth_wallet_test.exs
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Alert.EthWalletTriggerTest do use Sanbase.DataCase, async: false import Mock import Sanbase.Factory alias Sanbase.Model.Project alias Sanbase.Alert.{ UserTrigger, Trigger.EthWalletTriggerSettings, Scheduler } alias Sanbase.Clickhouse.HistoricalBalance setup do Sanbase.Cache.clear_all(:alerts_evaluator_cache) user = insert(:user, user_settings: %{settings: %{alert_notify_telegram: true}}) Sanbase.Accounts.UserSettings.set_telegram_chat_id(user.id, 123_123_123_123) project = Sanbase.Factory.insert(:random_erc20_project) Sanbase.Factory.insert(%Project{name: "eth", slug: "ethereum"}) {:ok, [eth_address]} = Project.eth_addresses(project) trigger_settings1 = %{ type: "eth_wallet", target: %{slug: project.slug}, asset: %{slug: "ethereum"}, channel: "telegram", time_window: "1d", operation: %{amount_up: 25.0} } trigger_settings2 = %{ type: "eth_wallet", target: %{eth_address: eth_address}, asset: %{slug: "ethereum"}, channel: "telegram", time_window: "1d", operation: %{amount_up: 200.0} } trigger_settings3 = %{ type: "eth_wallet", target: %{eth_address: eth_address}, asset: %{slug: "ethereum"}, channel: "telegram", time_window: "1d", operation: %{amount_down: 50.0} } {:ok, _} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "12h", settings: trigger_settings1 }) {:ok, _} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "1d", settings: trigger_settings2 }) {:ok, _} = UserTrigger.create_user_trigger(user, %{ title: "Generic title", is_public: true, cooldown: "1d", settings: trigger_settings3 }) [ project: project, eth_address: eth_address ] end test "triggers eth wallet signal when balance increases", context do test_pid = self() with_mocks [ {Sanbase.Telegram, [:passthrough], send_message: fn _user, text -> send(test_pid, {:telegram_to_self, text}) :ok end}, {HistoricalBalance, [:passthrough], balance_change: fn _, _, _, _ -> {:ok, [ %{ address: context.eth_address, balance_start: 20, balance_end: 70, balance_change_amount: 50, balance_change_percent: 250.0 } ]} end} ] do Scheduler.run_alert(EthWalletTriggerSettings) assert_receive({:telegram_to_self, message}) assert message =~ "**#{context.project.name}**'s ethereum balance increased by 50" assert message =~ "was: 20, now: 70" end end test "triggers eth wallet and address alerts when balance increases", context do test_pid = self() with_mocks [ {Sanbase.Telegram, [:passthrough], send_message: fn _user, text -> send(test_pid, {:telegram_to_self, text}) :ok end}, {HistoricalBalance, [:passthrough], balance_change: fn _, _, _, _ -> {:ok, [ %{ address: context.eth_address, balance_start: 20, balance_end: 300, balance_change_amount: 280, balance_change_percent: 1400.0 } ]} end} ] do Scheduler.run_alert(EthWalletTriggerSettings) assert_receive({:telegram_to_self, message1}) assert_receive({:telegram_to_self, message2}) # Plain sort won't work as depends on the randomly generated project name # Sorting on wheter there is `address` substring is deterministic sorted_messages = Enum.sort_by([message1, message2], &String.contains?(&1, "address")) assert Enum.at(sorted_messages, 0) =~ "**#{context.project.name}**'s ethereum balance increased by 280" assert Enum.at(sorted_messages, 1) =~ "The address #{context.eth_address}'s ethereum balance increased by 280" end end test "triggers address signal when balance decreases", context do test_pid = self() with_mocks [ {Sanbase.Telegram, [:passthrough], send_message: fn _user, text -> send(test_pid, {:telegram_to_self, text}) :ok end}, {HistoricalBalance, [:passthrough], balance_change: fn _, _, _, _ -> {:ok, [ %{ address: context.eth_address, balance_start: 100, balance_end: 0, balance_change_amount: -100, balance_change_percent: -100.0 } ]} end} ] do Scheduler.run_alert(EthWalletTriggerSettings) assert_receive({:telegram_to_self, message}) assert message =~ "🔔The address #{context.eth_address}'s ethereum balance decreased by 100" end end test "behavior is correct in case of database error" do test_pid = self() with_mocks [ {Sanbase.Telegram, [:passthrough], send_message: fn _user, text -> send(test_pid, {:telegram_to_self, text}) :ok end}, {HistoricalBalance, [:passthrough], balance_change: fn _, _, _, _ -> {:error, "Something bad happened"} end} ] do Scheduler.run_alert(EthWalletTriggerSettings) refute_receive({:telegram_to_self, _}) end end end
26.753555
92
0.590434
0397e99d36eb00d795f268746e4aebf014e545e5
609
exs
Elixir
mix.exs
qwertystop/scrub
d3dae0d705c3453ea855f56ce7d594dfb78c5394
[ "MIT" ]
null
null
null
mix.exs
qwertystop/scrub
d3dae0d705c3453ea855f56ce7d594dfb78c5394
[ "MIT" ]
null
null
null
mix.exs
qwertystop/scrub
d3dae0d705c3453ea855f56ce7d594dfb78c5394
[ "MIT" ]
null
null
null
defmodule Scrub.Mixfile do use Mix.Project def project do [apps_path: "apps", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps()] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options. # # Dependencies listed here are available only for this project # and cannot be accessed from applications inside the apps folder defp deps do [] end end
22.555556
79
0.638752
0397eddc60e2aea88780f7cdde10dd333deda345
1,516
ex
Elixir
.clext/saml2aws.ex
peterwwillis/clinst
0fff3e125ca3dbb1bdba2d4dde96170c8b644a1f
[ "MIT" ]
null
null
null
.clext/saml2aws.ex
peterwwillis/clinst
0fff3e125ca3dbb1bdba2d4dde96170c8b644a1f
[ "MIT" ]
null
null
null
.clext/saml2aws.ex
peterwwillis/clinst
0fff3e125ca3dbb1bdba2d4dde96170c8b644a1f
[ "MIT" ]
null
null
null
#!/usr/bin/env sh set -eu [ "${DEBUG:-0}" = "1" ] && set -x ### Extension-specific variables CLINST_E_NAME="${CLINST_E_NAME:-saml2aws}" CLINST_E_REV="0.3.0" CLINST_E_BIN_NAME="${CLINST_E_BIN_NAME:-$CLINST_E_NAME}" CLINST_E_DLFILE="${CLINST_E_DLFILE:-$CLINST_E_NAME.tar.gz}" CLINST_E_INSTDIR="${CLINST_E_INSTDIR:-$(pwd)}" CLINST_E_OS="${CLINST_E_OS:-linux}" CLINST_E_ARCH="${CLINST_E_ARCH:-amd64}" CLINST_E_GHREPOAPI="https://api.github.com/repos/Versent/$CLINST_E_NAME" CLINST_E_BASEURL="https://github.com/Versent/$CLINST_E_NAME/releases/download/v%s/$CLINST_E_NAME""_%s_%s_%s.tar.gz" CLINST_E_BASEURL_ARGS='"${CLINST_E_VERSION}" "${CLINST_E_VERSION}" "${CLINST_E_OS}" "${CLINST_E_ARCH}"' export CLINST_E_NAME CLINST_E_REV CLINST_E_BIN_NAME CLINST_E_DLFILE ### Extension-specific functions _ext_versions () { clinst -E "$CLINST_E_NAME" -X versions_ghtags "$CLINST_E_GHREPOAPI" ; } _ext_unpack () { clinst -E "$CLINST_E_NAME" -X unpack_untar "/usr/bin" ; } ### The rest of this doesn't need to be modified _ext_variables () { set | grep '^CLINST_E_' ; } _ext_help () { printf "Usage: $0 CMD\n\nCommands:\n%s\n" "$(grep -e "^_ext_.* ()" "$0" | awk '{print $1}' | sed -e 's/_ext_//;s/^/ /g' | tr _ -)" ; } if [ $# -lt 1 ] then _ext_help ; exit 1 else cmd="$1"; shift func="_ext_$(printf "%s\n" "$cmd" | tr - _)" [ -n "${CLINST_DIR:-}" -a -n "${CLINST_E_ENVIRON:-}" ] && [ -d "$CLINST_DIR/$CLINST_E_ENVIRON" ] && cd "$CLINST_DIR/$CLINST_E_ENVIRON" case "$cmd" in *) $func "$@" ;; esac fi
47.375
150
0.675462
0397ee5adb7e13d56cf63733a2b657595182d5f2
855
ex
Elixir
lib/blog/endpoint.ex
cuongkta/login_logout_elixir
71ad24e1077402fa719ce52fb3bc2a77510b1b86
[ "Apache-2.0" ]
null
null
null
lib/blog/endpoint.ex
cuongkta/login_logout_elixir
71ad24e1077402fa719ce52fb3bc2a77510b1b86
[ "Apache-2.0" ]
null
null
null
lib/blog/endpoint.ex
cuongkta/login_logout_elixir
71ad24e1077402fa719ce52fb3bc2a77510b1b86
[ "Apache-2.0" ]
null
null
null
defmodule Blog.Endpoint do use Phoenix.Endpoint, otp_app: :blog # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :blog, gzip: false, only: ~w(css images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head plug Plug.Session, store: :cookie, key: "_blog_key", signing_salt: "6UV4y9bB" plug Blog.Router end
23.75
65
0.694737
0397fd94441f0a6649891b69c83332d78b85eeb0
1,489
ex
Elixir
clients/double_click_bid_manager/lib/google_api/double_click_bid_manager/v1/model/download_line_items_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/double_click_bid_manager/lib/google_api/double_click_bid_manager/v1/model/download_line_items_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/double_click_bid_manager/lib/google_api/double_click_bid_manager/v1/model/download_line_items_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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.DoubleClickBidManager.V1.Model.DownloadLineItemsResponse do @moduledoc """ Download line items response. ## Attributes - lineItems (String): Retrieved line items in CSV format. For more information about file formats, see Entity Write File Format. Defaults to: `null`. """ defstruct [ :"lineItems" ] end defimpl Poison.Decoder, for: GoogleApi.DoubleClickBidManager.V1.Model.DownloadLineItemsResponse do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.DoubleClickBidManager.V1.Model.DownloadLineItemsResponse do def encode(value, options) do GoogleApi.DoubleClickBidManager.V1.Deserializer.serialize_non_nil(value, options) end end
32.369565
152
0.768972
0397ffea56bcfea6566c740988faec702135cd0f
1,949
exs
Elixir
config/prod.exs
wmnnd/phoenix_live_view_collection
61e0acf0cda8533c185edfc6011457c466ab5e09
[ "MIT" ]
null
null
null
config/prod.exs
wmnnd/phoenix_live_view_collection
61e0acf0cda8533c185edfc6011457c466ab5e09
[ "MIT" ]
null
null
null
config/prod.exs
wmnnd/phoenix_live_view_collection
61e0acf0cda8533c185edfc6011457c466ab5e09
[ "MIT" ]
null
null
null
import Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :phoenix_live_view_collection, LiveViewCollectionWeb.Endpoint, server: true, cache_static_manifest: "priv/static/cache_manifest.json", force_ssl: [rewrite_on: [:x_forwarded_proto]] # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :phoenix_live_view_collection, LiveViewCollectionWeb.Endpoint, # ..., # url: [host: "example.com", port: 443], # https: [ # ..., # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :phoenix_live_view_collection, LiveViewCollectionWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`.
36.773585
75
0.721396
03980e5e1115a4d2e7afbb92e18c7a9d7d9fbd53
419
exs
Elixir
mix.exs
CodeSteak/setup-plug-with-certbot
b7d33f58b755ed5cbee518e735823d770e943367
[ "Unlicense" ]
null
null
null
mix.exs
CodeSteak/setup-plug-with-certbot
b7d33f58b755ed5cbee518e735823d770e943367
[ "Unlicense" ]
null
null
null
mix.exs
CodeSteak/setup-plug-with-certbot
b7d33f58b755ed5cbee518e735823d770e943367
[ "Unlicense" ]
null
null
null
defmodule Certbot.MixProject do use Mix.Project def project do [ app: :certbot, version: "0.1.0", elixir: "~> 1.6", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end defp deps do [ {:plug, ">= 1.5.0"} ] end end
15.518519
59
0.541766
0398b2306024a2cdaa05968f8fce2003990ac336
776
exs
Elixir
mix.exs
tanguilp/attribute_repository_mnesia
9e8d6284716bbbe8d24b6f551cd295fbaf5d7674
[ "Apache-2.0" ]
1
2022-01-27T11:48:58.000Z
2022-01-27T11:48:58.000Z
mix.exs
tanguilp/attribute_repository_mnesia
9e8d6284716bbbe8d24b6f551cd295fbaf5d7674
[ "Apache-2.0" ]
null
null
null
mix.exs
tanguilp/attribute_repository_mnesia
9e8d6284716bbbe8d24b6f551cd295fbaf5d7674
[ "Apache-2.0" ]
null
null
null
defmodule AttributeRepositoryMnesia.MixProject do use Mix.Project def project do [ app: :attribute_repository_mnesia, version: "0.2.0", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps(), docs: [ main: "readme", extras: ["README.md"] ] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger, :mnesia] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:attribute_repository, github: "tanguilp/attribute_repository", tag: "v0.2.0"}, {:dialyxir, "~> 1.0.0-rc.4", only: [:dev], runtime: false}, {:ex_doc, "~> 0.19", only: :dev, runtime: false} ] end end
22.823529
86
0.582474
0398d9ac2d3027f437080c9c6bb390262a5b1639
3,597
ex
Elixir
lib/exhort/sat/constraint.ex
josejimenezjr0/exhort
07c9b735d82a96d6437554f51229c38cf287b39f
[ "Apache-2.0" ]
null
null
null
lib/exhort/sat/constraint.ex
josejimenezjr0/exhort
07c9b735d82a96d6437554f51229c38cf287b39f
[ "Apache-2.0" ]
null
null
null
lib/exhort/sat/constraint.ex
josejimenezjr0/exhort
07c9b735d82a96d6437554f51229c38cf287b39f
[ "Apache-2.0" ]
null
null
null
defmodule Exhort.SAT.Constraint do @moduledoc """ A constraint on the model. The binary constraints are: ``` :< | :<= | :== | :>= | :> | :"abs==" ``` The list constraints are: ``` :"all!=" | :no_overlap ``` The expression must include a boundary: `<`, `<=`, `==`, `>=`, `>`. ``` x < y ``` The components of the expressoin may be simple mathematical expressions, including the use of `+` and `*`: ``` x * y = z ``` The `sum/1` function may be used to sum over a series of terms: ``` sum(x + y) == z ``` The variables in the expression are defined in the model and do not by default reference the variables in Elixir scope. The pin operator, `^` may be used to reference a scoped Elixir variable. For example, where `x` is a model variable (e.g., `def_int_var(x, {0, 3}`)) and `y` is an Elixir variable (e.g., `y = 2`): ``` x < ^y ``` A `for` comprehension may be used to generate list values: ``` sum(for {x, y} <- ^list, do: x * y) == z ``` As a larger example: ``` y = 20 z = [{0, 1}, {2, 3}, {4, 5}] Builder.new() |> Builder.def_int_var(x, {0, 3}) |> Builder.constrain(sum(for {a, b} <- ^z, do: ^a * ^b) < y) |> Builder.build() ... ``` """ alias Exhort.SAT.DSL alias __MODULE__ @type constraint :: :< | :<= | :== | :>= | :> | :"abs==" | :"all!=" | :no_overlap @type t :: %__MODULE__{} defstruct [:res, :defn] @doc """ Define a bounded constraint. """ defmacro new(expr, opts \\ []) do expr = case expr do {:==, m1, [lhs, {:abs, _m2, [var]}]} -> {:"abs==", m1, [lhs, var]} expr -> expr end {op, _, [lhs, rhs]} = expr lhs = DSL.transform_expression(lhs) rhs = DSL.transform_expression(rhs) opts = Enum.map(opts, &DSL.transform_expression(&1)) quote do %Constraint{defn: {unquote(lhs), unquote(op), unquote(rhs), unquote(opts)}} end end @doc """ Define a constraint on the model using variables. - `constraint` is specified as an atom. See `Exhort.SAT.Constraint`. - `lhs` and `rhs` may each either be an atom, string, `LinearExpression`, or an existing `BoolVar` or `IntVar`. - `opts` may specify a restriction on the constraint: - `if: BoolVar` specifies that a constraint only takes effect if `BoolVar` is true - `unless: BoolVar` specifies that a constraint only takes effect if `BoolVar` is false - `:==` - `lhs == rhs` - `:abs==` - `lhs == abs(rhs)` - `:"all!="` - Require each element the provide list has a different value from all the rest """ @spec constrain( lhs :: atom() | String.t() | BoolVar.t() | IntVar.t() | LinearExpression.t(), constraint :: Constraint.constraint(), rhs :: atom() | String.t() | BoolVar.t() | IntVar.t() | LinearExpression.t(), opts :: [{:if, BoolVar.t()}] | [{:unless, BoolVar.t()}] ) :: Builder.t() def constrain(lhs, constraint, rhs, opts \\ []) do %Constraint{defn: {lhs, constraint, rhs, opts}} end @doc """ Create a constraint that ensures no overlap among the variables. """ @spec no_overlap(list(), Keyword.t()) :: Exhort.SAT.Constraint.t() def no_overlap(list, opts \\ []) do %Constraint{defn: {:no_overlap, list, opts}} end @doc """ Create a constraint that ensures each item in the list is different in the solution. """ @spec all_different(list(), Keyword.t()) :: Exhort.SAT.Constraint.t() def all_different(list, opts \\ []) do %Constraint{defn: {:"all!=", list, opts}} end end
25.330986
87
0.573812
0398e886bd80ff98e509238687e1cda99b3750a7
1,018
ex
Elixir
test/support/channel_case.ex
openregister/show-the-mess
c164420b246c6bf4df15911dd58c6902132dc4e0
[ "MIT" ]
null
null
null
test/support/channel_case.ex
openregister/show-the-mess
c164420b246c6bf4df15911dd58c6902132dc4e0
[ "MIT" ]
null
null
null
test/support/channel_case.ex
openregister/show-the-mess
c164420b246c6bf4df15911dd58c6902132dc4e0
[ "MIT" ]
1
2021-04-11T08:29:41.000Z
2021-04-11T08:29:41.000Z
defmodule ShowTheMess.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest alias ShowTheMess.Repo import Ecto import Ecto.Changeset import Ecto.Query # The default endpoint for testing @endpoint ShowTheMess.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(ShowTheMess.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(ShowTheMess.Repo, {:shared, self()}) end :ok end end
23.136364
73
0.706287
039914aaabed36aecf37dde4160c7ec39dc08cd4
250
exs
Elixir
priv/repo/migrations/20180107204841_create_categories.exs
allen-garvey/block-quote-phoenix
5c0f5d16daf6bb515a8f1846c3e4311b368a7bdb
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
apps/blockquote/priv/repo/migrations/20180107204841_create_categories.exs
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
apps/blockquote/priv/repo/migrations/20180107204841_create_categories.exs
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
null
null
null
defmodule Blockquote.Repo.Migrations.CreateCategories do use Ecto.Migration def change do create table(:categories) do add :name, :string, null: false timestamps() end create unique_index(:categories, [:name]) end end
19.230769
56
0.696
03995258e623a41b39e10fc27a79b98a12d5bdd2
1,284
exs
Elixir
mix.exs
satoren/libcluster_ec2
aa035c508d41c4667b865cc4c5f41f608311a280
[ "MIT" ]
78
2017-07-26T13:18:52.000Z
2021-12-17T21:27:40.000Z
mix.exs
satoren/libcluster_ec2
aa035c508d41c4667b865cc4c5f41f608311a280
[ "MIT" ]
17
2017-07-25T14:57:03.000Z
2022-03-05T04:09:41.000Z
mix.exs
satoren/libcluster_ec2
aa035c508d41c4667b865cc4c5f41f608311a280
[ "MIT" ]
27
2017-10-24T13:54:12.000Z
2022-03-02T01:24:37.000Z
defmodule ClusterEC2.Mixfile do use Mix.Project def project do [ app: :libcluster_ec2, version: "0.6.0", elixir: "~> 1.4", name: "libcluster_ec2", source_url: "https://github.com/kyleaa/libcluster_ec2", homepage_url: "https://github.com/kyleaa/libcluster_ec2", description: description(), build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), 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 [ {:libcluster, "~> 2.0 or ~> 3.0"}, {:ex_aws, "~> 2.0"}, {:ex_aws_ec2, "~> 2.0"}, {:sweet_xml, "~> 0.6"}, {:hackney, "~> 1.8"}, {:poison, ">= 1.0.0"}, {:tesla, "~> 1.0"}, {:ex_doc, ">= 0.0.0", only: :dev} ] end defp description do """ EC2 clustering strategy for libcluster """ end def package do [ maintainers: ["Kyle Anderson"], licenses: ["MIT License"], links: %{ "GitHub" => "https://github.com/kyleaa/libcluster_ec2.git" } ] end end
22.526316
66
0.558411
039958be1256f697db61e29eaf2122f97c53bd4e
146
ex
Elixir
web/controllers/page_controller.ex
jespr/ex_blog_example
0a014d4b88b224210a7e15d7c60521aff05059c9
[ "Unlicense" ]
null
null
null
web/controllers/page_controller.ex
jespr/ex_blog_example
0a014d4b88b224210a7e15d7c60521aff05059c9
[ "Unlicense" ]
null
null
null
web/controllers/page_controller.ex
jespr/ex_blog_example
0a014d4b88b224210a7e15d7c60521aff05059c9
[ "Unlicense" ]
null
null
null
defmodule BlogExample.PageController do use BlogExample.Web, :controller def index(conn, _params) do render conn, "index.html" end end
18.25
39
0.746575
03996a1cd37e4c026ff8c342e316bbb7e936f386
626
ex
Elixir
web/models/request.ex
damonkelley/requestbin
1f59df73ad3e47e74ba18a2987bd0b0cce262a13
[ "MIT" ]
4
2016-05-20T04:40:21.000Z
2017-12-20T12:54:55.000Z
web/models/request.ex
damonkelley/requestbin
1f59df73ad3e47e74ba18a2987bd0b0cce262a13
[ "MIT" ]
null
null
null
web/models/request.ex
damonkelley/requestbin
1f59df73ad3e47e74ba18a2987bd0b0cce262a13
[ "MIT" ]
null
null
null
defmodule RequestBin.Request do use RequestBin.Web, :model use Ecto.Model.Callbacks schema "requests" do field :method field :headers, :map field :body, :binary field :remote_ip belongs_to :bin, RequestBin.Bin timestamps end @required_fields ~w(method) @optional_fields ~w(headers body remote_ip) @doc """ Creates a changeset based on the `model` and `params`. If no params are provided, an invalid changeset is returned with no validation performed. """ def changeset(model, params \\ :empty) do model |> cast(params, @required_fields, @optional_fields) end end
21.586207
61
0.698083
039984b7cb2fc939e7af529a4d412691dce79429
1,960
exs
Elixir
test/validator_test.exs
Zac-Garby/ultradark_core
639f269e9a416ea034df78ac1c24703a23457840
[ "MIT" ]
1
2018-06-28T20:34:05.000Z
2018-06-28T20:34:05.000Z
test/validator_test.exs
Zac-Garby/ultradark_core
639f269e9a416ea034df78ac1c24703a23457840
[ "MIT" ]
null
null
null
test/validator_test.exs
Zac-Garby/ultradark_core
639f269e9a416ea034df78ac1c24703a23457840
[ "MIT" ]
null
null
null
defmodule ValidatorTest do alias UltraDark.Validator alias UltraDark.Blockchain.Block alias UltraDark.KeyPair alias UltraDark.Transaction use ExUnit.Case, async: true setup _ do on_exit(fn -> File.rm_rf!(".keys") end) :ok end test "refutes blocks with invalid difficulties" do difficulty = 5 block = Block.initialize() |> Block.initialize() assert {:error, _} = Validator.valid_difficulty?(block, difficulty) end test "allows blocks with valid difficulties" do block = Block.initialize() |> Block.initialize() assert :ok = Validator.valid_difficulty?(block, block.difficulty) end test "can validate a single transaction" do {public, private} = KeyPair.create_keypair() expected_valid_tx = %Transaction{ inputs: [ %{ txoid: "a", signature: KeyPair.sign(private, "a") |> Base.encode16(), addr: public |> Base.encode16() }, %{ txoid: "b", signature: KeyPair.sign(private, "b") |> Base.encode16(), addr: public |> Base.encode16() }, %{ txoid: "c", signature: KeyPair.sign(private, "c") |> Base.encode16(), addr: public |> Base.encode16() } ] } expected_invalid_tx = %Transaction{ inputs: [ %{ txoid: "a", signature: KeyPair.sign(private, "a") |> Base.encode16(), addr: "a fake address!" |> Base.encode16() }, %{ txoid: "b", signature: KeyPair.sign(private, "b") |> Base.encode16(), addr: "unencoded fake address!" }, %{ txoid: "c", signature: KeyPair.sign(private, "c") |> Base.encode16(), addr: public |> Base.encode16() } ] } assert Validator.valid_transaction?(expected_valid_tx) refute Validator.valid_transaction?(expected_invalid_tx) end end
25.128205
71
0.569388
0399b676dde7d978e040a7dd7ceb8f9fa7c1ba41
2,590
exs
Elixir
test/vutuv/sessions_test.exs
vutuv/vutuv
174706cdaf28cef24e1cc06bec0884c25f2412be
[ "MIT" ]
309
2016-05-03T17:16:23.000Z
2022-03-01T09:30:22.000Z
test/vutuv/sessions_test.exs
vutuv/vutuv
174706cdaf28cef24e1cc06bec0884c25f2412be
[ "MIT" ]
662
2016-04-27T07:45:18.000Z
2022-01-05T07:29:19.000Z
test/vutuv/sessions_test.exs
vutuv/vutuv
174706cdaf28cef24e1cc06bec0884c25f2412be
[ "MIT" ]
40
2016-04-27T07:46:22.000Z
2021-12-31T05:54:34.000Z
defmodule Vutuv.SessionsTest do use Vutuv.DataCase alias Vutuv.{UserProfiles, Sessions, Sessions.Session} setup do attrs = %{ "email" => "fred@example.com", "password" => "reallyHard2gue$$", "gender" => "male", "full_name" => "fred frederickson" } {:ok, user} = UserProfiles.create_user(attrs) {:ok, user: user} end def fixture(:session, attrs) do {:ok, session} = Sessions.create_session(attrs) session end describe "read session data" do test "list_sessions/1 returns all of a user's sessions", %{user: user} do session = fixture(:session, %{user_id: user.id}) assert Sessions.list_sessions(user) == [session] end test "get returns the session with given id", %{user: user} do session = fixture(:session, %{user_id: user.id}) assert Sessions.get_session(session.id) == session end test "change_session/1 returns a session changeset", %{user: user} do session = fixture(:session, %{user_id: user.id}) assert %Ecto.Changeset{} = Sessions.change_session(session) end end describe "write session data" do test "create_session/1 with valid data creates a session", %{user: user} do create_attrs = %{user_id: user.id} assert {:ok, %Session{} = session} = Sessions.create_session(create_attrs) assert session.user_id == user.id assert DateTime.diff(session.expires_at, DateTime.utc_now()) == 86400 end test "create_session/1 with invalid data returns error changeset" do invalid_attrs = %{user_id: nil} assert {:error, %Ecto.Changeset{}} = Sessions.create_session(invalid_attrs) end test "create_session/1 with custom max_age / expiry time", %{user: user} do create_attrs = %{user_id: user.id, max_age: 7200} assert {:ok, %Session{} = session} = Sessions.create_session(create_attrs) assert session.user_id == user.id assert DateTime.diff(session.expires_at, DateTime.utc_now()) == 7200 end end describe "delete session data" do test "delete_session/1 deletes the session", %{user: user} do session = fixture(:session, %{user_id: user.id}) assert {:ok, %Session{}} = Sessions.delete_session(session) refute Sessions.get_session(session.id) end test "delete_user_sessions/1 deletes all of a user's sessions", %{user: user} do fixture(:session, %{user_id: user.id}) fixture(:session, %{user_id: user.id}) assert {2, _} = Sessions.delete_user_sessions(user) assert Sessions.list_sessions(user) == [] end end end
34.078947
84
0.663707
0399c1f616b837d44491f4b943ea94745c61d881
1,321
ex
Elixir
lib/dbfs/crypto.ex
sunnys/dbfs
bf0e01b969d1107d12b8b7c0130dad17187b027b
[ "MIT" ]
57
2018-01-22T22:42:16.000Z
2022-02-18T05:20:25.000Z
lib/dbfs/crypto.ex
sunnys/dbfs
bf0e01b969d1107d12b8b7c0130dad17187b027b
[ "MIT" ]
2
2018-05-14T20:50:41.000Z
2021-12-12T18:15:59.000Z
lib/dbfs/crypto.ex
sunnys/dbfs
bf0e01b969d1107d12b8b7c0130dad17187b027b
[ "MIT" ]
15
2017-11-11T04:25:04.000Z
2022-03-07T04:55:19.000Z
defmodule DBFS.Crypto do alias DBFS.Block alias DBFS.JSON @sign_fields [:data, :type, :prev, :timestamp] @hash_fields [:creator, :signature | @sign_fields] @doc "Calculate a block's hash" def hash(block) do block |> JSON.encode(@hash_fields) |> sha256 end def hash!(block) do %{ block | hash: hash(block) } end @doc "Sign block data using a private key" def sign(block, private_key) do block |> JSON.encode(@sign_fields) |> RsaEx.sign(private_key) |> elem(1) |> encode end def sign!(block, private_key) do block |> Map.put(:creator, public_key(private_key)) |> Map.put(:signature, sign(block, private_key)) end @doc "Verify a block using the public key present in it" def verify(block) do sign = decode(block.signature) key = decode(block.creator) {:ok, valid} = block |> JSON.encode(@sign_fields) |> RsaEx.verify(sign, key) if valid, do: :ok, else: :invalid end # Helpers def sha256(binary) do :crypto.hash(:sha256, binary) |> encode end def public_key(private_key) do private_key |> RsaEx.generate_public_key |> elem(1) |> encode end def encode(binary), do: Base.encode16(binary) def decode(binary), do: Base.decode16!(binary) end
17.851351
58
0.626041
0399e731f58aeee6be30386c3dd5d292ed515733
16,414
ex
Elixir
lib/hex/remote_converger.ex
hrzndhrn/hex
f74e2ed979e74130bdc4a6974660aa986333f33f
[ "Apache-2.0" ]
824
2015-01-05T09:12:36.000Z
2022-03-28T12:02:29.000Z
lib/hex/remote_converger.ex
hrzndhrn/hex
f74e2ed979e74130bdc4a6974660aa986333f33f
[ "Apache-2.0" ]
737
2015-01-01T05:48:46.000Z
2022-03-29T12:56:12.000Z
lib/hex/remote_converger.ex
hrzndhrn/hex
f74e2ed979e74130bdc4a6974660aa986333f33f
[ "Apache-2.0" ]
220
2015-03-14T17:55:11.000Z
2022-03-23T22:17:07.000Z
defmodule Hex.RemoteConverger do @moduledoc false @behaviour Mix.RemoteConverger alias Hex.Registry.Server, as: Registry def post_converge() do Hex.UpdateChecker.check() if Hex.State.get(:print_sponsored_tip) do Hex.Shell.info( "You have added/upgraded packages you could sponsor, " <> "run `mix hex.sponsor` to learn more" ) Hex.State.put(:print_sponsored_tip, false) end Registry.close() end def remote?(dep) do !!dep.opts[:hex] end def converge(deps, lock) do Registry.open() # We cannot use given lock here, because all deps that are being # converged have been removed from the lock by Mix # We need the old lock to get the children of Hex packages old_lock = Mix.Dep.Lock.read() top_level = Hex.Mix.top_level(deps) overridden_map = Hex.Mix.overridden_deps(deps) flat_deps = Hex.Mix.flatten_deps(deps, overridden_map) requests = Hex.Mix.deps_to_requests(flat_deps) [ Hex.Mix.packages_from_lock(lock), Hex.Mix.packages_from_lock(old_lock), packages_from_requests(requests) ] |> Enum.concat() |> verify_prefetches() |> Registry.prefetch() locked = prepare_locked(lock, old_lock, deps) verify_lock(lock) verify_deps(deps, top_level) verify_input(requests, locked) repos = repo_overrides(deps) top_level = Enum.map(top_level, &Atom.to_string/1) Hex.Shell.info("Resolving Hex dependencies...") {:ok, pid} = Task.start_link(fn -> receive do :done -> :ok after 30_000 -> print_slow_resolver() end end) result = Hex.Resolver.resolve(Registry, requests, top_level, repos, locked, overridden_map) send(pid, :done) case result do {:ok, resolved} -> print_success(resolved, locked, old_lock) verify_resolved(resolved, old_lock) new_lock = Hex.Mix.to_lock(resolved) Hex.SCM.prefetch(new_lock) lock_merge(lock, new_lock) {:error, {:version, message}} -> resolver_version_failed(message) {:error, {:repo, message}} -> resolver_repo_failed(message) end after if Version.compare(System.version(), "1.4.0") == :lt do Registry.persist() end end defp print_slow_resolver() do Hex.Shell.warn(""" The dependency resolver is taking more than 30 seconds. This typically \ happens when Hex cannot find a suitable set of dependencies that match \ your requirements. Here are some suggestions: 1. Do not delete mix.lock. If you want to update some dependencies, \ do mix deps.update dep1 dep2 dep3 2. Tighten up your dependency requirements to the latest version. \ Instead of {:my_dep, ">= 1.0.0"}, try {:my_dep, "~> 3.6"} """) end defp repo_overrides(deps) do for dep <- deps, dep.top_level, into: %{}, do: {dep.opts[:hex], dep.opts[:repo]} end defp packages_from_requests(deps) do Enum.map(deps, fn {repo, package, _app, _req, _from} -> {repo, package} end) end defp lock_merge(old, new) do Map.merge(old, new, fn _key, old_tuple, new_tuple -> if lock_tuple_needs_update?(old_tuple, new_tuple) do new_tuple else old_tuple end end) end defp lock_tuple_needs_update?(old_tuple, new_tuple) do old_info = Hex.Utils.lock(old_tuple) new_info = Hex.Utils.lock(new_tuple) not (old_info != nil and new_info != nil and old_info.name == new_info.name and old_info.version == new_info.version and old_info.inner_checksum == new_info.inner_checksum and old_info.outer_checksum == new_info.outer_checksum and old_info.repo == new_info.repo) end defp resolver_version_failed(message) do Hex.Shell.info("\n" <> message) Mix.raise( "Hex dependency resolution failed, change the version " <> "requirements of your dependencies or unlock them (by " <> "using mix deps.update or mix deps.unlock). If you are " <> "unable to resolve the conflicts you can try overriding " <> "with {:dependency, \"~> 1.0\", override: true}" ) end defp resolver_repo_failed(message) do Hex.Shell.info("\n" <> message) Mix.raise( "Hex dependency resolution failed because of repo conflicts. " <> "You can override the repo by adding it as a dependency " <> "{:dependency, \"~> 1.0\", repo: \"my_repo\"}" ) end def deps(%Mix.Dep{app: app}, lock) do case Hex.Utils.lock(lock[app]) do %{name: name, version: version, deps: nil, repo: repo} -> Registry.open() Registry.prefetch([{repo, name}]) get_deps(repo, name, version) %{deps: deps} -> deps nil -> [] end end defp get_deps(repo, name, version) do deps = Registry.deps(repo, name, version) || [] for {repo, name, app, req, optional} <- deps do app = String.to_atom(app) opts = [optional: optional, hex: name, repo: repo] # Support old packages where requirement could be missing if req do {app, req, opts} else {app, opts} end end end defp verify_deps(deps, top_level) do Enum.each(deps, fn dep -> if dep.app in top_level and dep.scm == Hex.SCM and dep.requirement == nil do Hex.Shell.warn( "#{dep.app} is missing its version requirement, " <> "use \">= 0.0.0\" if it should match any version" ) end end) end defp verify_input(requests, locked) do Enum.each(requests, fn {repo, name, _app, req, from} -> verify_package_req(repo, name, req, from) end) Enum.each(locked, fn {repo, name, _app, req} -> verify_package_req(repo, name, req, "mix.lock") end) end defp verify_package_req(repo, name, req, from) do versions = Registry.versions(repo, name) unless versions do Mix.raise("No package with name #{name} (from: #{from}) in registry") end if req != nil and Hex.Version.parse_requirement(req) == :error do Mix.raise( "Required version #{inspect(req)} for package #{name} is incorrectly specified (from: #{from})" ) end if req != nil and not Enum.any?(versions, &Hex.Version.match?(&1, req)) do Mix.raise( "No matching version for #{name} #{req} (from: #{from}) in registry#{matching_versions_message(versions, req)}" ) end end defp matching_versions_message(versions, req) do versions = Enum.map(versions, &Hex.Version.parse!/1) pre_versions = matching_pre_versions(versions, req) if pre_versions != [] do "\n\nWhile there is no package matching the requirement above, there are pre-releases available:\n\n" <> Enum.map_join(pre_versions, "\n", &" * #{&1}") <> "\n\nIn order to match any of them, you need to include the \"-pre\" suffix in your requirement, " <> "where \"pre\" is one of the suffixes listed above." else latest = List.last(versions) "\n\nThe latest version is: #{latest}" end end defp matching_pre_versions(versions, req) do for version <- versions, version.pre != [], Hex.Version.match?(%{version | pre: []}, req) do version end end defp print_success(resolved, locked, old_lock) do previously_locked_versions = dep_info_from_lock(old_lock) resolved = resolve_dependencies(resolved, locked) if map_size(resolved) != 0 do Hex.Shell.info("Dependency resolution completed:") dep_changes = group_dependency_changes(resolved, previously_locked_versions) Enum.each(dep_changes, fn {mod, deps} -> unless length(deps) == 0, do: print_category(mod) print_dependency_group(deps, mod) end) end end defp resolve_dependencies(resolved, locked) do locked = Enum.map(locked, &elem(&1, 0)) resolved |> Enum.into(%{}, fn {repo, name, _app, version} -> {name, {repo, version}} end) |> Map.drop(locked) end defp group_dependency_changes(resolved, previously_locked_versions) do state = %{new: [], eq: [], gt: [], lt: []} resolved |> Enum.sort() |> Enum.reduce(state, fn {name, {repo, version}}, acc -> previous_version = previously_locked_versions |> Map.get(name) |> version_string_or_nil() change = categorize_dependency_change(previous_version, version) warning = warning_message(previous_version, version) Map.put(acc, change, acc[change] ++ [{name, repo, previous_version, version, warning}]) end) end defp dep_info_from_lock(lock) do Enum.flat_map(lock, fn {_app, info} -> case Hex.Utils.lock(info) do %{name: name, repo: repo, version: version} -> [{name, {repo, version}}] nil -> [] end end) |> Enum.into(%{}) end defp version_string_or_nil(nil), do: nil defp version_string_or_nil({_repo, version_string}), do: version_string defp categorize_dependency_change(nil, _version), do: :new defp categorize_dependency_change(previous_version, version) do Version.compare(version, previous_version) end defp warning_message(nil, _version), do: nil defp warning_message(previous_version, version) do prev_ver = Hex.Version.parse!(previous_version) new_ver = Hex.Version.parse!(version) cond do Hex.Version.major_version_change?(prev_ver, new_ver) -> " (major)" Hex.Version.breaking_minor_version_change?(prev_ver, new_ver) -> " (minor)" true -> nil end end defp print_category(mod) do case mod do :new -> Hex.Shell.info("New:") :eq -> Hex.Shell.info("Unchanged:") :lt -> Hex.Shell.info("Downgraded:") :gt -> Hex.Shell.info("Upgraded:") end end defp print_dependency_group(deps, mod) do Enum.each(deps, fn {name, repo, previous_version, version, warning} -> print_status( Registry.retired(repo, name, version), mod, name, previous_version, version, warning ) end) end defp print_status(nil, mod, name, previous_version, version, warning) do case mod do :new -> Hex.Shell.info(Hex.Shell.format([:green, " #{name} #{version}", :red, "#{warning}"])) :eq -> Hex.Shell.info(" #{name} #{version}") :lt -> Hex.Shell.info( Hex.Shell.format([ :yellow, " #{name} #{previous_version} => #{version}", :red, "#{warning}" ]) ) :gt -> Hex.Shell.info( Hex.Shell.format([ :green, " #{name} #{previous_version} => #{version}", :red, "#{warning}" ]) ) end end defp print_status(retired, mod, name, previous_version, version, _warning) do case mod do mod when mod in [:eq, :new] -> Hex.Shell.warn(" #{name} #{version} RETIRED!") Hex.Shell.warn(" #{Hex.Utils.package_retirement_message(retired)}") _ -> Hex.Shell.warn(" #{name} #{previous_version} => #{version} RETIRED!") Hex.Shell.warn(" #{Hex.Utils.package_retirement_message(retired)}") end end defp verify_prefetches(prefetches) do prefetches |> Enum.map(fn {repo, _package} -> repo end) |> Enum.uniq() |> Enum.each(&verify_repo/1) prefetches end defp verify_repo(repo) do case Hex.Repo.fetch_repo(repo) do {:ok, _} -> :ok :error -> case repo do "hexpm:" <> organization -> if Hex.Shell.yes?( "No authenticated organization found for #{organization}. Do you want to authenticate it now?" ) do Mix.Tasks.Hex.Organization.run(["auth", organization]) else Hex.Repo.get_repo(repo) end _ -> Mix.raise( "Unknown repository #{inspect(repo)}, add new repositories " <> "with the `mix hex.repo add` task" ) end end end defp verify_resolved(resolved, lock) do Enum.each(resolved, fn {repo, name, app, version} -> atom_name = String.to_atom(name) case Hex.Utils.lock(lock[String.to_atom(app)]) do %{name: ^atom_name, version: ^version, repo: ^repo} = lock -> verify_inner_checksum(repo, name, version, lock.inner_checksum) verify_outer_checksum(repo, name, version, lock.outer_checksum) verify_deps(repo, name, version, lock.deps) _ -> :ok end end) end defp verify_inner_checksum(repo, name, version, checksum) do registry_checksum = Registry.inner_checksum(repo, name, version) if checksum && Base.decode16!(checksum, case: :lower) != registry_checksum do Mix.raise("Registry checksum mismatch against lock (#{name} #{version})") end end defp verify_outer_checksum(repo, name, version, checksum) do registry_checksum = Registry.outer_checksum(repo, name, version) if checksum && Base.decode16!(checksum, case: :lower) != registry_checksum do Mix.raise("Registry checksum mismatch against lock (#{name} #{version})") end end defp verify_deps(nil, _name, _version, _deps), do: :ok defp verify_deps(repo, name, version, deps) do deps = Enum.map(deps, fn {app, req, opts} -> { opts[:repo], opts[:hex], Atom.to_string(app), req, !!opts[:optional] } end) if Enum.sort(deps) != Enum.sort(Registry.deps(repo, name, version)) do Mix.raise("Registry dependencies mismatch against lock (#{name} #{version})") end end defp verify_lock(lock) do Enum.each(lock, fn {_app, info} -> case Hex.Utils.lock(info) do %{name: name, version: version, repo: repo} -> verify_dep(repo, name, version) nil -> :ok end end) end defp verify_dep(repo, name, version) do Hex.Repo.get_repo(repo) if versions = Registry.versions(repo, name) do unless version in versions do Mix.raise("Unknown package version #{name} #{version} in lockfile") end else Mix.raise("Unknown package #{name} in lockfile") end end defp with_children(apps, lock) do [apps, do_with_children(apps, lock)] |> List.flatten() end defp do_with_children(names, lock) do Enum.map(names, fn name -> case Hex.Utils.lock(lock[String.to_atom(name)]) do %{name: name, version: version, deps: nil, repo: repo} -> # Do not error on bad data in the old lock because we should just # fix it automatically if deps = Registry.deps(repo, name, version) do apps = Enum.map(deps, &elem(&1, 1)) [apps, do_with_children(apps, lock)] else [] end %{deps: deps} -> apps = Enum.map(deps, &Atom.to_string(elem(&1, 0))) [apps, do_with_children(apps, lock)] nil -> [] end end) end defp prepare_locked(lock, old_lock, deps) do # Remove dependencies from the lock if: # 1. They are defined as git or path in mix.exs # 2. If the requirement or repo in mix.exs does not match the locked version # 3. If it's a child of another Hex package being unlocked/updated unlock_without_children = for {app, _} <- old_lock, not Map.has_key?(lock, app), do: Atom.to_string(app) unlock = (unlock_deps(deps, old_lock) ++ unlock_without_children) |> Enum.uniq() |> with_children(old_lock) |> Enum.uniq() old_lock |> Hex.Mix.from_lock() |> Enum.reject(fn {_repo, _name, app, _version} -> app in unlock end) end defp unlock_deps(deps, old_lock) do Enum.filter(deps, fn %Mix.Dep{scm: Hex.SCM, app: app, requirement: req, opts: opts} -> name = opts[:hex] case Hex.Utils.lock(old_lock[app]) do %{name: ^name, version: version, repo: repo} -> (req && !Hex.Version.match?(version, req)) || repo != opts[:repo] %{} -> false nil -> true end %Mix.Dep{} -> true end) |> Enum.map(&Atom.to_string(&1.app)) end end
28.348877
119
0.60753
039a0024b4a7ef1a9e8e9f2565a7f6ece919f4c2
449
ex
Elixir
lib/zero_phoenix_web/graphql/schemas/queries/person.ex
conradwt/zero-to-graphql-using-elixir
1014681c5708e2ee02db6fb9b6f64cee0f533150
[ "MIT" ]
6
2021-12-15T13:29:04.000Z
2022-01-23T14:13:03.000Z
lib/zero_phoenix_web/graphql/schemas/queries/person.ex
conradwt/zero-to-graphql-using-elixir
1014681c5708e2ee02db6fb9b6f64cee0f533150
[ "MIT" ]
null
null
null
lib/zero_phoenix_web/graphql/schemas/queries/person.ex
conradwt/zero-to-graphql-using-elixir
1014681c5708e2ee02db6fb9b6f64cee0f533150
[ "MIT" ]
null
null
null
defmodule ZeroPhoenixWeb.GraphQL.Schemas.Queries.Person do use Absinthe.Schema.Notation object :person_queries do field :person, type: :person do arg :id, non_null(:id) resolve(&ZeroPhoenixWeb.GraphQL.Resolvers.PersonResolver.find/3) end field :people, type: list_of(:person) do arg(:ids, list_of(:id), default_value: []) resolve(&ZeroPhoenixWeb.GraphQL.Resolvers.PersonResolver.list/3) end end end
24.944444
70
0.710468
039a0954a5bfed7d04fb7893d41e70df081fc91b
165
ex
Elixir
monitoring_hub/apps/monitoring_hub_utils/lib/monitoring_hub_utils/helpers.ex
pvmsikrsna/wallaroo
a08ef579ec809e5bf4ffe10937b2be20059a0530
[ "Apache-2.0" ]
1,459
2017-09-16T13:13:15.000Z
2020-10-05T06:19:50.000Z
monitoring_hub/apps/monitoring_hub_utils/lib/monitoring_hub_utils/helpers.ex
pvmsikrsna/wallaroo
a08ef579ec809e5bf4ffe10937b2be20059a0530
[ "Apache-2.0" ]
1,413
2017-09-14T18:18:14.000Z
2020-09-28T08:10:30.000Z
monitoring_hub/apps/monitoring_hub_utils/lib/monitoring_hub_utils/helpers.ex
pvmsikrsna/wallaroo
a08ef579ec809e5bf4ffe10937b2be20059a0530
[ "Apache-2.0" ]
80
2017-09-27T23:16:23.000Z
2020-06-02T09:18:53.000Z
defmodule MonitoringHubUtils.Helpers do def create_channel_name(category, app_name, pipeline_key) do category <> ":" <> app_name <> "||" <> pipeline_key end end
27.5
61
0.739394
039a298a5a98c77b66fe06f9b75c3691d4b928c4
1,714
exs
Elixir
test/sanbase_web/graphql/projects/project_api_is_trending_test.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
test/sanbase_web/graphql/projects/project_api_is_trending_test.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
1
2021-07-24T16:26:03.000Z
2021-07-24T16:26:03.000Z
test/sanbase_web/graphql/projects/project_api_is_trending_test.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
defmodule SanbaseWeb.Graphql.ProjectApiIsTrendingTest do use SanbaseWeb.ConnCase, async: false import Mock import Sanbase.Factory import SanbaseWeb.Graphql.TestHelpers, only: [execute_query: 3] test "fetch social_volume_query project field", context do p1 = insert(:random_erc20_project) p2 = insert(:random_erc20_project) p3 = insert(:random_erc20_project) p4 = insert(:random_project, %{slug: "eos"}) p5 = insert(:random_project, %{slug: "bitcoin"}) with_mock Sanbase.SocialData.TrendingWords, [], get_currently_trending_projects: fn -> {:ok, trending_projects()} end do result = context.conn |> execute_query(all_projects_trending_query(), "allProjects") |> Enum.sort_by(& &1["slug"]) expected_result = [ %{"isTrending" => false, "slug" => p1.slug}, %{"isTrending" => false, "slug" => p2.slug}, %{"isTrending" => false, "slug" => p3.slug}, %{"isTrending" => true, "slug" => p4.slug}, %{"isTrending" => true, "slug" => p5.slug} ] |> Enum.sort_by(& &1["slug"]) assert result == expected_result end end defp all_projects_trending_query() do """ { allProjects{ slug isTrending } } """ end defp trending_projects() do [ %{score: 372, slug: "eos"}, %{score: 309, slug: "satoshi"}, %{score: 228, slug: "time"}, %{score: 227, slug: "carl"}, %{score: 196, slug: "donuts"}, %{score: 190, slug: "like"}, %{score: 178, slug: "bitcoin"}, %{score: 172, slug: "mods"}, %{score: 157, slug: "mod"}, %{score: 118, slug: "pepper"} ] end end
27.645161
78
0.574679
039a2c34bdf221c939cf85014703951c1aac7b68
8,360
ex
Elixir
lib/cldr/language.ex
tcitworld/cldr_languages
6a3fcec2eda0d4d17cae65f673ccb3dbf0f3ad00
[ "Apache-2.0" ]
null
null
null
lib/cldr/language.ex
tcitworld/cldr_languages
6a3fcec2eda0d4d17cae65f673ccb3dbf0f3ad00
[ "Apache-2.0" ]
null
null
null
lib/cldr/language.ex
tcitworld/cldr_languages
6a3fcec2eda0d4d17cae65f673ccb3dbf0f3ad00
[ "Apache-2.0" ]
null
null
null
defmodule Cldr.Language do @moduledoc """ Cldr Languages does provide functionality regarding languages within the data supplied by the Cldr core package. To use the functionality of this module you need to [register it as provider](https://github.com/kipcole9/cldr#providers) in your cldr backend module. ## Example defmodule MyApp.Backend do use Cldr, providers: [Cldr.Language, …], … end ## Interface All functionality will be compiled into `MyApp.Backend.Language`. ### Functions * `available_languages/0` * `available_languages/1` * `known_languages/0` * `known_languages/1` * `to_string/1` * `to_string/2` """ # This is only meant to be called by Cldr @doc false def cldr_backend_provider(config) do module = inspect(__MODULE__) backend = config.backend config = Macro.escape(config) quote location: :keep, bind_quoted: [ module: module, backend: backend, config: config ] do defmodule Language do alias Cldr.LanguageTag alias Cldr.Locale @type styles :: :standard | :short @styles [:standard, :short] # Simpler than unquoting the backend everywhere defp backend, do: unquote(backend) defp get_locale, do: backend().get_locale() defp default_locale, do: backend().default_locale() @doc """ Return all the languages' iso-codes available for a given locale. Defaults to the current locale. ## Example > #{inspect(__MODULE__)}.Language.available_languages("en") ["aa", "ab", "ace", "ach", "ada", "ady", "ae", "aeb", "af", "afh", "agq", "ain", "ak", "akk", "akz", "ale", "aln", "alt", "am", "an", "ang", "anp", "ar", "ar-001", "arc", "arn", "aro", "arp", "arq", "ars", "arw", "ary", "arz", "as", "asa", "ase", "ast", "av", "avk", "awa", "ay", "az", "ba", "bal", "ban", "bar", "bas", "bax", "bbc", "bbj", ...] """ @spec available_languages() :: list(String.t()) | {:error, term()} @spec available_languages(String.t() | LanguageTag.t()) :: list(String.t()) | {:error, term()} def available_languages(locale \\ get_locale()) def available_languages(%LanguageTag{cldr_locale_name: cldr_locale_name}) do available_languages(cldr_locale_name) end @doc """ Return a map of iso-code keyed maps of language names in any available formats for the given locale. Defaults to the current locale. ## Example > #{inspect(__MODULE__)}.Language.known_languages("en") %{"bez" => %{standard: "Bena"}, "lo" => %{standard: "Lao"}, "kha" => %{standard: "Khasi"}, "eo" => %{standard: "Esperanto"}, "rm" => %{standard: "Romansh"}, "ja" => %{standard: "Japanese"}, "sw-CD" => %{standard: "Congo Swahili"}, "pdc" => %{standard: "Pennsylvania German"}, "om" => %{standard: "Oromo"}, "jut" => %{standard: "Jutish"}, "lij" => %{standard: "Ligurian"}, "kut" => %{standard: "Kutenai"}, "vep" => %{standard: "Veps"}, "yao" => %{standard: "Yao"}, "gez" => %{standard: "Geez"}, "cr" => %{standard: "Cree"}, "ne" => %{standard: "Nepali"}, "zbl" => %{standard: "Blissymbols"}, "ae" => %{standard: "Avestan"}, "rof" => %{standard: "Rombo"}, "tkl" => %{standard: "Tokelau"}, "rgn" => %{standard: "Romagnol"}, "el" => %{standard: "Greek"}, "myv" => %{standard: "Erzya"}, "smj" => %{standard: "Lule Sami"}, "fo" => %{standard: "Faroese"}, "ii" => %{standard: "Sichuan Yi"}, "bum" => %{standard: "Bulu"}, "za" => %{standard: "Zhuang"}, "raj" => %{standard: "Rajasthani"}, "mrj" => %{standard: "Western Mari"}, "stq" => %{standard: "Saterland Frisian"}, "hu" => %{standard: "Hungarian"}, "mga" => %{standard: "Middle Irish"}, "bej" => %{standard: "Beja"}, "yue" => %{standard: "Cantonese"}, "xog" => %{standard: "Soga"}, "ttt" => %{standard: "Muslim Tat"}, "uga" => %{standard: "Ugaritic"}, "rup" => %{standard: "Aromanian"}, "crs" => %{standard: "Seselwa Creole French"}, "oc" => %{standard: "Occitan"}, "chp" => %{standard: "Chipewyan"}, "zen" => %{standard: "Zenaga"}, "kmb" => %{standard: "Kimbundu"}, "nr" => %{standard: "South Ndebele"}, "tiv" => %{standard: "Tiv"}, "aln" => %{standard: "Gheg Albanian"}, "sh" => %{standard: "Serbo-Croatian"}, "fil" => %{...}, ...} """ @spec known_languages() :: %{String.t() => %{required(styles()) => String.t()}} | {:error, term()} @spec known_languages(String.t() | LanguageTag.t()) :: %{String.t() => %{required(styles()) => String.t()}} | {:error, term()} def known_languages(locale \\ get_locale()) def known_languages(%LanguageTag{cldr_locale_name: cldr_locale_name}) do known_languages(cldr_locale_name) end # Implement available_locales/known_locales for locale_name <- Cldr.Config.known_locale_names(config) do languages = locale_name |> Cldr.Config.get_locale(config) |> Map.get(:languages) def available_languages(unquote(locale_name)) do unquote(Enum.sort(Map.keys(languages))) end def known_languages(unquote(locale_name)) do unquote(Macro.escape(languages)) end end # Error cases for available_locales/known_locales def available_languages(locale), do: {:error, Locale.locale_error(locale)} def known_languages(locale), do: {:error, Locale.locale_error(locale)} @doc """ Try to translate the given lanuage iso code or language tag. ## Example iex> #{inspect(__MODULE__)}.Language.to_string("eo") {:ok, "Esperanto"} """ @spec to_string(String.t() | LanguageTag.t()) :: {:ok, String.t()} | {:error, term()} @spec to_string(String.t() | LanguageTag.t(), Keyword.t()) :: {:ok, String.t()} | {:error, term()} def to_string(key, options \\ []) do opts = %{} |> merge_style(options[:style]) |> merge_locale(options[:locale]) |> merge_fallback(options[:fallback]) result = to_string_by_locale(key, opts.locale, opts) if result == :error && Map.fetch!(opts, :fallback) do to_string_by_locale(key, default_locale(), opts) else result end end defp to_string_by_locale(key, locale, %{style: style}) do with {:ok, lang} <- locale |> known_languages |> Map.fetch(key) do case Map.fetch(lang, style) do {:ok, _} = val -> val :error -> Map.fetch(lang, :standard) end end end # Merge style into options # Only allow @styles (default to standard) defp merge_style(opts, nil), do: Map.put(opts, :style, :standard) defp merge_style(opts, style) when style in @styles, do: Map.put(opts, :style, style) defp merge_style(opts, style) do msg = "Invalid :style option #{inspect(style)} supplied. " <> "Valid styles are #{inspect(@styles)}." raise ArgumentError, msg end # Merge locale into options # Default to cldr's current locale defp merge_locale(opts, nil), do: Map.put(opts, :locale, get_locale()) defp merge_locale(opts, locale), do: Map.put(opts, :locale, locale) # Merge fallback into options # Only allow booleans (default to false) defp merge_fallback(opts, nil), do: Map.put(opts, :fallback, false) defp merge_fallback(opts, fallback) when is_boolean(fallback), do: Map.put(opts, :fallback, fallback) defp merge_fallback(opts, fallback) do msg = "Invalid :fallback option #{inspect(fallback)} supplied. " <> "Valid fallbacks are #{inspect([true, false])}." raise ArgumentError, msg end end end end end
39.433962
152
0.549761
039a3f56f2ceb12ffa85f890875137a4252b9d81
4,268
ex
Elixir
lib/membrane/rtcp/receiver.ex
membraneframework/membrane_rtp
1df5f0bdb66d5c89bc63122c8b29af6cd4e600aa
[ "Apache-2.0" ]
null
null
null
lib/membrane/rtcp/receiver.ex
membraneframework/membrane_rtp
1df5f0bdb66d5c89bc63122c8b29af6cd4e600aa
[ "Apache-2.0" ]
2
2020-04-01T14:06:34.000Z
2020-04-08T11:48:59.000Z
lib/membrane/rtcp/receiver.ex
membraneframework/membrane_rtp
1df5f0bdb66d5c89bc63122c8b29af6cd4e600aa
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.RTCP.Receiver do @moduledoc """ Element exchanging RTCP packets and RTCP receiver statistics. """ use Membrane.Filter alias Membrane.RTCPEvent alias Membrane.RTCP.{FeedbackPacket, SenderReportPacket} alias Membrane.{RTCP, RTP} alias Membrane.RTCP.ReceiverReport alias Membrane.Time require Membrane.Logger require Membrane.TelemetryMetrics def_input_pad :input, caps: :any, demand_mode: :auto def_output_pad :output, caps: :any, demand_mode: :auto def_options local_ssrc: [spec: RTP.ssrc_t()], remote_ssrc: [spec: RTP.ssrc_t()], report_interval: [spec: Membrane.Time.t() | nil, default: nil], fir_interval: [spec: Membrane.Time.t() | nil, default: nil], telemetry_label: [spec: Membrane.TelemetryMetrics.label(), default: []] @event_name [Membrane.RTP, :rtcp, :fir, :sent] @impl true def handle_init(opts) do Membrane.TelemetryMetrics.register(@event_name, opts.telemetry_label) {:ok, Map.from_struct(opts) |> Map.merge(%{fir_seq_num: 0, sr_info: %{}})} end @impl true def handle_prepared_to_playing(_ctx, state) do fir_timer = if state.fir_interval, do: [start_timer: {:fir_timer, state.fir_interval}], else: [] report_timer = if state.report_interval, do: [start_timer: {:report_timer, state.report_interval}], else: [] {{:ok, fir_timer ++ report_timer}, state} end @impl true def handle_playing_to_prepared(_ctx, state) do fir_timer = if state.fir_interval, do: [stop_timer: :fir_timer], else: [] report_timer = if state.report_interval, do: [stop_timer: :report_timer], else: [] {{:ok, fir_timer ++ report_timer}, state} end @impl true def handle_tick(:report_timer, _ctx, state) do {{:ok, event: {:output, %ReceiverReport.StatsRequestEvent{}}}, state} end @impl true def handle_tick(:fir_timer, _ctx, state) do send_fir(state) end @impl true def handle_event(:input, %RTCPEvent{rtcp: %SenderReportPacket{} = rtcp} = event, _ctx, state) do <<_wallclock_ts_upper_16_bits::16, wallclock_ts_middle_32_bits::32, _wallclock_ts_lower_16_bits::16>> = Time.to_ntp_timestamp(rtcp.sender_info.wallclock_timestamp) sr_info = %{ cut_wallclock_ts: wallclock_ts_middle_32_bits, arrival_ts: event.arrival_timestamp } {:ok, %{state | sr_info: sr_info}} end @impl true def handle_event(:input, %RTCPEvent{}, _ctx, state) do {:ok, state} end @impl true def handle_event(:output, %ReceiverReport.StatsEvent{stats: :no_stats}, _ctx, state) do {:ok, state} end @impl true def handle_event(:output, %ReceiverReport.StatsEvent{stats: stats}, _ctx, state) do now = Time.vm_time() delay_since_sr = now - Map.get(state.sr_info, :arrival_ts, now) report_block = %RTCP.ReportPacketBlock{ ssrc: state.remote_ssrc, fraction_lost: stats.fraction_lost, total_lost: stats.total_lost, highest_seq_num: stats.highest_seq_num, interarrival_jitter: trunc(stats.interarrival_jitter), last_sr_timestamp: Map.get(state.sr_info, :cut_wallclock_ts, 0), # delay_since_sr is expressed in 1/65536 seconds, see https://tools.ietf.org/html/rfc3550#section-6.4.1 delay_since_sr: Time.to_seconds(65_536 * delay_since_sr) } packet = %RTCP.ReceiverReportPacket{ssrc: state.local_ssrc, reports: [report_block]} {{:ok, event: {:input, %RTCPEvent{rtcp: packet}}}, state} end @impl true def handle_event(:output, %Membrane.KeyframeRequestEvent{}, _ctx, state) do send_fir(state) end @impl true def handle_event(pad, event, ctx, state), do: super(pad, event, ctx, state) @impl true def handle_process(:input, buffer, _ctx, state) do {{:ok, buffer: {:output, buffer}}, state} end defp send_fir(state) do rtcp = %FeedbackPacket{ origin_ssrc: state.local_ssrc, payload: %FeedbackPacket.FIR{ target_ssrc: state.remote_ssrc, seq_num: state.fir_seq_num } } Membrane.TelemetryMetrics.execute(@event_name, %{}, %{}, state.telemetry_label) event = %RTCPEvent{rtcp: rtcp} state = Map.update!(state, :fir_seq_num, &(&1 + 1)) {{:ok, event: {:input, event}}, state} end end
31.382353
109
0.685098
039aaf61ccf843c38dca2dd14cda4bfe272da58a
3,856
ex
Elixir
lib/nfl_player_searchex.ex
krmannix/nfl-player-searchex
2644f5927adda27d5a394a397baedab3d0db785a
[ "MIT" ]
5
2017-07-05T13:36:25.000Z
2021-08-06T05:21:01.000Z
lib/nfl_player_searchex.ex
krmannix/nfl_player_searchex
2644f5927adda27d5a394a397baedab3d0db785a
[ "MIT" ]
null
null
null
lib/nfl_player_searchex.ex
krmannix/nfl_player_searchex
2644f5927adda27d5a394a397baedab3d0db785a
[ "MIT" ]
null
null
null
defmodule NFLPlayerSearchex do @root "http://www.nfl.com" @search_root @root <> "/players/search" @moduledoc """ NFLPlayerSearchex allows look up of NFL Players via the official NFL player search. This module is not an official NFL module. Replicates the functionality found at http://www.nfl.com/players/search """ @doc """ Find current players by name. Matches on partial name, i.e. "smith" will match "Smith" & "smithwell". ## Parameters - `name`: String that represents the name of the player to search for. Can be first, last, or combination. Partial matches are also accepted. ## Examples iex> NFLPlayerSearchex.by_name("blount") [%{average: 3.9, carries: 299, jersey_number: nil, name: "LeGarrette Blount", position: "RB", position_description: "Running Back", status: "ACT", status_description: "Active", team_long: "Philadelphia Eagles", team_short: "PHI", touchdowns: 18, yards: 1161}] """ @spec by_name(String.t) :: [map] def by_name(name) do url_options = build_by_name_options(name) fetch_data_by_url(url_options) end @doc """ Find current players by position. ## Parameters - `position`: String that represents a position. Accepeted String values: * `"quarterback"` * `"runningback"` * `"widereceiver"` * `"tightend"` * `"offensiveline"` * `"defensivelineman"` * `"linebacker"` * `"defensiveback"` * `"kicker"` * `"punter"` ## Examples iex> NFLPlayerSearchex.by_position("kicker") [%{jersey_number: 19, name: "Roberto Aguayo", nil: 43, position: "K", position_description: "Kicker", status: "ACT", status_description: "Active", team_long: "Tampa Bay Buccaneers", team_short: "TB"}, %{jersey_number: 5, name: "Dan Bailey", nil: 56, position: "K", position_description: "Kicker", status: "ACT", status_description: "Active", team_long: "Dallas Cowboys", team_short: "DAL"}, ...] """ @spec by_position(String.t) :: [map] def by_position(position) do url_options = build_by_position_options(position) fetch_data_by_url(url_options) end defp fetch_data_by_url(url), do: fetch_data_by_url(url, []) defp fetch_data_by_url(url, data) do unless is_nil(url) do body = url |> get_request |> get_response_body next_url = get_next_page_link_from_response_body(body) results = get_results_from_response_body(body) fetch_data_by_url(next_url, data ++ results) else data end end ## Build initial options defp build_by_name_options(name) do [category: "name", filter: name] end defp build_by_position_options(position) do [category: "position", conference: "ALL", filter: position] end ## Parsing response body defp get_results_from_response_body(body) do body |> Floki.find("#result tbody") |> get_results end defp get_next_page_link_from_response_body(body) do body |> Floki.find(".linkNavigation a") |> Enum.find(fn el -> elem(el, 2) === ["next"] end) |> get_url_from_floki_anchor end defp get_url_from_floki_anchor(nil), do: nil defp get_url_from_floki_anchor({_, [{"href", url}], _}), do: url defp get_results(children_nodes) when length(children_nodes) == 0, do: [] defp get_results([{_, _, players}]) do players |> Enum.map(&NFLPlayerSearchex.Player.build_player_from_row(&1)) end # Requests defp get_request(options) do cond do Keyword.keyword?(options) -> HTTPoison.get!(@search_root, [], params: build_request_query_params(options)) true -> HTTPoison.get!(@root <> options) end end defp build_request_query_params(options), do: Enum.into(options, %{playerType: "current"}) defp get_response_body(response), do: response.body end
29.891473
145
0.668568
039aafd07aefd29fd9b1298f8075188dd79e112d
3,141
ex
Elixir
clients/qpx_express/lib/google_api/qpx_express/v1/model/slice_input.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/qpx_express/lib/google_api/qpx_express/v1/model/slice_input.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/qpx_express/lib/google_api/qpx_express/v1/model/slice_input.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 &quot;License&quot;); # 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 &quot;AS IS&quot; 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.QPXExpress.V1.Model.SliceInput do @moduledoc """ Criteria a desired slice must satisfy. ## Attributes - alliance (String): Slices with only the carriers in this alliance should be returned; do not use this field with permittedCarrier. Allowed values are ONEWORLD, SKYTEAM, and STAR. Defaults to: `null`. - date (String): Departure date in YYYY-MM-DD format. Defaults to: `null`. - destination (String): Airport or city IATA designator of the destination. Defaults to: `null`. - kind (String): Identifies this as a slice input object, representing the criteria a desired slice must satisfy. Value: the fixed string qpxexpress#sliceInput. Defaults to: `null`. - maxConnectionDuration (Integer): The longest connection between two legs, in minutes, you are willing to accept. Defaults to: `null`. - maxStops (Integer): The maximum number of stops you are willing to accept in this slice. Defaults to: `null`. - origin (String): Airport or city IATA designator of the origin. Defaults to: `null`. - permittedCarrier (List[String]): A list of 2-letter IATA airline designators. Slices with only these carriers should be returned. Defaults to: `null`. - permittedDepartureTime (TimeOfDayRange): Slices must depart in this time of day range, local to the point of departure. Defaults to: `null`. - preferredCabin (String): Prefer solutions that book in this cabin for this slice. Allowed values are COACH, PREMIUM_COACH, BUSINESS, and FIRST. Defaults to: `null`. - prohibitedCarrier (List[String]): A list of 2-letter IATA airline designators. Exclude slices that use these carriers. Defaults to: `null`. """ defstruct [ :"alliance", :"date", :"destination", :"kind", :"maxConnectionDuration", :"maxStops", :"origin", :"permittedCarrier", :"permittedDepartureTime", :"preferredCabin", :"prohibitedCarrier" ] end defimpl Poison.Decoder, for: GoogleApi.QPXExpress.V1.Model.SliceInput do import GoogleApi.QPXExpress.V1.Deserializer def decode(value, options) do value |> deserialize(:"permittedDepartureTime", :struct, GoogleApi.QPXExpress.V1.Model.TimeOfDayRange, options) end end defimpl Poison.Encoder, for: GoogleApi.QPXExpress.V1.Model.SliceInput do def encode(value, options) do GoogleApi.QPXExpress.V1.Deserializer.serialize_non_nil(value, options) end end
46.191176
203
0.746896
039ab13fae25dc0d94567624d0b6fead7b6e44a5
38,902
ex
Elixir
lib/elixir/lib/macro.ex
davidsulc/elixir
dd4fd6ab742acd75862e34e26dbdb86e0cf6453f
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/macro.ex
davidsulc/elixir
dd4fd6ab742acd75862e34e26dbdb86e0cf6453f
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/macro.ex
davidsulc/elixir
dd4fd6ab742acd75862e34e26dbdb86e0cf6453f
[ "Apache-2.0" ]
null
null
null
import Kernel, except: [to_string: 1] defmodule Macro do @moduledoc ~S""" Conveniences for working with macros. ## Custom Sigils To create a custom sigil, define a function with the name `sigil_{identifier}` that takes two arguments. The first argument will be the string, the second will be a charlist containing any modifiers. If the sigil is lower case (such as `sigil_x`) then the string argument will allow interpolation. If the sigil is upper case (such as `sigil_X`) then the string will not be interpolated. Valid modifiers include only lower and upper case letters. Other characters will cause a syntax error. The module containing the custom sigil must be imported before the sigil syntax can be used. ### Examples defmodule MySigils do defmacro sigil_x(term, [?r]) do quote do unquote(term) |> String.reverse() end end defmacro sigil_x(term, _modifiers) do term end defmacro sigil_X(term, [?r]) do quote do unquote(term) |> String.reverse() end end defmacro sigil_X(term, _modifiers) do term end end import MySigils ~x(with #{"inter" <> "polation"}) #=>"with interpolation" ~x(with #{"inter" <> "polation"})r #=>"noitalopretni htiw" ~X(without #{"interpolation"}) #=>"without \#{"interpolation"}" ~X(without #{"interpolation"})r #=>"}\"noitalopretni\"{# tuohtiw" """ alias Code.Identifier @typedoc "Abstract Syntax Tree (AST)" @type t :: expr | literal @typedoc "Represents expressions in the AST" @type expr :: {expr | atom, keyword, atom | [t]} @typedoc "Represents literals in the AST" @type literal :: atom | number | binary | fun | {t, t} | [t] @doc """ Breaks a pipeline expression into a list. The AST for a pipeline (a sequence of applications of `|>`) is similar to the AST of a sequence of binary operators or function applications: the top-level expression is the right-most `:|>` (which is the last one to be executed), and its left-hand and right-hand sides are its arguments: quote do: 100 |> div(5) |> div(2) #=> {:|>, _, [arg1, arg2]} In the example above, the `|>` pipe is the right-most pipe; `arg1` is the AST for `100 |> div(5)`, and `arg2` is the AST for `div(2)`. It's often useful to have the AST for such a pipeline as a list of function applications. This function does exactly that: Macro.unpipe(quote do: 100 |> div(5) |> div(2)) #=> [{100, 0}, {{:div, [], [5]}, 0}, {{:div, [], [2]}, 0}] We get a list that follows the pipeline directly: first the `100`, then the `div(5)` (more precisely, its AST), then `div(2)`. The `0` as the second element of the tuples is the position of the previous element in the pipeline inside the current function application: `{{:div, [], [5]}, 0}` means that the previous element (`100`) will be inserted as the 0th (first) argument to the `div/2` function, so that the AST for that function will become `{:div, [], [100, 5]}` (`div(100, 5)`). """ @spec unpipe(Macro.t) :: [Macro.t] def unpipe(expr) do :lists.reverse(unpipe(expr, [])) end defp unpipe({:|>, _, [left, right]}, acc) do unpipe(right, unpipe(left, acc)) end defp unpipe(other, acc) do [{other, 0} | acc] end @doc """ Pipes `expr` into the `call_args` at the given `position`. """ @spec pipe(Macro.t, Macro.t, integer) :: Macro.t | no_return def pipe(expr, call_args, position) def pipe(expr, {:&, _, _} = call_args, _integer) do raise ArgumentError, bad_pipe(expr, call_args) end def pipe(expr, {tuple_or_map, _, _} = call_args, _integer) when tuple_or_map in [:{}, :%{}] do raise ArgumentError, bad_pipe(expr, call_args) end # Without this, `Macro |> Env == Macro.Env`. def pipe(expr, {:__aliases__, _, _} = call_args, _integer) do raise ArgumentError, bad_pipe(expr, call_args) end # {:fn, _, _} is what we get when we pipe into an anonymous function without # calling it, e.g., `:foo |> (fn x -> x end)`. def pipe(expr, {:fn, _, _}, _integer) do expr_str = to_string(expr) raise ArgumentError, "cannot pipe #{expr_str} into an anonymous function without" <> " calling the function; use something like (fn ... end).() or" <> " define the anonymous function as a regular private function" end def pipe(expr, {call, line, atom}, integer) when is_atom(atom) do {call, line, List.insert_at([], integer, expr)} end def pipe(expr, {call, line, args} = call_args, integer) when is_list(args) do if is_atom(call) and Identifier.binary_op(call) != :error do raise ArgumentError, "cannot pipe #{to_string expr} into #{to_string call_args}, " <> "the #{to_string call} operator can only take two arguments" else {call, line, List.insert_at(args, integer, expr)} end end def pipe(expr, call_args, _integer) do raise ArgumentError, bad_pipe(expr, call_args) end defp bad_pipe(expr, call_args) do "cannot pipe #{to_string expr} into #{to_string call_args}, " <> "can only pipe into local calls foo(), remote calls Foo.bar() or anonymous functions calls foo.()" end @doc """ Applies the given function to the node metadata if it contains one. This is often useful when used with `Macro.prewalk/2` to remove information like lines and hygienic counters from the expression for either storage or comparison. ## Examples iex> quoted = quote line: 10, do: sample() {:sample, [line: 10], []} iex> Macro.update_meta(quoted, &Keyword.delete(&1, :line)) {:sample, [], []} """ @spec update_meta(t, (keyword -> keyword)) :: t def update_meta(quoted, fun) def update_meta({left, meta, right}, fun) when is_list(meta) do {left, fun.(meta), right} end def update_meta(other, _fun) do other end @doc """ Generates AST nodes for a given number of required argument variables using `Macro.var/2`. ## Examples iex> Macro.generate_arguments(2, __MODULE__) [{:var1, [], __MODULE__}, {:var2, [], __MODULE__}] """ def generate_arguments(0, _), do: [] def generate_arguments(amount, context) when is_integer(amount) and amount > 0 and is_atom(context) do for id <- 1..amount, do: Macro.var(String.to_atom("var" <> Integer.to_string(id)), context) end @doc """ Generates an AST node representing the variable given by the atoms `var` and `context`. ## Examples In order to build a variable, a context is expected. Most of the times, in order to preserve hygiene, the context must be `__MODULE__/0`: iex> Macro.var(:foo, __MODULE__) {:foo, [], __MODULE__} However, if there is a need to access the user variable, nil can be given: iex> Macro.var(:foo, nil) {:foo, [], nil} """ @spec var(var, context) :: {var, [], context} when var: atom, context: atom def var(var, context) when is_atom(var) and is_atom(context) do {var, [], context} end @doc """ Performs a depth-first traversal of quoted expressions using an accumulator. """ @spec traverse(t, any, (t, any -> {t, any}), (t, any -> {t, any})) :: {t, any} def traverse(ast, acc, pre, post) when is_function(pre, 2) and is_function(post, 2) do {ast, acc} = pre.(ast, acc) do_traverse(ast, acc, pre, post) end defp do_traverse({form, meta, args}, acc, pre, post) when is_atom(form) do {args, acc} = do_traverse_args(args, acc, pre, post) post.({form, meta, args}, acc) end defp do_traverse({form, meta, args}, acc, pre, post) do {form, acc} = pre.(form, acc) {form, acc} = do_traverse(form, acc, pre, post) {args, acc} = do_traverse_args(args, acc, pre, post) post.({form, meta, args}, acc) end defp do_traverse({left, right}, acc, pre, post) do {left, acc} = pre.(left, acc) {left, acc} = do_traverse(left, acc, pre, post) {right, acc} = pre.(right, acc) {right, acc} = do_traverse(right, acc, pre, post) post.({left, right}, acc) end defp do_traverse(list, acc, pre, post) when is_list(list) do {list, acc} = do_traverse_args(list, acc, pre, post) post.(list, acc) end defp do_traverse(x, acc, _pre, post) do post.(x, acc) end defp do_traverse_args(args, acc, _pre, _post) when is_atom(args) do {args, acc} end defp do_traverse_args(args, acc, pre, post) when is_list(args) do Enum.map_reduce(args, acc, fn x, acc -> {x, acc} = pre.(x, acc) do_traverse(x, acc, pre, post) end) end @doc """ Performs a depth-first, pre-order traversal of quoted expressions. """ @spec prewalk(t, (t -> t)) :: t def prewalk(ast, fun) when is_function(fun, 1) do elem(prewalk(ast, nil, fn x, nil -> {fun.(x), nil} end), 0) end @doc """ Performs a depth-first, pre-order traversal of quoted expressions using an accumulator. """ @spec prewalk(t, any, (t, any -> {t, any})) :: {t, any} def prewalk(ast, acc, fun) when is_function(fun, 2) do traverse(ast, acc, fun, fn x, a -> {x, a} end) end @doc """ Performs a depth-first, post-order traversal of quoted expressions. """ @spec postwalk(t, (t -> t)) :: t def postwalk(ast, fun) when is_function(fun, 1) do elem(postwalk(ast, nil, fn x, nil -> {fun.(x), nil} end), 0) end @doc """ Performs a depth-first, post-order traversal of quoted expressions using an accumulator. """ @spec postwalk(t, any, (t, any -> {t, any})) :: {t, any} def postwalk(ast, acc, fun) when is_function(fun, 2) do traverse(ast, acc, fn x, a -> {x, a} end, fun) end @doc """ Decomposes a local or remote call into its remote part (when provided), function name and argument list. Returns `:error` when an invalid call syntax is provided. ## Examples iex> Macro.decompose_call(quote(do: foo)) {:foo, []} iex> Macro.decompose_call(quote(do: foo())) {:foo, []} iex> Macro.decompose_call(quote(do: foo(1, 2, 3))) {:foo, [1, 2, 3]} iex> Macro.decompose_call(quote(do: Elixir.M.foo(1, 2, 3))) {{:__aliases__, [], [:Elixir, :M]}, :foo, [1, 2, 3]} iex> Macro.decompose_call(quote(do: 42)) :error """ @spec decompose_call(Macro.t) :: {atom, [Macro.t]} | {Macro.t, atom, [Macro.t]} | :error def decompose_call(ast) def decompose_call({{:., _, [remote, function]}, _, args}) when is_tuple(remote) or is_atom(remote), do: {remote, function, args} def decompose_call({name, _, args}) when is_atom(name) and is_atom(args), do: {name, []} def decompose_call({name, _, args}) when is_atom(name) and is_list(args), do: {name, args} def decompose_call(_), do: :error @doc """ Recursively escapes a value so it can be inserted into a syntax tree. One may pass `unquote: true` to `escape/2` which leaves `unquote/1` statements unescaped, effectively unquoting the contents on escape. ## Examples iex> Macro.escape(:foo) :foo iex> Macro.escape({:a, :b, :c}) {:{}, [], [:a, :b, :c]} iex> Macro.escape({:unquote, [], [1]}, unquote: true) 1 """ @spec escape(term, keyword) :: Macro.t def escape(expr, opts \\ []) do elem(:elixir_quote.escape(expr, Keyword.get(opts, :unquote, false)), 0) end @doc """ Validates the given expressions are valid quoted expressions. Checks the `t:Macro.t/0` for the specification of a valid quoted expression. It returns `:ok` if the expression is valid. Otherwise it returns a tuple in the form of `{:error, remainder}` where `remainder` is the invalid part of the quoted expression. ## Examples iex> Macro.validate({:two_element, :tuple}) :ok iex> Macro.validate({:three, :element, :tuple}) {:error, {:three, :element, :tuple}} iex> Macro.validate([1, 2, 3]) :ok iex> Macro.validate([1, 2, 3, {4}]) {:error, {4}} """ @spec validate(term) :: :ok | {:error, term} def validate(expr) do find_invalid(expr) || :ok end defp find_invalid({left, right}), do: find_invalid(left) || find_invalid(right) defp find_invalid({left, meta, right}) when is_list(meta) and (is_atom(right) or is_list(right)), do: find_invalid(left) || find_invalid(right) defp find_invalid(list) when is_list(list), do: Enum.find_value(list, &find_invalid/1) defp find_invalid(pid) when is_pid(pid), do: nil defp find_invalid(atom) when is_atom(atom), do: nil defp find_invalid(num) when is_number(num), do: nil defp find_invalid(bin) when is_binary(bin), do: nil defp find_invalid(fun) when is_function(fun) do unless :erlang.fun_info(fun, :env) == {:env, []} and :erlang.fun_info(fun, :type) == {:type, :external} do {:error, fun} end end defp find_invalid(other), do: {:error, other} @doc ~S""" Unescapes the given chars. This is the unescaping behaviour used by default in Elixir single- and double-quoted strings. Check `unescape_string/2` for information on how to customize the escaping map. In this setup, Elixir will escape the following: `\0`, `\a`, `\b`, `\d`, `\e`, `\f`, `\n`, `\r`, `\s`, `\t` and `\v`. Bytes can be given as hexadecimals via `\xNN` and Unicode Codepoints as `\uNNNN` escapes. This function is commonly used on sigil implementations (like `~r`, `~s` and others) which receive a raw, unescaped string. ## Examples iex> Macro.unescape_string("example\\n") "example\n" In the example above, we pass a string with `\n` escaped and return a version with it unescaped. """ @spec unescape_string(String.t) :: String.t def unescape_string(chars) do :elixir_interpolation.unescape_chars(chars) end @doc ~S""" Unescapes the given chars according to the map given. Check `unescape_string/1` if you want to use the same map as Elixir single- and double-quoted strings. ## Map The map must be a function. The function receives an integer representing the codepoint of the character it wants to unescape. Here is the default mapping function implemented by Elixir: def unescape_map(unicode), do: true def unescape_map(hex), do: true def unescape_map(?0), do: ?0 def unescape_map(?a), do: ?\a def unescape_map(?b), do: ?\b def unescape_map(?d), do: ?\d def unescape_map(?e), do: ?\e def unescape_map(?f), do: ?\f def unescape_map(?n), do: ?\n def unescape_map(?r), do: ?\r def unescape_map(?s), do: ?\s def unescape_map(?t), do: ?\t def unescape_map(?v), do: ?\v def unescape_map(e), do: e If the `unescape_map/1` function returns `false`, the char is not escaped and the backslash is kept in the string. Hexadecimals and Unicode codepoints will be escaped if the map function returns `true` for `?x`. Unicode codepoints if the map function returns `true` for `?u`. ## Examples Using the `unescape_map/1` function defined above is easy: Macro.unescape_string "example\\n", &unescape_map(&1) """ @spec unescape_string(String.t, (non_neg_integer -> non_neg_integer | false)) :: String.t def unescape_string(chars, map) do :elixir_interpolation.unescape_chars(chars, map) end @doc false def unescape_tokens(tokens) do :elixir_interpolation.unescape_tokens(tokens) end @doc false def unescape_tokens(tokens, map) do :elixir_interpolation.unescape_tokens(tokens, map) end @doc """ Converts the given expression AST to a string. The given `fun` is called for every node in the AST with two arguments: the AST of the node being printed and the string representation of that same node. The return value of this function is used as the final string representation for that AST node. This function discards all formatting of the original code. ## Examples iex> Macro.to_string(quote(do: foo.bar(1, 2, 3))) "foo.bar(1, 2, 3)" iex> Macro.to_string(quote(do: 1 + 2), fn ...> 1, _string -> "one" ...> 2, _string -> "two" ...> _ast, string -> string ...> end) "one + two" """ @spec to_string(Macro.t, (Macro.t, String.t -> String.t)) :: String.t def to_string(tree, fun \\ fn(_ast, string) -> string end) # Variables def to_string({var, _, atom} = ast, fun) when is_atom(atom) do fun.(ast, Atom.to_string(var)) end # Aliases def to_string({:__aliases__, _, refs} = ast, fun) do fun.(ast, Enum.map_join(refs, ".", &call_to_string(&1, fun))) end # Blocks def to_string({:__block__, _, [expr]} = ast, fun) do fun.(ast, to_string(expr, fun)) end def to_string({:__block__, _, _} = ast, fun) do block = adjust_new_lines block_to_string(ast, fun), "\n " fun.(ast, "(\n " <> block <> "\n)") end # Bits containers def to_string({:<<>>, _, parts} = ast, fun) do if interpolated?(ast) do fun.(ast, interpolate(ast, fun)) else result = Enum.map_join(parts, ", ", fn(part) -> str = bitpart_to_string(part, fun) if :binary.first(str) == ?< or :binary.last(str) == ?> do "(" <> str <> ")" else str end end) fun.(ast, "<<" <> result <> ">>") end end # Tuple containers def to_string({:{}, _, args} = ast, fun) do tuple = "{" <> Enum.map_join(args, ", ", &to_string(&1, fun)) <> "}" fun.(ast, tuple) end # Map containers def to_string({:%{}, _, args} = ast, fun) do map = "%{" <> map_to_string(args, fun) <> "}" fun.(ast, map) end def to_string({:%, _, [struct_name, map]} = ast, fun) do {:%{}, _, args} = map struct = "%" <> to_string(struct_name, fun) <> "{" <> map_to_string(args, fun) <> "}" fun.(ast, struct) end # Fn keyword def to_string({:fn, _, [{:->, _, [_, tuple]}] = arrow} = ast, fun) when not is_tuple(tuple) or elem(tuple, 0) != :__block__ do fun.(ast, "fn " <> arrow_to_string(arrow, fun) <> " end") end def to_string({:fn, _, [{:->, _, _}] = block} = ast, fun) do fun.(ast, "fn " <> block_to_string(block, fun) <> "\nend") end def to_string({:fn, _, block} = ast, fun) do block = adjust_new_lines block_to_string(block, fun), "\n " fun.(ast, "fn\n " <> block <> "\nend") end # left -> right def to_string([{:->, _, _} | _] = ast, fun) do fun.(ast, "(" <> arrow_to_string(ast, fun, true) <> ")") end # left when right def to_string({:when, _, [left, right]} = ast, fun) do right = if right != [] and Keyword.keyword?(right) do kw_list_to_string(right, fun) else fun.(ast, op_to_string(right, fun, :when, :right)) end fun.(ast, op_to_string(left, fun, :when, :left) <> " when " <> right) end # Splat when def to_string({:when, _, args} = ast, fun) do {left, right} = split_last(args) fun.(ast, "(" <> Enum.map_join(left, ", ", &to_string(&1, fun)) <> ") when " <> to_string(right, fun)) end # Capture def to_string({:&, _, [{:/, _, [{name, _, ctx}, arity]}]} = ast, fun) when is_atom(name) and is_atom(ctx) and is_integer(arity) do fun.(ast, "&" <> Atom.to_string(name) <> "/" <> to_string(arity, fun)) end def to_string({:&, _, [{:/, _, [{{:., _, [mod, name]}, _, []}, arity]}]} = ast, fun) when is_atom(name) and is_integer(arity) do fun.(ast, "&" <> to_string(mod, fun) <> "." <> Atom.to_string(name) <> "/" <> to_string(arity, fun)) end def to_string({:&, _, [arg]} = ast, fun) when not is_integer(arg) do fun.(ast, "&(" <> to_string(arg, fun) <> ")") end # left not in right def to_string({:not, _, [{:in, _, [left, right]}]} = ast, fun) do fun.(ast, to_string(left, fun) <> " not in " <> to_string(right, fun)) end # Access def to_string({{:., _, [Access, :get]}, _, [left, right]} = ast, fun) do if op_expr?(left) do fun.(ast, "(" <> to_string(left, fun) <> ")" <> to_string([right], fun)) else fun.(ast, to_string(left, fun) <> to_string([right], fun)) end end # foo.{bar, baz} def to_string({{:., _, [left, :{}]}, _, args} = ast, fun) do fun.(ast, to_string(left, fun) <> ".{" <> args_to_string(args, fun) <> "}") end # All other calls def to_string({target, _, args} = ast, fun) when is_list(args) do with :error <- unary_call(ast, fun), :error <- binary_call(ast, fun), :error <- sigil_call(ast, fun) do {list, last} = split_last(args) fun.(ast, case kw_blocks?(last) do true -> call_to_string_with_args(target, list, fun) <> kw_blocks_to_string(last, fun) false -> call_to_string_with_args(target, args, fun) end) else {:ok, value} -> value end end # Two-element tuples def to_string({left, right}, fun) do to_string({:{}, [], [left, right]}, fun) end # Lists def to_string(list, fun) when is_list(list) do fun.(list, cond do list == [] -> "[]" :io_lib.printable_list(list) -> {escaped, _} = Identifier.escape(IO.chardata_to_string(list), ?') IO.iodata_to_binary [?', escaped, ?'] Inspect.List.keyword?(list) -> "[" <> kw_list_to_string(list, fun) <> "]" true -> "[" <> Enum.map_join(list, ", ", &to_string(&1, fun)) <> "]" end) end # All other structures def to_string(other, fun), do: fun.(other, inspect(other, [])) defp bitpart_to_string({:::, _, [left, right]} = ast, fun) do result = op_to_string(left, fun, :::, :left) <> "::" <> bitmods_to_string(right, fun, :::, :right) fun.(ast, result) end defp bitpart_to_string(ast, fun) do to_string(ast, fun) end defp bitmods_to_string({op, _, [left, right]} = ast, fun, _, _) when op in [:*, :-] do result = bitmods_to_string(left, fun, op, :left) <> Atom.to_string(op) <> bitmods_to_string(right, fun, op, :right) fun.(ast, result) end defp bitmods_to_string(other, fun, parent_op, side) do op_to_string(other, fun, parent_op, side) end # Block keywords kw_keywords = [:do, :catch, :rescue, :after, :else] defp kw_blocks?([{:do, _} | _] = kw) do Enum.all?(kw, &match?({x, _} when x in unquote(kw_keywords), &1)) end defp kw_blocks?(_), do: false # Check if we have an interpolated string. defp interpolated?({:<<>>, _, [_ | _] = parts}) do Enum.all?(parts, fn {:::, _, [{{:., _, [Kernel, :to_string]}, _, [_]}, {:binary, _, _}]} -> true binary when is_binary(binary) -> true _ -> false end) end defp interpolated?(_) do false end defp interpolate({:<<>>, _, parts}, fun) do parts = Enum.map_join(parts, "", fn {:::, _, [{{:., _, [Kernel, :to_string]}, _, [arg]}, {:binary, _, _}]} -> "\#{" <> to_string(arg, fun) <> "}" binary when is_binary(binary) -> binary = inspect(binary, []) :binary.part(binary, 1, byte_size(binary) - 2) end) <<?", parts::binary, ?">> end defp module_to_string(atom, _fun) when is_atom(atom) do inspect(atom, []) end defp module_to_string({:&, _, [val]} = expr, fun) when not is_integer(val) do "(" <> to_string(expr, fun) <> ")" end defp module_to_string({:fn, _, _} = expr, fun) do "(" <> to_string(expr, fun) <> ")" end defp module_to_string({_, _, [_ | _] = args} = expr, fun) do if kw_blocks?(List.last(args)) do "(" <> to_string(expr, fun) <> ")" else to_string(expr, fun) end end defp module_to_string(expr, fun) do to_string(expr, fun) end defp unary_call({op, _, [arg]} = ast, fun) when is_atom(op) do case Identifier.unary_op(op) do {_, _} -> if op == :not or op_expr?(arg) do {:ok, fun.(ast, Atom.to_string(op) <> "(" <> to_string(arg, fun) <> ")")} else {:ok, fun.(ast, Atom.to_string(op) <> to_string(arg, fun))} end :error -> :error end end defp unary_call(_, _) do :error end defp binary_call({op, _, [left, right]} = ast, fun) when is_atom(op) do case Identifier.binary_op(op) do {_, _} -> left = op_to_string(left, fun, op, :left) right = op_to_string(right, fun, op, :right) op = if op in [:..], do: "#{op}", else: " #{op} " {:ok, fun.(ast, left <> op <> right)} :error -> :error end end defp binary_call(_, _) do :error end defp sigil_call({sigil, _, [{:<<>>, _, _} = bin, args]} = ast, fun) when is_atom(sigil) and is_list(args) do case Atom.to_string(sigil) do <<"sigil_", name>> -> {:ok, fun.(ast, "~" <> <<name>> <> interpolate(bin, fun) <> sigil_args(args, fun))} _ -> :error end end defp sigil_call(_other, _fun) do :error end defp sigil_args([], _fun), do: "" defp sigil_args(args, fun), do: fun.(args, List.to_string(args)) defp op_expr?(expr) do case expr do {op, _, [_, _]} -> Identifier.binary_op(op) != :error {op, _, [_]} -> Identifier.unary_op(op) != :error _ -> false end end defp call_to_string(atom, _fun) when is_atom(atom), do: Atom.to_string(atom) defp call_to_string({:., _, [arg]}, fun), do: module_to_string(arg, fun) <> "." defp call_to_string({:., _, [left, right]}, fun) when is_atom(right), do: module_to_string(left, fun) <> "." <> call_to_string_for_atom(right) defp call_to_string({:., _, [left, right]}, fun), do: module_to_string(left, fun) <> "." <> call_to_string(right, fun) defp call_to_string(other, fun), do: to_string(other, fun) defp call_to_string_with_args(target, args, fun) do target = call_to_string(target, fun) args = args_to_string(args, fun) target <> "(" <> args <> ")" end defp call_to_string_for_atom(atom) do Identifier.inspect_as_function(atom) end defp args_to_string(args, fun) do {list, last} = split_last(args) if last != [] and Inspect.List.keyword?(last) do prefix = case list do [] -> "" _ -> Enum.map_join(list, ", ", &to_string(&1, fun)) <> ", " end prefix <> kw_list_to_string(last, fun) else Enum.map_join(args, ", ", &to_string(&1, fun)) end end defp kw_blocks_to_string(kw, fun) do Enum.reduce(unquote(kw_keywords), " ", fn(x, acc) -> case Keyword.has_key?(kw, x) do true -> acc <> kw_block_to_string(x, Keyword.get(kw, x), fun) false -> acc end end) <> "end" end defp kw_block_to_string(key, value, fun) do block = adjust_new_lines block_to_string(value, fun), "\n " Atom.to_string(key) <> "\n " <> block <> "\n" end defp block_to_string([{:->, _, _} | _] = block, fun) do Enum.map_join(block, "\n", fn({:->, _, [left, right]}) -> left = comma_join_or_empty_paren(left, fun, false) left <> "->\n " <> adjust_new_lines block_to_string(right, fun), "\n " end) end defp block_to_string({:__block__, _, exprs}, fun) do Enum.map_join(exprs, "\n", &to_string(&1, fun)) end defp block_to_string(other, fun), do: to_string(other, fun) defp map_to_string([{:|, _, [update_map, update_args]}], fun) do to_string(update_map, fun) <> " | " <> map_to_string(update_args, fun) end defp map_to_string(list, fun) do cond do Inspect.List.keyword?(list) -> kw_list_to_string(list, fun) true -> map_list_to_string(list, fun) end end defp kw_list_to_string(list, fun) do Enum.map_join(list, ", ", fn {key, value} -> Identifier.inspect_as_key(key) <> to_string(value, fun) end) end defp map_list_to_string(list, fun) do Enum.map_join(list, ", ", fn {key, value} -> to_string(key, fun) <> " => " <> to_string(value, fun) end) end defp wrap_in_parenthesis(expr, fun) do "(" <> to_string(expr, fun) <> ")" end defp op_to_string({op, _, [_, _]} = expr, fun, parent_op, side) when is_atom(op) do case Identifier.binary_op(op) do {_, prec} -> {parent_assoc, parent_prec} = Identifier.binary_op(parent_op) cond do parent_prec < prec -> to_string(expr, fun) parent_prec > prec -> wrap_in_parenthesis(expr, fun) parent_assoc == side -> to_string(expr, fun) true -> wrap_in_parenthesis(expr, fun) end :error -> to_string(expr, fun) end end defp op_to_string(expr, fun, _, _), do: to_string(expr, fun) defp arrow_to_string(pairs, fun, paren \\ false) do Enum.map_join(pairs, "; ", fn({:->, _, [left, right]}) -> left = comma_join_or_empty_paren(left, fun, paren) left <> "-> " <> to_string(right, fun) end) end defp comma_join_or_empty_paren([], _fun, true), do: "() " defp comma_join_or_empty_paren([], _fun, false), do: "" defp comma_join_or_empty_paren(left, fun, _) do Enum.map_join(left, ", ", &to_string(&1, fun)) <> " " end defp split_last([]) do {[], []} end defp split_last(args) do {left, [right]} = Enum.split(args, -1) {left, right} end defp adjust_new_lines(block, replacement) do for <<x <- block>>, into: "" do case x == ?\n do true -> replacement false -> <<x>> end end end @doc """ Receives an AST node and expands it once. The following contents are expanded: * Macros (local or remote) * Aliases are expanded (if possible) and return atoms * Compilation environment macros (`__ENV__/0`, `__MODULE__/0` and `__DIR__/0`) * Module attributes reader (`@foo`) If the expression cannot be expanded, it returns the expression itself. Notice that `expand_once/2` performs the expansion just once and it is not recursive. Check `expand/2` for expansion until the node can no longer be expanded. ## Examples In the example below, we have a macro that generates a module with a function named `name_length` that returns the length of the module name. The value of this function will be calculated at compilation time and not at runtime. Consider the implementation below: defmacro defmodule_with_length(name, do: block) do length = length(Atom.to_charlist(name)) quote do defmodule unquote(name) do def name_length, do: unquote(length) unquote(block) end end end When invoked like this: defmodule_with_length My.Module do def other_function, do: ... end The compilation will fail because `My.Module` when quoted is not an atom, but a syntax tree as follow: {:__aliases__, [], [:My, :Module]} That said, we need to expand the aliases node above to an atom, so we can retrieve its length. Expanding the node is not straightforward because we also need to expand the caller aliases. For example: alias MyHelpers, as: My defmodule_with_length My.Module do def other_function, do: ... end The final module name will be `MyHelpers.Module` and not `My.Module`. With `Macro.expand/2`, such aliases are taken into consideration. Local and remote macros are also expanded. We could rewrite our macro above to use this function as: defmacro defmodule_with_length(name, do: block) do expanded = Macro.expand(name, __CALLER__) length = length(Atom.to_charlist(expanded)) quote do defmodule unquote(name) do def name_length, do: unquote(length) unquote(block) end end end """ def expand_once(ast, env) do elem(do_expand_once(ast, env), 0) end defp do_expand_once({:__aliases__, _, _} = original, env) do case :elixir_aliases.expand(original, env.aliases, env.macro_aliases, env.lexical_tracker) do receiver when is_atom(receiver) -> :elixir_lexical.record_remote(receiver, env.function, env.lexical_tracker) {receiver, true} aliases -> aliases = :lists.map(&elem(do_expand_once(&1, env), 0), aliases) case :lists.all(&is_atom/1, aliases) do true -> receiver = :elixir_aliases.concat(aliases) :elixir_lexical.record_remote(receiver, env.function, env.lexical_tracker) {receiver, true} false -> {original, false} end end end # Expand compilation environment macros defp do_expand_once({:__MODULE__, _, atom}, env) when is_atom(atom), do: {env.module, true} defp do_expand_once({:__DIR__, _, atom}, env) when is_atom(atom), do: {:filename.dirname(env.file), true} defp do_expand_once({:__ENV__, _, atom}, env) when is_atom(atom), do: {{:%{}, [], Map.to_list(env)}, true} defp do_expand_once({{:., _, [{:__ENV__, _, atom}, field]}, _, []} = original, env) when is_atom(atom) and is_atom(field) do if Map.has_key?(env, field) do {Map.get(env, field), true} else {original, false} end end # Expand possible macro import invocation defp do_expand_once({atom, meta, context} = original, env) when is_atom(atom) and is_list(meta) and is_atom(context) do if :lists.member({atom, Keyword.get(meta, :counter, context)}, env.vars) do {original, false} else case do_expand_once({atom, meta, []}, env) do {_, true} = exp -> exp {_, false} -> {original, false} end end end defp do_expand_once({atom, meta, args} = original, env) when is_atom(atom) and is_list(args) and is_list(meta) do arity = length(args) if :elixir_import.special_form(atom, arity) do {original, false} else module = env.module extra = if function_exported?(module, :__info__, 1) do [{module, module.__info__(:macros)}] else [] end expand = :elixir_dispatch.expand_import(meta, {atom, length(args)}, args, env, extra, true) case expand do {:ok, receiver, quoted} -> next = :erlang.unique_integer() {:elixir_quote.linify_with_context_counter(0, {receiver, next}, quoted), true} {:ok, _receiver, _name, _args} -> {original, false} :error -> {original, false} end end end # Expand possible macro require invocation defp do_expand_once({{:., _, [left, right]}, meta, args} = original, env) when is_atom(right) do {receiver, _} = do_expand_once(left, env) case is_atom(receiver) do false -> {original, false} true -> expand = :elixir_dispatch.expand_require(meta, receiver, {right, length(args)}, args, env) case expand do {:ok, receiver, quoted} -> next = :erlang.unique_integer() {:elixir_quote.linify_with_context_counter(0, {receiver, next}, quoted), true} :error -> {original, false} end end end # Anything else is just returned defp do_expand_once(other, _env), do: {other, false} @doc """ Receives an AST node and expands it until it can no longer be expanded. This function uses `expand_once/2` under the hood. Check it out for more information and examples. """ def expand(tree, env) do expand_until({tree, true}, env) end defp expand_until({tree, true}, env) do expand_until(do_expand_once(tree, env), env) end defp expand_until({tree, false}, _env) do tree end @doc """ Converts the given atom or binary to underscore format. If an atom is given, it is assumed to be an Elixir module, so it is converted to a binary and then processed. This function was designed to underscore language identifiers/tokens, that's why it belongs to the `Macro` module. Do not use it as a general mechanism for underscoring strings as it does not support Unicode or characters that are not valid in Elixir identifiers. ## Examples iex> Macro.underscore "FooBar" "foo_bar" iex> Macro.underscore "Foo.Bar" "foo/bar" iex> Macro.underscore Foo.Bar "foo/bar" In general, `underscore` can be thought of as the reverse of `camelize`, however, in some cases formatting may be lost: iex> Macro.underscore "SAPExample" "sap_example" iex> Macro.camelize "sap_example" "SapExample" iex> Macro.camelize "hello_10" "Hello10" """ def underscore(atom) when is_atom(atom) do "Elixir." <> rest = Atom.to_string(atom) underscore(rest) end def underscore(<<h, t::binary>>) do <<to_lower_char(h)>> <> do_underscore(t, h) end def underscore("") do "" end defp do_underscore(<<h, t, rest::binary>>, _) when (h >= ?A and h <= ?Z) and not (t >= ?A and t <= ?Z) and t != ?. and t != ?_ do <<?_, to_lower_char(h), t>> <> do_underscore(rest, t) end defp do_underscore(<<h, t::binary>>, prev) when (h >= ?A and h <= ?Z) and not (prev >= ?A and prev <= ?Z) and prev != ?_ do <<?_, to_lower_char(h)>> <> do_underscore(t, h) end defp do_underscore(<<?., t::binary>>, _) do <<?/>> <> underscore(t) end defp do_underscore(<<h, t::binary>>, _) do <<to_lower_char(h)>> <> do_underscore(t, h) end defp do_underscore(<<>>, _) do <<>> end @doc """ Converts the given string to CamelCase format. This function was designed to camelize language identifiers/tokens, that's why it belongs to the `Macro` module. Do not use it as a general mechanism for camelizing strings as it does not support Unicode or characters that are not valid in Elixir identifiers. ## Examples iex> Macro.camelize "foo_bar" "FooBar" If uppercase characters are present, they are not modified in anyway as a mechanism to preserve acronyms: iex> Macro.camelize "API.V1" "API.V1" iex> Macro.camelize "API_SPEC" "API_SPEC" """ @spec camelize(String.t) :: String.t def camelize(string) def camelize(""), do: "" def camelize(<<?_, t::binary>>), do: camelize(t) def camelize(<<h, t::binary>>), do: <<to_upper_char(h)>> <> do_camelize(t) defp do_camelize(<<?_, ?_, t::binary>>), do: do_camelize(<<?_, t::binary >>) defp do_camelize(<<?_, h, t::binary>>) when h >= ?a and h <= ?z, do: <<to_upper_char(h)>> <> do_camelize(t) defp do_camelize(<<?_, h, t::binary>>) when h >= ?0 and h <= ?9, do: <<h>> <> do_camelize(t) defp do_camelize(<<?_>>), do: <<>> defp do_camelize(<<?/, t::binary>>), do: <<?.>> <> camelize(t) defp do_camelize(<<h, t::binary>>), do: <<h>> <> do_camelize(t) defp do_camelize(<<>>), do: <<>> defp to_upper_char(char) when char >= ?a and char <= ?z, do: char - 32 defp to_upper_char(char), do: char defp to_lower_char(char) when char >= ?A and char <= ?Z, do: char + 32 defp to_lower_char(char), do: char end
30.040154
106
0.611974
039ab9e6aed6d9febbcebf57f30a5f9dc56ddbb2
2,389
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_gift_membership_received_details.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_gift_membership_received_details.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_gift_membership_received_details.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "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.YouTube.V3.Model.LiveChatGiftMembershipReceivedDetails do @moduledoc """ ## Attributes * `associatedMembershipGiftingMessageId` (*type:* `String.t`, *default:* `nil`) - The ID of the membership gifting message that is related to this gift membership. This ID will always refer to a message whose type is 'membershipGiftingEvent'. * `gifterChannelId` (*type:* `String.t`, *default:* `nil`) - The ID of the user that made the membership gifting purchase. This matches the `snippet.authorChannelId` of the associated membership gifting message. * `memberLevelName` (*type:* `String.t`, *default:* `nil`) - The name of the Level at which the viewer is a member. This matches the `snippet.membershipGiftingDetails.giftMembershipsLevelName` of the associated membership gifting message. The Level names are defined by the YouTube channel offering the Membership. In some situations this field isn't filled. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :associatedMembershipGiftingMessageId => String.t() | nil, :gifterChannelId => String.t() | nil, :memberLevelName => String.t() | nil } field(:associatedMembershipGiftingMessageId) field(:gifterChannelId) field(:memberLevelName) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.LiveChatGiftMembershipReceivedDetails do def decode(value, options) do GoogleApi.YouTube.V3.Model.LiveChatGiftMembershipReceivedDetails.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.LiveChatGiftMembershipReceivedDetails do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.075472
362
0.756802
039ae08dcf0653469c097574ec77f33bdb27c1de
542
exs
Elixir
video-code/30-application/servy/mix.exs
anwarsky/elixir_sample2
613599113e15fcd400853fc0e560a39001435f6d
[ "Unlicense" ]
null
null
null
video-code/30-application/servy/mix.exs
anwarsky/elixir_sample2
613599113e15fcd400853fc0e560a39001435f6d
[ "Unlicense" ]
null
null
null
video-code/30-application/servy/mix.exs
anwarsky/elixir_sample2
613599113e15fcd400853fc0e560a39001435f6d
[ "Unlicense" ]
null
null
null
defmodule Servy.Mixfile do use Mix.Project def project do [ app: :servy, description: "A humble HTTP server", 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: {Servy, []}, env: [port: 3000] ] end # Run "mix help deps" to learn about dependencies. defp deps do [{:poison, "~> 3.1"}] end end
18.066667
59
0.564576
039b475ca5e8af57ff34280421244a3afe743650
881
ex
Elixir
priv/templates/comgen.build/aggregate.ex
andyl/phx-cmdd
f72319d81b264b4deba4831ee1d0eb725d2b5adb
[ "MIT" ]
5
2019-05-23T23:25:25.000Z
2019-05-31T12:10:59.000Z
priv/templates/comgen.build/aggregate.ex
andyl/comgen
f72319d81b264b4deba4831ee1d0eb725d2b5adb
[ "MIT" ]
3
2019-05-31T04:42:02.000Z
2019-06-01T06:42:14.000Z
priv/templates/comgen.build/aggregate.ex
andyl/comgen
f72319d81b264b4deba4831ee1d0eb725d2b5adb
[ "MIT" ]
1
2019-06-01T05:04:14.000Z
2019-06-01T05:04:14.000Z
# <%= filedata.templates.lib.dst %> defmodule <%= filedata.module_long %> do defstruct [<%= filedata.string_fields %> ] alias <%= filedata.module_long %> <%= for command <- annotations.commands do %> alias <%= command.module_long %> <% end %> <%= for event <- annotations.events do %> alias <%= event.module_long %> <% end %> # ----- PUBLIC COMMAND API <%= for cmd <- filedata.api do %> def execute(%<%= filedata.name %>{}, %<%= cmd.cmd_name %>{<%= cmd.cmd_params %>}) do # your code here %<%= cmd.ev_name %>{<%= cmd.ev_params %>} end <% end %> # ----- STATE MUTATORS <%= for event <- filedata.mutators do %> def account(%<%= filedata.name %>{} = <%= event.old_state %>, %<%= event.ev_name %>{<%= event.ev_params %>}) do # your code here %<%= event.ev_name %>{<%= event.old_state %> | <%= event.ev_params %>} end <% end %> end
33.884615
113
0.569807
039b47c84a2b682ba705e7302a3d0117469b3c22
3,354
ex
Elixir
lib/gnat/connection_supervisor.ex
lubien/nats.ex
9ddb11acbca7727e97c6624425a2cb22243cfafe
[ "MIT" ]
102
2019-04-17T06:19:48.000Z
2022-03-31T02:36:11.000Z
lib/gnat/connection_supervisor.ex
lubien/nats.ex
9ddb11acbca7727e97c6624425a2cb22243cfafe
[ "MIT" ]
68
2017-03-23T04:54:00.000Z
2019-03-04T03:30:28.000Z
lib/gnat/connection_supervisor.ex
lubien/nats.ex
9ddb11acbca7727e97c6624425a2cb22243cfafe
[ "MIT" ]
17
2019-05-07T19:33:17.000Z
2022-03-24T18:27:25.000Z
defmodule Gnat.ConnectionSupervisor do use GenServer require Logger @moduledoc """ A process that can supervise a named connection for you If you would like to supervise a Gnat connection and have it automatically re-connect in case of failure you can use this module in your supervision tree. It takes a map with the following data: ``` gnat_supervisor_settings = %{ name: :gnat, # (required) the registered named you want to give the Gnat connection backoff_period: 4_000, # number of milliseconds to wait between consecutive reconnect attempts (default: 2_000) connection_settings: [ %{host: '10.0.0.100', port: 4222}, %{host: '10.0.0.101', port: 4222}, ] } ``` The connection settings can specify all of the same values that you pass to `Gnat.start_link/1`. Each time a connection is attempted we will use one of the provided connection settings to open the connection. This is a simplistic way of load balancing your connections across a cluster of nats nodes and allowing failover to other nodes in the cluster if one goes down. To use this in your supervision tree add an entry like this: ``` import Supervisor.Spec worker(Gnat.ConnectionSupervisor, [gnat_supervisor_settings, [name: :my_connection_supervisor]]) ``` The second argument is used as GenServer options so you can give the supervisor a registered name as well if you like. Now in the rest of your code you can call things like: ``` :ok = Gnat.pub(:gnat, "subject", "message") ``` And it will use your supervised connection. If the connection is down when you call that function (or dies during that function) it will raise an error. """ @spec start_link(map(), keyword()) :: GenServer.on_start def start_link(settings, options \\ []) do GenServer.start_link(__MODULE__, settings, options) end @impl GenServer def init(options) do state = %{ backoff_period: Map.get(options, :backoff_period, 2000), connection_settings: Map.fetch!(options, :connection_settings), name: Map.fetch!(options, :name), gnat: nil, } Process.flag(:trap_exit, true) send self(), :attempt_connection {:ok, state} end @impl GenServer def handle_info(:attempt_connection, state) do connection_config = random_connection_config(state) Logger.debug "connecting to #{inspect connection_config}" case Gnat.start_link(connection_config, name: state.name) do {:ok, gnat} -> {:noreply, %{state | gnat: gnat}} {:error, err} -> Logger.error "failed to connect #{inspect err}" {:noreply, %{state | gnat: nil}} # we will get an :EXIT message and handle it there end end def handle_info({:EXIT, _pid, reason}, %{gnat: nil}=state) do Logger.error "failed to connect #{inspect reason}" Process.send_after(self(), :attempt_connection, state.backoff_period) {:noreply, state} end def handle_info({:EXIT, _pid, reason}, state) do Logger.error "connection failed #{inspect reason}" send self(), :attempt_connection {:noreply, state} end def handle_info(msg, state) do Logger.error "#{__MODULE__} received unexpected message #{inspect msg}" {:noreply, state} end defp random_connection_config(%{connection_settings: connection_settings}) do connection_settings |> Enum.random() end end
38.551724
371
0.710197
039b56317105697c2ca28a8c3936ca81eb05aee5
3,945
exs
Elixir
test/people_sorter/people_list_test.exs
mstang/people_sorter
e712622c071748c79b26e977a8b029e1ba1877c5
[ "MIT" ]
null
null
null
test/people_sorter/people_list_test.exs
mstang/people_sorter
e712622c071748c79b26e977a8b029e1ba1877c5
[ "MIT" ]
null
null
null
test/people_sorter/people_list_test.exs
mstang/people_sorter
e712622c071748c79b26e977a8b029e1ba1877c5
[ "MIT" ]
null
null
null
defmodule PeopleSorter.PersonListTest do use ExUnit.Case, async: true alias Faker.{Color, Internet, Person} setup do child_spec = %{ id: TestProcess, start: {PeopleSorter.PeopleList, :start_link, [[], [name: TestProcess]]} } person_1 = create_random_person() person_2 = create_random_person() person_3 = create_random_person() {:ok, child_spec: child_spec, person_1: person_1, person_2: person_2, person_3: person_3} end test "returns an empty list", %{child_spec: child_spec} do pid = start_supervised!(child_spec) assert PeopleSorter.get_list(pid) == [] end test "returns an empty list even when killed", %{child_spec: child_spec} do pid = start_supervised!(child_spec) Process.exit(pid, :normal) assert PeopleSorter.get_list(pid) == [] end test "add a person", %{child_spec: child_spec, person_1: person_1} do pid = start_supervised!(child_spec) PeopleSorter.add_person(pid, person_1) assert person_1 == pid |> PeopleSorter.get_list() |> List.first() end test "add three people", %{ child_spec: child_spec, person_1: person_1, person_2: person_2, person_3: person_3 } do pid = start_supervised!(child_spec) PeopleSorter.add_person(pid, person_1) PeopleSorter.add_person(pid, person_2) PeopleSorter.add_person(pid, person_3) assert [person_3, person_2, person_1] == PeopleSorter.get_list(pid) end test "sort list by birthday", %{ child_spec: child_spec } do pid = start_supervised!(child_spec) Enum.each(1..30, fn _i -> new_person = create_random_person() PeopleSorter.add_person(pid, new_person) end) sorted_dob = pid |> PeopleSorter.get_list() |> Enum.map(fn person -> Map.get(person, :date_of_birth) end) |> Enum.sort(Date) sorted_persons = pid |> PeopleSorter.get_list_sorted_by_dob() |> Enum.map(fn person -> Map.get(person, :date_of_birth) end) assert sorted_dob == sorted_persons end test "sort list by last_name", %{ child_spec: child_spec } do pid = start_supervised!(child_spec) Enum.each(1..30, fn _i -> new_person = create_random_person() PeopleSorter.add_person(pid, new_person) end) sorted_last_name = pid |> PeopleSorter.get_list() |> Enum.map(fn person -> Map.get(person, :last_name) end) |> Enum.sort(:desc) sorted_persons = pid |> PeopleSorter.get_list_sorted_by_last_name() |> Enum.map(fn person -> Map.get(person, :last_name) end) assert sorted_last_name == sorted_persons end test "sort list by color, last_name", %{ child_spec: child_spec } do pid = start_supervised!(child_spec) person_2 = %PeopleSorter.Person{ date_of_birth: ~D[1945-08-09], email: "gracie2054@ward.biz", favorite_color: "Blue", first_name: "Scottie", last_name: "Smith" } PeopleSorter.add_person(pid, person_2) person_3 = %PeopleSorter.Person{ date_of_birth: ~D[1945-09-27], email: "assunta_rogahn@langworth.biz", favorite_color: "Red", first_name: "Danny", last_name: "Avon" } PeopleSorter.add_person(pid, person_3) person_1 = %PeopleSorter.Person{ date_of_birth: ~D[1976-02-10], email: "lexie2093@mayer.org", favorite_color: "Blue", first_name: "Jaron", last_name: "Hermiston" } PeopleSorter.add_person(pid, person_1) sorted_persons = PeopleSorter.get_list_sorted_by_color_last_name(pid) assert [person_1, person_2, person_3] == sorted_persons end defp create_random_person() do %PeopleSorter.Person{ date_of_birth: Faker.Date.date_of_birth(18..99), email: Internet.email(), favorite_color: Color.name(), first_name: Person.first_name(), last_name: Person.last_name() } end end
24.968354
93
0.656781
039b63594427614f00a77cfee6759acf6b4af199
1,870
ex
Elixir
clients/script/lib/google_api/script/v1/model/list_user_processes_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/script/lib/google_api/script/v1/model/list_user_processes_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/script/lib/google_api/script/v1/model/list_user_processes_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 &quot;License&quot;); # 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 &quot;AS IS&quot; 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.Script.V1.Model.ListUserProcessesResponse do @moduledoc """ Response with the list of Process resources. ## Attributes * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Token for the next page of results. If empty, there are no more pages remaining. * `processes` (*type:* `list(GoogleApi.Script.V1.Model.GoogleAppsScriptTypeProcess.t)`, *default:* `nil`) - List of processes matching request parameters. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :nextPageToken => String.t(), :processes => list(GoogleApi.Script.V1.Model.GoogleAppsScriptTypeProcess.t()) } field(:nextPageToken) field(:processes, as: GoogleApi.Script.V1.Model.GoogleAppsScriptTypeProcess, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Script.V1.Model.ListUserProcessesResponse do def decode(value, options) do GoogleApi.Script.V1.Model.ListUserProcessesResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Script.V1.Model.ListUserProcessesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.961538
158
0.742246
039b6ee3fa63629f4217e78e7a9a35b527123f9c
952
ex
Elixir
lib/web.ex
openrowing/raceman2
eee2d51c50bddf63b9c5b9b351424d4c056fa27d
[ "Apache-2.0" ]
null
null
null
lib/web.ex
openrowing/raceman2
eee2d51c50bddf63b9c5b9b351424d4c056fa27d
[ "Apache-2.0" ]
null
null
null
lib/web.ex
openrowing/raceman2
eee2d51c50bddf63b9c5b9b351424d4c056fa27d
[ "Apache-2.0" ]
null
null
null
defmodule Web do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec, warn: false children = [ # Start the endpoint when the application starts supervisor(Web.Endpoint, []), # Start the Ecto repository supervisor(Web.Repo, []), # Here you could define other workers and supervisors as children # worker(Web.Worker, [arg1, arg2, arg3]), ] # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Web.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do Web.Endpoint.config_change(changed, removed) :ok end end
30.709677
71
0.703782
039b8ffa1b9dd2f07c620b411ae265e57e2bea30
183
exs
Elixir
blog_data_writer_server/config/dev.exs
xawe/elixir_micro_blog
eee893238a9647708336901f3ead4629067d590f
[ "MIT" ]
null
null
null
blog_data_writer_server/config/dev.exs
xawe/elixir_micro_blog
eee893238a9647708336901f3ead4629067d590f
[ "MIT" ]
null
null
null
blog_data_writer_server/config/dev.exs
xawe/elixir_micro_blog
eee893238a9647708336901f3ead4629067d590f
[ "MIT" ]
null
null
null
import Config config :app, App.Repo, database: "blog_data_writer_dev", username: "postgres", password: "postgres", hostname: "localhost" config :app, ecto_repos: [App.Repo]
18.3
35
0.715847
039b935fa5562e7fcda1dae43dde64408f9b0f37
2,737
ex
Elixir
lib/cadet/auth/providers/github.ex
source-academy/cadet
c447552453f78799755de73f66999e4c9d20383c
[ "Apache-2.0" ]
27
2018-01-20T05:56:24.000Z
2021-05-24T03:21:55.000Z
lib/cadet/auth/providers/github.ex
source-academy/cadet
c447552453f78799755de73f66999e4c9d20383c
[ "Apache-2.0" ]
731
2018-04-16T13:25:49.000Z
2021-06-22T07:16:12.000Z
lib/cadet/auth/providers/github.ex
source-academy/cadet
c447552453f78799755de73f66999e4c9d20383c
[ "Apache-2.0" ]
43
2018-01-20T06:35:46.000Z
2021-05-05T03:22:35.000Z
defmodule Cadet.Auth.Providers.GitHub do @moduledoc """ Provides identity using GitHub OAuth. """ alias Cadet.Auth.Provider @behaviour Provider @type config :: %{ clients: %{}, token_url: String.t(), user_api: String.t() } @spec authorise(config(), Provider.code(), Provider.client_id(), Provider.redirect_uri()) :: {:ok, %{token: Provider.token(), username: String.t()}} | {:error, Provider.error(), String.t()} def authorise(config, code, client_id, redirect_uri) do token_headers = [ {"Content-Type", "application/x-www-form-urlencoded"}, {"Accept", "application/json"} ] token_url = config.token_url user_api = config.user_api with {:validate_client, {:ok, client_secret}} <- {:validate_client, Map.fetch(config.clients, client_id)}, {:token_query, token_query} <- {:token_query, URI.encode_query(%{ client_id: client_id, client_secret: client_secret, code: code, redirect_uri: redirect_uri })}, {:token, {:ok, %{body: body, status_code: 200}}} <- {:token, HTTPoison.post(token_url, token_query, token_headers)}, {:token_response, %{"access_token" => token}} <- {:token_response, Jason.decode!(body)}, {:user, {:ok, %{"login" => username}}} <- {:user, api_call(user_api, token)} do {:ok, %{token: token, username: username}} else {:validate_client, :error} -> {:error, :invalid_credentials, "Invalid client id"} {:token, {:ok, %{status_code: status}}} -> {:error, :upstream, "Status code #{status} from GitHub"} {:token_response, %{"error" => error}} -> {:error, :invalid_credentials, "Error from GitHub: #{error}"} {:user, {:error, _, _} = error} -> error end end @spec get_name(config(), Provider.token()) :: {:ok, String.t()} | {:error, Provider.error(), String.t()} def get_name(config, token) do user_api = config.user_api case api_call(user_api, token) do {:ok, %{"name" => name}} -> {:ok, name} {:error, _, _} = error -> error end end def get_role(_config, _claims) do # There is no role specified for the GitHub provider {:error, :invalid_credentials, "No role specified in token"} end defp api_call(url, token) do headers = [{"Authorization", "token " <> token}] case HTTPoison.get(url, headers) do {:ok, %{body: body, status_code: 200}} -> {:ok, Jason.decode!(body)} {:ok, %{status_code: status}} -> {:error, :upstream, "Status code #{status} from GitHub"} end end end
31.102273
97
0.576178
039b9d18294189c4b5fb707fac1d46ec7ba0af3c
16,859
ex
Elixir
lib/chat_api/slack/event.ex
Blazt0/papercups
5996b268f1d52e4463d546dcc458f9ecd0a7ffcd
[ "MIT" ]
1
2021-08-02T07:59:41.000Z
2021-08-02T07:59:41.000Z
lib/chat_api/slack/event.ex
Blazt0/papercups
5996b268f1d52e4463d546dcc458f9ecd0a7ffcd
[ "MIT" ]
null
null
null
lib/chat_api/slack/event.ex
Blazt0/papercups
5996b268f1d52e4463d546dcc458f9ecd0a7ffcd
[ "MIT" ]
null
null
null
defmodule ChatApi.Slack.Event do require Logger alias ChatApi.{ Companies, Conversations, Messages, Slack, SlackAuthorizations, SlackConversationThreads } alias ChatApi.Conversations.Conversation alias ChatApi.Messages.Message alias ChatApi.SlackAuthorizations.SlackAuthorization @spec handle_payload(map()) :: any() def handle_payload(%{ "event" => event, "team_id" => team, "is_ext_shared_channel" => true }) do # NB: this is a bit of a hack -- we override the "team" id in the "event" payload # to match the "team" where the Papercups app is installed (rather than the "team" # of the external workspace, where messages may also originate from) event |> Map.merge(%{"team" => team}) |> handle_event() end def handle_payload( %{ "event" => %{"team" => team} = event, "team_id" => payload_team_id, "is_ext_shared_channel" => false } = payload ) do if payload_team_id != team do Logger.error( "Team IDs on Slack event payload do not match: #{inspect(payload_team_id)} #{ inspect(team) } (#{inspect(payload)})" ) end handle_event(event) end def handle_payload(%{ "event" => event, "team_id" => team, "is_ext_shared_channel" => false }) do # If the "team" field is missing from the "event", add the payload "team_id" event |> Map.merge(%{"team" => team}) |> handle_event() end def handle_payload(%{"event" => event}), do: handle_event(event) def handle_payload(_), do: nil @spec handle_event(map()) :: any() def handle_event(%{"bot_id" => _bot_id} = _event) do # Don't do anything on bot events for now nil end def handle_event( %{ "type" => "message", "text" => text, "team" => team, "thread_ts" => thread_ts, "channel" => slack_channel_id, "user" => slack_user_id } = event ) do Logger.debug("Handling Slack message reply event: #{inspect(event)}") with {:ok, conversation} <- find_thread_conversation(thread_ts, slack_channel_id), %{account_id: account_id, id: conversation_id} <- conversation, primary_reply_authorization <- SlackAuthorizations.get_authorization_by_account(account_id, %{type: "reply"}), files <- Map.get(event, "files", []) do if Slack.Helpers.is_primary_channel?(primary_reply_authorization, slack_channel_id) do text |> Slack.Helpers.parse_message_type_params() |> Map.merge(%{ "body" => Slack.Helpers.sanitize_slack_message(text, primary_reply_authorization), "conversation_id" => conversation_id, "account_id" => account_id, "source" => "slack", "sent_at" => event |> Map.get("ts") |> Slack.Helpers.slack_ts_to_utc(), "user_id" => Slack.Helpers.get_admin_sender_id( primary_reply_authorization, slack_user_id, conversation.assignee_id ) }) |> create_and_fetch_message_with_attachments!(files, primary_reply_authorization) |> Messages.Notification.broadcast_to_customer!() |> Messages.Notification.broadcast_to_admin!() |> Messages.Notification.notify(:webhooks) |> Messages.Notification.notify(:slack_support_channel) |> Messages.Notification.notify(:slack_company_channel) |> Messages.Notification.notify(:conversation_reply_email) |> Messages.Notification.notify(:gmail) |> Messages.Notification.notify(:sms) |> Messages.Notification.notify(:ses) |> Messages.Notification.notify(:mattermost) |> Messages.Helpers.handle_post_creation_hooks() else case SlackAuthorizations.get_authorization_by_account(account_id, %{ team_id: team, type: "support" }) do nil -> nil authorization -> authorization |> Slack.Helpers.format_sender_id!(slack_user_id, slack_channel_id) |> Map.merge(%{ "body" => Slack.Helpers.sanitize_slack_message(text, authorization), "conversation_id" => conversation_id, "account_id" => account_id, "sent_at" => event |> Map.get("ts") |> Slack.Helpers.slack_ts_to_utc(), "source" => "slack" }) |> create_and_fetch_message_with_attachments!(files, authorization) |> Messages.Notification.broadcast_to_customer!() |> Messages.Notification.broadcast_to_admin!() |> Messages.Notification.notify(:webhooks) |> Messages.Notification.notify(:slack) |> Messages.Helpers.handle_post_creation_hooks() end end else # If an existing conversation is not found, we check to see if this is a reply to a bot # or agent message. At the moment, we want to start a new thread for replies to these messages. {:error, :not_found} -> handle_reply_to_unknown_thread(event) error -> error end end # NB: this currently listens for the Papercups app being added to a Slack channel. def handle_event( %{ "type" => "message", # Public channels use subtype "channel_join", while private channels use "group_join" "subtype" => subtype, "user" => slack_user_id, "channel" => slack_channel_id, "inviter" => _slack_inviter_id } = event ) when subtype in ["channel_join", "group_join"] do Logger.info("Slack channel_join/group_join event detected:") Logger.info(inspect(event)) with %{ account_id: account_id, access_token: access_token, channel_id: channel_id, team_id: team_id, team_name: team_name } <- SlackAuthorizations.find_slack_authorization(%{ bot_user_id: slack_user_id, type: "support" }), # This validates that the channel doesn't match the initially connected channel on # the `slack_authorization` record, since we currently treat that channel slightly differently true <- channel_id != slack_channel_id, :ok <- Slack.Validation.validate_no_existing_company(account_id, slack_channel_id), {:ok, response} <- Slack.Client.retrieve_channel_info(slack_channel_id, access_token), {:ok, channel} <- Slack.Extractor.extract_slack_channel(response), %{"name" => name, "purpose" => purpose, "topic" => topic} <- channel do Slack.Helpers.send_internal_notification( "Papercups app was added to Slack channel `##{name}` for account `#{account_id}`" ) # TODO: should we do this? might make onboarding a bit easier, but would also set up # companies with "weird" names (i.e. in the format of a Slack channel name) {:ok, result} = Companies.create_company(%{ # Set default company name to Slack channel name name: name, description: purpose["value"] || topic["value"], account_id: account_id, slack_channel_name: "##{name}", slack_channel_id: slack_channel_id, slack_team_name: team_name, slack_team_id: team_id }) Logger.info("Successfully auto-created company:") Logger.info(inspect(result)) end end def handle_event(%{ "type" => "message", "subtype" => subtype, "user" => _, "channel" => _ }) # Public channels use prefix "channel_*", while private channels use "group_*" when subtype in ["channel_join", "group_join", "channel_leave", "group_leave"], do: nil # TODO: ignore message if it's from a bot? def handle_event( %{ "type" => "message", "text" => _text, "team" => team, "channel" => slack_channel_id, "user" => slack_user_id, "ts" => _ts } = event ) do Logger.debug("Handling Slack new message event: #{inspect(event)}") with %SlackAuthorization{} = authorization <- SlackAuthorizations.find_slack_authorization(%{team_id: team, type: "support"}), %{sync_all_incoming_threads: true} <- SlackAuthorizations.get_authorization_settings(authorization), # TODO: remove after debugging! :ok <- Logger.info("Handling Slack new message event: #{inspect(event)}"), :ok <- Slack.Validation.validate_channel_supported(authorization, slack_channel_id), :ok <- Slack.Validation.validate_non_admin_user(authorization, slack_user_id) do create_new_conversation_from_slack_message(event, authorization) end end def handle_event( %{ "type" => "reaction_added", "reaction" => "eyes", "user" => _user, "item" => %{ "channel" => channel, "ts" => ts, "type" => "message" } } = event ) do Logger.info("Handling Slack reaction event: #{inspect(event)}") with :ok <- Slack.Validation.validate_no_existing_thread(channel, ts), %SlackAuthorization{access_token: access_token} = authorization <- SlackAuthorizations.find_support_authorization_by_channel(channel), %{sync_by_emoji_tagging: true} <- SlackAuthorizations.get_authorization_settings(authorization), {:ok, response} <- Slack.Client.retrieve_message(channel, ts, access_token), {:ok, message} <- Slack.Extractor.extract_slack_message(response) do Logger.info("Slack emoji reaction detected:") Logger.info(inspect(event)) # The message from the conversations.history API doesn't include the channel, so we add it manually message |> Map.merge(%{"channel" => channel}) |> handle_emoji_reaction_event() end end def handle_event(_), do: nil # TODO: DRY this up with the message event handler above, for now the only difference between this one # and that one is: this handler allows admin users to create threads via Slack support channels @spec handle_emoji_reaction_event(map()) :: any() def handle_emoji_reaction_event( %{ "type" => "message", "text" => _text, "team" => team, "channel" => slack_channel_id, "user" => _slack_user_id, "ts" => _ts } = event ) do with authorization <- SlackAuthorizations.find_slack_authorization(%{team_id: team, type: "support"}), :ok <- Slack.Validation.validate_channel_supported(authorization, slack_channel_id) do # TODO: sync whole message thread if there are multiple messages already # (See `Slack.Sync.sync_slack_message_thread(messages, authorization, event)`) create_new_conversation_from_slack_message(event, authorization) end end def handle_emoji_reaction_event(_), do: nil @spec handle_reply_to_unknown_thread(map()) :: any() def handle_reply_to_unknown_thread( %{ "type" => "message", "text" => _text, "team" => team, "thread_ts" => _thread_ts, "channel" => _slack_channel_id, "user" => _slack_user_id } = event ) do with %SlackAuthorization{} = authorization <- SlackAuthorizations.find_slack_authorization(%{team_id: team, type: "support"}), [_ | _] = messages <- Slack.Sync.get_syncable_slack_messages(authorization, event), true <- Slack.Sync.should_sync_slack_messages?(messages) do Slack.Sync.sync_slack_message_thread(messages, authorization, event) end end def handle_reply_to_unknown_thread(_event), do: nil @spec create_and_fetch_message_with_attachments!(map(), list(), SlackAuthorization.t()) :: Message.t() def create_and_fetch_message_with_attachments!( payload, files, %SlackAuthorization{} = authorization ) do file_ids = files |> process_message_attachments(authorization) |> Enum.map(& &1.id) {:ok, message} = Messages.create_message(payload) {_, nil} = Messages.create_attachments(message, file_ids) Messages.get_message!(message.id) end def process_message_attachments(nil, _authorization), do: [] def process_message_attachments([], _authorization), do: [] def process_message_attachments( [_ | _] = files, %SlackAuthorization{ account_id: account_id, access_token: access_token } = _authorization ) do files |> Enum.map(fn %{ "title" => filename, "mimetype" => content_type, "url_private_download" => url } = file -> unique_filename = ChatApi.Aws.generate_unique_filename(filename) with {:ok, %{status: 200, body: body}} when is_binary(body) <- ChatApi.Slack.Client.read_file(url, access_token), {:ok, %{status_code: 200}} <- ChatApi.Aws.upload_binary(body, unique_filename), {:ok, file} <- ChatApi.Files.create_file(%{ "filename" => filename, "unique_filename" => unique_filename, "file_url" => ChatApi.Aws.get_file_url(unique_filename), "content_type" => content_type, "account_id" => account_id }) do file else error -> Logger.error("Failed to process file #{inspect(file)}: #{inspect(error)}") nil end end) |> Enum.reject(&is_nil/1) end # TODO: move to Slack.Helpers? @spec create_new_conversation_from_slack_message(map(), SlackAuthorization.t()) :: Message.t() | {:error, any()} def create_new_conversation_from_slack_message( %{ "type" => "message", "text" => text, "channel" => slack_channel_id, "ts" => ts } = event, %SlackAuthorization{ account_id: account_id, team_id: slack_team_id } = authorization ) do # NB: not ideal, but this may treat an internal/admin user as a "customer", # because at the moment all conversations must have a customer associated with them with {:ok, customer} <- Slack.Helpers.create_or_update_customer_from_slack_event(authorization, event), # TODO: should the conversation + thread + message all be handled in a transaction? # Probably yes at some point, but for now... not too big a deal ¯\_(ツ)_/¯ # TODO: should we handle default assignment here as well? {:ok, conversation} <- Conversations.create_conversation(%{ account_id: account_id, customer_id: customer.id, source: "slack" }), {:ok, message} <- Messages.create_message(%{ account_id: account_id, conversation_id: conversation.id, customer_id: customer.id, body: Slack.Helpers.sanitize_slack_message(text, authorization), sent_at: Slack.Helpers.slack_ts_to_utc(ts), source: "slack" }), {:ok, _slack_conversation_thread} <- SlackConversationThreads.create_slack_conversation_thread(%{ slack_channel: slack_channel_id, slack_team: slack_team_id, slack_thread_ts: ts, account_id: account_id, conversation_id: conversation.id }) do conversation |> Conversations.Notification.broadcast_new_conversation_to_admin!() |> Conversations.Notification.broadcast_new_conversation_to_customer!() |> Conversations.Notification.notify(:webhooks, event: "conversation:created") Messages.get_message!(message.id) |> Messages.Notification.broadcast_to_customer!() |> Messages.Notification.broadcast_to_admin!() |> Messages.Notification.notify(:webhooks) # TODO: should we make this configurable? Or only do it from private channels? # (Leaving this enabled for the emoji reaction use case, since it's an explicit action # as opposed to the auto-syncing that occurs above for all new messages) |> Messages.Notification.notify(:slack, metadata: authorization.metadata) end end @spec find_thread_conversation(binary(), binary()) :: {:ok, Conversation.t()} | {:error, :not_found} defp find_thread_conversation(thread_ts, channel) do case SlackConversationThreads.get_by_slack_thread_ts(thread_ts, channel) do %{conversation: conversation} -> {:ok, conversation} _ -> {:error, :not_found} end end end
37.885393
105
0.619847
039bbac3fb2f119a1702407f7e83729f561f2c4b
619
ex
Elixir
generated-sources/elixir/mojang-authentication/lib/com/github/asyncmc/mojang/authentication/elixir/server/model/access_keys.ex
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/elixir/mojang-authentication/lib/com/github/asyncmc/mojang/authentication/elixir/server/model/access_keys.ex
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/elixir/mojang-authentication/lib/com/github/asyncmc/mojang/authentication/elixir/server/model/access_keys.ex
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule com.github.asyncmc.mojang.authentication.elixir.server.Model.AccessKeys do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"accessToken", :"clientToken" ] @type t :: %__MODULE__{ :"accessToken" => String.t, :"clientToken" => String.t | nil } end defimpl Poison.Decoder, for: com.github.asyncmc.mojang.authentication.elixir.server.Model.AccessKeys do def decode(value, _options) do value end end
22.107143
103
0.701131
039bc6b90973c7a87173ba78ebcc77d900cd788b
2,199
exs
Elixir
demo/config/prod.exs
git-toni/lv-states
588652ae698efc7193dc25a8e4a68b5201aa09bd
[ "MIT" ]
3
2021-07-07T09:10:11.000Z
2022-03-18T10:28:14.000Z
demo/config/prod.exs
git-toni/lv-states
588652ae698efc7193dc25a8e4a68b5201aa09bd
[ "MIT" ]
12
2021-07-06T21:08:21.000Z
2021-09-27T11:11:19.000Z
demo/config/prod.exs
git-toni/lv-states
588652ae698efc7193dc25a8e4a68b5201aa09bd
[ "MIT" ]
null
null
null
use Mix.Config host_url = case System.get_env("DOCKER_DEBUG") do "true" -> "localhost" _ -> "lv-states.fly.dev" end # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :demo, DemoWeb.Endpoint, url: [host: host_url, port: String.to_integer(System.get_env("PORT") || "4000")], cache_static_manifest: "priv/static/cache_manifest.json", transport_options: [socket_opts: [:inet6]] # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :demo, DemoWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), # transport_options: [socket_opts: [:inet6]] # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :demo, DemoWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
34.904762
83
0.707594
039bcc1fa6d75862d55aa49d8d24e4bae5646aaa
2,409
exs
Elixir
config/dev.exs
frunox/discuss
d19367eceb8c68ebef4e565981ceef256b5cb04e
[ "MIT" ]
null
null
null
config/dev.exs
frunox/discuss
d19367eceb8c68ebef4e565981ceef256b5cb04e
[ "MIT" ]
null
null
null
config/dev.exs
frunox/discuss
d19367eceb8c68ebef4e565981ceef256b5cb04e
[ "MIT" ]
null
null
null
import Config # Configure your database config :discuss, Discuss.Repo, username: "postgres", password: "frunox", database: "discuss_dev", hostname: "localhost", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with esbuild to bundle .js and .css sources. config :discuss, DiscussWeb.Endpoint, # Binding to loopback ipv4 address prevents access from other machines. # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. http: [ip: {127, 0, 0, 1}, port: 4000], check_origin: false, code_reloader: true, debug_errors: true, secret_key_base: "IUiZChIuqR5n+kxuIrpFvYISNJkllGSfQbAxX5oZuASrvbWHaxH/ObrdiFFmrl4R", watchers: [ # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args) esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]} ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :discuss, DiscussWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/discuss_web/(live|views)/.*(ex)$", ~r"lib/discuss_web/templates/.*(eex)$", ~r"posts/*/.*(md)$" ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
31.697368
86
0.706517
039bccb014c5701b5605ce0172ebc925d29a5fc0
322
ex
Elixir
lib/publishers/default.ex
krisztian-adam-liqid/ev
a4733d531967f0f4d4066f4e33b58a7414702a15
[ "MIT" ]
2
2021-12-29T15:37:34.000Z
2022-01-12T23:52:47.000Z
lib/publishers/default.ex
krisztian-adam-liqid/ev
a4733d531967f0f4d4066f4e33b58a7414702a15
[ "MIT" ]
null
null
null
lib/publishers/default.ex
krisztian-adam-liqid/ev
a4733d531967f0f4d4066f4e33b58a7414702a15
[ "MIT" ]
1
2022-01-31T11:07:57.000Z
2022-01-31T11:07:57.000Z
defmodule EV.Publishers.Default do @moduledoc """ The default publisher. Simply uses `Ecto.Changeset.apply_action/2` to return an event based on the given changeset. """ @behaviour EV.Publisher @impl EV.Publisher def call(changeset, _opts) do Ecto.Changeset.apply_action(changeset, :insert) end end
21.466667
94
0.736025
039be0eea795386703685f471f181fc8b6554a2e
719
ex
Elixir
lib/peerage/list.ex
kelostrada/peerage
1bc83b2662129161d36901a063553c1650bcbf4e
[ "MIT" ]
389
2016-10-29T01:40:47.000Z
2022-03-19T09:49:26.000Z
lib/peerage/list.ex
kelostrada/peerage
1bc83b2662129161d36901a063553c1650bcbf4e
[ "MIT" ]
18
2017-01-11T13:27:36.000Z
2019-04-09T20:17:15.000Z
lib/peerage/list.ex
kelostrada/peerage
1bc83b2662129161d36901a063553c1650bcbf4e
[ "MIT" ]
23
2017-01-11T12:50:18.000Z
2021-04-12T01:42:54.000Z
defmodule Peerage.Via.List do @behaviour Peerage.Provider @moduledoc """ Uses configurable list of node names. Good for development, or when you know production node names ahead of time. See example below. ### Example ```elixir config :peerage, via: Peerage.Via.List config :peerage, node_list: [ :"myapp1@127.0.0.1", :"myapp2@127.0.0.1" ] ``` $ iex --name myapp1@127.0.0.1 -S mix # one shell $ iex --name myapp2@127.0.0.1 -S mix # other shell I usually wrap the above with a script for launching dev shell, and prod release shells, so that I just call `bin/dev 1` or `bin/prod 2`. """ def poll do Application.fetch_env!(:peerage, :node_list) end end
23.193548
65
0.656467
039bf7bb39ff9a87fbf1b4616da9679104fa0954
3,708
exs
Elixir
test/lib/timber/event_plug_test.exs
montebrown/timber-elixir
1e177cc426422be3617479143038f5882037752f
[ "0BSD" ]
null
null
null
test/lib/timber/event_plug_test.exs
montebrown/timber-elixir
1e177cc426422be3617479143038f5882037752f
[ "0BSD" ]
null
null
null
test/lib/timber/event_plug_test.exs
montebrown/timber-elixir
1e177cc426422be3617479143038f5882037752f
[ "0BSD" ]
null
null
null
defmodule Timber.Integrations.EventPlugTest do # use Timber.TestCase, async: false # use Plug.Test # # import ExUnit.CaptureIO # # require Logger # # describe "Timber.Integrations.EventPlug.call/2" do # test "logs an incoming HTTP request event" do # conn = generate_conn(:get, []) # # log_msg = capture_io(:user, fn -> # Timber.Integrations.EventPlug.call(conn, []) # end) # # {_, metadata} = Timber.TestHelpers.parse_log_line(log_msg) # # http_request = # Map.get(metadata, "event") # |> Map.get("http_request") # # assert http_request["host"] == "www.example.com" # assert http_request["method"] == :get # assert http_request["path"] == "/my_path" # assert http_request["port"] == 80 # assert http_request["scheme"] == :http # assert http_request["query_params"] == %{} # # refute is_nil(http_request["headers"]["request_id"]) # end # # test "allows for a custom request ID header name" do # conn = generate_conn(:get, [request_id_header: "req-id"]) # # log_msg = capture_io(fn -> # Timber.Integrations.EventPlug.call(conn, [request_id_header: "req-id"]) # end) # # {_, metadata} = Timber.TestHelpers.parse_log_line(log_msg) # # http_request = # Map.get(metadata, "event") # |> Map.get("http_request") # # refute is_nil(http_request["headers"]["request_id"]) # end # # test "logs an HTTP response event" do # generate_conn(:get, []) # |> Timber.Integrations.EventPlug.call([]) # |> Plug.Conn.send_resp(200, "") # # metadata = Logger.metadata() # timber_context = Keyword.get(metadata, :timber_context, []) # # assert length(timber_context) == 2 # # http_response = # timber_context # |> Enum.reverse() # |> List.first() # |> Map.get(:data) # # assert http_response.bytes == 0 # assert http_response.headers == %{} # assert http_response.status == 200 # end # # test "correctly calculates HTTP response byte size when using iolist" do # # Weird formatting courtesy of IEx # # The following is iodata that when converted to a binary become: # # # # "{\"errors\":[{\"message\":\"internal server error :*(\",\"key\":\"internal\",\"category\":\"server\"}]}" # # # # which has a byte size of 89 bytes # response_body = # [123, # [[34, ["errors"], 34], 58, # [91, # [[123, # [[34, ["message"], 34], 58, [34, ["internal server error :*("], 34], 44, # [34, ["key"], 34], 58, [34, ["internal"], 34], 44, [34, ["category"], 34], # 58, [34, ["server"], 34]], 125]], 93]], 125] # # generate_conn(:get, []) # |> Timber.Integrations.EventPlug.call([]) # |> Plug.Conn.send_resp(200, response_body) # # metadata = Logger.metadata() # timber_context = Keyword.get(metadata, :timber_context, []) # # assert length(timber_context) == 2 # # http_response = # timber_context # |> Enum.reverse() # |> List.first() # |> Map.get(:data) # # assert http_response.bytes == 89 # end # end # # defp generate_conn(:get, opts) do # request_id_header = Keyword.get(opts, :request_id_header, "x-request-id") # # conn(:get, "/my_path") # |> Plug.Conn.put_req_header("accept", "application/json") # |> Plug.RequestId.call(request_id_header) # |> Plug.Conn.fetch_query_params() # end end
32.526316
116
0.549622
039bf7e4e8a8af43c7cbfd0b77000813e3fb82c9
11,143
exs
Elixir
test/livebook/evaluator_test.exs
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
test/livebook/evaluator_test.exs
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
test/livebook/evaluator_test.exs
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.EvaluatorTest do use ExUnit.Case, async: true alias Livebook.Evaluator setup do {:ok, _pid, evaluator} = start_supervised(Evaluator) %{evaluator: evaluator} end describe "evaluate_code/6" do test "given a valid code returns evaluation result", %{evaluator: evaluator} do code = """ x = 1 y = 2 x + y """ Evaluator.evaluate_code(evaluator, self(), code, :code_1) assert_receive {:evaluation_response, :code_1, {:ok, 3}, %{evaluation_time_ms: _time_ms}} end test "given no prev_ref does not see previous evaluation context", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), "x = 1", :code_1) assert_receive {:evaluation_response, :code_1, _, %{evaluation_time_ms: _time_ms}} ignore_warnings(fn -> Evaluator.evaluate_code(evaluator, self(), "x", :code_2) assert_receive {:evaluation_response, :code_2, {:error, _kind, %CompileError{description: "undefined function x/0"}, _stacktrace}, %{evaluation_time_ms: _time_ms}} end) end test "given prev_ref sees previous evaluation context", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), "x = 1", :code_1) assert_receive {:evaluation_response, :code_1, _, %{evaluation_time_ms: _time_ms}} Evaluator.evaluate_code(evaluator, self(), "x", :code_2, :code_1) assert_receive {:evaluation_response, :code_2, {:ok, 1}, %{evaluation_time_ms: _time_ms}} end test "given invalid prev_ref just uses default context", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), ":hey", :code_1, :code_nonexistent) assert_receive {:evaluation_response, :code_1, {:ok, :hey}, %{evaluation_time_ms: _time_ms}} end test "captures standard output and sends it to the caller", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), ~s{IO.puts("hey")}, :code_1) assert_receive {:evaluation_output, :code_1, "hey\n"} end test "using standard input sends input request to the caller", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), ~s{IO.gets("name: ")}, :code_1) assert_receive {:evaluation_input, :code_1, reply_to, "name: "} send(reply_to, {:evaluation_input_reply, {:ok, "Jake Peralta\n"}}) assert_receive {:evaluation_response, :code_1, {:ok, "Jake Peralta\n"}, %{evaluation_time_ms: _time_ms}} end test "returns error along with its kind and stacktrace", %{evaluator: evaluator} do code = """ List.first(%{}) """ Evaluator.evaluate_code(evaluator, self(), code, :code_1) assert_receive {:evaluation_response, :code_1, {:error, :error, %FunctionClauseError{}, [{List, :first, _arity, _location}]}, %{evaluation_time_ms: _time_ms}} end test "in case of an error returns only the relevant part of stacktrace", %{evaluator: evaluator} do code = """ defmodule Livebook.EvaluatorTest.Stacktrace.Math do def bad_math do result = 1 / 0 {:ok, result} end end defmodule Livebook.EvaluatorTest.Stacktrace.Cat do def meow do Livebook.EvaluatorTest.Stacktrace.Math.bad_math() :ok end end Livebook.EvaluatorTest.Stacktrace.Cat.meow() """ ignore_warnings(fn -> Evaluator.evaluate_code(evaluator, self(), code, :code_1) expected_stacktrace = [ {Livebook.EvaluatorTest.Stacktrace.Math, :bad_math, 0, [file: 'nofile', line: 3]}, {Livebook.EvaluatorTest.Stacktrace.Cat, :meow, 0, [file: 'nofile', line: 10]} ] # Note: evaluating module definitions is relatively slow, so we use a higher wait timeout. assert_receive {:evaluation_response, :code_1, {:error, _kind, _error, ^expected_stacktrace}, %{evaluation_time_ms: _time_ms}}, 2_000 end) end test "in case of an error uses own evaluation context as the resulting context", %{evaluator: evaluator} do code1 = """ x = 2 """ code2 = """ raise ":<" """ code3 = """ x * x """ Evaluator.evaluate_code(evaluator, self(), code1, :code_1) assert_receive {:evaluation_response, :code_1, {:ok, _}, %{evaluation_time_ms: _time_ms}} Evaluator.evaluate_code(evaluator, self(), code2, :code_2, :code_1) assert_receive {:evaluation_response, :code_2, {:error, _, _, _}, %{evaluation_time_ms: _time_ms}} Evaluator.evaluate_code(evaluator, self(), code3, :code_3, :code_2) assert_receive {:evaluation_response, :code_3, {:ok, 4}, %{evaluation_time_ms: _time_ms}} end test "given file option sets it in evaluation environment", %{evaluator: evaluator} do code = """ __DIR__ """ opts = [file: "/path/dir/file"] Evaluator.evaluate_code(evaluator, self(), code, :code_1, nil, opts) assert_receive {:evaluation_response, :code_1, {:ok, "/path/dir"}, %{evaluation_time_ms: _time_ms}} end test "kills widgets that that no evaluation points to", %{evaluator: evaluator} do # Evaluate the code twice, which spawns two widget processes # First of them should be eventually killed Evaluator.evaluate_code(evaluator, self(), spawn_widget_code(), :code_1) assert_receive {:evaluation_response, :code_1, {:ok, widget_pid1}, %{evaluation_time_ms: _time_ms}} ref = Process.monitor(widget_pid1) Evaluator.evaluate_code(evaluator, self(), spawn_widget_code(), :code_1) assert_receive {:evaluation_response, :code_1, {:ok, widget_pid2}, %{evaluation_time_ms: _time_ms}} assert_receive {:DOWN, ^ref, :process, ^widget_pid1, :shutdown} assert Process.alive?(widget_pid2) end test "does not kill a widget if another evaluation points to it", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), spawn_widget_code(), :code_1) assert_receive {:evaluation_response, :code_1, {:ok, widget_pid1}, %{evaluation_time_ms: _time_ms}} Evaluator.evaluate_code(evaluator, self(), spawn_widget_code(), :code_2) assert_receive {:evaluation_response, :code_2, {:ok, widget_pid2}, %{evaluation_time_ms: _time_ms}} ref = Process.monitor(widget_pid1) refute_receive {:DOWN, ^ref, :process, ^widget_pid1, :shutdown} assert Process.alive?(widget_pid1) assert Process.alive?(widget_pid2) end end describe "forget_evaluation/2" do test "invalidates the given reference", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), "x = 1", :code_1) assert_receive {:evaluation_response, :code_1, _, %{evaluation_time_ms: _time_ms}} Evaluator.forget_evaluation(evaluator, :code_1) ignore_warnings(fn -> Evaluator.evaluate_code(evaluator, self(), "x", :code_2, :code_1) assert_receive {:evaluation_response, :code_2, {:error, _kind, %CompileError{description: "undefined function x/0"}, _stacktrace}, %{evaluation_time_ms: _time_ms}} end) end test "kills widgets that no evaluation points to", %{evaluator: evaluator} do Evaluator.evaluate_code(evaluator, self(), spawn_widget_code(), :code_1) assert_receive {:evaluation_response, :code_1, {:ok, widget_pid1}, %{evaluation_time_ms: _time_ms}} ref = Process.monitor(widget_pid1) Evaluator.forget_evaluation(evaluator, :code_1) assert_receive {:DOWN, ^ref, :process, ^widget_pid1, :shutdown} end end describe "handle_intellisense/5 given completion request" do test "sends completion response to the given process", %{evaluator: evaluator} do request = {:completion, "System.ver"} Evaluator.handle_intellisense(evaluator, self(), :ref, request) assert_receive {:intellisense_response, :ref, ^request, %{items: [%{label: "version/0"}]}}, 2_000 end test "given evaluation reference uses its bindings and env", %{evaluator: evaluator} do code = """ alias IO.ANSI number = 10 """ Evaluator.evaluate_code(evaluator, self(), code, :code_1) assert_receive {:evaluation_response, :code_1, _, %{evaluation_time_ms: _time_ms}} request = {:completion, "num"} Evaluator.handle_intellisense(evaluator, self(), :ref, request, :code_1) assert_receive {:intellisense_response, :ref, ^request, %{items: [%{label: "number"}]}}, 2_000 request = {:completion, "ANSI.brigh"} Evaluator.handle_intellisense(evaluator, self(), :ref, request, :code_1) assert_receive {:intellisense_response, :ref, ^request, %{items: [%{label: "bright/0"}]}}, 2_000 end end describe "initialize_from/3" do setup do {:ok, _pid, parent_evaluator} = start_supervised(Evaluator, id: :parent_evaluator) %{parent_evaluator: parent_evaluator} end test "copies the given context and sets as the initial one", %{evaluator: evaluator, parent_evaluator: parent_evaluator} do Evaluator.evaluate_code(parent_evaluator, self(), "x = 1", :code_1) assert_receive {:evaluation_response, :code_1, _, %{evaluation_time_ms: _time_ms}} Evaluator.initialize_from(evaluator, parent_evaluator, :code_1) Evaluator.evaluate_code(evaluator, self(), "x", :code_2) assert_receive {:evaluation_response, :code_2, {:ok, 1}, %{evaluation_time_ms: _time_ms}} end test "mirrors process dictionary of the given evaluator", %{evaluator: evaluator, parent_evaluator: parent_evaluator} do Evaluator.evaluate_code(parent_evaluator, self(), "Process.put(:data, 1)", :code_1) assert_receive {:evaluation_response, :code_1, _, %{evaluation_time_ms: _time_ms}} Evaluator.initialize_from(evaluator, parent_evaluator, :code_1) Evaluator.evaluate_code(evaluator, self(), "Process.get(:data)", :code_2) assert_receive {:evaluation_response, :code_2, {:ok, 1}, %{evaluation_time_ms: _time_ms}} end end # Helpers # Some of the code passed to Evaluator above is expected # to produce compilation warnings, so we ignore them. defp ignore_warnings(fun) do ExUnit.CaptureIO.capture_io(:stderr, fun) :ok end # Returns a code that spawns and renders a widget process # and returns its pid from the evaluation defp spawn_widget_code() do """ widget_pid = spawn(fn -> Process.sleep(:infinity) end) ref = make_ref() send(Process.group_leader(), {:io_request, self(), ref, {:livebook_put_output, {:vega_lite_dynamic, widget_pid}}}) receive do {:io_reply, ^ref, :ok} -> :ok end widget_pid """ end end
35.714744
118
0.646146
039bfdcf71bd592c837e42d10a26db6177ef0b9d
1,588
exs
Elixir
test/ex_pesa/Mpesa/b2b_test.exs
MidigoF/ex_pesa
d2a62e72c67084385609c895e52a6ac52e8a9a8a
[ "AML", "MIT" ]
20
2020-08-07T18:45:03.000Z
2021-12-02T12:47:07.000Z
test/ex_pesa/Mpesa/b2b_test.exs
MidigoF/ex_pesa
d2a62e72c67084385609c895e52a6ac52e8a9a8a
[ "AML", "MIT" ]
65
2020-08-17T05:52:33.000Z
2021-05-20T16:06:34.000Z
test/ex_pesa/Mpesa/b2b_test.exs
MidigoF/ex_pesa
d2a62e72c67084385609c895e52a6ac52e8a9a8a
[ "AML", "MIT" ]
11
2020-08-17T07:53:02.000Z
2021-04-02T20:57:16.000Z
defmodule ExPesa.Mpesa.B2BTest do @moduledoc false use ExUnit.Case, async: true import Tesla.Mock doctest ExPesa.Mpesa.B2B alias ExPesa.Mpesa.B2B setup do mock(fn %{ url: "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials", method: :get } -> %Tesla.Env{ status: 200, body: %{ "access_token" => "SGWcJPtNtYNPGm6uSYR9yPYrAI3Bm", "expires_in" => "3599" } } %{ url: "https://sandbox.safaricom.co.ke/mpesa/b2b/v1/paymentrequest", method: :post } -> %Tesla.Env{ status: 200, body: %{ "ConversationID" => "AG_20200927_00007d4c98884c889b25", "OriginatorConversationID" => "27274-37744848-4", "ResponseCode" => "0", "ResponseDescription" => "Accept the service request successfully." } } end) :ok end describe "Mpesa B2B" do test "request/1 should Initiate a B2B request" do payment_details = %{ command_id: "BusinessPayBill", amount: 10500, receiver_party: 600_000, remarks: "B2B Request", account_reference: "BILL PAYMENT" } {:ok, result} = B2B.request(payment_details) assert result["ResponseCode"] == "0" end test "request/1 should error out without required parameter" do {:error, result} = B2B.request(%{}) "Required Parameter missing, 'command_id','amount','receiver_party', 'remarks'" = result end end end
24.430769
95
0.576196
039c2afa8d0e5a4ed16c1a914394a90214be5ce1
106
ex
Elixir
lib/argo/repo.ex
ne1ro/argo
87f6c0de8311cb3e1e4eb05fa63bb0b71068a743
[ "MIT" ]
null
null
null
lib/argo/repo.ex
ne1ro/argo
87f6c0de8311cb3e1e4eb05fa63bb0b71068a743
[ "MIT" ]
null
null
null
lib/argo/repo.ex
ne1ro/argo
87f6c0de8311cb3e1e4eb05fa63bb0b71068a743
[ "MIT" ]
null
null
null
defmodule Argo.Repo do @moduledoc """ OTP app repository """ use Ecto.Repo, otp_app: :argo end
13.25
31
0.650943
039c32810788ba37b27452271b4be3a47e9292a9
22
ex
Elixir
day5/lib/day5.ex
ryanbillingsley/advent_of_code
9219a4b763966b70caed85865bb073a26bb3a705
[ "MIT" ]
null
null
null
day5/lib/day5.ex
ryanbillingsley/advent_of_code
9219a4b763966b70caed85865bb073a26bb3a705
[ "MIT" ]
null
null
null
day5/lib/day5.ex
ryanbillingsley/advent_of_code
9219a4b763966b70caed85865bb073a26bb3a705
[ "MIT" ]
null
null
null
defmodule Day5 do end
7.333333
17
0.818182
039c467e188093b5de6ff51bb3dc9216ae0595cc
648
ex
Elixir
lib/arc/processor.ex
PharosProduction/arc
e799fb9e2abdff7fec5dd3f0c5926c501a3576d4
[ "Apache-2.0" ]
1,213
2015-06-18T04:01:20.000Z
2022-01-19T18:47:23.000Z
lib/arc/processor.ex
PharosProduction/arc
e799fb9e2abdff7fec5dd3f0c5926c501a3576d4
[ "Apache-2.0" ]
260
2015-06-18T22:34:58.000Z
2022-01-06T17:43:29.000Z
lib/arc/processor.ex
PharosProduction/arc
e799fb9e2abdff7fec5dd3f0c5926c501a3576d4
[ "Apache-2.0" ]
270
2015-07-07T17:10:31.000Z
2021-11-13T09:16:03.000Z
defmodule Arc.Processor do def process(definition, version, {file, scope}) do transform = definition.transform(version, {file, scope}) apply_transformation(file, transform) end defp apply_transformation(_, :skip), do: {:ok, nil} defp apply_transformation(file, :noaction), do: {:ok, file} defp apply_transformation(file, {:noaction}), do: {:ok, file} # Deprecated defp apply_transformation(file, {cmd, conversion, _}) do apply_transformation(file, {cmd, conversion}) end defp apply_transformation(file, {cmd, conversion}) do Arc.Transformations.Convert.apply(cmd, Arc.File.ensure_path(file), conversion) end end
36
82
0.729938
039c6f5d23a198020fa171aedbdb8318a025130d
495
ex
Elixir
lib/web/controllers/api/agency_controller.ex
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
9
2020-02-26T20:24:38.000Z
2022-03-22T21:14:52.000Z
lib/web/controllers/api/agency_controller.ex
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
15
2020-04-22T19:33:24.000Z
2022-03-26T15:11:17.000Z
lib/web/controllers/api/agency_controller.ex
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
4
2020-04-27T22:58:57.000Z
2022-01-14T13:42:09.000Z
defmodule Web.Api.AgencyController do use Web, :controller alias ChallengeGov.Agencies alias Web.Api.ErrorView def sub_agencies(conn, %{"agency_id" => id}) do with {id, _} <- Integer.parse(id), {:ok, agency} <- Agencies.get(id) do conn |> assign(:agencies, agency.sub_agencies) |> render("index.json") else _ -> conn |> put_status(:not_found) |> put_view(ErrorView) |> render("not_found.json") end end end
22.5
49
0.593939
039c779ef516e04aec07d834e7e75f69b406a9c7
1,598
ex
Elixir
clients/text_to_speech/lib/google_api/text_to_speech/v1beta1/model/list_voices_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/text_to_speech/lib/google_api/text_to_speech/v1beta1/model/list_voices_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/text_to_speech/lib/google_api/text_to_speech/v1beta1/model/list_voices_response.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.TextToSpeech.V1beta1.Model.ListVoicesResponse do @moduledoc """ The message returned to the client by the `ListVoices` method. ## Attributes * `voices` (*type:* `list(GoogleApi.TextToSpeech.V1beta1.Model.Voice.t)`, *default:* `nil`) - The list of voices. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :voices => list(GoogleApi.TextToSpeech.V1beta1.Model.Voice.t()) } field(:voices, as: GoogleApi.TextToSpeech.V1beta1.Model.Voice, type: :list) end defimpl Poison.Decoder, for: GoogleApi.TextToSpeech.V1beta1.Model.ListVoicesResponse do def decode(value, options) do GoogleApi.TextToSpeech.V1beta1.Model.ListVoicesResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.TextToSpeech.V1beta1.Model.ListVoicesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34
117
0.749687
039c9cd43bae53f3bdec119f5cffd7928cdbb75c
2,019
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/i18n_region_list_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/i18n_region_list_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/i18n_region_list_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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.YouTube.V3.Model.I18nRegionListResponse do @moduledoc """ ## Attributes - etag (String.t): Etag of this resource. Defaults to: `null`. - eventId (String.t): Serialized EventId of the request which produced this response. Defaults to: `null`. - items ([I18nRegion]): A list of regions where YouTube is available. In this map, the i18n region ID is the map key, and its value is the corresponding i18nRegion resource. Defaults to: `null`. - kind (String.t): Identifies what kind of resource this is. Value: the fixed string \&quot;youtube#i18nRegionListResponse\&quot;. Defaults to: `null`. - visitorId (String.t): The visitorId identifies the visitor. Defaults to: `null`. """ defstruct [ :etag, :eventId, :items, :kind, :visitorId ] end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.I18nRegionListResponse do import GoogleApi.YouTube.V3.Deserializer def decode(value, options) do value |> deserialize(:items, :list, GoogleApi.YouTube.V3.Model.I18nRegion, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.I18nRegionListResponse do def encode(value, options) do GoogleApi.YouTube.V3.Deserializer.serialize_non_nil(value, options) end end
36.709091
196
0.744923
039cd74daf7dfee1c10076398a8fe7cfebf0984d
1,359
ex
Elixir
example/lib/example.ex
arjan/sworm
a76a5fed2108db2a58615cd2d1721139d608ef23
[ "MIT" ]
21
2019-05-15T09:43:20.000Z
2021-01-12T10:04:47.000Z
example/lib/example.ex
arjan/sworm
a76a5fed2108db2a58615cd2d1721139d608ef23
[ "MIT" ]
1
2019-05-30T09:18:28.000Z
2019-08-16T13:41:38.000Z
example/lib/example.ex
arjan/sworm
a76a5fed2108db2a58615cd2d1721139d608ef23
[ "MIT" ]
null
null
null
defmodule Example do defmodule TestServer do require Logger use GenServer def start_link() do GenServer.start_link(__MODULE__, []) end def init(a) do {:ok, a} end def handle_info({:begin_handoff, delegate, ref}, state) do Logger.info("begin handoff") send(delegate, {ref, :handoff_state, "asdf"}) {:noreply, state} end end def process(name) do Example.Swarm.register_name(name, TestServer, :start_link, []) end defmodule Counter do require Logger use GenServer def start_link() do GenServer.start_link(__MODULE__, []) end def init(a) do :timer.send_interval(1000, :count) {:ok, 0} end def handle_info({Example.Swarm, :begin_handoff, delegate, ref}, state) do IO.puts("Begin handoff: #{state}") send(delegate, {ref, :handoff_state, state}) {:noreply, state} end def handle_info({Example.Swarm, :end_handoff, state}, _state) do IO.puts("End handoff: #{state}") {:noreply, state} end def handle_info(:count, state) do IO.puts("Count: #{state}") {:noreply, state + 1} end end def counter(name) do Example.Swarm.register_name(name, Counter, :start_link, []) end def c do counter(:a) end def many do for n <- 1..10, do: counter(n) end end
19.414286
77
0.613687
039d094920d03c994351c00afdd0269ffd9e7d7d
1,088
ex
Elixir
lib/ketbin_web/channels/user_socket.ex
ATechnoHazard/katbin
20a0b45954cf7819cd9d51c401db06be0f47666b
[ "MIT" ]
4
2020-08-05T20:05:34.000Z
2020-10-01T10:01:56.000Z
lib/ketbin_web/channels/user_socket.ex
ATechnoHazard/katbin
20a0b45954cf7819cd9d51c401db06be0f47666b
[ "MIT" ]
1
2020-07-08T05:02:12.000Z
2020-09-25T10:05:11.000Z
lib/ketbin_web/channels/user_socket.ex
ATechnoHazard/katbin
20a0b45954cf7819cd9d51c401db06be0f47666b
[ "MIT" ]
1
2020-08-30T12:59:49.000Z
2020-08-30T12:59:49.000Z
defmodule KetbinWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", KetbinWeb.RoomChannel # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. @impl true def connect(_params, socket, _connect_info) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # KetbinWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.222222
83
0.693934
039dd7a153787e3d0d9eb63b86dc51935b32a3f4
1,514
ex
Elixir
api/web/web.ex
manna422/loose
1d2dc1d1a88976fa3f883917f47023eae3167c37
[ "MIT" ]
null
null
null
api/web/web.ex
manna422/loose
1d2dc1d1a88976fa3f883917f47023eae3167c37
[ "MIT" ]
null
null
null
api/web/web.ex
manna422/loose
1d2dc1d1a88976fa3f883917f47023eae3167c37
[ "MIT" ]
null
null
null
defmodule Loose.Web do @moduledoc """ A module that keeps using definitions for controllers, views and so on. This can be used in your application as: use Loose.Web, :controller use Loose.Web, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. """ def model do quote do use Ecto.Schema import Ecto import Ecto.Changeset import Ecto.Query end end def controller do quote do use Phoenix.Controller alias Loose.Repo import Ecto import Ecto.Query import Loose.Router.Helpers import Loose.Gettext end end def view do quote do use Phoenix.View, root: "web/templates" # Import convenience functions from controllers import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1] import Loose.Router.Helpers import Loose.ErrorHelpers import Loose.Gettext end end def router do quote do use Phoenix.Router end end def channel do quote do use Phoenix.Channel alias Loose.Repo import Ecto import Ecto.Query import Loose.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
19.164557
88
0.663144
039de490fb2c53090a50416cf0af4042f95d7507
6,489
exs
Elixir
lib/elixir/test/elixir/module_test.exs
gabrielelana/elixir
7e78113f925d438568b7efa8eaded5ae43dce4b1
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/module_test.exs
gabrielelana/elixir
7e78113f925d438568b7efa8eaded5ae43dce4b1
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/module_test.exs
gabrielelana/elixir
7e78113f925d438568b7efa8eaded5ae43dce4b1
[ "Apache-2.0" ]
null
null
null
Code.require_file "test_helper.exs", __DIR__ defmodule ModuleTest.ToBeUsed do def value, do: 1 defmacro __using__(_) do target = __CALLER__.module Module.put_attribute(target, :has_callback, true) Module.put_attribute(target, :before_compile, __MODULE__) Module.put_attribute(target, :after_compile, __MODULE__) Module.put_attribute(target, :before_compile, {__MODULE__, :callback}) quote do: (def line, do: __ENV__.line) end defmacro __before_compile__(env) do quote do: (def before_compile, do: unquote(env.vars)) end defmacro __after_compile__(%Macro.Env{module: ModuleTest.ToUse, vars: []}, bin) when is_binary(bin) do # IO.puts "HELLO" end defmacro callback(env) do value = Module.get_attribute(env.module, :has_callback) quote do def callback_value(true), do: unquote(value) end end end defmodule ModuleTest.ToUse do 32 = __ENV__.line # Moving the next line around can make tests fail var = 1 var # Not available in callbacks def callback_value(false), do: false use ModuleTest.ToBeUsed end defmodule ModuleTest do use ExUnit.Case, async: true Module.register_attribute __MODULE__, :register_example, accumulate: true, persist: true @register_example :it_works @register_example :still_works contents = quote do: (def eval_quoted_info, do: {__MODULE__, __ENV__.file, __ENV__.line}) Module.eval_quoted __MODULE__, contents, [], file: "sample.ex", line: 13 defmacrop in_module(block) do quote do defmodule Temp, unquote(block) :code.purge(Temp) :code.delete(Temp) end end test :in_memory do assert :code.which(__MODULE__) == :in_memory end ## Eval test :eval_quoted do assert eval_quoted_info() == {ModuleTest, "sample.ex", 13} end test :line_from_macro do assert ModuleTest.ToUse.line == 36 end ## Callbacks test :compile_callback_hook do assert ModuleTest.ToUse.callback_value(true) == true assert ModuleTest.ToUse.callback_value(false) == false end test :before_compile_callback_hook do assert ModuleTest.ToUse.before_compile == [] end test :on_definition do defmodule OnDefinition do @on_definition ModuleTest def hello(foo, bar) do foo + bar end end assert Process.get(ModuleTest.OnDefinition) == :called end def __on_definition__(env, kind, name, args, guards, expr) do Process.put(env.module, :called) assert env.module == ModuleTest.OnDefinition assert kind == :def assert name == :hello assert [{:foo, _, _}, {:bar, _, _}] = args assert [] = guards assert {:+, _, [{:foo, _, nil}, {:bar, _, nil}]} = expr end test :overridable_inside_before_compile do defmodule OverridableWithBeforeCompile do @before_compile ModuleTest end assert OverridableWithBeforeCompile.constant == 1 end test :alias_with_raw_atom do defmodule :"Elixir.ModuleTest.RawModule" do def hello, do: :world end assert RawModule.hello == :world end defmacro __before_compile__(_) do quote do def constant, do: 1 defoverridable constant: 0 end end ## Attributes test :reserved_attributes do assert List.keyfind(ExUnit.Server.__info__(:attributes), :behaviour, 0) == {:behaviour, [:gen_server]} end test :registered_attributes do assert [{:register_example, [:it_works]}, {:register_example, [:still_works]}] == Enum.filter __MODULE__.__info__(:attributes), &match?({:register_example, _}, &1) end @some_attribute [1] @other_attribute [3, 2, 1] test :inside_function_attributes do assert [1] = @some_attribute assert [3, 2, 1] = @other_attribute end ## Naming test :concat do assert Module.concat(Foo, Bar) == Foo.Bar assert Module.concat(Foo, :Bar) == Foo.Bar assert Module.concat(Foo, "Bar") == Foo.Bar assert Module.concat(Foo, Bar.Baz) == Foo.Bar.Baz assert Module.concat(Foo, "Bar.Baz") == Foo.Bar.Baz assert Module.concat(Bar, nil) == Elixir.Bar end test :safe_concat do assert Module.safe_concat(Foo, :Bar) == Foo.Bar assert_raise ArgumentError, fn -> Module.safe_concat SafeConcat, Doesnt.Exist end end test :split do module = Very.Long.Module.Name.And.Even.Longer assert Module.split(module) == ["Very", "Long", "Module", "Name", "And", "Even", "Longer"] assert Module.split("Elixir.Very.Long") == ["Very", "Long"] assert_raise FunctionClauseError, fn -> Module.split(:just_an_atom) end assert_raise FunctionClauseError, fn -> Module.split("Foo") end assert Module.concat(Module.split(module)) == module end test :__MODULE__ do assert Code.eval_string("__MODULE__.Foo") |> elem(0) == Foo end ## Creation test :defmodule do assert match?({:module, Defmodule, binary, 3} when is_binary(binary), defmodule Defmodule do 1 + 2 end) end test :defmodule_with_atom do assert match?({:module, :root_defmodule, _, _}, defmodule :root_defmodule do :ok end) end test :create do contents = quote do def world, do: true end {:module, ModuleCreateSample, _, _} = Module.create(ModuleCreateSample, contents, __ENV__) assert ModuleCreateSample.world end test :create_with_elixir_as_a_name do contents = quote do def world, do: true end assert_raise CompileError, fn -> {:module, Elixir, _, _} = Module.create(Elixir, contents, __ENV__) end end test :no_function_in_module_body do in_module do assert __ENV__.function == nil end end ## Definitions test :defines? do in_module do refute Module.defines? __MODULE__, {:foo, 0} def foo(), do: bar() assert Module.defines? __MODULE__, {:foo, 0} assert Module.defines? __MODULE__, {:foo, 0}, :def refute Module.defines? __MODULE__, {:bar, 0}, :defp defp bar(), do: :ok assert Module.defines? __MODULE__, {:bar, 0}, :defp refute Module.defines? __MODULE__, {:baz, 0}, :defmacro defmacro baz(), do: :ok assert Module.defines? __MODULE__, {:baz, 0}, :defmacro end end test :definitions_in do in_module do def foo(1, 2, 3), do: 4 assert Module.definitions_in(__MODULE__) == [foo: 3] assert Module.definitions_in(__MODULE__, :def) == [foo: 3] assert Module.definitions_in(__MODULE__, :defp) == [] end end end
25.956
106
0.670365
039dfbeecd6124f3a22cf5b5f06aeb3a571d1874
322
exs
Elixir
priv/repo/migrations/20180716130048_create_emails.exs
nunopolonia/psc-api
2e358503851cc04cdaa89201a3f56586f8746736
[ "MIT" ]
1
2017-09-10T23:51:40.000Z
2017-09-10T23:51:40.000Z
priv/repo/migrations/20180716130048_create_emails.exs
nunopolonia/psc-api
2e358503851cc04cdaa89201a3f56586f8746736
[ "MIT" ]
24
2018-03-14T18:17:00.000Z
2021-03-01T07:47:53.000Z
priv/repo/migrations/20180716130048_create_emails.exs
portosummerofcode/psc-api
2e358503851cc04cdaa89201a3f56586f8746736
[ "MIT" ]
null
null
null
defmodule Api.Repo.Migrations.CreateEmails do use Ecto.Migration def change do create table(:emails, primary_key: false) do add :id, :binary_id, primary_key: true add :name, :string add :title, :string add :subject, :string add :content, :text timestamps() end end end
18.941176
48
0.642857
039e15efba4b509b7672d689286743fe419d3764
205,711
ex
Elixir
clients/spanner/lib/google_api/spanner/v1/api/projects.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/spanner/lib/google_api/spanner/v1/api/projects.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/api/projects.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Spanner.V1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.Spanner.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets information about a particular instance configuration. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the requested instance configuration. Values are of the form `projects//instanceConfigs/`. * `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.Spanner.V1.Model.InstanceConfig{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instance_configs_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.InstanceConfig.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instance_configs_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.InstanceConfig{}]) end @doc """ Lists the supported instance configurations for a given project. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the project for which a list of supported instance configurations is requested. Values are of the form `projects/`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - Number of instance configurations to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListInstanceConfigsResponse. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListInstanceConfigsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instance_configs_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListInstanceConfigsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instance_configs_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/instanceConfigs", %{ "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.Spanner.V1.Model.ListInstanceConfigsResponse{}] ) end @doc """ Creates an instance and begins preparing it to begin serving. The returned long-running operation can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, `CreateInstance` returns `ALREADY_EXISTS`. Immediately upon completion of this request: * The instance is readable via the API, with all requested attributes but no allocated resources. Its state is `CREATING`. Until completion of the returned operation: * Cancelling the operation renders the instance immediately unreadable via the API. * The instance can be deleted. * All other attempts to modify the instance are rejected. Upon completion of the returned operation: * Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). * Databases can be created in the instance. * The instance's allocated resource levels are readable via the API. * The instance's state becomes `READY`. The returned long-running operation will have a name of the format `/operations/` and can be used to track creation of the instance. The metadata field type is CreateInstanceMetadata. The response field type is Instance, if successful. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the project in which to create the instance. Values are of the form `projects/`. * `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.Spanner.V1.Model.CreateInstanceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_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("/v1/{+parent}/instances", %{ "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.Spanner.V1.Model.Operation{}]) end @doc """ Deletes an instance. Immediately upon completion of the request: * Billing ceases for all of the instance's reserved resources. Soon afterward: * The instance and *all of its databases* immediately and irrevocably disappear from the API. All data in the databases is permanently deleted. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the instance to be deleted. Values are of the form `projects//instances/` * `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.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_delete(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Gets information about a particular instance. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the requested instance. Values are of the form `projects//instances/`. * `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"). * `:fieldMask` (*type:* `String.t`) - If field_mask is present, specifies the subset of Instance fields that should be returned. If absent, all Instance fields are returned. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Instance{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Spanner.V1.Model.Instance.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_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, :fieldMask => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Instance{}]) end @doc """ Gets the access control policy for an instance resource. Returns an empty policy if an instance exists but does not have a policy set. Authorization requires `spanner.instances.getIamPolicy` on resource. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which the policy is being retrieved. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for database resources. * `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.Spanner.V1.Model.GetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_get_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_get_iam_policy( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:getIamPolicy", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Policy{}]) end @doc """ Lists all instances in the given project. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the project for which a list of instances is requested. Values are of the form `projects/`. * `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`) - An expression for filtering the results of the request. Filter rules are case insensitive. The fields eligible for filtering are: * `name` * `display_name` * `labels.key` where key is the name of a label Some examples of using filters are: * `name:*` --> The instance has a name. * `name:Howl` --> The instance's name contains the string "howl". * `name:HOWL` --> Equivalent to above. * `NAME:howl` --> Equivalent to above. * `labels.env:*` --> The instance has the label "env". * `labels.env:dev` --> The instance has the label "env" and the value of the label contains the string "dev". * `name:howl labels.env:dev` --> The instance's name contains "howl" and it has the label "env" with its value containing "dev". * `:instanceDeadline` (*type:* `DateTime.t`) - Deadline used while retrieving metadata for instances. Instances whose metadata cannot be retrieved within this deadline will be added to unreachable in ListInstancesResponse. * `:pageSize` (*type:* `integer()`) - Number of instances to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListInstancesResponse. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListInstancesResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Spanner.V1.Model.ListInstancesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_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, :instanceDeadline => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/instances", %{ "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.Spanner.V1.Model.ListInstancesResponse{}]) end @doc """ Updates an instance, and begins allocating or releasing resources as requested. The returned long-running operation can be used to track the progress of updating the instance. If the named instance does not exist, returns `NOT_FOUND`. Immediately upon completion of this request: * For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: * Cancelling the operation sets its metadata's cancel_time, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a `CANCELLED` status. * All other attempts to modify the instance are rejected. * Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: * Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). * All newly-reserved resources are available for serving the instance's tables. * The instance's new resource levels are readable via the API. The returned long-running operation will have a name of the format `/operations/` and can be used to track the instance modification. The metadata field type is UpdateInstanceMetadata. The response field type is Instance, if successful. Authorization requires `spanner.instances.update` permission on resource name. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. A unique identifier for the instance, which cannot be changed after the instance is created. Values are of the form `projects//instances/a-z*[a-z0-9]`. The final segment of the name must be between 2 and 64 characters in length. * `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.Spanner.V1.Model.UpdateInstanceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_patch(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Operation{}]) end @doc """ Sets the access control policy on an instance resource. Replaces any existing policy. Authorization requires `spanner.instances.setIamPolicy` on resource. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which the policy is being set. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for databases resources. * `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.Spanner.V1.Model.SetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_set_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_set_iam_policy( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:setIamPolicy", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Policy{}]) end @doc """ Returns permissions that the caller has on the specified instance resource. Attempting this RPC on a non-existent Cloud Spanner instance resource will result in a NOT_FOUND error if the user has `spanner.instances.list` permission on the containing Google Cloud Project. Otherwise returns an empty set of permissions. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which permissions are being tested. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for database resources. * `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.Spanner.V1.Model.TestIamPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_test_iam_permissions( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_test_iam_permissions( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:testIamPermissions", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse{}]) end @doc """ Lists the backup long-running operations in the given instance. A backup operation has a name of the form `projects//instances//backups//operations/`. The long-running operation metadata field type `metadata.type_url` describes the type of the metadata. Operations returned include those that have completed/failed/canceled within the last 7 days, and pending operations. Operations returned are ordered by `operation.metadata.value.progress.start_time` in descending order starting from the most recently started operation. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The instance of the backup operations. Values are of the form `projects//instances/`. * `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`) - An expression that filters the list of returned backup operations. A filter expression consists of a field name, a comparison operator, and a value for filtering. The value must be a string, a number, or a boolean. The comparison operator must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. Colon `:` is the contains operator. Filter rules are not case sensitive. The following fields in the operation are eligible for filtering: * `name` - The name of the long-running operation * `done` - False if the operation is in progress, else true. * `metadata.@type` - the type of metadata. For example, the type string for CreateBackupMetadata is `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. * `metadata.` - any field in metadata.value. * `error` - Error associated with the long-running operation. * `response.@type` - the type of response. * `response.` - any field in response.value. You can combine multiple expressions by enclosing each expression in parentheses. By default, expressions are combined with AND logic, but you can specify AND, OR, and NOT logic explicitly. Here are a few examples: * `done:true` - The operation is complete. * `metadata.database:prod` - The database the backup was taken from has a name containing the string "prod". * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \\ `(metadata.name:howl) AND` \\ `(metadata.progress.start_time < \\"2018-03-28T14:50:00Z\\") AND` \\ `(error:*)` - Returns operations where: * The operation's metadata type is CreateBackupMetadata. * The backup name contains the string "howl". * The operation started before 2018-03-28T14:50:00Z. * The operation resulted in an error. * `:pageSize` (*type:* `integer()`) - Number of operations to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListBackupOperationsResponse to the same `parent` and with the same `filter`. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListBackupOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backup_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListBackupOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backup_operations_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("/v1/{+parent}/backupOperations", %{ "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.Spanner.V1.Model.ListBackupOperationsResponse{}] ) end @doc """ Starts creating a new Cloud Spanner Backup. The returned backup long-running operation will have a name of the format `projects//instances//backups//operations/` and can be used to track creation of the backup. The metadata field type is CreateBackupMetadata. The response field type is Backup, if successful. Cancelling the returned operation will stop the creation and delete the backup. There can be only one pending backup creation per database. Backup creation of different databases can run concurrently. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the instance in which the backup will be created. This must be the same instance that contains the database the backup will be created from. The backup will be stored in the location(s) specified in the instance configuration of this instance. Values are of the form `projects//instances/`. * `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"). * `:backupId` (*type:* `String.t`) - Required. The id of the backup to be created. The `backup_id` appended to `parent` forms the full backup name of the form `projects//instances//backups/`. * `:"encryptionConfig.encryptionType"` (*type:* `String.t`) - Required. The encryption type of the backup. * `:"encryptionConfig.kmsKeyName"` (*type:* `String.t`) - Optional. The Cloud KMS key that will be used to protect the backup. This field should be set only when encryption_type is `CUSTOMER_MANAGED_ENCRYPTION`. Values are of the form `projects//locations//keyRings//cryptoKeys/`. * `:body` (*type:* `GoogleApi.Spanner.V1.Model.Backup.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_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, :backupId => :query, :"encryptionConfig.encryptionType" => :query, :"encryptionConfig.kmsKeyName" => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/backups", %{ "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.Spanner.V1.Model.Operation{}]) end @doc """ Deletes a pending or completed Backup. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. Name of the backup to delete. Values are of the form `projects//instances//backups/`. * `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.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Gets metadata on a pending or completed Backup. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. Name of the backup. Values are of the form `projects//instances//backups/`. * `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.Spanner.V1.Model.Backup{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Backup.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Backup{}]) end @doc """ Gets the access control policy for a database or backup resource. Returns an empty policy if a database or backup exists but does not have a policy set. Authorization requires `spanner.databases.getIamPolicy` permission on resource. For backups, authorization requires `spanner.backups.getIamPolicy` permission on resource. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which the policy is being retrieved. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for database resources. * `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.Spanner.V1.Model.GetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_get_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_get_iam_policy( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:getIamPolicy", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Policy{}]) end @doc """ Lists completed and pending backups. Backups returned are ordered by `create_time` in descending order, starting from the most recent `create_time`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The instance to list backups from. Values are of the form `projects//instances/`. * `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`) - An expression that filters the list of returned backups. A filter expression consists of a field name, a comparison operator, and a value for filtering. The value must be a string, a number, or a boolean. The comparison operator must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. Colon `:` is the contains operator. Filter rules are not case sensitive. The following fields in the Backup are eligible for filtering: * `name` * `database` * `state` * `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) * `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) * `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) * `size_bytes` You can combine multiple expressions by enclosing each expression in parentheses. By default, expressions are combined with AND logic, but you can specify AND, OR, and NOT logic explicitly. Here are a few examples: * `name:Howl` - The backup's name contains the string "howl". * `database:prod` - The database's name contains the string "prod". * `state:CREATING` - The backup is pending creation. * `state:READY` - The backup is fully created and ready for use. * `(name:howl) AND (create_time < \\"2018-03-28T14:50:00Z\\")` - The backup name contains the string "howl" and `create_time` of the backup is before 2018-03-28T14:50:00Z. * `expire_time < \\"2018-03-28T14:50:00Z\\"` - The backup `expire_time` is before 2018-03-28T14:50:00Z. * `size_bytes > 10000000000` - The backup's size is greater than 10GB * `:pageSize` (*type:* `integer()`) - Number of backups to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListBackupsResponse to the same `parent` and with the same `filter`. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListBackupsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListBackupsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_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("/v1/{+parent}/backups", %{ "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.Spanner.V1.Model.ListBackupsResponse{}]) end @doc """ Updates a pending or completed Backup. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only for the CreateBackup operation. Required for the UpdateBackup operation. A globally unique identifier for the backup which cannot be changed. Values are of the form `projects//instances//backups/a-z*[a-z0-9]` The final segment of the name must be between 2 and 60 characters in length. The backup is stored in the location(s) specified in the instance configuration of the instance containing the backup, identified by the prefix of the backup name of the form `projects//instances/`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:updateMask` (*type:* `String.t`) - Required. A mask specifying which fields (e.g. `expire_time`) in the Backup resource should be updated. This mask is relative to the Backup resource, not to the request message. The field mask must always be specified; this prevents any future fields from being erased accidentally by clients that do not know about them. * `:body` (*type:* `GoogleApi.Spanner.V1.Model.Backup.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Backup{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Backup.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_patch( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Backup{}]) end @doc """ Sets the access control policy on a database or backup resource. Replaces any existing policy. Authorization requires `spanner.databases.setIamPolicy` permission on resource. For backups, authorization requires `spanner.backups.setIamPolicy` permission on resource. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which the policy is being set. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for databases resources. * `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.Spanner.V1.Model.SetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_set_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_set_iam_policy( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:setIamPolicy", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Policy{}]) end @doc """ Returns permissions that the caller has on the specified database or backup resource. Attempting this RPC on a non-existent Cloud Spanner database will result in a NOT_FOUND error if the user has `spanner.databases.list` permission on the containing Cloud Spanner instance. Otherwise returns an empty set of permissions. Calling this method on a backup that does not exist will result in a NOT_FOUND error if the user has `spanner.backups.list` permission on the containing instance. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which permissions are being tested. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for database resources. * `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.Spanner.V1.Model.TestIamPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_test_iam_permissions( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_test_iam_permissions( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:testIamPermissions", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse{}]) 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.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be cancelled. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_operations_cancel( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_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 } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:cancel", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_operations_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_operations_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_operations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_operations_get( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Operation{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_backups_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_backups_operations_list( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.ListOperationsResponse{}]) end @doc """ Lists database longrunning-operations. A database operation has a name of the form `projects//instances//databases//operations/`. The long-running operation metadata field type `metadata.type_url` describes the type of the metadata. Operations returned include those that have completed/failed/canceled within the last 7 days, and pending operations. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The instance of the database operations. Values are of the form `projects//instances/`. * `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`) - An expression that filters the list of returned operations. A filter expression consists of a field name, a comparison operator, and a value for filtering. The value must be a string, a number, or a boolean. The comparison operator must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. Colon `:` is the contains operator. Filter rules are not case sensitive. The following fields in the Operation are eligible for filtering: * `name` - The name of the long-running operation * `done` - False if the operation is in progress, else true. * `metadata.@type` - the type of metadata. For example, the type string for RestoreDatabaseMetadata is `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. * `metadata.` - any field in metadata.value. * `error` - Error associated with the long-running operation. * `response.@type` - the type of response. * `response.` - any field in response.value. You can combine multiple expressions by enclosing each expression in parentheses. By default, expressions are combined with AND logic. However, you can specify AND, OR, and NOT logic explicitly. Here are a few examples: * `done:true` - The operation is complete. * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \\ `(metadata.source_type:BACKUP) AND` \\ `(metadata.backup_info.backup:backup_howl) AND` \\ `(metadata.name:restored_howl) AND` \\ `(metadata.progress.start_time < \\"2018-03-28T14:50:00Z\\") AND` \\ `(error:*)` - Return operations where: * The operation's metadata type is RestoreDatabaseMetadata. * The database is restored from a backup. * The backup name contains "backup_howl". * The restored database's name contains "restored_howl". * The operation started before 2018-03-28T14:50:00Z. * The operation resulted in an error. * `:pageSize` (*type:* `integer()`) - Number of operations to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListDatabaseOperationsResponse to the same `parent` and with the same `filter`. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListDatabaseOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_database_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListDatabaseOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_database_operations_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("/v1/{+parent}/databaseOperations", %{ "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.Spanner.V1.Model.ListDatabaseOperationsResponse{}] ) end @doc """ Creates a new Cloud Spanner database and starts to prepare it for serving. The returned long-running operation will have a name of the format `/operations/` and can be used to track preparation of the database. The metadata field type is CreateDatabaseMetadata. The response field type is Database, if successful. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the instance that will serve the new database. Values are of the form `projects//instances/`. * `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.Spanner.V1.Model.CreateDatabaseRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_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("/v1/{+parent}/databases", %{ "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.Spanner.V1.Model.Operation{}]) end @doc """ Drops (aka deletes) a Cloud Spanner database. Completed backups for the database will be retained according to their `expire_time`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `database` (*type:* `String.t`) - Required. The database to be dropped. * `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.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_drop_database( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_drop_database( connection, database, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+database}", %{ "database" => URI.encode(database, &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.Spanner.V1.Model.Empty{}]) end @doc """ Gets the state of a Cloud Spanner database. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the requested database. Values are of the form `projects//instances//databases/`. * `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.Spanner.V1.Model.Database{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Database.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_get( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Database{}]) end @doc """ Returns the schema of a Cloud Spanner database as a list of formatted DDL statements. This method does not show pending schema updates, those may be queried using the Operations API. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `database` (*type:* `String.t`) - Required. The database whose schema we wish to get. Values are of the form `projects//instances//databases/` * `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.Spanner.V1.Model.GetDatabaseDdlResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_get_ddl( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.GetDatabaseDdlResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_get_ddl( connection, database, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+database}/ddl", %{ "database" => URI.encode(database, &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.Spanner.V1.Model.GetDatabaseDdlResponse{}]) end @doc """ Gets the access control policy for a database or backup resource. Returns an empty policy if a database or backup exists but does not have a policy set. Authorization requires `spanner.databases.getIamPolicy` permission on resource. For backups, authorization requires `spanner.backups.getIamPolicy` permission on resource. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which the policy is being retrieved. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for database resources. * `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.Spanner.V1.Model.GetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_get_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_get_iam_policy( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:getIamPolicy", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Policy{}]) end @doc """ Request a specific scan with Database-specific data for Cloud Key Visualizer. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The unique name of the scan containing the requested information, specific to the Database service implementing this interface. * `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"). * `:endTime` (*type:* `DateTime.t`) - The upper bound for the time range to retrieve Scan data for. * `:startTime` (*type:* `DateTime.t`) - These fields restrict the Database-specific information returned in the `Scan.data` field. If a `View` is provided that does not include the `Scan.data` field, these are ignored. This range of time must be entirely contained within the defined time range of the targeted scan. The lower bound for the time range to retrieve Scan data for. * `:view` (*type:* `String.t`) - Specifies which parts of the Scan should be returned in the response. Note, if left unspecified, the FULL view is assumed. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Scan{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_get_scans( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Scan.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_get_scans( 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, :endTime => :query, :startTime => :query, :view => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}/scans", %{ "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.Spanner.V1.Model.Scan{}]) end @doc """ Lists Cloud Spanner databases. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The instance whose databases should be listed. Values are of the form `projects//instances/`. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - Number of databases to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListDatabasesResponse. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListDatabasesResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListDatabasesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/databases", %{ "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.Spanner.V1.Model.ListDatabasesResponse{}]) end @doc """ Create a new database by restoring from a completed backup. The new database must be in the same project and in an instance with the same instance configuration as the instance containing the backup. The returned database long-running operation has a name of the format `projects//instances//databases//operations/`, and can be used to track the progress of the operation, and to cancel it. The metadata field type is RestoreDatabaseMetadata. The response type is Database, if successful. Cancelling the returned operation will stop the restore and delete the database. There can be only one database being restored into an instance at a time. Once the restore operation completes, a new restore operation can be initiated, without waiting for the optimize operation associated with the first restore to complete. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the instance in which to create the restored database. This instance must be in the same project and have the same instance configuration as the instance containing the source backup. Values are of the form `projects//instances/`. * `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.Spanner.V1.Model.RestoreDatabaseRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_restore( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_restore( 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("/v1/{+parent}/databases:restore", %{ "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.Spanner.V1.Model.Operation{}]) end @doc """ Sets the access control policy on a database or backup resource. Replaces any existing policy. Authorization requires `spanner.databases.setIamPolicy` permission on resource. For backups, authorization requires `spanner.backups.setIamPolicy` permission on resource. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which the policy is being set. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for databases resources. * `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.Spanner.V1.Model.SetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_set_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_set_iam_policy( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:setIamPolicy", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Policy{}]) end @doc """ Returns permissions that the caller has on the specified database or backup resource. Attempting this RPC on a non-existent Cloud Spanner database will result in a NOT_FOUND error if the user has `spanner.databases.list` permission on the containing Cloud Spanner instance. Otherwise returns an empty set of permissions. Calling this method on a backup that does not exist will result in a NOT_FOUND error if the user has `spanner.backups.list` permission on the containing instance. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The Cloud Spanner resource for which permissions are being tested. The format is `projects//instances/` for instance resources and `projects//instances//databases/` for database resources. * `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.Spanner.V1.Model.TestIamPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_test_iam_permissions( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_test_iam_permissions( connection, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+resource}:testIamPermissions", %{ "resource" => URI.encode(resource, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.TestIamPermissionsResponse{}]) end @doc """ Updates the schema of a Cloud Spanner database by creating/altering/dropping tables, columns, indexes, etc. The returned long-running operation will have a name of the format `/operations/` and can be used to track execution of the schema change(s). The metadata field type is UpdateDatabaseDdlMetadata. The operation has no response. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `database` (*type:* `String.t`) - Required. The database to update. * `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.Spanner.V1.Model.UpdateDatabaseDdlRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_update_ddl( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_update_ddl( connection, database, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+database}/ddl", %{ "database" => URI.encode(database, &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.Spanner.V1.Model.Operation{}]) 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.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be cancelled. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_operations_cancel( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_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 } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:cancel", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_operations_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_operations_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_operations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_operations_get( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Operation{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_operations_list( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.ListOperationsResponse{}]) end @doc """ Creates multiple new sessions. This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `database` (*type:* `String.t`) - Required. The database in which the new sessions are created. * `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.Spanner.V1.Model.BatchCreateSessionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.BatchCreateSessionsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_batch_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.BatchCreateSessionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_batch_create( connection, database, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+database}/sessions:batchCreate", %{ "database" => URI.encode(database, &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.Spanner.V1.Model.BatchCreateSessionsResponse{}] ) end @doc """ Begins a new transaction. This step can often be skipped: Read, ExecuteSql and Commit can begin a new transaction as a side-effect. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the transaction runs. * `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.Spanner.V1.Model.BeginTransactionRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Transaction{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_begin_transaction( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Transaction.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_begin_transaction( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:beginTransaction", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.Transaction{}]) end @doc """ Commits a transaction. The request includes the mutations to be applied to rows in the database. `Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session. On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the transaction to be committed is running. * `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.Spanner.V1.Model.CommitRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.CommitResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_commit( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.CommitResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_commit( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:commit", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.CommitResponse{}]) end @doc """ Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit. Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner may delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`. Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `database` (*type:* `String.t`) - Required. The database in which the new session is created. * `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.Spanner.V1.Model.CreateSessionRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Session{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Session.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_create( connection, database, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+database}/sessions", %{ "database" => URI.encode(database, &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.Spanner.V1.Model.Session{}]) end @doc """ Ends a session, releasing server resources associated with it. This will asynchronously trigger cancellation of any operations that are running with this session. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the session 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.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ExecuteSql. Statements are executed in sequential order. A request can succeed even if a statement fails. The ExecuteBatchDmlResponse.status field in the response provides information about the statement that failed. Clients must inspect this field to determine whether an error occurred. Execution stops after the first failed statement; the remaining statements are not executed. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the DML statements should be performed. * `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.Spanner.V1.Model.ExecuteBatchDmlRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ExecuteBatchDmlResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_execute_batch_dml( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ExecuteBatchDmlResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_execute_batch_dml( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:executeBatchDml", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.ExecuteBatchDmlResponse{}]) end @doc """ Executes an SQL statement, returning all results in a single reply. This method cannot be used to return a result set larger than 10 MiB; if the query yields more data than that, the query fails with a `FAILED_PRECONDITION` error. Operations inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See Transaction for more details. Larger result sets can be fetched in streaming fashion by calling ExecuteStreamingSql instead. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the SQL query should be performed. * `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.Spanner.V1.Model.ExecuteSqlRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ResultSet{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_execute_sql( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ResultSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_execute_sql( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:executeSql", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.ResultSet{}]) end @doc """ Like ExecuteSql, except returns the result set as a stream. Unlike ExecuteSql, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the SQL query should be performed. * `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.Spanner.V1.Model.ExecuteSqlRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.PartialResultSet{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_execute_streaming_sql( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.PartialResultSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_execute_streaming_sql( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:executeStreamingSql", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.PartialResultSet{}]) end @doc """ Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the session 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.Spanner.V1.Model.Session{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Session.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_get( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Session{}]) end @doc """ Lists all sessions in a given database. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `database` (*type:* `String.t`) - Required. The database in which to list sessions. * `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`) - An expression for filtering the results of the request. Filter rules are case insensitive. The fields eligible for filtering are: * `labels.key` where key is the name of a label Some examples of using filters are: * `labels.env:*` --> The session has the label "env". * `labels.env:dev` --> The session has the label "env" and the value of the label contains the string "dev". * `:pageSize` (*type:* `integer()`) - Number of sessions to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size. * `:pageToken` (*type:* `String.t`) - If non-empty, `page_token` should contain a next_page_token from a previous ListSessionsResponse. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListSessionsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListSessionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_list( connection, database, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+database}/sessions", %{ "database" => URI.encode(database, &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.Spanner.V1.Model.ListSessionsResponse{}]) end @doc """ Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ExecuteStreamingSql to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session used to create the partitions. * `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.Spanner.V1.Model.PartitionQueryRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.PartitionResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_partition_query( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.PartitionResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_partition_query( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:partitionQuery", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.PartitionResponse{}]) end @doc """ Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by StreamingRead to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition_token. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session used to create the partitions. * `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.Spanner.V1.Model.PartitionReadRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.PartitionResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_partition_read( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.PartitionResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_partition_read( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:partitionRead", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.PartitionResponse{}]) end @doc """ Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteSql. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a `FAILED_PRECONDITION` error. Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See Transaction for more details. Larger result sets can be yielded in streaming fashion by calling StreamingRead instead. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the read should be performed. * `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.Spanner.V1.Model.ReadRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ResultSet{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_read( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ResultSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_read( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:read", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.ResultSet{}]) end @doc """ Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more Read or ExecuteSql requests and ultimately decides not to commit. `Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the transaction to roll back is running. * `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.Spanner.V1.Model.RollbackRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_rollback( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_rollback( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:rollback", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.Empty{}]) end @doc """ Like Read, except returns the result set as a stream. Unlike Read, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `session` (*type:* `String.t`) - Required. The session in which the read should be performed. * `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.Spanner.V1.Model.ReadRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.PartialResultSet{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_databases_sessions_streaming_read( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.PartialResultSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_databases_sessions_streaming_read( connection, session, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+session}:streamingRead", %{ "session" => URI.encode(session, &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.Spanner.V1.Model.PartialResultSet{}]) 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.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be cancelled. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_operations_cancel( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_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 } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:cancel", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_operations_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_operations_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Empty{}]) end @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_operations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_operations_get( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.Operation{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.Spanner.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Spanner.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec spanner_projects_instances_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Spanner.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def spanner_projects_instances_operations_list( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Spanner.V1.Model.ListOperationsResponse{}]) end end
49.378541
1,856
0.625353
039e3a6a4c3230041848d2ed17acc4b29b1e2dda
2,204
exs
Elixir
apps/lab3/test/log_test.exs
226wyj/Raft
b882839579bc70b5501e7f1d6fe41d3119162df4
[ "MIT" ]
null
null
null
apps/lab3/test/log_test.exs
226wyj/Raft
b882839579bc70b5501e7f1d6fe41d3119162df4
[ "MIT" ]
null
null
null
apps/lab3/test/log_test.exs
226wyj/Raft
b882839579bc70b5501e7f1d6fe41d3119162df4
[ "MIT" ]
null
null
null
defmodule LogTest do use ExUnit.Case doctest Raft defp create_empty_log() do Raft.new_configuration([:a, :b, :c], :a, 100, 1000, 20) end defp create_nop_log(last_index) do config = create_empty_log() log = for idx <- last_index..1, do: Raft.LogEntry.nop(idx, 1, :a) %{config | log: log} end test "Last index and term work" do assert Raft.get_last_log_index(create_empty_log()) == 0 assert Raft.get_last_log_index(create_nop_log(10)) == 10 assert Raft.get_last_log_term(create_empty_log()) == 0 assert Raft.get_last_log_term(create_nop_log(10)) == 1 end test "logged? works" do assert Raft.logged?(create_empty_log(), 1) == false assert Raft.logged?(create_nop_log(10), 1) == true end test "get_log_entry works" do assert Raft.get_log_entry(create_empty_log(), 2) == :noentry entry = Raft.get_log_entry(create_nop_log(10), 5) assert entry.index == 5 assert entry.term == 1 assert Raft.get_log_entry(create_nop_log(10), 0) == :noentry end test "truncate_log_at_index works" do config = create_nop_log(20) trunc_9 = Raft.truncate_log_at_index(config, 10) assert Raft.get_last_log_index(trunc_9) == 9 assert Raft.get_last_log_term(trunc_9) == 1 trunc_19 = Raft.truncate_log_at_index(config, 20) assert Raft.get_last_log_index(trunc_19) == 19 assert Raft.get_last_log_term(trunc_19) == 1 trunc_20 = Raft.truncate_log_at_index(config, 21) assert Raft.get_last_log_index(trunc_20) == 20 assert Raft.get_last_log_term(trunc_20) == 1 end test "get_log_suffix works" do config = create_nop_log(20) assert length(Raft.get_log_suffix(config, 10)) == 11 assert length(Raft.get_log_suffix(config, 20)) == 1 assert Raft.get_log_suffix(config, 21) == [] end test "add_log_entries works" do config = create_nop_log(2) entries = [Raft.LogEntry.nop(3, 2, :b)] config = Raft.add_log_entries(config, entries) assert Raft.get_last_log_index(config) == 3 assert Raft.get_last_log_term(config) == 2 config = Raft.add_log_entries(config, []) assert Raft.get_last_log_index(config) == 3 assert Raft.get_last_log_term(config) == 2 end end
33.393939
69
0.703267
039e405ed1ea331e3aec400f420588ec1444b4f8
808
exs
Elixir
test/data_helper.exs
elcritch/matrex_numerix
5835a9b477d8ea41bb9b862272a0997fe37c1236
[ "MIT" ]
8
2020-01-08T06:55:36.000Z
2021-03-10T15:44:46.000Z
test/data_helper.exs
elcritch/matrex_numerix
5835a9b477d8ea41bb9b862272a0997fe37c1236
[ "MIT" ]
null
null
null
test/data_helper.exs
elcritch/matrex_numerix
5835a9b477d8ea41bb9b862272a0997fe37c1236
[ "MIT" ]
null
null
null
defmodule DataHelper do def read(dataset) do lines = "test/resources/data/#{dataset}.dat" |> File.stream!() %{std_dev: parse_std_dev(lines), data: parse_data(lines)} end def read_mtx(dataset) do "test/resources/data/#{dataset}.mtx" |> Matrex.load() end defp parse_std_dev(lines) do lines |> Stream.filter(fn line -> String.contains?(line, "Sample Standard Deviation") end) |> Enum.at(0) |> String.split(":") |> List.last() |> String.trim() |> Float.parse() |> elem(0) end defp parse_data(lines) do lines |> Stream.drop_while(fn line -> line != "Data: Y\n" end) |> Stream.drop(2) |> Stream.map(&String.trim/1) |> Stream.map(&Float.parse/1) |> Stream.filter(fn x -> x != :error end) |> Stream.map(&elem(&1, 0)) end end
25.25
88
0.60396
039e4d9c30e74cbe74cd7fe136996d8c2dfd4ec8
2,989
ex
Elixir
lib/jsonrpc2/servers/http.ex
InoMurko/jsonrpc2-elixir
3edb92061231ddc9edc1a69531f7248d3d00d8f3
[ "Apache-2.0" ]
null
null
null
lib/jsonrpc2/servers/http.ex
InoMurko/jsonrpc2-elixir
3edb92061231ddc9edc1a69531f7248d3d00d8f3
[ "Apache-2.0" ]
null
null
null
lib/jsonrpc2/servers/http.ex
InoMurko/jsonrpc2-elixir
3edb92061231ddc9edc1a69531f7248d3d00d8f3
[ "Apache-2.0" ]
null
null
null
defmodule JSONRPC2.Servers.HTTP do @moduledoc """ An HTTP server which responds to POSTed JSON-RPC 2.0 in the request body. This server will respond to all requests on the given port. If you wish to mount a JSON-RPC 2.0 handler within a Plug-based web app (such as Phoenix), please see `JSONRPC2.Servers.HTTP.Plug`. """ alias JSONRPC2.Servers.HTTP.Plug, as: JSONRPC2Plug @doc """ Returns a supervisor child spec for the given `handler` via `scheme` with `cowboy_opts`. Allows you to embed a server directly in your app's supervision tree, rather than letting Plug/Cowboy handle it. Please see the docs for [Plug](https://hexdocs.pm/plug/Plug.Adapters.Cowboy.html) for the values which are allowed in `cowboy_opts`. If the server `ref` is not set in `cowboy_opts`, `handler.HTTP` or `handler.HTTPS` is the default. """ @spec child_spec(:http | :https, module, list) :: Supervisor.Spec.spec() def child_spec(scheme, handler, cowboy_opts \\ []) do cowboy_opts = cowboy_opts ++ [ref: ref(scheme, handler)] cowboy_adapter().child_spec(scheme, JSONRPC2Plug, handler, cowboy_opts) end @doc """ Starts an HTTP server for the given `handler` with `cowboy_opts`. Please see the docs for [Plug](https://hexdocs.pm/plug/Plug.Adapters.Cowboy.html) for the values which are allowed in `cowboy_opts`. If the server `ref` is not set in `cowboy_opts`, `handler.HTTP` is the default. """ @spec http(module, list) :: {:ok, pid} | {:error, term} def http(handler, cowboy_opts \\ []) do cowboy_opts = cowboy_opts ++ [ref: ref(:http, handler)] cowboy_adapter().http(JSONRPC2Plug, handler, cowboy_opts) end @doc """ Starts an HTTPS server for the given `handler` with `cowboy_opts`. Please see the docs for [Plug](https://hexdocs.pm/plug/Plug.Adapters.Cowboy.html) for the values which are allowed in `cowboy_opts`. In addition to the normal `cowboy_opts`, this function also accepts the same extra SSL-related options as [Plug.Adapters.Cowboy.https/3](https://hexdocs.pm/plug/Plug.Adapters.Cowboy.html#https/3). If the server `ref` is not set in `cowboy_opts`, `handler.HTTPS` is the default. """ @spec https(module, list) :: {:ok, pid} | {:error, term} def https(handler, cowboy_opts \\ []) do cowboy_opts = cowboy_opts ++ [ref: ref(:https, handler)] cowboy_adapter().https(JSONRPC2Plug, handler, cowboy_opts) end defp ref(scheme, handler) do case scheme do :http -> [handler, HTTP] :https -> [handler, HTTPS] end |> Module.concat() end @doc """ Shut down an existing server with given `ref`. """ @spec shutdown(atom) :: :ok | {:error, :not_found} def shutdown(ref) do cowboy_adapter().shutdown(ref) end defp cowboy_adapter() do cowboy_spec = Application.loaded_applications() |> List.keyfind(:cowboy, 0) if cowboy_spec do Plug.Cowboy else :ok = Application.load(:cowboy) cowboy_adapter() end end end
33.965909
100
0.689863
039e62ce63ef266f212033a0d6fa46ced0f994b8
1,753
ex
Elixir
lib/doc_gen/release_tasks.ex
the-mikedavis/doc_gen
efcc884ea65bba5748f41c5601abd00db2777ec4
[ "BSD-3-Clause" ]
null
null
null
lib/doc_gen/release_tasks.ex
the-mikedavis/doc_gen
efcc884ea65bba5748f41c5601abd00db2777ec4
[ "BSD-3-Clause" ]
27
2018-10-29T18:34:44.000Z
2019-03-11T18:43:12.000Z
lib/doc_gen/release_tasks.ex
the-mikedavis/doc_gen
efcc884ea65bba5748f41c5601abd00db2777ec4
[ "BSD-3-Clause" ]
null
null
null
defmodule DocGen.ReleaseTasks do @moduledoc """ Tasks runnable from a distillery release for doing database things. """ @start_apps [ :crypto, :ssl, :postgrex, :ecto ] @repos Application.get_env(:doc_gen, :ecto_repos, []) def migrate do start_services() run_migrations() stop_services() end def seed do start_services() run_migrations() run_seeds() stop_services() end defp start_services do IO.puts("Starting dependencies..") # Start apps necessary for executing migrations Enum.each(@start_apps, &Application.ensure_all_started/1) # Start the Repo(s) for app IO.puts("Starting repos..") Enum.each(@repos, & &1.start_link(pool_size: 1)) end defp stop_services do IO.puts("Success!") :init.stop() end defp run_migrations do Enum.each(@repos, &run_migrations_for/1) end defp run_migrations_for(repo) do app = Keyword.get(repo.config, :otp_app) IO.puts("Running migrations for #{app}") migrations_path = priv_path_for(repo, "migrations") Ecto.Migrator.run(repo, migrations_path, :up, all: true) end defp run_seeds do Enum.each(@repos, &run_seeds_for/1) end defp run_seeds_for(repo) do # Run the seed script if it exists seed_script = priv_path_for(repo, "seeds.exs") if File.exists?(seed_script) do IO.puts("Running seed script..") Code.eval_file(seed_script) end end defp priv_path_for(repo, filename) do app = Keyword.get(repo.config, :otp_app) repo_underscore = repo |> Module.split() |> List.last() |> Macro.underscore() priv_dir = "#{:code.priv_dir(app)}" Path.join([priv_dir, repo_underscore, filename]) end end
20.149425
69
0.659441
039e7a4cb43f536f2083a86f3ec91094fc86271d
1,648
exs
Elixir
mix.exs
annkissam/freshbooks_api_client
016edcf9e126d711048c6321ffd7f45b4727fd3d
[ "MIT" ]
2
2018-09-18T21:26:55.000Z
2020-04-24T15:29:05.000Z
mix.exs
annkissam/freshbooks_api_client
016edcf9e126d711048c6321ffd7f45b4727fd3d
[ "MIT" ]
1
2018-03-02T14:33:21.000Z
2018-03-02T14:33:21.000Z
mix.exs
annkissam/freshbooks_api_client
016edcf9e126d711048c6321ffd7f45b4727fd3d
[ "MIT" ]
null
null
null
defmodule FreshbooksApiClient.Mixfile do use Mix.Project @version "0.4.0" @url "https://github.com/annkissam/freshbooks_api_client" def project do [ app: :freshbooks_api_client, version: @version, elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, build_embedded: Mix.env() == :prod, deps: deps(), aliases: aliases(), # Hex description: description(), package: package(), # Docs name: "freshbooks_api_client", docs: docs() ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] def application do [extra_applications: [:logger]] end defp description() do """ A extendable wrapper around Freshbooks API written in Elixir. """ end def package do [ files: ["lib", "mix.exs", "README.md"], maintainers: ["Adi Iyengar", "Eric Sullivan"], licenses: ["MIT"], links: %{"Github" => @url} ] end def docs do [ main: "FreshbooksApiClient", source_url: @url, extras: ["README.md"], source_ref: "v#{@version}" ] end defp deps do [ {:ecto, "~> 3.0"}, {:ex_doc, "~> 0.22", only: :dev, runtime: false}, {:httpoison, "~> 1.7"}, {:retry, "~> 0.14"}, {:sweet_xml, "~> 0.6"}, {:xml_builder, "~> 2.0"} ] end defp aliases do [publish: ["hex.publish", &git_tag/1]] end defp git_tag(_args) do System.cmd("git", ["tag", "v" <> Mix.Project.config()[:version]]) System.cmd("git", ["push", "--tags"]) end end
20.860759
69
0.552791
039e7c2b9b6b7c0cdba2fea93fcead6fff982d17
3,952
exs
Elixir
test/suite/draft4/ref_remote_test.exs
depressed-pho/xema
56de4a5d3b3f37827c70f6052f895c59feb0bb51
[ "MIT" ]
null
null
null
test/suite/draft4/ref_remote_test.exs
depressed-pho/xema
56de4a5d3b3f37827c70f6052f895c59feb0bb51
[ "MIT" ]
null
null
null
test/suite/draft4/ref_remote_test.exs
depressed-pho/xema
56de4a5d3b3f37827c70f6052f895c59feb0bb51
[ "MIT" ]
null
null
null
defmodule Draft4.RefRemoteTest do use ExUnit.Case, async: true import Xema, only: [valid?: 2] describe "remote ref" do setup do %{schema: Xema.new({:ref, "http://localhost:1234/integer.exon"})} end test "remote ref valid", %{schema: schema} do data = 1 assert valid?(schema, data) end test "remote ref invalid", %{schema: schema} do data = "a" refute valid?(schema, data) end end describe "fragment within remote ref" do setup do %{ schema: Xema.new({:ref, "http://localhost:1234/subSchemas.exon#/integer"}) } end test "remote fragment valid", %{schema: schema} do data = 1 assert valid?(schema, data) end test "remote fragment invalid", %{schema: schema} do data = "a" refute valid?(schema, data) end end describe "ref within remote ref" do setup do %{ schema: Xema.new({:ref, "http://localhost:1234/subSchemas.exon#/refToInteger"}) } end test "ref within ref valid", %{schema: schema} do data = 1 assert valid?(schema, data) end test "ref within ref invalid", %{schema: schema} do data = "a" refute valid?(schema, data) end end describe "base URI change" do setup do %{ schema: Xema.new( id: "http://localhost:1234/", items: [id: "folder/", items: {:ref, "folderInteger.exon"}] ) } end test "base URI change ref valid", %{schema: schema} do data = [[1]] assert valid?(schema, data) end test "base URI change ref invalid", %{schema: schema} do data = [["a"]] refute valid?(schema, data) end end describe "base URI change - change folder" do setup do %{ schema: Xema.new( {:map, [ definitions: %{ baz: {:list, [id: "folder/", items: {:ref, "folderInteger.exon"}]} }, id: "http://localhost:1234/scope_change_defs1.exon", properties: %{list: {:ref, "#/definitions/baz"}} ]} ) } end test "number is valid", %{schema: schema} do data = %{list: [1]} assert valid?(schema, data) end test "string is invalid", %{schema: schema} do data = %{list: ["a"]} refute valid?(schema, data) end end describe "base URI change - change folder in subschema" do setup do %{ schema: Xema.new( {:map, [ definitions: %{ baz: [ definitions: %{ bar: {:list, [items: {:ref, "folderInteger.exon"}]} }, id: "folder/" ] }, id: "http://localhost:1234/scope_change_defs2.exon", properties: %{list: {:ref, "#/definitions/baz/definitions/bar"}} ]} ) } end test "number is valid", %{schema: schema} do data = %{list: [1]} assert valid?(schema, data) end test "string is invalid", %{schema: schema} do data = %{list: ["a"]} refute valid?(schema, data) end end describe "root ref in remote ref" do setup do %{ schema: Xema.new( {:map, [ id: "http://localhost:1234/object", properties: %{name: {:ref, "name.exon#/definitions/orNull"}} ]} ) } end test "string is valid", %{schema: schema} do data = %{name: "foo"} assert valid?(schema, data) end test "null is valid", %{schema: schema} do data = %{name: nil} assert valid?(schema, data) end test "object is invalid", %{schema: schema} do data = %{name: %{name: nil}} refute valid?(schema, data) end end end
23.111111
87
0.501518
039ead8d1fc6d885aac5adb1f6a9cd2b7bc3f02c
7,335
ex
Elixir
apps/ex_wire/lib/ex_wire/framing/frame.ex
atoulme/mana
cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
apps/ex_wire/lib/ex_wire/framing/frame.ex
atoulme/mana
cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
apps/ex_wire/lib/ex_wire/framing/frame.ex
atoulme/mana
cff3fd96c23feaaeb9fe32df3c0d35ee6dc548a5
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
defmodule ExWire.Framing.Frame do @moduledoc """ Handles framing a message for transport in RLPx. This is defined in the [RLPx docs[(https://github.com/ethereum/devp2p/blob/master/rlpx.md) under Framing section. TODO: Handle multi-frame packets, etc. TODO: Add tests, etc. """ alias ExthCrypto.{AES, MAC} alias ExWire.Framing.Secrets @type frame :: binary() @spec frame(integer(), ExRLP.t(), Secrets.t()) :: {frame, Secrets.t()} def frame( packet_type, packet_data, frame_secrets = %Secrets{ egress_mac: egress_mac, encoder_stream: encoder_stream, mac_encoder: mac_encoder, mac_secret: mac_secret } ) do # frame: # normal: rlp(packet-type) [|| rlp(packet-data)] || padding # chunked-0: rlp(packet-type) || rlp(packet-data...) # chunked-n: rlp(...packet-data) || padding # padding: zero-fill to 16-byte boundary (only necessary for last frame) frame_unpadded = ExRLP.encode(packet_type) <> if packet_data, do: ExRLP.encode(packet_data), else: <<>> # frame-size: 3-byte integer size of frame, big endian encoded (excludes padding) frame_size_int = byte_size(frame_unpadded) frame_size = <<frame_size_int::size(24)>> # assert! total-packet-size: < 2**32 frame_padding = padding_for(frame_size_int, 16) # header-data: # normal: rlp.list(protocol-type[, context-id]) # chunked-0: rlp.list(protocol-type, context-id, total-packet-size) # chunked-n: rlp.list(protocol-type, context-id) # values: # protocol-type: < 2**16 # context-id: < 2**16 (optional for normal frames) # total-packet-size: < 2**32 # protocol_type = <<>> # context_id = <<>> # header_data = [protocol_type, context_id] |> ExRLP.encode() # Honestly, this is what Geth and Parity use as a header data. header_data = <<0xC2, 0x80, 0x80>> header_padding = padding_for(byte_size(frame_size <> header_data), 16) # header: frame-size || header-data || padding header = frame_size <> header_data <> header_padding {encoder_stream, header_enc} = AES.stream_encrypt(header, encoder_stream) # header-mac: right128 of egress-mac.update(aes(mac-secret,egress-mac) ^ header-ciphertext).digest egress_mac = update_mac(egress_mac, mac_encoder, mac_secret, header_enc) header_mac = egress_mac |> MAC.final() |> Binary.take(16) {encoder_stream, frame_unpadded_enc} = AES.stream_encrypt(frame_unpadded, encoder_stream) {encoder_stream, frame_padding_enc} = if byte_size(frame_padding) > 0 do AES.stream_encrypt(frame_padding, encoder_stream) else {encoder_stream, <<>>} end frame_enc = frame_unpadded_enc <> frame_padding_enc # frame-mac: right128 of egress-mac.update(aes(mac-secret,egress-mac) ^ # right128(egress-mac.update(frame-ciphertext).digest)) # from EncryptedConnection::update_mac(&mut self.egress_mac, &mut self.mac_encoder, &[0u8; 0]); egress_mac = MAC.update(egress_mac, frame_enc) egress_mac = update_mac(egress_mac, mac_encoder, mac_secret, nil) frame_mac = egress_mac |> MAC.final() |> Binary.take(16) # egress-mac: h256, continuously updated with egress-bytes* # ingress-mac: h256, continuously updated with ingress-bytes* # Single-frame packet: # header || header-mac || frame || frame-mac frame = header_enc <> header_mac <> frame_enc <> frame_mac # Return packet and secrets with updated egress mac and symmetric encoder {frame, %{frame_secrets | egress_mac: egress_mac, encoder_stream: encoder_stream}} end @spec unframe(binary(), Secrets.t()) :: {:ok, integer(), binary(), binary(), Secrets.t()} | {:error, String.t()} def unframe( frame, frame_secrets = %Secrets{ ingress_mac: ingress_mac, decoder_stream: decoder_stream, mac_encoder: mac_encoder, mac_secret: mac_secret } ) do << # is header always 128 bits? header_enc::binary-size(16), header_mac::binary-size(16), frame_rest::binary() >> = frame # verify header mac ingress_mac = update_mac(ingress_mac, mac_encoder, mac_secret, header_enc) expected_header_mac = ingress_mac |> MAC.final() |> Binary.take(16) if expected_header_mac != header_mac do {:error, "Failed to match header ingress mac"} else {decoder_stream, header} = AES.stream_decrypt(header_enc, decoder_stream) << frame_size::integer-size(24), _header_data_and_padding::binary() >> = header # TODO: We should read the header? But, it's unused by all clients. # header_rlp = header_data_and_padding |> ExRLP.decode # protocol_id = Enum.at(header_rlp, 0) |> ExRLP.decode frame_padding_bytes = padding_size(frame_size, 16) if byte_size(frame_rest) < frame_size + frame_padding_bytes + 16 do {:error, "Insufficent data"} else # let's go and ignore the entire header data.... << frame_enc::binary-size(frame_size), frame_padding::binary-size(frame_padding_bytes), frame_mac::binary-size(16), frame_rest::binary() >> = frame_rest frame_enc_with_padding = frame_enc <> frame_padding ingress_mac = MAC.update(ingress_mac, frame_enc_with_padding) ingress_mac = update_mac(ingress_mac, mac_encoder, mac_secret, nil) expected_frame_mac = ingress_mac |> MAC.final() |> Binary.take(16) if expected_frame_mac != frame_mac do {:error, "Failed to match frame ingress mac"} else {decoder_stream, frame_with_padding} = AES.stream_decrypt(frame_enc_with_padding, decoder_stream) << frame::binary-size(frame_size), _frame_padding::binary() >> = frame_with_padding << packet_type_rlp::binary-size(1), packet_data_rlp::binary() >> = frame { :ok, packet_type_rlp |> ExRLP.decode() |> :binary.decode_unsigned(), packet_data_rlp |> ExRLP.decode(), frame_rest, %{frame_secrets | ingress_mac: ingress_mac, decoder_stream: decoder_stream} } end end end end # updateMAC reseeds the given hash with encrypted seed. # it returns the first 16 bytes of the hash sum after seeding. @spec update_mac( MAC.mac_inst(), ExthCrypto.Cipher.cipher(), ExthCrypto.Key.symmetric_key(), binary() | nil ) :: MAC.mac_inst() defp update_mac(mac, mac_encoder, mac_secret, seed) do final = mac |> MAC.final() |> Binary.take(16) enc = final |> ExthCrypto.Cipher.encrypt(mac_secret, mac_encoder) |> Binary.take(-16) enc_xored = ExthCrypto.Math.xor(enc, if(seed, do: seed, else: final)) MAC.update(mac, enc_xored) end @spec padding_size(integer(), integer()) :: integer() defp padding_size(given_size, to_size) do to_size - rem(given_size, to_size) end @spec padding_for(integer(), integer()) :: binary() defp padding_for(given_size, to_size) do padding_bits = padding_size(given_size, to_size) * 8 <<0::size(padding_bits)>> end end
35.095694
102
0.644717
039eb4928bf61d7b01aa38bf5da5cd211b30223f
878
ex
Elixir
clients/people/lib/google_api/people/v1/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/people/lib/google_api/people/v1/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/people/lib/google_api/people/v1/metadata.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.People.V1 do @moduledoc """ API client metadata for GoogleApi.People.V1. """ @discovery_revision "20201006" def discovery_revision(), do: @discovery_revision end
32.518519
74
0.757403
039ec124920672c0132b0906a1e3c6bcaadb107e
81
exs
Elixir
test/absinthe/integration/execution/custom_types/basic.exs
maartenvanvliet/absinthe
ebe820717200f53756e225b3dffbfefe924a94d3
[ "MIT" ]
null
null
null
test/absinthe/integration/execution/custom_types/basic.exs
maartenvanvliet/absinthe
ebe820717200f53756e225b3dffbfefe924a94d3
[ "MIT" ]
2
2020-07-21T05:23:37.000Z
2020-08-26T04:56:12.000Z
test/absinthe/integration/execution/custom_types/basic.exs
jlgeering/absinthe
a3dbc29640d613928398626ad75a8f03203a1720
[ "MIT" ]
null
null
null
{:ok, %{data: %{"customTypesQuery" => %{"datetime" => "2017-01-27T20:31:55Z"}}}}
40.5
80
0.567901
039ecc37ade3b0ff7ac96fa147c788c0a8f31da1
2,569
ex
Elixir
clients/data_labeling/lib/google_api/data_labeling/v1beta1/model/google_cloud_datalabeling_v1p1alpha1_export_data_operation_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/data_labeling/lib/google_api/data_labeling/v1beta1/model/google_cloud_datalabeling_v1p1alpha1_export_data_operation_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/data_labeling/lib/google_api/data_labeling/v1beta1/model/google_cloud_datalabeling_v1p1alpha1_export_data_operation_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1p1alpha1ExportDataOperationMetadata do @moduledoc """ Metadata of an ExportData operation. ## Attributes * `annotatedDataset` (*type:* `String.t`, *default:* `nil`) - Output only. The name of annotated dataset in format "projects/*/datasets/*/annotatedDatasets/*". * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Timestamp when export dataset request was created. * `dataset` (*type:* `String.t`, *default:* `nil`) - Output only. The name of dataset to be exported. "projects/*/datasets/*" * `partialFailures` (*type:* `list(GoogleApi.DataLabeling.V1beta1.Model.GoogleRpcStatus.t)`, *default:* `nil`) - Output only. Partial failures encountered. E.g. single files that couldn't be read. Status details field will contain standard GCP error details. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :annotatedDataset => String.t(), :createTime => DateTime.t(), :dataset => String.t(), :partialFailures => list(GoogleApi.DataLabeling.V1beta1.Model.GoogleRpcStatus.t()) } field(:annotatedDataset) field(:createTime, as: DateTime) field(:dataset) field(:partialFailures, as: GoogleApi.DataLabeling.V1beta1.Model.GoogleRpcStatus, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1p1alpha1ExportDataOperationMetadata do def decode(value, options) do GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1p1alpha1ExportDataOperationMetadata.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DataLabeling.V1beta1.Model.GoogleCloudDatalabelingV1p1alpha1ExportDataOperationMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.777778
262
0.740366
039f0ebd7a79ffb238be9174b053a357ec426149
1,797
ex
Elixir
clients/health_care/lib/google_api/health_care/v1beta1/model/import_dicom_data_error_details.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/health_care/lib/google_api/health_care/v1beta1/model/import_dicom_data_error_details.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/health_care/lib/google_api/health_care/v1beta1/model/import_dicom_data_error_details.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.HealthCare.V1beta1.Model.ImportDicomDataErrorDetails do @moduledoc """ Returns the errors encountered during DICOM store import. ## Attributes * `sampleErrors` (*type:* `list(GoogleApi.HealthCare.V1beta1.Model.ErrorDetail.t)`, *default:* `nil`) - Deprecated. Use only for debugging purposes. Contains sample errors encountered in imports of individual resources. For example, a Cloud Storage object. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :sampleErrors => list(GoogleApi.HealthCare.V1beta1.Model.ErrorDetail.t()) } field(:sampleErrors, as: GoogleApi.HealthCare.V1beta1.Model.ErrorDetail, type: :list) end defimpl Poison.Decoder, for: GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataErrorDetails do def decode(value, options) do GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataErrorDetails.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.HealthCare.V1beta1.Model.ImportDicomDataErrorDetails do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.94
152
0.760712
039f12a776deb0c5cb22f22201cd128e08462118
1,854
exs
Elixir
clients/cloud_scheduler/mix.exs
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_scheduler/mix.exs
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_scheduler/mix.exs
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.CloudScheduler.Mixfile do use Mix.Project @version "0.7.2" def project() do [ app: :google_api_cloud_scheduler, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/cloud_scheduler" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Scheduler API client library. Creates and manages jobs run on a regular recurring schedule. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/cloud_scheduler", "Homepage" => "https://cloud.google.com/scheduler/" } ] end end
27.671642
106
0.658576
039f2589fc6db224f8ace85ba8c6c9a91380544c
1,343
exs
Elixir
config/dev.exs
gilacost/task_manager
550d8ce603b555f017dd689a2db6819b85ddbbd1
[ "MIT" ]
null
null
null
config/dev.exs
gilacost/task_manager
550d8ce603b555f017dd689a2db6819b85ddbbd1
[ "MIT" ]
null
null
null
config/dev.exs
gilacost/task_manager
550d8ce603b555f017dd689a2db6819b85ddbbd1
[ "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 brunch.io to recompile .js and .css sources. config :home_work_manager, HomeWorkManager.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: ["node_modules/webpack/bin/webpack.js", "--watch", "--color"] ] # Watch static and templates for browser reloading. config :home_work_manager, HomeWorkManager.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{web/views/.*(ex)$}, ~r{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. # Do not configure such in production as keeping # and calculating stacktraces is usually expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :home_work_manager, HomeWorkManager.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "home_work_manager", hostname: "192.168.99.100", pool_size: 10
29.195652
73
0.714073
039f2adf8c334ae0994875ded7db673f39dae3c3
306
exs
Elixir
apps/rumbl/priv/repo/migrations/20160630203719_create_user.exs
Krustee/rumbrella
252ee46da0c563680f8dddb381523ab7a75069fe
[ "MIT" ]
null
null
null
apps/rumbl/priv/repo/migrations/20160630203719_create_user.exs
Krustee/rumbrella
252ee46da0c563680f8dddb381523ab7a75069fe
[ "MIT" ]
null
null
null
apps/rumbl/priv/repo/migrations/20160630203719_create_user.exs
Krustee/rumbrella
252ee46da0c563680f8dddb381523ab7a75069fe
[ "MIT" ]
null
null
null
defmodule Rumbl.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :name, :string add :username, :string, null: false add :password_hash, :string timestamps end create unique_index(:users, [:username]) end end
19.125
45
0.640523
039f47c1f2eaf791cd7ef6e46ded6c38c390460c
1,970
ex
Elixir
clients/games/lib/google_api/games/v1/model/player_achievement_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/games/lib/google_api/games/v1/model/player_achievement_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/games/lib/google_api/games/v1/model/player_achievement_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Games.V1.Model.PlayerAchievementListResponse do @moduledoc """ A list of achievement objects. ## Attributes * `items` (*type:* `list(GoogleApi.Games.V1.Model.PlayerAchievement.t)`, *default:* `nil`) - The achievements. * `kind` (*type:* `String.t`, *default:* `nil`) - Uniquely identifies the type of this resource. Value is always the fixed string `games#playerAchievementListResponse`. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Token corresponding to the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :items => list(GoogleApi.Games.V1.Model.PlayerAchievement.t()) | nil, :kind => String.t() | nil, :nextPageToken => String.t() | nil } field(:items, as: GoogleApi.Games.V1.Model.PlayerAchievement, type: :list) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.PlayerAchievementListResponse do def decode(value, options) do GoogleApi.Games.V1.Model.PlayerAchievementListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.PlayerAchievementListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.169811
172
0.726904
039f83c7190a122071e996eef6562f3fa5d5a42c
1,141
ex
Elixir
clients/data_migration/lib/google_api/data_migration/v1beta1/connection.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/data_migration/lib/google_api/data_migration/v1beta1/connection.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/data_migration/lib/google_api/data_migration/v1beta1/connection.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DataMigration.V1beta1.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.DataMigration.V1beta1. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # See, edit, configure, and delete your Google Cloud Platform data "https://www.googleapis.com/auth/cloud-platform" ], otp_app: :google_api_data_migration, base_url: "https://datamigration.googleapis.com/" end
34.575758
74
0.743208
039f87fea2d4b0ce913876ceefed3806c1912266
1,516
ex
Elixir
lib/ratatouille/renderer/element/tree.ex
Fitblip/ratatouille
873f8a51b0f824ce9e39b7575850fcc585cfc7b1
[ "MIT" ]
504
2019-01-13T21:53:21.000Z
2022-03-31T20:58:21.000Z
lib/ratatouille/renderer/element/tree.ex
iboard/ratatouille
cc7b6a37e0b1757cd89cc5084343814a79dd86dc
[ "MIT" ]
28
2019-01-26T21:00:23.000Z
2021-12-28T19:06:15.000Z
lib/ratatouille/renderer/element/tree.ex
iboard/ratatouille
cc7b6a37e0b1757cd89cc5084343814a79dd86dc
[ "MIT" ]
21
2019-02-21T09:08:27.000Z
2021-12-20T15:51:10.000Z
defmodule Ratatouille.Renderer.Element.Tree do @moduledoc false @behaviour Ratatouille.Renderer alias ExTermbox.Position alias Ratatouille.Renderer.{Canvas, Element, Text} @impl true def render(%Canvas{} = canvas, %Element{children: nodes}, _render_fn) do canvas |> render_nodes(nodes, "", true) |> Canvas.consume_rows(1) end def render_nodes(canvas, [], _depth, _root) do canvas end def render_nodes( %Canvas{render_box: box} = canvas, [ %Element{tag: :tree_node, attributes: attrs, children: children} | siblings ], parent_prefix, root ) do last_child = Enum.empty?(siblings) text = to_string(attrs[:content]) node_prefix = parent_prefix <> line(root, last_child) child_prefix = parent_prefix <> indent(root, last_child) node_prefix_offset = Position.translate_x(box.top_left, String.length(node_prefix)) canvas |> Text.render(box.top_left, node_prefix) |> Text.render(node_prefix_offset, text, attrs) |> Canvas.consume_rows(1) |> render_nodes(children, child_prefix, false) |> render_nodes(siblings, parent_prefix, root) end @line "├── " @line_last "└── " @indent "│   " @indent_last "    " defp line(true, _last_child), do: "" defp line(_root, true), do: @line_last defp line(_root, false), do: @line defp indent(true, _last_child), do: "" defp indent(_root, true), do: @indent_last defp indent(_root, false), do: @indent end
25.266667
74
0.655673
039f9ccf824c7caded7e4dc04da5d8afa454be3a
77
exs
Elixir
spec/brex/rule_spec.exs
kianmeng/brex
f9758e0e8684404d7552597aac9e436aa8063532
[ "MIT" ]
34
2018-04-04T10:27:08.000Z
2019-05-19T15:46:08.000Z
spec/brex/rule_spec.exs
kianmeng/brex
f9758e0e8684404d7552597aac9e436aa8063532
[ "MIT" ]
4
2020-05-04T08:50:21.000Z
2021-12-15T01:25:43.000Z
spec/brex/rule_spec.exs
kianmeng/brex
f9758e0e8684404d7552597aac9e436aa8063532
[ "MIT" ]
3
2020-05-07T13:36:25.000Z
2021-11-04T22:49:16.000Z
defmodule Brex.RuleSpec do use ESpec, async: true doctest Brex.Rule end
12.833333
26
0.753247
039fbdda5775b74e2fd9af595ccb81a02f8dc42e
1,129
exs
Elixir
excollections/config/config.exs
metabrain/elixir-playground
0c114ee8a8cb2d610f54b9cca83cbe6917226c33
[ "MIT" ]
null
null
null
excollections/config/config.exs
metabrain/elixir-playground
0c114ee8a8cb2d610f54b9cca83cbe6917226c33
[ "MIT" ]
null
null
null
excollections/config/config.exs
metabrain/elixir-playground
0c114ee8a8cb2d610f54b9cca83cbe6917226c33
[ "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 :excollections, key: :value # # And access this configuration in your application as: # # Application.get_env(:excollections, :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.419355
73
0.753764
03a02d9062805783ec843e262e794751bacda784
16,677
ex
Elixir
lib/ecto/repo/queryable.ex
adbatista/ecto
ab63701cf9b3ceab6ddf54c87d549abe24e1248a
[ "Apache-2.0" ]
2
2021-02-25T15:51:16.000Z
2021-02-25T18:42:35.000Z
lib/ecto/repo/queryable.ex
adbatista/ecto
ab63701cf9b3ceab6ddf54c87d549abe24e1248a
[ "Apache-2.0" ]
null
null
null
lib/ecto/repo/queryable.ex
adbatista/ecto
ab63701cf9b3ceab6ddf54c87d549abe24e1248a
[ "Apache-2.0" ]
1
2018-06-18T14:47:58.000Z
2018-06-18T14:47:58.000Z
defmodule Ecto.Repo.Queryable do @moduledoc false alias Ecto.Queryable alias Ecto.Query alias Ecto.Query.Planner alias Ecto.Query.SelectExpr require Ecto.Query def all(name, queryable, opts) when is_list(opts) do query = queryable |> Ecto.Queryable.to_query() |> Ecto.Query.Planner.ensure_select(true) execute(:all, name, query, opts) |> elem(1) end def stream(name, queryable, opts) when is_list(opts) do query = queryable |> Ecto.Queryable.to_query() |> Ecto.Query.Planner.ensure_select(true) {adapter, %{cache: cache, repo: repo} = adapter_meta} = Ecto.Repo.Registry.lookup(name) {query, opts} = repo.prepare_query(:stream, query, opts) query = attach_prefix(query, opts) {query_meta, prepared, params} = Planner.query(query, :all, cache, adapter, 0) case query_meta do %{select: nil} -> adapter_meta |> adapter.stream(query_meta, prepared, params, opts) |> Stream.flat_map(fn {_, nil} -> [] end) %{select: select, preloads: preloads} -> %{ assocs: assocs, preprocess: preprocess, postprocess: postprocess, take: take, from: from } = select if preloads != [] or assocs != [] do raise Ecto.QueryError, query: query, message: "preloads are not supported on streams" end preprocessor = preprocessor(from, preprocess, adapter) stream = adapter.stream(adapter_meta, query_meta, prepared, params, opts) postprocessor = postprocessor(from, postprocess, take, adapter) stream |> Stream.flat_map(fn {_, rows} -> rows end) |> Stream.map(preprocessor) |> Stream.map(postprocessor) end end def get(name, queryable, id, opts) do one(name, query_for_get(queryable, id), opts) end def get!(name, queryable, id, opts) do one!(name, query_for_get(queryable, id), opts) end def get_by(name, queryable, clauses, opts) do one(name, query_for_get_by(queryable, clauses), opts) end def get_by!(name, queryable, clauses, opts) do one!(name, query_for_get_by(queryable, clauses), opts) end def reload(name, [head | _] = structs, opts) when is_list(structs) do results = all(name, query_for_reload(structs), opts) [pk] = head.__struct__.__schema__(:primary_key) for struct <- structs do struct_pk = Map.fetch!(struct, pk) Enum.find(results, &Map.fetch!(&1, pk) == struct_pk) end end def reload(name, struct, opts) do one(name, query_for_reload([struct]), opts) end def reload!(name, [head | _] = structs, opts) when is_list(structs) do query = query_for_reload(structs) results = all(name, query, opts) [pk] = head.__struct__.__schema__(:primary_key) for struct <- structs do struct_pk = Map.fetch!(struct, pk) Enum.find(results, &Map.fetch!(&1, pk) == struct_pk) || raise "could not reload #{inspect(struct)}, maybe it doesn't exist or was deleted" end end def reload!(name, struct, opts) do query = query_for_reload([struct]) case one!(name, query, opts) do nil -> raise Ecto.NoResultsError, queryable: query res -> res end end def aggregate(name, queryable, aggregate, opts) do one!(name, query_for_aggregate(queryable, aggregate), opts) end def aggregate(name, queryable, aggregate, field, opts) do one!(name, query_for_aggregate(queryable, aggregate, field), opts) end def exists?(name, queryable, opts) do queryable = Query.exclude(queryable, :select) |> Query.exclude(:preload) |> Query.exclude(:order_by) |> Query.exclude(:distinct) |> Query.select(1) |> Query.limit(1) |> rewrite_combinations() case all(name, queryable, opts) do [1] -> true [] -> false end end defp rewrite_combinations(%{combinations: []} = query), do: query defp rewrite_combinations(%{combinations: combinations} = query) do combinations = Enum.map(combinations, fn {type, query} -> {type, query |> Query.exclude(:select) |> Query.select(1)} end) %{query | combinations: combinations} end def one(name, queryable, opts) do case all(name, queryable, opts) do [one] -> one [] -> nil other -> raise Ecto.MultipleResultsError, queryable: queryable, count: length(other) end end def one!(name, queryable, opts) do case all(name, queryable, opts) do [one] -> one [] -> raise Ecto.NoResultsError, queryable: queryable other -> raise Ecto.MultipleResultsError, queryable: queryable, count: length(other) end end def update_all(name, queryable, [], opts) when is_list(opts) do update_all(name, queryable, opts) end def update_all(name, queryable, updates, opts) when is_list(opts) do query = Query.from(queryable, update: ^updates) update_all(name, query, opts) end defp update_all(name, queryable, opts) do query = Ecto.Queryable.to_query(queryable) execute(:update_all, name, query, opts) end def delete_all(name, queryable, opts) when is_list(opts) do query = Ecto.Queryable.to_query(queryable) execute(:delete_all, name, query, opts) end @doc """ Load structs from query. """ def struct_load!([{field, type} | types], [value | values], acc, all_nil?, struct, adapter) do all_nil? = all_nil? and value == nil value = load!(type, value, field, struct, adapter) struct_load!(types, values, [{field, value} | acc], all_nil?, struct, adapter) end def struct_load!([], values, _acc, true, _struct, _adapter) do {nil, values} end def struct_load!([], values, acc, false, struct, _adapter) do {Map.merge(struct, Map.new(acc)), values} end ## Helpers defp attach_prefix(query, opts) do case Keyword.fetch(opts, :prefix) do {:ok, prefix} -> %{query | prefix: prefix} :error -> query end end defp execute(operation, name, query, opts) when is_list(opts) do {adapter, %{cache: cache, repo: repo} = adapter_meta} = Ecto.Repo.Registry.lookup(name) {query, opts} = repo.prepare_query(operation, query, opts) query = attach_prefix(query, opts) {query_meta, prepared, params} = Planner.query(query, operation, cache, adapter, 0) case query_meta do %{select: nil} -> adapter.execute(adapter_meta, query_meta, prepared, params, opts) %{select: select, sources: sources, preloads: preloads} -> %{ preprocess: preprocess, postprocess: postprocess, take: take, assocs: assocs, from: from } = select preprocessor = preprocessor(from, preprocess, adapter) {count, rows} = adapter.execute(adapter_meta, query_meta, prepared, params, opts) postprocessor = postprocessor(from, postprocess, take, adapter) {count, rows |> Ecto.Repo.Assoc.query(assocs, sources, preprocessor) |> Ecto.Repo.Preloader.query(name, preloads, take, postprocessor, opts)} end end defp preprocessor({_, {:source, {source, schema}, prefix, types}}, preprocess, adapter) do struct = Ecto.Schema.Loader.load_struct(schema, prefix, source) fn row -> {entry, rest} = struct_load!(types, row, [], false, struct, adapter) preprocess(rest, preprocess, entry, adapter) end end defp preprocessor({_, from}, preprocess, adapter) do fn row -> {entry, rest} = process(row, from, nil, adapter) preprocess(rest, preprocess, entry, adapter) end end defp preprocessor(:none, preprocess, adapter) do fn row -> preprocess(row, preprocess, nil, adapter) end end defp preprocess(row, [], _from, _adapter) do row end defp preprocess(row, [source | sources], from, adapter) do {entry, rest} = process(row, source, from, adapter) [entry | preprocess(rest, sources, from, adapter)] end defp postprocessor({:any, _}, postprocess, _take, adapter) do fn [from | row] -> row |> process(postprocess, from, adapter) |> elem(0) end end defp postprocessor({:map, _}, postprocess, take, adapter) do fn [from | row] -> row |> process(postprocess, to_map(from, take), adapter) |> elem(0) end end defp postprocessor(:none, postprocess, _take, adapter) do fn row -> row |> process(postprocess, nil, adapter) |> elem(0) end end defp process(row, {:source, :from}, from, _adapter) do {from, row} end defp process(row, {:source, {source, schema}, prefix, types}, _from, adapter) do struct = Ecto.Schema.Loader.load_struct(schema, prefix, source) struct_load!(types, row, [], true, struct, adapter) end defp process(row, {:merge, left, right}, from, adapter) do {left, row} = process(row, left, from, adapter) {right, row} = process(row, right, from, adapter) data = case {left, right} do {%{__struct__: s}, %{__struct__: s}} -> Map.merge(left, right) {%{__struct__: left_struct}, %{__struct__: right_struct}} -> raise ArgumentError, "cannot merge structs of different types, " <> "got: #{inspect(left_struct)} and #{inspect(right_struct)}" {%{__struct__: name}, %{}} -> for {key, _} <- right, not Map.has_key?(left, key) do raise ArgumentError, "struct #{inspect(name)} does not have the key #{inspect(key)}" end Map.merge(left, right) {%{}, %{}} -> Map.merge(left, right) {%{}, nil} -> left {_, %{}} -> raise ArgumentError, "cannot merge because the left side is not a map, got: #{inspect(left)}" {%{}, _} -> raise ArgumentError, "cannot merge because the right side is not a map, got: #{inspect(right)}" end {data, row} end defp process(row, {:struct, struct, data, args}, from, adapter) do case process(row, data, from, adapter) do {%{__struct__: ^struct} = data, row} -> process_update(data, args, row, from, adapter) {data, _row} -> raise BadStructError, struct: struct, term: data end end defp process(row, {:struct, struct, args}, from, adapter) do {fields, row} = process_kv(args, row, from, adapter) case Map.merge(struct.__struct__(), Map.new(fields)) do %{__meta__: %Ecto.Schema.Metadata{state: state} = metadata} = struct when state != :loaded -> {Map.replace!(struct, :__meta__, %{metadata | state: :loaded}), row} map -> {map, row} end end defp process(row, {:map, data, args}, from, adapter) do {data, row} = process(row, data, from, adapter) process_update(data, args, row, from, adapter) end defp process(row, {:map, args}, from, adapter) do {args, row} = process_kv(args, row, from, adapter) {Map.new(args), row} end defp process(row, {:list, args}, from, adapter) do process_args(args, row, from, adapter) end defp process(row, {:tuple, args}, from, adapter) do {args, row} = process_args(args, row, from, adapter) {List.to_tuple(args), row} end defp process([value | row], {:value, :any}, _from, _adapter) do {value, row} end defp process([value | row], {:value, type}, _from, adapter) do {load!(type, value, nil, nil, adapter), row} end defp process(row, value, _from, _adapter) when is_binary(value) or is_number(value) or is_atom(value) do {value, row} end defp process_update(data, args, row, from, adapter) do {args, row} = process_kv(args, row, from, adapter) data = Enum.reduce(args, data, fn {key, value}, acc -> %{acc | key => value} end) {data, row} end defp process_args(args, row, from, adapter) do Enum.map_reduce(args, row, fn arg, row -> process(row, arg, from, adapter) end) end defp process_kv(kv, row, from, adapter) do Enum.map_reduce(kv, row, fn {key, value}, row -> {key, row} = process(row, key, from, adapter) {value, row} = process(row, value, from, adapter) {{key, value}, row} end) end @compile {:inline, load!: 5} defp load!(type, value, field, struct, adapter) do case Ecto.Type.adapter_load(adapter, type, value) do {:ok, value} -> value :error -> field = field && " for field #{inspect(field)}" struct = struct && " in #{inspect(struct)}" raise ArgumentError, "cannot load `#{inspect(value)}` as type #{inspect(type)}#{field}#{struct}" end end defp to_map(nil, _fields) do nil end defp to_map(value, fields) when is_list(value) do Enum.map(value, &to_map(&1, fields)) end defp to_map(value, fields) do for field <- fields, into: %{} do case field do {k, v} -> {k, to_map(Map.fetch!(value, k), List.wrap(v))} k -> {k, Map.fetch!(value, k)} end end end defp query_for_get(_queryable, nil) do raise ArgumentError, "cannot perform Ecto.Repo.get/2 because the given value is nil" end defp query_for_get(queryable, id) do query = Queryable.to_query(queryable) schema = assert_schema!(query) case schema.__schema__(:primary_key) do [pk] -> Query.from(x in query, where: field(x, ^pk) == ^id) pks -> raise ArgumentError, "Ecto.Repo.get/2 requires the schema #{inspect(schema)} " <> "to have exactly one primary key, got: #{inspect(pks)}" end end defp query_for_get_by(queryable, clauses) do Query.where(queryable, [], ^Enum.to_list(clauses)) end defp query_for_reload([head| _] = structs) do assert_structs!(structs) schema = head.__struct__ prefix = head.__meta__.prefix case schema.__schema__(:primary_key) do [pk] -> keys = Enum.map(structs, &get_pk!(&1, pk)) query = Query.from(x in schema, where: field(x, ^pk) in ^keys) %{query | prefix: prefix} pks -> raise ArgumentError, "Ecto.Repo.reload/2 requires the schema #{inspect(schema)} " <> "to have exactly one primary key, got: #{inspect(pks)}" end end defp query_for_aggregate(queryable, aggregate) do query = case prepare_for_aggregate(queryable) do %{distinct: nil, limit: nil, offset: nil} = query -> %{query | order_bys: []} query -> query |> Query.subquery() |> Queryable.Ecto.SubQuery.to_query() end select = %SelectExpr{expr: {aggregate, [], []}, file: __ENV__.file, line: __ENV__.line} %{query | select: select} end defp query_for_aggregate(queryable, aggregate, field) do ast = field(0, field) query = case prepare_for_aggregate(queryable) do %{distinct: nil, limit: nil, offset: nil} = query -> %{query | order_bys: []} query -> select = %SelectExpr{expr: ast, file: __ENV__.file, line: __ENV__.line} %{query | select: select} |> Query.subquery() |> Queryable.Ecto.SubQuery.to_query() end select = %SelectExpr{expr: {aggregate, [], [ast]}, file: __ENV__.file, line: __ENV__.line} %{query | select: select} end defp prepare_for_aggregate(queryable) do case %{Queryable.to_query(queryable) | preloads: [], assocs: []} do %{group_bys: [_ | _]} = query -> raise Ecto.QueryError, message: "cannot aggregate on query with group_by", query: query %{} = query -> query end end defp field(ix, field) when is_integer(ix) and is_atom(field) do {{:., [], [{:&, [], [ix]}, field]}, [], []} end defp assert_schema!(%{from: %{source: {_source, schema}}}) when schema != nil, do: schema defp assert_schema!(query) do raise Ecto.QueryError, query: query, message: "expected a from expression with a schema" end defp assert_structs!([head | _] = structs) when is_list(structs) do unless Enum.all?(structs, &schema?/1) do raise ArgumentError, "expected a struct or a list of structs, received #{inspect(structs)}" end unless Enum.all?(structs, &(&1.__struct__ == head.__struct__)) do raise ArgumentError, "expected an homogenous list, received different struct types" end :ok end defp schema?(%{__meta__: _}), do: true defp schema?(_), do: false defp get_pk!(struct, pk) do struct |> Map.fetch!(pk) |> case do nil -> raise ArgumentError, "Ecto.Repo.reload/2 expects existent structs, found a `nil` primary key" key -> key end end end
29.412698
144
0.619896
03a07fc45554abd53a715e011ae651ca3a884bfd
2,949
exs
Elixir
mix.exs
df1228/elixir-boilerplate
dcd0282aa4a9a0e604e3d2b7ae1dc209f16fb02b
[ "BSD-3-Clause" ]
null
null
null
mix.exs
df1228/elixir-boilerplate
dcd0282aa4a9a0e604e3d2b7ae1dc209f16fb02b
[ "BSD-3-Clause" ]
null
null
null
mix.exs
df1228/elixir-boilerplate
dcd0282aa4a9a0e604e3d2b7ae1dc209f16fb02b
[ "BSD-3-Clause" ]
null
null
null
defmodule ElixirBoilerplate.Mixfile do use Mix.Project def project do [ app: :elixir_boilerplate, version: "0.0.1", elixir: "~> 1.12", erlang: "~> 24.1", elixirc_paths: elixirc_paths(Mix.env()), test_paths: ["test"], test_pattern: "**/*_test.exs", test_coverage: [tool: ExCoveralls], preferred_cli_env: [coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test], compilers: [:gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps(), releases: releases() ] end def application do [ mod: {ElixirBoilerplate.Application, []}, extra_applications: [:logger, :runtime_tools] ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp aliases do [ "assets.deploy": [ "esbuild default --minify", "phx.digest" ], "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end defp deps do [ # Assets bundling {:esbuild, "~> 0.4", runtime: Mix.env() == :dev}, # HTTP Client {:hackney, "~> 1.18"}, # HTTP server {:plug_cowboy, "~> 2.5"}, {:plug_canonical_host, "~> 2.0"}, {:corsica, "~> 1.1"}, # Phoenix {:phoenix, "~> 1.6"}, {:phoenix_html, "~> 3.2"}, {:phoenix_ecto, "~> 4.4"}, {:phoenix_live_reload, "~> 1.3", only: :dev}, {:jason, "~> 1.2"}, # GraphQL {:absinthe, "~> 1.7"}, {:absinthe_plug, "~> 1.5.8"}, {:dataloader, "~> 1.0"}, {:absinthe_error_payload, "~> 1.1"}, # Database {:ecto_sql, "~> 3.7"}, {:postgrex, "~> 0.16"}, # Translations {:gettext, "~> 0.19"}, # Errors {:sentry, "~> 8.0"}, # Monitoring {:new_relic_agent, "~> 1.27"}, {:new_relic_absinthe, "~> 0.0"}, # Linting {:credo, "~> 1.6", only: [:dev, :test], override: true}, {:credo_envvar, "~> 0.1", only: [:dev, :test], runtime: false}, {:credo_naming, "~> 1.0", only: [:dev, :test], runtime: false}, # Security check {:sobelow, "~> 0.11", only: [:dev, :test], runtime: true}, {:mix_audit, "~> 1.0", only: [:dev, :test], runtime: false}, # Health {:plug_checkup, "~> 0.6"}, # Test factories {:ex_machina, "~> 2.7", only: :test}, {:faker, "~> 0.17", only: :test}, # Test coverage {:excoveralls, "~> 0.14", only: :test} ] end defp releases do [ elixir_boilerplate: [ version: {:from_app, :elixir_boilerplate}, applications: [elixir_boilerplate: :permanent], include_executables_for: [:unix], steps: [:assemble, :tar] ] ] end end
25.205128
121
0.517124
03a0e2f067af6ba3119ee145f2100e64bca25087
1,507
ex
Elixir
lib/rfx/util/source.ex
doorgan/rfx
566b8623ce8957632329b4b0a142ea26a46f2301
[ "MIT" ]
null
null
null
lib/rfx/util/source.ex
doorgan/rfx
566b8623ce8957632329b4b0a142ea26a46f2301
[ "MIT" ]
null
null
null
lib/rfx/util/source.ex
doorgan/rfx
566b8623ce8957632329b4b0a142ea26a46f2301
[ "MIT" ]
null
null
null
defmodule Rfx.Util.Source do @moduledoc """ A utility module for source code manipulation. """ alias Rfx.Util.Str @base_diff "/tmp/rfx_base_diff" @doc """ Returns updated text, edited according to the Sourceror edit function. """ def edit(code, efun) do code |> Sourceror.parse_string() |> Sourceror.postwalk(efun) |> Sourceror.to_string() end @doc """ Returns diff text, given two source texts. """ def diff(old_source, new_source), do: diff({old_source, new_source}) def diff({src1, src2}) do rand = Str.rand_str() path1 = @base_diff <> "/src1_" <> rand path2 = @base_diff <> "/src2_" <> rand File.mkdir(@base_diff) File.write(path1, src1 |> terminate_nl()) File.write(path2, src2 |> terminate_nl()) {diff, _} = System.cmd("diff", [path1, path2]) File.rm(path1) File.rm(path2) diff end @doc """ Returns modified source, given old source text, and a diff text. """ def patch(source, diff) do ext = Str.rand_str() spath = @base_diff <> "/patch_src_" <> ext dpath = @base_diff <> "/patch_dif_" <> ext File.mkdir(@base_diff) File.write(spath, source) File.write(dpath, diff |> terminate_nl()) opts = [spath, dpath, "-s", "-o", "-"] {new_src, _} = System.cmd("patch", opts) File.rm(spath) File.rm(dpath) new_src end defp terminate_nl(string) do case Regex.match?(~r/\n$/, string) do true -> string false -> string <> "\n" end end end
23.184615
72
0.613139
03a10a2ecffe538e561ae31e5ff9af1dd42be5b7
3,071
ex
Elixir
lib/asterix.ex
chribben/asterix
92d30b7489df9209168f3991b8d5ead500054cb6
[ "MIT" ]
1
2015-02-20T19:25:29.000Z
2015-02-20T19:25:29.000Z
lib/asterix.ex
chribben/asterix
92d30b7489df9209168f3991b8d5ead500054cb6
[ "MIT" ]
null
null
null
lib/asterix.ex
chribben/asterix
92d30b7489df9209168f3991b8d5ead500054cb6
[ "MIT" ]
null
null
null
defmodule Asterix do alias Asterix.Protocol.Request alias Asterix.Protocol.Response alias Asterix.Protocol.MetadataRequest alias Asterix.Protocol.MetadataResponse alias Asterix.Protocol.Encodeable alias Asterix.Protocol.Decodeable alias Asterix.Protocol.Decoder alias Asterix.Protocol.ProduceRequest alias Asterix.Protocol.ProduceRequest.TopicPartition alias Asterix.Protocol.ProduceRequest.PartitionMessageSet alias Asterix.Protocol.MessageSetEntry alias Asterix.Protocol.Message @default_timeout 2000 def connect(host, port) do :gen_tcp.connect host, port, [:binary, active: false] end defp encode_and_send_request(client, req) do data = Encodeable.encode req :gen_tcp.send client, data end defp get_response(client) do # First 4 bytes is the response size case :gen_tcp.recv client, 4, @default_timeout do {:ok, data} -> {size, _} = Decoder.int32(data) :gen_tcp.recv client, size, @default_timeout e -> e end end defp get_response_and_decode(client, res) do case get_response client do {:ok, data} -> {res, _} = Decodeable.decode res, data {:ok, res} e -> e end end defp send_request_and_get_response(client, req, res) do case encode_and_send_request client, req do :ok -> get_response_and_decode client, res e -> e end end def get_metadata(client, topics) do req = %Request{message: %MetadataRequest{topics: topics}, correlation_id: 1} res = %Response{message: %MetadataResponse{}} case send_request_and_get_response client, req, res do {:ok, metadata} -> IO.puts "Result" IO.inspect metadata :ok e -> e end end def produce(client, topic) do message = %Message { value: "something else entirely" } message_set = [ %MessageSetEntry { offset: 0, message: message } ] partition_message_sets = [ %PartitionMessageSet { partition: 0, message_set: message_set } ] topic_partitions = [ %TopicPartition { topic_name: topic, partition_message_sets: partition_message_sets } ] produce_request = %ProduceRequest { timeout: 100, topic_partitions: topic_partitions } req = %Request { message: produce_request } case encode_and_send_request(client, req) do :ok -> IO.inspect(get_response client) IO.puts("Sent!") :ok e -> e end end def main do main :localhost, 9092, :metadata end def main(host, port, action) do case connect host, port do {:ok, client} -> result = case action do :metadata -> get_metadata client, ["test"] :produce -> produce client, "test" end case result do {:error, e} -> IO.puts :stderr, e _ -> IO.puts "Exiting..." end {:error, e} -> IO.puts :stderr, "Failed to connect to Kafka: #{e}" end end end
24.766129
61
0.629437
03a12dd5a85e0c789632052a400244cd344439b8
5,030
ex
Elixir
lib/riak/object.ex
MikaAK/riak-elixir-client
c58700ec30a451a46b226a09387144becc47d5ae
[ "Apache-2.0" ]
193
2015-01-04T15:36:15.000Z
2022-03-17T21:31:57.000Z
lib/riak/object.ex
MikaAK/riak-elixir-client
c58700ec30a451a46b226a09387144becc47d5ae
[ "Apache-2.0" ]
51
2015-02-12T02:32:23.000Z
2020-09-22T11:10:56.000Z
lib/riak/object.ex
MikaAK/riak-elixir-client
c58700ec30a451a46b226a09387144becc47d5ae
[ "Apache-2.0" ]
54
2015-03-05T01:10:33.000Z
2021-09-27T10:40:26.000Z
defmodule Riak.Object do @moduledoc """ The Data wrapper makes it convenient to work with Riak data in Elixir """ @doc """ Struct representing a Riak Object. Attributes: * `type`: String; Bucket Type with a unique name within the cluster namespace * `bucket`: String; Bucket with a unique name within the bucket type namespace * `key`: String; Not required; Key with a unique name within the bucket namespace * `data`: Any; Value to be stored under the key * `metadata`: Orddict; User specified metadata * `vclock`: String; Dotted Version Vector / Causal Context for object * `content_type`: String; Content Type for object """ defstruct [bucket: nil, type: nil, key: nil, data: nil, metadata: nil, vclock: nil, content_type: "application/json"] @doc """ Get all metadata entries """ def get_metadata(obj, key) do case :riakc_obj.get_user_metadata_entry( to_undefined(obj.metadata), to_undefined(key)) do :notfound -> nil val -> val end end def get_all_metadata(obj) do :riakc_obj.get_user_metadata_entries( to_undefined(obj.metadata)) end def delete_metadata(obj, key) do %{obj | metadata: :riakc_obj.delete_user_metadata_entry( to_undefined(obj.metadata), to_undefined(key))} end def delete_all_metadata(obj) do %{obj | metadata: :riakc_obj.clear_user_metadata_entries( to_undefined(obj.metadata))} end def put_metadata(obj, {key, value}) do %{obj | metadata: :riakc_obj.set_user_metadata_entry( to_undefined(obj.metadata), {key, value})} end # Secondary Index def index_id({:binary_index, name}), do: "#{name}_bin" def index_id({:integer_index, name}), do: "#{name}_int" def get_index(obj, {type, name}) do case :riakc_obj.get_secondary_index( to_undefined(obj.metadata), {to_undefined(type), to_undefined(name)}) do :notfound -> nil val -> val end end def get_all_indexes(obj) do :riakc_obj.get_secondary_indexes(to_undefined(obj.metadata)) end def delete_index(obj, {type, name}) do %{obj | metadata: :riakc_obj.delete_secondary_index( to_undefined(obj.metadata), {to_undefined(type), to_undefined(name)})} end def delete_all_indexes(obj) do %{obj | metadata: :riakc_obj.clear_secondary_indexes( to_undefined(obj.metadata))} end def put_index(obj, {type, name}, values) do %{obj | metadata: :riakc_obj.add_secondary_index( to_undefined(obj.metadata), [{{to_undefined(type), to_undefined(name)}, to_undefined(values)}])} end # Links def get_link(obj, tag) do case :riakc_obj.get_links( to_undefined(obj.metadata), tag) do :notfound -> nil val -> val end end def get_all_links(obj) do :riakc_obj.get_all_links( to_undefined(obj.metadata)) end def delete_link(obj, tag) do %{obj | metadata: :riakc_obj.delete_links( to_undefined(obj.metadata), tag)} end def delete_all_links(obj) do %{obj | metadata: :riakc_obj.clear_links( to_undefined(obj.metadata))} end def put_link(obj, tag, bucket, key) do %{obj | metadata: :riakc_obj.add_link( to_undefined(obj.metadata), [{tag, [{to_undefined(bucket),to_undefined(key)}]}])} end def from_robj(robj) do data = try do :riakc_obj.get_update_value(robj) catch :no_value -> nil e -> raise e end %Riak.Object{bucket: to_nil(:riakc_obj.bucket(robj)), type: to_nil(:riakc_obj.bucket_type(robj)), key: to_nil(:riakc_obj.key(robj)), data: to_nil(data), metadata: to_nil(:riakc_obj.get_update_metadata(robj)), vclock: to_nil(:riakc_obj.vclock(robj)), content_type: to_nil(:riakc_obj.get_update_content_type(robj))} end def to_robj(obj) do type = to_undefined(obj.type) bucket = to_bucket(obj.bucket) typed_bucket = case {type, bucket} do {:undefined, b} -> b; {t, {_, b}} -> {t, b}; {t, b} -> {t, b}; end robj = :riakc_obj.new( typed_bucket, to_undefined(obj.key), to_undefined(obj.data), to_undefined(obj.content_type)) robj = case to_undefined(obj.vclock) do :undefined -> robj; v -> :riakc_obj.set_vclock(robj, v) end robj = case to_undefined(obj.metadata) do :undefined -> robj; m -> :riakc_obj.update_metadata(robj, m) end robj end def create(args \\ [bucket: "default"]) do obj = struct(Riak.Object, args) from_robj(to_robj(obj)) end defp to_undefined(nil) do :undefined end defp to_undefined(v) do v end defp to_nil(:undefined) do nil end defp to_nil(v) do v end defp to_bucket({nil, b}) do to_undefined(b) end defp to_bucket({:undefined, b}) do to_undefined(b) end defp to_bucket(b) do to_undefined(b) end end
26.613757
119
0.636978
03a132b1d49896e4e5256c9a285add57ff9dc068
419
exs
Elixir
test/support/test_client.exs
mbta/sentry-elixir
ce417a69efec0eeb968a3c8fdcd61d3115c69875
[ "MIT" ]
null
null
null
test/support/test_client.exs
mbta/sentry-elixir
ce417a69efec0eeb968a3c8fdcd61d3115c69875
[ "MIT" ]
null
null
null
test/support/test_client.exs
mbta/sentry-elixir
ce417a69efec0eeb968a3c8fdcd61d3115c69875
[ "MIT" ]
null
null
null
defmodule Sentry.TestClient do @behaviour Sentry.HTTPClient def send_event(%Sentry.Event{} = event, _opts \\ []) do {endpoint, _public_key, _secret_key} = Sentry.Client.get_dsn! event = Sentry.Client.maybe_call_before_send_event(event) case Poison.encode(event) do {:ok, body} -> Sentry.Client.request(:post, endpoint, [], body) {:error, _error} -> :error end end end
27.933333
65
0.658711
03a153253f21c677b1d6e88c0c4daf3cffa70f75
11,300
exs
Elixir
test/extensions/persistent_session/plug/cookie_test.exs
jordelver/pow
60235189155c87efbb40238ce5008340d470e995
[ "MIT" ]
null
null
null
test/extensions/persistent_session/plug/cookie_test.exs
jordelver/pow
60235189155c87efbb40238ce5008340d470e995
[ "MIT" ]
null
null
null
test/extensions/persistent_session/plug/cookie_test.exs
jordelver/pow
60235189155c87efbb40238ce5008340d470e995
[ "MIT" ]
null
null
null
defmodule PowPersistentSession.Plug.CookieTest do use ExUnit.Case doctest PowPersistentSession.Plug.Cookie alias Plug.Conn alias Pow.{Plug, Plug.Session} alias Pow.Test.ConnHelpers alias PowPersistentSession.{Plug.Cookie, Store.PersistentSessionCache} alias PowPersistentSession.Test.Users.User @cookie_key "persistent_session" @max_age Integer.floor_div(:timer.hours(24) * 30, 1000) @custom_cookie_opts [domain: "domain.com", max_age: 1, path: "/path", http_only: false, secure: true, extra: "SameSite=Lax"] setup do config = PowPersistentSession.Test.pow_config() ets = Pow.Config.get(config, :cache_store_backend, nil) ets.init() conn = :get |> ConnHelpers.conn("/") |> ConnHelpers.init_session() |> Session.call(config) {:ok, %{conn: conn, config: config, ets: ets}} end test "call/2 sets pow_persistent_session plug in conn", %{conn: conn, config: config} do conn = run_plug(conn) expected_config = [mod: Session, plug: Session] ++ config assert {Cookie, ^expected_config} = conn.private[:pow_persistent_session] refute conn.resp_cookies[@cookie_key] end test "call/2 assigns user from cookie", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" conn = conn |> store_persistent(ets, id, {[id: user.id], []}) |> run_plug() assert Plug.current_user(conn) == user assert %{value: new_id, max_age: @max_age, path: "/"} = conn.resp_cookies[@cookie_key] refute new_id == id assert PersistentSessionCache.get([backend: ets], id) == :not_found assert PersistentSessionCache.get([backend: ets], new_id) == {[id: 1], []} end test "call/2 assigns user from cookie and doesn't expire with simultanous request", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" conn = store_persistent(conn, ets, id, {[id: user.id], []}) first_conn = run_plug(conn) assert Plug.current_user(first_conn) == user assert %{value: _id, max_age: @max_age, path: "/"} = first_conn.resp_cookies[@cookie_key] second_conn = run_plug(conn) refute Plug.current_user(second_conn) == user refute second_conn.resp_cookies[@cookie_key] end test "call/2 assigns user from cookie passing fingerprint to the session metadata", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" conn = conn |> store_persistent(ets, id, {[id: user.id], session_metadata: [fingerprint: "fingerprint"]}) |> run_plug() assert Plug.current_user(conn) == user assert %{value: new_id, max_age: @max_age, path: "/"} = conn.resp_cookies[@cookie_key] refute new_id == id assert PersistentSessionCache.get([backend: ets], id) == :not_found assert PersistentSessionCache.get([backend: ets], new_id) == {[id: 1], session_metadata: [fingerprint: "fingerprint"]} assert conn.private[:pow_session_metadata][:fingerprint] == "fingerprint" end test "call/2 assigns user from cookie passing custom metadata to session metadata", %{conn: conn, ets: ets} do user = %User{id: 1} conn = conn |> store_persistent(ets, "test", {[id: user.id], session_metadata: [a: 1, b: 2, fingerprint: "fingerprint"]}) |> Conn.put_private(:pow_persistent_session_metadata, session_metadata: [a: 2]) |> Conn.put_private(:pow_session_metadata, [a: 3, fingerprint: "new_fingerprint"]) |> run_plug() assert Plug.current_user(conn) == user assert %{value: id, max_age: @max_age, path: "/"} = conn.resp_cookies[@cookie_key] assert PersistentSessionCache.get([backend: ets], id) == {[id: 1], session_metadata: [fingerprint: "new_fingerprint", b: 2, a: 2]} assert [inserted_at: _, b: 2, a: 3, fingerprint: "new_fingerprint"] = conn.private[:pow_session_metadata] end test "call/2 assigns user from cookie with prepended `:otp_app`", %{config: config, ets: ets} do user = %User{id: 1} conn = :get |> ConnHelpers.conn("/") |> ConnHelpers.init_session() |> Session.call(config ++ [otp_app: :test_app]) |> store_persistent(ets, "test_app_test", {[id: user.id], []}, "test_app_" <> @cookie_key) |> run_plug(config) assert Plug.current_user(conn) == user assert %{value: new_id, max_age: @max_age, path: "/"} = conn.resp_cookies["test_app_" <> @cookie_key] assert String.starts_with?(new_id, "test_app") assert PersistentSessionCache.get([backend: ets], new_id) == {[id: 1], []} end test "call/2 when user already assigned", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" conn = conn |> store_persistent(ets, id, {[id: user.id], []}) |> Plug.assign_current_user(:user, []) |> run_plug() refute conn.resp_cookies[@cookie_key] assert PersistentSessionCache.get([backend: ets], id) == {[id: 1], []} end test "call/2 when user doesn't exist in database", %{conn: conn, ets: ets} do user = %User{id: -1} id = "test" conn = conn |> store_persistent(ets, id, {[id: user.id], []}) |> run_plug() refute Plug.current_user(conn) refute conn.resp_cookies[@cookie_key] assert PersistentSessionCache.get([backend: ets], id) == :not_found end test "call/2 when persistent session cache doesn't have credentials", %{conn: conn} do conn = conn |> persistent_cookie(@cookie_key, "test") |> run_plug() refute Plug.current_user(conn) refute conn.resp_cookies[@cookie_key] end test "call/2 with invalid stored clauses", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" assert_raise RuntimeError, "Invalid get_by clauses stored: [id: 1, uid: 2]", fn -> conn |> store_persistent(ets, id, {[id: user.id, uid: 2], []}) |> run_plug() end end # TODO: Remove by 1.1.0 test "call/2 is backwards-compatible with just user fetch clause", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" conn = conn |> store_persistent(ets, id, id: user.id) |> run_plug() assert Plug.current_user(conn) == user assert %{value: new_id, max_age: @max_age, path: "/"} = conn.resp_cookies[@cookie_key] refute new_id == id assert PersistentSessionCache.get([backend: ets], id) == :not_found assert PersistentSessionCache.get([backend: ets], new_id) == {[id: 1], []} end # TODO: Remove by 1.1.0 test "call/2 is backwards-compatible with `:session_fingerprint` metadata", %{conn: conn, ets: ets} do user = %User{id: 1} id = "test" conn = conn |> store_persistent(ets, id, {[id: user.id], session_fingerprint: "fingerprint"}) |> run_plug() assert Plug.current_user(conn) == user assert %{value: new_id, max_age: @max_age, path: "/"} = conn.resp_cookies[@cookie_key] refute new_id == id assert PersistentSessionCache.get([backend: ets], id) == :not_found assert PersistentSessionCache.get([backend: ets], new_id) == {[id: 1], session_metadata: [fingerprint: "fingerprint"]} assert conn.private[:pow_session_metadata][:fingerprint] == "fingerprint" end test "create/3 with custom TTL", %{conn: conn, config: config} do config = Keyword.put(config, :persistent_session_ttl, 1000) conn = conn |> init_plug(config) |> run_create(%User{id: 1}, config) assert_received {:ets, :put, [{_key, _value} | _rest], config} assert config[:ttl] == 1000 assert %{max_age: 1, path: "/"} = conn.resp_cookies[@cookie_key] end test "create/3 handles clause error", %{conn: conn, config: config} do assert_raise RuntimeError, "Primary key value for key `:id` in #{inspect User} can't be `nil`", fn -> conn |> init_plug(config) |> run_create(%User{id: nil}, config) end end test "create/3 with custom cookie options", %{conn: conn, config: config} do config = Keyword.put(config, :persistent_session_cookie_opts, @custom_cookie_opts) conn = conn |> init_plug(config) |> run_create(%User{id: 1}, config) assert %{ domain: "domain.com", extra: "SameSite=Lax", http_only: false, max_age: 1, path: "/path", secure: true } = conn.resp_cookies[@cookie_key] end test "create/3 deletes previous persistent session", %{conn: conn, config: config, ets: ets} do conn = store_persistent(conn, ets, "previous_persistent_session", {[id: 1], []}) assert PersistentSessionCache.get([backend: ets], "previous_persistent_session") == {[id: 1], []} conn |> init_plug(config) |> run_create(%User{id: 1}, config) assert_received {:ets, :put, [{_key, {[id: 1], []}}], _config} assert PersistentSessionCache.get([backend: ets], "previous_persistent_session") == :not_found end test "create/3 with `[:pow_session_metadata][:fingerprint]` defined in conn.private", %{conn: conn, config: config} do conn |> Conn.put_private(:pow_session_metadata, fingerprint: "fingerprint") |> init_plug(config) |> run_create(%User{id: 1}, config) assert_received {:ets, :put, [{_key, {[id: 1], session_metadata: [fingerprint: "fingerprint"]}}], _config} end test "create/3 with custom metadata", %{conn: conn, config: config} do conn |> Conn.put_private(:pow_persistent_session_metadata, session_metadata: [a: 1]) |> init_plug(config) |> run_create(%User{id: 1}, config) assert_received {:ets, :put, [{_key, {[id: 1], session_metadata: [a: 1]}}], _config} end test "delete/3", %{conn: conn, ets: ets, config: config} do id = "test" conn = conn |> store_persistent(ets, id, {[id: 1], []}) |> init_plug(config) |> run_delete(config) assert conn.resp_cookies[@cookie_key] == %{max_age: 0, path: "/", universal_time: {{1970, 1, 1}, {0, 0, 0}}} assert PersistentSessionCache.get([backend: ets], id) == :not_found end test "delete/3 with custom cookie options", %{conn: conn, ets: ets, config: config} do id = "test" config = Keyword.put(config, :persistent_session_cookie_opts, @custom_cookie_opts) conn = conn |> store_persistent(ets, id, {[id: 1], []}) |> init_plug(config) |> run_delete(config) assert conn.resp_cookies[@cookie_key] == %{max_age: 0, universal_time: {{1970, 1, 1}, {0, 0, 0}}, path: "/path", domain: "domain.com", extra: "SameSite=Lax", http_only: false, secure: true} assert PersistentSessionCache.get([backend: ets], id) == :not_found end defp store_persistent(conn, ets, id, value, cookie_key \\ @cookie_key) do PersistentSessionCache.put([backend: ets], id, value) persistent_cookie(conn, cookie_key, id) end defp persistent_cookie(conn, cookie_key, id) do cookies = Map.new([{cookie_key, id}]) %{conn | req_cookies: cookies, cookies: cookies} end defp run_plug(conn, config \\ []) do conn |> init_plug(config) |> Conn.send_resp(200, "") end defp init_plug(conn, config) do Cookie.call(conn, Cookie.init(config)) end defp run_create(conn, user, config) do conn |> Cookie.create(user, config) |> Conn.send_resp(200, "") end defp run_delete(conn, config) do conn |> Cookie.delete(config) |> Conn.send_resp(200, "") end end
35.093168
193
0.643628
03a1546a2acc00347e00db47f81a8a249ab738e9
629
ex
Elixir
Microsoft.Azure.Management.Preview.Containers/lib/microsoft/azure/management/preview/containers/model/docker_build_step.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Preview.Containers/lib/microsoft/azure/management/preview/containers/model/docker_build_step.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Preview.Containers/lib/microsoft/azure/management/preview/containers/model/docker_build_step.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# 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 Microsoft.Azure.Management.Preview.Containers.Model.DockerBuildStep do @moduledoc """ The Docker build step. """ @derive [Poison.Encoder] defstruct [ :"provisioningState", :"type" ] @type t :: %__MODULE__{ :"provisioningState" => String.t, :"type" => String.t } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Preview.Containers.Model.DockerBuildStep do def decode(value, _options) do value end end
22.464286
99
0.712242
03a1e39076c2e8d7078a0163f606d3a8aaabb3e3
7,146
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/proposal.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/proposal.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/proposal.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.Proposal do @moduledoc """ Note: this resource requires whitelisting for access. Please contact your account manager for access to Marketplace resources. Represents a proposal in the Marketplace. A proposal is the unit of negotiation between a seller and a buyer and contains deals which are served. Note: you can not update, create, or otherwise modify Private Auction or Preferred Deals deals through the API. Fields are updatable unless noted otherwise. ## Attributes * `billedBuyer` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.Buyer.t`, *default:* `nil`) - Output only. Reference to the buyer that will get billed for this proposal. * `buyer` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.Buyer.t`, *default:* `nil`) - Reference to the buyer on the proposal. Note: This field may be set only when creating the resource. Modifying this field while updating the resource will result in an error. * `buyerContacts` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.ContactInformation.t)`, *default:* `nil`) - Contact information for the buyer. * `buyerPrivateData` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.PrivateData.t`, *default:* `nil`) - Private data for buyer. (hidden from seller). * `deals` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.Deal.t)`, *default:* `nil`) - The deals associated with this proposal. For Private Auction proposals (whose deals have NonGuaranteedAuctionTerms), there will only be one deal. * `displayName` (*type:* `String.t`, *default:* `nil`) - The name for the proposal. * `isRenegotiating` (*type:* `boolean()`, *default:* `nil`) - Output only. True if the proposal is being renegotiated. * `isSetupComplete` (*type:* `boolean()`, *default:* `nil`) - Output only. True, if the buyside inventory setup is complete for this proposal. * `lastUpdaterOrCommentorRole` (*type:* `String.t`, *default:* `nil`) - Output only. The role of the last user that either updated the proposal or left a comment. * `notes` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.Note.t)`, *default:* `nil`) - Output only. The notes associated with this proposal. * `originatorRole` (*type:* `String.t`, *default:* `nil`) - Output only. Indicates whether the buyer/seller created the proposal. * `privateAuctionId` (*type:* `String.t`, *default:* `nil`) - Output only. Private auction ID if this proposal is a private auction proposal. * `proposalId` (*type:* `String.t`, *default:* `nil`) - Output only. The unique ID of the proposal. * `proposalRevision` (*type:* `String.t`, *default:* `nil`) - Output only. The revision number for the proposal. Each update to the proposal or the deal causes the proposal revision number to auto-increment. The buyer keeps track of the last revision number they know of and pass it in when making an update. If the head revision number on the server has since incremented, then an ABORTED error is returned during the update operation to let the buyer know that a subsequent update was made. * `proposalState` (*type:* `String.t`, *default:* `nil`) - Output only. The current state of the proposal. * `seller` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.Seller.t`, *default:* `nil`) - Reference to the seller on the proposal. Note: This field may be set only when creating the resource. Modifying this field while updating the resource will result in an error. * `sellerContacts` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.ContactInformation.t)`, *default:* `nil`) - Output only. Contact information for the seller. * `termsAndConditions` (*type:* `String.t`, *default:* `nil`) - Output only. The terms and conditions set by the publisher for this proposal. * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time when the proposal was last revised. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :billedBuyer => GoogleApi.AdExchangeBuyer.V2beta1.Model.Buyer.t(), :buyer => GoogleApi.AdExchangeBuyer.V2beta1.Model.Buyer.t(), :buyerContacts => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.ContactInformation.t()), :buyerPrivateData => GoogleApi.AdExchangeBuyer.V2beta1.Model.PrivateData.t(), :deals => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.Deal.t()), :displayName => String.t(), :isRenegotiating => boolean(), :isSetupComplete => boolean(), :lastUpdaterOrCommentorRole => String.t(), :notes => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.Note.t()), :originatorRole => String.t(), :privateAuctionId => String.t(), :proposalId => String.t(), :proposalRevision => String.t(), :proposalState => String.t(), :seller => GoogleApi.AdExchangeBuyer.V2beta1.Model.Seller.t(), :sellerContacts => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.ContactInformation.t()), :termsAndConditions => String.t(), :updateTime => DateTime.t() } field(:billedBuyer, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.Buyer) field(:buyer, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.Buyer) field(:buyerContacts, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.ContactInformation, type: :list ) field(:buyerPrivateData, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.PrivateData) field(:deals, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.Deal, type: :list) field(:displayName) field(:isRenegotiating) field(:isSetupComplete) field(:lastUpdaterOrCommentorRole) field(:notes, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.Note, type: :list) field(:originatorRole) field(:privateAuctionId) field(:proposalId) field(:proposalRevision) field(:proposalState) field(:seller, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.Seller) field(:sellerContacts, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.ContactInformation, type: :list ) field(:termsAndConditions) field(:updateTime, as: DateTime) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.Proposal do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.Proposal.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.Proposal do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
64.378378
496
0.724461
03a1ef6e7e84656d68db7385ca2a14f32028edc1
655
exs
Elixir
test/charge_test.exs
NarrativeApp/stripe-elixir
873c79cf4f6cc5db974b11fbd4e4f85c8a0a9004
[ "MIT" ]
null
null
null
test/charge_test.exs
NarrativeApp/stripe-elixir
873c79cf4f6cc5db974b11fbd4e4f85c8a0a9004
[ "MIT" ]
24
2020-09-08T20:24:59.000Z
2021-09-22T04:04:17.000Z
test/charge_test.exs
NarrativeApp/stripe-elixir
873c79cf4f6cc5db974b11fbd4e4f85c8a0a9004
[ "MIT" ]
null
null
null
defmodule Stripe.ChargeTest do use ExUnit.Case, async: true alias Stripe.Charge alias Stripe.InvalidRequestError @tag skip: "currently failing" test "create a charge" do assert {:error, %InvalidRequestError{message: "Must provide source or customer."}} = Charge.create([]) end @tag skip: "currently failing" test "retrieve a charge" do assert {:error, %InvalidRequestError{message: "No such charge: not exist"}} = Charge.retrieve("not exist") end @tag skip: "currently failing" test "list all charges" do assert {:ok, %{"object" => "list", "url" => "/v1/charges"}} = Charge.list() end end
27.291667
88
0.659542
03a1f1ef6c11b954b4de6f9dc5818d4c035367c0
21,628
ex
Elixir
lib/cldr/interval/date_time.ex
kipcole9/cldr_dates_times
c5d495ac8bd4cdd8a279a517ed24c243c9c2e4a3
[ "Apache-2.0" ]
9
2017-10-07T00:01:18.000Z
2019-01-12T17:20:09.000Z
lib/cldr/interval/date_time.ex
kipcole9/cldr_dates_times
c5d495ac8bd4cdd8a279a517ed24c243c9c2e4a3
[ "Apache-2.0" ]
8
2017-10-05T20:00:52.000Z
2019-02-12T00:22:11.000Z
lib/cldr/interval/date_time.ex
kipcole9/cldr_dates_times
c5d495ac8bd4cdd8a279a517ed24c243c9c2e4a3
[ "Apache-2.0" ]
3
2017-10-05T11:35:34.000Z
2018-12-28T16:31:35.000Z
defmodule Cldr.DateTime.Interval do @moduledoc """ Interval formats allow for software to format intervals like "Jan 10-12, 2008" as a shorter and more natural format than "Jan 10, 2008 - Jan 12, 2008". They are designed to take a start and end date, time or datetime plus a formatting pattern and use that information to produce a localized format. See `Cldr.Interval.to_string/3` and `Cldr.DateTime.Interval.to_string/3` """ import Cldr.Calendar, only: [ naivedatetime: 0 ] @default_format :medium @formats [:short, :medium, :long] if Cldr.Code.ensure_compiled?(CalendarInterval) do @doc false def to_string(%CalendarInterval{} = interval) do {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(interval, backend, locale: locale) end end if Cldr.Code.ensure_compiled?(CalendarInterval) do @doc false def to_string(%CalendarInterval{} = interval, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(interval, backend, locale: locale) end @doc false def to_string(%CalendarInterval{} = interval, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) to_string(interval, backend, locale: locale) end @doc """ Returns a localised string representing the formatted `CalendarInterval`. ## Arguments * `range` is a `CalendarInterval.t` * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representing of an interval format. The default is `:medium`. * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0` * `number_system:` a number system into which the formatted date digits should be transliterated ## Returns * `{:ok, string}` or * `{:error, {exception, reason}}` ## Notes * `CalendarInterval` support requires adding the dependency [calendar_interval](https://hex.pm/packages/calendar_interval) to the `deps` configuration in `mix.exs`. * For more information on interval format string see the `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single datetime is formatted instead of an interval ## Examples iex> Cldr.DateTime.Interval.to_string ~I"2020-01-01 10:00/12:00", MyApp.Cldr {:ok, "Jan 1, 2020, 10:00:00 AM – 12:00:00 PM"} """ @spec to_string(CalendarInterval.t(), Cldr.backend(), Keyword.t()) :: {:ok, String.t()} | {:error, {module, String.t()}} def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:year, :month, :day] do Cldr.Date.Interval.to_string(from, to, backend, options) end def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:hour, :minute] do from = %{from | second: 0, microsecond: {0, 6}} to = %{to | second: 0, microsecond: {0, 6}} to_string(from, to, backend, options) end def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:hour, :minute] do from = %{from | microsecond: {0, 6}} to = %{to | microsecond: {0, 6}} to_string(from, to, backend, options) end end @doc false def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to) do {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(from, to, backend, locale: locale) end def to_string(nil = from, unquote(naivedatetime()) = to) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(from, to, backend, locale: locale) end def to_string(unquote(naivedatetime()) = from, nil = to) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(from, to, backend, locale: locale) end @doc false def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(from, to, backend, locale: locale) end def to_string(nil = from, unquote(naivedatetime()) = to, backend) when is_atom(backend) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(from, to, backend, locale: locale) end def to_string(unquote(naivedatetime()) = from, nil = to, backend) when is_atom(backend) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(from, to, backend, locale: locale) end @doc false def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) to_string(from, to, backend, locale: locale) end def to_string(nil = from, unquote(naivedatetime()) = to, options) when is_list(options) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(options) to_string(from, to, backend, locale: locale) end def to_string(unquote(naivedatetime()) = from, nil = to, options) when is_list(options) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(options) to_string(from, to, backend, locale: locale) end @doc """ Returns a localised string representing the formatted interval formed by two dates. ## Arguments * `from` is any map that conforms to the `Calendar.datetime` type. * `to` is any map that conforms to the `Calendar.datetime` type. `to` must occur on or after `from`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module * `options` is a keyword list of options. The default is `[]`. Either of `from` or `to` may also be `nil` in which case the result is an "open" interval and the non-nil parameter is formatted using `Cldr.DateTime.to_string/3`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representation of an interval format. The default is `:medium`. * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0` * `number_system:` a number system into which the formatted date digits should be transliterated ## Returns * `{:ok, string}` or * `{:error, {exception, reason}}` ## Notes * For more information on interval format string see the `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date is formatted instead of an interval ## Examples iex> Cldr.DateTime.Interval.to_string ~U[2020-01-01 00:00:00.0Z], ...> ~U[2020-12-31 10:00:00.0Z], MyApp.Cldr {:ok, "Jan 1, 2020, 12:00:00 AM – Dec 31, 2020, 10:00:00 AM"} iex> Cldr.DateTime.Interval.to_string ~U[2020-01-01 00:00:00.0Z], nil, MyApp.Cldr {:ok, "Jan 1, 2020, 12:00:00 AM –"} """ @spec to_string(Calendar.datetime() | nil, Calendar.datetime() | nil, Cldr.backend(), Keyword.t()) :: {:ok, String.t()} | {:error, {module, String.t()}} def to_string(from, to, backend, options \\ []) def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, backend, options) when calendar == Calendar.ISO do from = %{from | calendar: Cldr.Calendar.Gregorian} to = %{to | calendar: Cldr.Calendar.Gregorian} to_string(from, to, backend, options) end def to_string(nil = from, unquote(naivedatetime()) = to, backend, options) when calendar == Calendar.ISO do to = %{to | calendar: Cldr.Calendar.Gregorian} to_string(from, to, backend, options) end def to_string(unquote(naivedatetime()) = from, nil = to, backend, options) when calendar == Calendar.ISO do from = %{from | calendar: Cldr.Calendar.Gregorian} to_string(from, to, backend, options) end def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, options, []) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) to_string(from, to, backend, Keyword.put_new(options, :locale, locale)) end def to_string(unquote(naivedatetime()) = from, nil = to, options, []) when is_list(options) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(options) to_string(from, to, backend, Keyword.put_new(options, :locale, locale)) end def to_string(nil = from, unquote(naivedatetime()) = to, options, []) when is_list(options) do _ = calendar {locale, backend} = Cldr.locale_and_backend_from(options) to_string(from, to, backend, Keyword.put_new(options, :locale, locale)) end def to_string(unquote(naivedatetime()) = from, unquote(naivedatetime()) = to, backend, options) do {locale, backend} = Cldr.locale_and_backend_from(options[:locale], backend) format = Keyword.get(options, :format, @default_format) locale_number_system = Cldr.Number.System.number_system_from_locale(locale, backend) number_system = Keyword.get(options, :number_system, locale_number_system) options = options |> Keyword.put(:locale, locale) |> Keyword.put(:nunber_system, number_system) with {:ok, _} <- from_less_than_or_equal_to(from, to), {:ok, backend} <- Cldr.validate_backend(backend), {:ok, locale} <- Cldr.validate_locale(locale, backend), {:ok, _} <- Cldr.Number.validate_number_system(locale, number_system, backend), {:ok, format} <- validate_format(format), {:ok, calendar} <- Cldr.Calendar.validate_calendar(from.calendar), {:ok, greatest_difference} <- greatest_difference(from, to) do options = adjust_options(options, locale, format) format_date_time(from, to, locale, backend, calendar, greatest_difference, options) else {:error, :no_practical_difference} -> options = adjust_options(options, locale, format) Cldr.DateTime.to_string(from, backend, options) other -> other end end # Open ended intervals use the `date_time_interval_fallback/0` format def to_string(nil, unquote(naivedatetime()) = to, backend, options) do {locale, backend} = Cldr.locale_and_backend_from(options[:locale], backend) cldr_calendar = calendar.cldr_calendar_type with {:ok, formatted} <- Cldr.DateTime.to_string(to, backend, options) do pattern = Module.concat(backend, DateTime.Format).date_time_interval_fallback(locale, cldr_calendar) result = ["", formatted] |> Cldr.Substitution.substitute(pattern) |> Enum.join() |> String.trim_leading() {:ok, result} end end def to_string(unquote(naivedatetime()) = from, nil, backend, options) do {locale, backend} = Cldr.locale_and_backend_from(options[:locale], backend) cldr_calendar = calendar.cldr_calendar_type with {:ok, formatted} <- Cldr.DateTime.to_string(from, backend, options) do pattern = Module.concat(backend, DateTime.Format).date_time_interval_fallback(locale, cldr_calendar) result = [formatted, ""] |> Cldr.Substitution.substitute(pattern) |> Enum.join() |> String.trim_trailing() {:ok, result} end end if Cldr.Code.ensure_compiled?(CalendarInterval) do @doc false def to_string!(%CalendarInterval{} = range, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string!(range, backend, locale: locale) end @doc false def to_string!(%CalendarInterval{} = range, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options[:locale], nil) options = Keyword.put_new(options, :locale, locale) to_string!(range, backend, options) end end if Cldr.Code.ensure_compiled?(CalendarInterval) do @doc """ Returns a localised string representing the formatted interval formed by two dates or raises an exception. ## Arguments * `from` is any map that conforms to the `Calendar.datetime` type. * `to` is any map that conforms to the `Calendar.datetime` type. `to` must occur on or after `from`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module. * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representing of an interval format. The default is `:medium`. * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`. * `number_system:` a number system into which the formatted date digits should be transliterated. ## Returns * `string` or * raises an exception ## Notes * For more information on interval format string see the `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date is formatted instead of an interval ## Examples iex> use CalendarInterval iex> Cldr.DateTime.Interval.to_string! ~I"2020-01-01 00:00/10:00", MyApp.Cldr "Jan 1, 2020, 12:00:00 AM – 10:00:59 AM" """ @spec to_string!(CalendarInterval.t(), Cldr.backend(), Keyword.t()) :: String.t() | no_return def to_string!(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:year, :month, :day] do Cldr.Date.Interval.to_string!(from, to, backend, options) end def to_string!(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:hour, :minute, :second] do to_string!(from, to, backend, options) end end @doc """ Returns a localised string representing the formatted interval formed by two dates or raises an exception. ## Arguments * `from` is any map that conforms to the `Calendar.datetime` type. * `to` is any map that conforms to the `Calendar.datetime` type. `to` must occur on or after `from`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module. * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representation of an interval format. The default is `:medium`. * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`. * `number_system:` a number system into which the formatted date digits should be transliterated. ## Returns * `string` or * raises an exception ## Notes * For more information on interval format string see the `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date is formatted instead of an interval ## Examples iex> Cldr.DateTime.Interval.to_string! ~U[2020-01-01 00:00:00.0Z], ...> ~U[2020-12-31 10:00:00.0Z], MyApp.Cldr "Jan 1, 2020, 12:00:00 AM – Dec 31, 2020, 10:00:00 AM" """ def to_string!(from, to, backend, options \\ []) do case to_string(from, to, backend, options) do {:ok, string} -> string {:error, {exception, reason}} -> raise exception, reason end end @doc """ Returns the format code representing the date or time unit that is the greatest difference between two date/times. ## Arguments * `from` is any `t:DateTime.t/0` or `t:NaiveDateTine.t/0` * `to` is any `t:DateTime.t/0` or `t:NaiveDateTine.t/0` ## Returns * `{:ok, format_code}` where `format_code` is one of * `:y` meaning that the greatest difference is in the year * `:M` meaning that the greatest difference is in the month * `:d` meaning that the greatest difference is in the day * `:H` meaning that the greatest difference is in the hour * `:m` meaning that the greatest difference is in the minute * `{:error, :no_practical_difference}` ## Example iex> Cldr.DateTime.Interval.greatest_difference ~U[2022-04-22 02:00:00.0Z], ~U[2022-04-22 03:00:00.0Z] {:ok, :H} iex> Cldr.DateTime.Interval.greatest_difference ~U[2022-04-22 02:00:00.0Z], ~U[2022-04-22 02:00:01.0Z] {:error, :no_practical_difference} """ def greatest_difference(from, to) do Cldr.Date.Interval.greatest_difference(from, to) end defp from_less_than_or_equal_to(%{time_zone: zone} = from, %{time_zone: zone} = to) do case DateTime.compare(from, to) do comp when comp in [:eq, :lt] -> {:ok, comp} _other -> {:error, Cldr.Date.Interval.datetime_order_error(from, to)} end end defp from_less_than_or_equal_to(%{time_zone: _zone1} = from, %{time_zone: _zone2} = to) do {:error, Cldr.Date.Interval.datetime_incompatible_timezone_error(from, to)} end defp from_less_than_or_equal_to(from, to) do case NaiveDateTime.compare(from, to) do comp when comp in [:eq, :lt] -> {:ok, comp} _other -> {:error, Cldr.Date.Interval.datetime_order_error(from, to)} end end @doc false def adjust_options(options, locale, format) do options |> Keyword.put(:locale, locale) |> Keyword.put(:format, format) |> Keyword.delete(:style) end defp format_date_time(from, to, locale, backend, calendar, difference, options) do backend_format = Module.concat(backend, DateTime.Format) {:ok, calendar} = Cldr.DateTime.type_from_calendar(calendar) fallback = backend_format.date_time_interval_fallback(locale, calendar) format = Keyword.fetch!(options, :format) [from_format, to_format] = extract_format(format) from_options = Keyword.put(options, :format, from_format) to_options = Keyword.put(options, :format, to_format) do_format_date_time(from, to, backend, format, difference, from_options, to_options, fallback) end # The difference is only in the time part defp do_format_date_time(from, to, backend, format, difference, from_opts, to_opts, fallback) when difference in [:H, :m] do with {:ok, from_string} <- Cldr.DateTime.to_string(from, backend, from_opts), {:ok, to_string} <- Cldr.Time.to_string(to, backend, to_opts) do {:ok, combine_result(from_string, to_string, format, fallback)} end end # The difference is in the date part # Format each datetime separately and join with # the interval fallback format defp do_format_date_time(from, to, backend, format, difference, from_opts, to_opts, fallback) when difference in [:y, :M, :d] do with {:ok, from_string} <- Cldr.DateTime.to_string(from, backend, from_opts), {:ok, to_string} <- Cldr.DateTime.to_string(to, backend, to_opts) do {:ok, combine_result(from_string, to_string, format, fallback)} end end defp combine_result(left, right, format, _fallback) when is_list(format) do left <> right end defp combine_result(left, right, format, fallback) when is_atom(format) do [left, right] |> Cldr.Substitution.substitute(fallback) |> Enum.join() end defp extract_format(format) when is_atom(format) do [format, format] end defp extract_format([from_format, to_format]) do [from_format, to_format] end # Using standard format terms like :short, :medium, :long defp validate_format(format) when format in @formats do {:ok, format} end # Direct specification of a format as a string @doc false defp validate_format(format) when is_binary(format) do Cldr.DateTime.Format.split_interval(format) end @doc false def format_error(format) do { Cldr.DateTime.UnresolvedFormat, "The interval format #{inspect(format)} is invalid. " <> "Valid formats are #{inspect(@formats)} or an interval format string.}" } end end
33.583851
108
0.676715
03a1fb0492eae47fb3bb620a6869f4182febe31d
129
exs
Elixir
config/ipv6.exs
thomasvolk/lightbulb
f8d512c62073f814846762093076cf16a1e100be
[ "Apache-2.0" ]
null
null
null
config/ipv6.exs
thomasvolk/lightbulb
f8d512c62073f814846762093076cf16a1e100be
[ "Apache-2.0" ]
null
null
null
config/ipv6.exs
thomasvolk/lightbulb
f8d512c62073f814846762093076cf16a1e100be
[ "Apache-2.0" ]
null
null
null
use Mix.Config config :lightbulb, udp_api: Lightbulb.UdpIpv6, broadcast_address: "ff02::1" config :logger, level: :debug
16.125
31
0.728682
03a200721912f07fcef0faec78a22eab07d6aba2
393
exs
Elixir
test/w_web/views/error_view_test.exs
ponyatov/w
3211fd253018f07da382871cf2d08b80574b72e6
[ "MIT" ]
null
null
null
test/w_web/views/error_view_test.exs
ponyatov/w
3211fd253018f07da382871cf2d08b80574b72e6
[ "MIT" ]
null
null
null
test/w_web/views/error_view_test.exs
ponyatov/w
3211fd253018f07da382871cf2d08b80574b72e6
[ "MIT" ]
null
null
null
defmodule WWeb.ErrorViewTest do use WWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(WWeb.ErrorView, "404.html", []) == "Not Found" end test "renders 500.html" do assert render_to_string(WWeb.ErrorView, "500.html", []) == "Internal Server Error" end end
26.2
86
0.717557