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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93d23fc0720fff2958a75963b5d92b0c778630ef
| 331
|
ex
|
Elixir
|
lib/battle_city/environment/ice.ex
|
clszzyh/battle_city_core
|
7a3aca9000b186382f1faf526ebce837a76ef86e
|
[
"MIT"
] | null | null | null |
lib/battle_city/environment/ice.ex
|
clszzyh/battle_city_core
|
7a3aca9000b186382f1faf526ebce837a76ef86e
|
[
"MIT"
] | 38
|
2020-12-17T12:40:44.000Z
|
2022-03-31T02:05:59.000Z
|
lib/battle_city/environment/ice.ex
|
clszzyh/battle_city
|
7a3aca9000b186382f1faf526ebce837a76ef86e
|
[
"MIT"
] | null | null | null |
defmodule BattleCity.Environment.Ice do
@moduledoc false
use BattleCity.Environment,
health: 0,
enter?: false
@impl true
def handle_enter(_, %{speed: speed} = t) do
{:ok, %{t | speed: speed + 10}}
end
@impl true
def handle_leave(_, %{speed: speed} = t) do
{:ok, %{t | speed: speed - 10}}
end
end
| 18.388889
| 45
| 0.613293
|
93d24f098d303a0cd180330a521903f8d4177330
| 1,100
|
ex
|
Elixir
|
ping_elixir/lib/ping_elixir_web/channels/user_socket.ex
|
tedpark/Clojure_Elixir_Concurrent_Ping
|
44fd2cc7b4056332998695de46b37c3e3ff54be7
|
[
"MIT"
] | null | null | null |
ping_elixir/lib/ping_elixir_web/channels/user_socket.ex
|
tedpark/Clojure_Elixir_Concurrent_Ping
|
44fd2cc7b4056332998695de46b37c3e3ff54be7
|
[
"MIT"
] | null | null | null |
ping_elixir/lib/ping_elixir_web/channels/user_socket.ex
|
tedpark/Clojure_Elixir_Concurrent_Ping
|
44fd2cc7b4056332998695de46b37c3e3ff54be7
|
[
"MIT"
] | null | null | null |
defmodule PingElixirWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", PingElixirWeb.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:
#
# PingElixirWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
@impl true
def id(_socket), do: nil
end
| 30.555556
| 85
| 0.697273
|
93d2632dffc1d36b26cc97f9ef5673a805e686fd
| 516
|
exs
|
Elixir
|
priv/repo/migrations/20220129030105_reload_views_from_files.exs
|
bikebrigade/dispatch
|
eb622fe4f6dab7c917d678d3d7a322a01f97da44
|
[
"Apache-2.0"
] | 28
|
2021-10-11T01:53:53.000Z
|
2022-03-24T17:45:55.000Z
|
priv/repo/migrations/20220129030105_reload_views_from_files.exs
|
bikebrigade/dispatch
|
eb622fe4f6dab7c917d678d3d7a322a01f97da44
|
[
"Apache-2.0"
] | 20
|
2021-10-21T08:12:31.000Z
|
2022-03-31T13:35:53.000Z
|
priv/repo/migrations/20220129030105_reload_views_from_files.exs
|
bikebrigade/dispatch
|
eb622fe4f6dab7c917d678d3d7a322a01f97da44
|
[
"Apache-2.0"
] | null | null | null |
defmodule BikeBrigade.Repo.Migrations.ReloadViewsFromFiles do
use Ecto.Migration
import BikeBrigade.MigrationUtils
def change do
# removing since we load these views later
# execute "drop view if exists rider_stats", ""
# load_sql("rider_stats_view.sql", "drop view if exists rider_stats")
# load_sql("rider_program_stats_view.sql", "drop view if exists rider_program_stats")
# load_sql("riders_latest_campaigns_view.sql", "drop view if exists riders_latest_campaigns")
end
end
| 36.857143
| 99
| 0.755814
|
93d2977ddd832c410b96f78035661d819b8930b8
| 268
|
ex
|
Elixir
|
apps/re_web/lib/sentry_event_filter.ex
|
ruby2elixir/emcasa-backend
|
70d7f4f233555417941ffa6ada84cf8740c21dd2
|
[
"MIT"
] | 4
|
2019-11-01T16:29:31.000Z
|
2020-10-10T21:20:12.000Z
|
apps/re_web/lib/sentry_event_filter.ex
|
caspg/backend
|
34df9dc14ab8ed75de4578fefa2e087580c7e867
|
[
"MIT"
] | null | null | null |
apps/re_web/lib/sentry_event_filter.ex
|
caspg/backend
|
34df9dc14ab8ed75de4578fefa2e087580c7e867
|
[
"MIT"
] | 5
|
2019-11-04T21:25:45.000Z
|
2020-02-13T23:49:36.000Z
|
defmodule ReWeb.SentryEventFilter do
@moduledoc """
Module to ignore sentry events
"""
@behaviour Sentry.EventFilter
def exclude_exception?(%Elixir.Phoenix.Router.NoRouteError{}, :plug), do: true
def exclude_exception?(_exception, _source), do: false
end
| 26.8
| 80
| 0.753731
|
93d2b1c03ce4692a5984d10a1f4476df4add8982
| 72
|
ex
|
Elixir
|
lib/metrics/repo_instrumenter.ex
|
helium/console
|
c6912b521926455ee0d4172dbd8e8183bdbae186
|
[
"Apache-2.0"
] | 83
|
2018-05-31T14:49:10.000Z
|
2022-03-27T16:49:49.000Z
|
lib/metrics/repo_instrumenter.ex
|
helium/console
|
c6912b521926455ee0d4172dbd8e8183bdbae186
|
[
"Apache-2.0"
] | 267
|
2018-05-22T23:19:02.000Z
|
2022-03-31T04:31:06.000Z
|
lib/metrics/repo_instrumenter.ex
|
helium/console
|
c6912b521926455ee0d4172dbd8e8183bdbae186
|
[
"Apache-2.0"
] | 18
|
2018-11-20T05:15:54.000Z
|
2022-03-28T08:20:13.000Z
|
defmodule App.Repo.Instrumenter do
use Prometheus.EctoInstrumenter
end
| 24
| 34
| 0.861111
|
93d2b1f008c8b01b7020b34d22c4c410d9c77417
| 704
|
ex
|
Elixir
|
lib/gituser/user/commands/list_user_data.ex
|
vinolivae/gituser
|
30dd93a8ea8ac5a8d40b91a17ee2eb29ed6bfd81
|
[
"MIT"
] | null | null | null |
lib/gituser/user/commands/list_user_data.ex
|
vinolivae/gituser
|
30dd93a8ea8ac5a8d40b91a17ee2eb29ed6bfd81
|
[
"MIT"
] | null | null | null |
lib/gituser/user/commands/list_user_data.ex
|
vinolivae/gituser
|
30dd93a8ea8ac5a8d40b91a17ee2eb29ed6bfd81
|
[
"MIT"
] | null | null | null |
defmodule Gituser.User.Commands.ListUserData do
@spec execute(user_name :: String.t()) :: {:ok, User.t()} | {:error, :not_found}
def execute(user_name) do
case github_client().user_repos(user_name) do
{:ok, user_datas} ->
datas = Enum.map(user_datas, &build_user_data/1)
{:ok, datas}
error ->
error
end
end
defp build_user_data(user_data) do
%{
id: user_data["id"],
name: user_data["name"],
description: user_data["description"],
html_url: user_data["html_url"],
stargazers_count: user_data["stargazers_count"]
}
end
defp github_client, do: Application.fetch_env!(:gituser, __MODULE__)[:github_adapter]
end
| 27.076923
| 87
| 0.646307
|
93d2be80db50226fa5445ff097f978d43604241d
| 1,645
|
ex
|
Elixir
|
clients/big_query/lib/google_api/big_query/v2/model/row.ex
|
linjunpop/elixir-google-api
|
444cb2b2fb02726894535461a474beddd8b86db4
|
[
"Apache-2.0"
] | null | null | null |
clients/big_query/lib/google_api/big_query/v2/model/row.ex
|
linjunpop/elixir-google-api
|
444cb2b2fb02726894535461a474beddd8b86db4
|
[
"Apache-2.0"
] | null | null | null |
clients/big_query/lib/google_api/big_query/v2/model/row.ex
|
linjunpop/elixir-google-api
|
444cb2b2fb02726894535461a474beddd8b86db4
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.BigQuery.V2.Model.Row do
@moduledoc """
A single row in the confusion matrix.
## Attributes
- actualLabel (String.t): The original label of this row. Defaults to: `null`.
- entries ([Entry]): Info describing predicted label distribution. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:actualLabel => any(),
:entries => list(GoogleApi.BigQuery.V2.Model.Entry.t())
}
field(:actualLabel)
field(:entries, as: GoogleApi.BigQuery.V2.Model.Entry, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.Row do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.Row.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.Row do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.254902
| 89
| 0.729483
|
93d2dcb395635c261e9a0b5aa39f9ad721b089bf
| 185
|
ex
|
Elixir
|
lib/oniichain_web/views/peer_view.ex
|
freester1/OniiChain
|
28153c2fa3b1425aeac240df016c907d5b822101
|
[
"Apache-2.0"
] | 9
|
2017-12-17T02:58:48.000Z
|
2018-11-07T13:48:50.000Z
|
lib/oniichain_web/views/peer_view.ex
|
freester1/OniiChain
|
28153c2fa3b1425aeac240df016c907d5b822101
|
[
"Apache-2.0"
] | 1
|
2017-12-12T23:58:22.000Z
|
2017-12-13T00:00:21.000Z
|
lib/oniichain_web/views/peer_view.ex
|
freester1/OniiChain
|
28153c2fa3b1425aeac240df016c907d5b822101
|
[
"Apache-2.0"
] | 3
|
2017-12-12T23:57:20.000Z
|
2018-03-03T22:13:38.000Z
|
defmodule OniichainWeb.PeerView do
use OniichainWeb, :view
def render("200.json", %{}) do
%{}
end
def render("peers.json", %{peers: peers}) do
%{peers: peers}
end
end
| 18.5
| 46
| 0.632432
|
93d2e57173b880fa0398c79e615aa6ee8936a25b
| 2,922
|
ex
|
Elixir
|
lib/live_element/test/structs.ex
|
gaslight/live_element
|
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
|
[
"MIT"
] | null | null | null |
lib/live_element/test/structs.ex
|
gaslight/live_element
|
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
|
[
"MIT"
] | null | null | null |
lib/live_element/test/structs.ex
|
gaslight/live_element
|
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
|
[
"MIT"
] | null | null | null |
defmodule LiveElementTest.View do
@moduledoc """
The struct for testing LiveViews.
The following public fields represent the LiveView:
* `id` - The DOM id of the LiveView
* `module` - The module of the running LiveView
* `pid` - The Pid of the running LiveView
* `endpoint` - The endpoint for the LiveView
* `target` - The target to scope events to
See the `LiveElementTest` documentation for usage.
"""
if Version.match?(System.version(), ">= 1.8.0") do
@derive {Inspect, only: [:id, :module, :pid, :endpoint]}
end
defstruct id: nil,
module: nil,
pid: nil,
proxy: nil,
endpoint: nil,
target: nil
end
defmodule LiveElementTest.Element do
@moduledoc """
The struct returned by `LiveElementTest.element/3`.
The following public fields represent the element:
* `selector` - The query selector
* `text_filter` - The text to further filter the element
See the `LiveElementTest` documentation for usage.
"""
if Version.match?(System.version(), ">= 1.8.0") do
@derive {Inspect, only: [:selector, :text_filter]}
end
defstruct proxy: nil,
selector: nil,
text_filter: nil,
event: nil,
form_data: nil,
meta: %{}
end
defmodule LiveElementTest.Upload do
@moduledoc """
The struct returned by `LiveElementTest.file_input/4`.
The following public fields represent the element:
* `selector` - The query selector
* `entries` - The list of selected file entries
See the `LiveElementTest` documentation for usage.
"""
alias LiveElementTest.{Upload, Element}
if Version.match?(System.version(), ">= 1.8.0") do
@derive {Inspect, only: [:selector, :entries]}
end
defstruct pid: nil,
view: nil,
element: nil,
ref: nil,
selector: nil,
config: %{},
entries: [],
cid: nil
@doc false
def new(pid, %LiveElementTest.View{} = view, form_selector, name, entries, cid) do
populated_entries = Enum.map(entries, fn entry -> populate_entry(entry) end)
selector = "#{form_selector} input[type=\"file\"][name=\"#{name}\"]"
%Upload{
pid: pid,
view: view,
element: %Element{proxy: view.proxy, selector: selector},
entries: populated_entries,
cid: cid
}
end
defp populate_entry(%{} = entry) do
name =
Map.get(entry, :name) ||
raise ArgumentError, "a :name of the entry filename is required."
content =
Map.get(entry, :content) ||
raise ArgumentError, "the :content of the binary entry file data is required."
%{
"name" => name,
"content" => content,
"ref" => to_string(System.unique_integer([:positive])),
"size" => entry[:size] || byte_size(content),
"type" => entry[:type] || MIME.from_path(name)
}
end
end
| 26.807339
| 86
| 0.610883
|
93d2f27a17162411d7a53158616060fbdc01f700
| 17,263
|
ex
|
Elixir
|
lib/ps2/api/query_builder.ex
|
Bentheburrito/planetside_api
|
1c419c5a9d52ab354493ac0ded2a50e4d3ff6c60
|
[
"MIT"
] | 4
|
2020-04-04T16:28:51.000Z
|
2021-12-15T15:33:39.000Z
|
lib/ps2/api/query_builder.ex
|
Bentheburrito/planetside_api
|
1c419c5a9d52ab354493ac0ded2a50e4d3ff6c60
|
[
"MIT"
] | null | null | null |
lib/ps2/api/query_builder.ex
|
Bentheburrito/planetside_api
|
1c419c5a9d52ab354493ac0ded2a50e4d3ff6c60
|
[
"MIT"
] | null | null | null |
defmodule PS2.API.QueryBuilder do
@moduledoc """
A module for creating Census API queries in a clean manner via pipelines.
### Example
iex> import PS2.API.QueryBuilder
PS2.API.QueryBuilder
iex> alias PS2.API.Query
PS2.API.Query
iex> query = Query.new(collection: "character")
...> |> term("character_id", "5428011263335537297")
...> |> show(["character_id", "name.en", "faction_id"])
...> |> limit(3)
...> |> exact_match_first(true)
%PS2.API.Query{
collection: "character",
joins: [],
sort: nil,
params: %{
"c:exactMatchFirst" => true,
"c:limit" => 3,
"c:show" => "character_id,name.en,faction_id",
"character_id" => {"", "5428011263335537297"}
},
tree: nil
}
iex> PS2.API.encode query
{:ok, "character?c:exactMatchFirst=true&c:limit=3&c:show=character_id,name.en,faction_id&character_id=5428011263335537297"}
You can then send the query to the api using `PS2.API.query/1`.
## Search Modifiers
The Census API provides [search modifiers](https://census.daybreakgames.com/#search-modifier) for filtering query results.
You can pass an atom as the third parameter in `term/4` representing one of
these search modifiers. The recognized atoms are the following:
```
:greater_than
:greater_than_or_equal
:less_than
:less_than_or_equal
:starts_with
:contains
:not
```
For example: `term(query_or_join, "name.first_lower", "wrel", :starts_with)`
## Joining Queries
You can use `Join`s to gather data from multiple collections within one query,
like so:
```elixir
import PS2.API.QueryBuilder
alias PS2.API.{Query, Join}
online_status_join =
# Note we could use Join.new(collection: "characters_online_status", show: "online_status" ...)
%Join{}
|> collection("characters_online_status")
|> show("online_status")
|> inject_at("online_status")
|> list(true)
query =
%Query{}
|> collection("character")
|> join(online_status_join)
```
When the query `q` is sent to the API, the result with have an extra field,
"online_status", which contains the result of the `Join` (the player's
online status.)
You can create as many adjacent `Join`s as you'd like by repeatedly piping
a query through `QueryBuilder.join/2`. You can also nest `Join`s via
`QueryBuilder.join/2` when you pass a Join as the first argument instead
of a Query.
```elixir
import PS2.API.QueryBuilder
alias PS2.API.{Query, Join}
char_achieve_join =
Join.new(collection: "characters_achievement", on: "character_id")
char_name_join =
Join.new(collection: "character_name", on: "character_id", inject_at: "c_name")
online_status_join =
Join.new(collection: "characters_online_status")
|> join(char_name_join)
|> join(char_achieve_join)
query =
%Query{}
|> collection("character")
|> term("name.first", "Snowful")
|> show(["character_id", "faction_id"])
|> join(online_status_join)
```
## Trees
You can organize the returned data by a field within the data, using the
`QueryBuilder.tree/2`.
```elixir
import PS2.API.QueryBuilder
alias PS2.API.{Query, Tree}
%Query{}
|> collection("world_event")
|> term("type", "METAGAME")
|> lang("en")
|> tree(
%Tree{}
|> field("world_id")
|> list(true)
)
```
"""
@modifier_map %{
greater_than: ">",
greater_than_or_equal: "]",
less_than: "<",
less_than_or_equal: "[",
starts_with: "^",
contains: "*",
not: "!"
}
@type modifer ::
:greater_than
| :greater_than_or_equal
| :less_than
| :less_than_or_equal
| :starts_with
| :contains
| :not
| nil
@type collection_name :: String.t()
@type field_name :: String.t()
alias PS2.API.{Query, Join, Tree}
@doc """
Set the collection of the query/join.
"""
@spec collection(Query.t(), collection_name) :: Query.t()
@spec collection(Join.t(), collection_name) :: Join.t()
def collection(query_or_join, collection_name)
def collection(%Query{} = query, collection_name),
do: %Query{query | collection: collection_name}
def collection(%Join{} = join, collection), do: %Join{join | collection: collection}
@doc """
Adds a c:show term. Overwrites previous params of the same name.
### API Documentation:
Only include the provided fields from the object within the result.
"""
@spec show(Query.t(), String.t() | list(String.t())) :: Query.t()
@spec show(Join.t(), String.t() | list(String.t())) :: Join.t()
def show(query_or_join, value)
def show(%Query{} = query, values) when is_list(values), do: show(query, Enum.join(values, ","))
def show(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:show", value)}
def show(%Join{} = join, values) when is_list(values), do: show(join, Enum.join(values, "'"))
def show(%Join{} = join, value), do: %Join{join | params: Map.put(join.params, "show", value)}
@doc """
Adds a c:hide term. Overwrites previous params of the same name.
### API Documentation:
Include all field except the provided fields from the object within the result.
"""
@spec hide(Query.t(), String.t() | list(String.t())) :: Query.t()
@spec hide(Join.t(), String.t() | list(String.t())) :: Join.t()
def hide(query_or_join, values)
def hide(%Query{} = query, values) when is_list(values), do: hide(query, Enum.join(values, ","))
def hide(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:hide", value)}
def hide(%Join{} = join, values) when is_list(values), do: hide(join, Enum.join(values, "'"))
def hide(%Join{} = join, field), do: %Join{join | params: Map.put(join.params, "hide", field)}
@doc """
Add a term to filter query results. i.e. filter a query by character ID: `.../character?character_id=1234123412341234123`
"""
@spec term(Query.t(), String.t() | atom, any, modifer) :: Query.t()
@spec term(Join.t(), String.t() | atom, any, modifer) :: Join.t()
def term(query_or_join, field, value, modifier \\ nil)
def term(%Query{} = query, field, value, modifier),
do: %Query{
query
| params: Map.put(query.params, field, {Map.get(@modifier_map, modifier, ""), value})
}
def term(%Join{} = join, field, value, modifier) do
term_value = {Map.get(@modifier_map, modifier, ""), value}
%Join{
join
| params:
Map.update(join.params, :terms, %{field => term_value}, &Map.put(&1, field, term_value))
}
end
@doc """
Adds a join to a query.
See the "Using c:join to join collections dynamically"
section at https://census.daybreakgames.com/#query-commands to learn more about joining
queries.
### c:join API Documentation:
Meant to replace c:resolve, useful for dynamically joining (resolving)
multiple data types in one query.
"""
@spec join(Query.t(), Join.t()) :: Query.t()
@spec join(Join.t(), Join.t()) :: Join.t()
def join(query_or_join, join)
def join(%Query{} = query, %Join{} = join), do: %Query{query | joins: [join | query.joins]}
def join(%Join{} = join, %Join{} = new_join), do: %Join{join | joins: [new_join | join.joins]}
@doc """
Adds a sort term (to a Join or Tree).
Specifies whether the result should be a list (true) or a single record (false). Defaults to false.
"""
@spec list(Join.t(), boolean()) :: %Join{}
@spec list(Tree.t(), boolean()) :: %Tree{}
def list(tree_or_join, boolean)
def list(%Join{} = join, boolean),
do: %Join{join | params: Map.put(join.params, "list", PS2.Utils.boolean_to_integer(boolean))}
def list(%Tree{} = tree, boolean),
do: %Tree{tree | terms: Map.put(tree.terms, :list, PS2.Utils.boolean_to_integer(boolean))}
# ~~Query specific functions~~
@doc """
Adds a c:sort term. Overwrites previous params of the same name.
### API Documentation:
Sort the results by the field(s) provided.
"""
@spec sort(Query.t(), Query.sort_terms()) :: Query.t()
def sort(%Query{} = query, %{} = sort_terms), do: %Query{query | sort: sort_terms}
@doc """
Adds a c:has term. Overwrites previous params of the same name.
### API Documentation:
Include objects where the specified field exists, regardless
of the value within that field.
"""
@spec has(Query.t(), String.t() | list()) :: Query.t()
def has(%Query{} = query, values) when is_list(values), do: has(query, Enum.join(values, ","))
def has(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:has", value)}
@doc """
Adds a c:resolve term. Overwrites previous params of the same name.
**Note** that `join/3` is recommended over `resolve/2`, as resolve relies
on supported collections to work.
### API Documentation:
"Resolve" information by merging data from another collection and include
the detailed object information for the provided fields from the object
within the result (multiple field names separated by a comma).\n
*Please note that the resolve will only function if the initial query contains
the field to be resolved on. For instance, resolving leader on outfit requires
that leader_character_id be in the initial query.
"""
@spec resolve(Query.t(), String.t()) :: Query.t()
def resolve(%Query{} = query, collection),
do: %Query{query | params: Map.put(query.params, "c:resolve", collection)}
@doc """
Adds a c:case (sensitivity) term. Overwrites previous params of the same name.
### API Documentation:
Set whether a search should be case-sensitive, `true` means
case-sensitive. true is the default. Note that using this command may slow
down your queries. If a lower case version of a field is available use that
instead for faster performance.
"""
@spec case_sensitive(Query.t(), boolean()) :: Query.t()
def case_sensitive(%Query{} = query, boolean),
do: %Query{query | params: Map.put(query.params, "c:case", boolean)}
@doc """
Adds a c:limit term. Overwrites previous params of the same name.
### API Documentation:
Limit the results to at most N [`value`] objects.
"""
@spec limit(Query.t(), integer()) :: Query.t()
def limit(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:limit", value)}
@doc """
Adds a c:limitPerDB term. Overwrites previous params of the same name.
### API Documentation:
Limit the results to at most (N * number of databases) objects.\n
*The data type ps2/character is distributed randomly across 20
databases. Using c:limitPerDb will have more predictable results on
ps2/character than c:limit will.
"""
@spec limit_per_db(Query.t(), integer()) :: Query.t()
def limit_per_db(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:limitPerDB", value)}
@doc """
Adds a c:start term. Overwrites previous params of the same name.
### API Documentation:
Start with the Nth object within the results of the query.\n
*Please note that c:start will have unusual behavior when
querying ps2/character which is distributed randomly across
20 databases.
"""
@spec start(Query.t(), integer()) :: Query.t()
def start(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:start", value)}
@doc """
Adds a c:includeNull term. Overwrites previous params of the same name.
### API Documentation:
Include `NULL` values in the result. By default this is false. For
example, if the `name.fr` field of a vehicle is `NULL` the field `name.fr`
will not be included in the response by default. Add the
c:includeNull=true command if you want the value name.fr : `NULL` to be
returned in the result.
"""
@spec include_null(Query.t(), boolean()) :: Query.t()
def include_null(%Query{} = query, boolean),
do: %Query{query | params: Map.put(query.params, "c:includeNull", boolean)}
@doc """
Adds a c:lang term. Overwrites previous params of the same name.
### API Documentation:
For internationalized strings, remove all translations except the one specified.
"""
@spec lang(Query.t(), String.t()) :: Query.t()
def lang(%Query{} = query, value),
do: %Query{query | params: Map.put(query.params, "c:lang", value)}
@doc """
Adds a c:tree term
### API Documentaion:
Useful for rearranging lists of data into trees of data. See below for details.
"""
@spec tree(Query.t(), Tree.t()) :: Query.t()
def tree(%Query{} = query, %Tree{} = tree), do: %Query{query | tree: tree}
@doc """
Adds a c:timing term. Overwrites previous params of the same name.
### API Documentation:
Shows the time taken by the involved server-side queries and resolves.
"""
@spec timing(Query.t(), boolean()) :: Query.t()
def timing(%Query{} = query, boolean),
do: %Query{query | params: Map.put(query.params, "c:timing", boolean)}
@doc """
Adds a c:exactMatchFirst term. Overwrites previous params of the same name.
### API Documentation:
When using a regex search (=^ or =*) c:exactMatchFirst=true will cause
exact matches of the regex value to appear at the top of the result list
despite the value of c:sort.
"""
@spec exact_match_first(Query.t(), boolean()) :: Query.t()
def exact_match_first(%Query{} = query, boolean),
do: %Query{query | params: Map.put(query.params, "c:exactMatchFirst", boolean)}
@doc """
Adds a c:distinct term. Overwrites previous params of the same name.
### API Documentation:
Get the distinct values of the given field. For example to get the
distinct values of ps2.item.max_stack_size use
`http://census.daybreakgames.com/get/ps2/item?c:distinct=max_stack_size`.
Results are capped at 20,000 values.
"""
@spec distinct(Query.t(), boolean()) :: Query.t()
def distinct(%Query{} = query, boolean),
do: %Query{query | params: Map.put(query.params, "c:distinct", boolean)}
@doc """
Adds a c:retry term. Overwrites previous params of the same name.
### API Documentation:
If `true`, query will be retried one time. Default value is true.
If you prefer your query to fail quickly pass c:retry=false.
"""
@spec retry(Query.t(), boolean()) :: Query.t()
def retry(%Query{} = query, boolean),
do: %Query{query | params: Map.put(query.params, "c:retry", boolean)}
# ~~Join specific functions~~
@doc """
Adds an `on:` term. `field` is the field on the parent/leading collection to compare with the join's field
(optionally specified with the `to/2` function).
### API Documentation:
The field on this type to join on, i.e. item_id. Will default to {this_type}_id or {other_type}_id if not provided.
"""
@spec on(Join.t(), field_name) :: %Join{}
def on(%Join{} = join, field), do: %Join{join | params: Map.put(join.params, "on", field)}
@doc """
Adds a `to:` term. `field` is the field on the joined collection to compare with the parent/leading field
(optionally specified with the `on/2` function).
### API Documentation:
The field on the joined type to join to, i.e. attachment_item_id. Will default to on if on is provide, otherwise
will default to {this_type}_id or {other_type}_id if not provided.
"""
@spec to(Join.t(), field_name) :: %Join{}
def to(%Join{} = join, field), do: %Join{join | params: Map.put(join.params, "to", field)}
@doc """
Adds an `injected_at:` term. `field` is the name of the new field where the result of the join is inserted.
### API Documentation:
The field name where the joined data should be injected into the returned document.
"""
@spec inject_at(Join.t(), field_name) :: %Join{}
def inject_at(%Join{} = join, field),
do: %Join{join | params: Map.put(join.params, "inject_at", field)}
@doc """
Adds an `outer:` term. Note: where the API docs specify `1`, `true` should be passed, and `false` in place of `0`.
### API Documentation:
1 if you wish to do an outer join (include non-matches), 0 if you wish to do an inner join (exclude non-matches).
Defaults to 1- do an outer join, include non-matches.
"""
@spec outer(Join.t(), boolean()) :: %Join{}
def outer(%Join{} = join, boolean),
do: %Join{join | params: Map.put(join.params, "outer", PS2.Utils.boolean_to_integer(boolean))}
# ~~Tree specific functions~~
@doc """
Adds a `start:` term.
### API Documentaion:
Used to tell the tree where to start. By default, the list of objects at the root will be formatted as a tree.
"""
@spec start_field(Tree.t(), field_name) :: %Tree{}
def start_field(%Tree{} = tree, field),
do: %Tree{tree | terms: Map.put(tree.terms, :start, field)}
@doc """
Adds a `field:` term.
### API Documentation:
The field to remove and use as in the data structure, or tree.
"""
@spec field(Tree.t(), field_name) :: %Tree{}
def field(%Tree{} = tree, field), do: %Tree{tree | terms: Map.put(tree.terms, :field, field)}
@doc """
Add a `prefix:` term.
### API Documentation:
A prefix to add to the field value to make it more readable. For example, if the field is "faction_id" and prefix
is "f_", path will be f_1, f_2, f_3 etc.
"""
@spec prefix(Tree.t(), String.t()) :: %Tree{}
def prefix(%Tree{} = tree, prefix),
do: %Tree{tree | terms: Map.put(tree.terms, :prefix, prefix)}
end
| 36.729787
| 126
| 0.6635
|
93d2f6506cfed4a1263cea8676a146603c130926
| 969
|
ex
|
Elixir
|
clients/plus/lib/google_api/plus/v1/deserializer.ex
|
hauptbenutzer/elixir-google-api
|
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
|
[
"Apache-2.0"
] | null | null | null |
clients/plus/lib/google_api/plus/v1/deserializer.ex
|
hauptbenutzer/elixir-google-api
|
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
|
[
"Apache-2.0"
] | null | null | null |
clients/plus/lib/google_api/plus/v1/deserializer.ex
|
hauptbenutzer/elixir-google-api
|
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
|
[
"Apache-2.0"
] | 1
|
2020-11-10T16:58:27.000Z
|
2020-11-10T16:58:27.000Z
|
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Plus.V1.Deserializer do
@moduledoc """
Helper functions for deserializing responses into models.
This module is no longer used. Please use GoogleApi.Gax.ModelBase instead.
"""
end
| 37.269231
| 77
| 0.764706
|
93d31fde21eefc51235046ebdf035e3215cd3562
| 1,700
|
exs
|
Elixir
|
exercises/armstrong-numbers/armstrong_number_test.exs
|
pashutk/elixir
|
35938cf20bca2c40b0ec0bd1ce2227863a2cd318
|
[
"MIT"
] | null | null | null |
exercises/armstrong-numbers/armstrong_number_test.exs
|
pashutk/elixir
|
35938cf20bca2c40b0ec0bd1ce2227863a2cd318
|
[
"MIT"
] | 1
|
2019-06-13T09:31:54.000Z
|
2019-06-13T09:31:54.000Z
|
exercises/armstrong-numbers/armstrong_number_test.exs
|
pashutk/elixir
|
35938cf20bca2c40b0ec0bd1ce2227863a2cd318
|
[
"MIT"
] | 1
|
2019-06-13T04:29:09.000Z
|
2019-06-13T04:29:09.000Z
|
if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("armstrong_number.exs", __DIR__)
end
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
defmodule ArmstrongNumberTest do
use ExUnit.Case
test "One-digit numbers are Armstrong numbers" do
assert ArmstrongNumber.valid?(1)
assert ArmstrongNumber.valid?(6)
assert ArmstrongNumber.valid?(9)
end
@tag :pending
test "Two-digit numbers aren't Armstrong numbers" do
refute ArmstrongNumber.valid?(11)
refute ArmstrongNumber.valid?(89)
refute ArmstrongNumber.valid?(44)
end
@tag :pending
test "Three-digit numbers that are the Armstrong numbers" do
assert ArmstrongNumber.valid?(153)
assert ArmstrongNumber.valid?(370)
end
@tag :pending
test "Three-digit numbers that aren't the Armstrong numbers" do
refute ArmstrongNumber.valid?(555)
refute ArmstrongNumber.valid?(662)
end
@tag :pending
test "Four-digit number that is the Armstrong numbers" do
assert ArmstrongNumber.valid?(1634)
end
@tag :pending
test "Four-digit number that is not the Armstrong numbers" do
refute ArmstrongNumber.valid?(9989)
end
@tag :pending
test "Seven-digit number that is the Armstrong numbers" do
assert ArmstrongNumber.valid?(9_926_315)
end
@tag :pending
test "Seven-digit number that is not the Armstrong numbers" do
refute ArmstrongNumber.valid?(2_369_989)
end
@tag :pending
test "Ten-digit number that is the Armstrong numbers" do
assert ArmstrongNumber.valid?(4_679_307_774)
end
@tag :pending
test "Fourteen-digit number that is the Armstrong numbers" do
assert ArmstrongNumber.valid?(28_116_440_335_967)
end
end
| 25.757576
| 65
| 0.740588
|
93d35d38f97280da53c8fcbb783ad84b37b58cf3
| 86
|
exs
|
Elixir
|
test/views/layout_view_test.exs
|
jchartsell/atbash_cipher
|
707d8efa97fc36794c9e69717d8786e26da4d479
|
[
"MIT"
] | null | null | null |
test/views/layout_view_test.exs
|
jchartsell/atbash_cipher
|
707d8efa97fc36794c9e69717d8786e26da4d479
|
[
"MIT"
] | null | null | null |
test/views/layout_view_test.exs
|
jchartsell/atbash_cipher
|
707d8efa97fc36794c9e69717d8786e26da4d479
|
[
"MIT"
] | null | null | null |
defmodule AtbashCipher.LayoutViewTest do
use AtbashCipher.ConnCase, async: true
end
| 21.5
| 40
| 0.837209
|
93d37352e9d3ccc384af81493a27be7ba92e49a5
| 3,466
|
exs
|
Elixir
|
test/extrace_test.exs
|
LostKobrakai/extrace
|
cb569b491daa3ac2307b73b1b4b28943b49f65f7
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
test/extrace_test.exs
|
LostKobrakai/extrace
|
cb569b491daa3ac2307b73b1b4b28943b49f65f7
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
test/extrace_test.exs
|
LostKobrakai/extrace
|
cb569b491daa3ac2307b73b1b4b28943b49f65f7
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
defmodule ExtraceTest do
use ExUnit.Case
import Extrace, only: [to_erl_tspec: 1, format: 1]
test "to_erl_tspec/1" do
shellfun = make_shellfun("fn([n, _]) when n > 10 -> :ok end")
matchspec = [{[:"$1", :_], [{:>, :"$1", 10}], [:ok]}]
assert to_erl_tspec({:queue, :in, shellfun}) == {:queue, :in, matchspec}
assert to_erl_tspec({:queue, :in, matchspec}) == {:queue, :in, matchspec}
assert to_erl_tspec({:queue, :in, 2}) == {:queue, :in, 2}
shellfun = make_shellfun("fn([:item, _]) -> :return end")
matchspec = [{[:item, :_], [], [{:return_trace}]}]
assert to_erl_tspec({:queue, :in, shellfun}) == {:queue, :in, matchspec}
end
test "format/1 for :call" do
ts = :os.timestamp()
# Format an Elixir module call with atom and function
assert format(
{:trace_ts, pid(0, 1, 2), :call, {Emum, :each, [[:hello, "world"], &IO.puts/1]}, ts}
) ==
'\n#{format_timestamp(ts)} <0.1.2> Emum.each([:hello, "world"], &IO.puts/1)\n'
# Format an Erlang module call
assert format({:trace_ts, pid(0, 1, 2), :call, {:lists, :seq, [1, 10]}, ts}) ==
'\n#{format_timestamp(ts)} <0.1.2> :lists.seq(1, 10)\n'
end
test "limit format/1 for :call " do
:ok = :recon_map.limit(:test, fn map -> Map.get(map, :test) != nil end, [:a, :b])
ts = :os.timestamp()
# Format an Map data
assert format(
{:trace_ts, pid(0, 1, 2), :return_from, {IO, :inspect, 1}, %{test: true, a: 1, b: 2},
ts}
) ==
'\n#{format_timestamp(ts)} <0.1.2> IO.inspect/1 --> %{a: 1, b: 2, ...}\n'
assert format(
{:trace_ts, pid(0, 1, 2), :return_from, {IO, :inspect, 1}, %{a: 1, b: 2, c: 3}, ts}
) ==
'\n#{format_timestamp(ts)} <0.1.2> IO.inspect/1 --> %{a: 1, b: 2, c: 3}\n'
:ok = :recon_map.limit(:struct, &match?(%Inspect.Opts{}, &1), [:limit, :width])
# Format an Struct data
assert format({:trace_ts, pid(0, 1, 2), :return_from, {IO, :inspect, 1}, %Inspect.Opts{}, ts}) ==
'\n#{format_timestamp(ts)} <0.1.2> IO.inspect/1 --> #Inspect.Opts<limit: 50, width: 80, ...>\n'
map_set = MapSet.new()
assert format({:trace_ts, pid(0, 1, 2), :return_from, {MapSet, :new, 0}, map_set, ts}) ==
'\n#{format_timestamp(ts)} <0.1.2> MapSet.new/0 --> #MapSet<[]>\n'
end
test "format/1 for :return_to" do
ts = :os.timestamp()
assert format({:trace_ts, pid(0, 1, 2), :return_from, {Emum, :each, 2}, :ok, ts}) ==
'\n#{format_timestamp(ts)} <0.1.2> Emum.each/2 --> :ok\n'
end
#################
### Utilities ###
#################
@spec make_shellfun(binary) :: ([term] -> term)
defp make_shellfun(fun_str) do
to_charlist(fun_str) |> :elixir.eval([]) |> elem(0)
end
# defp make_shellfun_erl(erl_fun_str) do
# {:ok, tokens, _} = to_char_list(erl_fun_str) |> :erl_scan.string
# {:ok, [expr]} = :erl_parse.parse_exprs(tokens)
# {:value, shellfun, _} = :erl_eval.expr(expr, [])
# shellfun
# end
defp pid(a, b, c) do
:erlang.list_to_pid('<#{a}.#{b}.#{c}>')
end
defp to_hms({_, _, micro} = ts) do
{_, {h, m, secs}} = :calendar.now_to_local_time(ts)
seconds = rem(secs, 60) + micro / 1_000_000
{h, m, seconds}
end
defp format_hms({h, m, s}) do
:io_lib.format('~2.2.0w:~2.2.0w:~9.6.0f', [h, m, s])
end
defp format_timestamp(ts) do
to_hms(ts) |> format_hms
end
end
| 33.650485
| 108
| 0.541258
|
93d38d94c30f28b82bb678eef2f89280afac123a
| 680
|
exs
|
Elixir
|
config/test.exs
|
mzgajner/smena
|
6c0243ae1e8d1cef6e8a8e240f0f6b703ea638c9
|
[
"Unlicense"
] | null | null | null |
config/test.exs
|
mzgajner/smena
|
6c0243ae1e8d1cef6e8a8e240f0f6b703ea638c9
|
[
"Unlicense"
] | null | null | null |
config/test.exs
|
mzgajner/smena
|
6c0243ae1e8d1cef6e8a8e240f0f6b703ea638c9
|
[
"Unlicense"
] | null | null | null |
use Mix.Config
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :app, Smena.Repo,
username: System.get_env("PGUSER"),
password: System.get_env("PGPASSWORD"),
database: System.get_env("PGDATABASE") <> "_test",
hostname: System.get_env("PGHOST"),
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :app, SmenaWeb.Endpoint,
http: [port: 4002],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 29.565217
| 58
| 0.741176
|
93d39bc2193988a3884566cf05ecc512ea1e0801
| 2,961
|
ex
|
Elixir
|
clients/jobs/lib/google_api/jobs/v3/model/google_cloud_talent_v4_custom_attribute.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/jobs/lib/google_api/jobs/v3/model/google_cloud_talent_v4_custom_attribute.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/jobs/lib/google_api/jobs/v3/model/google_cloud_talent_v4_custom_attribute.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Jobs.V3.Model.GoogleCloudTalentV4CustomAttribute do
@moduledoc """
Custom attribute values that are either filterable or non-filterable.
## Attributes
* `filterable` (*type:* `boolean()`, *default:* `nil`) - If the `filterable` flag is true, the custom field values may be used for custom attribute filters JobQuery.custom_attribute_filter. If false, these values may not be used for custom attribute filters. Default is false.
* `keywordSearchable` (*type:* `boolean()`, *default:* `nil`) - If the `keyword_searchable` flag is true, the keywords in custom fields are searchable by keyword match. If false, the values are not searchable by keyword match. Default is false.
* `longValues` (*type:* `list(String.t)`, *default:* `nil`) - Exactly one of string_values or long_values must be specified. This field is used to perform number range search. (`EQ`, `GT`, `GE`, `LE`, `LT`) over filterable `long_value`. Currently at most 1 long_values is supported.
* `stringValues` (*type:* `list(String.t)`, *default:* `nil`) - Exactly one of string_values or long_values must be specified. This field is used to perform a string match (`CASE_SENSITIVE_MATCH` or `CASE_INSENSITIVE_MATCH`) search. For filterable `string_value`s, a maximum total number of 200 values is allowed, with each `string_value` has a byte size of no more than 500B. For unfilterable `string_values`, the maximum total byte size of unfilterable `string_values` is 50KB. Empty string isn't allowed.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:filterable => boolean(),
:keywordSearchable => boolean(),
:longValues => list(String.t()),
:stringValues => list(String.t())
}
field(:filterable)
field(:keywordSearchable)
field(:longValues, type: :list)
field(:stringValues, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Jobs.V3.Model.GoogleCloudTalentV4CustomAttribute do
def decode(value, options) do
GoogleApi.Jobs.V3.Model.GoogleCloudTalentV4CustomAttribute.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Jobs.V3.Model.GoogleCloudTalentV4CustomAttribute do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 52.875
| 511
| 0.74029
|
93d3c20f708ced31af09b0e30b5de571ecd2a778
| 878
|
exs
|
Elixir
|
test/graphql/astra_graphql_test.exs
|
omnifroodle/astraex
|
873d5ca985c8387f236c086ffb76780092823e01
|
[
"Apache-2.0"
] | 3
|
2021-02-16T20:30:52.000Z
|
2021-08-16T15:02:59.000Z
|
test/graphql/astra_graphql_test.exs
|
omnifroodle/astraex
|
873d5ca985c8387f236c086ffb76780092823e01
|
[
"Apache-2.0"
] | null | null | null |
test/graphql/astra_graphql_test.exs
|
omnifroodle/astraex
|
873d5ca985c8387f236c086ffb76780092823e01
|
[
"Apache-2.0"
] | null | null | null |
defmodule AstraGraphqlTest do
use ExUnit.Case
doctest Astra.Graphql
describe "schema" do
test "query" do
query = """
query GetTables {
keyspace(name: "test") {
name
tables {
name
columns {
name
kind
type {
basic
info {
name
}
}
}
}
}
}
"""
assert {:ok, %{keyspace: _}} = Astra.Graphql.schema(query)
end
end
describe "keyspace" do
test "query" do
query = """
query oneThing {
thing(value: { id: "test" }) {
values {
id
name
}
}
}
"""
assert {:ok, %{thing: %{values: []}}} = Astra.Graphql.tables("test", query)
end
end
end
| 19.086957
| 81
| 0.390661
|
93d3e537485db125fbd524f51d1b0cbf752638ec
| 3,691
|
ex
|
Elixir
|
lib/apds9960/sensor.ex
|
mnishiguchi/apds9960
|
e37108f84f40fc21487879d419dbf55866d5babf
|
[
"MIT"
] | null | null | null |
lib/apds9960/sensor.ex
|
mnishiguchi/apds9960
|
e37108f84f40fc21487879d419dbf55866d5babf
|
[
"MIT"
] | null | null | null |
lib/apds9960/sensor.ex
|
mnishiguchi/apds9960
|
e37108f84f40fc21487879d419dbf55866d5babf
|
[
"MIT"
] | null | null | null |
defmodule APDS9960.Sensor do
@moduledoc "The APDS9960 sensor."
alias APDS9960.{Comm, Sensor, Transport}
@i2c_address 0x39
use TypedStruct
typedstruct do
field(:transport, Transport.t(), enforce: true)
end
@typedoc "The APDS9960 sensor option"
@type option() :: [
{:bus_name, binary}
| {:reset, boolean}
| {:set_defaults, boolean}
]
@type engine :: :color | :als | :proximity | :gesture
@type gesture_direction :: :up | :down | :left | :right
@doc "Initializes the I2C bus and sensor."
@spec init([option]) :: t()
def init(opts \\ []) do
bus_name = Access.get(opts, :bus_name, "i2c-1")
reset = Access.get(opts, :reset, true)
set_defaults = Access.get(opts, :set_defaults, true)
sensor = %Sensor{
transport: Transport.new(bus_name, @i2c_address)
}
:ok = ensure_connected!(sensor)
if reset, do: reset!(sensor)
if set_defaults, do: set_defaults!(sensor)
%Sensor{} = sensor
end
@spec ensure_connected!(Sensor.t()) :: :ok
defp ensure_connected!(%Sensor{transport: i2c}) do
true = Comm.connected?(i2c)
:ok
end
@spec reset!(Sensor.t()) :: :ok
def reset!(%Sensor{transport: i2c}) do
# Disable prox, gesture, and color engines
:ok = Comm.set_enable(i2c, gesture: 0, proximity: 0, als: 0)
# Reset basic config registers to power-on defaults
:ok = Comm.set_proximity_threshold(i2c, low: 0, high: 0)
:ok = Comm.set_interrupt_persistence(i2c, <<0>>)
:ok = Comm.set_gesture_proximity_threshold(i2c, enter: 0, exit: 0)
:ok = Comm.set_gesture_conf1(i2c, <<0>>)
:ok = Comm.set_gesture_conf2(i2c, <<0>>)
:ok = Comm.set_gesture_conf4(i2c, <<0>>)
:ok = Comm.set_gesture_pulse(i2c, <<0>>)
:ok = Comm.set_adc_integration_time(i2c, <<255>>)
:ok = Comm.set_control(i2c, als_and_color_gain: 1)
# Clear all non-gesture interrupts
:ok = Comm.clear_all_non_gesture_interrupts(i2c)
# Disable sensor and all functions/interrupts
:ok = Comm.set_enable(i2c, <<0>>)
:ok = Process.sleep(25)
# Re-enable sensor and wait 10ms for the power on delay to finish
:ok = Comm.set_enable(i2c, power: 1)
:ok = Process.sleep(10)
:ok
end
@spec set_defaults!(Sensor.t()) :: :ok
def set_defaults!(%Sensor{transport: i2c}) do
# Trigger proximity interrupt at >= 5, PPERS: 4 cycles
:ok = Comm.set_proximity_threshold(i2c, low: 0, high: 5)
:ok = Comm.set_interrupt_persistence(i2c, proximity: 4)
# Enter gesture engine at >= 5 proximity counts
# Exit gesture engine if all counts drop below 30
:ok = Comm.set_gesture_proximity_threshold(i2c, enter: 5, exit: 30)
# GEXPERS: 2 (4 cycles), GEXMSK: 0 (default) GFIFOTH: 2 (8 datasets)
:ok =
Comm.set_gesture_conf1(i2c,
fifo_threshold: 2,
exit_mask: 0,
exit_persistence: 2
)
# GGAIN: 2 (4x), GLDRIVE: 0 (100 mA), GWTIME: 1 (2.8 ms)
:ok =
Comm.set_gesture_conf2(i2c,
gain: 2,
led_drive_strength: 0,
wait_time: 1
)
# GPULSE: 5 (6 pulses), GPLEN: 2 (16 us)
:ok =
Comm.set_gesture_pulse(i2c,
pulse_count: 5,
pulse_length: 2
)
# ATIME: 0 (712ms color integration time, max count of 65535)
:ok = Comm.set_adc_integration_time(i2c, <<0>>)
# AGAIN: 1 (4x color gain)
:ok = Comm.set_control(i2c, als_and_color_gain: 1)
:ok
end
@doc "Enable an engine for a desired feature."
@spec enable(Sensor.t(), engine) :: :ok
def enable(%Sensor{transport: i2c}, :color), do: Comm.set_enable(i2c, als: 1)
def enable(%Sensor{transport: i2c}, engine), do: Comm.set_enable(i2c, [{engine, 1}])
end
| 29.062992
| 86
| 0.634245
|
93d3efb07ca81f00acf83802b96c88c3b30bf392
| 859
|
ex
|
Elixir
|
lib/runlet/ctrl/start.ex
|
msantos/runlet
|
d9cb44b113295387c296ab4576a09ca4a7ce0f7b
|
[
"ISC"
] | 4
|
2020-01-12T19:04:46.000Z
|
2021-09-20T14:37:22.000Z
|
lib/runlet/ctrl/start.ex
|
msantos/runlet
|
d9cb44b113295387c296ab4576a09ca4a7ce0f7b
|
[
"ISC"
] | null | null | null |
lib/runlet/ctrl/start.ex
|
msantos/runlet
|
d9cb44b113295387c296ab4576a09ca4a7ce0f7b
|
[
"ISC"
] | 1
|
2021-09-20T14:37:25.000Z
|
2021-09-20T14:37:25.000Z
|
defmodule Runlet.Ctrl.Start do
@moduledoc "Start a stopped process"
@doc """
Start a process.
"""
def exec(%Runlet{uid: uid} = env, pid), do: exec(env, pid, uid)
@doc """
Start multiple processes.
"""
@spec exec(Runlet.t(), String.t(), String.t()) :: Enumerable.t()
def exec(env, pid, uid) when is_binary(pid) do
pid
|> String.split()
|> Enum.map(fn t -> Runlet.PID.to_float(t) end)
|> Enum.map(fn t -> exec(env, t, uid) end)
end
@spec exec(Runlet.t(), Runlet.PID.t(), String.t()) :: Enumerable.t()
def exec(_env, pid, uid) when is_integer(pid) do
result = Runlet.Process.start(uid, pid)
[
%Runlet.Event{
event: %Runlet.Event.Ctrl{
service: "start",
description: result,
host: "#{node()}"
},
query: "start #{pid} #{uid}"
}
]
end
end
| 23.861111
| 70
| 0.559953
|
93d3f4e6a86501108c6a0f7caeb98b726c446c59
| 150
|
exs
|
Elixir
|
test/noaa_weather_test.exs
|
jjdonov/noaa_weather
|
d849f6e6122d1219c63ec5b4e9a4254ca97ac3a3
|
[
"MIT"
] | null | null | null |
test/noaa_weather_test.exs
|
jjdonov/noaa_weather
|
d849f6e6122d1219c63ec5b4e9a4254ca97ac3a3
|
[
"MIT"
] | null | null | null |
test/noaa_weather_test.exs
|
jjdonov/noaa_weather
|
d849f6e6122d1219c63ec5b4e9a4254ca97ac3a3
|
[
"MIT"
] | null | null | null |
defmodule NoaaWeatherTest do
use ExUnit.Case
doctest NoaaWeather
test "greets the world" do
assert NoaaWeather.hello() == :world
end
end
| 16.666667
| 40
| 0.733333
|
93d3f86687886eaea74555504217ab71eb9192a8
| 2,768
|
exs
|
Elixir
|
elixir/test/homework/merchants_test.exs
|
pauleibye/web-homework
|
1eb7a781796ee9186c8591207f87de96d138d5fd
|
[
"MIT"
] | 1
|
2021-03-15T04:09:23.000Z
|
2021-03-15T04:09:23.000Z
|
elixir/test/homework/merchants_test.exs
|
pauleibye/web-homework
|
1eb7a781796ee9186c8591207f87de96d138d5fd
|
[
"MIT"
] | null | null | null |
elixir/test/homework/merchants_test.exs
|
pauleibye/web-homework
|
1eb7a781796ee9186c8591207f87de96d138d5fd
|
[
"MIT"
] | null | null | null |
defmodule Homework.MerchantsTest do
use Homework.DataCase
alias Homework.Merchants
describe "merchants" do
alias Homework.Merchants.Merchant
@valid_attrs %{description: "some description", name: "some name"}
@update_attrs %{
description: "some updated description",
name: "some updated name"
}
@invalid_attrs %{description: nil, name: nil}
def merchant_fixture(attrs \\ %{}) do
{:ok, merchant} =
attrs
|> Enum.into(@valid_attrs)
|> Merchants.create_merchant()
merchant
end
test "list_merchants/1 returns all merchants" do
merchant = merchant_fixture()
assert Merchants.list_merchants([]) == [merchant]
end
test "get_merchant!/1 returns the merchant with given id" do
merchant = merchant_fixture()
assert Merchants.get_merchant!(merchant.id) == merchant
end
test "get_merchants_where_name/1 returns the merchant with the exact name" do
merchant = merchant_fixture()
assert Merchants.get_merchants_where_name("some name") == [merchant]
end
test "create_merchant/1 with valid data creates a merchant" do
assert {:ok, %Merchant{} = merchant} = Merchants.create_merchant(@valid_attrs)
assert merchant.description == "some description"
assert merchant.name == "some name"
end
test "create_merchant/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Merchants.create_merchant(@invalid_attrs)
end
test "update_merchant/2 with valid data updates the merchant" do
merchant = merchant_fixture()
assert {:ok, %Merchant{} = merchant} = Merchants.update_merchant(merchant, @update_attrs)
assert merchant.description == "some updated description"
assert merchant.name == "some updated name"
end
test "update_merchant/2 with invalid data returns error changeset" do
merchant = merchant_fixture()
assert {:error, %Ecto.Changeset{}} = Merchants.update_merchant(merchant, @invalid_attrs)
assert merchant == Merchants.get_merchant!(merchant.id)
end
test "delete_merchant/1 deletes the merchant" do
merchant = merchant_fixture()
assert {:ok, %Merchant{}} = Merchants.delete_merchant(merchant)
assert_raise Ecto.NoResultsError, fn -> Merchants.get_merchant!(merchant.id) end
end
test "change_merchant/1 returns a merchant changeset" do
merchant = merchant_fixture()
assert %Ecto.Changeset{} = Merchants.change_merchant(merchant)
end
test "get_merchants_fuzzy/return merchants within a levenshtein distance based on name" do
merchant = merchant_fixture()
assert [merchant] == Merchants.get_merchants_fuzzy("some name", 5)
end
end
end
| 34.6
| 95
| 0.697254
|
93d4261062a3eb02c73a23e1153014850506e6b3
| 201,988
|
ex
|
Elixir
|
clients/spanner/lib/google_api/spanner/v1/api/projects.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"Apache-2.0"
] | null | null | null |
clients/spanner/lib/google_api/spanner/v1/api/projects.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"Apache-2.0"
] | null | null | null |
clients/spanner/lib/google_api/spanner/v1/api/projects.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"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 """
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.385819
| 1,856
| 0.625483
|
93d429f0aa84b513de7d98bf226f1ebb84d86808
| 1,188
|
ex
|
Elixir
|
lib/teslamate/log/car.ex
|
fmossott/teslamate
|
611296aa4b95db117a13e6aa284e673bc0c66a7d
|
[
"MIT"
] | 1
|
2022-01-30T17:46:07.000Z
|
2022-01-30T17:46:07.000Z
|
lib/teslamate/log/car.ex
|
fmossott/teslamate
|
611296aa4b95db117a13e6aa284e673bc0c66a7d
|
[
"MIT"
] | null | null | null |
lib/teslamate/log/car.ex
|
fmossott/teslamate
|
611296aa4b95db117a13e6aa284e673bc0c66a7d
|
[
"MIT"
] | null | null | null |
defmodule TeslaMate.Log.Car do
use Ecto.Schema
import Ecto.Changeset
alias TeslaMate.Log.{ChargingProcess, Position, Drive}
alias TeslaMate.Settings.CarSettings
schema "cars" do
field :name, :string
field :efficiency, :float
field :model, :string
field :trim_badging, :string
field :marketing_name, :string
field :exterior_color, :string
field :wheel_type, :string
field :spoiler_type, :string
field :eid, :integer
field :vid, :integer
# TODO: with v2.0 mark as non nullable
field :vin, :string
belongs_to :settings, CarSettings
has_many :charging_processes, ChargingProcess
has_many :positions, Position
has_many :drives, Drive
timestamps()
end
@doc false
def changeset(car, attrs) do
car
|> cast(attrs, [
:eid,
:vid,
:vin,
:name,
:model,
:efficiency,
:trim_badging,
:marketing_name,
:exterior_color,
:wheel_type,
:spoiler_type
])
|> validate_required([:eid, :vid, :vin])
|> unique_constraint(:settings_id)
|> unique_constraint(:eid)
|> unique_constraint(:vin)
|> unique_constraint(:vid)
end
end
| 21.6
| 56
| 0.645623
|
93d42b9610ab3b0fa6563d294f002e4b720b61ec
| 22,914
|
exs
|
Elixir
|
test/json_pointer_test.exs
|
kianmeng/elixir-jsonpointer
|
637142af361b4a0c3774a5c89017dcb16728ab45
|
[
"MIT"
] | 9
|
2018-07-01T22:01:53.000Z
|
2022-03-09T12:21:10.000Z
|
test/json_pointer_test.exs
|
kianmeng/elixir-jsonpointer
|
637142af361b4a0c3774a5c89017dcb16728ab45
|
[
"MIT"
] | 3
|
2019-01-04T07:47:01.000Z
|
2019-07-31T09:15:23.000Z
|
test/json_pointer_test.exs
|
kianmeng/elixir-jsonpointer
|
637142af361b4a0c3774a5c89017dcb16728ab45
|
[
"MIT"
] | 4
|
2018-05-03T17:02:02.000Z
|
2021-11-21T10:57:03.000Z
|
defmodule JSONPointerTest do
use ExUnit.Case
doctest JSONPointer
doctest JSONPointer.Utils
defp rfc_data,
do: %{
"foo" => ["bar", "baz"],
"bar" => %{"baz" => 10},
"" => 0,
"a/b" => 1,
"c%d" => 2,
"e^f" => 3,
"g|h" => 4,
"i\\j" => 5,
"k\"l" => 6,
" " => 7,
"m~n" => 8
}
defp nested_data,
do: %{
"a" => 1,
"b" => %{"c" => 2},
"d" => %{"e" => [%{"a" => 3}, %{"b" => 4}, %{"c" => 5}]},
"f" => [6, 7],
"200" => %{"a" => "b"},
"01" => 8
}
defp book_store_data,
do: %{
"store" => %{
"book" => [
%{
"category" => "reference",
"author" => "Nigel Rees",
"title" => "Sayings of the Century",
"price" => 8.95
},
%{
"category" => "fiction",
"author" => "Evelyn Waugh",
"title" => "Sword of Honour",
"price" => 12.99
},
%{
"category" => "fiction",
"author" => "Herman Melville",
"title" => "Moby Dick",
"isbn" => "0-553-21311-3",
"price" => 8.99
},
%{
"category" => "fiction",
"author" => "J. R. R. Tolkien",
"title" => "The Lord of the Rings",
"isbn" => "0-395-19395-8",
"price" => 22.99
}
],
"bicycle" => %{
"color" => "red",
"price" => 19.95
}
}
}
describe "get" do
test "get rfc" do
assert JSONPointer.get!(rfc_data(), "") == rfc_data()
assert JSONPointer.get!(rfc_data(), "/foo") == rfc_data()["foo"]
assert JSONPointer.get!(rfc_data(), "/foo/0") == "bar"
assert JSONPointer.get!(rfc_data(), "/bar") == rfc_data()["bar"]
assert JSONPointer.get!(rfc_data(), "/bar/baz") == 10
assert JSONPointer.get!(rfc_data(), "/") == 0
assert JSONPointer.get!(rfc_data(), "/a~1b") == 1
assert JSONPointer.get!(rfc_data(), "/c%d") == 2
assert JSONPointer.get!(rfc_data(), "/e^f") == 3
assert JSONPointer.get!(rfc_data(), "/g|h") == 4
assert JSONPointer.get!(rfc_data(), "/i\\j") == 5
assert JSONPointer.get!(rfc_data(), "/k\"l") == 6
assert JSONPointer.get!(rfc_data(), "/ ") == 7
assert JSONPointer.get!(rfc_data(), "/m~0n") == 8
# starting with fragments
assert JSONPointer.get(rfc_data(), "#") == {:ok, rfc_data()}
assert JSONPointer.get(rfc_data(), "#/foo") == {:ok, ["bar", "baz"]}
assert JSONPointer.get(rfc_data(), "#/foo/0") == {:ok, "bar"}
assert JSONPointer.get(rfc_data(), "#/") == {:ok, 0}
assert JSONPointer.get(rfc_data(), "#/a~1b") == {:ok, 1}
# this library used to support escaped uri fragments, but this was not spec compliant and so removed
assert JSONPointer.get(rfc_data(), "#/c%25d") == {:error, "token not found: c%25d"}
end
test "get expanded" do
assert JSONPointer.get(nested_data(), "/a") == {:ok, 1}
assert JSONPointer.get(nested_data(), "/b/c") == {:ok, 2}
assert JSONPointer.get(nested_data(), "/d/e/0/a") == {:ok, 3}
assert JSONPointer.get(nested_data(), "/d/e/1/b") == {:ok, 4}
assert JSONPointer.get(nested_data(), "/d/e/2/c") == {:ok, 5}
assert JSONPointer.get(nested_data(), "/f/0") == {:ok, 6}
assert JSONPointer.get([], "/2") == {:error, "index out of bounds: 2"}
assert JSONPointer.get([], "/2/3") == {:error, "index out of bounds: 2"}
assert JSONPointer.get(nested_data(), "/d/e/3") == {:error, "index out of bounds: 3"}
assert JSONPointer.get(%{}, "") == {:ok, %{}}
assert JSONPointer.get(nested_data(), "/200") == {:ok, %{"a" => "b"}}
assert JSONPointer.get(nested_data(), ["d", "e", "1", "b"]) == {:ok, 4}
# passing a string an the object raises an error
assert_raise ArgumentError, ~s(invalid object: { "unencoded":"json" }), fn ->
JSONPointer.get(~s({ "unencoded":"json" }), "/unencoded")
end
end
test "special array rule" do
assert JSONPointer.get!(nested_data(), "/01") == 8
assert JSONPointer.get(["zero", "one", "two"], "/01") == {:error, "invalid index: 01"}
end
test "get using wildcard" do
data = book_store_data()
assert JSONPointer.get(data, "/store/bicycle/color") == {:ok, "red"}
# "the prices of all books in the store"
assert JSONPointer.get(data, "/store/book/**/price") == {:ok, [8.95, 12.99, 8.99, 22.99]}
# "all authors"
assert JSONPointer.get(data, "/**/author") ==
{:ok, ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]}
# the price of everything in the store.
assert JSONPointer.get(data, "/store/**/price") == {:ok, [19.95, 8.95, 12.99, 8.99, 22.99]}
assert JSONPointer.get(data, "/store/bicycle/**") ==
{:ok, %{"color" => "red", "price" => 19.95}}
assert JSONPointer.get(data, "/store/**") == {:ok, data["store"]}
assert JSONPointer.get(data, "/store/**/**") == {:error, "token not found: **"}
assert JSONPointer.get(data, "/store/book/**") == {:ok, data["store"]["book"]}
assert JSONPointer.get(data, "/store/book") == {:ok, data["store"]["book"]}
assert JSONPointer.get(data, "/**/nothing") == {:error, "token not found: nothing"}
assert_raise ArgumentError, "token not found: newspaper", fn ->
JSONPointer.get!(data, "/**/newspaper")
end
end
end
describe "set" do
test "set" do
assert JSONPointer.set(%{"a" => 1}, "/a", 2) == {:ok, %{"a" => 2}, 1}
assert JSONPointer.set(%{"a" => %{"b" => 2}}, "/a/b", 3) == {:ok, %{"a" => %{"b" => 3}}, 2}
assert JSONPointer.set(%{}, "/a", 1) == {:ok, %{"a" => 1}, nil}
assert JSONPointer.set(%{"a" => 1}, "/a", 6) == {:ok, %{"a" => 6}, 1}
assert JSONPointer.set(%{}, "/a/b", 2) == {:ok, %{"a" => %{"b" => 2}}, nil}
assert JSONPointer.set([], "/0", "first") == {:ok, ["first"], nil}
assert JSONPointer.set([], "/1", "second") == {:ok, [nil, "second"], nil}
assert JSONPointer.set([], "/0/test", "prudent") == {:ok, [%{"test" => "prudent"}], nil}
end
test "set empty array" do
assert JSONPointer.set(%{}, "/0/test/0", "expected") ==
{:ok, %{"0" => %{"test" => ["expected"]}}, nil}
assert JSONPointer.set([], "/0/test/1", "expected") ==
{:ok, [%{"test" => [nil, "expected"]}], nil}
end
test "set with /-" do
assert JSONPointer.set([1, 2], "/-", "three") == {:ok, [1, 2, "three"], nil}
assert JSONPointer.set(%{}, "/f/g/h/foo/-", "four") ==
{:ok, %{"f" => %{"g" => %{"h" => %{"foo" => ["four"]}}}}, nil}
assert JSONPointer.set([], "/1/-", "five") == {:ok, [nil, ["five"]], nil}
assert JSONPointer.set(%{"a" => 1}, "/-", "six") == {:ok, %{"a" => 1, "-" => "six"}, nil}
assert JSONPointer.set([], "/-", "seven") == {:ok, ["seven"], nil}
assert JSONPointer.set(%{}, "/-", "eight") == {:ok, %{"-" => "eight"}, nil}
assert JSONPointer.set(%{"f" => %{}}, "/f/-", "nine") ==
{:ok, %{"f" => %{"-" => "nine"}}, nil}
end
test "set using wildcard" do
assert JSONPointer.set(book_store_data(), "/store/book/**/author", "unknown") ==
{:ok,
%{
"store" => %{
"bicycle" => %{"color" => "red", "price" => 19.95},
"book" => [
%{
"author" => "unknown",
"category" => "reference",
"price" => 8.95,
"title" => "Sayings of the Century"
},
%{
"author" => "unknown",
"category" => "fiction",
"price" => 12.99,
"title" => "Sword of Honour"
},
%{
"author" => "unknown",
"category" => "fiction",
"isbn" => "0-553-21311-3",
"price" => 8.99,
"title" => "Moby Dick"
},
%{
"author" => "unknown",
"category" => "fiction",
"isbn" => "0-395-19395-8",
"price" => 22.99,
"title" => "The Lord of the Rings"
}
]
}
}, nil}
# using a wildcard to replace all instances within a list
assert JSONPointer.set(book_store_data(), "/store/book/**", %{"status" => "recalled"}) ==
{:ok,
%{
"store" => %{
"bicycle" => %{"color" => "red", "price" => 19.95},
"book" => [
%{"status" => "recalled"},
%{"status" => "recalled"},
%{"status" => "recalled"},
%{"status" => "recalled"}
]
}
}, nil}
assert JSONPointer.set(book_store_data(), "/store/book/**/price", 5.99) ==
{:ok,
%{
"store" => %{
"bicycle" => %{"color" => "red", "price" => 19.95},
"book" => [
%{
"author" => "Nigel Rees",
"category" => "reference",
"price" => 5.99,
"title" => "Sayings of the Century"
},
%{
"author" => "Evelyn Waugh",
"category" => "fiction",
"price" => 5.99,
"title" => "Sword of Honour"
},
%{
"author" => "Herman Melville",
"category" => "fiction",
"isbn" => "0-553-21311-3",
"price" => 5.99,
"title" => "Moby Dick"
},
%{
"author" => "J. R. R. Tolkien",
"category" => "fiction",
"isbn" => "0-395-19395-8",
"price" => 5.99,
"title" => "The Lord of the Rings"
}
]
}
}, nil}
assert JSONPointer.set(book_store_data(), "/store/**/price", 34.95) ==
{:ok,
%{
"store" => %{
"bicycle" => %{"color" => "red", "price" => 34.95},
"book" => [
%{
"author" => "Nigel Rees",
"category" => "reference",
"price" => 34.95,
"title" => "Sayings of the Century"
},
%{
"author" => "Evelyn Waugh",
"category" => "fiction",
"price" => 34.95,
"title" => "Sword of Honour"
},
%{
"author" => "Herman Melville",
"category" => "fiction",
"isbn" => "0-553-21311-3",
"price" => 34.95,
"title" => "Moby Dick"
},
%{
"author" => "J. R. R. Tolkien",
"category" => "fiction",
"isbn" => "0-395-19395-8",
"price" => 34.95,
"title" => "The Lord of the Rings"
}
]
}
}, nil}
end
end
describe "add" do
test "add to list" do
assert JSONPointer.add(%{"foo" => ["bar", "baz"]}, "/foo/1", "qux") ==
{:ok, %{"foo" => ["bar", "qux", "baz"]}, ["bar", "baz"] }
# out of bounds (upper)
assert JSONPointer.add(%{"bar" => [1, 2]}, "/bar/8", "5") ==
{:error, "index out of bounds: 8", [1, 2]}
# out of bounds (lower)
assert JSONPointer.add(%{"bar" => [1, 2]}, "/bar/-1", "5") ==
{:error, "index out of bounds: -1", [1, 2]}
# 0 can be an array index or object element name
assert JSONPointer.add(%{"foo" => 1}, "/0", "bar") ==
{:ok, %{"foo" => 1, "0" => "bar"}, nil}
assert JSONPointer.add(["foo"], "/1", "bar") ==
{:ok, ["foo", "bar"], ["foo"] }
# object operation on array target
assert JSONPointer.add(["foo", "baz"], "/bar", 42) ==
{:error, "invalid index: bar", ["foo", "baz"]}
assert JSONPointer.add(["foo", "sil"], "/1", ["bar", "baz"]) ==
{:ok, ["foo", ["bar", "baz"], "sil"], ["foo", "sil"]}
# add with bad number
assert JSONPointer.add(["foo", "sil"], "/1e0", "bar") ==
{:error, "invalid index: 1e0", ["foo", "sil"]}
assert JSONPointer.add(%{"foo" => ["bar"]}, "/foo/-", ["abc", "def"]) ==
{:ok, %{"foo" => ["bar", ["abc", "def"]]}, nil}
end
test "add to map" do
assert JSONPointer.add(%{"foo" => "bar"}, "/baz", "qux") ==
{:ok, %{"baz" => "qux", "foo" => "bar"}, nil}
# replaces existing field
assert JSONPointer.add(%{"foo" => nil}, "/foo", 1) ==
{:ok, %{"foo" => 1}, nil}
# top level object
assert JSONPointer.add(%{}, "/foo", 1) ==
{:ok, %{"foo" => 1}, nil}
assert JSONPointer.add(%{}, "/", 1) ==
{:ok, %{"" => 1}, nil}
# add to non-existent target
assert JSONPointer.add(%{"foo" => "bar"}, "/baz/bat", "qux") ==
{:error, "path /baz does not exist", %{"foo" => "bar"}}
# replacing root is possible with add
assert JSONPointer.add(%{"foo" => "bar"}, "", %{"baz" => "qux"}) ==
{:ok, %{"baz" => "qux"}, %{"foo" => "bar"}}
assert JSONPointer.add(%{"baz" => [%{"qux" => "hello"}], "foo" =>1}, "/baz/0/foo", "world") ==
{:ok, %{"baz" => [%{"foo"=>"world","qux" => "hello"}], "foo" =>1}, [%{"qux" => "hello"}] }
doc = [1,2,[3,[4,5]]]
assert JSONPointer.add!( doc, "/2/1/-", %{"foo" => ["bar","baz"]} ) ==
[1,2,[3,[4,5, %{"foo" => ["bar","baz"]}]]]
end
end
describe "remove" do
test "remove" do
assert JSONPointer.remove(%{"example" => "hello"}, "/example") == {:ok, %{}, "hello"}
assert JSONPointer.remove(%{"a" => %{"b" => 5}}, "/a/b") == {:ok, %{"a" => %{}}, 5}
assert JSONPointer.remove(%{"a" => %{"b" => %{"c" => "discard"}}}, "/a/b/c") ==
{:ok, %{"a" => %{"b" => %{}}}, "discard"}
assert JSONPointer.remove(%{"a" => %{"b" => %{"c" => "discard"}}}, "/a") ==
{:ok, %{}, %{"b" => %{"c" => "discard"}}}
assert JSONPointer.remove(["alpha", "beta"], "/0") == {:ok, ["beta"], "alpha"}
assert JSONPointer.remove(["alpha", %{"beta" => ["c", "d"]}], "/1/beta/0") ==
{:ok, ["alpha", %{"beta" => ["d"]}], "c"}
end
test "remove using wildcard" do
obj = %{
"a" => %{"b" => 2},
"c" => [%{"d" => 3}, %{"e" => 4}],
"f" => 5,
"g" => [%{"d" => 6}, %{"e" => 7}]
}
assert JSONPointer.remove(obj, "/a/**") ==
{:ok,
%{
"a" => nil,
"c" => [%{"d" => 3}, %{"e" => 4}],
"f" => 5,
"g" => [%{"d" => 6}, %{"e" => 7}]
}, %{"b" => 2}}
end
end
describe "de/hydrate" do
test "dehydrate" do
tests = [
{
%{},
# empty result
[]
},
{
[],
# empty result
[]
},
{
%{"a" => 1},
[{"/a", 1}]
},
{
%{"a" => 1, "b" => true},
[{"/a", 1}, {"/b", true}]
},
{
%{"a" => 1, "b" => %{"c" => "nice"}},
[{"/a", 1}, {"/b/c", "nice"}]
},
{
["alpha", "beta"],
[{"/0", "alpha"}, {"/1", "beta"}]
},
{
%{"a" => %{"b" => ["c", "d"]}},
[{"/a/b/0", "c"}, {"/a/b/1", "d"}]
},
{
%{"a" => [10, %{"b" => 12.5}], "c" => 99},
[{"/a/0", 10}, {"/a/1/b", 12.5}, {"/c", 99}]
},
{
%{"a" => %{}, "b" => [], "c" => nil},
[{"/a", %{}}, {"/b", []}, {"/c", nil}]
},
{
%{
"" => 0,
"a/b" => 1,
"c%d" => 2,
"e^f" => 3,
"g|h" => 4,
"i\\j" => 5,
"k\"l" => 6,
" " => 7,
"m~n" => 8
},
[
{"/", 0},
{"/ ", 7},
{"/a~1b", 1},
{"/c%d", 2},
{"/e^f", 3},
{"/g|h", 4},
{"/i\\j", 5},
{"/k\"l", 6},
{"/m~0n", 8}
]
}
]
Enum.each(tests, fn {obj, expected_paths} ->
assert JSONPointer.dehydrate(obj) == {:ok, expected_paths}
end)
end
test "hydrate" do
tests = [
{
%{},
[],
%{}
},
{
%{},
[{"/a/b/1", 1}],
%{"a" => %{"b" => [nil, 1]}}
},
{
[],
[{"/1/a", true}],
[nil, %{"a" => true}]
},
{
[],
[{"/a", 14.5}],
# because of the attempt to set a key on an array
{:error, "invalid index: a"}
},
{
%{},
[{"/4", false}],
[nil, nil, nil, nil, false]
}
]
Enum.each(tests, fn {src, paths, expected} ->
expected =
case expected do
{:error, _} -> expected
_ -> {:ok, expected}
end
assert JSONPointer.hydrate(src, paths) == expected
end)
end
end
describe "merge" do
test "merge" do
src = %{
"bla" => %{"test" => "expected"},
"foo" => [["hello"]],
"abc" => "bla"
}
assert JSONPointer.merge(["foo", "bar"], %{"a" => false}) ==
{:error, "invalid index: a"}
assert JSONPointer.merge(%{"a" => false}, %{"c" => true, "b" => 13}) ==
{:ok, %{"a" => false, "b" => 13, "c" => true}}
assert JSONPointer.merge(src, %{"bla" => %{"alpha" => "beta"}}) ==
{:ok,
%{
"bla" => %{"alpha" => "beta", "test" => "expected"},
"foo" => [["hello"]],
"abc" => "bla"
}}
assert JSONPointer.merge(src, %{"foo" => [10, %{"a" => true, "b" => false}], "abc" => 30}) ==
{:ok,
%{
"abc" => 30,
"bla" => %{"test" => "expected"},
"foo" => [10, %{"a" => true, "b" => false}]
}}
assert JSONPointer.merge(src, %{"foo" => nil, "bla" => nil}) ==
{:ok, %{"abc" => "bla", "bla" => nil, "foo" => nil}}
end
end
describe "has" do
test "has" do
obj = %{
"bla" => %{"test" => "expected"},
"foo" => [["hello"]],
"abc" => "bla"
}
assert JSONPointer.has?(obj, "/bla") == true
assert JSONPointer.has?(obj, "/foo/0/0") == true
assert JSONPointer.has?(obj, "/bla/test") == true
assert JSONPointer.has?(obj, "/not-existing") == false
assert JSONPointer.has?(obj, "/not-existing/bla") == false
assert JSONPointer.has?(obj, "/test/1/bla") == false
assert JSONPointer.has?(obj, "/0") == false
assert JSONPointer.has?([], "/2") == false
assert JSONPointer.has?([], "/2/3") == false
end
end
describe "test" do
test "test" do
obj = %{
"fridge" => %{
"milk" => "semi skimmed",
"eggs" => 5,
"salad" => ["avocado", "spinach", "tomatoes"]
}
}
assert JSONPointer.test(obj, "/fridge/milk", "semi skimmed") == {:ok, obj}
assert JSONPointer.test(obj, "/fridge/milk", "skimmed") == {:error, "string not equivalent"}
assert JSONPointer.test(obj, "/fridge/eggs", "5") == {:error, "number is not equal to string"}
assert JSONPointer.test(obj, "/fridge/salad", ["avocado", "spinach", "tomatoes"]) ==
{:ok, obj}
assert JSONPointer.test(obj, "/fridge/salad", ["spinach", "tomatoes", "avocado"]) ==
{:error, "not equal"}
assert JSONPointer.test(obj, "/", obj) == {:ok, obj}
assert JSONPointer.test(%{"/" => 9, "~1" => 10}, "/~01", 10) ==
{:ok, %{"/" => 9, "~1" => 10}}
end
end
describe "transform" do
test "transform" do
input = ~s({
"dt": 1520942400,
"temp": {
"day": 11
},
"pressure": 1005.47,
"humidity": 100,
"weather": [
{
"main": "few clouds"
}
],
"speed": 3.12,
"deg": 272,
"clouds": 12
}) |> Jason.decode!()
time = :os.system_time(:seconds)
result =
JSONPointer.transform(input, [
{"/temp/day", "/temp"},
{"/weather/0/main", "/description"},
{"/created_at", fn -> time end},
{"/dt", "/datetime",
fn val -> val |> DateTime.from_unix!() |> DateTime.to_iso8601() end}
])
assert result ==
{:ok,
%{
"created_at" => time,
"datetime" => "2018-03-13T12:00:00Z",
"description" => "few clouds",
"temp" => 11
}}
end
end
describe "utils" do
test "parse" do
assert JSONPointer.Utils.parse("") == {:ok, []}
assert JSONPointer.Utils.parse("invalid") == {:error, "invalid json pointer", "invalid"}
assert JSONPointer.Utils.parse("/some/where/over") == {:ok, ["some", "where", "over"]}
assert JSONPointer.Utils.parse("/hello~0bla/test~1bla") == {:ok, ["hello~bla", "test/bla"]}
assert JSONPointer.Utils.parse("/~2") == {:ok, ["**"]}
assert JSONPointer.Utils.parse("/initial/**/**") == {:ok, ["initial", "**", "**"]}
assert JSONPointer.Utils.parse(["some", "where", "over"]) ==
{:ok, ["some", "where", "over"]}
assert JSONPointer.Utils.parse("/c%d") == {:ok, ["c%d"]}
assert JSONPointer.Utils.parse("/~01") == {:ok, ["~1"]}
end
end
end
| 33.451095
| 106
| 0.386183
|
93d495908536dcef50524fb6ce187a64d8f18cbe
| 1,450
|
ex
|
Elixir
|
lib/ex_oapi/parser/context/paths/paths_map.ex
|
mnussbaumer/ex_oapi
|
f5eb610283a7f92a69e6266effc0dc4e2c497b61
|
[
"MIT"
] | null | null | null |
lib/ex_oapi/parser/context/paths/paths_map.ex
|
mnussbaumer/ex_oapi
|
f5eb610283a7f92a69e6266effc0dc4e2c497b61
|
[
"MIT"
] | null | null | null |
lib/ex_oapi/parser/context/paths/paths_map.ex
|
mnussbaumer/ex_oapi
|
f5eb610283a7f92a69e6266effc0dc4e2c497b61
|
[
"MIT"
] | null | null | null |
defmodule ExOAPI.Parser.V3.Context.Paths.Map do
@behaviour Ecto.Type
import Ecto.Changeset, only: [apply_action: 2]
alias ExOAPI.Parser.V3.Context
@type t() :: %{String.t() => Context.Paths.t()}
@ex_oapi_paths ExOAPI.Parser.ex_oapi_paths()
@impl Ecto.Type
def type, do: :map
@impl Ecto.Type
def load(data), do: cast(data)
@impl Ecto.Type
def cast(data) when is_map(data) do
paths = Process.get(@ex_oapi_paths, false)
Enum.reduce_while(data, {:ok, %{}}, fn {k, v}, {_, acc} ->
case Context.Paths.check_path(k, paths) do
false ->
{:cont, {:ok, acc}}
path_info ->
with changeset <- Context.Paths.map_cast(v, {k, path_info}),
{:ok, applied} <- apply_action(changeset, :insert) do
{:cont, {:ok, Map.put(acc, k, applied)}}
else
{:error, changeset} ->
{:halt, {:error, {k, v, changeset}}}
end
end
end)
|> case do
{:ok, _} = ok ->
ok
{:error, {k, v, changeset}} ->
raise "Error casting Schema: #{inspect(k)} -> #{inspect(v)} resulting in #{inspect(changeset)}"
end
end
def cast(_), do: :error
@impl Ecto.Type
def dump(data) when is_map(data), do: {:ok, data}
def dump(nil), do: {:ok, %{}}
def dump(_), do: :error
@impl Ecto.Type
def equal?(a, a), do: true
def equal?(_, _), do: false
@impl Ecto.Type
def embed_as(_), do: :self
end
| 24.166667
| 103
| 0.564138
|
93d4b29eacf1153ecf92ae59fe0a029b97936a11
| 1,040
|
ex
|
Elixir
|
dummy/test/support/conn_case.ex
|
zgohr/turbo_ecto
|
2467be3f0923193349c08d18061efbc952523b21
|
[
"MIT"
] | 4
|
2019-01-23T14:10:31.000Z
|
2019-05-14T15:41:11.000Z
|
dummy/test/support/conn_case.ex
|
zgohr/turbo_ecto
|
2467be3f0923193349c08d18061efbc952523b21
|
[
"MIT"
] | 35
|
2019-02-19T02:11:33.000Z
|
2021-09-01T07:09:42.000Z
|
dummy/test/support/conn_case.ex
|
zgohr/turbo_ecto
|
2467be3f0923193349c08d18061efbc952523b21
|
[
"MIT"
] | 4
|
2019-11-03T16:11:39.000Z
|
2022-03-05T14:34:23.000Z
|
defmodule DummyWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias DummyWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint DummyWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Dummy.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Dummy.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.666667
| 67
| 0.715385
|
93d4cba2d9fef8c2d0240eb2dffe83f3f1251d72
| 736
|
ex
|
Elixir
|
lib/bmp280/measurement.ex
|
dkuku/bmp280
|
e7cb8fcef0043a354a9c2dde0946ab1d033c0b59
|
[
"Apache-2.0"
] | 11
|
2020-09-17T08:03:11.000Z
|
2021-04-28T16:20:13.000Z
|
lib/bmp280/measurement.ex
|
dkuku/bmp280
|
e7cb8fcef0043a354a9c2dde0946ab1d033c0b59
|
[
"Apache-2.0"
] | 13
|
2021-01-31T23:08:26.000Z
|
2021-03-27T23:08:42.000Z
|
lib/bmp280/measurement.ex
|
dkuku/bmp280
|
e7cb8fcef0043a354a9c2dde0946ab1d033c0b59
|
[
"Apache-2.0"
] | 3
|
2021-09-05T08:48:27.000Z
|
2021-10-21T17:14:43.000Z
|
defmodule BMP280.Measurement do
@moduledoc """
One sensor measurement report
The temperature, pressure and relative humidity measurements are computed
directly from the sensor. All other values are derived.
"""
defstruct [
:temperature_c,
:pressure_pa,
:altitude_m,
humidity_rh: :unknown,
dew_point_c: :unknown,
gas_resistance_ohms: :unknown,
timestamp_ms: :unknown
]
@type t :: %__MODULE__{
temperature_c: number(),
pressure_pa: number(),
altitude_m: number(),
humidity_rh: number() | :unknown,
dew_point_c: number() | :unknown,
gas_resistance_ohms: number() | :unknown,
timestamp_ms: number() | :unknown
}
end
| 26.285714
| 75
| 0.639946
|
93d4e41f1f4c34b6bd95e0ff38a4320eb0055bf4
| 343
|
ex
|
Elixir
|
lib/supabase_surface/components/icons/icon_pen_tool.ex
|
treebee/supabase-surface
|
5a184ca92323c085dd81e2fc8aa8c10367f2382e
|
[
"Apache-2.0"
] | 5
|
2021-06-08T08:02:43.000Z
|
2022-02-09T23:13:46.000Z
|
lib/supabase_surface/components/icons/icon_pen_tool.ex
|
treebee/supabase-surface
|
5a184ca92323c085dd81e2fc8aa8c10367f2382e
|
[
"Apache-2.0"
] | null | null | null |
lib/supabase_surface/components/icons/icon_pen_tool.ex
|
treebee/supabase-surface
|
5a184ca92323c085dd81e2fc8aa8c10367f2382e
|
[
"Apache-2.0"
] | 1
|
2021-07-14T05:20:31.000Z
|
2021-07-14T05:20:31.000Z
|
defmodule SupabaseSurface.Components.Icons.IconPenTool do
use SupabaseSurface.Components.Icon
@impl true
def render(assigns) do
icon_size = IconContainer.get_size(assigns.size)
~F"""
<IconContainer assigns={assigns}>
{Feathericons.pen_tool(width: icon_size, height: icon_size)}
</IconContainer>
"""
end
end
| 22.866667
| 66
| 0.720117
|
93d50be94a8983fea6d95779950bc6e036f042ac
| 765
|
ex
|
Elixir
|
lib/hl7/2.5/segments/ub2.ex
|
calvinb/elixir-hl7
|
5e953fa11f9184857c0ec4dda8662889f35a6bec
|
[
"Apache-2.0"
] | null | null | null |
lib/hl7/2.5/segments/ub2.ex
|
calvinb/elixir-hl7
|
5e953fa11f9184857c0ec4dda8662889f35a6bec
|
[
"Apache-2.0"
] | null | null | null |
lib/hl7/2.5/segments/ub2.ex
|
calvinb/elixir-hl7
|
5e953fa11f9184857c0ec4dda8662889f35a6bec
|
[
"Apache-2.0"
] | null | null | null |
defmodule HL7.V2_5.Segments.UB2 do
@moduledoc false
require Logger
alias HL7.V2_5.{DataTypes}
use HL7.Segment,
fields: [
segment: nil,
set_id_ub2: nil,
co_insurance_days_9: nil,
condition_code_24_30: nil,
covered_days_7: nil,
non_covered_days_8: nil,
value_amount_code: DataTypes.Uvc,
occurrence_code_date_32_35: DataTypes.Ocd,
occurrence_span_code_dates_36: DataTypes.Osp,
ub92_locator_2_state: nil,
ub92_locator_11_state: nil,
ub92_locator_31_national: nil,
document_control_number: nil,
ub92_locator_49_national: nil,
ub92_locator_56_state: nil,
ub92_locator_57_national: nil,
ub92_locator_78_state: nil,
special_visit_count: nil
]
end
| 26.37931
| 51
| 0.701961
|
93d54126e7cfa6887f786eb9b205395fd768a186
| 698
|
ex
|
Elixir
|
clients/elixir/generated/lib/swaggy_jenkins/model/free_style_projecthealth_report.ex
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 23
|
2017-08-01T12:25:26.000Z
|
2022-01-25T03:44:11.000Z
|
clients/elixir/generated/lib/swaggy_jenkins/model/free_style_projecthealth_report.ex
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 35
|
2017-06-14T03:28:15.000Z
|
2022-02-14T10:25:54.000Z
|
clients/elixir/generated/lib/swaggy_jenkins/model/free_style_projecthealth_report.ex
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 11
|
2017-08-31T19:00:20.000Z
|
2021-12-19T12:04:12.000Z
|
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule SwaggyJenkins.Model.FreeStyleProjecthealthReport do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"description",
:"iconClassName",
:"iconUrl",
:"score",
:"_class"
]
@type t :: %__MODULE__{
:"description" => String.t,
:"iconClassName" => String.t,
:"iconUrl" => String.t,
:"score" => integer(),
:"_class" => String.t
}
end
defimpl Poison.Decoder, for: SwaggyJenkins.Model.FreeStyleProjecthealthReport do
def decode(value, _options) do
value
end
end
| 20.529412
| 91
| 0.65616
|
93d5573210d9efd07f64a8897c761456507547e7
| 4,280
|
exs
|
Elixir
|
test/services/translations_renderer_test.exs
|
paulelliott/accent
|
fabd0d2768088adf780317c6e44fcabcccadba11
|
[
"BSD-3-Clause"
] | 1
|
2020-07-01T16:08:34.000Z
|
2020-07-01T16:08:34.000Z
|
test/services/translations_renderer_test.exs
|
paulelliott/accent
|
fabd0d2768088adf780317c6e44fcabcccadba11
|
[
"BSD-3-Clause"
] | 6
|
2021-03-11T07:37:48.000Z
|
2022-02-13T21:10:33.000Z
|
test/services/translations_renderer_test.exs
|
doc-ai/accent
|
e337e16f3658cc0728364f952c0d9c13710ebb06
|
[
"BSD-3-Clause"
] | 1
|
2020-05-29T21:47:35.000Z
|
2020-05-29T21:47:35.000Z
|
defmodule AccentTest.TranslationsRenderer do
use Accent.RepoCase
alias Accent.{
Document,
Language,
ProjectCreator,
Repo,
Translation,
TranslationsRenderer,
User
}
@user %User{email: "test@test.com"}
setup do
user = Repo.insert!(@user)
language = Repo.insert!(%Language{name: "English", slug: Ecto.UUID.generate()})
{:ok, project} = ProjectCreator.create(params: %{main_color: "#f00", name: "My project", language_id: language.id}, user: user)
revision =
project
|> Repo.preload(:revisions)
|> Map.get(:revisions)
|> hd()
|> Repo.preload(:language)
{:ok, [project: project, revision: revision]}
end
test "render json with filename", %{project: project, revision: revision} do
document = Repo.insert!(%Document{project_id: project.id, path: "my-test", format: "json"})
translation =
%Translation{
key: "a",
proposed_text: "B",
corrected_text: "A",
revision_id: revision.id,
document_id: document.id
}
|> Repo.insert!()
%{render: render} =
TranslationsRenderer.render(%{
master_translations: [],
master_revision: revision,
translations: [translation],
document: document,
language: revision.language
})
expected_render = """
{
"a": "A"
}
"""
assert render == expected_render
end
test "render json with runtime error", %{project: project, revision: revision} do
document = Repo.insert!(%Document{project_id: project.id, path: "my-test", format: "json"})
translations =
[
%Translation{
key: "a.nested.foo",
proposed_text: "B",
corrected_text: "A",
revision_id: revision.id,
document_id: document.id
},
%Translation{
key: "a.nested",
proposed_text: "C",
corrected_text: "D",
revision_id: revision.id,
document_id: document.id
}
]
|> Enum.map(&Repo.insert!/1)
%{render: render} =
TranslationsRenderer.render(%{
master_translations: [],
master_revision: revision,
translations: translations,
document: document,
language: revision.language
})
assert render == ""
end
test "render rails with locale", %{project: project, revision: revision} do
document = Repo.insert!(%Document{project_id: project.id, path: "my-test", format: "rails_yml"})
translation =
%Translation{
key: "a",
proposed_text: "A",
corrected_text: "A",
revision_id: revision.id,
document_id: document.id
}
|> Repo.insert!()
%{render: render} =
TranslationsRenderer.render(%{
master_translations: [],
master_revision: revision,
translations: [translation],
document: document,
language: %Language{slug: "fr"}
})
expected_render = """
"fr":
"a": "A"
"""
assert render == expected_render
end
test "render xliff and revision overrides on source revision", %{project: project, revision: revision} do
revision = Repo.update!(Ecto.Changeset.change(revision, %{slug: "testtest"}))
document = Repo.insert!(%Document{project_id: project.id, path: "my-test", format: "xliff_1_2"})
translation =
%Translation{
key: "a",
proposed_text: "A",
corrected_text: "A",
revision_id: revision.id,
document_id: document.id
}
|> Repo.insert!()
%{render: render} =
TranslationsRenderer.render(%{
master_translations: [
%Translation{
key: "a",
corrected_text: "master A"
}
],
master_revision: revision,
translations: [translation],
document: document,
language: %Language{slug: "fr"}
})
expected_render = """
<file original=\"my-test\" datatype=\"plaintext\" source-language=\"testtest\" target-language=\"fr\">
<body>
<trans-unit id=\"a\">
<source>master A</source>
<target>A</target>
</trans-unit>
</body>
</file>
"""
assert render == expected_render
end
end
| 25.47619
| 131
| 0.576402
|
93d56c32d17ec6958d989fe089aca2a878681d2e
| 8,181
|
ex
|
Elixir
|
test/support/adapter_case.ex
|
warmwaffles/file_store
|
6b6f4cf4ef036b616915ce0dffd5de05e0b021de
|
[
"MIT"
] | null | null | null |
test/support/adapter_case.ex
|
warmwaffles/file_store
|
6b6f4cf4ef036b616915ce0dffd5de05e0b021de
|
[
"MIT"
] | null | null | null |
test/support/adapter_case.ex
|
warmwaffles/file_store
|
6b6f4cf4ef036b616915ce0dffd5de05e0b021de
|
[
"MIT"
] | null | null | null |
defmodule FileStore.AdapterCase do
@moduledoc false
use ExUnit.CaseTemplate
@tmp Path.join(System.tmp_dir!(), "file_store")
setup do
File.rm_rf!(@tmp)
File.mkdir!(@tmp)
{:ok, tmp: @tmp}
end
using do
# credo:disable-for-this-file Credo.Check.Refactor.LongQuoteBlocks
quote location: :keep do
import FileStore.AdapterCase
describe "write/4 conformance" do
test "writes a file", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert {:ok, "bar"} = FileStore.read(store, "foo")
end
test "overwrites a file", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert {:ok, "bar"} = FileStore.read(store, "foo")
assert :ok = FileStore.write(store, "foo", "baz")
assert {:ok, "baz"} = FileStore.read(store, "foo")
end
end
describe "read/2 conformance" do
test "reads a file", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert {:ok, "bar"} = FileStore.read(store, "foo")
end
test "errors when file does not exist", %{store: store} do
assert {:error, _} = FileStore.read(store, "does-not-exist")
end
end
describe "upload/3 conformance" do
test "uploads a file", %{store: store} do
bar = write("bar.txt", "bar")
assert :ok = FileStore.upload(store, bar, "foo")
assert {:ok, "bar"} = FileStore.read(store, "foo")
end
test "overwrites a file", %{store: store} do
bar = write("bar.txt", "bar")
baz = write("baz.txt", "baz")
assert :ok = FileStore.upload(store, bar, "foo")
assert {:ok, "bar"} = FileStore.read(store, "foo")
assert :ok = FileStore.upload(store, baz, "foo")
assert {:ok, "baz"} = FileStore.read(store, "foo")
end
test "fails when the source file is missing", %{store: store} do
assert {:error, _} = FileStore.upload(store, "doesnotexist.txt", "foo")
end
end
describe "download/3 conformance" do
test "downloads a file", %{store: store} do
download = join("download.txt")
assert :ok = FileStore.write(store, "foo", "bar")
assert :ok = FileStore.download(store, "foo", download)
assert File.read!(download) == "bar"
end
end
describe "stat/2 conformance" do
test "retrieves file info", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert {:ok, stat} = FileStore.stat(store, "foo")
assert stat.key == "foo"
assert stat.size == 3
assert stat.etag == "37b51d194a7513e45b56f6524f2d51f2"
end
test "fails when the file is missing", %{store: store} do
assert {:error, _} = FileStore.stat(store, "completegarbage")
end
end
describe "delete/2 conformance" do
test "deletes the file", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert :ok = FileStore.delete(store, "foo")
end
test "indicates success for non-existent keys", %{store: store} do
assert :ok = FileStore.delete(store, "non-existent")
assert :ok = FileStore.delete(store, "non/existent")
end
end
describe "delete_all/2 conformance" do
test "deletes all files", %{store: store} do
assert :ok = FileStore.write(store, "foo", "")
assert :ok = FileStore.write(store, "bar/buzz", "")
assert :ok = FileStore.delete_all(store)
assert {:error, _} = FileStore.stat(store, "foo")
assert {:error, _} = FileStore.stat(store, "bar/buzz")
end
test "deletes files under prefix", %{store: store} do
assert :ok = FileStore.write(store, "foo", "")
assert :ok = FileStore.write(store, "bar/buzz", "")
assert :ok = FileStore.write(store, "bar/baz", "")
assert :ok = FileStore.delete_all(store, prefix: "bar")
assert {:ok, _} = FileStore.stat(store, "foo")
assert {:error, _} = FileStore.stat(store, "bar/buzz")
assert {:error, _} = FileStore.stat(store, "bar/baz")
end
test "indicates success for non-existent keys", %{store: store} do
assert :ok = FileStore.delete_all(store, prefix: "non-existent")
end
end
describe "get_public_url/3 conformance" do
test "returns a URL", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert url = FileStore.get_public_url(store, "foo")
assert is_valid_url(url)
end
end
describe "get_signed_url/3 conformance" do
test "returns a URL", %{store: store} do
assert :ok = FileStore.write(store, "foo", "bar")
assert {:ok, url} = FileStore.get_signed_url(store, "foo")
assert is_valid_url(url)
end
end
describe "list!/2 conformance" do
test "lists keys in the store", %{store: store} do
assert :ok = FileStore.write(store, "foo", "")
assert "foo" in Enum.to_list(FileStore.list!(store))
end
test "lists nested keys in the store", %{store: store} do
assert :ok = FileStore.write(store, "foo/bar", "")
assert "foo/bar" in Enum.to_list(FileStore.list!(store))
end
test "lists keys matching prefix", %{store: store} do
assert :ok = FileStore.write(store, "bar", "")
assert :ok = FileStore.write(store, "foo/bar", "")
keys = Enum.to_list(FileStore.list!(store, prefix: "foo"))
refute "bar" in keys
assert "foo/bar" in keys
end
end
describe "copy/3 conformance" do
test "copies a file", %{store: store} do
:ok = FileStore.write(store, "foo", "test")
assert :ok = FileStore.copy(store, "foo", "bar")
assert {:ok, "test"} = FileStore.read(store, "foo")
end
test "fails to copy a non existing file", %{store: store} do
assert {:error, _} = FileStore.copy(store, "foo", "bar")
assert {:error, _} = FileStore.stat(store, "bar")
end
test "copy replaces existing file", %{store: store} do
:ok = FileStore.write(store, "foo", "test")
:ok = FileStore.write(store, "bar", "i exist")
assert :ok = FileStore.copy(store, "foo", "bar")
assert {:ok, "test"} = FileStore.read(store, "bar")
end
end
describe "rename/3 conformance" do
test "renames a file", %{store: store} do
:ok = FileStore.write(store, "foo", "test")
assert :ok = FileStore.rename(store, "foo", "bar")
assert {:error, _} = FileStore.stat(store, "foo")
assert {:ok, _} = FileStore.stat(store, "bar")
end
test "fails to rename a non existing file", %{store: store} do
assert {:error, _} = FileStore.rename(store, "foo", "bar")
assert {:error, _} = FileStore.stat(store, "bar")
end
test "rename replaces existing file", %{store: store} do
:ok = FileStore.write(store, "foo", "test")
:ok = FileStore.write(store, "bar", "i exist")
assert :ok = FileStore.rename(store, "foo", "bar")
assert {:error, _} = FileStore.stat(store, "foo")
assert {:ok, _} = FileStore.stat(store, "bar")
end
end
end
end
def join(name) do
Path.join(@tmp, name)
end
def write(name, data) do
path = join(name)
File.write!(path, data)
path
end
def is_valid_url(value) do
case URI.parse(value) do
%URI{scheme: nil} -> false
%URI{host: nil} -> false
%URI{scheme: scheme} -> scheme =~ ~r"^https?$"
end
end
def get_query(url, param) do
url
|> URI.parse()
|> Map.fetch!(:query)
|> URI.decode_query()
|> Map.fetch!(param)
end
def omit_query(url) do
url
|> URI.parse()
|> Map.put(:query, nil)
|> URI.to_string()
end
end
| 33.121457
| 81
| 0.561912
|
93d571ebbf968ab9a14c961ef42e37db338bccf8
| 7,172
|
ex
|
Elixir
|
lib/ex_unit/lib/ex_unit/case.ex
|
jbcrail/elixir
|
f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb
|
[
"Apache-2.0"
] | 1
|
2015-02-23T00:01:48.000Z
|
2015-02-23T00:01:48.000Z
|
lib/ex_unit/lib/ex_unit/case.ex
|
jbcrail/elixir
|
f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb
|
[
"Apache-2.0"
] | null | null | null |
lib/ex_unit/lib/ex_unit/case.ex
|
jbcrail/elixir
|
f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb
|
[
"Apache-2.0"
] | null | null | null |
defmodule ExUnit.Case do
@moduledoc """
Sets up an ExUnit test case.
This module must be used in other modules as a way to configure
and prepare them for testing.
When used, it accepts the following options:
* :async - configure Elixir to run that specific test case in parallel with
others. Must be used for performance when your test cases do not change
any global state.
This module automatically includes all callbacks defined in
`ExUnit.Callbacks`. See that module's documentation for more
information.
## Examples
defmodule AssertionTest do
# Use the module
use ExUnit.Case, async: true
# The `test` macro is imported by ExUnit.Case
test "always pass" do
assert true
end
end
## Context
All tests receive a context as an argument. The context is particularly
useful for sharing information between callbacks and tests:
defmodule KVTest do
use ExUnit.Case
setup do
{:ok, pid} = KV.start_link
{:ok, [pid: pid]}
end
test "stores key-values", context do
assert KV.put(context[:pid], :hello, :world) == :ok
assert KV.get(context[:pid], :hello) == :world
end
end
As the context is a map, it can be pattern matched on to extract
information:
test "stores key-values", %{pid: pid} do
assert KV.put(pid, :hello, :world) == :ok
assert KV.get(pid, :hello) == :world
end
## Tags
The context is used to pass information from the callbacks to
the test. In order to pass information from the test to the
callback, ExUnit provides tags.
By tagging a test, the tag value can be accessed in the context,
allowing the developer to customize the test. Let's see an
example:
defmodule FileTest do
# Changing directory cannot be async
use ExUnit.Case, async: false
setup context do
# Read the :cd tag value
if cd = context[:cd] do
prev_cd = File.cwd!
File.cd!(cd)
on_exit fn -> File.cd!(prev_cd) end
end
:ok
end
@tag cd: "fixtures"
test "reads utf-8 fixtures" do
File.read("hello")
end
end
In the example above, we have defined a tag called `:cd` that is
read in the setup callback to configure the working directory the
test is going to run on.
Tags are also very effective when used with case templates
(`ExUnit.CaseTemplate`) allowing callbacks in the case template
to customize the test behaviour.
Note a tag can be set in two different ways:
@tag key: value
@tag :key # equivalent to setting @tag key: true
If a tag is given more than once, the last value wins.
### Module tags
A tag can be set for all tests in a module by setting `@moduletag`:
@moduletag :external
If the same key is set via `@tag`, the `@tag` value has higher
precedence.
### Known tags
The following tags are set automatically by ExUnit and are
therefore reserved:
* `:case` - the test case module
* `:test` - the test name
* `:line` - the line on which the test was defined
* `:file` - the file on which the test was defined
The following tags customize how tests behaves:
* `:timeout` - customizes the test timeout in miliseconds (defaults to 30000)
## Filters
Tags can also be used to identify specific tests, which can then
be included or excluded using filters. The most common functionality
is to exclude some particular tests from running, which can be done
via `ExUnit.configure/1`:
# Exclude all external tests from running
ExUnit.configure(exclude: [external: true])
From now on, ExUnit will not run any test that has the `external` flag
set to true. This behaviour can be reversed with the `:include` option
which is usually passed through the command line:
mix test --include external:true
Run `mix help test` for more information on how to run filters via Mix.
Another use case for tags and filters is to exclude all tests that have
a particular tag by default, regardless of its value, and include only
a certain subset:
ExUnit.configure(exclude: :os, include: [os: :unix])
Keep in mind that all tests are included by default, so unless they are
excluded first, the `include` option has no effect.
"""
@doc false
defmacro __using__(opts) do
async = Keyword.get(opts, :async, false)
unless Process.whereis(ExUnit.Server) do
raise "cannot use ExUnit.Case without starting the ExUnit application, " <>
"please call ExUnit.start() or explicitly start the :ex_unit app"
end
quote do
unless Module.get_attribute(__MODULE__, :ex_unit_tests) do
if unquote(async) do
ExUnit.Server.add_async_case(__MODULE__)
else
ExUnit.Server.add_sync_case(__MODULE__)
end
Enum.each [:ex_unit_tests, :tag, :moduletag],
&Module.register_attribute(__MODULE__, &1, accumulate: true)
@before_compile ExUnit.Case
use ExUnit.Callbacks
end
import ExUnit.Callbacks
import ExUnit.Assertions
import ExUnit.Case
import ExUnit.DocTest
end
end
@doc """
Define a test with a string.
Provides a convenient macro that allows a test to be
defined with a string. This macro automatically inserts
the atom `:ok` as the last line of the test. That said,
a passing test always returns `:ok`, but, more importantly,
it forces Elixir to not tail call optimize the test and
therefore avoids hiding lines from the backtrace.
## Examples
test "true is equal to true" do
assert true == true
end
"""
defmacro test(message, var \\ quote(do: _), contents) do
contents =
case contents do
[do: block] ->
quote do
unquote(block)
:ok
end
_ ->
quote do
try(unquote(contents))
:ok
end
end
var = Macro.escape(var)
contents = Macro.escape(contents, unquote: true)
quote bind_quoted: binding do
test = :"test #{message}"
ExUnit.Case.__on_definition__(__ENV__, test)
def unquote(test)(unquote(var)), do: unquote(contents)
end
end
@doc false
defmacro __before_compile__(_) do
quote do
def __ex_unit__(:case) do
%ExUnit.TestCase{name: __MODULE__, tests: @ex_unit_tests}
end
end
end
@doc false
def __on_definition__(env, name) do
mod = env.module
tags = Module.get_attribute(mod, :tag) ++ Module.get_attribute(mod, :moduletag)
tags = tags |> normalize_tags |> Map.merge(%{line: env.line, file: env.file})
Module.put_attribute(mod, :ex_unit_tests,
%ExUnit.Test{name: name, case: mod, tags: tags})
Module.delete_attribute(mod, :tag)
end
defp normalize_tags(tags) do
Enum.reduce Enum.reverse(tags), %{}, fn
tag, acc when is_atom(tag) -> Map.put(acc, tag, true)
tag, acc when is_list(tag) -> Dict.merge(acc, tag)
end
end
end
| 28.12549
| 83
| 0.651422
|
93d62635464da4b4fb9e231d34018c09ab7bb1fc
| 3,294
|
ex
|
Elixir
|
clients/app_engine/lib/google_api/app_engine/v1/model/static_files_handler.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/app_engine/lib/google_api/app_engine/v1/model/static_files_handler.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/app_engine/lib/google_api/app_engine/v1/model/static_files_handler.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.AppEngine.V1.Model.StaticFilesHandler do
@moduledoc """
Files served directly to the user for a given URL, such as images, CSS stylesheets, or JavaScript source files. Static file handlers describe which files in the application directory are static files, and which URLs serve them.
## Attributes
* `applicationReadable` (*type:* `boolean()`, *default:* `nil`) - Whether files should also be uploaded as code data. By default, files declared in static file handlers are uploaded as static data and are only served to end users; they cannot be read by the application. If enabled, uploads are charged against both your code and static data storage resource quotas.
* `expiration` (*type:* `String.t`, *default:* `nil`) - Time a static file served by this handler should be cached by web proxies and browsers.
* `httpHeaders` (*type:* `map()`, *default:* `nil`) - HTTP headers to use for all responses from these URLs.
* `mimeType` (*type:* `String.t`, *default:* `nil`) - MIME type used to serve all files served by this handler.Defaults to file-specific MIME types, which are derived from each file's filename extension.
* `path` (*type:* `String.t`, *default:* `nil`) - Path to the static files matched by the URL pattern, from the application root directory. The path can refer to text matched in groupings in the URL pattern.
* `requireMatchingFile` (*type:* `boolean()`, *default:* `nil`) - Whether this handler should match the request if the file referenced by the handler does not exist.
* `uploadPathRegex` (*type:* `String.t`, *default:* `nil`) - Regular expression that matches the file paths for all files that should be referenced by this handler.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:applicationReadable => boolean(),
:expiration => String.t(),
:httpHeaders => map(),
:mimeType => String.t(),
:path => String.t(),
:requireMatchingFile => boolean(),
:uploadPathRegex => String.t()
}
field(:applicationReadable)
field(:expiration)
field(:httpHeaders, type: :map)
field(:mimeType)
field(:path)
field(:requireMatchingFile)
field(:uploadPathRegex)
end
defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.StaticFilesHandler do
def decode(value, options) do
GoogleApi.AppEngine.V1.Model.StaticFilesHandler.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.StaticFilesHandler do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 50.676923
| 370
| 0.722222
|
93d62c0c1defc81269ae06e7706d91b13d1b8da7
| 1,730
|
ex
|
Elixir
|
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/update_release_request.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | 1
|
2018-12-03T23:43:10.000Z
|
2018-12-03T23:43:10.000Z
|
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/update_release_request.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
clients/firebase_rules/lib/google_api/firebase_rules/v1/model/update_release_request.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.FirebaseRules.V1.Model.UpdateReleaseRequest do
@moduledoc """
The request for FirebaseRulesService.UpdateReleasePatch.
## Attributes
* `release` (*type:* `GoogleApi.FirebaseRules.V1.Model.Release.t`, *default:* `nil`) - `Release` to update.
* `updateMask` (*type:* `String.t`, *default:* `nil`) - Specifies which fields to update.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:release => GoogleApi.FirebaseRules.V1.Model.Release.t(),
:updateMask => String.t()
}
field(:release, as: GoogleApi.FirebaseRules.V1.Model.Release)
field(:updateMask)
end
defimpl Poison.Decoder, for: GoogleApi.FirebaseRules.V1.Model.UpdateReleaseRequest do
def decode(value, options) do
GoogleApi.FirebaseRules.V1.Model.UpdateReleaseRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.FirebaseRules.V1.Model.UpdateReleaseRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.6
| 111
| 0.739884
|
93d65b440c62c984d59350dde1df571d1a4399b4
| 1,111
|
ex
|
Elixir
|
test/support/channel_case.ex
|
angelo-moreira/topflow
|
00946c317aba3e2247932e83cc4f5ac7fd38e280
|
[
"Unlicense"
] | null | null | null |
test/support/channel_case.ex
|
angelo-moreira/topflow
|
00946c317aba3e2247932e83cc4f5ac7fd38e280
|
[
"Unlicense"
] | null | null | null |
test/support/channel_case.ex
|
angelo-moreira/topflow
|
00946c317aba3e2247932e83cc4f5ac7fd38e280
|
[
"Unlicense"
] | null | null | null |
defmodule TopflowWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use TopflowWeb.ChannelCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
import Phoenix.ChannelTest
import TopflowWeb.ChannelCase
# The default endpoint for testing
@endpoint TopflowWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Topflow.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Topflow.Repo, {:shared, self()})
end
:ok
end
end
| 27.097561
| 69
| 0.727273
|
93d66240d43320c88bc0f115bd1a36d49714f076
| 31,508
|
ex
|
Elixir
|
clients/chat/lib/google_api/chat/v1/api/spaces.ex
|
MMore/elixir-google-api
|
0574ec1439d9bbfe22d63965be1681b0f45a94c9
|
[
"Apache-2.0"
] | null | null | null |
clients/chat/lib/google_api/chat/v1/api/spaces.ex
|
MMore/elixir-google-api
|
0574ec1439d9bbfe22d63965be1681b0f45a94c9
|
[
"Apache-2.0"
] | null | null | null |
clients/chat/lib/google_api/chat/v1/api/spaces.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.Chat.V1.Api.Spaces do
@moduledoc """
API calls for all endpoints tagged `Spaces`.
"""
alias GoogleApi.Chat.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Returns a space.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the space, in the form "spaces/*". Example: spaces/AAAAAAAAAAAA
* `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.Chat.V1.Model.Space{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Space.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_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.Chat.V1.Model.Space{}])
end
@doc """
Lists spaces the caller is a member of.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Requested page size. The value is capped at 1000. Server may return fewer results than requested. If unspecified, server will default to 100.
* `:pageToken` (*type:* `String.t`) - A token identifying a page of results the server should return.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.ListSpacesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.ListSpacesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/spaces", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.ListSpacesResponse{}])
end
@doc """
Legacy path for creating message. Calling these will result in a BadRequest response.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Space resource name, in the form "spaces/*". Example: spaces/AAAAAAAAAAA
* `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").
* `:requestId` (*type:* `String.t`) - Optional. A unique request ID for this message. Specifying an existing request ID returns the message created with that ID instead of creating a new message.
* `:threadKey` (*type:* `String.t`) - Optional. Opaque thread identifier string that can be specified to group messages into a single thread. If this is the first message with a given thread identifier, a new thread is created. Subsequent messages with the same thread identifier will be posted into the same thread. This relieves bots and webhooks from having to store the Google Chat thread ID of a thread (created earlier by them) to post further updates to it. Has no effect if thread field, corresponding to an existing thread, is set in message.
* `:body` (*type:* `GoogleApi.Chat.V1.Model.Message.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_webhooks(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_webhooks(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,
:requestId => :query,
:threadKey => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/webhooks", %{
"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.Chat.V1.Model.Message{}])
end
@doc """
Returns a membership.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the membership to be retrieved, in the form "spaces/*/members/*". Example: spaces/AAAAAAAAAAAA/members/111111111111111111111
* `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.Chat.V1.Model.Membership{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_members_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Membership.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_members_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.Chat.V1.Model.Membership{}])
end
@doc """
Lists human memberships in a space.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The resource name of the space for which membership list is to be fetched, in the form "spaces/*". Example: spaces/AAAAAAAAAAAA
* `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()`) - Requested page size. The value is capped at 1000. Server may return fewer results than requested. If unspecified, server will default to 100.
* `:pageToken` (*type:* `String.t`) - A token identifying a page of results the server should return.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.ListMembershipsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_members_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.ListMembershipsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_members_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}/members", %{
"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.Chat.V1.Model.ListMembershipsResponse{}])
end
@doc """
Creates a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Space resource name, in the form "spaces/*". Example: spaces/AAAAAAAAAAA
* `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").
* `:requestId` (*type:* `String.t`) - Optional. A unique request ID for this message. Specifying an existing request ID returns the message created with that ID instead of creating a new message.
* `:threadKey` (*type:* `String.t`) - Optional. Opaque thread identifier string that can be specified to group messages into a single thread. If this is the first message with a given thread identifier, a new thread is created. Subsequent messages with the same thread identifier will be posted into the same thread. This relieves bots and webhooks from having to store the Google Chat thread ID of a thread (created earlier by them) to post further updates to it. Has no effect if thread field, corresponding to an existing thread, is set in message.
* `:body` (*type:* `GoogleApi.Chat.V1.Model.Message.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_create(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_messages_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,
:requestId => :query,
:threadKey => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/messages", %{
"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.Chat.V1.Model.Message{}])
end
@doc """
Deletes a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the message to be deleted, in the form "spaces/*/messages/*" Example: spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB
* `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.Chat.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_messages_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.Chat.V1.Model.Empty{}])
end
@doc """
Returns a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the message to be retrieved, in the form "spaces/*/messages/*". Example: spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB
* `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.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_messages_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.Chat.V1.Model.Message{}])
end
@doc """
Updates a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name in the form `spaces/*/messages/*`. Example: `spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB`
* `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. The field paths to be updated, comma separated if there are multiple. Currently supported field paths: * text * cards * attachment
* `:body` (*type:* `GoogleApi.Chat.V1.Model.Message.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_update(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_messages_update(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(:put)
|> 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.Chat.V1.Model.Message{}])
end
@doc """
Gets the metadata of a message attachment. The attachment data is fetched using the media API.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the attachment, in the form "spaces/*/messages/*/attachments/*".
* `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.Chat.V1.Model.Attachment{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_attachments_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Attachment.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def chat_spaces_messages_attachments_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.Chat.V1.Model.Attachment{}])
end
end
| 48.548536
| 559
| 0.618605
|
93d6941bb6b80b62e8925cc7ccdeab5905ed6a75
| 2,493
|
exs
|
Elixir
|
apps/site/test/site_web/controllers/schedule/offset_test.exs
|
noisecapella/dotcom
|
d5ef869412102d2230fac3dcc216f01a29726227
|
[
"MIT"
] | 42
|
2019-05-29T16:05:30.000Z
|
2021-08-09T16:03:37.000Z
|
apps/site/test/site_web/controllers/schedule/offset_test.exs
|
noisecapella/dotcom
|
d5ef869412102d2230fac3dcc216f01a29726227
|
[
"MIT"
] | 872
|
2019-05-29T17:55:50.000Z
|
2022-03-30T09:28:43.000Z
|
apps/site/test/site_web/controllers/schedule/offset_test.exs
|
noisecapella/dotcom
|
d5ef869412102d2230fac3dcc216f01a29726227
|
[
"MIT"
] | 12
|
2019-07-01T18:33:21.000Z
|
2022-03-10T02:13:57.000Z
|
defmodule SiteWeb.ScheduleController.OffsetTest do
use SiteWeb.ConnCase, async: true
import SiteWeb.ScheduleController.Offset
describe "init/1" do
test "takes no options" do
assert init([]) == []
end
end
describe "call/2" do
test "when time is before the first trip offset is 0" do
now = Util.now()
conn =
now
|> make_timetable_schedules
|> assign(:date_time, Timex.shift(now, minutes: -1))
|> call([])
assert conn.assigns.offset == 0
end
test "when time is during the first trip offset is 0" do
now = Util.now()
conn =
now
|> make_timetable_schedules
|> assign(:date_time, Timex.shift(now, minutes: 5))
|> call([])
assert conn.assigns.offset == 0
end
test "when time is right after the first trip offset is 1" do
now = Util.now()
conn =
now
|> make_timetable_schedules
|> assign(:date_time, Timex.shift(now, minutes: 21))
|> call([])
assert conn.assigns.offset == 1
end
test "when time is during the second trip offset is 1" do
now = Util.now()
conn =
now
|> make_timetable_schedules
|> assign(:date_time, Timex.shift(now, hours: 1, minutes: 5))
|> call([])
assert conn.assigns.offset == 1
end
test "when time is after the third trip offset is 0" do
now = Util.now()
conn =
now
|> make_timetable_schedules
|> assign(:date_time, Timex.shift(now, hours: 4))
|> call([])
assert conn.assigns.offset == 0
end
end
defp make_timetable_schedules(now) do
build_conn()
|> assign(:date_time, now)
|> assign(:timetable_schedules, Enum.flat_map(0..2, &make_one_trip(&1, now)))
end
# makes a list of schedules that look like this:
#
# | trip0 | trip1 | trip2
# ------+-------------+---------------+-------------
# stop0 | now+0min | now+1h | now+2h
# stop1 | now+10min | now+1h+10min | now+2h+10min
# stop2 | how+20min | now+1h+20min | now+2h+20min
defp make_one_trip(i, now) do
Enum.map(
0..2,
&make_schedule(
Timex.shift(now, minutes: &1 * 10, hours: i),
"trip" <> Integer.to_string(i),
"stop" <> Integer.to_string(&1)
)
)
end
defp make_schedule(time, trip_id, stop_id) do
%{time: time, trip: %{id: trip_id}, stop: %{id: stop_id}}
end
end
| 24.203883
| 81
| 0.561171
|
93d6a54792761c100e3e3844d577234088d14e7e
| 5,861
|
exs
|
Elixir
|
test/support/schema.exs
|
StareIntoTheBeard/coherence
|
96607cefb1b6269c6e8dea6fab897ed9489ad749
|
[
"MIT"
] | 2
|
2018-01-19T06:12:16.000Z
|
2018-03-12T07:17:17.000Z
|
test/support/schema.exs
|
StareIntoTheBeard/coherence
|
96607cefb1b6269c6e8dea6fab897ed9489ad749
|
[
"MIT"
] | null | null | null |
test/support/schema.exs
|
StareIntoTheBeard/coherence
|
96607cefb1b6269c6e8dea6fab897ed9489ad749
|
[
"MIT"
] | null | null | null |
defmodule TestCoherence.User do
use Ecto.Schema
use Coherence.Schema
import Ecto.Changeset
schema "users" do
coherence_schema()
field :email, :string
field :name, :string
timestamps()
end
@required_fields ~w(email name)a
@optional_fields ~w() ++ coherence_fields()
def changeset(model, params \\ %{}) do
model
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
|> validate_coherence(params)
end
def changeset(model, params, :password) do
model
|> cast(params, ~w(password password_confirmation reset_password_token reset_password_sent_at))
|> validate_coherence_password_reset(params)
end
end
defmodule TestCoherence.Invitation do
use Ecto.Schema
use Coherence.Schema
import Ecto.Changeset
schema "invitations" do
field :email, :string
field :name, :string
field :token, :string
timestamps()
end
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(name email token))
|> validate_required([:name, :email])
|> unique_constraint(:email)
|> validate_format(:email, ~r/@/)
end
end
defmodule TestCoherence.Account do
use Ecto.Schema
use Coherence.Schema
import Ecto.Changeset
schema "accounts" do
field :email, :string
field :name, :string
coherence_schema()
timestamps()
end
@required_fields ~w(email name)a
@optional_fields ~w() ++ coherence_fields()
def changeset(model, params \\ %{}) do
model
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
|> unique_constraint(:email)
|> validate_coherence(params)
end
def changeset(model, params, :password) do
model
|> cast(params, ~w(password password_confirmation reset_password_token reset_password_sent_at))
|> validate_coherence_password_reset(params)
end
end
defmodule TestCoherence.Coherence.User do
use Ecto.Schema
use Coherence.Schema
import Ecto.Changeset
schema "users" do
coherence_schema()
field :email, :string
field :name, :string
timestamps()
end
@required_fields ~w(email name)a
@optional_fields ~w() ++ coherence_fields()
def changeset(model, params \\ %{}) do
model
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
|> validate_coherence(params)
end
def changeset(model, params, :password) do
model
|> cast(params, ~w(password password_confirmation reset_password_token reset_password_sent_at))
|> validate_coherence_password_reset(params)
end
end
defmodule TestCoherence.Coherence.Invitation do
use Ecto.Schema
use Coherence.Schema
import Ecto.Changeset
schema "invitations" do
field :email, :string
field :name, :string
field :token, :string
timestamps()
end
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(name email token))
|> validate_required([:name, :email])
|> unique_constraint(:email)
|> validate_format(:email, ~r/@/)
end
def new_changeset(params \\ %{}) do
changeset __MODULE__.__struct__, params
end
end
defmodule TestCoherence.Coherence.Account do
use Ecto.Schema
use Coherence.Schema
import Ecto.Changeset
schema "accounts" do
field :email, :string
field :name, :string
coherence_schema()
timestamps()
end
@required_fields ~w(email name)a
@optional_fields ~w() ++ coherence_fields()
def changeset(model, params \\ %{}) do
model
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)
|> unique_constraint(:email)
|> validate_coherence(params)
end
def changeset(model, params, :password) do
model
|> cast(params, ~w(password password_confirmation reset_password_token reset_password_sent_at))
|> validate_coherence_password_reset(params)
end
end
defmodule TestCoherence.Coherence.Rememberable do
use Ecto.Schema
import Ecto.Query
import Ecto.Changeset
alias Coherence.Config
schema "rememberables" do
field :series_hash, :string
field :token_hash, :string
field :token_created_at, :naive_datetime
belongs_to :user, Config.user_schema
timestamps()
end
use Coherence.Rememberable
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(series_hash token_hash token_created_at user_id))
|> validate_required(~w(series_hash token_hash token_created_at user_id)a)
end
def new_changeset(params \\ %{}) do
changeset %Rememberable{}, params
end
end
defmodule TestCoherence.Coherence.Trackable do
@moduledoc """
Schema responsible for saving user tracking data for the --trackable-table option.
"""
use Ecto.Schema
import Ecto.Changeset
alias Coherence.Config
@fields ~w(action sign_in_count current_sign_in_ip current_sign_in_at last_sign_in_ip last_sign_in_at user_id)a
schema "trackables" do
field :action, :string, null: false
field :sign_in_count, :integer, default: 0
field :current_sign_in_at, :naive_datetime
field :last_sign_in_at, :naive_datetime
field :current_sign_in_ip, :string
field :last_sign_in_ip, :string
belongs_to :user, Config.user_schema
timestamps()
end
@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 \\ %{}) do
model
|> cast(params, @fields)
|> validate_required([:action, :user_id])
end
@doc """
Creates a changeset for a new schema
"""
def new_changeset(params \\ %{}) do
changeset %__MODULE__{}, params
end
end
| 23.538153
| 113
| 0.702781
|
93d6c2efafc5b666ef7493b3965aa3c18526c627
| 2,355
|
ex
|
Elixir
|
lib/creator.ex
|
wise-home/wise_homex
|
851f13191ed67acb1003888c12f4e6b71800d31b
|
[
"MIT"
] | 2
|
2019-03-14T09:09:14.000Z
|
2020-11-25T06:44:46.000Z
|
lib/creator.ex
|
wise-home/wise_homex
|
851f13191ed67acb1003888c12f4e6b71800d31b
|
[
"MIT"
] | 139
|
2019-03-14T06:58:55.000Z
|
2022-03-29T12:28:09.000Z
|
lib/creator.ex
|
wise-home/wise_homex
|
851f13191ed67acb1003888c12f4e6b71800d31b
|
[
"MIT"
] | 7
|
2021-04-09T13:55:45.000Z
|
2021-04-16T15:49:36.000Z
|
defmodule WiseHomex.Creator do
@moduledoc """
Auto creation of main wise_homex module functions from configuration
These function simply delegate to the api_client() function, which in turn sends a request to either
the API client implementation or the mock server
"""
@doc """
When used by a module, we inject autogenerated mock functions from the api client definition
"""
defmacro __using__([]) do
WiseHomex.ApiDefinition.api_endpoints()
|> Enum.map(&WiseHomex.Creator.create_endpoint/1)
end
@doc """
Functions for creating endpoints at compile time
"""
# Create an index function that delegates to api_client()
def create_endpoint(%{verb: :index} = api_endpoint) do
function_name = "get_#{api_endpoint.name_plural}" |> String.to_atom()
quote do
def unquote(function_name)(config, query \\ %{}), do: api_client().unquote(function_name)(config, query)
end
end
# Create a show function that delegates to api_client()
def create_endpoint(%{verb: :show} = api_endpoint) do
function_name = "get_#{api_endpoint.name_singular}" |> String.to_atom()
quote do
def unquote(function_name)(config, id, query \\ %{}), do: api_client().unquote(function_name)(config, id, query)
end
end
# Create a create function that delegates to api_client()
def create_endpoint(%{verb: :create} = api_endpoint) do
function_name = "create_#{api_endpoint.name_singular}" |> String.to_atom()
quote do
def unquote(function_name)(config, attrs, rels \\ %{}, query \\ %{}),
do: api_client().unquote(function_name)(config, attrs, rels, query)
end
end
# Create an update function that delegates to api_client()
def create_endpoint(%{verb: :update} = api_endpoint) do
function_name = "update_#{api_endpoint.name_singular}" |> String.to_atom()
quote do
def unquote(function_name)(config, id, attrs, rels \\ %{}, query \\ %{}),
do: api_client().unquote(function_name)(config, id, attrs, rels, query)
end
end
# Create a delete function that delegates to api_client()
def create_endpoint(%{verb: :delete} = api_endpoint) do
function_name = "delete_#{api_endpoint.name_singular}" |> String.to_atom()
quote do
def unquote(function_name)(config, id), do: api_client().unquote(function_name)(config, id)
end
end
end
| 35.149254
| 118
| 0.700212
|
93d6d8a739d03a07c876692a183e880f2c24a984
| 1,760
|
ex
|
Elixir
|
clients/dataproc/lib/google_api/dataproc/v1/model/list_clusters_response.ex
|
GoNZooo/elixir-google-api
|
cf3ad7392921177f68091f3d9001f1b01b92f1cc
|
[
"Apache-2.0"
] | null | null | null |
clients/dataproc/lib/google_api/dataproc/v1/model/list_clusters_response.ex
|
GoNZooo/elixir-google-api
|
cf3ad7392921177f68091f3d9001f1b01b92f1cc
|
[
"Apache-2.0"
] | null | null | null |
clients/dataproc/lib/google_api/dataproc/v1/model/list_clusters_response.ex
|
GoNZooo/elixir-google-api
|
cf3ad7392921177f68091f3d9001f1b01b92f1cc
|
[
"Apache-2.0"
] | 1
|
2018-07-28T20:50:50.000Z
|
2018-07-28T20:50:50.000Z
|
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Dataproc.V1.Model.ListClustersResponse do
@moduledoc """
The list of all clusters in a project.
## Attributes
- clusters (List[Cluster]): Output-only. The clusters in the project. Defaults to: `null`.
- nextPageToken (String): Output-only. This token is included in the response if there are more results to fetch. To fetch additional results, provide this value as the page_token in a subsequent ListClustersRequest. Defaults to: `null`.
"""
defstruct [
:"clusters",
:"nextPageToken"
]
end
defimpl Poison.Decoder, for: GoogleApi.Dataproc.V1.Model.ListClustersResponse do
import GoogleApi.Dataproc.V1.Deserializer
def decode(value, options) do
value
|> deserialize(:"clusters", :list, GoogleApi.Dataproc.V1.Model.Cluster, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Dataproc.V1.Model.ListClustersResponse do
def encode(value, options) do
GoogleApi.Dataproc.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 35.2
| 239
| 0.756818
|
93d6dbc69e8443cf626df8232fc1d4ff07934bce
| 2,215
|
ex
|
Elixir
|
clients/drive/lib/google_api/drive/v3/model/permission_list.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/drive/lib/google_api/drive/v3/model/permission_list.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/drive/lib/google_api/drive/v3/model/permission_list.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.Drive.V3.Model.PermissionList do
@moduledoc """
A list of permissions for a file.
## Attributes
* `kind` (*type:* `String.t`, *default:* `drive#permissionList`) - Identifies what kind of resource this is. Value: the fixed string "drive#permissionList".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The page token for the next page of permissions. This field will be absent if the end of the permissions list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results.
* `permissions` (*type:* `list(GoogleApi.Drive.V3.Model.Permission.t)`, *default:* `nil`) - The list of permissions. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:nextPageToken => String.t(),
:permissions => list(GoogleApi.Drive.V3.Model.Permission.t())
}
field(:kind)
field(:nextPageToken)
field(:permissions, as: GoogleApi.Drive.V3.Model.Permission, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Drive.V3.Model.PermissionList do
def decode(value, options) do
GoogleApi.Drive.V3.Model.PermissionList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Drive.V3.Model.PermissionList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.792453
| 322
| 0.730474
|
93d6ddf8858aae4a04f490aa9331d72ccd1e5f05
| 1,654
|
ex
|
Elixir
|
lib/codex/runner.ex
|
maartenvanvliet/codex
|
4026a5bc64f5aafd94ce21ee4ec922ea79af49c9
|
[
"MIT"
] | 3
|
2021-05-16T14:13:18.000Z
|
2021-05-18T18:51:06.000Z
|
lib/codex/runner.ex
|
maartenvanvliet/codex
|
4026a5bc64f5aafd94ce21ee4ec922ea79af49c9
|
[
"MIT"
] | 11
|
2021-09-22T04:15:16.000Z
|
2022-03-24T04:14:17.000Z
|
lib/codex/runner.ex
|
maartenvanvliet/codex
|
4026a5bc64f5aafd94ce21ee4ec922ea79af49c9
|
[
"MIT"
] | null | null | null |
defmodule Codex.Runner do
@moduledoc false
@doc false
def run(module, params, opts \\ []) do
case module.validate(params) do
{:error, error} ->
{:error, error}
{:ok, result} ->
call(module, result, module.init(opts))
end
end
@doc false
defp call(module, params, opts) do
result =
module.steps
|> Enum.reduce_while(params, fn step, acc ->
{mod, opts} = step_invocation(step)
result =
if function_exported?(mod, :run, 2) do
init_opts = mod.init(opts)
case mod.steps() do
[] ->
case mod.validate(acc) do
{:error, error} ->
{:error, error}
{:ok, result} ->
mod.call(result, init_opts)
end
_steps ->
mod.run(acc, init_opts)
end
else
apply(module, mod, [acc])
end
case Codex.Result.halt(result) do
{:halt, data} ->
{:halt, {:error, data}}
{:ok, params} ->
{:cont, params}
end
end)
case process_result(result) do
{:error, error} ->
{:error, error}
{:ok, params} ->
module.call(params, opts)
|> process_result
end
end
defp process_result(result) do
case Codex.Result.halt(result) do
{:halt, data} ->
{:error, data}
{:ok, params} ->
{:ok, params}
end
end
defp step_invocation({module, config}) do
{module, config}
end
defp step_invocation(module) do
{module, []}
end
end
| 20.936709
| 50
| 0.48549
|
93d6f7dabc6731f5e5af2d257c75a65aa835f1c0
| 1,628
|
ex
|
Elixir
|
hello/test/support/model_case.ex
|
enilsen16/elixir
|
b4d1d45858a25e4beb39e07de8685f3d93d6a520
|
[
"MIT"
] | null | null | null |
hello/test/support/model_case.ex
|
enilsen16/elixir
|
b4d1d45858a25e4beb39e07de8685f3d93d6a520
|
[
"MIT"
] | null | null | null |
hello/test/support/model_case.ex
|
enilsen16/elixir
|
b4d1d45858a25e4beb39e07de8685f3d93d6a520
|
[
"MIT"
] | null | null | null |
defmodule Hello.ModelCase do
@moduledoc """
This module defines the test case to be used by
model tests.
You may define functions here to be used as helpers in
your model tests. See `errors_on/2`'s definition as reference.
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
alias Hello.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Hello.ModelCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Hello.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Hello.Repo, {:shared, self()})
end
:ok
end
@doc """
Helper for returning list of errors in a struct when given certain data.
## Examples
Given a User schema that lists `:name` as a required field and validates
`:password` to be safe, it would return:
iex> errors_on(%User{}, %{password: "password"})
[password: "is unsafe", name: "is blank"]
You could then write your assertion like:
assert {:password, "is unsafe"} in errors_on(%User{}, %{password: "password"})
You can also create the changeset manually and retrieve the errors
field directly:
iex> changeset = User.changeset(%User{}, password: "password")
iex> {:password, "is unsafe"} in changeset.errors
true
"""
def errors_on(struct, data) do
struct.__struct__.changeset(struct, data).errors
end
end
| 25.4375
| 84
| 0.683661
|
93d728ab42e44c53680cfa92f19651be0f777a09
| 291
|
ex
|
Elixir
|
lib/ambry_web/views/layout_view.ex
|
froseph/ambry
|
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
|
[
"MIT"
] | null | null | null |
lib/ambry_web/views/layout_view.ex
|
froseph/ambry
|
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
|
[
"MIT"
] | null | null | null |
lib/ambry_web/views/layout_view.ex
|
froseph/ambry
|
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
|
[
"MIT"
] | null | null | null |
defmodule AmbryWeb.LayoutView do
@moduledoc false
use AmbryWeb, :view
# Phoenix LiveDashboard is available only in development by default,
# so we instruct Elixir to not warn if the dashboard route is missing.
@compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}}
end
| 29.1
| 72
| 0.766323
|
93d74cc025fcd968ea471366cc4cd3f26acbd801
| 15,348
|
exs
|
Elixir
|
test/changeset_parser_test.exs
|
qwexvf/absinthe_error_payload
|
d75abe2234ac48eeea00c6e9b7444172e9901f79
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2021-09-30T04:40:13.000Z
|
2021-09-30T04:40:13.000Z
|
test/changeset_parser_test.exs
|
qwexvf/absinthe_error_payload
|
d75abe2234ac48eeea00c6e9b7444172e9901f79
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
test/changeset_parser_test.exs
|
qwexvf/absinthe_error_payload
|
d75abe2234ac48eeea00c6e9b7444172e9901f79
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
defmodule AbsintheErrorPayload.ChangesetParserTest do
@moduledoc """
Test conversion of changeset errors to ValidationMessage structs
"""
use ExUnit.Case
import Ecto.Changeset
alias AbsintheErrorPayload.ChangesetParser
alias AbsintheErrorPayload.ValidationMessage
# taken from Ecto.changeset tests
defmodule Author do
@moduledoc false
use Ecto.Schema
schema "author" do
field(:name, :string)
end
end
defmodule Tag do
@moduledoc false
use Ecto.Schema
schema "tags" do
field(:name, :string)
end
end
defmodule Post do
@moduledoc false
use Ecto.Schema
schema "posts" do
field(:title, :string, default: "")
field(:body)
field(:uuid, :binary_id)
field(:decimal, :decimal)
field(:upvotes, :integer, default: 0)
field(:topics, {:array, :string})
field(:virtual, :string, virtual: true)
field(:published_at, :naive_datetime)
belongs_to(:author, Author)
has_many(:tags, Tag)
embeds_many :embedded_tags, EmbeddedTag, on_replace: :delete do
field(:name)
end
end
end
defp changeset(params) do
cast(%Post{}, params, ~w(title body upvotes decimal topics virtual)a)
end
defp changeset_with_embeds(params) do
cast(
%Post{
embedded_tags: [
%Post.EmbeddedTag{id: "30b2111e-6b57-45ed-bf85-ed2f41715832", name: "foo"}
]
},
params,
~w(title body upvotes decimal topics virtual)a
)
end
describe "interpolate_message/1" do
test "interpolates correctly" do
result = ChangesetParser.interpolate_message({"Test %{one}", [one: "1"]})
assert "Test 1" == result
result = ChangesetParser.interpolate_message({"Test %{one}", %{one: "1"}})
assert "Test 1" == result
end
end
describe "multiples" do
test "multiple fields with errors" do
changeset =
%{"title" => "foobar", "virtual" => "foobar", "author" => %{"name" => ""}}
|> changeset()
|> cast_assoc(:author,
with: fn author, params ->
author
|> cast(params, ~w(name)a)
|> validate_required(:name)
end
)
|> validate_format(:title, ~r/@/)
|> validate_length(:virtual, is: 4)
result = ChangesetParser.extract_messages(changeset)
assert [first, second, third] = result
assert %ValidationMessage{field: "author.name", key: :name} = first
assert %ValidationMessage{code: :format, field: :title, key: :title} = second
assert %ValidationMessage{code: :length, field: :virtual, key: :virtual} = third
end
test "multiple fields with nested errors" do
changeset =
%{"title" => "foobar", "virtual" => "foobar"}
|> changeset()
|> validate_format(:title, ~r/@/)
|> validate_length(:virtual, is: 4)
result = ChangesetParser.extract_messages(changeset)
assert [first, second] = result
assert %ValidationMessage{code: :format, field: :title, key: :title} = first
assert %ValidationMessage{code: :length, field: :virtual, key: :virtual} = second
end
test "multiple errors on one field" do
changeset =
%{"title" => "foobar"}
|> changeset()
|> validate_format(:title, ~r/@/)
|> validate_length(:title, is: 4)
result = ChangesetParser.extract_messages(changeset)
assert [first, second] = result
assert %ValidationMessage{code: :length, field: :title, key: :title} = first
assert %ValidationMessage{code: :format, field: :title, key: :title} = second
end
end
describe "nested" do
test "nested fields with errors" do
changeset =
%{"author" => %{"name" => ""}}
|> changeset()
|> cast_assoc(:author,
with: fn author, params ->
author
|> cast(params, ~w(name)a)
|> validate_required(:name)
end
)
result = ChangesetParser.extract_messages(changeset)
assert [first] = result
assert %ValidationMessage{code: :required, field: "author.name", key: :name} = first
end
test "nested fields with errors on replaced embeds_many" do
changeset =
%{"embedded_tags" => [%{"name" => ""}, %{"name" => "valid"}, %{"name" => ""}]}
|> changeset_with_embeds()
|> cast_embed(:embedded_tags,
with: fn tag, params ->
tag
|> cast(params, ~w(name)a)
|> validate_required(:name)
end
)
result = ChangesetParser.extract_messages(changeset)
assert [first, second] = result
assert %ValidationMessage{message: "can't be blank", code: :required, field: "embedded_tags.0.name", key: :name} = first
assert %ValidationMessage{message: "can't be blank", code: :required, field: "embedded_tags.2.name", key: :name} = second
end
test "nested has many fields with errors" do
changeset =
%{"tags" => [%{"name" => ""}, %{"name" => ""}]}
|> changeset()
|> cast_assoc(:tags,
with: fn tag, params ->
tag
|> cast(params, ~w(name)a)
|> validate_required(:name)
end
)
result = ChangesetParser.extract_messages(changeset)
assert [first, second] = result
assert %ValidationMessage{code: :required, field: "tags.0.name", key: :name} = first
assert %ValidationMessage{code: :required, field: "tags.1.name", key: :name} = second
end
end
describe "construct_message/2" do
test "creates expected struct" do
message = "can't be %{illegal}"
options = %{code: "foobar", illegal: "foobar"}
message = ChangesetParser.construct_message(:title, {message, options})
assert %ValidationMessage{} = message
assert message.code == "foobar"
assert message.key == :title
assert message.field == :title
assert message.options == %{illegal: "foobar"}
assert message.message =~ ~r/foobar/
assert message.template =~ ~r/%{illegal}/
end
end
describe "validations" do
test "custom with code" do
changeset =
%{"title" => "foobar"}
|> changeset()
|> add_error(:title, "can't be %{illegal}", code: "foobar", illegal: "foobar")
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == "foobar"
assert message.key == :title
assert message.field == :title
assert message.options == %{illegal: "foobar"}
assert message.message =~ ~r/foobar/
assert message.template =~ ~r/%{illegal}/
end
test "custom without code" do
changeset =
%{"title" => "foobar"}
|> changeset()
|> add_error(:title, "can't be %{illegal}", illegal: "foobar")
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :unknown
assert message.key == :title
assert message.field == :title
assert message.options == %{illegal: "foobar"}
assert message.message =~ ~r/foobar/
assert message.template =~ ~r/%{illegal}/
end
test "format validation" do
changeset =
%{"title" => "foobar"}
|> changeset()
|> validate_format(:title, ~r/@/)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :format
assert message.key == :title
assert message.field == :title
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "inclusion validation" do
changeset =
%{"title" => "hello"}
|> changeset()
|> validate_inclusion(:title, ~w(world))
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :inclusion
assert message.key == :title
assert message.field == :title
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "subset validation" do
changeset =
%{"topics" => ["cat", "laptop"]}
|> changeset()
|> validate_subset(:topics, ~w(cat dog))
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :subset
assert message.key == :topics
assert message.field == :topics
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "exclusion validation" do
changeset =
%{"title" => "world"}
|> changeset()
|> validate_exclusion(:title, ~w(world))
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :exclusion
assert message.key == :title
assert message.field == :title
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "min validation" do
changeset =
%{"title" => "w"}
|> changeset()
|> validate_length(:title, min: 2, max: 3)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :min
assert message.key == :title
assert message.field == :title
assert message.options == %{count: 2, kind: :min, type: :string}
assert message.message =~ ~r/2/
assert message.template =~ ~r/%{count}/
end
test "max validation" do
changeset =
%{"title" => "world"}
|> changeset()
|> validate_length(:title, min: 2, max: 3)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :max
assert message.key == :title
assert message.field == :title
assert message.options == %{count: 3, kind: :max, type: :string}
assert message.message =~ ~r/3/
assert message.template =~ ~r/%{count}/
end
test "length validation" do
changeset =
%{"title" => "world"}
|> changeset()
|> validate_length(:title, is: 7)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :length
assert message.key == :title
assert message.field == :title
assert message.options == %{count: 7, kind: :is, type: :string}
assert message.message =~ ~r/7/
assert message.template =~ ~r/%{count}/
end
test "greater_than validation" do
changeset =
%{"upvotes" => 3}
|> changeset()
|> validate_number(:upvotes, greater_than: 10)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :greater_than
assert message.key == :upvotes
assert message.field == :upvotes
assert message.options == %{kind: :greater_than, number: 10}
assert message.message =~ ~r/10/
assert message.template =~ ~r/%{number}/
end
test "greater_than_or_equal_to validation" do
changeset =
%{"upvotes" => 3}
|> changeset()
|> validate_number(:upvotes, greater_than_or_equal_to: 10)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :greater_than_or_equal_to
assert message.key == :upvotes
assert message.field == :upvotes
assert message.options == %{kind: :greater_than_or_equal_to, number: 10}
assert message.message =~ ~r/10/
assert message.template =~ ~r/%{number}/
end
test "less_than validation" do
changeset =
%{"upvotes" => 3}
|> changeset()
|> validate_number(:upvotes, less_than: 1)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :less_than
assert message.key == :upvotes
assert message.field == :upvotes
assert message.options == %{kind: :less_than, number: 1}
assert message.message =~ ~r/1/
assert message.template =~ ~r/%{number}/
end
test "less_than_or_equal_to validation" do
changeset =
%{"upvotes" => 3}
|> changeset()
|> validate_number(:upvotes, less_than_or_equal_to: 1)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :less_than_or_equal_to
assert message.key == :upvotes
assert message.field == :upvotes
assert message.options == %{kind: :less_than_or_equal_to, number: 1}
assert message.message =~ ~r/1/
assert message.template =~ ~r/%{number}/
end
test "equal_to validation" do
changeset =
%{"upvotes" => 3}
|> changeset()
|> validate_number(:upvotes, equal_to: 1)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :equal_to
assert message.key == :upvotes
assert message.field == :upvotes
assert message.options == %{kind: :equal_to, number: 1}
assert message.message =~ ~r/1/
assert message.template =~ ~r/%{number}/
end
test "confirmation validation" do
changeset =
%{"title" => "title", "title_confirmation" => "not title"}
|> changeset()
|> validate_confirmation(:title, required: true)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :confirmation
assert message.key == :title_confirmation
assert message.field == :title_confirmation
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "acceptance validation" do
changeset =
%{"terms_of_service" => "false"}
|> changeset()
|> validate_acceptance(:terms_of_service)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :acceptance
assert message.key == :terms_of_service
assert message.field == :terms_of_service
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "required validation" do
changeset =
%{}
|> changeset()
|> validate_required(:title)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :required
assert message.key == :title
assert message.field == :title
assert message.options == %{}
assert message.message != ""
assert message.template != ""
end
test "cast validation" do
params = %{"body" => :world}
struct = %Post{}
changeset = cast(struct, params, ~w(body)a)
assert [%ValidationMessage{} = message] = ChangesetParser.extract_messages(changeset)
assert message.code == :cast
assert message.key == :body
assert message.field == :body
assert message.options == %{type: :string}
assert message.message != ""
assert message.template != ""
end
end
end
| 32.379747
| 127
| 0.608223
|
93d77bf01200151b1619ddd6c61e9f63590a51dc
| 145
|
exs
|
Elixir
|
config/config.exs
|
RubMurga/tatumex
|
759e653e94d39a069db561f12e5002ba583ff73f
|
[
"MIT"
] | null | null | null |
config/config.exs
|
RubMurga/tatumex
|
759e653e94d39a069db561f12e5002ba583ff73f
|
[
"MIT"
] | null | null | null |
config/config.exs
|
RubMurga/tatumex
|
759e653e94d39a069db561f12e5002ba583ff73f
|
[
"MIT"
] | null | null | null |
use Mix.Config
config :tatumex, tatum_url: "https://api-eu1.tatum.io/v3"
config :tatumex, tatum_api_key: "c43a1147-0d72-40b3-a7f3-df20ade722df"
| 29
| 70
| 0.772414
|
93d78eca05a96f57c9a0bfc46dfdbb1e5664d7a9
| 575
|
ex
|
Elixir
|
lib/entities/entity_macros.ex
|
iboard/repox
|
3b2d1a74439ae8ee6634bc8b37756773d1bed51d
|
[
"Unlicense"
] | null | null | null |
lib/entities/entity_macros.ex
|
iboard/repox
|
3b2d1a74439ae8ee6634bc8b37756773d1bed51d
|
[
"Unlicense"
] | 3
|
2015-05-10T20:49:22.000Z
|
2015-05-20T19:18:12.000Z
|
lib/entities/entity_macros.ex
|
iboard/repox
|
3b2d1a74439ae8ee6634bc8b37756773d1bed51d
|
[
"Unlicense"
] | null | null | null |
defmodule Repox.Entity.Macros do
@moduledoc """
Some useful macros to support Entities.
Use with `use Repox.Entity.Macros` within any Repox.Entity
"""
@doc """
Define functions to convert between %NamedStructures{} and %{}
"""
defmacro define_entity_functions do
quote do
def as_struct entity do
Map.from_struct(entity)
end
def from_struct target, struct do
Map.merge(target, struct)
end
end
end
defmacro __using__(_) do
quote do
Repox.Entity.Macros.define_entity_functions
end
end
end
| 19.166667
| 64
| 0.669565
|
93d7ce24dea666039d6cabe834a3b33899da72aa
| 16,819
|
ex
|
Elixir
|
lib/expected.ex
|
ejpcmac/expected
|
c2b03bfa9bcb7efd52cf4003fb46f1309e8aa3c4
|
[
"MIT"
] | 33
|
2018-01-18T12:16:19.000Z
|
2021-07-30T00:33:26.000Z
|
lib/expected.ex
|
ejpcmac/expected
|
c2b03bfa9bcb7efd52cf4003fb46f1309e8aa3c4
|
[
"MIT"
] | 5
|
2018-01-18T12:56:28.000Z
|
2019-09-30T07:16:00.000Z
|
lib/expected.ex
|
ejpcmac/expected
|
c2b03bfa9bcb7efd52cf4003fb46f1309e8aa3c4
|
[
"MIT"
] | 1
|
2018-08-08T12:02:44.000Z
|
2018-08-08T12:02:44.000Z
|
defmodule Expected do
@moduledoc """
A module for login and session management.
This module enables persistent logins through a cookie, following Barry
Jaspan’s [Improved Persistent Login Cookie Best Practice](http://www.jaspan.com/improved_persistent_login_cookie_best_practice).
It also provides an API to list and discard sessions.
## Setup
To use Expected in your app, add this to your dependencies:
{:expected, "~> #{Mix.Project.config()[:version]}"}
### Configuration
You must configure Expected in your `config.exs`, for instance:
config :expected,
store: :mnesia,
table: :logins,
auth_cookie: "_my_app_auth",
session_store: PlugSessionMnesia.Store,
session_cookie: "_my_app_key"
The mandatory fields are the following:
* `store` - the login store
* `auth_cookie` - the persistent authentication cookie name
* `session_store` - the session store passed to `Plug.Session`
* `session_cookie` - the `key` option for `Plug.Session`
There are also some optional fields:
* `cookie_max_age` - the authentication cookie max age is seconds (default:
90 days)
* `cleaner_period` - the login cleaner period in seconds (default: 1 day)
* `session_opts` - options passed to `Plug.Session`
* `plug_config` - options passed to the plugs in `Expected.Plugs`
#### Login store
Currently, the built-in stores are `:mnesia` and `:memory`. `:memory` is for
testing purpose only, so please use `:mnesia`. An official `:ecto` one could
come some day; feel free to ask me if you need it or plan to implement it. You
can also implement another store using the `Expected.Store`specifications.
For the `:mnesia` store, you need to add a `:table` option to set the Mnesia
table where to store logins. Then, ask mix to create the table for you:
$ mix expected.mnesia.setup
If you want to use a node name or a custom directory for the Mnesia database,
you can take a look at `Mix.Tasks.Expected.Mnesia.Setup`.
You can also create it directly from Elixir using
`Expected.MnesiaStore.Helpers.setup!/0`. This can be useful to include in a
setup task to be run in a release environment.
#### Authentication cookie
The authentication cookie contains the username, a serial and a token
seperated by dots. The token is usable only once, and is renewed on each
successful authentication.
By default, the authentication cookie is valid for 90 days after the last
successful authentication. This can be configured using the `cookie_max_age`
option in the configuration.
To avoid old logins to accumulate in the store, inactive logins older than the
`cookie_max_age` are automatically cleaned by `Expected.Cleaner` once a day.
You can change this period by setting `cleaner_period` (in seconds) in the
application configuration.
#### Session store
Expected calls `Plug.Session` itself. Therefore, you need to set the session
store in the Expected configuration. For the session management to work, **it
must be a server-side session store that stores the session ID in the session
cookie**. I’ve written
[`plug_session_mnesia`](https://hex.pm/packages/plug_session_mnesia), but you
can use whatever server-side session store you want.
The `session_cookie` field is passed as `key` to `Plug.Session`. Every other
specific options you would need to pass to `Plug.Session` must be written in
a `session_opts` list. For example, to set the table for the `:ets` session
store:
config :expected,
...
session_store: :ets,
session_opts: [table: :session],
session_cookie: "_my_app_auth"
* * *
You must plug `Expected` in you endpoint, and do **not** plug `Plug.Session`
yourself:
# Plug Expected
plug Expected
# Do NOT plug Plug.Session
# plug Plug.Session,
# store: PlugSessionMnesia.Store,
# key: "_my_app_key"
Then, in your pipeline, plug `Expected.Plugs.authenticate/2`:
defmodule MyAppWeb.Router do
use MyAppWeb, :router
# Import the authenticate/2 plug
import Expected.Plugs, only: [authenticate: 2]
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :authenticate # Plug it after fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
...
end
## Login registration
To register a login, use `Expected.Plugs.register_login/2` in your login
pipeline, for instance:
case Auth.authenticate(username, password) do
{:ok, user} ->
conn
|> put_session(:authenticated, true)
|> put_session(:current_user, user)
|> register_login() # Call register_login here
|> redirect(to: page)
:error ->
...
end
To associate the login with a user, `register_login/2` expects a
`:current_user` key featuring a `:username` field in the session. For more
information and configuration options, please look at
`Expected.Plugs.register_login/2` in the documentation.
## Authentication
When `Expected.Plugs.authenticate/2` is called in the pipeline, it does the
following things:
1. It checks wether the session is authenticated, *i.e.* the
`:authenticated` key is set to `true`. If it is the case, it assigns
`:authenticated` and `:current_user` in the connection according to their
values in the session, and does nothing more.
2. If the session is not authenticated, it checks for an authentication
cookie. If there is no authentication cookie, it does nothing more.
3. If there is an authentication cookie, it checks for a login matching with
the username and serial in the store. If the cookie is invalid or there
is no login in the store, it just deletes the cookie and does nothing
more.
4. If there is a matching login, it checks wether the token matches. If it
is the case, it sets `:authenticated` to `true` and `:current_user` to an
`Expected.NotLoadedUser` in both the session and the connection assigns.
If the token does not match, it deletes all the users’s logins and
sessions, puts a flag in the connection assigns, deletes the cookie and
does not authenticate.
## User loading
Expected does not makes any assumptions regarding your user module or how to
load it from the database. When authenticating from a cookie, it puts an
`Expected.NotLoadedUser` with the username matching the one in the cookie in
both the session and the connection assings.
If you want the user to be loaded in the session and/or the connection
assigns, you should write a plug to do so:
@spec load_user(Plug.Conn.t(), keyword()) :: Plug.Conn.t()
def load_user(conn, _opts \\\\ []) do
case conn.assigns[:current_user] do
# If there has been a successful authentication, there is a
# NotLoadedUser in the connection assigns.
%Expected.NotLoadedUser{username: username} ->
# Get the user from the database.
user = Accounts.get_user!(username)
# Replace the NotLoadedUser with the loaded one in both the session
# and the connection assigns.
conn
|> put_session(:current_user, user)
|> assign(:current_user, user)
# If there is no user to load, do nothing.
_ ->
conn
end
end
Then, plug it in your pipeline:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :authenticate
plug :load_user # Plug it after authenticate
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
## Unexpected token
A token mismatch generally means an old token has been reused. It basically
can arrive in two situations:
1. the user has rolled back a backup or has cloned his browser profile,
2. the user tries to authenticate after some malicious people have stolen
the cookie and already authenticated with it.
In the assumption we are in the case (2), all the user’s sessions are deleted
and a flag is put in the connection assigns. You can check after an
authentication attempt if there has been an unexpected token using
`Expected.unexpected_token?/1`. It’s up to you to choose wether you should
show an alert to the user. Do not forget to state it can be due to case (1).
## Logout
To log a user out, simply call `Expected.Plugs.logout/2` on the connection. It
will delete the login and its associated session from the stores and their
cookies. For instance, you can imagine the following action for your session
controller:
import Expected.Plugs, only: [logout: 1]
@spec delete(Plug.Conn.t, map) :: Plug.Conn.t
def delete(conn, _params) do
conn
|> logout()
|> redirect(to: "/")
end
"""
@behaviour Plug
use Application
use ExportPrivate
import Plug.Conn,
only: [
get_req_header: 2,
put_private: 3,
put_resp_cookie: 4,
register_before_send: 2
]
alias Expected.Cleaner
alias Expected.Login
alias Expected.ConfigurationError
alias Plug.Session
#################
# API functions #
#################
@doc """
Returns wether there has been an authentication attempt with a bad token.
"""
@spec unexpected_token?(Plug.Conn.t()) :: boolean()
def unexpected_token?(conn), do: !!conn.assigns[:unexpected_token]
@doc """
Lists the logins for the given `username`.
"""
@spec list_user_logins(String.t()) :: [Login.t()]
def list_user_logins(username) do
%{store: store, store_opts: store_opts} = config_module().get()
store.list_user_logins(username, store_opts)
end
@doc """
Deletes a login given its `username` and `serial`.
"""
@spec delete_login(String.t(), String.t()) :: :ok
def delete_login(username, serial) do
%{
store: store,
store_opts: store_opts,
session_opts: %{store: session_store, store_config: session_config}
} = config_module().get()
case store.get(username, serial, store_opts) do
{:ok, login} ->
store.delete(username, serial, store_opts)
session_store.delete(nil, login.sid, session_config)
{:error, :no_login} ->
:ok
end
end
@doc """
Deletes all logins for a given `username`.
"""
@spec delete_all_user_logins(String.t()) :: :ok
def delete_all_user_logins(username) do
username
|> list_user_logins()
|> Enum.each(&delete_login(username, &1.serial))
end
@doc """
Deletes all logins older than `max_age`.
"""
@spec clean_old_logins(integer()) :: :ok
def clean_old_logins(max_age) do
%{
store: store,
store_opts: store_opts,
session_opts: %{store: session_store, store_config: session_config}
} = config_module().get()
max_age
|> store.clean_old_logins(store_opts)
|> Enum.each(&session_store.delete(nil, &1.sid, session_config))
end
# Define a private function to avoid unavailable module warnings on
# compilation.
@spec config_module :: module()
defp config_module, do: Expected.Config
#########################
# Application functions #
#########################
@impl Application
def start(_type, _args) do
compile_config_module()
Supervisor.start_link(
[Cleaner],
strategy: :one_for_one,
name: Expected.Supervisor
)
end
# Compiles the `Expected.Config` module using values fetched from the
# application environment. Functions from this module are used like runtime
# constants.
@spec compile_config_module :: :ok
defp compile_config_module do
expected = init_config()
config_module =
quote do
# credo:disable-for-next-line Credo.Check.Readability.ModuleDoc
defmodule Expected.Config do
def get, do: unquote(Macro.escape(expected))
end
end
_ = Code.compile_quoted(config_module)
:ok
end
@spec init_config :: map()
defp init_config do
%{}
|> init_store()
|> put_config()
|> init_session()
end
@spec init_store(map()) :: map()
defp init_store(expected) do
store = fetch_store!()
store_opts =
:expected
|> Application.get_all_env()
|> store.init()
expected
|> Map.put(:store, store)
|> Map.put(:store_opts, store_opts)
end
@spec put_config(map()) :: map()
defp put_config(expected) do
expected
|> Map.put(:auth_cookie, fetch_auth_cookie_name!())
end
@spec init_session(map()) :: map()
defp init_session(expected) do
session_cookie = fetch_session_cookie_name!()
opts = [
store: fetch_session_store!(),
key: session_cookie
]
other_opts = Application.get_env(:expected, :session_opts, [])
session_opts = Session.init(opts ++ other_opts)
expected
|> Map.put(:session_opts, session_opts)
|> Map.put(:session_cookie, session_cookie)
end
@spec fetch_store! :: module()
defp fetch_store! do
case Application.fetch_env(:expected, :store) do
{:ok, key} -> get_store(key)
:error -> raise ConfigurationError, reason: :no_store
end
end
@spec get_store(atom()) :: module()
defp get_store(:memory), do: Expected.MemoryStore
defp get_store(:mnesia), do: Expected.MnesiaStore
defp get_store(store), do: store
@spec fetch_auth_cookie_name! :: String.t()
defp fetch_auth_cookie_name! do
case Application.fetch_env(:expected, :auth_cookie) do
{:ok, auth_cookie} -> auth_cookie
:error -> raise ConfigurationError, reason: :no_auth_cookie
end
end
@spec fetch_session_store! :: atom()
defp fetch_session_store! do
case Application.fetch_env(:expected, :session_store) do
{:ok, session_store} -> session_store
:error -> raise ConfigurationError, reason: :no_session_store
end
end
@spec fetch_session_cookie_name! :: String.t()
defp fetch_session_cookie_name! do
case Application.fetch_env(:expected, :session_cookie) do
{:ok, session_cookie} -> session_cookie
:error -> raise ConfigurationError, reason: :no_session_cookie
end
end
##################
# Plug functions #
##################
@impl Plug
def init(_opts), do: nil
@impl Plug
def call(conn, _opts) do
expected = config_module().get()
conn
|> put_private(:expected, expected)
|> register_before_send(&before_send(&1))
|> Session.call(expected.session_opts)
end
@spec before_send(Plug.Conn.t(), keyword()) :: Plug.Conn.t()
defp before_send(conn, _opts \\ []) do
expected = conn.private[:expected]
do_before_send(conn, expected)
end
@spec do_before_send(Plug.Conn.t(), term()) :: Plug.Conn.t()
defp do_before_send(conn, %{action: :register_login} = expected) do
%{
username: username,
store: store,
store_opts: store_opts,
session_cookie: session_cookie
} = expected
login = %Login{
username: username,
serial: 48 |> :crypto.strong_rand_bytes() |> Base.encode64(),
token: 48 |> :crypto.strong_rand_bytes() |> Base.encode64(),
sid: conn.cookies[session_cookie],
created_at: System.os_time(),
last_login: System.os_time(),
last_ip: conn.remote_ip,
last_useragent: get_user_agent(conn)
}
store.put(login, store_opts)
put_auth_cookie(conn, login)
end
defp do_before_send(conn, %{action: :update_login} = expected) do
%{
login: login,
store: store,
store_opts: store_opts,
session_cookie: session_cookie
} = expected
login = %{
login
| token: 48 |> :crypto.strong_rand_bytes() |> Base.encode64(),
sid: conn.cookies[session_cookie],
last_login: System.os_time(),
last_ip: conn.remote_ip,
last_useragent: get_user_agent(conn)
}
store.put(login, store_opts)
put_auth_cookie(conn, login)
end
defp do_before_send(conn, _) do
conn
end
@spec get_user_agent(Plug.Conn.t()) :: String.t()
defp get_user_agent(conn) do
case get_req_header(conn, "user-agent") do
[user_agent] -> user_agent
_ -> ""
end
end
@spec put_auth_cookie(Plug.Conn.t(), Login.t()) :: Plug.Conn.t()
defp put_auth_cookie(conn, login) do
auth_cookie_name = conn.private.expected.auth_cookie
max_age = conn.private.expected.cookie_max_age
auth_cookie =
"#{Base.encode64(login.username)}.#{login.serial}.#{login.token}"
put_resp_cookie(conn, auth_cookie_name, auth_cookie, max_age: max_age)
end
end
| 30.747715
| 130
| 0.670135
|
93d7cf0d135b812abf150b3c99e2930125510d2f
| 513
|
exs
|
Elixir
|
test/cog/chat/slack/templates/embedded/permission_list_test.exs
|
matusf/cog
|
71708301c7dc570fb0d3498a50f47a70ef957788
|
[
"Apache-2.0"
] | 1,003
|
2016-02-23T17:21:12.000Z
|
2022-02-20T14:39:35.000Z
|
test/cog/chat/slack/templates/embedded/permission_list_test.exs
|
matusf/cog
|
71708301c7dc570fb0d3498a50f47a70ef957788
|
[
"Apache-2.0"
] | 906
|
2016-02-22T22:54:19.000Z
|
2022-03-11T15:19:43.000Z
|
test/cog/chat/slack/templates/embedded/permission_list_test.exs
|
matusf/cog
|
71708301c7dc570fb0d3498a50f47a70ef957788
|
[
"Apache-2.0"
] | 95
|
2016-02-23T13:42:31.000Z
|
2021-11-30T14:39:55.000Z
|
defmodule Cog.Chat.Slack.Templates.Embedded.PermissionListTest do
use Cog.TemplateCase
test "permission-list template" do
data = %{"results" => [%{"bundle" => "site", "name" => "foo"},
%{"bundle" => "site", "name" => "bar"},
%{"bundle" => "site", "name" => "baz"}]}
attachments = [
"site:foo",
"site:bar",
"site:baz"
]
assert_rendered_template(:slack, :embedded, "permission-list", data, {"", attachments})
end
end
| 27
| 91
| 0.526316
|
93d821ffdb73da2acde283d86584e89aaded127c
| 891
|
exs
|
Elixir
|
test/fixtures/n00b/mix.exs
|
TokiTori/bootleg
|
59466712b4cf85d2930c1126355fc2837d483c81
|
[
"MIT"
] | null | null | null |
test/fixtures/n00b/mix.exs
|
TokiTori/bootleg
|
59466712b4cf85d2930c1126355fc2837d483c81
|
[
"MIT"
] | null | null | null |
test/fixtures/n00b/mix.exs
|
TokiTori/bootleg
|
59466712b4cf85d2930c1126355fc2837d483c81
|
[
"MIT"
] | null | null | null |
defmodule N00b.Mixfile do
use Mix.Project
def project do
[
app: :n00b,
version: "0.1.0",
elixir: "~> 1.4",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
# Specify extra applications you'll use from Erlang/Elixir
[extra_applications: [:logger]]
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
defp deps do
[
{:distillery, "~> 2.0", runtime: false},
{:bootleg, ">= 0.0.0", path: System.get_env("BOOTLEG_PATH"), runtime: false}
]
end
end
| 22.846154
| 82
| 0.597082
|
93d8366ff1acf792fd19a1848f656ac96389a4f0
| 3,047
|
ex
|
Elixir
|
lib/grapex/models/operations.ex
|
zeionara/grapex
|
d10bd40d61cd00ff4ace6c8922745748de509948
|
[
"Apache-2.0"
] | null | null | null |
lib/grapex/models/operations.ex
|
zeionara/grapex
|
d10bd40d61cd00ff4ace6c8922745748de509948
|
[
"Apache-2.0"
] | 1
|
2021-11-14T20:42:26.000Z
|
2021-11-14T20:42:26.000Z
|
lib/grapex/models/operations.ex
|
zeionara/grapex
|
d10bd40d61cd00ff4ace6c8922745748de509948
|
[
"Apache-2.0"
] | null | null | null |
defmodule Grapex.Model.Operations do
require Axon
@doc """
Analyzes provided parameters and depending on the analysis results runs model testing either using test subset of a corpus either validation subset
"""
@spec test_or_validate({Grapex.Init, Axon, Map}) :: tuple # , list) :: tuple
def test_or_validate({%Grapex.Init{validate: should_run_validation, task: task, reverse: reverse, tester: tester} = params, model, model_state}) do # , opts \\ []) do
# IO.puts "Reverse: #{reverse}"
# reverse = Keyword.get(opts, :reverse, false)
case task do
:link_prediction ->
case should_run_validation do
true -> tester.validate({params, model, model_state}, reverse: reverse) # implement reverse option
false -> tester.test({params, model, model_state}, reverse: reverse)
end
_ -> raise "Task #{task} is not supported"
end
end
@doc """
Saves trained model to an external file in onnx-compatible format
"""
def save({%Grapex.Init{output_path: output_path, remove: remove, is_imported: is_imported, verbose: verbose} = params, model, model_state}) do
case is_imported do
true ->
case verbose do
true -> IO.puts "The model was not saved because it was initialized from pre-trained tensors"
_ -> {:ok, nil}
end
_ ->
case remove do
true ->
case verbose do
true -> IO.puts "Trained model was not saved because the appropriate flag was provided"
_ -> {:ok, nil}
end
_ ->
File.mkdir_p!(Path.dirname(output_path))
model
|> AxonOnnx.Serialize.__export__(model_state, filename: output_path)
case verbose do
true -> IO.puts "Trained model is saved as #{output_path}"
_ -> {:ok, nil}
end
end
end
{params, model, model_state}
end
@doc """
Load model from an external file
"""
def load(%Grapex.Init{import_path: import_path} = params) do
[params | Tuple.to_list(AxonOnnx.Deserialize.__import__(import_path))]
|> List.to_tuple
end
@doc """
Analyzes the passed parameters object and according to the analysis results either loads trained model from an external file either trains it from scratch.
"""
@spec train_or_import(Grapex.Init) :: tuple
def train_or_import(%Grapex.Init{import_path: import_path, verbose: verbose, trainer: trainer} = params) do
IO.puts "Training model..."
if verbose do
IO.puts "Supported computational platforms:"
IO.inspect EXLA.NIF.get_supported_platforms()
IO.puts "Gpu client:"
IO.inspect EXLA.NIF.get_gpu_client(1.0, 0)
end
# IO.puts "Import path:"
# IO.puts import_path
case import_path do
nil ->
# trainer = Grapex.Init.get_trainer(params)
trainer.train(params)
_ ->
{params, model, state} = load(params)
{Grapex.Init.set_is_imported(params, true), model, state}
end
end
end
| 35.430233
| 168
| 0.638333
|
93d87b824ff1a87182eeabd1c46b4f2f088b21c4
| 2,574
|
ex
|
Elixir
|
clients/fusion_tables/lib/google_api/fusion_tables/v2/model/template.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/fusion_tables/lib/google_api/fusion_tables/v2/model/template.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/fusion_tables/lib/google_api/fusion_tables/v2/model/template.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.FusionTables.V2.Model.Template do
@moduledoc """
Represents the contents of InfoWindow templates.
## Attributes
* `automaticColumnNames` (*type:* `list(String.t)`, *default:* `nil`) - List of columns from which the template is to be automatically constructed. Only one of body or automaticColumns can be specified.
* `body` (*type:* `String.t`, *default:* `nil`) - Body of the template. It contains HTML with {column_name} to insert values from a particular column. The body is sanitized to remove certain tags, e.g., script. Only one of body or automaticColumns can be specified.
* `kind` (*type:* `String.t`, *default:* `fusiontables#template`) - The kind of item this is. For a template, this is always fusiontables#template.
* `name` (*type:* `String.t`, *default:* `nil`) - Optional name assigned to a template.
* `tableId` (*type:* `String.t`, *default:* `nil`) - Identifier for the table for which the template is defined.
* `templateId` (*type:* `integer()`, *default:* `nil`) - Identifier for the template, unique within the context of a particular table.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:automaticColumnNames => list(String.t()),
:body => String.t(),
:kind => String.t(),
:name => String.t(),
:tableId => String.t(),
:templateId => integer()
}
field(:automaticColumnNames, type: :list)
field(:body)
field(:kind)
field(:name)
field(:tableId)
field(:templateId)
end
defimpl Poison.Decoder, for: GoogleApi.FusionTables.V2.Model.Template do
def decode(value, options) do
GoogleApi.FusionTables.V2.Model.Template.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.FusionTables.V2.Model.Template do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.516129
| 269
| 0.702409
|
93d8b7216d545ae377e8c13f7be01e89ef686eff
| 4,544
|
ex
|
Elixir
|
clients/web_security_scanner/lib/google_api/web_security_scanner/v1/model/scan_run.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/web_security_scanner/lib/google_api/web_security_scanner/v1/model/scan_run.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/web_security_scanner/lib/google_api/web_security_scanner/v1/model/scan_run.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.WebSecurityScanner.V1.Model.ScanRun do
@moduledoc """
A ScanRun is a output-only resource representing an actual run of the scan. Next id: 12
## Attributes
* `endTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time at which the ScanRun reached termination state - that the ScanRun is either finished or stopped by user.
* `errorTrace` (*type:* `GoogleApi.WebSecurityScanner.V1.Model.ScanRunErrorTrace.t`, *default:* `nil`) - Output only. If result_state is an ERROR, this field provides the primary reason for scan's termination and more details, if such are available.
* `executionState` (*type:* `String.t`, *default:* `nil`) - Output only. The execution state of the ScanRun.
* `hasVulnerabilities` (*type:* `boolean()`, *default:* `nil`) - Output only. Whether the scan run has found any vulnerabilities.
* `name` (*type:* `String.t`, *default:* `nil`) - Output only. The resource name of the ScanRun. The name follows the format of 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. The ScanRun IDs are generated by the system.
* `progressPercent` (*type:* `integer()`, *default:* `nil`) - Output only. The percentage of total completion ranging from 0 to 100. If the scan is in queue, the value is 0. If the scan is running, the value ranges from 0 to 100. If the scan is finished, the value is 100.
* `resultState` (*type:* `String.t`, *default:* `nil`) - Output only. The result state of the ScanRun. This field is only available after the execution state reaches "FINISHED".
* `startTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time at which the ScanRun started.
* `urlsCrawledCount` (*type:* `String.t`, *default:* `nil`) - Output only. The number of URLs crawled during this ScanRun. If the scan is in progress, the value represents the number of URLs crawled up to now.
* `urlsTestedCount` (*type:* `String.t`, *default:* `nil`) - Output only. The number of URLs tested during this ScanRun. If the scan is in progress, the value represents the number of URLs tested up to now. The number of URLs tested is usually larger than the number URLS crawled because typically a crawled URL is tested with multiple test payloads.
* `warningTraces` (*type:* `list(GoogleApi.WebSecurityScanner.V1.Model.ScanRunWarningTrace.t)`, *default:* `nil`) - Output only. A list of warnings, if such are encountered during this scan run.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:endTime => DateTime.t(),
:errorTrace => GoogleApi.WebSecurityScanner.V1.Model.ScanRunErrorTrace.t(),
:executionState => String.t(),
:hasVulnerabilities => boolean(),
:name => String.t(),
:progressPercent => integer(),
:resultState => String.t(),
:startTime => DateTime.t(),
:urlsCrawledCount => String.t(),
:urlsTestedCount => String.t(),
:warningTraces => list(GoogleApi.WebSecurityScanner.V1.Model.ScanRunWarningTrace.t())
}
field(:endTime, as: DateTime)
field(:errorTrace, as: GoogleApi.WebSecurityScanner.V1.Model.ScanRunErrorTrace)
field(:executionState)
field(:hasVulnerabilities)
field(:name)
field(:progressPercent)
field(:resultState)
field(:startTime, as: DateTime)
field(:urlsCrawledCount)
field(:urlsTestedCount)
field(:warningTraces, as: GoogleApi.WebSecurityScanner.V1.Model.ScanRunWarningTrace, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.WebSecurityScanner.V1.Model.ScanRun do
def decode(value, options) do
GoogleApi.WebSecurityScanner.V1.Model.ScanRun.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.WebSecurityScanner.V1.Model.ScanRun do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 58.25641
| 354
| 0.71809
|
93d8c8018ef674537b061cebde0f569c6b4ef45a
| 49,886
|
ex
|
Elixir
|
clients/calendar/lib/google_api/calendar/v3/api/events.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/calendar/lib/google_api/calendar/v3/api/events.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/calendar/lib/google_api/calendar/v3/api/events.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.Calendar.V3.Api.Events do
@moduledoc """
API calls for all endpoints tagged `Events`.
"""
alias GoogleApi.Calendar.V3.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes an event.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `event_id` (*type:* `String.t`) - Event identifier.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:sendNotifications` (*type:* `boolean()`) - Deprecated. Please use sendUpdates instead.
Whether to send notifications about the deletion of the event. Note that some emails might still be sent even if you set the value to false. The default is false.
* `:sendUpdates` (*type:* `String.t`) - Guests who should receive notifications about the deletion of the event.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_delete(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, nil} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()}
def calendar_events_delete(connection, calendar_id, event_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:sendNotifications => :query,
:sendUpdates => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/calendars/{calendarId}/events/{eventId}", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1),
"eventId" => URI.encode(event_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Returns an event.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `event_id` (*type:* `String.t`) - Event identifier.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:alwaysIncludeEmail` (*type:* `boolean()`) - Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:timeZone` (*type:* `String.t`) - Time zone used in the response. Optional. The default is the time zone of the calendar.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_get(connection, calendar_id, event_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:alwaysIncludeEmail => :query,
:maxAttendees => :query,
:timeZone => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/calendars/{calendarId}/events/{eventId}", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1),
"eventId" => URI.encode(event_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Imports an event. This operation is used to add a private copy of an existing event to a calendar.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:conferenceDataVersion` (*type:* `integer()`) - Version number of conference data supported by the API client. Version 0 assumes no conference data support and ignores conference data in the event's body. Version 1 enables support for copying of ConferenceData as well as for creating new conferences using the createRequest field of conferenceData. The default is 0.
* `:supportsAttachments` (*type:* `boolean()`) - Whether API client performing operation supports event attachments. Optional. The default is False.
* `:body` (*type:* `GoogleApi.Calendar.V3.Model.Event.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_import(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_import(connection, calendar_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:conferenceDataVersion => :query,
:supportsAttachments => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/calendars/{calendarId}/events/import", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Creates an event.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:conferenceDataVersion` (*type:* `integer()`) - Version number of conference data supported by the API client. Version 0 assumes no conference data support and ignores conference data in the event's body. Version 1 enables support for copying of ConferenceData as well as for creating new conferences using the createRequest field of conferenceData. The default is 0.
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:sendNotifications` (*type:* `boolean()`) - Deprecated. Please use sendUpdates instead.
Whether to send notifications about the creation of the new event. Note that some emails might still be sent even if you set the value to false. The default is false.
* `:sendUpdates` (*type:* `String.t`) - Whether to send notifications about the creation of the new event. Note that some emails might still be sent. The default is false.
* `:supportsAttachments` (*type:* `boolean()`) - Whether API client performing operation supports event attachments. Optional. The default is False.
* `:body` (*type:* `GoogleApi.Calendar.V3.Model.Event.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_insert(connection, calendar_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:conferenceDataVersion => :query,
:maxAttendees => :query,
:sendNotifications => :query,
:sendUpdates => :query,
:supportsAttachments => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/calendars/{calendarId}/events", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Returns instances of the specified recurring event.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `event_id` (*type:* `String.t`) - Recurring event identifier.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:alwaysIncludeEmail` (*type:* `boolean()`) - Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:maxResults` (*type:* `integer()`) - Maximum number of events returned on one result page. By default the value is 250 events. The page size can never be larger than 2500 events. Optional.
* `:originalStart` (*type:* `String.t`) - The original start time of the instance in the result. Optional.
* `:pageToken` (*type:* `String.t`) - Token specifying which result page to return. Optional.
* `:showDeleted` (*type:* `boolean()`) - Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events will still be included if singleEvents is False. Optional. The default is False.
* `:timeMax` (*type:* `DateTime.t`) - Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset.
* `:timeMin` (*type:* `DateTime.t`) - Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with mandatory time zone offset.
* `:timeZone` (*type:* `String.t`) - Time zone used in the response. Optional. The default is the time zone of the calendar.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Events{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_instances(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Calendar.V3.Model.Events.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_instances(
connection,
calendar_id,
event_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:alwaysIncludeEmail => :query,
:maxAttendees => :query,
:maxResults => :query,
:originalStart => :query,
:pageToken => :query,
:showDeleted => :query,
:timeMax => :query,
:timeMin => :query,
:timeZone => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/calendars/{calendarId}/events/{eventId}/instances", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1),
"eventId" => URI.encode(event_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Events{}])
end
@doc """
Returns events on the specified calendar.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:alwaysIncludeEmail` (*type:* `boolean()`) - Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
* `:iCalUID` (*type:* `String.t`) - Specifies event ID in the iCalendar format to be included in the response. Optional.
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:maxResults` (*type:* `integer()`) - Maximum number of events returned on one result page. The number of events in the resulting page may be less than this value, or none at all, even if there are more events matching the query. Incomplete pages can be detected by a non-empty nextPageToken field in the response. By default the value is 250 events. The page size can never be larger than 2500 events. Optional.
* `:orderBy` (*type:* `String.t`) - The order of the events returned in the result. Optional. The default is an unspecified, stable order.
* `:pageToken` (*type:* `String.t`) - Token specifying which result page to return. Optional.
* `:privateExtendedProperty` (*type:* `list(String.t)`) - Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to return events that match all given constraints.
* `:q` (*type:* `String.t`) - Free text search terms to find events that match these terms in any field, except for extended properties. Optional.
* `:sharedExtendedProperty` (*type:* `list(String.t)`) - Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to return events that match all given constraints.
* `:showDeleted` (*type:* `boolean()`) - Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events (but not the underlying recurring event) will still be included if showDeleted and singleEvents are both False. If showDeleted and singleEvents are both True, only single instances of deleted events (but not the underlying recurring events) are returned. Optional. The default is False.
* `:showHiddenInvitations` (*type:* `boolean()`) - Whether to include hidden invitations in the result. Optional. The default is False.
* `:singleEvents` (*type:* `boolean()`) - Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves. Optional. The default is False.
* `:syncToken` (*type:* `String.t`) - Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False.
There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state.
These are:
- iCalUID
- orderBy
- privateExtendedProperty
- q
- sharedExtendedProperty
- timeMin
- timeMax
- updatedMin If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken.
Learn more about incremental synchronization.
Optional. The default is to return all entries.
* `:timeMax` (*type:* `DateTime.t`) - Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset, for example, 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but are ignored. If timeMin is set, timeMax must be greater than timeMin.
* `:timeMin` (*type:* `DateTime.t`) - Lower bound (exclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with mandatory time zone offset, for example, 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but are ignored. If timeMax is set, timeMin must be smaller than timeMax.
* `:timeZone` (*type:* `String.t`) - Time zone used in the response. Optional. The default is the time zone of the calendar.
* `:updatedMin` (*type:* `DateTime.t`) - Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted. Optional. The default is not to filter by last modification time.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Events{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Events.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_list(connection, calendar_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:alwaysIncludeEmail => :query,
:iCalUID => :query,
:maxAttendees => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:privateExtendedProperty => :query,
:q => :query,
:sharedExtendedProperty => :query,
:showDeleted => :query,
:showHiddenInvitations => :query,
:singleEvents => :query,
:syncToken => :query,
:timeMax => :query,
:timeMin => :query,
:timeZone => :query,
:updatedMin => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/calendars/{calendarId}/events", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Events{}])
end
@doc """
Moves an event to another calendar, i.e. changes an event's organizer.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier of the source calendar where the event currently is on.
* `event_id` (*type:* `String.t`) - Event identifier.
* `destination` (*type:* `String.t`) - Calendar identifier of the target calendar where the event is to be moved to.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:sendNotifications` (*type:* `boolean()`) - Deprecated. Please use sendUpdates instead.
Whether to send notifications about the change of the event's organizer. Note that some emails might still be sent even if you set the value to false. The default is false.
* `:sendUpdates` (*type:* `String.t`) - Guests who should receive notifications about the change of the event's organizer.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_move(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_move(
connection,
calendar_id,
event_id,
destination,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:sendNotifications => :query,
:sendUpdates => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/calendars/{calendarId}/events/{eventId}/move", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1),
"eventId" => URI.encode(event_id, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :destination, destination)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Updates an event. This method supports patch semantics.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `event_id` (*type:* `String.t`) - Event identifier.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:alwaysIncludeEmail` (*type:* `boolean()`) - Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
* `:conferenceDataVersion` (*type:* `integer()`) - Version number of conference data supported by the API client. Version 0 assumes no conference data support and ignores conference data in the event's body. Version 1 enables support for copying of ConferenceData as well as for creating new conferences using the createRequest field of conferenceData. The default is 0.
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:sendNotifications` (*type:* `boolean()`) - Deprecated. Please use sendUpdates instead.
Whether to send notifications about the event update (for example, description changes, etc.). Note that some emails might still be sent even if you set the value to false. The default is false.
* `:sendUpdates` (*type:* `String.t`) - Guests who should receive notifications about the event update (for example, title changes, etc.).
* `:supportsAttachments` (*type:* `boolean()`) - Whether API client performing operation supports event attachments. Optional. The default is False.
* `:body` (*type:* `GoogleApi.Calendar.V3.Model.Event.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_patch(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_patch(connection, calendar_id, event_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:alwaysIncludeEmail => :query,
:conferenceDataVersion => :query,
:maxAttendees => :query,
:sendNotifications => :query,
:sendUpdates => :query,
:supportsAttachments => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/calendars/{calendarId}/events/{eventId}", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1),
"eventId" => URI.encode(event_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Creates an event based on a simple text string.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `text` (*type:* `String.t`) - The text describing the event to be created.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:sendNotifications` (*type:* `boolean()`) - Deprecated. Please use sendUpdates instead.
Whether to send notifications about the creation of the event. Note that some emails might still be sent even if you set the value to false. The default is false.
* `:sendUpdates` (*type:* `String.t`) - Guests who should receive notifications about the creation of the new event.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_quick_add(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_quick_add(connection, calendar_id, text, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:sendNotifications => :query,
:sendUpdates => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/calendars/{calendarId}/events/quickAdd", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1)
})
|> Request.add_param(:query, :text, text)
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Updates an event.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `event_id` (*type:* `String.t`) - Event identifier.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:alwaysIncludeEmail` (*type:* `boolean()`) - Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
* `:conferenceDataVersion` (*type:* `integer()`) - Version number of conference data supported by the API client. Version 0 assumes no conference data support and ignores conference data in the event's body. Version 1 enables support for copying of ConferenceData as well as for creating new conferences using the createRequest field of conferenceData. The default is 0.
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:sendNotifications` (*type:* `boolean()`) - Deprecated. Please use sendUpdates instead.
Whether to send notifications about the event update (for example, description changes, etc.). Note that some emails might still be sent even if you set the value to false. The default is false.
* `:sendUpdates` (*type:* `String.t`) - Guests who should receive notifications about the event update (for example, title changes, etc.).
* `:supportsAttachments` (*type:* `boolean()`) - Whether API client performing operation supports event attachments. Optional. The default is False.
* `:body` (*type:* `GoogleApi.Calendar.V3.Model.Event.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Event{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_update(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Event.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_update(connection, calendar_id, event_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:alwaysIncludeEmail => :query,
:conferenceDataVersion => :query,
:maxAttendees => :query,
:sendNotifications => :query,
:sendUpdates => :query,
:supportsAttachments => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/calendars/{calendarId}/events/{eventId}", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1),
"eventId" => URI.encode(event_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Event{}])
end
@doc """
Watch for changes to Events resources.
## Parameters
* `connection` (*type:* `GoogleApi.Calendar.V3.Connection.t`) - Connection to server
* `calendar_id` (*type:* `String.t`) - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:alwaysIncludeEmail` (*type:* `boolean()`) - Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
* `:iCalUID` (*type:* `String.t`) - Specifies event ID in the iCalendar format to be included in the response. Optional.
* `:maxAttendees` (*type:* `integer()`) - The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* `:maxResults` (*type:* `integer()`) - Maximum number of events returned on one result page. The number of events in the resulting page may be less than this value, or none at all, even if there are more events matching the query. Incomplete pages can be detected by a non-empty nextPageToken field in the response. By default the value is 250 events. The page size can never be larger than 2500 events. Optional.
* `:orderBy` (*type:* `String.t`) - The order of the events returned in the result. Optional. The default is an unspecified, stable order.
* `:pageToken` (*type:* `String.t`) - Token specifying which result page to return. Optional.
* `:privateExtendedProperty` (*type:* `list(String.t)`) - Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to return events that match all given constraints.
* `:q` (*type:* `String.t`) - Free text search terms to find events that match these terms in any field, except for extended properties. Optional.
* `:sharedExtendedProperty` (*type:* `list(String.t)`) - Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to return events that match all given constraints.
* `:showDeleted` (*type:* `boolean()`) - Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events (but not the underlying recurring event) will still be included if showDeleted and singleEvents are both False. If showDeleted and singleEvents are both True, only single instances of deleted events (but not the underlying recurring events) are returned. Optional. The default is False.
* `:showHiddenInvitations` (*type:* `boolean()`) - Whether to include hidden invitations in the result. Optional. The default is False.
* `:singleEvents` (*type:* `boolean()`) - Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves. Optional. The default is False.
* `:syncToken` (*type:* `String.t`) - Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False.
There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state.
These are:
- iCalUID
- orderBy
- privateExtendedProperty
- q
- sharedExtendedProperty
- timeMin
- timeMax
- updatedMin If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken.
Learn more about incremental synchronization.
Optional. The default is to return all entries.
* `:timeMax` (*type:* `DateTime.t`) - Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset, for example, 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but are ignored. If timeMin is set, timeMax must be greater than timeMin.
* `:timeMin` (*type:* `DateTime.t`) - Lower bound (exclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with mandatory time zone offset, for example, 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but are ignored. If timeMax is set, timeMin must be smaller than timeMax.
* `:timeZone` (*type:* `String.t`) - Time zone used in the response. Optional. The default is the time zone of the calendar.
* `:updatedMin` (*type:* `DateTime.t`) - Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted. Optional. The default is not to filter by last modification time.
* `:resource` (*type:* `GoogleApi.Calendar.V3.Model.Channel.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Calendar.V3.Model.Channel{}}` on success
* `{:error, info}` on failure
"""
@spec calendar_events_watch(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Calendar.V3.Model.Channel.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def calendar_events_watch(connection, calendar_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:alwaysIncludeEmail => :query,
:iCalUID => :query,
:maxAttendees => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:privateExtendedProperty => :query,
:q => :query,
:sharedExtendedProperty => :query,
:showDeleted => :query,
:showHiddenInvitations => :query,
:singleEvents => :query,
:syncToken => :query,
:timeMax => :query,
:timeMin => :query,
:timeZone => :query,
:updatedMin => :query,
:resource => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/calendars/{calendarId}/events/watch", %{
"calendarId" => URI.encode(calendar_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Calendar.V3.Model.Channel{}])
end
end
| 60.467879
| 457
| 0.663553
|
93d8d1d7acc6da6776a63654297d287bc4db8d79
| 1,815
|
ex
|
Elixir
|
clients/content/lib/google_api/content/v21/model/metrics.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v21/model/metrics.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v21/model/metrics.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"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.Content.V21.Model.Metrics do
@moduledoc """
Performance metrics. Values are only set for metrics requested explicitly in the request's search query.
## Attributes
* `clicks` (*type:* `String.t`, *default:* `nil`) - Number of clicks.
* `ctr` (*type:* `float()`, *default:* `nil`) - Number of clicks merchant's products receive (clicks) divided by the number of times the products are shown (impressions).
* `impressions` (*type:* `String.t`, *default:* `nil`) - Number of times merchant's products are shown.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:clicks => String.t() | nil,
:ctr => float() | nil,
:impressions => String.t() | nil
}
field(:clicks)
field(:ctr)
field(:impressions)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.Metrics do
def decode(value, options) do
GoogleApi.Content.V21.Model.Metrics.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.Metrics do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.245283
| 174
| 0.707438
|
93d8ea37661ea0880240e423dd5969f8442d6b1c
| 2,137
|
exs
|
Elixir
|
test/rocketpay_web/controllers/users_controller_test.exs
|
cassiofariasmachado/rocketpay
|
7d8cf92f41b67b3861e0e2952579693efe11116b
|
[
"MIT"
] | null | null | null |
test/rocketpay_web/controllers/users_controller_test.exs
|
cassiofariasmachado/rocketpay
|
7d8cf92f41b67b3861e0e2952579693efe11116b
|
[
"MIT"
] | null | null | null |
test/rocketpay_web/controllers/users_controller_test.exs
|
cassiofariasmachado/rocketpay
|
7d8cf92f41b67b3861e0e2952579693efe11116b
|
[
"MIT"
] | null | null | null |
defmodule RocketpayWeb.UsersControllerTest do
use RocketpayWeb.ConnCase, async: true
alias Rocketpay.User
describe "create/2" do
setup %{conn: conn} do
user = %{
name: "Cassio",
password: "123456",
nickname: "cassio",
email: "cassio@yahoo.com",
age: 24
}
{:ok, %User{}} = Rocketpay.create_user(user)
{:ok, conn: conn}
end
test "when all params are valid, create the user", %{conn: conn} do
user = %{
name: "Nathalia",
password: "123456",
nickname: "nathalia",
email: "nathalia@yahoo.com",
age: 20
}
response =
conn
|> post(Routes.users_path(conn, :create, user))
|> json_response(:created)
assert %{
"message" => "User created",
"user" => %{
"account" => %{
"balance" => "0.0"
},
"name" => "Nathalia",
"nickname" => "nathalia"
}
} = response
end
test "when params are invalid, returns an error", %{conn: conn} do
response =
conn
|> post(Routes.users_path(conn, :create, %{}))
|> json_response(:bad_request)
expected_response = %{
"message" => %{
"age" => ["can't be blank"],
"email" => ["can't be blank"],
"name" => ["can't be blank"],
"nickname" => ["can't be blank"],
"password" => ["can't be blank"]
}
}
assert expected_response == response
end
test "when email is already used, returns an error", %{conn: conn} do
user = %{
name: "Cassio",
password: "123456",
nickname: "cassio",
email: "cassio@yahoo.com",
age: 24
}
response =
conn
|> post(Routes.users_path(conn, :create, user))
|> json_response(:bad_request)
expected_response = %{
"message" => %{
"email" => ["has already been taken"]
}
}
assert expected_response == response
end
end
end
| 23.744444
| 73
| 0.482452
|
93d90eb18631d3995f43889998ddc6b29d431d09
| 14,951
|
ex
|
Elixir
|
lib/ecto/adapters/riak/search.ex
|
TanYewWei/ecto
|
916c6467d5f7368fa10ecd7cfcfd2d4a9924a282
|
[
"Apache-2.0"
] | 1
|
2015-08-27T13:17:10.000Z
|
2015-08-27T13:17:10.000Z
|
lib/ecto/adapters/riak/search.ex
|
TanYewWei/ecto
|
916c6467d5f7368fa10ecd7cfcfd2d4a9924a282
|
[
"Apache-2.0"
] | null | null | null |
lib/ecto/adapters/riak/search.ex
|
TanYewWei/ecto
|
916c6467d5f7368fa10ecd7cfcfd2d4a9924a282
|
[
"Apache-2.0"
] | null | null | null |
defmodule Ecto.Adapters.Riak.Search do
@moduledoc """
Yokozuna shares the same query syntax as Apache Solr.
For Solr query options
see -- http://wiki.apache.org/solr/CommonQueryParameters
"""
alias Ecto.Adapters.Riak.Migration
alias Ecto.Adapters.Riak.Object
alias Ecto.Adapters.Riak.SearchHaving
alias Ecto.Adapters.Riak.SearchOrderBy
alias Ecto.Adapters.Riak.SearchSelect
alias Ecto.Adapters.Riak.SearchWhere
alias Ecto.Adapters.Riak.Util, as: RiakUtil
alias Ecto.Query.Query
alias Ecto.Query.Util
alias :riakc_pb_socket, as: RiakSocket
## ----------------------------------------------------------------------
## Types
## ----------------------------------------------------------------------
@type bucket :: binary
@type entity :: Ecto.Entity.t
@type expr_field :: atom ## entity field reference
@type expr_var :: { atom, list, list }
@type expr_order_by :: { :asc | :desc, expr_var, expr_field }
@type query :: Ecto.Query.t
@type querystring :: binary
@type search_index :: binary
@type query_tuple :: { search_index, bucket, querystring, [search_option] }
@type name :: { bucket :: binary,
entity_module :: atom,
model_module :: atom}
## riak search result
## see -- https://github.com/basho/riak-erlang-client/blob/master/include/riakc.hrl
@type search_doc :: { index :: binary,
attr :: [{ binary, binary }] }
@type search_result :: { :search_result,
docs :: [search_doc],
max_score :: integer,
num_found :: integer }
@type source :: { { bucket :: binary, unique_name :: integer },
entity_module :: atom,
model_module :: atom}
@type source_tuple :: { { queryable :: binary, ## the `x` in queryable x do ... end
varname :: binary }, ## unique query variable
entity :: atom, ## entity module
model :: atom} ## module module
@type search_option :: { :index, binary }
| { :q, query :: binary }
| { :df, default_field :: binary }
| { :op, :and | :or }
| { :start, integer } ## used for paging
| { :rows, integer } ## max number of results
| { :sort, fieldname :: binary }
| { :filter, filterquery :: binary }
| { :presort, :key | :score }
## post processing
@type post_proc_fun :: (([entity]) -> term)
## ----------------------------------------------------------------------
## Constants
## ----------------------------------------------------------------------
@timeout 5000
@yz_bucket_key "_yz_rb"
@yz_riak_key "_yz_rk"
@yz_id_key "_yz_id"
@yz_meta_keys [ @yz_bucket_key, @yz_riak_key, @yz_id_key ]
## ----------------------------------------------------------------------
## API
## ----------------------------------------------------------------------
"""
Order of operations:
1. form query from any LIMIT, OFFSET, ORDER_BY, and WHERE clauses
2. for each JOIN clause, construct multiple search queries
to obtain the correct info.
3. generate post-processing function
for dealing with GROUP_BY, HAVING, and SELECT clauses.
The order of post-processing is:
(a) form GROUP_BY groups
(b) apply HAVING aggregate functions
(c) perform SELECT transformations
4. Results processing
- perform sibling resolution
- perform model migration if needed
- if there are joins, merge results based on the join
- apply the post-processing function from step (3)
----------------------------------------------------------------------
NOTES
----------------------------------------------------------------------
"""
@doc """
Constructs a tuple { { querystring, [search_option] }, post_proc_fun }
The querystring and search_option are sent to YZ as a search request,
where post_proc_fun/1 should be called on all results of
the search query in the execute/3 function below.
"""
@spec query(query, Keyword.t) :: { query_tuple, post_proc_fun }
def query(Query[] = query, opts \\ []) do
sources = create_names(query) # :: [source]
model = Util.model(query.from)
search_index = RiakUtil.search_index(model)
bucket = RiakUtil.bucket(model)
## Check to see if unsupported queries are specified
## and raise error if any are present
joins(query)
lock(query)
distincts(query)
## Build Query Part
where = SearchWhere.query(query.wheres, sources)
limit = limit(query.limit)
offset = offset(query.offset)
## querystring defaults to all results
querystring = Enum.join([ where ])
querystring = if querystring == "", do: "*:*", else: querystring
options = List.flatten([ limit, offset ] ++ opts)
|> Enum.filter(&(nil != &1))
query_part = { search_index, bucket, querystring, options }
## Build Post-processing function
group_by = group_by(query.group_bys)
having = SearchHaving.post_proc(query.havings)
order_by = SearchOrderBy.post_proc(query.order_bys, sources)
select = SearchSelect.post_proc(query.select)
post_proc = fn entities ->
group_by.(entities)
|> having.()
|> order_by.()
|> select.()
end
## DONE
{ query_part, post_proc }
end
@doc """
Executes a search query using a provided worker pid,
returning a list of valid entities (or an empty list)
"""
@spec execute(pid, query_tuple, post_proc_fun) :: [entity]
def execute(worker, query_tuple, post_proc_fun) do
if is_get?(query_tuple) do
execute_get(worker, query_tuple)
else
execute_search(worker, query_tuple, post_proc_fun)
end
end
defp is_get?(query_tuple) do
## returns true if the query is intended to only
## get a single riak object
{ _, _, querystring, opts } = query_tuple
case Regex.split(~r":", querystring) do
[k, v] when is_binary(k) and is_binary(v) and k != "*" and v != "*" ->
String.ends_with?(k, "_s") &&
Keyword.get(opts, :rows) == 1
_ ->
false
end
end
defp execute_get(worker, query_tuple) do
{ _, bucket, querystring, opts } = query_tuple
[_, key] = Regex.split(~r":", querystring)
key = String.strip(key, hd ')')
timeout = opts[:timeout] || @timeout
case RiakSocket.get(worker, bucket, key, timeout) do
{ :ok, object } ->
entity = Object.object_to_entity(object)
|> Migration.migrate
[entity]
_ ->
[]
end
end
defp execute_search(worker, query_tuple, post_proc_fun) do
{ search_index, _, querystring, opts } = query_tuple
timeout = opts[:timeout] || @timeout
case RiakSocket.search(worker, search_index, querystring, opts, timeout) do
## -----------------
## Got Search Result
{ :ok, search_result } ->
## get search docs from erlang record representation
search_docs = elem(search_result, 1)
## Reduce search_docs into a HashDict mapping
## the riak object key to a list of stateboxes which
## can be used for sibling resolution
doc_dict = Enum.reduce(search_docs, HashDict.new, fn x, acc ->
case parse_search_result(x) do
{ key, json } ->
box = Object.resolve_to_statebox(json)
fun = &([box | &1])
HashDict.update(acc, key, [box], fun)
_ ->
acc
end
end)
## Use doc_dict to resolve any duplicates (riak siblings).
## The resulting list is a list of entity objects
resolved = Enum.map(HashDict.to_list(doc_dict), fn { _, box_list } ->
:statebox_orddict.from_values(box_list)
|> Object.statebox_to_entity
end)
## Perform any migrations if needed
migrated = Enum.map(resolved, &Migration.migrate/1)
## Apply post_proc_fun and we're done
post_proc_fun.(migrated)
## -------------
## unknown error
_ ->
[]
end
end
@spec parse_search_result(search_doc) :: { riak_key :: binary,
json :: tuple}
defp parse_search_result({ _, doc }) do
riak_key = Dict.get(doc, @yz_riak_key)
proplist =
## Filter out YZ keys
Enum.filter(doc, fn x -> ! (x in @yz_meta_keys) end)
## Riak Search returns list values as multiple key-value tuples.
## Any duplicate keys should have their values put into a list
## ie: { "a":[1,2] } gets returned as: [{"a",1}, {"a",2}]
|> Enum.reduce(HashDict.new(), fn { k, v }, acc ->
HashDict.update(acc, k, v, fn existing ->
if HashDict.has_key?(acc, k) do
if is_list(existing) do
[v | existing]
else
[v, existing]
end
else
v
end
end)
end)
## Transform to list and filter out nil values
|> HashDict.to_list
|> Enum.filter(fn { _, v } -> v != nil end)
## Return
case Dict.get(proplist, "ectomodel_s") do
nil ->
nil
_ ->
json = { proplist }
{ riak_key, json }
end
end
## ----------------------------------------------------------------------
## Unsupported Queries
## ----------------------------------------------------------------------
defp joins(query) do
case query.joins do
[] ->
nil
_ ->
raise Ecto.QueryError, reason: "Riak adapter does not support joins"
end
end
defp lock(query) do
if query.lock do
raise Ecto.QueryError, reason: "Riak adapter does not support locks"
end
end
defp distincts(query) do
case query.distincts do
[] ->
nil
_ ->
raise Ecto.QueryError, reason: "Riak adapter does not support distinct queries"
end
end
## ----------------------------------------------------------------------
## GROUP BY
## ----------------------------------------------------------------------
@spec group_by(term) :: (([entity]) -> [[entity]])
defp group_by([]) do
## Empty group_by query should simply return
## the entire list of entities
fn entities -> entities end
end
defp group_by(group_bys) do
## create a post-processing function
## that accumulates values in a HashDict.
## (intended to be called as a function to Enum.reduce/3)
##
## The hashdict maps tuples of field values
## to a list of entities which have that value.
## eg: grouping by [category_id, title]
## could result in example groups:
## { {2, "fruits"} => [ ... ],
## {3, "veggies"} => [ ... ],
## ... }
##
## An entity should only appear once in this dict
fields = Enum.map(group_bys, fn expr ->
Enum.map(expr.expr, fn { _, field } -> field end)
end)
|> List.flatten
fn entities ->
fun = fn entity, dict ->
## Get values using fields to create key tuple
entity_kw = RiakUtil.entity_keyword(entity)
values = Enum.map(fields, &entity_kw[&1])
key = list_to_tuple(values)
HashDict.update(dict, key, [entity], fn e -> [entity | e] end)
end
Enum.reduce(entities, HashDict.new, fun) |> HashDict.values |> Enum.sort
end
end
## ----------------------------------------------------------------------
## LIMIT, and OFFSET
## ----------------------------------------------------------------------
@spec limit(integer) :: search_option
defp limit(nil), do: nil
defp limit(num) when is_integer(num) do
{ :rows, num }
end
@spec offset(integer) :: search_option
defp offset(nil), do: nil
defp offset(num) when is_integer(num) do
{ :start, num }
end
## ----------------------------------------------------------------------
## Variable Handling
## ----------------------------------------------------------------------
@spec create_names(query) :: source_tuple
def create_names(query) do
## Creates unique variable names for a query
sources = query.sources |> tuple_to_list
Enum.reduce(sources, [], fn { queryable, entity, model }, acc ->
name = unique_name(acc, String.first(queryable), 0)
[{ { queryable, name }, entity, model } | acc]
end)
|> Enum.reverse
|> list_to_tuple
end
@spec unique_name(list, binary, integer) :: binary
defp unique_name(names, name, counter) do
counted_name = name <> integer_to_binary(counter)
if Enum.any?(names, fn { { _, n }, _, _ } -> n == counted_name end) do
unique_name(names, name, counter+1)
else
counted_name
end
end
## ----------------------------------------------------------------------
## Search Schema and Index
## ----------------------------------------------------------------------
@doc """
Sets search indexes for all detected `Ecto.RiakModel` modules.
Called during Ecto.Adapters.Riak.start_link/2 or during the mix
task `mix ecto.create Your.Riak.Repo`
Note: this DOES NOT create and activate the Bucket Type needed for
operation of Yokozuna. Bucket Type creation and activation is
done manually via the mix task `mix ecto.create Your.Riak.Repo`
with functionality implemented in the
`Ecto.Adapters.Riak.storage_up/1` function
"""
@spec search_index_reload_all(pid) :: [{ atom, :ok | { :error, term } }]
def search_index_reload_all(socket) do
models = riak_models()
Enum.map(models, fn model ->
{ model, search_index_reload(socket, model) }
end)
end
def search_index_reload(socket, model) do
schema = RiakUtil.default_search_schema()
search_index = RiakUtil.search_index(model)
case RiakSocket.create_search_index(socket, search_index, schema, []) do
:ok ->
bucket = RiakUtil.bucket(model)
case RiakSocket.set_search_index(socket, bucket, search_index) do
:ok ->
:ok
_ ->
{ :error, "failed to set search index '#{search_index}' on bucket '#{bucket}'" }
end
_ ->
{ :error, "search index '#{search_index}' failed to be created" }
end
end
defp riak_models() do
## returns all models
:code.all_loaded
|> Enum.filter(fn { mod, _ } ->
function_exported?(mod, :__model__, 1)
end)
|> Enum.map(fn { mod, _ } -> mod end)
end
end
| 33.150776
| 92
| 0.533208
|
93d913cb809b2144b0564fa491d0a562425ecca5
| 822
|
ex
|
Elixir
|
lib/aoc2016/day3.ex
|
xingxing/aoc
|
fa07510b4fdd587d971890dd0a785941d74b3288
|
[
"MIT"
] | null | null | null |
lib/aoc2016/day3.ex
|
xingxing/aoc
|
fa07510b4fdd587d971890dd0a785941d74b3288
|
[
"MIT"
] | null | null | null |
lib/aoc2016/day3.ex
|
xingxing/aoc
|
fa07510b4fdd587d971890dd0a785941d74b3288
|
[
"MIT"
] | null | null | null |
defmodule Aoc2016.Day3 do
@moduledoc """
Day 3: Squares With Three Sides
In a valid triangle, the sum of any two sides must be larger than the remaining side.
"""
@input_file_path "priv/2016/day3.txt"
@doc """
iex> Aoc2016.Day3.resolve()
917
"""
def resolve do
@input_file_path
|> File.stream!([:read], :line)
|> Enum.filter(fn (l) ->
valid_triangle?(l)
end)
|> length
end
@doc """
iex> Aoc2016.Day3.valid_triangle?("5 10 25")
false
"""
def valid_triangle?(line) do
[x, y, z] = line |> to_int
((x + y) > z) and ((y + z) > x) and ((x + z) > y)
end
def to_int(line) do
line
|> String.split(~r/\W+/)
|> Stream.filter(fn(w) -> String.trim(w) != "" end)
|> Enum.map(fn(x) ->
{n, _} = Integer.parse(x)
n
end)
end
end
| 19.116279
| 87
| 0.554745
|
93d92b7d7c9c21e3e22ea93f5f09cc5f51f7aa3a
| 472
|
exs
|
Elixir
|
package.head.exs
|
yrashk/erlang-ossp-uuid
|
a279ce337dce5d6d5bebfacd61b9ba08ecddfe0d
|
[
"MIT"
] | 3
|
2018-06-20T00:01:00.000Z
|
2022-02-06T15:34:43.000Z
|
package.head.exs
|
yrashk/erlang-ossp-uuid
|
a279ce337dce5d6d5bebfacd61b9ba08ecddfe0d
|
[
"MIT"
] | 2
|
2015-11-10T22:39:54.000Z
|
2016-06-19T23:08:02.000Z
|
package.head.exs
|
yrashk/erlang-ossp-uuid
|
a279ce337dce5d6d5bebfacd61b9ba08ecddfe0d
|
[
"MIT"
] | 5
|
2015-01-20T14:26:16.000Z
|
2020-01-21T02:31:23.000Z
|
Expm.Package.new(name: "ossp_uuid", description: "NIF-based ossp-uuid binding",
version: :head, keywords: ["Erlang","UUID"],
maintainers: [[name: "Yurii Rashkovskii", email: "yrashk@gmail.com"]],
contributors: [[name: "Michael Santos", email: "michael.santos@gmail.com"],
[name: "OJ Reeves", email: "oj@buffered.io"]],
repositories: [[github: "yrashk/erlang-ossp-uuid"]])
| 67.428571
| 92
| 0.555085
|
93d9474c7d01c478d3d0fa735edc689eefe53278
| 468
|
exs
|
Elixir
|
Chapter09/apps/elixir_drip/config/test.exs
|
sthagen/Mastering-Elixir
|
1b52ee79afe6b2ae80767a5e55c2be51df3c4c1d
|
[
"MIT"
] | 28
|
2018-08-09T05:05:29.000Z
|
2022-03-14T06:59:07.000Z
|
Chapter09/apps/elixir_drip/config/test.exs
|
sthagen/Mastering-Elixir
|
1b52ee79afe6b2ae80767a5e55c2be51df3c4c1d
|
[
"MIT"
] | 1
|
2019-02-11T09:11:33.000Z
|
2019-05-06T06:40:19.000Z
|
Chapter09/apps/elixir_drip/config/test.exs
|
sthagen/Mastering-Elixir
|
1b52ee79afe6b2ae80767a5e55c2be51df3c4c1d
|
[
"MIT"
] | 8
|
2018-08-09T14:53:02.000Z
|
2020-12-14T19:31:21.000Z
|
use Mix.Config
config :elixir_drip, storage_provider: ElixirDrip.Storage.Providers.GoogleCloudStorageMock
# Configure your database
config :elixir_drip, ElixirDrip.Repo,
adapter: Ecto.Adapters.Postgres,
username: System.get_env("DB_USER"),
password: System.get_env("DB_PASS"),
database: System.get_env("DB_NAME"),
hostname: System.get_env("DB_HOST"),
port: System.get_env("DB_PORT"),
pool: Ecto.Adapters.SQL.Sandbox
config :stream_data, max_runs: 500
| 29.25
| 90
| 0.773504
|
93d98b4c9258332123ce63cc54207c35ff42e55f
| 975
|
exs
|
Elixir
|
mix.exs
|
amorphid/json_momoa
|
ab31268fd29b9d3b175972346f797f83461cabf6
|
[
"Apache-2.0"
] | null | null | null |
mix.exs
|
amorphid/json_momoa
|
ab31268fd29b9d3b175972346f797f83461cabf6
|
[
"Apache-2.0"
] | null | null | null |
mix.exs
|
amorphid/json_momoa
|
ab31268fd29b9d3b175972346f797f83461cabf6
|
[
"Apache-2.0"
] | null | null | null |
defmodule JSONMomoa.MixProject do
use Mix.Project
#######
# API #
#######
def application() do
[
extra_applications: [:logger],
mod: {JSONMomoa.Application, []}
]
end
def project() do
[
app: :json_momoa,
deps: deps(),
description: description(),
# feel free to submit pull request w/ lower Elixir version
elixir: "~> 1.8",
package: package(),
start_permanent: Mix.env() == :prod,
version: "0.1.0"
]
end
###########
# Private #
###########
defp deps() do
[
# static analysis
{:dialyxir, "~> 1.0.0-rc.4", only: [:dev], runtime: false},
# document generation
{:ex_doc, ">= 0.0.0", only: [:dev]}
]
end
defp description() do
"A streaming JSON parser/encoder written in pure Elixir."
end
defp package() do
[
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/amorphid/json_momoa"}
]
end
end
| 18.75
| 68
| 0.531282
|
93d98f2231c3b477808294f0971aa189ff39c1d6
| 2,231
|
ex
|
Elixir
|
lib/pow/phoenix/html/form_template.ex
|
patrickbiermann/pow
|
ebc2ac7d6e15961dac4be38091ff75dae0d26554
|
[
"MIT"
] | 4
|
2018-05-07T16:37:15.000Z
|
2018-07-14T00:44:12.000Z
|
lib/pow/phoenix/html/form_template.ex
|
patrickbiermann/pow
|
ebc2ac7d6e15961dac4be38091ff75dae0d26554
|
[
"MIT"
] | null | null | null |
lib/pow/phoenix/html/form_template.ex
|
patrickbiermann/pow
|
ebc2ac7d6e15961dac4be38091ff75dae0d26554
|
[
"MIT"
] | 1
|
2020-07-13T01:11:17.000Z
|
2020-07-13T01:11:17.000Z
|
defmodule Pow.Phoenix.HTML.FormTemplate do
@moduledoc """
Module that can build user form templates for Phoenix.
For Phoenix 1.3, or bootstrap templates, `Pow.Phoenix.HTML.Bootstrap` can be
used.
"""
alias Pow.Phoenix.HTML.Bootstrap
@template EEx.compile_string(
"""
<%%= form_for @changeset, @action, [as: :user], fn f -> %>
<%%= if @changeset.action do %>
<div class="alert alert-danger">
<p>Oops, something went wrong! Please check the errors below.</p>
</div>
<%% end %>
<%= for {label, input, error} <- inputs, input do %>
<%= label %>
<%= input %>
<%= error %>
<% end %>
<div>
<%%= submit <%= inspect button_label %> %>
</div>
<%% end %>
""")
@doc """
Renders a form.
## Options
* `:button_label` - the submit button label, defaults to "Submit".
* `:bootstrap` - to render form as bootstrap, defaults to false with
phoenix 1.4 and true with phoenix 1.3.
"""
@spec render(list(), Keyword.t()) :: Macro.t()
def render(inputs, opts \\ []) do
button_label = Keyword.get(opts, :button_label, "Submit")
case bootstrap?(opts) do
true -> Bootstrap.render_form(inputs, button_label)
_any -> render_form(inputs, button_label)
end
end
# TODO: Remove bootstrap support by 1.1.0 and only support Phoenix 1.4.0
defp bootstrap?(opts) do
bootstrap = Pow.dependency_vsn_match?(:phoenix, "~> 1.3.0")
Keyword.get(opts, :bootstrap, bootstrap)
end
defp render_form(inputs, button_label) do
inputs = for {type, key} <- inputs, do: input(type, key)
unquote(@template)
end
defp input(:text, key) do
{label(key), ~s(<%= text_input f, #{inspect_key(key)} %>), error(key)}
end
defp input(:password, key) do
{label(key), ~s(<%= password_input f, #{inspect_key(key)} %>), error(key)}
end
defp label(key) do
~s(<%= label f, #{inspect_key(key)} %>)
end
defp error(key) do
~s(<%= error_tag f, #{inspect_key(key)} %>)
end
@doc false
@spec inspect_key(any()) :: binary()
def inspect_key({:changeset, :pow_user_id_field}), do: "Pow.Ecto.Schema.user_id_field(@changeset)"
def inspect_key(key), do: inspect(key)
end
| 27.54321
| 100
| 0.609144
|
93d9ad97a5633852cb5fb19b41851ca5aeee0906
| 95
|
ex
|
Elixir
|
lib/places_alloverse_com_web/views/user_confirmation_view.ex
|
alloverse/places_alloverse_com
|
5c15ea08a88429378ce8f41047418e166cbde7e9
|
[
"BSD-2-Clause"
] | null | null | null |
lib/places_alloverse_com_web/views/user_confirmation_view.ex
|
alloverse/places_alloverse_com
|
5c15ea08a88429378ce8f41047418e166cbde7e9
|
[
"BSD-2-Clause"
] | 1
|
2021-03-10T11:40:47.000Z
|
2021-03-10T11:40:47.000Z
|
lib/places_alloverse_com_web/views/user_confirmation_view.ex
|
alloverse/places_alloverse_com
|
5c15ea08a88429378ce8f41047418e166cbde7e9
|
[
"BSD-2-Clause"
] | null | null | null |
defmodule PlacesAlloverseComWeb.UserConfirmationView do
use PlacesAlloverseComWeb, :view
end
| 23.75
| 55
| 0.873684
|
93d9bfa97cf2e7d66c8f0e0c113f91364dd1c236
| 1,591
|
ex
|
Elixir
|
clients/big_query/lib/google_api/big_query/v2/model/category_count.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/big_query/lib/google_api/big_query/v2/model/category_count.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/big_query/lib/google_api/big_query/v2/model/category_count.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigQuery.V2.Model.CategoryCount do
@moduledoc """
Represents the count of a single category within the cluster.
## Attributes
* `category` (*type:* `String.t`, *default:* `nil`) - The name of category.
* `count` (*type:* `String.t`, *default:* `nil`) - The count of training samples matching the category within the cluster.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:category => String.t() | nil,
:count => String.t() | nil
}
field(:category)
field(:count)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.CategoryCount do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.CategoryCount.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.CategoryCount do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.82
| 126
| 0.719673
|
93da190561e641ccd5d8ada0a227a905ed7aaa4c
| 2,212
|
ex
|
Elixir
|
apps/local_ledger/lib/local_ledger/entry.ex
|
jimpeebles/ewallet
|
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
|
[
"Apache-2.0"
] | null | null | null |
apps/local_ledger/lib/local_ledger/entry.ex
|
jimpeebles/ewallet
|
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
|
[
"Apache-2.0"
] | null | null | null |
apps/local_ledger/lib/local_ledger/entry.ex
|
jimpeebles/ewallet
|
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule LocalLedger.Entry do
@moduledoc """
This module is responsible for preparing and formatting the entries
before they are passed to a transaction to be inserted in the database.
"""
alias LocalLedgerDB.{Entry, Token, Wallet}
@doc """
Get or insert the given token and all the given addresses before
building a map representation usable by the LocalLedgerDB schemas.
"""
def build_all(entries) do
Enum.map(entries, fn attrs ->
{:ok, token} = Token.get_or_insert(attrs["token"])
{:ok, wallet} = Wallet.get_or_insert(attrs)
%{
type: attrs["type"],
amount: attrs["amount"],
token_id: token.id,
wallet_address: wallet.address
}
end)
end
@doc """
Extract the list of DEBIT addresses.
"""
def get_addresses(entries) do
entries
|> Enum.filter(fn entry ->
entry[:type] == Entry.debit_type()
end)
|> Enum.map(fn entry -> entry[:wallet_address] end)
end
@doc """
Match when genesis is set to true and does... nothing.
"""
def check_balance(_, %{genesis: true}) do
:ok
end
@doc """
Match when genesis is false and run the wallet check.
"""
def check_balance(entries, %{genesis: _}) do
check_balance(entries)
end
@doc """
Check the current wallet amount for each DEBIT entry.
"""
def check_balance(entries) do
Enum.each(entries, fn entry ->
if entry[:type] == Entry.debit_type() do
Entry.check_balance(%{
amount: entry[:amount],
token_id: entry[:token_id],
address: entry[:wallet_address]
})
end
end)
end
end
| 27.65
| 74
| 0.665913
|
93da4c64b5cff30ecd9cde03f956c611664ed38d
| 1,636
|
ex
|
Elixir
|
clients/sheets/lib/google_api/sheets/v4/model/delete_conditional_format_rule_response.ex
|
hauptbenutzer/elixir-google-api
|
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
|
[
"Apache-2.0"
] | null | null | null |
clients/sheets/lib/google_api/sheets/v4/model/delete_conditional_format_rule_response.ex
|
hauptbenutzer/elixir-google-api
|
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
|
[
"Apache-2.0"
] | null | null | null |
clients/sheets/lib/google_api/sheets/v4/model/delete_conditional_format_rule_response.ex
|
hauptbenutzer/elixir-google-api
|
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
|
[
"Apache-2.0"
] | 1
|
2020-11-10T16:58:27.000Z
|
2020-11-10T16:58:27.000Z
|
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Sheets.V4.Model.DeleteConditionalFormatRuleResponse do
@moduledoc """
The result of deleting a conditional format rule.
## Attributes
- rule (ConditionalFormatRule): The rule that was deleted. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:rule => GoogleApi.Sheets.V4.Model.ConditionalFormatRule.t()
}
field(:rule, as: GoogleApi.Sheets.V4.Model.ConditionalFormatRule)
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.DeleteConditionalFormatRuleResponse do
def decode(value, options) do
GoogleApi.Sheets.V4.Model.DeleteConditionalFormatRuleResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.DeleteConditionalFormatRuleResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.083333
| 93
| 0.762836
|
93da6b13f0fec7f97bbb66f1dc6f0f9d85706e6e
| 1,060
|
ex
|
Elixir
|
test/support/conn_case.ex
|
AmadorZcv/crius_chat
|
2ed002414f207536a0d2ab6e53e7d99da9fa920d
|
[
"MIT"
] | null | null | null |
test/support/conn_case.ex
|
AmadorZcv/crius_chat
|
2ed002414f207536a0d2ab6e53e7d99da9fa920d
|
[
"MIT"
] | 3
|
2021-03-09T17:37:23.000Z
|
2021-09-01T22:28:38.000Z
|
test/support/conn_case.ex
|
AmadorZcv/crius_chat
|
2ed002414f207536a0d2ab6e53e7d99da9fa920d
|
[
"MIT"
] | null | null | null |
defmodule CriusChatWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias CriusChatWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint CriusChatWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(CriusChat.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(CriusChat.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 27.179487
| 71
| 0.720755
|
93da7bd4bcf9cc13e7997aebd478e0bd6465d9e3
| 1,115
|
ex
|
Elixir
|
lib/ergo_web/router.ex
|
insprac/ergo
|
978970ba7f9639adb7ff8c32fec8cd25f487c656
|
[
"MIT"
] | null | null | null |
lib/ergo_web/router.ex
|
insprac/ergo
|
978970ba7f9639adb7ff8c32fec8cd25f487c656
|
[
"MIT"
] | 2
|
2021-03-10T22:00:43.000Z
|
2021-05-11T17:17:30.000Z
|
lib/ergo_web/router.ex
|
insprac/ergo
|
978970ba7f9639adb7ff8c32fec8cd25f487c656
|
[
"MIT"
] | null | null | null |
defmodule ErgoWeb.Router do
use ErgoWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {ErgoWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", ErgoWeb do
pipe_through :browser
live "/", PageLive, :index
end
# Other scopes may use custom stacks.
# scope "/api", ErgoWeb do
# pipe_through :api
# end
# Enables LiveDashboard only for development
#
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
if Mix.env() in [:dev, :test] do
import Phoenix.LiveDashboard.Router
scope "/" do
pipe_through :browser
live_dashboard "/dashboard", metrics: ErgoWeb.Telemetry
end
end
end
| 25.340909
| 70
| 0.695964
|
93da7e26386a637aca72b36d938921dacc241000
| 5,678
|
exs
|
Elixir
|
test/ecto/integration/crud_test.exs
|
dozoyo/exqlite
|
517eaa7f39be7effad0e968986f708f7845e1d5c
|
[
"MIT"
] | null | null | null |
test/ecto/integration/crud_test.exs
|
dozoyo/exqlite
|
517eaa7f39be7effad0e968986f708f7845e1d5c
|
[
"MIT"
] | null | null | null |
test/ecto/integration/crud_test.exs
|
dozoyo/exqlite
|
517eaa7f39be7effad0e968986f708f7845e1d5c
|
[
"MIT"
] | null | null | null |
defmodule Ecto.Integration.CrudTest do
use Ecto.Integration.Case
alias Ecto.Integration.TestRepo
alias Exqlite.Integration.Account
alias Exqlite.Integration.User
alias Exqlite.Integration.AccountUser
alias Exqlite.Integration.Product
import Ecto.Query
describe "insert" do
test "insert user" do
{:ok, user1} = TestRepo.insert(%User{name: "John"}, [])
assert user1
{:ok, user2} = TestRepo.insert(%User{name: "James"}, [])
assert user2
assert user1.id != user2.id
user =
User
|> select([u], u)
|> where([u], u.id == ^user1.id)
|> TestRepo.one()
assert user.name == "John"
end
test "handles nulls when querying correctly" do
{:ok, account} =
%Account{name: "Something"}
|> TestRepo.insert()
{:ok, product} =
%Product{
name: "Thing",
account_id: account.id,
approved_at: nil
}
|> TestRepo.insert()
found = TestRepo.get(Product, product.id)
assert found.id == product.id
assert found.approved_at == nil
assert found.description == nil
assert found.name == "Thing"
assert found.tags == []
end
test "insert_all" do
timestamp = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
account = %{
name: "John",
inserted_at: timestamp,
updated_at: timestamp,
}
{1, nil} = TestRepo.insert_all(Account, [account], [])
end
end
describe "delete" do
test "deletes user" do
{:ok, user} = TestRepo.insert(%User{name: "John"}, [])
{:ok, _} = TestRepo.delete(user)
end
@tag :busy_repo
test "delete_all deletes one product" do
TestRepo.insert!(%Product{name: "hello"})
# we have to do this because the tests are not isolated from one another.
# @kevinlang is working on rectifying that problem
assert {total, _} = TestRepo.delete_all(Product)
assert total >= 1
end
# this test keeps on hitting busy issues, not sure why
# one error i saw, tho not sure what test exactly, was
# passes fine in isolation.
@tag :busy_repo
test "delete_all deletes all products" do
TestRepo.insert!(%Product{name: "hello"})
TestRepo.insert!(%Product{name: "hello again"})
# we have to do this because the tests are not isolated from one another.
# @kevinlang is working on rectifying that problem
assert {total, _} = TestRepo.delete_all(Product)
assert total >= 2
end
end
describe "update" do
test "updates user" do
{:ok, user} = TestRepo.insert(%User{name: "John"}, [])
changeset = User.changeset(user, %{name: "Bob"})
{:ok, changed} = TestRepo.update(changeset)
assert changed.name == "Bob"
end
end
describe "transaction" do
test "successful user and account creation" do
{:ok, _} =
Ecto.Multi.new()
|> Ecto.Multi.insert(:account, fn _ ->
Account.changeset(%Account{}, %{name: "Foo"})
end)
|> Ecto.Multi.insert(:user, fn _ ->
User.changeset(%User{}, %{name: "Bob"})
end)
|> Ecto.Multi.insert(:account_user, fn %{account: account, user: user} ->
AccountUser.changeset(%AccountUser{}, %{
account_id: account.id,
user_id: user.id
})
end)
|> TestRepo.transaction()
end
# "cannot open savepoint - SQL statements in progress"
# which indicates we are not closing some of our statement handles
# properly, which is manifesting in this test not being able to run
# though it passes fine in isolation... - kcl
# test "unsuccessful account creation" do
# {:error, _, _, _} =
# Ecto.Multi.new()
# |> Ecto.Multi.insert(:account, fn _ ->
# Account.changeset(%Account{}, %{name: nil})
# end)
# |> Ecto.Multi.insert(:user, fn _ ->
# User.changeset(%User{}, %{name: "Bob"})
# end)
# |> Ecto.Multi.insert(:account_user, fn %{account: account, user: user} ->
# AccountUser.changeset(%AccountUser{}, %{
# account_id: account.id,
# user_id: user.id
# })
# end)
# |> TestRepo.transaction()
# end
test "unsuccessful user creation" do
{:error, _, _, _} =
Ecto.Multi.new()
|> Ecto.Multi.insert(:account, fn _ ->
Account.changeset(%Account{}, %{name: "Foo"})
end)
|> Ecto.Multi.insert(:user, fn _ ->
User.changeset(%User{}, %{name: nil})
end)
|> Ecto.Multi.insert(:account_user, fn %{account: account, user: user} ->
AccountUser.changeset(%AccountUser{}, %{
account_id: account.id,
user_id: user.id
})
end)
|> TestRepo.transaction()
end
end
describe "preloading" do
test "preloads many to many relation" do
account1 = TestRepo.insert!(%Account{name: "Main"})
account2 = TestRepo.insert!(%Account{name: "Secondary"})
user1 = TestRepo.insert!(%User{name: "John"}, [])
user2 = TestRepo.insert!(%User{name: "Shelly"}, [])
TestRepo.insert!(%AccountUser{user_id: user1.id, account_id: account1.id})
TestRepo.insert!(%AccountUser{user_id: user1.id, account_id: account2.id})
TestRepo.insert!(%AccountUser{user_id: user2.id, account_id: account2.id})
accounts = from(a in Account, preload: [:users]) |> TestRepo.all()
assert Enum.count(accounts) == 2
Enum.each(accounts, fn account ->
assert Ecto.assoc_loaded?(account.users)
end)
end
end
end
| 30.526882
| 83
| 0.587707
|
93da878fe019493ba42db2d5e7f9b397ecbde2aa
| 72
|
ex
|
Elixir
|
lib/madari_web/views/user_reset_password_view.ex
|
yoossaland/yoossa
|
1e1ab968d12c7690a76fc670c47c91c29efb2979
|
[
"BSD-2-Clause"
] | null | null | null |
lib/madari_web/views/user_reset_password_view.ex
|
yoossaland/yoossa
|
1e1ab968d12c7690a76fc670c47c91c29efb2979
|
[
"BSD-2-Clause"
] | null | null | null |
lib/madari_web/views/user_reset_password_view.ex
|
yoossaland/yoossa
|
1e1ab968d12c7690a76fc670c47c91c29efb2979
|
[
"BSD-2-Clause"
] | null | null | null |
defmodule MadariWeb.UserResetPasswordView do
use MadariWeb, :view
end
| 18
| 44
| 0.833333
|
93dac29905b48a200f3e2ab180fa7df040925408
| 2,265
|
ex
|
Elixir
|
clients/script/lib/google_api/script/v1/model/google_apps_script_type_add_on_entry_point.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/script/lib/google_api/script/v1/model/google_apps_script_type_add_on_entry_point.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/script/lib/google_api/script/v1/model/google_apps_script_type_add_on_entry_point.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.Script.V1.Model.GoogleAppsScriptTypeAddOnEntryPoint do
@moduledoc """
An add-on entry point.
## Attributes
* `addOnType` (*type:* `String.t`, *default:* `nil`) - The add-on's required list of supported container types.
* `description` (*type:* `String.t`, *default:* `nil`) - The add-on's optional description.
* `helpUrl` (*type:* `String.t`, *default:* `nil`) - The add-on's optional help URL.
* `postInstallTipUrl` (*type:* `String.t`, *default:* `nil`) - The add-on's required post install tip URL.
* `reportIssueUrl` (*type:* `String.t`, *default:* `nil`) - The add-on's optional report issue URL.
* `title` (*type:* `String.t`, *default:* `nil`) - The add-on's required title.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:addOnType => String.t(),
:description => String.t(),
:helpUrl => String.t(),
:postInstallTipUrl => String.t(),
:reportIssueUrl => String.t(),
:title => String.t()
}
field(:addOnType)
field(:description)
field(:helpUrl)
field(:postInstallTipUrl)
field(:reportIssueUrl)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.Script.V1.Model.GoogleAppsScriptTypeAddOnEntryPoint do
def decode(value, options) do
GoogleApi.Script.V1.Model.GoogleAppsScriptTypeAddOnEntryPoint.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Script.V1.Model.GoogleAppsScriptTypeAddOnEntryPoint do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.532258
| 115
| 0.695364
|
93dae40cdd372e14d87c4943cb19c75b51f1d6f3
| 10,144
|
ex
|
Elixir
|
apps/gitgud/lib/gitgud/schemas/issue.ex
|
rogervezaro/gitgud
|
6656f8c2df16817a6c5325fb4c18b03f9d3f7140
|
[
"MIT"
] | null | null | null |
apps/gitgud/lib/gitgud/schemas/issue.ex
|
rogervezaro/gitgud
|
6656f8c2df16817a6c5325fb4c18b03f9d3f7140
|
[
"MIT"
] | null | null | null |
apps/gitgud/lib/gitgud/schemas/issue.ex
|
rogervezaro/gitgud
|
6656f8c2df16817a6c5325fb4c18b03f9d3f7140
|
[
"MIT"
] | null | null | null |
defmodule GitGud.Issue do
@moduledoc """
Issue schema and helper functions.
"""
use Ecto.Schema
alias Ecto.Multi
alias GitGud.DB
alias GitGud.Repo
alias GitGud.User
alias GitGud.IssueLabel
alias GitGud.Comment
import Ecto.Changeset
import Ecto.Query, only: [from: 2]
schema "issues" do
belongs_to :repo, Repo
field :number, :integer, read_after_writes: true
field :title, :string
field :status, :string, default: "open"
belongs_to :author, User
many_to_many :labels, IssueLabel, join_through: "issues_labels", join_keys: [issue_id: :id, label_id: :id]
many_to_many :comments, Comment, join_through: "issues_comments", join_keys: [thread_id: :id, comment_id: :id]
field :events, {:array, :map}
timestamps()
end
@type t :: %__MODULE__{
id: pos_integer,
repo: Repo.t,
number: pos_integer,
author_id: pos_integer,
author: User.t,
repo_id: pos_integer,
labels: [IssueLabel.t],
comments: [Comment.t],
events: [map],
inserted_at: NaiveDateTime.t,
updated_at: NaiveDateTime.t
}
@doc """
Creates a new issue with the given `params`.
```elixir
{:ok, issue} = GitGud.Issue.create(repo_id: repo.id, author_id: user.id, title: "Help me!", comments: [author_id: user.id, body: "I really need help."])
```
This function validates the given `params` using `changeset/2`.
"""
@spec create(map | keyword) :: {:ok, t} | {:error, Ecto.Changeset.t}
def create(params) do
DB.insert(changeset(%__MODULE__{}, map_issue_params(params)))
end
@doc """
Similar to `create/1`, but raises an `Ecto.InvalidChangesetError` if an error occurs.
"""
@spec create!(map | keyword) :: t
def create!(params) do
DB.insert!(changeset(%__MODULE__{}, map_issue_params(params)))
end
@doc """
Closes the given `issue`.
"""
@spec close(t) :: {:ok, t} | {:error, Ecto.Changeset.t}
def close(issue, opts \\ [])
def close(%__MODULE__{status: "close"} = issue, _opts), do: {:ok, issue}
def close(%__MODULE__{} = issue, opts) do
query = from(i in __MODULE__, where: i.id == ^issue.id, select: i)
event = Map.merge(Map.new(opts), %{type: "close", timestamp: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)})
case DB.update_all(query, set: [status: "close", updated_at: event.timestamp], push: [events: event]) do
{1, [new_issue]} ->
{:ok, struct(new_issue, Map.take(issue, __schema__(:associations)))}
{0, nil} ->
changeset = change(issue, status: "close", events: issue.events ++ [event])
{:error, %{changeset|action: :update}}
end
end
@doc """
Similar to `close/1`, but raises an `Ecto.InvalidChangesetError` if an error occurs.
"""
@spec close!(t) :: t
def close!(%__MODULE__{} = issue, opts \\ []) do
case close(issue, opts) do
{:ok, issue} -> issue
{:error, changeset} -> raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset
end
end
@doc """
Reopens the given `issue`.
"""
@spec reopen(t) :: {:ok, t} | {:error, term}
def reopen(issue, opts \\ [])
def reopen(%__MODULE__{status: "open"} = issue, _opts), do: {:ok, issue}
def reopen(%__MODULE__{} = issue, opts) do
query = from(i in __MODULE__, where: i.id == ^issue.id, select: i)
event = Map.merge(Map.new(opts), %{type: "reopen", timestamp: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)})
case DB.update_all(query, set: [status: "open", updated_at: event.timestamp], push: [events: event]) do
{1, [new_issue]} ->
{:ok, struct(new_issue, Map.take(issue, __schema__(:associations)))}
{0, nil} ->
changeset = change(issue, status: "open", events: issue.events ++ [event])
{:error, %{changeset|action: :update}}
end
end
@doc """
Similar to `reopen/1`, but raises an `Ecto.InvalidChangesetError` if an error occurs.
"""
@spec reopen!(t) :: t
def reopen!(%__MODULE__{} = issue, opts \\ []) do
case reopen(issue, opts) do
{:ok, issue} -> issue
{:error, changeset} -> raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset
end
end
@doc """
Updates the title of the given `issue`.
"""
@spec update_title(t, binary, keyword) :: {:ok, t} | {:error, term}
def update_title(issue, title, opts \\ [])
def update_title(%__MODULE__{title: title} = issue, title, _opts), do: {:ok, issue}
def update_title(%__MODULE__{} = issue, title, opts) do
query = from(i in __MODULE__, where: i.id == ^issue.id, select: i)
event = Map.merge(Map.new(Keyword.merge([old_title: issue.title, new_title: title], opts)), %{type: "title_update", timestamp: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)})
case DB.update_all(query, set: [title: title, updated_at: event.timestamp], push: [events: event]) do
{1, [new_issue]} ->
{:ok, struct(new_issue, Map.take(issue, __schema__(:associations)))}
{0, nil} ->
changeset = change(issue, title: title, events: issue.events ++ [event])
{:error, %{changeset|action: :update}}
end
end
@doc """
Similar to `update_title/2`, but raises an `Ecto.InvalidChangesetError` if an error occurs.
"""
@spec update_title!(t, binary, keyword) :: t
def update_title!(%__MODULE__{} = issue, title, opts \\ []) do
case update_title(issue, title, opts) do
{:ok, issue} -> issue
{:error, changeset} -> raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset
end
end
@doc """
Updates the labels of the given `issue`.
"""
@spec update_labels(t, {[pos_integer], [pos_integer]}, keyword) :: {:ok, t} | {:error, term}
def update_labels(%__MODULE__{} = issue, {labels_push, labels_pull} = _changes, opts \\ []) do
multi = Multi.new()
multi =
unless Enum.empty?(labels_push),
do: Multi.insert_all(multi, :issue_labels_push, "issues_labels", Enum.map(labels_push, &Map.new(issue_id: issue.id, label_id: &1))),
else: multi
multi =
unless Enum.empty?(labels_pull),
do: Multi.delete_all(multi, :issue_labels_pull, from(l in "issues_labels", where: l.issue_id == ^issue.id and l.label_id in ^labels_pull)),
else: multi
query = from(i in __MODULE__, where: i.id == ^issue.id, select: i)
event = Map.merge(Map.new(Keyword.merge([push: labels_push, pull: labels_pull, updated_at: NaiveDateTime.utc_now()], opts)), %{type: "labels_update", timestamp: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)})
multi = Multi.update_all(multi, :issue, query, push: [events: event])
case DB.transaction(multi) do
{:ok, %{issue: {1, [issue]}}} ->
{:ok, DB.preload(issue, :labels)}
{:error, _operation, reason, _changes} ->
{:error, reason}
end
end
@doc """
Similar to `update_labels/2`, but raises an `Ecto.InvalidChangesetError` if an error occurs.
"""
@spec update_labels!(t, {[pos_integer], [pos_integer]}, keyword) :: t
def update_labels!(%__MODULE__{} = issue, changes, opts \\ []) do
case update_labels(issue, changes, opts) do
{:ok, issue} -> issue
{:error, changeset} -> raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset
end
end
@doc """
Adds a new comment.
"""
@spec add_comment(t, User.t, binary) :: {:ok, Comment.t} | {:error, term}
def add_comment(%__MODULE__{} = issue, author, body) do
case DB.transaction(insert_issue_comment(issue.repo_id, issue.id, author.id, body)) do
{:ok, %{comment: comment}} ->
{:ok, struct(comment, issue: issue, author: author)}
{:error, _operation, reason, _changes} ->
{:error, reason}
end
end
@doc """
Returns an issue changeset for the given `params`.
"""
@spec changeset(t, map) :: Ecto.Changeset.t
def changeset(%__MODULE__{} = issue, params \\ %{}) do
issue
|> cast(params, [:repo_id, :author_id, :title])
|> cast_assoc(:comments, with: &Comment.changeset/2)
|> validate_required([:repo_id, :author_id, :title])
|> put_labels()
|> assoc_constraint(:repo)
|> assoc_constraint(:author)
end
#
# Protocols
#
defimpl GitGud.AuthorizationPolicies do
alias GitGud.Issue
# Owner can do everything
def can?(%Issue{author_id: user_id}, %User{id: user_id}, _action), do: true
# Everybody can read comments.
def can?(%Issue{}, _user, :read), do: true
# Everybody can write comments if the issue is open.
def can?(%Issue{status: "open"}, _user, :write), do: true
# Everything-else is forbidden.
def can?(%Issue{}, _user, _actions), do: false
end
#
# Helpers
#
defp put_labels(changeset) do
if labels = changeset.params["labels"],
do: put_assoc(changeset, :labels, labels),
else: changeset
end
defp map_issue_params(issue_params) do
issue_params =
Map.new(issue_params, fn
{key, val} when is_atom(key) -> {key, val}
{key, val} when is_binary(key) -> {String.to_atom(key), val}
end)
Map.update(issue_params, :comments, [], fn comments -> Enum.map(comments, &map_comment_params(issue_params, &1)) end)
end
defp map_comment_params(issue_params, {_index, comment_params}) do
map_comment_params(issue_params, comment_params)
end
defp map_comment_params(issue_params, comment_params) do
comment_params =
Map.new(comment_params, fn
{key, val} when is_atom(key) -> {key, val}
{key, val} when is_binary(key) -> {String.to_atom(key), val}
end)
Map.merge(comment_params, %{repo_id: issue_params[:repo_id], thread_table: "issues_comments", author_id: issue_params[:author_id]})
end
defp insert_issue_comment(repo_id, issue_id, author_id, body) do
Multi.new()
|> Multi.insert(:comment, Comment.changeset(%Comment{}, %{repo_id: repo_id, thread_table: "issues_comments", author_id: author_id, body: body}))
|> Multi.run(:issue_comment, fn db, %{comment: comment} ->
case db.insert_all("issues_comments", [%{thread_id: issue_id, comment_id: comment.id}]) do
{1, val} -> {:ok, val}
end
end)
end
end
| 36.228571
| 223
| 0.648265
|
93daf919a5771936b938caaa5b951cd29e0950ed
| 2,477
|
ex
|
Elixir
|
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_image_redaction_config.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_image_redaction_config.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_image_redaction_config.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ImageRedactionConfig do
@moduledoc """
Configuration for determining how redaction of images should occur.
## Attributes
* `infoType` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2InfoType.t`, *default:* `nil`) - Only one per info_type should be provided per request. If not specified, and redact_all_text is false, the DLP API will redact all text that it matches against all info_types that are found, but not specified in another ImageRedactionConfig.
* `redactAllText` (*type:* `boolean()`, *default:* `nil`) - If true, all text found in the image, regardless whether it matches an info_type, is redacted. Only one should be provided.
* `redactionColor` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Color.t`, *default:* `nil`) - The color to use when redacting content from an image. If not specified, the default is black.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:infoType => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2InfoType.t() | nil,
:redactAllText => boolean() | nil,
:redactionColor => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Color.t() | nil
}
field(:infoType, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2InfoType)
field(:redactAllText)
field(:redactionColor, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Color)
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ImageRedactionConfig do
def decode(value, options) do
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ImageRedactionConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ImageRedactionConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.735849
| 342
| 0.754945
|
93dafb0b2cc75234b7bd88acfc8575a65d83ae88
| 1,734
|
ex
|
Elixir
|
clients/testing/lib/google_api/testing/v1/model/device_file.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/testing/lib/google_api/testing/v1/model/device_file.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/testing/lib/google_api/testing/v1/model/device_file.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.Testing.V1.Model.DeviceFile do
@moduledoc """
A single device file description.
## Attributes
* `obbFile` (*type:* `GoogleApi.Testing.V1.Model.ObbFile.t`, *default:* `nil`) - A reference to an opaque binary blob file.
* `regularFile` (*type:* `GoogleApi.Testing.V1.Model.RegularFile.t`, *default:* `nil`) - A reference to a regular file.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:obbFile => GoogleApi.Testing.V1.Model.ObbFile.t(),
:regularFile => GoogleApi.Testing.V1.Model.RegularFile.t()
}
field(:obbFile, as: GoogleApi.Testing.V1.Model.ObbFile)
field(:regularFile, as: GoogleApi.Testing.V1.Model.RegularFile)
end
defimpl Poison.Decoder, for: GoogleApi.Testing.V1.Model.DeviceFile do
def decode(value, options) do
GoogleApi.Testing.V1.Model.DeviceFile.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Testing.V1.Model.DeviceFile do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.68
| 127
| 0.731257
|
93db0c2b00b09f5ce1a52e29beea285981da12ec
| 488
|
ex
|
Elixir
|
lib/rails_to_iana_tz.ex
|
newshipt/rails_to_iana_tz
|
5f810e5ed0a4c52e36152b752d87d7866723ab4d
|
[
"MIT"
] | null | null | null |
lib/rails_to_iana_tz.ex
|
newshipt/rails_to_iana_tz
|
5f810e5ed0a4c52e36152b752d87d7866723ab4d
|
[
"MIT"
] | null | null | null |
lib/rails_to_iana_tz.ex
|
newshipt/rails_to_iana_tz
|
5f810e5ed0a4c52e36152b752d87d7866723ab4d
|
[
"MIT"
] | null | null | null |
defmodule RailsToIanaTz do
@moduledoc """
Converts rails US timezones to the iana equivalent which is useful for elixir.
## Example
iex> RailsToIanaTz.convert("Alaska")
"America/Juneau""
"""
File.stream!("tzconvert.csv")
|> CSV.decode(separator: ?,, headers: true)
|> Enum.each(fn(%{"IANATZ" => iana_tz, "RAILSTZ" => rails_tz}) ->
@doc false
def convert(unquote(rails_tz)), do: unquote(iana_tz)
end)
def convert(_missing), do: nil
end
| 23.238095
| 80
| 0.643443
|
93db13a1c562cd2a0480ad80097536c092ff079f
| 2,161
|
ex
|
Elixir
|
lib/eval.ex
|
epiphone/sammal
|
0058359f62fcdf048743fdd62bd84913b98b7773
|
[
"MIT"
] | 2
|
2017-05-02T14:15:11.000Z
|
2021-12-11T11:13:15.000Z
|
lib/eval.ex
|
epiphone/sammal
|
0058359f62fcdf048743fdd62bd84913b98b7773
|
[
"MIT"
] | null | null | null |
lib/eval.ex
|
epiphone/sammal
|
0058359f62fcdf048743fdd62bd84913b98b7773
|
[
"MIT"
] | null | null | null |
defmodule Sammal.Eval do
@moduledoc """
Evaluate parsed Lisp expressions.
"""
alias Sammal.{Env, Expr, Parser, SammalError}
@spec eval_all([Parser.form], Env) :: {any, Env}
def eval_all([], env), do: {nil, env}
def eval_all([exp], env), do: eval(exp, env)
def eval_all([exp | rest], env) do
{result, new_env} = eval(exp, env)
eval_all(rest, new_env)
end
def eval_all(_), do: throw "Expecting a list of expressions" # TODO handle
# TODO also include context here? for errors etc
@doc """
Evaluate a single expression or a form in given environment.
"""
@spec eval(Parser.form | Expr, Env) :: {any, Env}
def eval(%Expr{val: []}, env), do: {[], env}
def eval(%Expr{val: val} = expr, env) when is_atom(val) do
case Env.lookup_var(env, val) do
{:ok, res} -> {res, env}
{:error, _} -> throw SammalError.new(:unbound, expr)
end
end
def eval(%Expr{val: val}, env) when is_number(val) or is_binary(val) or is_boolean(val) do
{val, env}
end
def eval([%Expr{val: :define} = head, %Expr{val: var}, %Expr{} = val], env) when is_atom(var) do
unless Env.top_level?(env) do
# TODO allow internal definitions http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-8.html#%25_sec_5.2.2
throw SammalError.new(:cannot_bind, head)
end
{resolved_val, _} = eval(val, env)
{:ok, new_env} = Env.assign(env, var, resolved_val)
{nil, new_env}
end
# TODO:
# def eval([:let, ...
# def eval([:lambda, ...
# TODO lookup and handle macros
# procedure call:
def eval([%Expr{val: val} = head | rest], env) when is_atom(val) do
{proc, _} = eval(head, env)
proc_scope = %Env{parent: env}
args = Enum.map(rest, fn arg -> eval(arg, proc_scope) |> elem(0) end)
{proc.(args), env}
end
def eval([%Expr{} = expr | _], _), do: throw SammalError.new(:not_applicable, expr)
# TODO remove
def eval_raw(raw_code) do
{:ok, tokens} = Sammal.Tokenizer.tokenize(raw_code)
{:ok, {ast, _}} = Sammal.Parser.parse(tokens)
unless Mix.env == :test do
IO.inspect ast, label: "Evaluating AST"
end
eval_all(ast, Env.global)
end
end
| 29.60274
| 119
| 0.628413
|
93db1d1ca82afc60af61079e8c38365d2d9c3f35
| 541
|
ex
|
Elixir
|
core/lib/cronus_core_web/views/error_view.ex
|
Parasrah/cronus
|
b630a7d62128b03c7cdf65f941af2a2c2bd617e5
|
[
"MIT"
] | null | null | null |
core/lib/cronus_core_web/views/error_view.ex
|
Parasrah/cronus
|
b630a7d62128b03c7cdf65f941af2a2c2bd617e5
|
[
"MIT"
] | null | null | null |
core/lib/cronus_core_web/views/error_view.ex
|
Parasrah/cronus
|
b630a7d62128b03c7cdf65f941af2a2c2bd617e5
|
[
"MIT"
] | null | null | null |
defmodule CronusCoreWeb.ErrorView do
use CronusCoreWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def template_not_found(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
| 31.823529
| 83
| 0.722736
|
93db77bfdf8d6d323ce94921e3ca70e434e84622
| 2,622
|
exs
|
Elixir
|
languages/elixir/exercises/concept/kitchen-calculator/test/kitchen_calculator_test.exs
|
AlexLeSang/v3
|
3d35961a961b5a2129b1d42f1d118972d9665357
|
[
"MIT"
] | 3
|
2020-07-25T06:24:00.000Z
|
2020-09-14T17:39:11.000Z
|
languages/elixir/exercises/concept/kitchen-calculator/test/kitchen_calculator_test.exs
|
AlexLeSang/v3
|
3d35961a961b5a2129b1d42f1d118972d9665357
|
[
"MIT"
] | 45
|
2020-01-24T17:04:52.000Z
|
2020-11-24T17:50:18.000Z
|
languages/elixir/exercises/concept/kitchen-calculator/test/kitchen_calculator_test.exs
|
AlexLeSang/v3
|
3d35961a961b5a2129b1d42f1d118972d9665357
|
[
"MIT"
] | 1
|
2020-04-20T11:41:55.000Z
|
2020-04-20T11:41:55.000Z
|
defmodule KitchenCalculatorTest do
use ExUnit.Case
alias KitchenCalculator, as: KC
describe "get volume from tuple pair" do
# @tag :pending
test "get cups" do
assert KC.get_volume({:cup, 1}) == 1
end
@tag :pending
test "get fluid ounces" do
assert KC.get_volume({:fluid_ounce, 2}) == 2
end
@tag :pending
test "get teaspoons" do
assert KC.get_volume({:teaspoons, 3}) == 3
end
@tag :pending
test "get tablespoons" do
assert KC.get_volume({:tablespoons, 4}) == 4
end
@tag :pending
test "get millilitres" do
assert KC.get_volume({:millilitre, 5}) == 5
end
end
describe "convert to millilitres from" do
@tag :pending
test "millilitres" do
assert KC.to_millilitre({:millilitre, 3}) == {:millilitre, 3}
end
@tag :pending
test "cups" do
assert KC.to_millilitre({:cup, 3}) == {:millilitre, 720}
end
@tag :pending
test "fluid ounces" do
assert KC.to_millilitre({:fluid_ounce, 100}) == {:millilitre, 3000}
end
@tag :pending
test "teaspoon" do
assert KC.to_millilitre({:teaspoon, 3}) == {:millilitre, 15}
end
@tag :pending
test "tablespoon" do
assert KC.to_millilitre({:tablespoon, 3}) == {:millilitre, 45}
end
end
describe "convert from millilitres to" do
@tag :pending
test "millilitres" do
assert KC.from_millilitre({:millilitre, 4}, :millilitre) == {:millilitre, 4}
end
@tag :pending
test "cups" do
assert KC.from_millilitre({:millilitre, 840}, :cup) == {:cup, 3.5}
end
@tag :pending
test "fluid ounces" do
assert KC.from_millilitre({:millilitre, 4522.5}, :fluid_ounce) == {:fluid_ounce, 150.75}
end
@tag :pending
test "teaspoon" do
assert KC.from_millilitre({:millilitre, 61.25}, :teaspoon) == {:teaspoon, 12.25}
end
@tag :pending
test "tablespoon" do
assert KC.from_millilitre({:millilitre, 71.25}, :tablespoon) == {:tablespoon, 4.75}
end
end
describe "convert from x to y:" do
@tag :pending
test "teaspoon to tablespoon" do
assert KC.convert({:teaspoon, 15}, :tablespoon) == {:tablespoon, 5}
end
@tag :pending
test "cups to fluid ounces" do
assert KC.convert({:cup, 4}, :fluid_ounce) == {:fluid_ounce, 32}
end
@tag :pending
test "fluid ounces to teaspoons" do
assert KC.convert({:fluid_ounce, 4}, :teaspoon) == {:teaspoon, 24}
end
@tag :pending
test "tablespoons to cups" do
assert KC.convert({:tablespoon, 320}, :cup) == {:cup, 20}
end
end
end
| 24.055046
| 94
| 0.613272
|
93dba7d887472e13b5a8575273fc24cdc81c31fc
| 733
|
ex
|
Elixir
|
apps/customer/lib/customer/web/models/job_title_alias.ex
|
JaiMali/job_search-1
|
5fe1afcd80aa5d55b92befed2780cd6721837c88
|
[
"MIT"
] | 102
|
2017-05-21T18:24:04.000Z
|
2022-03-10T12:53:20.000Z
|
apps/customer/lib/customer/web/models/job_title_alias.ex
|
JaiMali/job_search-1
|
5fe1afcd80aa5d55b92befed2780cd6721837c88
|
[
"MIT"
] | 2
|
2017-05-21T01:53:30.000Z
|
2017-12-01T00:27:06.000Z
|
apps/customer/lib/customer/web/models/job_title_alias.ex
|
JaiMali/job_search-1
|
5fe1afcd80aa5d55b92befed2780cd6721837c88
|
[
"MIT"
] | 18
|
2017-05-22T09:51:36.000Z
|
2021-09-24T00:57:01.000Z
|
defmodule Customer.Web.JobTitleAlias do
use Customer.Web, :model
schema "job_title_aliases" do
field :name, :string
timestamps()
belongs_to :job_title, JobTitle
end
@required_fields ~w(name job_title_id)a
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct \\ %__MODULE__{}, params \\ %{}) do
struct
|> cast(params, @required_fields)
|> validate_required(@required_fields)
|> downcase
|> unique_constraint(:name)
end
def build(params) do
changeset(%__MODULE__{}, params)
end
defp downcase(changeset) do
with {:ok, name} <- fetch_change(changeset, :name),
do: put_change(changeset, :name, String.downcase(name))
end
end
| 21.558824
| 59
| 0.672578
|
93dbb675a4c3a5ca2dd1b327eff30cd8f628d9e7
| 291
|
ex
|
Elixir
|
lib/phone/nanp/us/mo.ex
|
net/phone
|
18e1356d2f8d32fe3f95638c3c44bceab0164fb2
|
[
"Apache-2.0"
] | null | null | null |
lib/phone/nanp/us/mo.ex
|
net/phone
|
18e1356d2f8d32fe3f95638c3c44bceab0164fb2
|
[
"Apache-2.0"
] | null | null | null |
lib/phone/nanp/us/mo.ex
|
net/phone
|
18e1356d2f8d32fe3f95638c3c44bceab0164fb2
|
[
"Apache-2.0"
] | null | null | null |
defmodule Phone.NANP.US.MO do
@moduledoc false
use Helper.Area
def regex, do: ~r/^(1)(314|417|573|636|660|816)([2-9].{6})$/
def area_name, do: "Missouri"
def area_type, do: "state"
def area_abbreviation, do: "MO"
matcher ["1314", "1417", "1573", "1636", "1660", "1816"]
end
| 22.384615
| 62
| 0.628866
|
93dbd6dda108f1d4ea5bc239d7a0de669500725e
| 485
|
ex
|
Elixir
|
lib/uro/user_content/prop.ex
|
V-Sekai/uro
|
0b23da65d5c7e459efcd6b2c3d9bdf91c533b737
|
[
"MIT"
] | 1
|
2022-01-11T04:05:39.000Z
|
2022-01-11T04:05:39.000Z
|
lib/uro/user_content/prop.ex
|
V-Sekai/uro
|
0b23da65d5c7e459efcd6b2c3d9bdf91c533b737
|
[
"MIT"
] | 35
|
2021-02-10T08:18:57.000Z
|
2021-05-06T17:19:50.000Z
|
lib/uro/user_content/prop.ex
|
V-Sekai/uro
|
0b23da65d5c7e459efcd6b2c3d9bdf91c533b737
|
[
"MIT"
] | null | null | null |
defmodule Uro.UserContent.Prop do
import Ecto.Changeset
use Uro.UserContent.UserContent
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
@derive {Phoenix.Param, key: :id}
schema "props" do
user_content_fields()
timestamps()
end
@doc false
def changeset(prop, attrs) do
user_content_changeset(prop, attrs)
end
@doc false
def upload_changeset(prop, attrs) do
user_content_upload_changeset(prop, attrs)
end
end
| 20.208333
| 52
| 0.729897
|
93dbdda6605ba1f9572007f8b28690556e19718c
| 1,260
|
exs
|
Elixir
|
test/auto_api/states/windows_state_test.exs
|
nonninz/auto-api-elixir
|
53e11542043285e94bbb5a0a3b8ffff0b1b47167
|
[
"MIT"
] | 4
|
2018-01-19T16:11:10.000Z
|
2019-12-13T16:35:10.000Z
|
test/auto_api/states/windows_state_test.exs
|
nonninz/auto-api-elixir
|
53e11542043285e94bbb5a0a3b8ffff0b1b47167
|
[
"MIT"
] | 5
|
2020-07-16T07:20:21.000Z
|
2021-09-22T10:18:04.000Z
|
test/auto_api/states/windows_state_test.exs
|
nonninz/auto-api-elixir
|
53e11542043285e94bbb5a0a3b8ffff0b1b47167
|
[
"MIT"
] | 1
|
2021-02-17T18:36:13.000Z
|
2021-02-17T18:36:13.000Z
|
# AutoAPI
# The MIT License
#
# Copyright (c) 2018- High-Mobility GmbH (https://high-mobility.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
defmodule AutoApi.WindowsStateTest do
use ExUnit.Case, async: true
doctest AutoApi.WindowsState
end
| 46.666667
| 79
| 0.778571
|
93dbe65d017cedf1edd1fb2236b3346594fca189
| 819
|
ex
|
Elixir
|
lib/dynamite.ex
|
j-pel/dynamite
|
767055750822845474112dbace1e569b6731b332
|
[
"MIT"
] | null | null | null |
lib/dynamite.ex
|
j-pel/dynamite
|
767055750822845474112dbace1e569b6731b332
|
[
"MIT"
] | 3
|
2016-04-20T05:30:40.000Z
|
2016-05-02T03:02:29.000Z
|
lib/dynamite.ex
|
j-pel/dynamite
|
767055750822845474112dbace1e569b6731b332
|
[
"MIT"
] | null | null | null |
defmodule Dynamite do
use Application
def start(_type, _args) do
Application.fetch_env!(:dynamite, :sites)
|>launch
device = File.open!("dbg.log", [:write])
Application.put_env(:dbg, :device, device)
Dynamite.Supervisor.start_link([])
end
def site_info(site, :static_path) do
sites = Application.fetch_env!(:dynamite, :sites)
site = sites[site]
table = site[:routing_table]
route = table[:static]
end
defp launch([]) do
end
defp launch(sites) do
[site|rest] = sites
{name,info} = site
{:ok,pid} = :cowboy.start_http(name, 100,
[{:port, info[:port]}], [{ :env, [{:dispatch, []}]}]
)
table = info[:routing_table]
EEx.eval_file table[:routes]<>"main.eex"
IO.puts("info for #{name}: #{inspect(pid)}")
launch(rest)
end
end
| 24.088235
| 58
| 0.616606
|
93dc2969d68f659f4abf968aea511efda4b0ef27
| 4,355
|
ex
|
Elixir
|
lib/set_locale.ex
|
VinogradovAlexandr/set_locale
|
2b02ffb14707f63344d8c5548a61a443b7cf7298
|
[
"WTFPL"
] | null | null | null |
lib/set_locale.ex
|
VinogradovAlexandr/set_locale
|
2b02ffb14707f63344d8c5548a61a443b7cf7298
|
[
"WTFPL"
] | null | null | null |
lib/set_locale.ex
|
VinogradovAlexandr/set_locale
|
2b02ffb14707f63344d8c5548a61a443b7cf7298
|
[
"WTFPL"
] | null | null | null |
defmodule SetLocale do
import Plug.Conn
defmodule Config do
defstruct gettext: nil, default_locale: nil, cookie_key: nil
end
def init(gettext: gettext, default_locale: default_locale, cookie_key: cookie_key) do
%Config{gettext: gettext, default_locale: default_locale, cookie_key: cookie_key}
end
def init(gettext: gettext, default_locale: default_locale) do
%Config{gettext: gettext, default_locale: default_locale, cookie_key: nil}
end
def init([gettext, default_locale]) do
unless Mix.env == :test do
IO.warn ~S(
This config style has been deprecated for for set_locale. Please update the old style config:
plug SetLocale, [MyApp.Gettext, "en-gb"]
to the new config:
plug SetLocale, gettext: MyApp.Gettext, default_locale: "en-gb", cookie_key: "preferred_locale"]
), Macro.Env.stacktrace(__ENV__)
end
%Config{gettext: gettext, default_locale: default_locale, cookie_key: nil}
end
def call(
%{
params: %{
"locale" => requested_locale
}
} = conn,
config
) do
if Enum.member?(supported_locales(config), requested_locale) do
Gettext.put_locale(config.gettext, requested_locale)
assign(conn, :locale, requested_locale)
else
path = rewrite_path(conn, requested_locale, config)
conn
|> redirect_to(path)
|> halt
end
end
def call(conn, config) do
path = rewrite_path(conn, nil, config)
conn
|> redirect_to(path)
|> halt
end
defp rewrite_path(%{request_path: request_path} = conn, requested_locale, config) do
locale = determine_locale(conn, requested_locale, config)
request_path
|> maybe_strip_unsupported_locale
|> localize_path(locale)
end
defp determine_locale(conn, nil, config) do
get_locale_from_cookie(conn, config)
|| get_locale_from_http_referrer(conn)
|| get_locale_from_header(conn, config)
|| config.default_locale
end
defp determine_locale(conn, requested_locale, config) do
base = hd String.split(requested_locale, "-")
if (is_locale?(requested_locale) and Enum.member?(supported_locales(config), base)) do
base
else
determine_locale(conn, nil, config)
end
end
# Attempt to extract a locale from the HTTP "referer" header.
# If that url exists and had a language prefix, it's a good indication of what locale the user prefers.
# And yes, it is referer, not referrer. A typo in the original HTTP spec means it will haunt us forever.
defp get_locale_from_http_referrer(conn) do
conn
|> get_req_header("referer")
|> case do
[referrer] when is_binary(referrer) ->
uri = URI.parse(referrer)
maybe_extract_locale(uri.path)
_ ->
nil
end
end
defp supported_locales(config), do: Gettext.known_locales(config.gettext)
defp maybe_strip_unsupported_locale(request_path) do
maybe_locale = maybe_extract_locale(request_path)
if maybe_locale, do: strip_unsupported_locale(request_path), else: request_path
end
defp maybe_extract_locale(request_path) when is_binary(request_path) do
case String.split(request_path, "/") do
[_, maybe_locale | _] ->
if is_locale?(maybe_locale), do: maybe_locale, else: nil
_ -> nil
end
end
defp maybe_extract_locale(_), do: nil
defp is_locale?(maybe_locale), do: Regex.match?(~r/^[a-z]{2}(-[a-z]{2})?$/, maybe_locale)
defp strip_unsupported_locale(request_path) do
[_, _ | rest] = String.split(request_path, "/")
"/" <> Enum.join(rest, "/")
end
defp localize_path("/", locale), do: "/#{locale}"
defp localize_path(request_path, locale), do: "/#{locale}#{request_path}"
defp redirect_to(conn, path) do
path = get_redirect_path(conn, path)
Phoenix.Controller.redirect(conn, to: path)
end
defp get_redirect_path(%{query_string: query_string}, path) when query_string != "", do: path <> "?#{query_string}"
defp get_redirect_path(_conn, path), do: path
defp get_locale_from_cookie(conn, config), do: conn.cookies[config.cookie_key]
defp get_locale_from_header(conn, gettext) do
conn
|> SetLocale.Headers.extract_accept_language
|> Enum.find(nil, fn accepted_locale -> Enum.member?(supported_locales(gettext), accepted_locale) end)
end
end
| 31.788321
| 117
| 0.690241
|
93dc5aad1d2259cdb01814088b4872eab0d3965b
| 4,914
|
exs
|
Elixir
|
mix.exs
|
halostatue/oban
|
f6789e745554e4f2e7076d25f628fe54a64635f8
|
[
"Apache-2.0"
] | null | null | null |
mix.exs
|
halostatue/oban
|
f6789e745554e4f2e7076d25f628fe54a64635f8
|
[
"Apache-2.0"
] | null | null | null |
mix.exs
|
halostatue/oban
|
f6789e745554e4f2e7076d25f628fe54a64635f8
|
[
"Apache-2.0"
] | null | null | null |
defmodule Oban.MixProject do
use Mix.Project
@version "2.3.4"
def project do
[
app: :oban,
version: @version,
elixir: "~> 1.8",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps(),
aliases: aliases(),
preferred_cli_env: [
bench: :test,
ci: :test,
"test.setup": :test
],
# Hex
package: package(),
description: """
Robust job processing, backed by modern PostgreSQL.
""",
# Dialyzer
dialyzer: [
plt_add_apps: [:ex_unit],
plt_core_path: "_build/#{Mix.env()}",
flags: [:error_handling, :race_conditions, :underspecs]
],
# Docs
name: "Oban",
docs: [
main: "Oban",
source_ref: "v#{@version}",
source_url: "https://github.com/sorentwo/oban",
extra_section: "GUIDES",
formatters: ["html"],
extras: extras() ++ pro_extras() ++ web_extras(),
groups_for_extras: groups_for_extras(),
groups_for_modules: groups_for_modules()
]
]
end
def application do
[
mod: {Oban.Application, []},
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_env), do: ["lib"]
defp extras do
[
"CHANGELOG.md",
"guides/installation.md",
"guides/troubleshooting.md",
"guides/writing_plugins.md",
"guides/upgrading/v2.0.md",
"guides/release_configuration.md",
"guides/recipes/recursive-jobs.md",
"guides/recipes/reliable-scheduling.md",
"guides/recipes/reporting-progress.md",
"guides/recipes/expected-failures.md",
"guides/recipes/splitting-queues.md"
]
end
defp pro_extras do
if File.exists?("../oban_pro") do
[
"../oban_pro/guides/pro/overview.md": [filename: "pro_overview"],
"../oban_pro/guides/pro/installation.md": [filename: "pro_installation"],
"../oban_pro/guides/plugins/lifeline.md": [title: "Lifeline Plugin"],
"../oban_pro/guides/plugins/dynamic_cron.md": [title: "Dynamic Cron Plugin"],
"../oban_pro/guides/plugins/dynamic_pruner.md": [title: "Dynamic Pruner Plugin"],
"../oban_pro/guides/plugins/reprioritizer.md": [title: "Reprioritizer Plugin"],
"../oban_pro/guides/workers/batch.md": [title: "Batch Worker"],
"../oban_pro/guides/workers/workflow.md": [title: "Workflow Worker"],
"../oban_pro/CHANGELOG.md": [filename: "pro-changelog", title: "Changelog"]
]
else
[]
end
end
defp web_extras do
if File.exists?("../oban_web") do
[
"../oban_web/guides/web/overview.md": [filename: "web_overview"],
"../oban_web/guides/web/installation.md": [filename: "web_installation"],
"../oban_web/guides/web/customizing.md": [filename: "web_customizing"],
"../oban_web/guides/web/telemetry.md": [filename: "web_telemetry"],
"../oban_web/guides/web/troubleshooting.md": [filename: "web_troubleshooting"],
"../oban_web/CHANGELOG.md": [filename: "web-changelog", title: "Changelog"]
]
else
[]
end
end
defp groups_for_extras do
[
Guides: ~r{guides/[^\/]+\.md},
Recipes: ~r{guides/recipes/.?},
Extras: ~r{^CHANGELOG.md},
"Upgrade Guides": ~r{guides/upgrading/.*},
"Oban Pro": ~r{oban_pro/.?},
"Oban Web": ~r{oban_web/.?}
]
end
defp groups_for_modules do
[
Plugins: [
Oban.Plugins.Cron,
Oban.Plugins.Pruner,
Oban.Plugins.Stager
],
Extending: [
Oban.Config,
Oban.Notifier,
Oban.Registry,
Oban.Repo
]
]
end
defp package do
[
maintainers: ["Parker Selbert"],
licenses: ["Apache-2.0"],
links: %{
Website: "https://getoban.pro",
Changelog: "https://github.com/sorentwo/oban/blob/master/CHANGELOG.md",
GitHub: "https://github.com/sorentwo/oban",
Sponsor: "https://getoban.pro"
}
]
end
defp deps do
[
{:ecto_sql, ">= 3.4.3"},
{:jason, "~> 1.1"},
{:postgrex, "~> 0.14"},
{:telemetry, "~> 0.4"},
{:stream_data, "~> 0.4", only: [:test, :dev]},
{:tzdata, "~> 1.0", only: [:test, :dev]},
{:benchee, "~> 1.0", only: [:test, :dev], runtime: false},
{:credo, "~> 1.4", only: [:test, :dev], runtime: false},
{:dialyxir, "~> 1.0", only: [:test, :dev], runtime: false},
{:ex_doc, "~> 0.20", only: [:test, :dev], runtime: false}
]
end
defp aliases do
[
bench: "run bench/bench_helper.exs",
"test.setup": ["ecto.create", "ecto.migrate"],
ci: [
"format --check-formatted",
"deps.unlock --check-unused",
"credo --strict",
"test --raise",
"dialyzer"
]
]
end
end
| 27.762712
| 89
| 0.560236
|
93dc886567af5c40bb8937cd82297b35a9df612a
| 64
|
ex
|
Elixir
|
template/$PROJECT_NAME$/apps/$APP1_NAME$/lib/$APP1_NAME$/endpoint.ex
|
ericsteen/master_proxy
|
df5a93bca9e655d7d4b9724da200639e0b247133
|
[
"Apache-2.0"
] | 3
|
2019-02-01T09:47:15.000Z
|
2019-03-29T23:10:01.000Z
|
template/$PROJECT_NAME$/apps/$APP1_NAME$/lib/$APP1_NAME$/endpoint.ex
|
upstarter/master_proxy
|
df5a93bca9e655d7d4b9724da200639e0b247133
|
[
"Apache-2.0"
] | null | null | null |
template/$PROJECT_NAME$/apps/$APP1_NAME$/lib/$APP1_NAME$/endpoint.ex
|
upstarter/master_proxy
|
df5a93bca9e655d7d4b9724da200639e0b247133
|
[
"Apache-2.0"
] | null | null | null |
defmodule <%= Macro.camelize(@app1_name) %>Web.Endpoint do
end
| 16
| 58
| 0.734375
|
93dce2cfbe086b14af9993dd2bbca6c7aa9656d0
| 1,021
|
ex
|
Elixir
|
farmbot_core/lib/farmbot_core.ex
|
adamswsk/farmbot_os
|
d177d3b74888c1e7bcbf8f8595818708ee97f73b
|
[
"MIT"
] | null | null | null |
farmbot_core/lib/farmbot_core.ex
|
adamswsk/farmbot_os
|
d177d3b74888c1e7bcbf8f8595818708ee97f73b
|
[
"MIT"
] | null | null | null |
farmbot_core/lib/farmbot_core.ex
|
adamswsk/farmbot_os
|
d177d3b74888c1e7bcbf8f8595818708ee97f73b
|
[
"MIT"
] | null | null | null |
defmodule FarmbotCore do
@moduledoc """
Core Farmbot Services.
This includes
* Core global state management
* Data storage management
* Firmware management
* RPC and IPC management
"""
use Application
@doc false
def start(_, args), do: Supervisor.start_link(__MODULE__, args, name: __MODULE__)
def init([]) do
Supervisor.init(children(), [strategy: :one_for_one])
end
def children do
default = [
FarmbotCore.Leds,
FarmbotCore.EctoMigrator,
FarmbotCore.BotState.Supervisor,
FarmbotCore.StorageSupervisor,
FarmbotCore.FirmwareTTYDetector,
FarmbotCore.FirmwareOpenTask,
FarmbotCore.FirmwareEstopTimer,
{FarmbotFirmware,
transport: FarmbotFirmware.StubTransport,
side_effects: FarmbotCore.FirmwareSideEffects,
reset: FarmbotCore.FirmwareResetter},
FarmbotCeleryScript.Scheduler
]
config = (Application.get_env(:farmbot_ext, __MODULE__) || [])
Keyword.get(config, :children, default)
end
end
| 26.179487
| 83
| 0.705191
|
93dce39d2ebf0941be6aa1ae14d91bd77aee55f0
| 57
|
ex
|
Elixir
|
web/views/layout_view.ex
|
lucianosousa/gears
|
a59a93dd28ccd82e6cd1e3db809535a4dc10d007
|
[
"MIT"
] | null | null | null |
web/views/layout_view.ex
|
lucianosousa/gears
|
a59a93dd28ccd82e6cd1e3db809535a4dc10d007
|
[
"MIT"
] | null | null | null |
web/views/layout_view.ex
|
lucianosousa/gears
|
a59a93dd28ccd82e6cd1e3db809535a4dc10d007
|
[
"MIT"
] | null | null | null |
defmodule Gears.LayoutView do
use Gears.Web, :view
end
| 14.25
| 29
| 0.77193
|
93dd0204f655fa30c47a2652fb3213a1d237b87a
| 2,714
|
exs
|
Elixir
|
priv/repo/migrations/20191117231438_bootstrap_base.exs
|
themaxhero/Machinista
|
2e0114dbbc69fc8187b3ed080de694ac4f558ae8
|
[
"BSD-2-Clause"
] | 1
|
2019-12-16T10:22:07.000Z
|
2019-12-16T10:22:07.000Z
|
priv/repo/migrations/20191117231438_bootstrap_base.exs
|
themaxhero/Machinista
|
2e0114dbbc69fc8187b3ed080de694ac4f558ae8
|
[
"BSD-2-Clause"
] | 2
|
2021-03-10T06:56:47.000Z
|
2021-05-11T02:41:32.000Z
|
priv/repo/migrations/20191117231438_bootstrap_base.exs
|
themaxhero/Macchinista
|
2e0114dbbc69fc8187b3ed080de694ac4f558ae8
|
[
"BSD-2-Clause"
] | null | null | null |
defmodule Macchinista.Repo.Migrations.BootstrapBase do
use Ecto.Migration
def change do
create table(:boards, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string, default: "Untitled Board"
add :order, :integer, null: false
add :background, :string
add :shelve, :boolean, default: false
add :user_id, references(:users, type: :uuid)
timestamps()
end
create unique_index(:boards, [:user_id, :order])
create table(:tags, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string, default: "Untitled Tag"
add :color, :string, size: 7
add :board_id, references(:boards, type: :uuid)
timestamps()
end
create table(:card_lists, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string, default: "Untitled List"
add :order, :integer
add :shelve, :boolean, default: false
add :board_id, references(:boards, type: :uuid)
timestamps()
end
create unique_index(:card_lists, [:board_id, :order, :shelve])
create table(:cards, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string, default: "Untitled Card"
add :description, :string
add :shelve, :boolean, default: false
add :order, :integer
add :parent_id, references(:cards, type: :uuid)
add :card_list_id, references(:card_lists, type: :uuid)
timestamps()
end
create unique_index(:cards, [:card_list_id, :order, :shelve, :parent_id])
create table(:checklists, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string, default: "Untitled Checklist"
add :order, :integer
add :card_id, references(:cards, type: :uuid)
timestamps()
end
create unique_index(:checklists, [:card_id, :order])
create table(:quests, primary_key: false) do
add :id, :uuid, primary_key: true
add :name, :string, default: "Untitled Quest"
add :order, :integer
add :checked, :boolean, default: false
add :checklist_id, references(:checklists, type: :uuid)
timestamps()
end
create unique_index(:quests, [:checklist_id, :order])
create table(:cards_tags, primary_key: false) do
add :id, :uuid, primary_key: true
add :card_id, references(:cards, column: :id, type: :uuid, on_delete: :delete_all)
add :tag_id, references(:tags, column: :id, type: :uuid, on_delete: :delete_all)
end
create index(:cards_tags, [:card_id])
create index(:cards_tags, [:tag_id])
create unique_index(:cards_tags, [:card_id, :tag_id], name: :card_id_tag_id_unique_index)
end
end
| 31.195402
| 93
| 0.648121
|
93dd2732d49316810a4b144349f0c486a1ba6ea9
| 1,720
|
ex
|
Elixir
|
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/sql_server_database_details.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/sql_server_database_details.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/sql_server_database_details.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.SQLAdmin.V1beta4.Model.SqlServerDatabaseDetails do
@moduledoc """
Represents a Sql Server database on the Cloud SQL instance.
## Attributes
* `compatibilityLevel` (*type:* `integer()`, *default:* `nil`) - The version of SQL Server with which the database is to be made compatible
* `recoveryModel` (*type:* `String.t`, *default:* `nil`) - The recovery model of a SQL Server database
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:compatibilityLevel => integer(),
:recoveryModel => String.t()
}
field(:compatibilityLevel)
field(:recoveryModel)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.SqlServerDatabaseDetails do
def decode(value, options) do
GoogleApi.SQLAdmin.V1beta4.Model.SqlServerDatabaseDetails.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.SqlServerDatabaseDetails do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.4
| 143
| 0.741279
|
93dd2b68b0eab8d44379cff92a75e1524802fe15
| 5,331
|
ex
|
Elixir
|
lib/memcache/connection.ex
|
cloud8421/memcache-ex
|
90661826c43742c5a5f86d3858c6f4f6cfcbce50
|
[
"MIT"
] | 1
|
2017-01-26T22:44:19.000Z
|
2017-01-26T22:44:19.000Z
|
lib/memcache/connection.ex
|
cloud8421/memcache-ex
|
90661826c43742c5a5f86d3858c6f4f6cfcbce50
|
[
"MIT"
] | null | null | null |
lib/memcache/connection.ex
|
cloud8421/memcache-ex
|
90661826c43742c5a5f86d3858c6f4f6cfcbce50
|
[
"MIT"
] | null | null | null |
defmodule Memcache.Connection do
use GenServer
alias Memcache.Protocol
defmodule State do
defstruct opts: nil, sock: nil
end
@spec start_link(Keyword.t) :: { :ok, pid } | { :error, term }
def start_link(opts) do
case :gen_server.start_link(__MODULE__, [], []) do
{ :ok, pid } ->
opts = with_defaults(opts)
case :gen_server.call(pid, { :connect, opts }) do
:ok -> { :ok, pid }
err -> { :error, err }
end
err -> err
end
end
def execute(pid, command, args) do
:gen_server.call(pid, { :execute, command, args })
end
def execute_quiet(pid, commands) do
:gen_server.call(pid, { :execute_quiet, commands })
end
def init([]) do
{ :ok, %State{} }
end
def handle_call({ :connect, opts }, _from, s) do
sock_opts = [ { :active, false }, { :packet, :raw }, :binary ]
case :gen_tcp.connect(opts[:hostname], opts[:port], sock_opts) do
{ :ok, sock } -> { :reply, :ok, %State{ sock: sock, opts: opts } }
{ :error, reason } -> { :stop, :normal, reason, s }
end
end
def handle_call({ :execute, command, args }, _from, %State{ sock: sock } = s) do
packet = apply(Protocol, :to_binary, [command | args])
case :gen_tcp.send(sock, packet) do
:ok -> recv_response(command, s)
{ :error, reason } -> { :stop, :normal, reason, s }
end
end
def handle_call({ :execute_quiet, commands }, _from, %State{ sock: sock } = s) do
{ packet, commands, i } = Enum.reduce(commands, { <<>>, [], 1 }, fn ({ command, args }, { packet, commands, i }) ->
{ packet <> apply(Protocol, :to_binary, [command | [i | args]]), [{ i, command, args } | commands], i + 1 }
end)
packet = packet <> Protocol.to_binary(:NOOP, i)
case :gen_tcp.send(sock, packet) do
:ok -> recv_response_quiet(Enum.reverse([ { i, :NOOP, [] } | commands]), s, [], <<>>)
{ :error, reason } -> { :stop, :normal, reason, s }
end
end
def terminate(_reason, %State{ sock: sock }) do
if sock do
:gen_tcp.close(sock)
end
end
## Private ##
defp recv_response(:STAT, s) do
recv_stat(s, HashDict.new)
end
defp recv_response(_command, s) do
recv_header(s)
end
defp recv_header(%State{ sock: sock } = s) do
case :gen_tcp.recv(sock, 24) do
{ :ok, raw_header } ->
header = Protocol.parse_header(raw_header)
recv_body(header, s)
{ :error, reason } -> { :stop, :normal, reason, s }
end
end
defp recv_body(header, %State{ sock: sock } = s) do
body_size = Protocol.total_body_size(header)
if body_size > 0 do
case :gen_tcp.recv(sock, body_size) do
{ :ok, body } ->
response = Protocol.parse_body(header, body)
{ :reply, response, s }
{ :error, reason } -> { :stop, :normal, reason, s }
end
else
response = Protocol.parse_body(header, :empty)
{ :reply, response, s }
end
end
defp recv_stat(s, results) do
case recv_header(s) do
{ :reply, { :ok, :done }, _ } -> { :reply, { :ok, results }, s }
{ :reply, { :ok, key, val }, _ } -> recv_stat(s, HashDict.put(results, key, val))
err -> err
end
end
defp recv_response_quiet([], s, results, _buffer) do
{ :reply, { :ok, Enum.reverse(tl(results)) }, s }
end
defp recv_response_quiet(commands, s, results, buffer) when byte_size(buffer) >= 24 do
{ header_raw, rest } = cut(buffer, 24)
header = Protocol.parse_header(header_raw)
body_size = Protocol.total_body_size(header)
if body_size > 0 do
case read_more_if_needed(s, rest, body_size) do
{ :ok, buffer } ->
{ body, rest } = cut(buffer, body_size)
{ rest_commands, results } = match_response(commands, results, Protocol.parse_body(header, body))
recv_response_quiet(rest_commands, s, results, rest)
err -> err
end
else
{ rest_commands, results } = match_response(commands, results, Protocol.parse_body(header, :empty))
recv_response_quiet(rest_commands, s, results, rest)
end
end
defp recv_response_quiet(commands, s, results, buffer) do
case read_more_if_needed(s, buffer, 24) do
{ :ok, buffer } -> recv_response_quiet(commands, s, results, buffer)
err -> err
end
end
defp match_response([ { i, _command, _args } | rest ], results, { i, response }) do
{ rest, [response | results] }
end
defp match_response([ { _i , command, _args } | rest ], results, _response_with_index) do
match_response(rest, [Protocol.quiet_response(command) | results], _response_with_index)
end
defp read_more_if_needed(_sock, buffer, min_required) when byte_size(buffer) >= min_required do
{ :ok, buffer }
end
defp read_more_if_needed(%State{ sock: sock } = s, buffer, min_required) do
case :gen_tcp.recv(sock, 0) do
{ :ok, data } -> read_more_if_needed(s, buffer <> data, min_required)
{ :error, reason } -> { :stop, :normal, reason, s }
end
end
defp with_defaults(opts) do
opts
|> Keyword.put_new(:port, 11211)
|> Keyword.update!(:hostname, &if is_binary(&1), do: String.to_char_list(&1), else: &1)
end
defp cut(bin, at) do
first = binary_part(bin, 0, at)
rest = binary_part(bin, at, byte_size(bin) - at)
{ first, rest }
end
end
| 31.358824
| 119
| 0.605515
|
93dd31f1cb2d363f5a27b03c1cfcb9de1b586c07
| 1,011
|
ex
|
Elixir
|
lib/virgo/cache/problem_detail.ex
|
GinShio/AstraeaVirgo
|
92804cbae01f67e21b8f421009fa37fddc9054e1
|
[
"BSD-2-Clause"
] | null | null | null |
lib/virgo/cache/problem_detail.ex
|
GinShio/AstraeaVirgo
|
92804cbae01f67e21b8f421009fa37fddc9054e1
|
[
"BSD-2-Clause"
] | null | null | null |
lib/virgo/cache/problem_detail.ex
|
GinShio/AstraeaVirgo
|
92804cbae01f67e21b8f421009fa37fddc9054e1
|
[
"BSD-2-Clause"
] | null | null | null |
defmodule AstraeaVirgo.Cache.ProblemDetail do
@moduledoc """
Implement ProblemDetail operation for cache
## Problem Detail
A key-value mapping the problem detail, key is problem id
- Key: `Astraea:Problem:ID:<problem_id>:Detail`
- type: hash
- fields:
- id
- public
- detail
- mime
- time_limit
- memory_limit
"""
use AstraeaVirgo.Cache.Utils.Hash
def get_show_key(id), do: "Astraea:Problem:ID:#{id}:Detail"
defp get_field_name(), do: ["id", "public", "detail", "mime", "time_limit", "memory_limit"]
defp get_empty_value(), do: [nil, nil, nil, nil, nil, nil]
defp get_info_from_db(id) do
# TODO: request problem info from DB
{:ok, nil}
end
defp parse([id, public, detail, mime, time_limit, memory_limit]) do
%{
id: id,
public: String.to_atom(public),
detail: detail,
mime: mime,
time_limit: String.to_integer(time_limit),
memory_limit: String.to_integer(memory_limit),
}
end
end
| 24.658537
| 93
| 0.642928
|
93dd41871035fd4d0d4f2f291c120d9a3f62168d
| 2,853
|
ex
|
Elixir
|
lib/quark/compose.ex
|
doma-engineering/quark
|
16af5e00f9048053678cbaf6fb770969446e0d1e
|
[
"MIT"
] | 80
|
2019-06-07T00:02:56.000Z
|
2022-03-14T19:33:27.000Z
|
lib/quark/compose.ex
|
doma-engineering/quark
|
16af5e00f9048053678cbaf6fb770969446e0d1e
|
[
"MIT"
] | 11
|
2019-07-08T09:56:54.000Z
|
2021-11-29T09:57:16.000Z
|
lib/quark/compose.ex
|
doma-engineering/quark
|
16af5e00f9048053678cbaf6fb770969446e0d1e
|
[
"MIT"
] | 7
|
2019-09-18T14:56:57.000Z
|
2021-05-25T17:16:43.000Z
|
defmodule Quark.Compose do
@moduledoc ~S"""
Function composition is taking two functions, and joining them together to
create a new function. For example:
## Examples
iex> sum_plus_one = compose([&(&1 + 1), &Enum.sum/1])
...> sum_plus_one.([1,2,3])
7
In this case, we have joined `Enum.sum` with a function that adds one,
to create a new function that takes a list, sums it, and adds one.
Note that composition normally applies _from right to left_, though `Quark`
provides the opposite in the form of `*_forward` functions.
"""
import Quark.SKI
import Quark.Curry
@doc ~S"""
Function composition
## Examples
iex> sum_plus_one = compose(&(&1 + 1), &Enum.sum/1)
...> [1, 2, 3] |> sum_plus_one.()
7
"""
@spec compose(fun, fun) :: any
def compose(g, f) do
fn x ->
x
|> curry(f).()
|> curry(g).()
end
end
@doc ~S"""
Function composition, from the tail of the list to the head
## Examples
iex> sum_plus_one = compose([&(&1 + 1), &Enum.sum/1])
...> [1,2,3] |> sum_plus_one.()
7
"""
@spec compose([fun]) :: fun
def compose(funcs) when is_list(funcs), do: funcs |> List.foldr(&id/1, &compose/2)
@doc ~S"""
Infix compositon operator
## Examples
iex> sum_plus_one = fn x -> x + 1 end <|> &Enum.sum/1
...> sum_plus_one.([1,2,3])
7
iex> add_one = &(&1 + 1)
...> piped = [1, 2, 3] |> Enum.sum() |> add_one.()
...> composed = [1, 2, 3] |> ((add_one <|> &Enum.sum/1)).()
...> piped == composed
true
"""
@spec fun <|> fun :: fun
def g <|> f, do: compose(g, f)
@doc ~S"""
Function composition, from the head to tail (left-to-right)
## Examples
iex> sum_plus_one = compose_forward(&Enum.sum/1, &(&1 + 1))
...> [1, 2, 3] |> sum_plus_one.()
7
"""
@spec compose_forward(fun, fun) :: fun
def compose_forward(f, g) do
compose(g, f)
end
@doc ~S"""
Infix "forward" compositon operator
## Examples
iex> sum_plus_one = (&Enum.sum/1) <~> fn x -> x + 1 end
...> sum_plus_one.([1, 2, 3])
7
iex> x200 = (&(&1 * 2)) <~> (&(&1 * 10)) <~> (&(&1 * 10))
...> x200.(5)
1000
iex> add_one = &(&1 + 1)
...> piped = [1, 2, 3] |> Enum.sum() |> add_one.()
...> composed = [1, 2, 3] |> ((&Enum.sum/1) <~> add_one).()
...> piped == composed
true
"""
@spec fun <~> fun :: fun
def f <~> g, do: compose_forward(f, g)
@doc ~S"""
Compose functions, from the head of the list of functions.
## Examples
iex> sum_plus_one = compose_forward([&Enum.sum/1, &(&1 + 1)])
...> sum_plus_one.([1, 2, 3])
7
"""
@spec compose_forward([fun]) :: fun
def compose_forward(funcs) when is_list(funcs), do: funcs |> List.foldl(&id/1, &compose/2)
end
| 22.824
| 92
| 0.540133
|
93dd4ca27c4ce428586ffcb55ec4ba5e68abcc4e
| 657
|
exs
|
Elixir
|
test/suite/compact_test.exs
|
rustra/jsonld-ex
|
4f903a04d4ba9f0f0df1b871a92eb89bc20f38dc
|
[
"MIT"
] | 12
|
2020-06-18T18:23:34.000Z
|
2022-01-05T15:00:09.000Z
|
test/suite/compact_test.exs
|
rustra/jsonld-ex
|
4f903a04d4ba9f0f0df1b871a92eb89bc20f38dc
|
[
"MIT"
] | 5
|
2020-06-16T16:18:14.000Z
|
2021-08-19T20:23:03.000Z
|
test/suite/compact_test.exs
|
rustra/jsonld-ex
|
4f903a04d4ba9f0f0df1b871a92eb89bc20f38dc
|
[
"MIT"
] | 6
|
2020-06-17T22:25:51.000Z
|
2021-08-19T19:55:49.000Z
|
defmodule JSON.LD.TestSuite.CompactTest do
use ExUnit.Case, async: false
import JSON.LD.TestSuite
setup_all do
[base_iri: manifest("compact")["baseIri"]]
end
test_cases("compact")
|> Enum.each(fn %{"name" => name, "input" => input} = test_case ->
@tag :test_suite
@tag :compact_test_suite
@tag data: test_case
test "#{input}: #{name}",
%{
data: %{"input" => input, "expect" => output, "context" => context} = test_case,
base_iri: base_iri
} do
assert JSON.LD.compact(j(input), j(context), test_case_options(test_case, base_iri)) ==
j(output)
end
end)
end
| 26.28
| 93
| 0.596651
|
93dd64084016c3b24ea56a6368e2c2722eabc1c1
| 1,620
|
ex
|
Elixir
|
lib/graphql/lang/ast/reducer.ex
|
marvinhagemeister/graphql
|
43bccc041438f05d14c8c6f40f193c3d7957ca9d
|
[
"BSD-3-Clause"
] | 719
|
2016-03-18T03:10:46.000Z
|
2022-02-02T10:07:29.000Z
|
lib/graphql/lang/ast/reducer.ex
|
marvinhagemeister/graphql
|
43bccc041438f05d14c8c6f40f193c3d7957ca9d
|
[
"BSD-3-Clause"
] | 51
|
2015-08-30T03:15:17.000Z
|
2016-03-02T07:13:26.000Z
|
lib/graphql/lang/ast/reducer.ex
|
marvinhagemeister/graphql
|
43bccc041438f05d14c8c6f40f193c3d7957ca9d
|
[
"BSD-3-Clause"
] | 34
|
2016-03-30T12:56:11.000Z
|
2021-08-30T09:21:54.000Z
|
# Used for computing a result as a function of the an AST traversal. The
# traditional OO Visitor pattern does not really work well in functional
# languages due to its reliance on generating side-effects.
defmodule GraphQL.Lang.AST.Reducer do
alias GraphQL.Lang.AST.{
Visitor,
InitialisingVisitor,
PostprocessingVisitor,
Nodes
}
def reduce(node, visitor, accumulator) do
accumulator = InitialisingVisitor.init(visitor, accumulator)
accumulator = visit(node, visitor, accumulator)
PostprocessingVisitor.finish(visitor, accumulator)
end
defp visit([child|rest], visitor, accumulator) do
accumulator = visit(child, visitor, accumulator)
visit(rest, visitor, accumulator)
end
defp visit([], _visitor, accumulator), do: accumulator
defp visit(node, visitor, accumulator) do
{next_action, accumulator} = Visitor.enter(visitor, node, accumulator)
accumulator = if next_action != :skip do
visit_children(node, visitor, accumulator)
else
accumulator
end
Visitor.leave(visitor, node, accumulator)
end
defp visit_children(node = %{kind: kind}, visitor, accumulator) when is_atom(kind) do
children = for child_key <- Nodes.kinds[node[:kind]], Map.has_key?(node, child_key), do: node[child_key]
visit_each_child(children, visitor, accumulator)
end
defp visit_each_child([child|rest], visitor, accumulator) do
accumulator = visit(child, visitor, accumulator)
accumulator = visit_each_child(rest, visitor, accumulator)
accumulator
end
defp visit_each_child([], _visitor, accumulator), do: accumulator
end
| 31.153846
| 108
| 0.733333
|
93dd8ae1c5d4b9ea853d267f573f4107f979651c
| 1,200
|
exs
|
Elixir
|
design/data_model_playground/test/commands/get_home_categories_test.exs
|
CircleCI-Public/firestorm
|
9ca2c46a2b2377370347ad94d6003eeb77be38d6
|
[
"MIT"
] | 10
|
2017-06-28T08:06:52.000Z
|
2022-03-19T17:49:21.000Z
|
design/data_model_playground/test/commands/get_home_categories_test.exs
|
CircleCI-Public/firestorm
|
9ca2c46a2b2377370347ad94d6003eeb77be38d6
|
[
"MIT"
] | null | null | null |
design/data_model_playground/test/commands/get_home_categories_test.exs
|
CircleCI-Public/firestorm
|
9ca2c46a2b2377370347ad94d6003eeb77be38d6
|
[
"MIT"
] | 2
|
2017-10-21T12:01:02.000Z
|
2021-01-29T10:26:22.000Z
|
defmodule DataModelPlayground.Commands.GetHomeCategoriesTest do
use ExUnit.Case
alias DataModelPlayground.Commands.{CreateCategory, GetHomeCategories}
alias DataModelPlayground.{Category, Repo}
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)
end
describe "fetching categories for the home screen" do
setup [:create_categories, :get_home_categories]
# FIXME: Don't return all!
test "returns all categories",
%{
category_ids: category_ids,
result: result
} do
{:ok, categories} = result
result_ids =
categories
|> Enum.map(&(&1.id))
assert Enum.sort(category_ids) == Enum.sort(result_ids)
end
end
def create_categories(_) do
options_foo =
%CreateCategory{
title: "foo",
}
options_bar =
%CreateCategory{
title: "bar",
}
{:ok, foo_id} = CreateCategory.run(options_foo)
{:ok, bar_id} = CreateCategory.run(options_bar)
{:ok, %{category_ids: [foo_id, bar_id]}}
end
def get_home_categories(_) do
options =
%GetHomeCategories{user_id: 0}
result = GetHomeCategories.run(options)
{:ok, result: result}
end
end
| 22.641509
| 72
| 0.65
|
93dde70239dd1be68032d2cd64652b404be675d5
| 972
|
ex
|
Elixir
|
lib/maestro/aggregate/supervisor.ex
|
toniqsystems/event_store
|
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
|
[
"Apache-2.0"
] | 103
|
2018-02-09T23:13:21.000Z
|
2021-08-18T04:22:41.000Z
|
lib/maestro/aggregate/supervisor.ex
|
tonic-sys/event_store
|
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
|
[
"Apache-2.0"
] | 20
|
2018-04-05T16:10:53.000Z
|
2021-07-01T08:21:50.000Z
|
lib/maestro/aggregate/supervisor.ex
|
tonic-sys/event_store
|
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
|
[
"Apache-2.0"
] | 3
|
2018-09-13T06:03:10.000Z
|
2019-07-11T15:22:53.000Z
|
defmodule Maestro.Aggregate.Supervisor do
@moduledoc """
Supervisor for `Maestro.Aggregate.Root`s across any/all domains.
All aggregate roots, no matter how many different kinds you may have, are
managed by a single supervisor/registry (for now). Given that aggregates are
independently configurable and extensible, the need for a 1:1 on supervisors
per aggregate is a premature optimization. Furthermore, aggregate IDs are HLC
timestamps and are thus unique even across aggregates.
"""
use DynamicSupervisor
alias Maestro.Aggregate.Root
def start_link(args) do
DynamicSupervisor.start_link(__MODULE__, args, name: __MODULE__)
end
def get_child(key, mod) do
spec = {Root, aggregate_id: key, module: mod}
case DynamicSupervisor.start_child(__MODULE__, spec) do
{:ok, pid} -> pid
{:error, {:already_started, pid}} -> pid
end
end
def init(_args) do
DynamicSupervisor.init(strategy: :one_for_one)
end
end
| 29.454545
| 79
| 0.737654
|
93de011f11c5dcd6fdefa5e2d46d6e472e93fe04
| 497
|
exs
|
Elixir
|
cards/mix.exs
|
thalesmiguel/elixir_tests
|
585d70f8e47686a6927db4d0ab23f5e6525292a1
|
[
"MIT"
] | null | null | null |
cards/mix.exs
|
thalesmiguel/elixir_tests
|
585d70f8e47686a6927db4d0ab23f5e6525292a1
|
[
"MIT"
] | null | null | null |
cards/mix.exs
|
thalesmiguel/elixir_tests
|
585d70f8e47686a6927db4d0ab23f5e6525292a1
|
[
"MIT"
] | null | null | null |
defmodule Cards.MixProject do
use Mix.Project
def project do
[
app: :cards,
version: "0.1.0",
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{ :ex_doc, "~> 0.19", only: :dev, runtime: false }
]
end
end
| 17.75
| 59
| 0.567404
|
93de1b2e75edfaeea567519b19b3768484ab349f
| 381
|
exs
|
Elixir
|
priv/repo/migrations/20171125175904_create_states.exs
|
suhaschitade/AppoRemind
|
64ed7123e7e5e2c40e398597c61d0a45db0cae50
|
[
"MIT"
] | null | null | null |
priv/repo/migrations/20171125175904_create_states.exs
|
suhaschitade/AppoRemind
|
64ed7123e7e5e2c40e398597c61d0a45db0cae50
|
[
"MIT"
] | null | null | null |
priv/repo/migrations/20171125175904_create_states.exs
|
suhaschitade/AppoRemind
|
64ed7123e7e5e2c40e398597c61d0a45db0cae50
|
[
"MIT"
] | null | null | null |
defmodule Hello.Repo.Migrations.CreateStates do
use Ecto.Migration
def change do
create table(:states) do
add :name, :string
add :twolettercode, :string
add :active, :boolean, default: false, null: false
add :country_id, references(:countries, on_delete: :delete_all)
timestamps()
end
create index(:states, [:country_id])
end
end
| 22.411765
| 69
| 0.674541
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.