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
sequence | 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
sequence | 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
sequence | 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f70047e45b24ccabf7e84e6af6eadcc9c0ab0135 | 6,398 | ex | Elixir | lib/monex/result.ex | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | 7 | 2016-12-25T08:26:08.000Z | 2021-08-15T01:23:53.000Z | lib/monex/result.ex | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | null | null | null | lib/monex/result.ex | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | 1 | 2020-09-07T06:59:55.000Z | 2020-09-07T06:59:55.000Z | defmodule MonEx.Result do
@moduledoc """
Result module provides Result type with utility functions.
"""
alias MonEx.Option
defmacro ok(res) do
quote do
{:ok, unquote(res)}
end
end
defmacro error(err) do
quote do
{:error, unquote(err)}
end
end
@typedoc """
Result type.
`ok(res)` or `error(err)` unwraps into `{:ok, res}` or `{:error, err}`
"""
@type t(res, err) :: {:ok, res} | {:error, err}
@doc """
Returns true if argument is `ok()`, false if `error()`
## Examples
iex> is_ok(ok(5))
true
iex> is_error(ok(5))
false
"""
@spec is_ok(t(any, any)) :: boolean
def is_ok(ok(_)), do: true
def is_ok(error(_)), do: false
@doc """
Returns true if argument is `error()`, false if `ok()`
## Examples
iex> is_error(error("Error"))
true
iex> is_ok(error("Error"))
false
"""
@spec is_error(t(any, any)) :: boolean
def is_error(x), do: !is_ok(x)
@doc """
Returns value `x` if argument is `ok(x)`, raises `e` if `error(e)`.
Second argument is a fallback. It can by a lambda accepting error, or some precomputed default value.
## Examples
iex> unwrap(ok(5))
5
iex> unwrap(error(:uh_oh), fn _ -> 10 end)
10
iex> unwrap(error(:uh_oh), 10)
10
"""
@spec unwrap(t(res, err), res | (err -> res)) :: res when res: any, err: any
def unwrap(result, fallback \\ nil)
def unwrap(ok(x), _), do: x
def unwrap(error(m), nil), do: raise m
def unwrap(error(m), f) when is_function(f, 1), do: f.(m)
def unwrap(error(_), fallback), do: fallback
@doc """
Converts Result into Option: `ok(val)` -> `some(val)`, `error(e)` -> `none()`.
Useful when you don't care about the error value and only what to emphasize that
nothing has been found.
## Examples
iex> unwrap_option(ok(5))
{:some, 5} # same as some(5)
iex> unwrap_option(error(:uh_oh))
{:none} # none()
"""
@spec unwrap_option(t(res, any)) :: Option.t(res) when res: any
def unwrap_option(ok(x)), do: {:some, x}
def unwrap_option(error(_)), do: {:none}
@doc """
Returns self if it is `ok(x)`, or evaluates supplied lambda that expected
to return another `result`. Returns supplied fallback result, if second argument is not a function.
## Examples
iex> ok(5) |> fallback(fn _ -> 1 end)
ok(5)
iex> error("WTF") |> fallback(fn m -> ok("\#{m}LOL") end)
ok("WTFLOL")
iex> error("WTF") |> fallback(ok(5))
ok(5)
"""
@spec fallback(t(res, err), t(res, err) | (err -> t(res, err))) :: t(res, err) when res: any, err: any
def fallback(ok(x), _), do: ok(x)
def fallback(error(m), f) when is_function(f, 1) do
f.(m)
end
def fallback(error(_), any), do: any
@doc """
Filters and unwraps the collection of results, leaving only ok's
## Examples
iex> [ok(1), error("oops")] |> collect_ok
[1]
"""
@spec collect_ok([t(res, any)]) :: [res] when res: any
def collect_ok(results) when is_list(results) do
Enum.reduce(results, [], fn
ok(res), acc -> [res | acc]
error(_), acc -> acc
end) |> Enum.reverse
end
@doc """
Filters and unwraps the collection of results, leaving only errors:
## Examples
iex> [ok(1), error("oops")] |> collect_error
["oops"]
"""
@spec collect_error([t(res, err)]) :: [err] when res: any, err: any
def collect_error(results) when is_list(results) do
Enum.reduce(results, [], fn
ok(_), acc -> acc
error(err), acc -> [err | acc]
end) |> Enum.reverse
end
@doc """
Groups and unwraps the collection of results, forming a Map with keys `:ok` and `:error`:
## Examples
iex> [ok(1), error("oops"), ok(2)] |> partition
%{ok: [1, 2], error: ["oops"]}
iex> [ok(1)] |> partition
%{ok: [1], error: []}
"""
@spec partition([t(res, err)]) :: %{ok: [res], error: [err]} when res: any, err: any
def partition(results) when is_list(results) do
base = %{ok: [], error: []}
results = Enum.group_by(results, fn
ok(_) -> :ok
error(_) -> :error
end, fn
ok(res) -> res
error(err) -> err
end)
Map.merge(base, results)
end
@doc """
Retry in case of error.
Possible options:
* `:n` - times to retry
* `:delay` — delay between retries
## Examples
result = retry n: 3, delay: 3000 do
remote_service()
end
This will call `remove_service()` 4 times (1 time + 3 retries) with an interval of 3 seconds.
"""
defmacro retry(opts \\ [], do: exp) do
quote do
n = Keyword.get(unquote(opts), :n, 5)
delay = Keyword.get(unquote(opts), :delay, 0)
retry_rec(n, delay, fn -> unquote(exp) end)
end
end
@doc false
@spec retry_rec(integer, integer, (() -> t(res, err))) :: t(res, err) when res: any, err: any
def retry_rec(0, _delay, lambda), do: lambda.()
def retry_rec(n, delay, lambda) do
case lambda.() do
error(_) ->
:timer.sleep(delay)
retry_rec(n - 1, delay, lambda)
ok -> ok
end
end
@doc """
Wraps expression and returns exception wrapped into `error()` if it happens,
otherwise `ok(result of expression)`, in case if expression returns result
type, it won't be wrapped.
Possible modes:
* `:full` - returns exception struct intact (default)
* `:message` — returns error message only
* `:module` — returns error module only
## Examples
iex> try_result do
...> 5 + 5
...> end
ok(10)
iex> broken = fn -> raise ArithmeticError, [message: "bad argument"] end
...> try_result do
...> broken.()
...> end
error(%ArithmeticError{message: "bad argument"})
...> try_result :message do
...> broken.()
...> end
error("bad argument")
...> try_result :module do
...> broken.()
...> end
error(ArithmeticError)
"""
defmacro try_result(mode \\ :full, do: exp) do
error_handler = case mode do
:message -> quote do e -> error(e.message) end
:module -> quote do e -> error(e.__struct__) end
_ -> quote do e -> error(e) end
end
quote do
try do
case unquote(exp) do
ok(res) -> ok(res)
error(e) -> error(e)
x -> ok(x)
end
rescue
unquote(error_handler)
end
end
end
end
| 25.49004 | 104 | 0.571429 |
f700654e4685725725ead8db046a39c968e0c08c | 1,378 | ex | Elixir | clients/cloud_search/lib/google_api/cloud_search/v1/model/spell_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_search/lib/google_api/cloud_search/v1/model/spell_result.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_search/lib/google_api/cloud_search/v1/model/spell_result.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.CloudSearch.V1.Model.SpellResult do
@moduledoc """
## Attributes
* `suggestedQuery` (*type:* `String.t`, *default:* `nil`) - The suggested spelling of the query.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:suggestedQuery => String.t()
}
field(:suggestedQuery)
end
defimpl Poison.Decoder, for: GoogleApi.CloudSearch.V1.Model.SpellResult do
def decode(value, options) do
GoogleApi.CloudSearch.V1.Model.SpellResult.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudSearch.V1.Model.SpellResult do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.319149 | 100 | 0.736575 |
f70074818b71a0cb48d3509586811e66e73a2243 | 2,338 | ex | Elixir | clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/location.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/location.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/location.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.CloudTasks.V2beta2.Model.Location do
@moduledoc """
A resource that represents Google Cloud Platform location.
## Attributes
* `displayName` (*type:* `String.t`, *default:* `nil`) - The friendly name for this location, typically a nearby city name.
For example, "Tokyo".
* `labels` (*type:* `map()`, *default:* `nil`) - Cross-service attributes for the location. For example
{"cloud.googleapis.com/region": "us-east1"}
* `locationId` (*type:* `String.t`, *default:* `nil`) - The canonical id for this location. For example: `"us-east1"`.
* `metadata` (*type:* `map()`, *default:* `nil`) - Service-specific metadata. For example the available capacity at the given
location.
* `name` (*type:* `String.t`, *default:* `nil`) - Resource name for the location, which may vary between implementations.
For example: `"projects/example-project/locations/us-east1"`
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:displayName => String.t(),
:labels => map(),
:locationId => String.t(),
:metadata => map(),
:name => String.t()
}
field(:displayName)
field(:labels, type: :map)
field(:locationId)
field(:metadata, type: :map)
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2beta2.Model.Location do
def decode(value, options) do
GoogleApi.CloudTasks.V2beta2.Model.Location.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2beta2.Model.Location do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.53125 | 129 | 0.690761 |
f70093a50210d9ff8af12d10d872138bde6080a3 | 3,216 | exs | Elixir | test/espy_web/api_test.exs | XRPL-Labs/XRPL-Webhook | 4b4194d3263ff957bbd3d654aefe06d1225fa73d | [
"MIT"
] | 9 | 2019-02-22T10:33:28.000Z | 2021-02-27T20:26:03.000Z | test/espy_web/api_test.exs | XRPL-Labs/XRPL-Webhook | 4b4194d3263ff957bbd3d654aefe06d1225fa73d | [
"MIT"
] | 11 | 2019-04-02T19:21:25.000Z | 2022-01-05T23:22:04.000Z | test/espy_web/api_test.exs | XRPL-Labs/XRPL-Webhook | 4b4194d3263ff957bbd3d654aefe06d1225fa73d | [
"MIT"
] | 6 | 2019-03-07T15:54:30.000Z | 2020-03-26T02:33:40.000Z | defmodule EspyWeb.ApiTest do
use EspyWeb.ConnCase
import EspyWeb.Factory
setup do
Supervisor.terminate_child(Espy.Supervisor, ConCache)
Supervisor.restart_child(Espy.Supervisor, ConCache)
:ok
end
test "/api/v1/webhooks", %{conn: conn} do
app1 = insert(:app)
# CREATE WEBHOOK INVALID URL
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_webhook_path(conn, :create), url: "https://invalid-url")
|> BlueBird.ConnLogger.save()
# CREATE WEBHOOK
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_webhook_path(conn, :create), url: "https://myapp.com/webhook")
|> BlueBird.ConnLogger.save()
response_create = json_response(conn1, 200)
webhook_id = Map.get(response_create, "webhook_id")
# GET LIST OF WEBHOOKS
conn2 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> get(api_webhook_path(conn, :list))
|> BlueBird.ConnLogger.save()
response_list = json_response(conn2, 200)
# DELETE WEBHOOK
conn3 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> delete(api_webhook_path(conn, :delete, webhook_id))
|> BlueBird.ConnLogger.save()
end
test "/api/v1/subscriptions", %{conn: conn} do
app1 = insert(:app)
# Invalid address
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_subscription_path(conn, :create), address: "invalid_address")
|> BlueBird.ConnLogger.save()
# Subscription an address
conn1 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> post(api_subscription_path(conn, :create), address: "rqAiBkWakRA9Jr5TCahtKrPS23KBYUZhj")
|> BlueBird.ConnLogger.save()
response_create = json_response(conn1, 200)
subscription_id = Map.get(response_create, "subscription_id")
# GET LIST OF SUBSCRIPTIONS
conn2 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> get(api_subscription_path(conn, :list))
|> BlueBird.ConnLogger.save()
response_list = json_response(conn2, 200)
# DEACTIVATE SUBSCRIPTION
conn3 = conn
|> put_req_header("x-api-key", app1.api_key)
|> put_req_header("x-api-secret", app1.api_secret)
|> put_req_header("content-type", "application/json; charset=utf-8")
|> delete(api_subscription_path(conn, :delete, subscription_id))
|> BlueBird.ConnLogger.save()
end
end
| 32.816327 | 97 | 0.664801 |
f700a389d06d19b1e2c4f273852e4c3149585893 | 3,906 | ex | Elixir | lib/jukee_web/channels/player_channel.ex | samuelbriole/Jukee | 1f0dd7616d63d742fac17daabaf50b406d9dbede | [
"MIT"
] | 3 | 2018-05-17T17:43:06.000Z | 2018-06-09T02:12:25.000Z | lib/jukee_web/channels/player_channel.ex | samuelbriole/Jukee | 1f0dd7616d63d742fac17daabaf50b406d9dbede | [
"MIT"
] | 2 | 2018-06-04T15:51:36.000Z | 2018-06-20T11:31:23.000Z | lib/jukee_web/channels/player_channel.ex | samuelbriole/jukee | 1f0dd7616d63d742fac17daabaf50b406d9dbede | [
"MIT"
] | null | null | null | defmodule JukeeWeb.PlayerChannel do
use JukeeWeb, :channel
alias Jukee.Players
alias JukeeWeb.PlayerView
alias Jukee.TrackSearch
alias Jukee.Tracks
alias JukeeWeb.PlayerPresence
require Logger
def join("player:" <> player_id, payload, socket) do
if authorized?(player_id, payload) do
send(self(), :after_join)
{:ok, socket}
else
{:error, %{reason: "unauthorized"}}
end
end
def terminate(_reason, socket) do
end_player_connection(socket)
end
def handle_info(:after_join, socket) do
socket = create_player_connection(socket)
push socket, "presence_state", PlayerPresence.list(socket)
{:ok, _} = PlayerPresence.track(socket, socket.assigns.user.id, %{
username: socket.assigns.user.username,
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
# Channels can be used in a request/response fashion
# by sending replies to requests from the client
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
def handle_in("play_track", %{"playerTrackIndex" => player_track_index}, socket) do
player_id = get_player_id(socket)
Players.play_track_on_player(player_id, player_track_index)
{:reply, {:ok, %{ message: "new track playing" }}, socket}
end
def handle_in("play", _payload, socket) do
player_id = get_player_id(socket)
Players.play(player_id)
{:reply, {:ok, %{ message: "playing" }}, socket}
end
def handle_in("pause", _payload, socket) do
player_id = get_player_id(socket)
Players.pause(player_id)
{:reply, {:ok, %{ message: "paused" }}, socket}
end
def handle_in("toggle_pause", _payload, socket) do
player_id = get_player_id(socket)
Players.toggle_pause(player_id)
{:reply, {:ok, %{ message: "toggled" }}, socket}
end
def handle_in("seek", %{"to" => to}, socket) do
player_id = get_player_id(socket)
Players.seek(player_id, to)
{:reply, {:ok, %{ message: "seek success" }}, socket}
end
def handle_in("next", _payload, socket) do
player_id = get_player_id(socket)
Players.next(player_id)
{:reply, {:ok, %{ message: "next success" }}, socket}
end
def handle_in("previous", _payload, socket) do
player_id = get_player_id(socket)
Players.previous(player_id)
{:reply, {:ok, %{ message: "previous success" }}, socket}
end
def handle_in("add_track", %{"provider" => provider, "externalId" => external_id}, socket) do
player_id = get_player_id(socket)
track = TrackSearch.get_track(provider, external_id)
Players.add_track(player_id, track)
{:reply, {:ok, %{ message: "track added" }}, socket}
end
def handle_in("delete_track", %{"playerTrackIndex" => player_track_index}, socket) do
player_id = get_player_id(socket)
Players.delete_track_on_player(player_id, player_track_index)
{:reply, {:ok, %{ message: "track deleted" }}, socket}
end
def handle_in("autoplay", %{"autoplay" => autoplay}, socket) do
player_id = get_player_id(socket)
Players.set_autoplay(player_id, autoplay)
{:reply, {:ok, %{ message: "ok" }}, socket}
end
defp get_player_id(socket) do
"player:" <> player_id = socket.topic
player_id
end
# Everyone can join a player channel
defp authorized?(_player_id, _payload) do
true
end
defp create_player_connection(socket) do
user = socket.assigns.user
player_id = get_player_id(socket)
{:ok, player_connection} = Players.create_player_connection(%{
user_id: user.id,
player_id: player_id,
start_date: NaiveDateTime.utc_now()
})
Phoenix.Socket.assign(socket, :player_connection, player_connection)
end
defp end_player_connection(socket) do
player_connection = socket.assigns.player_connection
Players.update_player_connection(player_connection, %{ end_date: NaiveDateTime.utc_now() })
end
end
| 31 | 95 | 0.689196 |
f700ed269eb4d8e6666457796cce8fe603084df7 | 1,383 | exs | Elixir | mix.exs | appunite/proto_response | 6bb3e0023000e741598ea004bbb114abbc2278fd | [
"Apache-2.0"
] | 4 | 2017-09-19T12:21:13.000Z | 2021-01-04T16:29:43.000Z | mix.exs | appunite/proto_response | 6bb3e0023000e741598ea004bbb114abbc2278fd | [
"Apache-2.0"
] | 1 | 2017-10-20T12:14:51.000Z | 2017-10-20T12:14:51.000Z | mix.exs | appunite/proto_response | 6bb3e0023000e741598ea004bbb114abbc2278fd | [
"Apache-2.0"
] | 1 | 2017-09-23T03:52:47.000Z | 2017-09-23T03:52:47.000Z | defmodule ProtoResponse.Mixfile do
use Mix.Project
@version "0.4.1"
def project do
[
app: :proto_response,
deps: deps(System.get_env("PROTOBUF_PACKAGE")),
description: description(),
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env()),
package: package(),
version: @version
]
end
defp package do
[
name: :proto_response,
files: ~w(lib mix.exs README.md LICENSE),
maintainers: ["Tobiasz Małecki"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/appunite/proto_response"}
]
end
defp description do
"Provides helper function similar to Phoenix.ConnTest.json_response/2, but for protobuf"
end
def application do
[
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/proto.ex"]
defp elixirc_paths(_), do: ["lib"]
# both libraries uses same module name :/
defp deps("exprotobuf") do
[
{:exprotobuf, "~> 1.0", optional: true},
{:phoenix, "~> 1.1"}
]
end
defp deps("protobuf") do
[
{:protobuf, "~> 0.3", optional: true},
{:phoenix, "~> 1.1"}
]
end
defp deps(_) do
[
{:exprotobuf, "~> 1.0", optional: true},
{:protobuf, "~> 0.3", optional: true},
{:phoenix, "~> 1.1"},
{:ex_doc, "~> 0.13", only: :dev}
]
end
end
| 21.276923 | 92 | 0.570499 |
f700f90fdd8771acfd6a54887dd63fe8ad2876fd | 143 | ex | Elixir | lib/demo_web/live/example_live/static_title_component.ex | pthompson/live_component_examples | e2e1be52a7ff1065fd5ef749c375d729d5d08c21 | [
"MIT"
] | 21 | 2019-12-15T19:14:56.000Z | 2022-02-07T16:04:30.000Z | lib/demo_web/live/example_live/static_title_component.ex | pthompson/live_component_examples | e2e1be52a7ff1065fd5ef749c375d729d5d08c21 | [
"MIT"
] | 4 | 2020-02-06T01:05:28.000Z | 2020-09-07T19:08:45.000Z | lib/demo_web/live/example_live/static_title_component.ex | pthompson/live_component_examples | e2e1be52a7ff1065fd5ef749c375d729d5d08c21 | [
"MIT"
] | 6 | 2019-12-15T19:15:02.000Z | 2021-09-16T20:35:53.000Z | defmodule DemoWeb.StaticTitleComponent do
use Phoenix.LiveComponent
def render(assigns) do
~L"""
<h1>Title</h1>
"""
end
end
| 14.3 | 41 | 0.664336 |
f700fda5320043e8b56a32eb3ff0a5251971236f | 3,989 | ex | Elixir | lib/apoc/hazmat/aead/aes-gcm.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 6 | 2018-10-04T14:18:35.000Z | 2020-05-15T08:43:31.000Z | lib/apoc/hazmat/aead/aes-gcm.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 3 | 2018-10-23T12:20:45.000Z | 2021-01-27T10:41:14.000Z | lib/apoc/hazmat/aead/aes-gcm.ex | auxesis/apoc | e650c21767f508a2720dad1bb3d14439bdcf39c4 | [
"Apache-2.0"
] | 2 | 2020-02-19T00:43:37.000Z | 2021-08-19T04:04:25.000Z | defmodule Apoc.Hazmat.AEAD.AESGCM do
@moduledoc """
Implementation of the AES block encryption
standard as per [FIPS PUB 197](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf).
The functions in this module operate in GCM (Galois/Counter Mode) to provide
fast Authenticated Encryption.
See [Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC](https://csrc.nist.gov/publications/detail/sp/800-38d/final).
Additionally, three block sizes are support (128, 192 and 256). For those particularly
paranoid users, a block size of 256 is recommended for defense against [Shore's algorithm](https://arxiv.org/abs/quant-ph/9508027).
Use a 32 byte key for a 256 bit block size. See `encrypt/2`.
"""
@type aes_key() :: <<_::16, _::_*8>> | <<_::24, _::_*8>> | <<_::32, _::_*8>>
@iv_byte_size 16
defguardp is_key_of_size(key, size) when is_binary(key) and byte_size(key) == size
defguardp is_valid_aad(aad) when aad in ["AES128GCM", "AES192GCM", "AES256GCM"]
@doc """
Encrypt a message using AES under the given key
The key should be a 16, 24 or 32 byte binary string
## Example
```elixir
Apoc.AES.encrypt("a secret message", Apoc.rand_bytes(16))
```
It's important that the key be as uniformly random as possible.
Consequently, avoid the temptation to do this:
```elixir
# Don't do this
k = Apoc.rand_bytes(16) |> Base.encode16
byte_size(k) # => 32
Apoc.AES.encrypt(message, k)
```
As the bytesize of the encoded key in this example is 32 bytes
the 256 bit block size will be used. However, this is not a uniformly
random key in `{0,1}^32`. Specifically, the probability of a key containing
a character other than [0-9a-f] is zero.
To avoid this issue, don't use ASCII (e.g. hex of base 64 encoded strings)
as the key. By all means, encode the key for storage purposes but make sure
your key has been generated with the correct number of bytes.
```elixir
k = Apoc.rand_bytes(32)
Apoc.AES.encrypt(message, k)
Apoc.encode(k) # => base 64 encoded for storage somewhere safe
```
"""
# TODO: Optional additional AD
@spec encrypt(String.t(), aes_key()) :: {:ok, binary()} | {:error, binary()}
def encrypt(msg, key) when is_binary(msg) and is_key_of_size(key, 16) do
do_encrypt(msg, "AES128GCM", key)
end
def encrypt(msg, key) when is_binary(msg) and is_key_of_size(key, 24) do
do_encrypt(msg, "AES192GCM", key)
end
def encrypt(msg, key) when is_binary(msg) and is_key_of_size(key, 32) do
do_encrypt(msg, "AES256GCM", key)
end
def encrypt(x, _) when not is_binary(x) do
{:error, "Message must be a binary"}
end
def encrypt(_, _) do
{:error, "Invalid key size"}
end
def encrypt!(msg, key) do
with {:ok, ct} <- encrypt(msg, key) do
ct
else
{:error, message} ->
raise Apoc.Error, message: message
end
end
@doc """
Decrypt a cipher text that has been encrypted under the given key.
## Example
```elixir
{:ok, plaintext} = Apoc.AES.decrypt(ciphertext, key)
```
"""
@spec decrypt(String.t(), aes_key) :: {:ok, binary} | {:error, String.t()}
def decrypt(payload, key) do
with {:ok, <<aad::binary-9, iv::binary-16, tag::binary-16, ct::binary>>} <-
Apoc.decode(payload) do
do_decrypt(ct, aad, iv, tag, key)
end
end
defp do_encrypt(msg, aad, key) do
iv = Apoc.rand_bytes(@iv_byte_size)
try do
with {ct, tag} <- :crypto.block_encrypt(:aes_gcm, key, iv, {aad, msg}) do
{:ok, Apoc.encode(aad <> iv <> tag <> ct)}
end
rescue
err in ArgumentError ->
{:error, err.message}
err ->
{:error, inspect(err)}
end
end
defp do_decrypt(ct, aad, iv, tag, key) when is_valid_aad(aad) do
:aes_gcm
|> :crypto.block_decrypt(key, iv, {aad, ct, tag})
|> case do
plain_text when is_binary(plain_text) ->
{:ok, plain_text}
_ ->
:error
end
end
end
| 29.548148 | 155 | 0.655051 |
f701022b8d97e5f4a5de3b2648eb7ee92865775b | 808 | ex | Elixir | lib/coherence/plugs/validate_option.ex | henb/coherence | 725247353bad46df464caffa12b9ea2788fe774f | [
"MIT"
] | null | null | null | lib/coherence/plugs/validate_option.ex | henb/coherence | 725247353bad46df464caffa12b9ea2788fe774f | [
"MIT"
] | null | null | null | lib/coherence/plugs/validate_option.ex | henb/coherence | 725247353bad46df464caffa12b9ea2788fe774f | [
"MIT"
] | 1 | 2019-09-11T10:21:21.000Z | 2019-09-11T10:21:21.000Z | defmodule Coherence.ValidateOption do
@moduledoc """
Plug to validate the given option is enabled in the project's configuration.
"""
import Coherence.Controller, only: [logged_out_url: 1]
import Plug.Conn
import Phoenix.Controller, only: [put_flash: 3, redirect: 2]
alias Coherence.Messages
@behaviour Plug
@dialyzer [
{:nowarn_function, call: 2},
{:nowarn_function, init: 1},
]
@spec init(Keyword.t | atom) :: [tuple]
def init(options) do
%{option: options}
end
@spec call(Plug.Conn.t, Map.t) :: Plug.Conn.t
def call(conn, opts) do
if Coherence.Config.has_option(opts[:option]) do
conn
else
conn
|> put_flash(:error, Messages.backend().invalid_request())
|> redirect(to: logged_out_url(conn))
|> halt
end
end
end
| 21.837838 | 78 | 0.659653 |
f7012f6d03c928c74a572130021e6c4258a7e3c5 | 2,242 | ex | Elixir | clients/monitoring/lib/google_api/monitoring/v3/model/typed_value.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/monitoring/lib/google_api/monitoring/v3/model/typed_value.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/monitoring/lib/google_api/monitoring/v3/model/typed_value.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.Monitoring.V3.Model.TypedValue do
@moduledoc """
A single strongly-typed value.
## Attributes
* `boolValue` (*type:* `boolean()`, *default:* `nil`) - A Boolean value: true or false.
* `distributionValue` (*type:* `GoogleApi.Monitoring.V3.Model.Distribution.t`, *default:* `nil`) - A distribution value.
* `doubleValue` (*type:* `float()`, *default:* `nil`) - A 64-bit double-precision floating-point number. Its magnitude is approximately ±10±300 and it has 16 significant digits of precision.
* `int64Value` (*type:* `String.t`, *default:* `nil`) - A 64-bit integer. Its range is approximately ±9.2x1018.
* `stringValue` (*type:* `String.t`, *default:* `nil`) - A variable-length string value.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:boolValue => boolean(),
:distributionValue => GoogleApi.Monitoring.V3.Model.Distribution.t(),
:doubleValue => float(),
:int64Value => String.t(),
:stringValue => String.t()
}
field(:boolValue)
field(:distributionValue, as: GoogleApi.Monitoring.V3.Model.Distribution)
field(:doubleValue)
field(:int64Value)
field(:stringValue)
end
defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.TypedValue do
def decode(value, options) do
GoogleApi.Monitoring.V3.Model.TypedValue.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.TypedValue do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38 | 194 | 0.70785 |
f70142ac0dead99bb1eb2d8a7db06d555b05d8d1 | 149 | exs | Elixir | test/make_word_bot/base_test.exs | nulleof/make-word-bot | bf6ed80975f0d89697cdd5e1019d73c47dd335d4 | [
"MIT"
] | null | null | null | test/make_word_bot/base_test.exs | nulleof/make-word-bot | bf6ed80975f0d89697cdd5e1019d73c47dd335d4 | [
"MIT"
] | 5 | 2019-02-10T14:22:39.000Z | 2019-02-11T16:29:02.000Z | test/make_word_bot/base_test.exs | nulleof/make-word-bot | bf6ed80975f0d89697cdd5e1019d73c47dd335d4 | [
"MIT"
] | null | null | null | defmodule MakeWordBot.BaseTest do
use ExUnit.Case
doctest MakeWordBot
doctest MakeWordBot.ProcessMessage
doctest MakeWordBot.WordChecker
end
| 21.285714 | 36 | 0.838926 |
f7014928c025feb734460b4d6d668cfb64b55039 | 2,498 | ex | Elixir | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_addons_config.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_addons_config.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_addons_config.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig do
@moduledoc """
Add-on configurations for the Apigee organization.
## Attributes
* `advancedApiOpsConfig` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AdvancedApiOpsConfig.t`, *default:* `nil`) - Configuration for the Advanced API Ops add-on.
* `integrationConfig` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1IntegrationConfig.t`, *default:* `nil`) - Configuration for the Integration add-on.
* `monetizationConfig` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1MonetizationConfig.t`, *default:* `nil`) - Configuration for the Monetization add-on.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:advancedApiOpsConfig =>
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AdvancedApiOpsConfig.t() | nil,
:integrationConfig =>
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1IntegrationConfig.t() | nil,
:monetizationConfig =>
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1MonetizationConfig.t() | nil
}
field(:advancedApiOpsConfig,
as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AdvancedApiOpsConfig
)
field(:integrationConfig, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1IntegrationConfig)
field(:monetizationConfig, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1MonetizationConfig)
end
defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig do
def decode(value, options) do
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1AddonsConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.338983 | 175 | 0.760208 |
f70149449b7d97da2121163e4632ebd915daa9ff | 1,676 | ex | Elixir | lib/grakn/session.ex | liveforeverx/grakn_elixir | e64745fb200dd64956396c33b986b94706556ab4 | [
"MIT"
] | 1 | 2019-04-25T18:12:23.000Z | 2019-04-25T18:12:23.000Z | lib/grakn/session.ex | liveforeverx/grakn_elixir | e64745fb200dd64956396c33b986b94706556ab4 | [
"MIT"
] | null | null | null | lib/grakn/session.ex | liveforeverx/grakn_elixir | e64745fb200dd64956396c33b986b94706556ab4 | [
"MIT"
] | null | null | null | defmodule Grakn.Session do
@moduledoc false
@opaque t :: GRPC.Channel.t()
# every 5 min
@ping_rate 300_000
@spec new(String.t()) :: {:ok, t()} | {:error, any()}
def new(uri) do
GRPC.Stub.connect(uri, adapter_opts: %{http2_opts: %{keepalive: @ping_rate}})
end
@spec transaction(t(), String.t()) :: {:ok, Grakn.Transaction.t(), String.t()} | {:error, any()}
def transaction(channel, keyspace) do
channel
|> Grakn.Transaction.new(keyspace)
end
@spec command(t(), Grakn.Command.command(), keyword()) :: {:ok, any()} | {:error, any()}
def command(channel, :get_keyspaces, _) do
request = Keyspace.Keyspace.Retrieve.Req.new()
channel
|> Keyspace.KeyspaceService.Stub.retrieve(request)
|> case do
{:ok, %Keyspace.Keyspace.Retrieve.Res{names: names}} ->
{:ok, names}
{:error, reason} ->
{:error, reason}
resp ->
{:error, "Unexpected response from service #{inspect(resp)}"}
end
end
def command(channel, :create_keyspace, name: name) do
request = Keyspace.Keyspace.Create.Req.new(name: name)
channel
|> Keyspace.KeyspaceService.Stub.create(request)
|> case do
{:ok, %Keyspace.Keyspace.Create.Res{}} -> {:ok, nil}
error -> error
end
end
def command(channel, :delete_keyspace, name: name) do
request = Keyspace.Keyspace.Delete.Req.new(name: name)
channel
|> Keyspace.KeyspaceService.Stub.delete(request)
|> case do
{:ok, %Keyspace.Keyspace.Delete.Res{}} -> {:ok, nil}
error -> error
end
end
@spec close(t()) :: :ok
def close(channel) do
channel
|> GRPC.Stub.disconnect()
:ok
end
end
| 24.647059 | 98 | 0.618138 |
f7014def0560d0dce71f8f4c7e9cafbdd023f64f | 997 | ex | Elixir | web/views/error_helpers.ex | sgeos/memo_api | d57d0a1190296364a559510de9b4dd9d50b034e8 | [
"CC0-1.0"
] | null | null | null | web/views/error_helpers.ex | sgeos/memo_api | d57d0a1190296364a559510de9b4dd9d50b034e8 | [
"CC0-1.0"
] | null | null | null | web/views/error_helpers.ex | sgeos/memo_api | d57d0a1190296364a559510de9b4dd9d50b034e8 | [
"CC0-1.0"
] | null | null | null | defmodule MemoApi.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
if error = form.errors[field] do
content_tag :span, translate_error(error), class: "help-block"
end
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# Because error messages were defined within Ecto, we must
# call the Gettext module passing our Gettext backend. We
# also use the "errors" domain as translations are placed
# in the errors.po file. On your own code and templates,
# this could be written simply as:
#
# dngettext "errors", "1 file", "%{count} files", count
#
Gettext.dngettext(MemoApi.Gettext, "errors", msg, msg, opts[:count], opts)
end
def translate_error(msg) do
Gettext.dgettext(MemoApi.Gettext, "errors", msg)
end
end
| 27.694444 | 78 | 0.679037 |
f70190f0277a8ed36ef3050b36678f27aa12a095 | 1,536 | ex | Elixir | web/controllers/server_controller.ex | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | 2 | 2016-11-16T17:24:21.000Z | 2019-02-15T05:38:27.000Z | web/controllers/server_controller.ex | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | null | null | null | web/controllers/server_controller.ex | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | null | null | null | defmodule Tox.ServerController do
use Tox.Web, :controller
alias Tox.Server
def index(conn, _params) do
servers = Repo.all(Server)
render(conn, "index.json", servers: servers)
end
def create(conn, %{"server" => server_params}) do
changeset = Server.changeset(%Server{}, server_params)
case Repo.insert(changeset) do
{:ok, server} ->
conn
|> put_status(:created)
|> put_resp_header("location", server_path(conn, :show, server))
|> render("show.json", server: server)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Tox.ChangesetView, "error.json", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
server = Repo.get!(Server, id)
render(conn, "show.json", server: server)
end
def update(conn, %{"id" => id, "server" => server_params}) do
server = Repo.get!(Server, id)
changeset = Server.changeset(server, server_params)
case Repo.update(changeset) do
{:ok, server} ->
render(conn, "show.json", server: server)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(Tox.ChangesetView, "error.json", changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
server = Repo.get!(Server, id)
# Here we use delete! (with a bang) because we expect
# it to always work (and if it does not, it will raise).
Repo.delete!(server)
send_resp(conn, :no_content, "")
end
end
| 27.428571 | 72 | 0.61849 |
f701b34d822846e33faa33cebaf337e526076b8f | 3,494 | ex | Elixir | clients/games/lib/google_api/games/v1/model/player_leaderboard_score.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/games/lib/google_api/games/v1/model/player_leaderboard_score.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/player_leaderboard_score.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.Games.V1.Model.PlayerLeaderboardScore do
@moduledoc """
This is a JSON template for a player leaderboard score object.
## Attributes
* `kind` (*type:* `String.t`, *default:* `games#playerLeaderboardScore`) - Uniquely identifies the type of this resource. Value is always the fixed string games#playerLeaderboardScore.
* `leaderboard_id` (*type:* `String.t`, *default:* `nil`) - The ID of the leaderboard this score is in.
* `publicRank` (*type:* `GoogleApi.Games.V1.Model.LeaderboardScoreRank.t`, *default:* `nil`) - The public rank of the score in this leaderboard. This object will not be present if the user is not sharing their scores publicly.
* `scoreString` (*type:* `String.t`, *default:* `nil`) - The formatted value of this score.
* `scoreTag` (*type:* `String.t`, *default:* `nil`) - Additional information about the score. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986.
* `scoreValue` (*type:* `String.t`, *default:* `nil`) - The numerical value of this score.
* `socialRank` (*type:* `GoogleApi.Games.V1.Model.LeaderboardScoreRank.t`, *default:* `nil`) - The social rank of the score in this leaderboard.
* `timeSpan` (*type:* `String.t`, *default:* `nil`) - The time span of this score.
Possible values are:
- "ALL_TIME" - The score is an all-time score.
- "WEEKLY" - The score is a weekly score.
- "DAILY" - The score is a daily score.
* `writeTimestamp` (*type:* `String.t`, *default:* `nil`) - The timestamp at which this score was recorded, in milliseconds since the epoch in UTC.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:leaderboard_id => String.t(),
:publicRank => GoogleApi.Games.V1.Model.LeaderboardScoreRank.t(),
:scoreString => String.t(),
:scoreTag => String.t(),
:scoreValue => String.t(),
:socialRank => GoogleApi.Games.V1.Model.LeaderboardScoreRank.t(),
:timeSpan => String.t(),
:writeTimestamp => String.t()
}
field(:kind)
field(:leaderboard_id)
field(:publicRank, as: GoogleApi.Games.V1.Model.LeaderboardScoreRank)
field(:scoreString)
field(:scoreTag)
field(:scoreValue)
field(:socialRank, as: GoogleApi.Games.V1.Model.LeaderboardScoreRank)
field(:timeSpan)
field(:writeTimestamp)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.PlayerLeaderboardScore do
def decode(value, options) do
GoogleApi.Games.V1.Model.PlayerLeaderboardScore.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.PlayerLeaderboardScore do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.586667 | 230 | 0.700057 |
f701d95899578b5b28f213b78eb2316130b1676b | 732 | exs | Elixir | test/nerves_hub/client/default_test.exs | aadavids/nerves_hub | 504f143381b2cc7c7e76a049febbb590ad5752f1 | [
"Apache-2.0"
] | null | null | null | test/nerves_hub/client/default_test.exs | aadavids/nerves_hub | 504f143381b2cc7c7e76a049febbb590ad5752f1 | [
"Apache-2.0"
] | null | null | null | test/nerves_hub/client/default_test.exs | aadavids/nerves_hub | 504f143381b2cc7c7e76a049febbb590ad5752f1 | [
"Apache-2.0"
] | null | null | null | defmodule NervesHub.Client.DefaultTest do
use ExUnit.Case, async: true
alias NervesHub.Client.Default
doctest Default
test "update_available/1" do
assert Default.update_available(-1) == :apply
end
describe "handle_fwup_message/1" do
test "progress" do
assert Default.handle_fwup_message({:progress, 25}) == :ok
end
test "error" do
assert Default.handle_fwup_message({:error, :any, "message"}) == :ok
end
test "warning" do
assert Default.handle_fwup_message({:warning, :any, "message"}) == :ok
end
test "any" do
assert Default.handle_fwup_message(:any) == :ok
end
end
test "handle_error/1" do
assert Default.handle_error(:error) == :ok
end
end
| 22.181818 | 76 | 0.670765 |
f701ddc702fd1180e83f428cab70fbdc9e210469 | 992 | ex | Elixir | apps/legion/lib/stereotype/stereotype.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 1 | 2021-01-04T11:06:12.000Z | 2021-01-04T11:06:12.000Z | apps/legion/lib/stereotype/stereotype.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 3 | 2021-01-30T06:40:37.000Z | 2021-01-30T06:41:08.000Z | apps/legion/lib/stereotype/stereotype.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | null | null | null | defmodule Legion.Stereotype do
@moduledoc """
Defines stereotypes for the modules of the application.
"""
def model do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
alias Legion.Repo
end
end
def virtual do
quote do
use Ecto.Schema
import Ecto
import Ecto.Query
alias Legion.Repo
end
end
def singleton do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
alias Legion.Repo
end
end
def service do
quote do
import Ecto
import Ecto.Changeset
import Ecto.Query
alias Legion.Repo
end
end
def viewdecl do
quote do
use Legion.Stereotype.ViewDecl
use Legion.Stereotype, :model
end
end
@doc """
When used, dispatch to the appropriate stereotype.
"""
defmacro __using__(which) when is_atom(which),
do: apply(__MODULE__, which, [])
end
| 15.746032 | 57 | 0.629032 |
f701dea430ebd5735b2ba5cb96f32926ebf56630 | 5,323 | ex | Elixir | lib/api.ex | symmetrically/paypal | c775ef4cb8f8f169b2bd37bd2587e4edff1c25b3 | [
"MIT"
] | null | null | null | lib/api.ex | symmetrically/paypal | c775ef4cb8f8f169b2bd37bd2587e4edff1c25b3 | [
"MIT"
] | 1 | 2021-12-11T02:43:28.000Z | 2021-12-11T02:43:28.000Z | lib/api.ex | symmetrically/paypal | c775ef4cb8f8f169b2bd37bd2587e4edff1c25b3 | [
"MIT"
] | null | null | null | defmodule PayPal.API do
@moduledoc """
Documentation for PayPal.API. This module is about the base HTTP functionality
"""
@base_url_sandbox "https://api.sandbox.paypal.com/v1/"
@base_url_live "https://api.paypal.com/v1/"
@doc """
Requests an OAuth token from PayPal, returns a tuple containing the token and seconds till expiry.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, {"XXXXXXXXXXXXXX", 32000}}
- {:error, :unauthorised}
- {:error, :bad_network}
## Examples
iex> PayPal.API.get_oauth_token
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec get_oauth_token :: {atom, any}
def get_oauth_token do
headers = %{"Content-Type" => "application/x-www-form-urlencoded"}
options = [hackney: [basic_auth: {PayPal.Config.get.client_id, PayPal.Config.get.client_secret}]]
form = {:form, [grant_type: "client_credentials"]}
case HTTPoison.post(base_url() <> "oauth2/token", form, headers, options) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{body: body, status_code: 200}} ->
%{access_token: access_token, expires_in: expires_in} = Poison.decode!(body, keys: :atoms)
{:ok, {access_token, expires_in}}
_->
{:error, :bad_network}
end
end
@doc """
Make a HTTP GET request to the correct API depending on environment, adding needed auth header.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, data}
- {:ok, :not_found}
- {:ok, :no_content}
- {:error, :bad_network}
- {:error, reason}
## Examples
iex> PayPal.API.get(url)
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec get(String.t) :: {atom, any}
def get(url) do
case HTTPoison.get(base_url() <> url, headers()) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{body: body, status_code: 200}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{status_code: 404}} ->
{:ok, :not_found}
{:ok, %{status_code: 400}} ->
{:ok, :not_found}
{:ok, %{status_code: 204}} ->
{:ok, :no_content}
{:ok, %{body: body}}->
{:error, body}
_ ->
{:error, :bad_network}
end
end
@doc """
Make a HTTP POST request to the correct API depending on environment, adding needed auth header.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, data}
- {:ok, :not_found}
- {:ok, :no_content}
- {:error, :bad_network}
- {:error, reason}
## Examples
iex> PayPal.API.post(url, data)
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec post(String.t, map) :: {atom, any}
def post(url, data) do
{:ok, data} = Poison.encode(data)
case HTTPoison.post(base_url() <> url, data, headers()) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{body: body, status_code: 200}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{body: body, status_code: 201}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{status_code: 404}} ->
{:ok, :not_found}
{:ok, %{status_code: 204}} ->
{:ok, nil}
{:ok, %{status_code: 400}} ->
{:error, :malformed_request}
{:ok, %{body: body}} = resp ->
IO.inspect resp
{:error, body}
_ ->
{:error, :bad_network}
end
end
@doc """
Make a HTTP PATCH request to the correct API depending on environment, adding needed auth header.
Note: If your name is not Zen and you're reading this, unless you're sending me a PR (thanks!), you probably don't need this.
Possible returns:
- {:ok, data}
- {:ok, :not_found}
- {:ok, :no_content}
- {:error, :bad_network}
- {:error, reason}
## Examples
iex> PayPal.API.patch(url, data)
{:ok, {"XXXXXXXXXXXXXX", 32000}}
"""
@spec patch(String.t, map) :: {atom, any}
def patch(url, data) do
{:ok, data} = Poison.encode(data)
case HTTPoison.patch(base_url() <> url, data, headers()) do
{:ok, %{status_code: 401}} ->
{:error, :unauthorised}
{:ok, %{status_code: 200}} ->
{:ok, nil}
{:ok, %{body: body, status_code: 201}} ->
{:ok, Poison.decode!(body, keys: :atoms)}
{:ok, %{status_code: 404}} ->
{:ok, :not_found}
{:ok, %{status_code: 204}} ->
{:ok, :no_content}
{:ok, %{status_code: 400}} ->
{:error, :malformed_request}
{:ok, %{body: body}} = resp ->
IO.inspect resp
{:error, body}
_ ->
{:error, :bad_network}
end
end
@spec headers :: map
defp headers do
%{"Authorization" => "Bearer #{Application.get_env(:pay_pal, :access_token)}", "Content-Type" => "application/json"}
end
@spec base_url :: String.t
defp base_url do
case Application.get_env(:pay_pal, :env) do
:sandbox -> @base_url_sandbox
:live -> @base_url_live
_ ->
require Logger
Logger.warn "[PayPal] No `env` found in config, use `sandbox` as default."
@base_url_sandbox
end
end
end
| 28.929348 | 127 | 0.588014 |
f701fadbf33e0d3277a9561d2305055110b4c622 | 84 | exs | Elixir | legacy/artie/apps/pypool/test/python_process_test.exs | MaxStrange/ArtieInfant | 1edbb171a5405d2971227f2d2d83acb523c70034 | [
"MIT"
] | 1 | 2018-04-28T16:55:05.000Z | 2018-04-28T16:55:05.000Z | legacy/artie/apps/pypool/test/python_process_test.exs | MaxStrange/ArtieInfant | 1edbb171a5405d2971227f2d2d83acb523c70034 | [
"MIT"
] | null | null | null | legacy/artie/apps/pypool/test/python_process_test.exs | MaxStrange/ArtieInfant | 1edbb171a5405d2971227f2d2d83acb523c70034 | [
"MIT"
] | null | null | null | defmodule PythonProcessTest do
use ExUnit.Case
doctest Pypool.PythonProcess
end
| 16.8 | 30 | 0.833333 |
f702205e88e69c40e02640d593d43096ec88e0eb | 1,454 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/firewall_log_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/firewall_log_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/firewall_log_config.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.FirewallLogConfig do
@moduledoc """
The available logging options for a firewall rule.
## Attributes
* `enable` (*type:* `boolean()`, *default:* `nil`) - This field denotes whether to enable logging for a particular firewall rule.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:enable => boolean()
}
field(:enable)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.FirewallLogConfig do
def decode(value, options) do
GoogleApi.Compute.V1.Model.FirewallLogConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.FirewallLogConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.93617 | 133 | 0.73934 |
f7026023063a76dbd9cffc791045a366bf80f97b | 1,719 | ex | Elixir | lib/private.ex | rockneurotiko/private | 7e5cbec79b079ee456fcbaf53ff91e42c37f2ee6 | [
"Apache-2.0"
] | null | null | null | lib/private.ex | rockneurotiko/private | 7e5cbec79b079ee456fcbaf53ff91e42c37f2ee6 | [
"Apache-2.0"
] | null | null | null | lib/private.ex | rockneurotiko/private | 7e5cbec79b079ee456fcbaf53ff91e42c37f2ee6 | [
"Apache-2.0"
] | null | null | null | defmodule Private do
@moduledoc File.read!("README.md")
defmacro __using__(_opts) do
quote do
require Private
import Private, only: [ private: 1, private: 2 ]
end
end
@doc """
Define private functions:
private do
def ...
defp ...
end
All functions in the block will be defined as public if Mix.env is `:test`,
private otherwise. `def` and `defp` are effectively the same in the block.
See the documentation for the `Private` module for more information.
"""
defmacro private(do: block) do
quote do
unquote(do_private(block, Mix.env))
end
end
@doc false && """
Define private functions:
private(env) do
def ...
defp ...
end
All functions in the block will be defined as public if env is `:test`,
private otherwise. This is only provided for my own testing.
"""
defmacro private(env, do: block) do
quote do
unquote(do_private(block, env))
end
end
defp do_private(block, _env = :test) do
make_defs_public(block)
end
defp do_private(block, _env) do
make_defs_private(block)
end
defp make_defs_private(block) do
Macro.traverse(block, nil, &make_private/2, &identity/2)
end
defp make_defs_public(block) do
Macro.traverse(block, nil, &make_public/2, &identity/2)
end
defp make_private({:def, meta, code}, acc) do
{ {:defp, meta, code}, acc }
end
defp make_private(ast, acc), do: identity(ast, acc)
defp make_public({:defp, meta, code}, acc) do
{ {:def, meta, code}, acc }
end
defp make_public(ast, acc), do: identity(ast, acc)
defp identity(ast, acc) do
{ ast, acc }
end
end
| 20.464286 | 78 | 0.628854 |
f702b373e89fddf47a5306f9e8d8c80aa47cc8ef | 1,768 | ex | Elixir | lib/caddr.ex | jamesandariese/ex-utils-caddr | dca3ccae973cf5dda8874af343cac2eb207841e8 | [
"Apache-2.0"
] | null | null | null | lib/caddr.ex | jamesandariese/ex-utils-caddr | dca3ccae973cf5dda8874af343cac2eb207841e8 | [
"Apache-2.0"
] | null | null | null | lib/caddr.ex | jamesandariese/ex-utils-caddr | dca3ccae973cf5dda8874af343cac2eb207841e8 | [
"Apache-2.0"
] | null | null | null | defmodule Caddr do
@moduledoc """
Documentation for Elixir Utils by Caddr.
"""
@doc """
Uniq -c
## Examples
iex> Caddr.uniqc([1,2,3,1,2,3,1,2,4])
%{1 => 3, 2 => 3, 3 => 2, 4 => 1}
"""
def uniqc(e) do
Enum.map(e, &({&1}))
|> reduce_groups({0}, [{&Enum.count/1, 0}])
|> Map.to_list
|> Enum.map(fn {{x}, {y}} -> {x, y} end)
|> Map.new
end
@doc """
Reduce by groups. Similar to SELECT x, y, SUM(z), SUM(w) FROM stuff GROUP BY (x,y);
This will always return tuples even if single items in a list are passed in.
## Examples
iex(1)> Caddr.reduce_groups([1, 2, 3, 1, 2, 3], {0}, [{&Enum.count/1, 0}])
%{{1} => {2}, {2} => {2}, {3} => {2}}
iex> Caddr.reduce_groups([{1,2,3,5}, {1,2,1,5}, {1,1,1,5}], {0, 1}, [{&Enum.sum/1, 2}, {&Enum.sum/1, 3}])
%{{1, 2} => {4, 10}, {1, 1} => {1, 5}}
"""
def reduce_groups(e, gb, aggs) do
e
|> Enum.map(&tuplize/1)
|> Enum.group_by(&(select_from_tuple(&1, gb)))
|> Map.to_list
|> Enum.map(fn {g, n} ->
{g, aggregate_tuple(n, aggs)}
end)
|> Map.new
end
@doc """
Aggregate tuple
## Examples
iex> Caddr.aggregate_tuple([{1,2,3}, {3,4,5}], [{&Enum.sum/1, 2}, {&Enum.count/1, 0}])
{8, 2}
"""
def aggregate_tuple(_, []), do: {}
def aggregate_tuple(e, [{agg, aggn}| r]) do
Tuple.insert_at(aggregate_tuple(e, r), 0,
e |> Enum.map(&(elem(&1, aggn))) |> agg.()
)
end
@doc """
## Examples
iex> Caddr.select_from_tuple({1,2,3,4,5}, {3,2})
{4, 3}
"""
def select_from_tuple(t, el) do
Tuple.to_list(el)
|> Enum.reduce({}, fn y,x -> Tuple.append(x, elem(tuplize(t), y)) end)
end
defp tuplize(t) when is_tuple(t), do: t
defp tuplize(t), do: {t}
end
| 23.891892 | 111 | 0.511878 |
f702c5316b049e52813340529e4f9877fe87990a | 8,107 | ex | Elixir | lib/litmus/type/string.ex | lob/litmus | e7ffccc2e8897e280d3a69942a2ad6cbe4bbb965 | [
"MIT"
] | 38 | 2018-08-21T22:07:25.000Z | 2021-09-23T09:27:57.000Z | lib/litmus/type/string.ex | lob/litmus | e7ffccc2e8897e280d3a69942a2ad6cbe4bbb965 | [
"MIT"
] | 7 | 2018-07-17T17:47:08.000Z | 2019-07-09T21:18:58.000Z | lib/litmus/type/string.ex | lob/litmus | e7ffccc2e8897e280d3a69942a2ad6cbe4bbb965 | [
"MIT"
] | 6 | 2019-05-02T22:28:33.000Z | 2021-02-13T02:10:27.000Z | defmodule Litmus.Type.String do
@moduledoc """
This type validates and converts values to strings It converts boolean and
number values to strings.
## Options
* `:default` - Setting `:default` will populate a field with the provided
value, assuming that it is not present already. If a field already has a
value present, it will not be altered.
* `:min_length` - Specifies the minimum number of characters allowed in the
string. Allowed values are non-negative integers.
* `:max_length` - Specifies the maximum number of characters allowed in the
string. Allowed values are non-negative integers.
* `:length` - Specifies the exact number of characters allowed in the
string. Allowed values are non-negative integers.
* `:regex` - Specifies a Regular expression that a string must match. Use
the `Litmus.Type.String.Regex` struct with the options:
* `:pattern` - A `Regex.t()` to match
* `:error_message` - An error message to use when the pattern does not match
* `:replace` - Replaces occurences of a pattern with a string. Use the
`Litmus.Type.String.Replace` struct with the options:
* `:pattern` - A `Regex.t()`, `String.t()`, or compiled pattern to match
* `:replacement` - A `String.t()` to replace
* `:global` - When `true`, all occurences of the pattern are replaced.
When `false`, only the first occurence is replaced. Defaults to `true`.
* `:required` - Setting `:required` to `true` will cause a validation error
when a field is not present or the value is `nil`. Allowed values for
required are `true` and `false`. The default is `false`.
* `:trim` - Removes additional whitespace at the front and end of a string.
Allowed values are `true` and `false`. The default is `false`.
## Examples
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> min_length: 3,
...> max_length: 10,
...> trim: true
...> },
...> "password" => %Litmus.Type.String{
...> length: 6,
...> regex: %Litmus.Type.String.Regex{
...> pattern: ~r/^[a-zA-Z0-9_]*$/,
...> error_message: "password must be alphanumeric"
...> }
...> }
...> }
iex> params = %{"username" => " user123 ", "password" => "root01"}
iex> Litmus.validate(params, schema)
{:ok, %{"username" => "user123", "password" => "root01"}}
iex> Litmus.validate(%{"password" => "ro!_@1"}, schema)
{:error, "password must be alphanumeric"}
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> replace: %Litmus.Type.String.Replace{
...> pattern: ~r/\_/,
...> replacement: ""
...> }
...> }
...> }
iex> Litmus.validate(%{"username" => "one_two_three"}, schema)
{:ok, %{"username" => "onetwothree"}}
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> default: "anonymous"
...> }
...> }
iex> Litmus.validate(%{}, schema)
{:ok, %{"username" => "anonymous"}}
"""
alias Litmus.{Default, Required}
alias Litmus.Type
defstruct [
:min_length,
:max_length,
:length,
default: Litmus.Type.Any.NoDefault,
regex: %Type.String.Regex{},
replace: %Type.String.Replace{},
trim: false,
required: false
]
@type t :: %__MODULE__{
default: any,
min_length: non_neg_integer | nil,
max_length: non_neg_integer | nil,
length: non_neg_integer | nil,
regex: Type.String.Regex.t(),
replace: Type.String.Replace.t(),
trim: boolean,
required: boolean
}
@spec validate_field(t, term, map) :: {:ok, map} | {:error, String.t()}
def validate_field(type, field, data) do
with {:ok, data} <- Required.validate(type, field, data),
{:ok, data} <- convert(type, field, data),
{:ok, data} <- trim(type, field, data),
{:ok, data} <- min_length_validate(type, field, data),
{:ok, data} <- max_length_validate(type, field, data),
{:ok, data} <- length_validate(type, field, data),
{:ok, data} <- regex_validate(type, field, data),
{:ok, data} <- replace(type, field, data) do
{:ok, data}
else
{:ok_not_present, data} -> Default.validate(type, field, data)
{:error, msg} -> {:error, msg}
end
end
@spec convert(t, term, map) :: {:ok, map} | {:error, String.t()}
defp convert(%__MODULE__{}, field, params) do
cond do
params[field] == nil ->
{:ok, params}
is_binary(params[field]) ->
{:ok, params}
is_number(params[field]) or is_boolean(params[field]) ->
{:ok, Map.update!(params, field, &to_string/1)}
true ->
{:error, "#{field} must be a string"}
end
end
@spec min_length_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp min_length_validate(%__MODULE__{min_length: min_length}, field, params)
when is_integer(min_length) and min_length > 0 do
if params[field] == nil or String.length(params[field]) < min_length do
{:error, "#{field} length must be greater than or equal to #{min_length} characters"}
else
{:ok, params}
end
end
defp min_length_validate(%__MODULE__{}, _field, params) do
{:ok, params}
end
@spec max_length_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp max_length_validate(%__MODULE__{max_length: nil}, _field, params) do
{:ok, params}
end
defp max_length_validate(%__MODULE__{max_length: max_length}, field, params)
when is_integer(max_length) and max_length >= 0 do
if Map.get(params, field) && String.length(params[field]) > max_length do
{:error, "#{field} length must be less than or equal to #{max_length} characters"}
else
{:ok, params}
end
end
@spec length_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp length_validate(%__MODULE__{length: nil}, _field, params) do
{:ok, params}
end
defp length_validate(%__MODULE__{length: 0}, field, params) do
if params[field] in [nil, ""] do
{:ok, params}
else
{:error, "#{field} length must be 0 characters"}
end
end
defp length_validate(%__MODULE__{length: len}, field, params) when is_integer(len) do
if params[field] == nil || String.length(params[field]) != len do
{:error, "#{field} length must be #{len} characters"}
else
{:ok, params}
end
end
@spec replace(t, term, map) :: {:ok, map}
defp replace(%__MODULE__{replace: %__MODULE__.Replace{pattern: nil}}, _field, params) do
{:ok, params}
end
defp replace(%__MODULE__{replace: replace}, field, params) do
new_string =
String.replace(params[field], replace.pattern, replace.replacement, global: replace.global)
{:ok, Map.put(params, field, new_string)}
end
@spec regex_validate(t, term, map) :: {:ok, map} | {:error, String.t()}
defp regex_validate(%__MODULE__{regex: %__MODULE__.Regex{pattern: nil}}, _field, params) do
{:ok, params}
end
defp regex_validate(%__MODULE__{regex: regex}, field, params) do
if params[field] == nil or !Regex.match?(regex.pattern, params[field]) do
error_message = regex.error_message || "#{field} must be in a valid format"
{:error, error_message}
else
{:ok, params}
end
end
@spec trim(t, term, map) :: {:ok, map}
defp trim(%__MODULE__{trim: true}, field, params) do
if Map.get(params, field) do
trimmed_value = String.trim(params[field])
trimmed_params = Map.put(params, field, trimmed_value)
{:ok, trimmed_params}
else
{:ok, params}
end
end
defp trim(%__MODULE__{trim: false}, _field, params) do
{:ok, params}
end
defimpl Litmus.Type do
alias Litmus.Type
@spec validate(Type.t(), term, map) :: {:ok, map} | {:error, String.t()}
def validate(type, field, data), do: Type.String.validate_field(type, field, data)
end
end
| 33.639004 | 97 | 0.605526 |
f7030562008233f3dcfa29a3d46903cd3e774935 | 1,529 | ex | Elixir | clients/vault/lib/google_api/vault/v1/model/remove_held_accounts_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/vault/lib/google_api/vault/v1/model/remove_held_accounts_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/vault/lib/google_api/vault/v1/model/remove_held_accounts_request.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest do
@moduledoc """
Remove a list of accounts from a hold.
## Attributes
- accountIds ([String.t]): Account ids to identify HeldAccounts to remove. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountIds => list(any())
}
field(:accountIds, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest do
def decode(value, options) do
GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.RemoveHeldAccountsRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.854167 | 97 | 0.746893 |
f7034424d62d793744af617d6144b4b485cdce43 | 2,430 | exs | Elixir | config/dev.exs | buoy49/zcash-explorer | 3774ef15a46ef13379d5a808f7cea198b76c589a | [
"Apache-2.0"
] | 5 | 2021-11-04T20:19:35.000Z | 2022-02-15T06:55:49.000Z | config/dev.exs | buoy49/zcash-explorer | 3774ef15a46ef13379d5a808f7cea198b76c589a | [
"Apache-2.0"
] | 5 | 2021-09-12T01:36:25.000Z | 2022-02-18T07:28:42.000Z | config/dev.exs | buoy49/zcash-explorer | 3774ef15a46ef13379d5a808f7cea198b76c589a | [
"Apache-2.0"
] | 8 | 2021-07-23T17:11:41.000Z | 2022-03-17T17:07:55.000Z | use Mix.Config
# Configure your database
config :zcash_explorer, ZcashExplorer.Repo,
username: "postgres",
password: "postgres",
database: "zcash_explorer_dev",
hostname: "localhost",
show_sensitive_data_on_connection_error: true,
pool_size: 10
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :zcash_explorer, ZcashExplorerWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch-stdin",
cd: Path.expand("../assets", __DIR__)
]
]
config :zcash_explorer, Zcashex,
zcashd_hostname: "localhost",
zcashd_port: "38232",
zcashd_username: "zcashrpc",
zcashd_password: "changeme",
vk_cpus: "0.2",
vk_mem: "2048M",
vk_runnner_image: "nighthawkapps/vkrunner"
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :zcash_explorer, ZcashExplorerWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/zcash_explorer_web/(live|views)/.*(ex)$",
~r"lib/zcash_explorer_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 28.255814 | 68 | 0.701646 |
f703447424f554b11ddc5d75cd2dab445e762ce1 | 2,965 | ex | Elixir | clients/you_tube/lib/google_api/you_tube/v3/model/playlist_list_response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/playlist_list_response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/playlist_list_response.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"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.YouTube.V3.Model.PlaylistListResponse do
@moduledoc """
## Attributes
- etag (String.t): Etag of this resource. Defaults to: `null`.
- eventId (String.t): Serialized EventId of the request which produced this response. Defaults to: `null`.
- items ([Playlist]): A list of playlists that match the request criteria. Defaults to: `null`.
- kind (String.t): Identifies what kind of resource this is. Value: the fixed string \"youtube#playlistListResponse\". Defaults to: `null`.
- nextPageToken (String.t): The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set. Defaults to: `null`.
- pageInfo (PageInfo): Defaults to: `null`.
- prevPageToken (String.t): The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set. Defaults to: `null`.
- tokenPagination (TokenPagination): Defaults to: `null`.
- visitorId (String.t): The visitorId identifies the visitor. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:etag => any(),
:eventId => any(),
:items => list(GoogleApi.YouTube.V3.Model.Playlist.t()),
:kind => any(),
:nextPageToken => any(),
:pageInfo => GoogleApi.YouTube.V3.Model.PageInfo.t(),
:prevPageToken => any(),
:tokenPagination => GoogleApi.YouTube.V3.Model.TokenPagination.t(),
:visitorId => any()
}
field(:etag)
field(:eventId)
field(:items, as: GoogleApi.YouTube.V3.Model.Playlist, type: :list)
field(:kind)
field(:nextPageToken)
field(:pageInfo, as: GoogleApi.YouTube.V3.Model.PageInfo)
field(:prevPageToken)
field(:tokenPagination, as: GoogleApi.YouTube.V3.Model.TokenPagination)
field(:visitorId)
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.PlaylistListResponse do
def decode(value, options) do
GoogleApi.YouTube.V3.Model.PlaylistListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.PlaylistListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.180556 | 166 | 0.71602 |
f703a4645a24a5c36bfae17d86cdd6c837c0401a | 11,969 | ex | Elixir | lib/game/session/process.ex | jgsmith/ex_venture | 546adaa8fe80d45a72fde6de8d8d6906902c12d4 | [
"MIT"
] | 2 | 2019-05-14T11:36:44.000Z | 2020-07-01T08:54:04.000Z | lib/game/session/process.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | null | null | null | lib/game/session/process.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | 1 | 2021-01-29T14:12:40.000Z | 2021-01-29T14:12:40.000Z | defmodule Game.Session.Process do
@moduledoc """
GenServer process module, client access is at `Game.Session`
Holds knowledge if the player is logged in, who they are, what they're save is.
"""
use GenServer, restart: :temporary
require Logger
alias Game.Account
alias Game.Character
alias Game.Command.Move
alias Game.Command.Pager
alias Game.Environment
alias Game.Format
alias Game.Format.Players, as: FormatPlayers
alias Game.Hint
alias Game.Player
alias Game.Session
alias Game.Session.Channels
alias Game.Session.Character, as: SessionCharacter
alias Game.Session.Commands
alias Game.Session.Effects
alias Game.Session.Help
alias Game.Session.GMCP
alias Game.Session.Regen
alias Game.Session.SessionStats
alias Game.Session.State
alias Game.Socket
alias Game.World.Master, as: WorldMaster
alias Metrics.PlayerInstrumenter
@save_period 15_000
@force_disconnect_period 5_000
@heartbeat_timeout 60_000
@timeout_check 5000
@timeout_seconds Application.get_env(:ex_venture, :game)[:timeout_seconds]
#
# GenServer callbacks
#
@doc false
def start_link(socket) do
GenServer.start_link(__MODULE__, socket)
end
def init([socket]) do
Logger.info("New session started #{inspect(self())}", type: :session)
state = clean_state(socket)
Session.Registry.register_connection(state.id)
send(self(), :start)
{:ok, state}
end
def init([socket, player_id]) do
send(self(), {:recover_session, player_id})
PlayerInstrumenter.session_recovered()
Logger.info("Session recovering (#{player_id}) - #{inspect(self())}", type: :session)
{:ok, clean_state(socket)}
end
defp clean_state(socket) do
now = Timex.now()
%State{
id: UUID.uuid4(),
socket: socket,
state: "login",
session_started_at: now,
last_recv: now,
idle: Help.init_idle(now),
mode: "commands",
target: nil,
is_targeting: MapSet.new(),
regen: %{is_regenerating: false, count: 0},
reply_to: nil,
commands: %{},
skills: %{},
stats: %SessionStats{},
is_afk: false
}
end
# On a disconnect unregister the PID and stop the server
def handle_cast(:disconnect, state = %{state: "login"}) do
Logger.info(fn -> "Disconnecting the session" end, type: :session)
{:stop, :normal, state}
end
def handle_cast(:disconnect, state = %{state: "create"}) do
Logger.info(fn -> "Disconnecting the session" end, type: :session)
{:stop, :normal, state}
end
def handle_cast(:disconnect, state = %{state: "active"}) do
Logger.info(fn -> "Disconnecting the session" end, type: :session)
%{save: save, session_started_at: session_started_at, stats: stats} = state
Session.Registry.unregister()
Session.Registry.player_offline(state.character)
Environment.leave(save.room_id, state.character, :signout)
Environment.unlink(save.room_id)
Account.save_session(
state.user,
state.character,
save,
session_started_at,
Timex.now(),
stats
)
{:stop, :normal, state}
end
def handle_cast(:disconnect, state) do
Logger.info(fn -> "Disconnecting the session - Fall through" end, type: :session)
{:stop, :normal, state}
end
def handle_cast({:disconnect, opts}, state) when is_list(opts) do
case Keyword.get(opts, :reason) do
"server shutdown" ->
state |> Socket.echo("The server will be shutting down shortly.")
_ ->
state |> Socket.echo("You are being signed out.\nGood bye.")
end
Task.start(fn ->
Process.sleep(@force_disconnect_period)
state |> Socket.disconnect()
end)
{:noreply, state}
end
# forward the echo the socket pid
def handle_cast({:echo, message}, state) do
state |> Socket.echo(message)
{:noreply, state}
end
# Handle logging in
def handle_cast({:recv, name}, state = %{state: "login"}) do
state = Session.Login.process(name, state)
{:noreply, Map.merge(state, %{last_recv: Timex.now()})}
end
# Handle displaying message after signing in
def handle_cast({:recv, _name}, state = %{state: "after_sign_in"}) do
state = Session.Login.after_sign_in(state, self())
send(self(), :regen)
{:noreply, Map.merge(state, %{last_recv: Timex.now()})}
end
# Handle creating an account
def handle_cast({:recv, name}, state = %{state: "create"}) do
state = Session.CreateAccount.process(name, state)
{:noreply, Map.merge(state, %{last_recv: Timex.now()})}
end
def handle_cast({:recv, message}, state = %{state: "active", mode: "commands"}) do
state |> Commands.process_command(message)
end
def handle_cast({:recv, message}, state = %{state: "active", mode: "paginate"}) do
{:noreply, Pager.paginate(state, command: message, lines: state.save.config.pager_size)}
end
def handle_cast({:recv, _message}, state = %{state: "active", mode: "continuing"}) do
{:noreply, state}
end
def handle_cast({:recv, ""}, state = %{state: "active", mode: "editor"}) do
case state.editor_module.editor(:complete, state) do
{:update, state} ->
state =
state
|> Map.put(:mode, "commands")
|> Map.delete(:editor_module)
state |> prompt()
{:noreply, Map.put(state, :mode, "commands")}
end
end
def handle_cast({:recv, line}, state = %{state: "active", mode: "editor"}) do
case state.editor_module.editor({:text, line}, state) do
{:update, state} ->
{:noreply, state}
end
end
def handle_cast({:recv_gmcp, module, data}, state) do
case GMCP.handle_gmcp(state, module, data) do
:ok ->
{:noreply, state}
{:update, state} ->
{:noreply, state}
end
end
def handle_cast({:teleport, room_id}, state) do
{:update, state} = Move.move_to(state, room_id, :teleport, :teleport)
state |> prompt()
{:noreply, state}
end
# Handle logging in from the web client
def handle_cast({:sign_in, character_id}, state = %{state: "login"}) do
state = Session.Login.sign_in(character_id, state)
{:noreply, state}
end
#
# Character callbacks
#
def handle_cast({:targeted, player}, state) do
{:noreply, SessionCharacter.targeted(state, player)}
end
def handle_cast({:apply_effects, effects, from, description}, state = %{state: "active"}) do
{:noreply, SessionCharacter.apply_effects(state, effects, from, description)}
end
def handle_cast({:effects_applied, effects, target}, state = %{state: "active"}) do
{:noreply, SessionCharacter.effects_applied(state, effects, target)}
end
def handle_cast({:notify, event}, state) do
{:noreply, SessionCharacter.notify(state, event)}
end
def handle_call(:info, _from, state) do
{:reply, Character.to_simple(state.character), state}
end
#
# Channels
#
def handle_info({:channel, {:joined, channel}}, state) do
{:noreply, Channels.joined(state, channel)}
end
def handle_info({:channel, {:left, channel}}, state) do
{:noreply, Channels.left(state, channel)}
end
def handle_info({:channel, {:broadcast, channel, message}}, state) do
{:noreply, Channels.broadcast(state, channel, message)}
end
def handle_info({:channel, {:tell, from, message}}, state) do
{:noreply, Channels.tell(state, from, message)}
end
#
# General callback
#
def handle_info(:start, state) do
case WorldMaster.is_world_online?() do
true ->
state |> Session.Login.start()
false ->
state |> Socket.echo("The world is not online yet. Please try again shortly.")
self() |> Process.send_after({:disconnect, :world_not_alive}, 750)
end
{:noreply, state}
end
def handle_info({:authorize, character}, state) do
state = Session.Login.sign_in(character.id, state)
{:noreply, state}
end
def handle_info({:disconnect, :world_not_alive}, state) do
state |> Socket.disconnect()
{:noreply, state}
end
def handle_info({:recover_session, user_id}, state) do
state = Session.Login.recover_session(user_id, state)
self() |> schedule_save()
self() |> schedule_inactive_check()
self() |> schedule_heartbeat()
{:noreply, state}
end
def handle_info(:regen, state = %{save: _save}) do
{:noreply, Regen.tick(state)}
end
def handle_info({:continue, command}, state) do
command |> Commands.run_command(state)
end
def handle_info(:save, state = %{state: "active"}) do
%{save: save, session_started_at: session_started_at} = state
state.character |> Account.save(save)
state.character |> Account.update_time_online(session_started_at, Timex.now())
self() |> schedule_save()
{:noreply, state}
end
def handle_info(:save, state) do
self() |> schedule_save()
{:noreply, state}
end
def handle_info(:inactive_check, state) do
{:noreply, check_for_inactive(state)}
end
def handle_info(:heartbeat, state) do
state |> GMCP.heartbeat()
state |> Socket.nop()
self() |> schedule_heartbeat()
{:noreply, state}
end
def handle_info({:continuous_effect, effect_id}, state) do
Logger.debug(
fn ->
"Processing effect (#{effect_id})"
end,
type: :player
)
state =
state
|> Effects.handle_continuous_effect(effect_id)
|> Regen.maybe_trigger_regen()
{:noreply, state}
end
def handle_info({:continuous_effect, :clear, effect_id}, state) do
Logger.debug(
fn ->
"Clearing effect (#{effect_id})"
end,
type: :player
)
state = Character.Effects.clear_continuous_effect(state, effect_id)
{:noreply, state}
end
def handle_info({:skill, :ready, skill}, state) do
state |> Socket.echo("#{Format.skill_name(skill)} is ready.")
state |> GMCP.skill_state(skill, active: true)
skills = Map.delete(state.skills, skill.id)
state = Map.put(state, :skills, skills)
{:noreply, state}
end
def handle_info({:resurrect, graveyard_id}, state) do
%{save: %{stats: stats}} = state
case stats.health_points do
health_points when health_points < 1 ->
stats = Map.put(stats, :health_points, 1)
save = %{state.save | stats: stats}
state =
state
|> Player.update_save(save)
|> Regen.maybe_trigger_regen()
{:update, state} = Move.move_to(state, graveyard_id, :death, :respawn)
state |> prompt()
{:noreply, state}
_ ->
{:noreply, state}
end
end
@doc """
Send the prompt to the user's socket
"""
def prompt(state) do
state |> GMCP.vitals()
state |> Socket.prompt(FormatPlayers.prompt(state.save))
state
end
# Schedule an inactive check
def schedule_inactive_check(pid) do
:erlang.send_after(@timeout_check, pid, :inactive_check)
end
# Schedule a save
def schedule_save(pid) do
:erlang.send_after(@save_period, pid, :save)
end
# Schedule a heartbeat
def schedule_heartbeat(pid) do
:erlang.send_after(@heartbeat_timeout, pid, :heartbeat)
end
# Check if the session is inactive, disconnect if it is
defp check_for_inactive(state = %{is_afk: true}) do
self() |> schedule_inactive_check()
state
end
defp check_for_inactive(state = %{last_recv: last_recv}) do
self() |> schedule_inactive_check()
{:ok, state} = state |> Help.maybe_display_hints()
case Timex.diff(Timex.now(), last_recv, :seconds) do
time when time > @timeout_seconds ->
Logger.info("Idle player #{inspect(self())} - setting afk", type: :session)
state = %{state | is_afk: true}
Session.Registry.update(%{state.character | save: state.save}, state)
message = "You seem to be idle, setting you to {command}AFK{/command}."
state |> Socket.echo(message)
Hint.gate(state, "afk.started")
state
_ ->
state
end
end
end
| 26.716518 | 94 | 0.651516 |
f703bbdb6cf64f5b574832bc4b5f1eedf6b7ce71 | 1,065 | ex | Elixir | lib/tembeza_web/channels/user_socket.ex | AdolfodelSel/Tembeza | 20c19d6cc090e7c128bf35f016b7a3843cfc0dad | [
"Apache-2.0"
] | null | null | null | lib/tembeza_web/channels/user_socket.ex | AdolfodelSel/Tembeza | 20c19d6cc090e7c128bf35f016b7a3843cfc0dad | [
"Apache-2.0"
] | 1 | 2021-05-11T18:22:04.000Z | 2021-05-11T18:22:04.000Z | lib/tembeza_web/channels/user_socket.ex | AdolfodelSel/Tembeza | 20c19d6cc090e7c128bf35f016b7a3843cfc0dad | [
"Apache-2.0"
] | null | null | null | defmodule TembezaWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", TembezaWeb.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# TembezaWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31.323529 | 83 | 0.696714 |
f703e67482aa768518cd4a082154dcf7eb3bf23f | 1,562 | ex | Elixir | test/support/data_case.ex | DianaOlympos/remote_test | e222d4e937789871baab3a7b4fd8428b714c1af4 | [
"MIT"
] | 1 | 2020-09-18T03:32:45.000Z | 2020-09-18T03:32:45.000Z | test/support/data_case.ex | DianaOlympos/remote_test | e222d4e937789871baab3a7b4fd8428b714c1af4 | [
"MIT"
] | null | null | null | test/support/data_case.ex | DianaOlympos/remote_test | e222d4e937789871baab3a7b4fd8428b714c1af4 | [
"MIT"
] | null | null | null | defmodule RemotePoints.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
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 RemotePoints.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias RemotePoints.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import RemotePoints.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(RemotePoints.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(RemotePoints.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 27.892857 | 77 | 0.694622 |
f70424c89288999e5d18016254f06285a06fcc49 | 1,592 | ex | Elixir | lib/double_agent/listening_post.ex | felix-starman/double_agent | f35cc6012eb7793167d0151c74c23c436ec4d811 | [
"MIT"
] | null | null | null | lib/double_agent/listening_post.ex | felix-starman/double_agent | f35cc6012eb7793167d0151c74c23c436ec4d811 | [
"MIT"
] | null | null | null | lib/double_agent/listening_post.ex | felix-starman/double_agent | f35cc6012eb7793167d0151c74c23c436ec4d811 | [
"MIT"
] | null | null | null | defmodule DoubleAgent.ListeningPost do
use GenServer
### CLIENT
def fetch(module, func, args_arity_or_atom) do
GenServer.call(__MODULE__, {:fetch, {module, func, args_arity_or_atom}})
end
def list do
GenServer.call(__MODULE__, :list)
end
def record({_mod, _function_name, _args} = mfa) do
GenServer.call(__MODULE__, {:record, mfa})
end
### SERVER & CALLBACKS
@impl GenServer
def init(state \\ []) do
{:ok, state}
end
@impl GenServer
def handle_call({:fetch, fetch_args}, _from, state) do
result =
case Enum.filter(state, &invoke_matches?(&1, fetch_args)) do
[] -> :error
invokes -> {:ok, invokes}
end
{:reply, result, state}
end
def handle_call(:list, _from, state) do
{:reply, state, state}
end
def handle_call({:record, mfa}, {pid, _tag} = _from, state) do
state = [{pid, mfa} | state]
{:reply, state, state}
end
@type invocation :: {pid(), mfargs()}
@type mfargs :: {module :: atom(), function_name :: atom(), args :: list()}
@type matcher :: {module(), atom(), :any}
@type mfargs_mfa_or_matcher :: mfargs() | mfa() | matcher()
@spec invoke_matches?(invocation(), mfargs_mfa_or_matcher()) :: boolean()
def invoke_matches?({_pid, {mod, func, _args}}, {mod, func, :any}), do: true
def invoke_matches?({_pid, {m, f, args}}, {m, f, arity}) when is_integer(arity),
do: length(args) == arity
def invoke_matches?({_pid, {mod, func, args}}, {mod, func, args}) when is_list(args), do: true
def invoke_matches?({_pid, _invoked_mfa}, _fetch_args), do: false
end
| 26.983051 | 96 | 0.635678 |
f7042aee33d55f42603a61593d0d4d4d9f911cfe | 37,568 | exs | Elixir | test/ecto/association_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | test/ecto/association_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | null | null | null | test/ecto/association_test.exs | dgvncsz0f/ecto | bae06fe650328cc1060c09fe889a2de9a10edb1b | [
"Apache-2.0"
] | 1 | 2018-09-21T16:05:29.000Z | 2018-09-21T16:05:29.000Z | defmodule Ecto.AssociationTest do
use ExUnit.Case, async: true
doctest Ecto.Association
import Ecto
import Ecto.Query, only: [from: 2, dynamic: 2]
alias __MODULE__.Author
alias __MODULE__.Comment
alias __MODULE__.CommentWithPrefix
alias __MODULE__.Permalink
alias __MODULE__.Post
alias __MODULE__.PostWithPrefix
alias __MODULE__.Summary
alias __MODULE__.Email
alias __MODULE__.Profile
alias __MODULE__.AuthorPermalink
defmodule Post do
use Ecto.Schema
schema "posts" do
field :title, :string
field :upvotes, :integer
has_many :comments, Comment
has_one :permalink, Permalink
has_many :permalinks, Permalink
belongs_to :author, Author, defaults: [title: "World!"]
belongs_to :summary, Summary
end
def awesome() do
dynamic([row], row.upvotes >= 1000)
end
end
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :text, :string
belongs_to :post, Post
has_one :permalink, Permalink
has_one :post_author, through: [:post, :author] # belongs -> belongs
has_one :post_permalink, through: [:post, :permalink] # belongs -> one
end
end
defmodule Permalink do
use Ecto.Schema
schema "permalinks" do
field :url, :string
field :special, :boolean
many_to_many :authors, Author, join_through: AuthorPermalink, defaults: [title: "m2m!"]
has_many :author_emails, through: [:authors, :emails]
end
def special() do
dynamic([row], row.special)
end
end
defmodule PostWithPrefix do
use Ecto.Schema
@schema_prefix "my_prefix"
schema "posts" do
belongs_to :author, Author
has_many :comments_with_prefix, CommentWithPrefix
end
end
defmodule CommentWithPrefix do
use Ecto.Schema
@schema_prefix "my_prefix"
schema "comments" do
belongs_to :posts_with_prefix, Post, foreign_key: :post_with_prefix_id
end
end
defmodule AuthorPermalink do
use Ecto.Schema
schema "authors_permalinks" do
field :author_id
field :permalink_id
field :deleted, :boolean
end
def active() do
dynamic([row], not(row.deleted))
end
end
defmodule Author do
use Ecto.Schema
schema "authors" do
field :title, :string
field :super_user, :boolean
has_many :posts, Post, on_replace: :delete
has_many :posts_comments, through: [:posts, :comments] # many -> many
has_many :posts_permalinks, through: [:posts, :permalink] # many -> one
has_many :emails, {"users_emails", Email}
has_many :awesome_posts, Post, where: {Post, :awesome, []}
has_one :profile, {"users_profiles", Profile},
defaults: [name: "default"], on_replace: :delete
many_to_many :permalinks, {"custom_permalinks", Permalink},
join_through: "authors_permalinks"
many_to_many :active_special_permalinks, Permalink,
join_through: AuthorPermalink,
join_through_where: {AuthorPermalink, :active, []},
where: {Permalink, :special, []}
many_to_many :special_permalinks, Permalink,
join_through: AuthorPermalink,
where: {Permalink, :special, []}
many_to_many :active_permalinks, Permalink,
join_through: AuthorPermalink,
join_through_where: {AuthorPermalink, :active, []}
has_many :posts_with_prefix, PostWithPrefix
has_many :comments_with_prefix, through: [:posts_with_prefix, :comments_with_prefix]
end
def super_users() do
dynamic([row], row.super_user)
end
end
defmodule Summary do
use Ecto.Schema
schema "summaries" do
has_one :post, Post, defaults: [title: "default"], on_replace: :nilify
has_one :awesome_post, Post, where: {Post, :awesome, []}
has_many :posts, Post, on_replace: :nilify
has_one :post_author, through: [:post, :author] # one -> belongs
has_many :post_comments, through: [:post, :comments] # one -> many
end
end
defmodule Email do
use Ecto.Schema
schema "emails" do
belongs_to :author, {"post_authors", Author}
belongs_to :super_user, Author, where: {Author, :super_users, []}, foreign_key: :author_id, define_field: false
end
end
defmodule Profile do
use Ecto.Schema
schema "profiles" do
field :name
belongs_to :author, Author
belongs_to :summary, Summary
end
end
test "has many" do
assoc = Post.__schema__(:association, :comments)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from p in Post, join: c in Comment, on: c.post_id == p.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from c in Comment, where: c.post_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2, 3])
end
test "has many with specified source" do
assoc = Author.__schema__(:association, :emails)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from a in Author, join: e in {"users_emails", Email}, on: e.author_id == a.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from e in {"users_emails", Email}, where: e.author_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from e in {"users_emails", Email}, where: e.author_id in ^[1, 2, 3])
end
test "has many custom assoc query" do
assoc = Post.__schema__(:association, :comments)
query = from c in Comment, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2, 3], limit: 5)
end
test "has many query-based assoc query" do
assoc = Author.__schema__(:association, :awesome_posts)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from a in Author, join: p in ^(from p in Post, where: p.upvotes >= 1000), on: p.author_id == a.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.author_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.author_id in ^[1, 2, 3])
end
test "has many query-based assoc with custom query" do
assoc = Author.__schema__(:association, :awesome_posts)
query = from p in Post, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.author_id in ^[1, 2, 3], limit: 5)
end
test "has one" do
assoc = Post.__schema__(:association, :permalink)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from p in Post, join: c in Permalink, on: c.post_id == p.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from c in Permalink, where: c.post_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1])) ==
inspect(from c in Permalink, where: c.post_id == ^1)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from c in Permalink, where: c.post_id in ^[1, 2, 3])
end
test "has one with specified source" do
assoc = Author.__schema__(:association, :profile)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from a in Author, join: p in {"users_profiles", Profile}, on: p.author_id == a.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from p in {"users_profiles", Profile}, where: p.author_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in {"users_profiles", Profile}, where: p.author_id in ^[1, 2, 3])
end
test "has one custom assoc query" do
assoc = Post.__schema__(:association, :permalink)
query = from c in Permalink, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from c in Permalink, where: c.post_id in ^[1, 2, 3], limit: 5)
end
test "has one query-based assoc query" do
assoc = Summary.__schema__(:association, :awesome_post)
assert inspect(Ecto.Association.Has.joins_query(assoc)) ==
inspect(from s in Summary, join: p in ^(from p in Post, where: p.upvotes >= 1000), on: p.summary_id == s.id)
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.summary_id in ^[])
assert inspect(Ecto.Association.Has.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.summary_id in ^[1, 2, 3])
end
test "has one query-based assoc with custom query" do
assoc = Summary.__schema__(:association, :awesome_post)
query = from p in Post, limit: 5
assert inspect(Ecto.Association.Has.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Post, where: p.upvotes >= 1000, where: p.summary_id in ^[1, 2, 3], limit: 5)
end
test "belongs to" do
assoc = Post.__schema__(:association, :author)
assert inspect(Ecto.Association.BelongsTo.joins_query(assoc)) ==
inspect(from p in Post, join: a in Author, on: a.id == p.author_id)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [])) ==
inspect(from a in Author, where: a.id in ^[])
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1])) ==
inspect(from a in Author, where: a.id == ^1)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in Author, where: a.id in ^[1, 2, 3])
end
test "belongs to with specified source" do
assoc = Email.__schema__(:association, :author)
assert inspect(Ecto.Association.BelongsTo.joins_query(assoc)) ==
inspect(from e in Email, join: a in {"post_authors", Author}, on: a.id == e.author_id)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [])) ==
inspect(from a in {"post_authors", Author}, where: a.id in ^[])
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1])) ==
inspect(from a in {"post_authors", Author}, where: a.id == ^1)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in {"post_authors", Author}, where: a.id in ^[1, 2, 3])
end
test "belongs to custom assoc query" do
assoc = Post.__schema__(:association, :author)
query = from a in Author, limit: 5
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from a in Author, where: a.id in ^[1, 2, 3], limit: 5)
end
test "belongs to query-based assoc query" do
assoc = Email.__schema__(:association, :super_user)
assert inspect(Ecto.Association.BelongsTo.joins_query(assoc)) ==
inspect(from e in Email, join: a in ^(from a in Author, where: a.super_user), on: a.id == e.author_id)
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [])) ==
inspect(from a in Author, where: a.super_user, where: a.id in ^[])
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in Author, where: a.super_user, where: a.id in ^[1, 2, 3])
end
test "belongs to query-based assoc with custom query" do
assoc = Email.__schema__(:association, :super_user)
query = from a in Author, limit: 5
assert inspect(Ecto.Association.BelongsTo.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from a in Author, where: a.super_user, where: a.id in ^[1, 2, 3], limit: 5)
end
test "many to many" do
assoc = Permalink.__schema__(:association, :authors)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from p in Permalink,
join: m in AuthorPermalink, on: m.permalink_id == p.id,
join: a in Author, on: m.author_id == a.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from a in Author,
join: p in Permalink, on: p.id in ^[],
join: m in AuthorPermalink, on: m.permalink_id == p.id,
where: m.author_id == a.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from a in Author,
join: p in Permalink, on: p.id in ^[1, 2, 3],
join: m in AuthorPermalink, on: m.permalink_id == p.id,
where: m.author_id == a.id)
end
test "many to many with specified source" do
assoc = Author.__schema__(:association, :permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in "authors_permalinks", on: m.author_id == a.id,
join: p in {"custom_permalinks", Permalink}, on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in {"custom_permalinks", Permalink},
join: a in Author, on: a.id in ^[],
join: m in "authors_permalinks", on: m.author_id == a.id,
where: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in {"custom_permalinks", Permalink},
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in "authors_permalinks", on: m.author_id == a.id,
where: m.permalink_id == p.id)
end
test "many to many custom assoc query" do
assoc = Permalink.__schema__(:association, :authors)
query = from a in Author, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from a in Author,
join: p in Permalink, on: p.id in ^[1, 2, 3],
join: m in AuthorPermalink, on: m.permalink_id == p.id,
where: m.author_id == a.id, limit: 5)
end
test "many to many query-based assoc and query based join_through query" do
assoc = Author.__schema__(:association, :active_special_permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
join: p in ^(from p in Permalink, where: p.special),
on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
end
test "many to many query-based assoc and query based join through with custom query" do
assoc = Author.__schema__(:association, :active_special_permalinks)
query = from p in Permalink, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author,
on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: p.special(),
where: m.permalink_id == p.id,
limit: 5)
end
test "many to many query-based assoc query" do
assoc = Author.__schema__(:association, :special_permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in AuthorPermalink,
on: m.author_id == a.id,
join: p in ^(from p in Permalink, where: p.special),
on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[],
join: m in AuthorPermalink,
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Permalink, where: p.special,
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in AuthorPermalink,
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
end
test "many to many query-based assoc query with custom query" do
assoc = Author.__schema__(:association, :special_permalinks)
query = from p in Permalink, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author,
on: a.id in ^[1, 2, 3],
join: m in AuthorPermalink,
on: m.author_id == a.id,
where: p.special(),
where: m.permalink_id == p.id,
limit: 5)
end
test "many to many query-based join through query" do
assoc = Author.__schema__(:association, :active_permalinks)
assert inspect(Ecto.Association.ManyToMany.joins_query(assoc)) ==
inspect(from a in Author,
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
join: p in Permalink,
on: m.permalink_id == p.id)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [])) ==
inspect(from p in Permalink,
join: a in Author, on: a.id in ^[],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author, on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id
)
end
test "many to many query-based join through with custom query" do
assoc = Author.__schema__(:association, :active_permalinks)
query = from p in Permalink, limit: 5
assert inspect(Ecto.Association.ManyToMany.assoc_query(assoc, query, [1, 2, 3])) ==
inspect(from p in Permalink,
join: a in Author,
on: a.id in ^[1, 2, 3],
join: m in ^(from m in AuthorPermalink, where: not(m.deleted)),
on: m.author_id == a.id,
where: m.permalink_id == p.id,
limit: 5)
end
test "has many through many to many" do
assoc = Author.__schema__(:association, :posts_comments)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from a in Author, join: p in assoc(a, :posts), join: c in assoc(p, :comments))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from c in Comment, join: p in Post, on: p.author_id in ^[1, 2, 3],
where: c.post_id == p.id, distinct: true)
end
test "has many through many to one" do
assoc = Author.__schema__(:association, :posts_permalinks)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from a in Author, join: p in assoc(a, :posts), join: c in assoc(p, :permalink))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from l in Permalink, join: p in Post, on: p.author_id in ^[1, 2, 3],
where: l.post_id == p.id, distinct: true)
end
test "has one through belongs to belongs" do
assoc = Comment.__schema__(:association, :post_author)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from c in Comment, join: p in assoc(c, :post), join: a in assoc(p, :author))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from a in Author, join: p in Post, on: p.id in ^[1, 2, 3],
where: a.id == p.author_id, distinct: true)
end
test "has one through belongs to one" do
assoc = Comment.__schema__(:association, :post_permalink)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from c in Comment, join: p in assoc(c, :post), join: l in assoc(p, :permalink))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from l in Permalink, join: p in Post, on: p.id in ^[1, 2, 3],
where: l.post_id == p.id, distinct: true)
end
test "has many through one to many" do
assoc = Summary.__schema__(:association, :post_comments)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from s in Summary, join: p in assoc(s, :post), join: c in assoc(p, :comments))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from c in Comment, join: p in Post, on: p.summary_id in ^[1, 2, 3],
where: c.post_id == p.id, distinct: true)
end
test "has one through one to belongs" do
assoc = Summary.__schema__(:association, :post_author)
assert inspect(Ecto.Association.HasThrough.joins_query(assoc)) ==
inspect(from s in Summary, join: p in assoc(s, :post), join: a in assoc(p, :author))
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1,2,3])) ==
inspect(from a in Author, join: p in Post, on: p.summary_id in ^[1, 2, 3],
where: a.id == p.author_id, distinct: true)
end
test "has many through custom assoc many to many query" do
assoc = Author.__schema__(:association, :posts_comments)
query = from c in Comment, where: c.text == "foo", limit: 5
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, query, [1,2,3])) ==
inspect(from c in Comment, join: p in Post,
on: p.author_id in ^[1, 2, 3],
where: c.post_id == p.id, where: c.text == "foo",
distinct: true, limit: 5)
query = from c in {"custom", Comment}, where: c.text == "foo", limit: 5
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, query, [1,2,3])) ==
inspect(from c in {"custom", Comment}, join: p in Post,
on: p.author_id in ^[1, 2, 3],
where: c.post_id == p.id, where: c.text == "foo",
distinct: true, limit: 5)
query = from c in Comment, join: p in assoc(c, :permalink), limit: 5
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, query, [1,2,3])) ==
inspect(from c in Comment, join: p0 in Permalink, on: p0.comment_id == c.id,
join: p1 in Post, on: p1.author_id in ^[1, 2, 3],
where: c.post_id == p1.id,
distinct: true, limit: 5)
end
test "has many through many to many and has many" do
assoc = Permalink.__schema__(:association, :author_emails)
assert inspect(Ecto.Association.HasThrough.assoc_query(assoc, nil, [1, 2, 3])) ==
inspect(from e in {"users_emails", Email},
join: p in Permalink, on: p.id in ^[1, 2, 3],
join: ap in AuthorPermalink, on: ap.permalink_id == p.id,
join: a in Author, on: ap.author_id == a.id,
where: e.author_id == a.id, distinct: true)
end
## Integration tests through Ecto
test "build/2" do
# has many
assert build_assoc(%Post{id: 1}, :comments) ==
%Comment{post_id: 1}
# has one
assert build_assoc(%Summary{id: 1}, :post) ==
%Post{summary_id: 1, title: "default"}
# belongs to
assert build_assoc(%Post{id: 1}, :author) ==
%Author{title: "World!"}
# many to many
assert build_assoc(%Permalink{id: 1}, :authors) ==
%Author{title: "m2m!"}
assert_raise ArgumentError, ~r"cannot build through association `:post_author`", fn ->
build_assoc(%Comment{}, :post_author)
end
end
test "build/2 with custom source" do
email = build_assoc(%Author{id: 1}, :emails)
assert email.__meta__.source == "users_emails"
profile = build_assoc(%Author{id: 1}, :profile)
assert profile.__meta__.source == "users_profiles"
profile = build_assoc(%Email{id: 1}, :author)
assert profile.__meta__.source == "post_authors"
permalink = build_assoc(%Author{id: 1}, :permalinks)
assert permalink.__meta__.source == "custom_permalinks"
end
test "build/3 with custom attributes" do
# has many
assert build_assoc(%Post{id: 1}, :comments, text: "Awesome!") ==
%Comment{post_id: 1, text: "Awesome!"}
assert build_assoc(%Post{id: 1}, :comments, %{text: "Awesome!"}) ==
%Comment{post_id: 1, text: "Awesome!"}
# has one
assert build_assoc(%Post{id: 1}, :comments, post_id: 2) ==
%Comment{post_id: 1}
# belongs to
assert build_assoc(%Post{id: 1}, :author, title: "Hello!") ==
%Author{title: "Hello!"}
# 2 belongs to
with author_post = build_assoc(%Author{id: 1}, :posts),
author_and_summary_post = build_assoc(%Summary{id: 2}, :posts, author_post) do
assert author_and_summary_post.author_id == 1
assert author_and_summary_post.summary_id == 2
end
# many to many
assert build_assoc(%Permalink{id: 1}, :authors, title: "Hello!") ==
%Author{title: "Hello!"}
# Overriding defaults
assert build_assoc(%Summary{id: 1}, :post, title: "Hello").title == "Hello"
# Should not allow overriding of __meta__
meta = %{__meta__: %{source: "posts"}}
comment = build_assoc(%Post{id: 1}, :comments, meta)
assert comment.__meta__.source == "comments"
end
test "assoc_loaded?/1 sets association to loaded/not loaded" do
refute Ecto.assoc_loaded?(%Post{}.comments)
assert Ecto.assoc_loaded?(%Post{comments: []}.comments)
assert Ecto.assoc_loaded?(%Post{comments: [%Comment{}]}.comments)
assert Ecto.assoc_loaded?(%Post{permalink: nil}.permalink)
end
test "assoc/2" do
assert inspect(assoc(%Post{id: 1}, :comments)) ==
inspect(from c in Comment, where: c.post_id == ^1)
assert inspect(assoc([%Post{id: 1}, %Post{id: 2}], :comments)) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2])
end
test "assoc/2 with prefixes" do
author = %Author{id: 1}
assert Ecto.assoc(author, :posts_with_prefix).from.prefix == "my_prefix"
assert Ecto.assoc(author, :comments_with_prefix).from.prefix == "my_prefix"
end
test "assoc/2 filters nil ids" do
assert inspect(assoc([%Post{id: 1}, %Post{id: 2}, %Post{}], :comments)) ==
inspect(from c in Comment, where: c.post_id in ^[1, 2])
end
test "assoc/2 fails on empty list" do
assert_raise ArgumentError, ~r"cannot retrieve association :whatever for empty list", fn ->
assoc([], :whatever)
end
end
test "assoc/2 fails on missing association" do
assert_raise ArgumentError, ~r"does not have association :whatever", fn ->
assoc([%Post{}], :whatever)
end
end
test "assoc/2 fails on heterogeneous collections" do
assert_raise ArgumentError, ~r"expected a homogeneous list containing the same struct", fn ->
assoc([%Post{}, %Comment{}], :comments)
end
end
## Preloader
alias Ecto.Repo.Preloader
test "preload: normalizer" do
assert Preloader.normalize(:foo, nil, []) ==
[foo: {nil, nil, []}]
assert Preloader.normalize([foo: :bar], nil, []) ==
[foo: {nil, nil, [bar: {nil, nil, []}]}]
assert Preloader.normalize([foo: [:bar, baz: :bat], this: :that], nil, []) ==
[this: {nil, nil, [that: {nil, nil, []}]},
foo: {nil, nil, [baz: {nil, nil, [bat: {nil, nil, []}]},
bar: {nil, nil, []}]}]
end
test "preload: normalize with query" do
query = from(p in Post, limit: 1)
assert Preloader.normalize([foo: query], nil, []) ==
[foo: {nil, query, []}]
assert Preloader.normalize([foo: {query, :bar}], nil, []) ==
[foo: {nil, query, [bar: {nil, nil, []}]}]
assert Preloader.normalize([foo: {query, bar: :baz}], nil, []) ==
[foo: {nil, query, [bar: {nil, nil, [baz: {nil, nil, []}]}]}]
end
test "preload: normalize with take" do
assert Preloader.normalize([:foo], [foo: :id], []) ==
[foo: {[:id], nil, []}]
assert Preloader.normalize([foo: :bar], [foo: :id], []) ==
[foo: {[:id], nil, [bar: {nil, nil, []}]}]
assert Preloader.normalize([foo: :bar], [foo: [:id, bar: :id]], []) ==
[foo: {[:id, bar: :id], nil, [bar: {[:id], nil, []}]}]
assert Preloader.normalize([foo: [bar: :baz]], [foo: [:id, bar: :id]], []) ==
[foo: {[:id, bar: :id], nil, [bar: {[:id], nil, [baz: {nil, nil, []}]}]}]
end
test "preload: raises on invalid preload" do
assert_raise ArgumentError, ~r"invalid preload `123` in `123`", fn ->
Preloader.normalize(123, nil, 123)
end
assert_raise ArgumentError, ~r"invalid preload `{:bar, :baz}` in", fn ->
Preloader.normalize([foo: {:bar, :baz}], nil, []) == [foo: [bar: []]]
end
end
defp expand(schema, preloads, take \\ nil) do
Preloader.expand(schema, Preloader.normalize(preloads, take, preloads), {%{}, %{}})
end
test "preload: expand" do
assert {%{comments: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []},
permalink: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []}},
%{}} =
expand(Post, [:comments, :permalink])
assert {%{post: {{:assoc, %Ecto.Association.BelongsTo{}, {0, :id}}, nil, nil, [author: {nil, nil, []}]}},
%{}} =
expand(Comment, [post: :author])
assert {%{post: {{:assoc, %Ecto.Association.BelongsTo{}, {0, :id}}, nil, nil,
[author: {nil, nil, []}, permalink: {nil, nil, []}]}},
%{}} =
expand(Comment, [:post, post: :author, post: :permalink])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: {nil, nil, [post: {nil, nil, []}]}]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [posts_comments: :post])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: _, comments: _]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [:posts, posts_comments: :post, posts: [comments: :post]])
end
test "preload: expand with queries" do
query = from(c in Comment, limit: 1)
assert {%{permalink: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []},
comments: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, ^query, []}},
%{}} =
expand(Post, [:permalink, comments: query])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: {nil, ^query, [post: {nil, nil, []}]}]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [posts_comments: {query, :post}])
end
test "preload: expand with take" do
assert {%{permalink: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, [:id], nil, []},
comments: {{:assoc, %Ecto.Association.Has{}, {0, :post_id}}, nil, nil, []}},
%{}} =
expand(Post, [:permalink, :comments], [permalink: :id])
assert {%{posts: {{:assoc, %Ecto.Association.Has{}, {0, :author_id}}, nil, nil,
[comments: {[:id], nil, [post: {nil, nil, []}]}]}},
%{posts_comments: {:through, %Ecto.Association.HasThrough{}, [:posts, :comments]}}} =
expand(Author, [posts_comments: :post], [posts_comments: :id])
end
test "preload: expand raises on duplicated entries" do
message = ~r"cannot preload `comments` as it has been supplied more than once with different queries"
assert_raise ArgumentError, message, fn ->
expand(Post, [comments: from(c in Comment, limit: 2),
comments: from(c in Comment, limit: 1)])
end
end
describe "after_compile_validation/2" do
defp after_compile_validation(assoc, name, opts) do
defmodule Sample do
use Ecto.Schema
schema "sample" do
opts = [cardinality: :one] ++ opts
throw assoc.after_compile_validation(assoc.struct(__MODULE__, name, opts),
%{__ENV__ | context_modules: [Ecto.AssociationTest]})
end
end
catch
result -> result
end
test "for has" do
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: __MODULE__) ==
:ok
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Unknown) ==
{:error, "associated schema Unknown does not exist"}
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Ecto.Changeset) ==
{:error, "associated module Ecto.Changeset is not an Ecto schema"}
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Post) ==
{:error, "associated schema Ecto.AssociationTest.Post does not have field `sample_id`"}
assert after_compile_validation(Ecto.Association.Has, :post,
cardinality: :one, queryable: Post, foreign_key: :author_id) ==
:ok
end
test "for belongs_to" do
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, queryable: __MODULE__) ==
:ok
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, queryable: Unknown) ==
{:error, "associated schema Unknown does not exist"}
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, queryable: Ecto.Changeset) ==
{:error, "associated module Ecto.Changeset is not an Ecto schema"}
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, references: :non_id, queryable: Post) ==
{:error, "associated schema Ecto.AssociationTest.Post does not have field `non_id`"}
assert after_compile_validation(Ecto.Association.BelongsTo, :sample,
foreign_key: :post_id, references: :id, queryable: Post) ==
:ok
end
test "for many_to_many" do
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: __MODULE__) ==
:ok
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: Unknown) ==
{:error, "associated schema Unknown does not exist"}
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: Ecto.Changeset) ==
{:error, "associated module Ecto.Changeset is not an Ecto schema"}
assert after_compile_validation(Ecto.Association.ManyToMany, :sample,
join_through: "join", queryable: Post) ==
:ok
end
end
end
| 41.328933 | 119 | 0.599127 |
f7043314a61147ef8af794ff83579d30b5e2ea15 | 1,989 | ex | Elixir | lib/git_hooks.ex | pojiro/elixir_git_hooks | 3b9448d535365e4b67b86b7f0ceb97d620c35b96 | [
"MIT"
] | null | null | null | lib/git_hooks.ex | pojiro/elixir_git_hooks | 3b9448d535365e4b67b86b7f0ceb97d620c35b96 | [
"MIT"
] | null | null | null | lib/git_hooks.ex | pojiro/elixir_git_hooks | 3b9448d535365e4b67b86b7f0ceb97d620c35b96 | [
"MIT"
] | null | null | null | defmodule GitHooks do
@moduledoc false
alias Mix.Tasks.GitHooks.Install
if Application.get_env(:git_hooks, :auto_install, true) do
Install.run(["--quiet"])
end
@typedoc """
A Git hook
"""
@type git_hook_type :: atom
@type git_hook_args :: list(String.t())
alias GitHooks.Tasks.Cmd
alias GitHooks.Tasks.File
alias GitHooks.Tasks.MFA
alias GitHooks.Tasks.Mix, as: MixTask
alias Mix.Tasks.GitHooks.Run
@type allowed_configs ::
{:file, String.t()}
| {:file, String.t(), Run.run_opts()}
| {:cmd, String.t()}
| {:cmd, String.t(), Run.run_opts()}
| {:mix_task, Mix.Task.task_name()}
| {:mix_task, Mix.Task.task_name(), [any]}
| mfa()
@spec new_task(allowed_configs(), git_hook_type(), git_hook_args()) ::
GitHooks.Task.t() | no_return
def new_task({:file, path}, git_hook_type, git_hook_args) do
File.new({:file, path, []}, git_hook_type, git_hook_args)
end
def new_task({:file, _path, _opts} = file_config, git_hook_type, git_hook_args) do
File.new(file_config, git_hook_type, git_hook_args)
end
def new_task({:cmd, command}, git_hook_type, git_hook_args) do
Cmd.new({:cmd, command, []}, git_hook_type, git_hook_args)
end
def new_task({:cmd, _command, _opts} = cmd, git_hook_type, git_hook_args) do
Cmd.new(cmd, git_hook_type, git_hook_args)
end
def new_task({:mix_task, task}, _git_hook_type, _git_hook_args) do
MixTask.new({:mix_task, task, []})
end
def new_task({:mix_task, _task, _args} = mix_task_config, _git_hook_type, _git_hook_args) do
MixTask.new(mix_task_config)
end
def new_task({_module, _function, _arity} = mfa, git_hook_type, git_hook_args) do
MFA.new(mfa, git_hook_type, git_hook_args)
end
def new_task(task_config, git_hook_type, _git_hook_args) do
raise """
Invalid task `#{inspect(task_config)}` for hook `#{inspect(git_hook_type)}`, please check documentation.
"""
end
end
| 29.686567 | 108 | 0.671694 |
f7043b1ab31b69778dc3edcfa268d03334acf384 | 2,491 | ex | Elixir | clients/service_control/lib/google_api/service_control/v1/model/authorization_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_control/lib/google_api/service_control/v1/model/authorization_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_control/lib/google_api/service_control/v1/model/authorization_info.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.ServiceControl.V1.Model.AuthorizationInfo do
@moduledoc """
Authorization information for the operation.
## Attributes
* `granted` (*type:* `boolean()`, *default:* `nil`) - Whether or not authorization for `resource` and `permission` was granted.
* `permission` (*type:* `String.t`, *default:* `nil`) - The required IAM permission.
* `resource` (*type:* `String.t`, *default:* `nil`) - The resource being accessed, as a REST-style or cloud resource string. For example: bigquery.googleapis.com/projects/PROJECTID/datasets/DATASETID or projects/PROJECTID/datasets/DATASETID
* `resourceAttributes` (*type:* `GoogleApi.ServiceControl.V1.Model.Resource.t`, *default:* `nil`) - Resource attributes used in IAM condition evaluation. This field contains resource attributes like resource type and resource name. To get the whole view of the attributes used in IAM condition evaluation, the user must also look into `AuditLog.request_metadata.request_attributes`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:granted => boolean() | nil,
:permission => String.t() | nil,
:resource => String.t() | nil,
:resourceAttributes => GoogleApi.ServiceControl.V1.Model.Resource.t() | nil
}
field(:granted)
field(:permission)
field(:resource)
field(:resourceAttributes, as: GoogleApi.ServiceControl.V1.Model.Resource)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceControl.V1.Model.AuthorizationInfo do
def decode(value, options) do
GoogleApi.ServiceControl.V1.Model.AuthorizationInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceControl.V1.Model.AuthorizationInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.482143 | 386 | 0.738659 |
f70444a2a3ef4376b680efed34e63fd551612bee | 2,423 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/async_batch_annotate_images_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vision/lib/google_api/vision/v1/model/async_batch_annotate_images_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vision/lib/google_api/vision/v1/model/async_batch_annotate_images_request.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.Vision.V1.Model.AsyncBatchAnnotateImagesRequest do
@moduledoc """
Request for async image annotation for a list of images.
## Attributes
* `outputConfig` (*type:* `GoogleApi.Vision.V1.Model.OutputConfig.t`, *default:* `nil`) - Required. The desired output location and metadata (e.g. format).
* `parent` (*type:* `String.t`, *default:* `nil`) - Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.
* `requests` (*type:* `list(GoogleApi.Vision.V1.Model.AnnotateImageRequest.t)`, *default:* `nil`) - Required. Individual image annotation requests for this batch.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:outputConfig => GoogleApi.Vision.V1.Model.OutputConfig.t() | nil,
:parent => String.t() | nil,
:requests => list(GoogleApi.Vision.V1.Model.AnnotateImageRequest.t()) | nil
}
field(:outputConfig, as: GoogleApi.Vision.V1.Model.OutputConfig)
field(:parent)
field(:requests, as: GoogleApi.Vision.V1.Model.AnnotateImageRequest, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest do
def decode(value, options) do
GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.AsyncBatchAnnotateImagesRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 45.716981 | 395 | 0.737928 |
f704590b6a5ce66b12731d325e93ae908b07ff90 | 362 | ex | Elixir | lib/twitchbot/application.ex | adigitalmonk/twitchbot | 2d2afd21032d8f94272d5cf2605f69451a24e08e | [
"MIT"
] | null | null | null | lib/twitchbot/application.ex | adigitalmonk/twitchbot | 2d2afd21032d8f94272d5cf2605f69451a24e08e | [
"MIT"
] | null | null | null | lib/twitchbot/application.ex | adigitalmonk/twitchbot | 2d2afd21032d8f94272d5cf2605f69451a24e08e | [
"MIT"
] | null | null | null | defmodule Twitchbot.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
children = [
Twitchbot.Client
]
opts = [strategy: :one_for_one, name: Twitchbot.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 21.294118 | 63 | 0.71547 |
f704c7e684d59a95e1ead5bd20f49667ee7ff226 | 1,486 | ex | Elixir | clients/vm_migration/lib/google_api/vm_migration/v1/model/add_group_migration_request.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vm_migration/lib/google_api/vm_migration/v1/model/add_group_migration_request.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vm_migration/lib/google_api/vm_migration/v1/model/add_group_migration_request.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest do
@moduledoc """
Request message for 'AddGroupMigration' request.
## Attributes
* `migratingVm` (*type:* `String.t`, *default:* `nil`) - The full path name of the MigratingVm to add.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:migratingVm => String.t() | nil
}
field(:migratingVm)
end
defimpl Poison.Decoder, for: GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest do
def decode(value, options) do
GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.VMMigration.V1.Model.AddGroupMigrationRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.617021 | 106 | 0.745626 |
f704d41e80148866f2e4295ddc2e221689526c76 | 1,824 | ex | Elixir | lib/espec/assertions/interface.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 807 | 2015-03-25T14:00:19.000Z | 2022-03-24T08:08:15.000Z | lib/espec/assertions/interface.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 254 | 2015-03-27T10:12:25.000Z | 2021-07-12T01:40:15.000Z | lib/espec/assertions/interface.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 85 | 2015-04-02T10:25:19.000Z | 2021-01-30T21:30:43.000Z | defmodule ESpec.Assertions.Interface do
@moduledoc """
Defines the assertion interface.
There are 3 functions that should be defined in the 'assertion' module:
- `match/2`;
- `success_message/4`;
- `error_message/4`.
"""
defmacro __using__(_opts) do
quote do
def assert(subject, data, positive \\ true) do
case match(subject, data) do
{false, result} when positive -> raise_error(subject, data, result, positive)
{true, result} when not positive -> raise_error(subject, data, result, positive)
{true, result} when positive -> success_message(subject, data, result, positive)
{false, result} when not positive -> success_message(subject, data, result, positive)
end
end
def assert(subject, data, positive, stacktrace) do
case match(subject, data) do
{false, result} when positive ->
raise_error(subject, data, result, positive, stacktrace)
{true, result} when not positive ->
raise_error(subject, data, result, positive, stacktrace)
{true, result} when positive ->
success_message(subject, data, result, positive)
{false, result} when not positive ->
success_message(subject, data, result, positive)
end
end
defp raise_error(subject, data, result, positive, stacktrace \\ nil) do
e = error_message(subject, data, result, positive)
{message, extra} =
case e do
{_, _} -> e
_ -> {e, nil}
end
raise ESpec.AssertionError,
subject: subject,
data: data,
result: result,
assertion: __MODULE__,
message: message,
extra: extra,
stacktrace: stacktrace
end
end
end
end
| 32 | 95 | 0.602522 |
f70508d41ac05dc4e6a910127b0f0e2cbecae0c8 | 1,681 | ex | Elixir | web/web.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | 48 | 2015-06-29T21:20:25.000Z | 2021-05-09T04:27:41.000Z | web/web.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | null | null | null | web/web.ex | houshuang/survey | 948acaf20840af82af1d9af3147acca94cb4fcf8 | [
"Apache-2.0"
] | 15 | 2015-06-29T21:13:57.000Z | 2021-07-27T10:02:40.000Z | defmodule Survey.Web do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use Survey.Web, :controller
use Survey.Web, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below.
"""
def model do
quote do
use Ecto.Model
end
end
def controller do
quote do
use Phoenix.Controller
# Alias the data repository and import query/model functions
alias Survey.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
# Import URL helpers from the router
import Survey.Router.Helpers
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
# Import URL helpers from the router
import Survey.Router.Helpers
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
# Alias the data repository and import query/model functions
alias Survey.Repo
import Ecto.Model
import Ecto.Query, only: [from: 2]
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 21.278481 | 88 | 0.66865 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 49