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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
73a8d41e444eb5d039697fdd91ffa47873393529 | 4,339 | ex | Elixir | clients/home_graph/lib/google_api/home_graph/v1/api/agent_users.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/home_graph/lib/google_api/home_graph/v1/api/agent_users.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/home_graph/lib/google_api/home_graph/v1/api/agent_users.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.HomeGraph.V1.Api.AgentUsers do
@moduledoc """
API calls for all endpoints tagged `AgentUsers`.
"""
alias GoogleApi.HomeGraph.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Unlinks the given third-party user from your smart home Action. All data related to this user will be deleted. For more details on how users link their accounts, see [fulfillment and authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-authentication). The third-party user's identity is passed in via the `agent_user_id` (see DeleteAgentUserRequest). This request must be authorized using service account credentials from your Actions console project.
## Parameters
* `connection` (*type:* `GoogleApi.HomeGraph.V1.Connection.t`) - Connection to server
* `agent_users_id` (*type:* `String.t`) - Part of `agentUserId`. Required. Third-party user ID.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:requestId` (*type:* `String.t`) - Request ID used for debugging.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.HomeGraph.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec homegraph_agent_users_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.HomeGraph.V1.Model.Empty.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def homegraph_agent_users_delete(connection, agent_users_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/agentUsers/{agentUsersId}", %{
"agentUsersId" => URI.encode(agent_users_id, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.HomeGraph.V1.Model.Empty{}])
end
end
| 48.211111 | 488 | 0.662595 |
73a8ea46d78c0aeb4c4dc72bd7a4b4d955b89107 | 939 | exs | Elixir | arena/phoenix_elixir/config/dev.exs | Jesterovskiy/api-fight | 2f23859eb7d0aa77e93bfe33aa9d05dd3c875854 | [
"MIT"
] | null | null | null | arena/phoenix_elixir/config/dev.exs | Jesterovskiy/api-fight | 2f23859eb7d0aa77e93bfe33aa9d05dd3c875854 | [
"MIT"
] | null | null | null | arena/phoenix_elixir/config/dev.exs | Jesterovskiy/api-fight | 2f23859eb7d0aa77e93bfe33aa9d05dd3c875854 | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :phoenix_elixir, PhoenixElixir.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: []
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :phoenix_elixir, PhoenixElixir.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "phoenix_elixir_dev",
hostname: "localhost",
pool_size: 10
| 29.34375 | 68 | 0.759318 |
73a901a993cada88555693bff55a54511184ba28 | 1,634 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/target_ssl_proxies_set_ssl_certificates_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/compute/lib/google_api/compute/v1/model/target_ssl_proxies_set_ssl_certificates_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/target_ssl_proxies_set_ssl_certificates_request.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Model.TargetSslProxiesSetSslCertificatesRequest do
@moduledoc """
## Attributes
* `sslCertificates` (*type:* `list(String.t)`, *default:* `nil`) - New set of URLs to SslCertificate resources to associate with this TargetSslProxy. Currently exactly one ssl certificate must be specified.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:sslCertificates => list(String.t())
}
field(:sslCertificates, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.TargetSslProxiesSetSslCertificatesRequest do
def decode(value, options) do
GoogleApi.Compute.V1.Model.TargetSslProxiesSetSslCertificatesRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetSslProxiesSetSslCertificatesRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.765957 | 210 | 0.76071 |
73a91ff819197a583020c115b9312b0b42aa5d4d | 1,170 | exs | Elixir | mix.exs | hrzndhrn/beam_file | 3a54bdfa9c458501e0c308e8ceba0ade661317b7 | [
"MIT"
] | 16 | 2020-05-28T20:41:45.000Z | 2022-03-29T13:51:14.000Z | mix.exs | hrzndhrn/beam_file | 3a54bdfa9c458501e0c308e8ceba0ade661317b7 | [
"MIT"
] | null | null | null | mix.exs | hrzndhrn/beam_file | 3a54bdfa9c458501e0c308e8ceba0ade661317b7 | [
"MIT"
] | 1 | 2021-08-23T02:51:47.000Z | 2021-08-23T02:51:47.000Z | defmodule BeamFile.MixProject do
use Mix.Project
def project do
[
app: :beam_file,
version: "0.1.0",
elixir: "~> 1.11",
description: "An interface to the BEAM file format and a decompiler",
start_permanent: Mix.env() == :prod,
deps: deps(),
elixirc_paths: elixirc_paths(),
dialyzer: dialyzer(),
package: package()
]
end
def application do
[
extra_applications: [:logger, :syntax_tools]
]
end
defp elixirc_paths do
if Mix.env() == :test do
["lib", "test/fixtures"]
else
["lib"]
end
end
defp dialyzer do
[
plt_add_apps: [:mix, :syntax_tools, :beam_lib],
plt_file: {:no_warn, "test/support/plts/dialyzer.plt"},
flags: [:unmatched_returns]
]
end
defp deps do
[
{:credo, "~> 1.5", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.1", only: :dev, runtime: false},
{:ex_doc, "~> 0.21", only: :dev, runtime: false}
]
end
defp package do
[
maintainers: ["Marcus Kruse"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/hrzndhrn/beam_file"}
]
end
end
| 20.892857 | 75 | 0.561538 |
73a93b4da8afbce7d373e650932acd249cdc710f | 406 | ex | Elixir | lib/dynamo/app.ex | stevedomin/dynamo | 3c28f27603a480d2755a89aba3a91e88df3469ce | [
"Apache-2.0"
] | 415 | 2015-01-04T15:59:47.000Z | 2022-02-02T21:12:46.000Z | lib/dynamo/app.ex | stevedomin/dynamo | 3c28f27603a480d2755a89aba3a91e88df3469ce | [
"Apache-2.0"
] | 9 | 2015-02-06T16:09:46.000Z | 2018-08-08T06:33:50.000Z | lib/dynamo/app.ex | stevedomin/dynamo | 3c28f27603a480d2755a89aba3a91e88df3469ce | [
"Apache-2.0"
] | 44 | 2015-02-01T15:49:50.000Z | 2021-11-29T09:08:37.000Z | defmodule Dynamo.App do
@moduledoc false
use Application.Behaviour
@doc """
Manually start the application when such is
required at compilation time.
"""
def start do
:application.ensure_all_started(:dynamo)
end
@doc """
Application module callback. Starts Dynamo's supervisor.
"""
def start(_type, _args) do
Dynamo.Supervisor.start_link(Dynamo.Supervisor, [])
end
end
| 19.333333 | 58 | 0.711823 |
73a95243007cebdf50b19fa53404d9ac263e12e2 | 2,990 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/router_status_bgp_peer_status.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/router_status_bgp_peer_status.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/router_status_bgp_peer_status.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Model.RouterStatusBgpPeerStatus do
@moduledoc """
## Attributes
- advertisedRoutes ([Route]): Routes that were advertised to the remote BGP peer Defaults to: `null`.
- ipAddress (String.t): IP address of the local BGP interface. Defaults to: `null`.
- linkedVpnTunnel (String.t): URL of the VPN tunnel that this BGP peer controls. Defaults to: `null`.
- name (String.t): Name of this BGP peer. Unique within the Routers resource. Defaults to: `null`.
- numLearnedRoutes (integer()): Number of routes learned from the remote BGP Peer. Defaults to: `null`.
- peerIpAddress (String.t): IP address of the remote BGP interface. Defaults to: `null`.
- state (String.t): BGP state as specified in RFC1771. Defaults to: `null`.
- status (String.t): Status of the BGP peer: {UP, DOWN} Defaults to: `null`.
- Enum - one of [DOWN, UNKNOWN, UP]
- uptime (String.t): Time this session has been up. Format: 14 years, 51 weeks, 6 days, 23 hours, 59 minutes, 59 seconds Defaults to: `null`.
- uptimeSeconds (String.t): Time this session has been up, in seconds. Format: 145 Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:advertisedRoutes => list(GoogleApi.Compute.V1.Model.Route.t()),
:ipAddress => any(),
:linkedVpnTunnel => any(),
:name => any(),
:numLearnedRoutes => any(),
:peerIpAddress => any(),
:state => any(),
:status => any(),
:uptime => any(),
:uptimeSeconds => any()
}
field(:advertisedRoutes, as: GoogleApi.Compute.V1.Model.Route, type: :list)
field(:ipAddress)
field(:linkedVpnTunnel)
field(:name)
field(:numLearnedRoutes)
field(:peerIpAddress)
field(:state)
field(:status)
field(:uptime)
field(:uptimeSeconds)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.RouterStatusBgpPeerStatus do
def decode(value, options) do
GoogleApi.Compute.V1.Model.RouterStatusBgpPeerStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.RouterStatusBgpPeerStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.342105 | 143 | 0.701338 |
73a95bcba799c1ec63d81583bcad9307533b4c4c | 602 | exs | Elixir | test/stripe/connect/country_spec_test.exs | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 555 | 2016-11-29T05:02:27.000Z | 2022-03-30T00:47:59.000Z | test/stripe/connect/country_spec_test.exs | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 532 | 2016-11-28T18:22:25.000Z | 2022-03-30T17:04:32.000Z | test/stripe/connect/country_spec_test.exs | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 296 | 2016-12-05T14:04:09.000Z | 2022-03-28T20:39:37.000Z | defmodule Stripe.CountrySpecTest do
use Stripe.StripeCase, async: true
describe "retrieve/2" do
test "retrieves a country spec" do
assert {:ok, %Stripe.CountrySpec{}} = Stripe.CountrySpec.retrieve("US")
assert_stripe_requested(:get, "/v1/country_specs/US")
end
end
describe "list/2" do
test "lists all country specs" do
assert {:ok, %Stripe.List{data: country_specs}} = Stripe.CountrySpec.list()
assert_stripe_requested(:get, "/v1/country_specs")
assert is_list(country_specs)
assert %Stripe.CountrySpec{} = hd(country_specs)
end
end
end
| 30.1 | 81 | 0.694352 |
73a97b45999d881bd165afb7f07852e2b68b9d84 | 250 | exs | Elixir | priv/repo/migrations/20151027005127_add_rf_codes_and_ifttt_to_switches.exs | nickgal/homemade_pi | a7b7df7d9214cb409ac5b133b52b70c13c98180c | [
"MIT"
] | null | null | null | priv/repo/migrations/20151027005127_add_rf_codes_and_ifttt_to_switches.exs | nickgal/homemade_pi | a7b7df7d9214cb409ac5b133b52b70c13c98180c | [
"MIT"
] | null | null | null | priv/repo/migrations/20151027005127_add_rf_codes_and_ifttt_to_switches.exs | nickgal/homemade_pi | a7b7df7d9214cb409ac5b133b52b70c13c98180c | [
"MIT"
] | null | null | null | defmodule HomemadePi.Repo.Migrations.AddRfCodesAndIftttToSwitches do
use Ecto.Migration
def change do
alter table(:switches) do
add :rf_code_on, :integer
add :rf_code_off, :integer
add :ifttt_id, :integer
end
end
end
| 20.833333 | 68 | 0.712 |
73a9b50af0b19133e24c619dcae539758aa2b51e | 1,382 | exs | Elixir | apps/aecore/test/aecore_keys_test.exs | boundedvariable/elixir-blockchain | f100a067a9e27e83658d8cf5012c70382100420f | [
"0BSD"
] | null | null | null | apps/aecore/test/aecore_keys_test.exs | boundedvariable/elixir-blockchain | f100a067a9e27e83658d8cf5012c70382100420f | [
"0BSD"
] | null | null | null | apps/aecore/test/aecore_keys_test.exs | boundedvariable/elixir-blockchain | f100a067a9e27e83658d8cf5012c70382100420f | [
"0BSD"
] | null | null | null | defmodule AecoreKeysTest do
@moduledoc """
Unit tests for the keys module
"""
use ExUnit.Case
doctest Aecore.Keys.Worker
alias Aecore.Keys.Worker, as: Keys
alias Aecore.Chain.Worker, as: Chain
setup do
Keys.start_link([])
[]
end
@tag :keys
test "test if a pubkey is loaded" do
assert {:ok, _key} = Keys.pubkey()
end
@tag :keys
test "sign transaction" do
{:ok, to_account} = Keys.pubkey()
assert {:ok, _} = Keys.sign_tx(to_account, 5,
Map.get(Chain.chain_state,
to_account, %{nonce: 0}).nonce + 1, 1,
Chain.top_block().header.height +
Application.get_env(:aecore, :tx_data)[:lock_time_coinbase] + 1)
end
@tag :keys
test "check pubkey length" do
pub_key_str = "041A470AE9831B61D9951A10D49663419CE087DF1BD7DB06578971767F032D389CB283AD4DD4E3532F3A5F3C89B006092CB6CECE39CAC3B06C2CB6DF8B51C73675"
pub_key_bin = pub_key_str |> Base.decode16!()
assert false == Keys.verify("", "", pub_key_bin)
end
@tag :keys
test "wrong key verification" do
pub_key_str = "041A470AE9831B61D9951A10D49663419CE087DF1BD7DB06578971767F032D389CB283AD4DD4E3"
pub_key_bin = pub_key_str |> Base.decode16!()
assert {:error, _} = Keys.verify("", "", pub_key_bin)
end
end
| 28.791667 | 150 | 0.632417 |
73a9cf0ba234333017ca5c7286c223b3fd50edc7 | 3,194 | ex | Elixir | priv/cabbage/apps/itest/lib/contract_event.ex | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | priv/cabbage/apps/itest/lib/contract_event.ex | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | priv/cabbage/apps/itest/lib/contract_event.ex | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019-2020 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule Itest.ContractEvent do
@moduledoc """
Listens for contract events passed in as `listen_to`.
"""
use WebSockex
alias Itest.Transactions.Encoding
@subscription_id 1
require Logger
#
# Client API
#
@doc """
Starts a GenServer that listens to events.
"""
@spec start_link(Keyword.t()) :: {:ok, pid()} | no_return()
def start_link(opts) do
name = Keyword.fetch!(opts, :name)
case Process.whereis(name) do
nil ->
websockex_start_link(name, opts)
pid ->
{:ok, pid}
end
end
#
# Server API
#
@doc false
@impl true
def handle_frame({:text, msg}, state) do
{:ok, decoded} = Jason.decode(msg)
case decoded["params"]["result"] do
nil ->
:ok
result ->
# parsing events
# per spec, they have 4 topics and data field
topics = result["topics"]
case Enum.count(topics) do
4 ->
abi = Keyword.fetch!(state, :abi)
event =
ABI.Event.find_and_decode(
abi,
Encoding.to_binary(Enum.at(topics, 0)),
Encoding.to_binary(Enum.at(topics, 1)),
Encoding.to_binary(Enum.at(topics, 2)),
Encoding.to_binary(Enum.at(topics, 3)),
Encoding.to_binary(result["data"])
)
Kernel.send(Keyword.fetch!(state, :subscribe), {:event, event})
_ = Logger.info("Event detected: #{inspect(event)}")
_ ->
:ok
end
end
{:ok, state}
end
defp websockex_start_link(name, opts) do
ws_url = Keyword.fetch!(opts, :ws_url)
abi_path = Keyword.fetch!(opts, :abi_path)
abi =
abi_path
|> File.read!()
|> Jason.decode!()
|> Map.fetch!("abi")
|> ABI.parse_specification(include_events?: true)
case WebSockex.start_link(ws_url, __MODULE__, [{:abi, abi} | opts], name: name) do
{:error, {:already_started, pid}} ->
{:ok, pid}
{:ok, pid} ->
spawn(fn -> listen(pid, opts) end)
{:ok, pid}
end
end
# >> {"id": 1, "method": "eth_subscribe", "params": ["logs",
# {"address": "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd",
# "topics": ["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"]}]}
defp listen(pid, opts) do
payload = %{
jsonrpc: "2.0",
id: @subscription_id,
method: "eth_subscribe",
params: [
"logs",
Keyword.fetch!(opts, :listen_to)
]
}
WebSockex.send_frame(pid, {:text, Jason.encode!(payload)})
end
end
| 25.552 | 87 | 0.596431 |
73a9f0bb299f59cb1e2563ff4f8313f38908329a | 1,456 | ex | Elixir | lib/philopets_web/router.ex | audacioustux/philopets | 9380416937d635d4b1f5e13fa6f8b52ee603addf | [
"blessing"
] | null | null | null | lib/philopets_web/router.ex | audacioustux/philopets | 9380416937d635d4b1f5e13fa6f8b52ee603addf | [
"blessing"
] | null | null | null | lib/philopets_web/router.ex | audacioustux/philopets | 9380416937d635d4b1f5e13fa6f8b52ee603addf | [
"blessing"
] | null | null | null | defmodule PhilopetsWeb.Router do
use PhilopetsWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {PhilopetsWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", PhilopetsWeb do
pipe_through :browser
get "/", PageController, :index
end
# Other scopes may use custom stacks.
# scope "/api", PhilopetsWeb do
# pipe_through :api
# end
# Enables LiveDashboard only for development
#
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
if Mix.env() in [:dev, :test] do
import Phoenix.LiveDashboard.Router
scope "/" do
pipe_through :browser
live_dashboard "/dashboard", metrics: PhilopetsWeb.Telemetry
end
end
# Enables the Swoosh mailbox preview in development.
#
# Note that preview only shows emails that were sent by the same
# node running the Phoenix server.
if Mix.env() == :dev do
scope "/dev" do
pipe_through :browser
forward "/mailbox", Plug.Swoosh.MailboxPreview
end
end
end
| 26 | 70 | 0.699176 |
73a9f6db1e69494459380c3e612c955bfbb5025f | 9,086 | ex | Elixir | farmbot_core/lib/farmbot_core/firmware_side_effects.ex | EarthEngineering/facetop_os | c82a7f1e8098d3a03dddbd2f2cb46cda7b88b6fb | [
"MIT"
] | 1 | 2021-04-22T10:18:50.000Z | 2021-04-22T10:18:50.000Z | farmbot_core/lib/farmbot_core/firmware_side_effects.ex | bluewaysw/farmbot_os | 3449864bc5c17a688ec2fe75e4a5cf247da57806 | [
"MIT"
] | null | null | null | farmbot_core/lib/farmbot_core/firmware_side_effects.ex | bluewaysw/farmbot_os | 3449864bc5c17a688ec2fe75e4a5cf247da57806 | [
"MIT"
] | null | null | null | defmodule FarmbotCore.FirmwareSideEffects do
@moduledoc "Handles firmware data and syncing it with BotState."
@behaviour FarmbotFirmware.SideEffects
require Logger
require FarmbotCore.Logger
alias FarmbotCore.{Asset, BotState, FirmwareEstopTimer, Leds}
@impl FarmbotFirmware.SideEffects
def handle_position(x: x, y: y, z: z) do
:ok = BotState.set_position(x, y, z)
end
@impl FarmbotFirmware.SideEffects
def handle_load(x: x, y: y, z: z) do
:ok = BotState.set_load(x, y, z)
end
@impl FarmbotFirmware.SideEffects
def handle_position_change([{axis, 0.0}]) do
FarmbotCore.Logger.warn(1, "#{axis}-axis stopped at home")
:noop
end
@impl FarmbotFirmware.SideEffects
def handle_position_change([{axis, _}]) do
FarmbotCore.Logger.warn(1, "#{axis}-axis stopped at maximum")
:noop
end
@impl FarmbotFirmware.SideEffects
def handle_axis_state([{axis, state}]) do
BotState.set_axis_state(axis, state)
end
@impl FarmbotFirmware.SideEffects
def handle_axis_timeout(axis) do
FarmbotCore.Logger.error(1, "#{axis}-axis timed out waiting for movement to complete")
:noop
end
@impl FarmbotFirmware.SideEffects
def handle_home_complete(_) do
:noop
end
@impl FarmbotFirmware.SideEffects
def handle_calibration_state([{_axis, _state}]) do
:noop
end
@impl FarmbotFirmware.SideEffects
def handle_encoders_scaled(x: x, y: y, z: z) do
:ok = BotState.set_encoders_scaled(x, y, z)
end
# this is a bug in the firmware code i think
def handle_encoders_scaled([]), do: :noop
@impl FarmbotFirmware.SideEffects
def handle_encoders_raw(x: x, y: y, z: z) do
:ok = BotState.set_encoders_raw(x, y, z)
end
@impl FarmbotFirmware.SideEffects
def handle_parameter_value([{param, value}]) do
:ok = BotState.set_firmware_config(param, value)
end
@impl FarmbotFirmware.SideEffects
def handle_parameter_calibration_value([{param, value}]) do
%{param => value}
|> Asset.update_firmware_config!()
|> Asset.Private.mark_dirty!(%{})
:ok
end
@impl FarmbotFirmware.SideEffects
def handle_pin_value(p: pin, v: value) do
:ok = BotState.set_pin_value(pin, value)
end
@impl FarmbotFirmware.SideEffects
def handle_software_version([version]) do
:ok = BotState.set_firmware_version(version)
case String.split(version, ".") do
# Ramps
[_, _, _, "R"] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("arduino")
[_, _, _, "R", _] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("arduino")
# Farmduino
[_, _, _, "F"] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("farmduino")
[_, _, _, "F", _] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("farmduino")
# Farmduino V14
[_, _, _, "G"] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("farmduino_k14")
[_, _, _, "G", _] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("farmduino_k14")
# Farmduino V15
[_, _, _, "H"] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("farmduino_k15")
[_, _, _, "H", _] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("farmduino_k15")
# Express V10
[_, _, _, "E"] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("express_k10")
[_, _, _, "E", _] ->
_ = Leds.red(:solid)
:ok = BotState.set_firmware_hardware("express_k10")
[_, _, _, "S"] ->
_ = Leds.red(:slow_blink)
:ok = BotState.set_firmware_version("none")
:ok = BotState.set_firmware_hardware("none")
[_, _, _, "S", _] ->
_ = Leds.red(:slow_blink)
:ok = BotState.set_firmware_version("none")
:ok = BotState.set_firmware_hardware("none")
end
end
@impl FarmbotFirmware.SideEffects
def handle_end_stops(_) do
:noop
end
@impl FarmbotFirmware.SideEffects
def handle_busy(busy) do
:ok = BotState.set_firmware_busy(busy)
end
@impl FarmbotFirmware.SideEffects
def handle_idle(idle) do
_ = FirmwareEstopTimer.cancel_timer()
:ok = BotState.set_firmware_unlocked()
:ok = BotState.set_firmware_idle(idle)
end
@impl FarmbotFirmware.SideEffects
def handle_emergency_lock() do
_ = FirmwareEstopTimer.start_timer()
_ = Leds.yellow(:slow_blink)
:ok = BotState.set_firmware_locked()
end
@impl FarmbotFirmware.SideEffects
def handle_emergency_unlock() do
_ = FirmwareEstopTimer.cancel_timer()
_ = Leds.yellow(:off)
:ok = BotState.set_firmware_unlocked()
end
@impl FarmbotFirmware.SideEffects
def handle_input_gcode({_, {:unknown, _}}) do
:ok
end
def handle_input_gcode({:unknown, _}) do
:ok
end
def handle_input_gcode(code) do
string_code = FarmbotFirmware.GCODE.encode(code)
should_log? = Asset.fbos_config().firmware_input_log
should_log? && FarmbotCore.Logger.debug(3, "Firmware input: " <> string_code)
end
@impl FarmbotFirmware.SideEffects
def handle_output_gcode(code) do
string_code = FarmbotFirmware.GCODE.encode(code)
should_log? = Asset.fbos_config().firmware_output_log
should_log? && FarmbotCore.Logger.debug(3, "Firmware output: " <> string_code)
end
@impl FarmbotFirmware.SideEffects
def handle_debug_message([message]) do
fbos_config = Asset.fbos_config()
should_log? = fbos_config.firmware_debug_log || fbos_config.arduino_debug_messages
should_log? && do_send_debug_message(message)
end
# TODO(Rick): 0 means OK, but firmware debug logs say "error 0". Why?
def do_send_debug_message("error 0"), do: do_send_debug_message("OK")
def do_send_debug_message(message) do
FarmbotCore.Logger.debug(3, "Firmware debug message: " <> message)
end
@impl FarmbotFirmware.SideEffects
def load_params do
conf = Asset.firmware_config()
known_params(conf)
end
def known_params(conf) do
Map.take(conf, [
:param_e_stop_on_mov_err,
:param_mov_nr_retry,
:movement_timeout_x,
:movement_timeout_y,
:movement_timeout_z,
:movement_keep_active_x,
:movement_keep_active_y,
:movement_keep_active_z,
:movement_home_at_boot_x,
:movement_home_at_boot_y,
:movement_home_at_boot_z,
:movement_invert_endpoints_x,
:movement_invert_endpoints_y,
:movement_invert_endpoints_z,
:movement_enable_endpoints_x,
:movement_enable_endpoints_y,
:movement_enable_endpoints_z,
:movement_invert_motor_x,
:movement_invert_motor_y,
:movement_invert_motor_z,
:movement_secondary_motor_x,
:movement_secondary_motor_invert_x,
:movement_steps_acc_dec_x,
:movement_steps_acc_dec_y,
:movement_steps_acc_dec_z,
:movement_stop_at_home_x,
:movement_stop_at_home_y,
:movement_stop_at_home_z,
:movement_home_up_x,
:movement_home_up_y,
:movement_home_up_z,
:movement_step_per_mm_x,
:movement_step_per_mm_y,
:movement_step_per_mm_z,
:movement_min_spd_x,
:movement_min_spd_y,
:movement_min_spd_z,
:movement_home_spd_x,
:movement_home_spd_y,
:movement_home_spd_z,
:movement_max_spd_x,
:movement_max_spd_y,
:movement_max_spd_z,
:movement_invert_2_endpoints_x,
:movement_invert_2_endpoints_y,
:movement_invert_2_endpoints_z,
:movement_motor_current_x,
:movement_motor_current_y,
:movement_motor_current_z,
:movement_stall_sensitivity_x,
:movement_stall_sensitivity_y,
:movement_stall_sensitivity_z,
:movement_microsteps_x,
:movement_microsteps_y,
:movement_microsteps_z,
:encoder_enabled_x,
:encoder_enabled_y,
:encoder_enabled_z,
:encoder_type_x,
:encoder_type_y,
:encoder_type_z,
:encoder_missed_steps_max_x,
:encoder_missed_steps_max_y,
:encoder_missed_steps_max_z,
:encoder_scaling_x,
:encoder_scaling_y,
:encoder_scaling_z,
:encoder_missed_steps_decay_x,
:encoder_missed_steps_decay_y,
:encoder_missed_steps_decay_z,
:encoder_use_for_pos_x,
:encoder_use_for_pos_y,
:encoder_use_for_pos_z,
:encoder_invert_x,
:encoder_invert_y,
:encoder_invert_z,
:movement_axis_nr_steps_x,
:movement_axis_nr_steps_y,
:movement_axis_nr_steps_z,
:movement_stop_at_max_x,
:movement_stop_at_max_y,
:movement_stop_at_max_z,
:pin_guard_1_pin_nr,
:pin_guard_1_time_out,
:pin_guard_1_active_state,
:pin_guard_2_pin_nr,
:pin_guard_2_time_out,
:pin_guard_2_active_state,
:pin_guard_3_pin_nr,
:pin_guard_3_time_out,
:pin_guard_3_active_state,
:pin_guard_4_pin_nr,
:pin_guard_4_time_out,
:pin_guard_4_active_state,
:pin_guard_5_pin_nr,
:pin_guard_5_time_out,
:pin_guard_5_active_state
])
end
end
| 28.936306 | 90 | 0.683029 |
73aa64ea93c92ed9cc4726cfcb597f9fa1f75764 | 1,099 | ex | Elixir | lib/ecto_mysql_extras/queries/table_size.ex | timothyvanderaerden/ecto_mysql_extras | 82a30f35e6869ca0040aee71de81841f0d8a3998 | [
"Apache-2.0"
] | null | null | null | lib/ecto_mysql_extras/queries/table_size.ex | timothyvanderaerden/ecto_mysql_extras | 82a30f35e6869ca0040aee71de81841f0d8a3998 | [
"Apache-2.0"
] | 9 | 2021-10-13T08:31:33.000Z | 2021-12-24T13:19:09.000Z | lib/ecto_mysql_extras/queries/table_size.ex | timothyvanderaerden/ecto_mysql_extras | 82a30f35e6869ca0040aee71de81841f0d8a3998 | [
"Apache-2.0"
] | 1 | 2021-12-29T16:52:00.000Z | 2021-12-29T16:52:00.000Z | defmodule EctoMySQLExtras.TableSize do
@moduledoc """
Query the total size of each table in the `Ecto.Repo` database.
Data is retrieved from the `information_schema` database and the `tables` table.
"""
@behaviour EctoMySQLExtras
def info do
%{
title: "Size of the tables (excluding indexes), descending by size",
order_by: [size: :DESC],
args: [:table],
columns: [
%{name: :schema, type: :string},
%{name: :name, type: :string},
%{name: :engine, type: :string},
%{name: :size, type: :bytes}
]
}
end
def query(args \\ []) do
where_table =
if args[:table] do
"TABLE_NAME = '#{args[:table]}'"
else
"TABLE_NAME IS NOT NULL"
end
"""
/* ECTO_MYSQL_EXTRAS: #{info().title} */
SELECT
TABLE_SCHEMA AS `schema`,
TABLE_NAME AS `name`,
ENGINE AS `engine`,
DATA_LENGTH AS `size`
FROM information_schema.tables
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_TYPE <> 'VIEW'
AND #{where_table}
ORDER BY `size` DESC;
"""
end
end
| 23.382979 | 82 | 0.582348 |
73aaaa0d54d3e151b80a851bfa184f5240f24535 | 2,451 | ex | Elixir | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/list_domain_mappings_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/list_domain_mappings_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/list_domain_mappings_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudRun.V1alpha1.Model.ListDomainMappingsResponse do
@moduledoc """
ListDomainMappingsResponse is a list of DomainMapping resources.
## Attributes
* `apiVersion` (*type:* `String.t`, *default:* `nil`) - The API version for this call such as "domains.cloudrun.com/v1alpha1".
* `items` (*type:* `list(GoogleApi.CloudRun.V1alpha1.Model.DomainMapping.t)`, *default:* `nil`) - List of DomainMappings.
* `kind` (*type:* `String.t`, *default:* `nil`) - The kind of this resource, in this case "DomainMappingList".
* `metadata` (*type:* `GoogleApi.CloudRun.V1alpha1.Model.ListMeta.t`, *default:* `nil`) - Metadata associated with this DomainMapping list.
* `unreachable` (*type:* `list(String.t)`, *default:* `nil`) - Locations that could not be reached.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:apiVersion => String.t(),
:items => list(GoogleApi.CloudRun.V1alpha1.Model.DomainMapping.t()),
:kind => String.t(),
:metadata => GoogleApi.CloudRun.V1alpha1.Model.ListMeta.t(),
:unreachable => list(String.t())
}
field(:apiVersion)
field(:items, as: GoogleApi.CloudRun.V1alpha1.Model.DomainMapping, type: :list)
field(:kind)
field(:metadata, as: GoogleApi.CloudRun.V1alpha1.Model.ListMeta)
field(:unreachable, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.ListDomainMappingsResponse do
def decode(value, options) do
GoogleApi.CloudRun.V1alpha1.Model.ListDomainMappingsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.ListDomainMappingsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.542373 | 143 | 0.722154 |
73aaab950d39f059d8d29c6e2ab719a1532a6319 | 1,185 | ex | Elixir | lib/pxblog/endpoint.ex | jgunnink/phoenix_blog | 15017cdbca1da3ef5338c819b265cca3997aebe5 | [
"MIT"
] | 1 | 2016-10-07T14:36:21.000Z | 2016-10-07T14:36:21.000Z | lib/pxblog/endpoint.ex | jgunnink/phoenix_blog | 15017cdbca1da3ef5338c819b265cca3997aebe5 | [
"MIT"
] | null | null | null | lib/pxblog/endpoint.ex | jgunnink/phoenix_blog | 15017cdbca1da3ef5338c819b265cca3997aebe5 | [
"MIT"
] | null | null | null | defmodule Pxblog.Endpoint do
use Phoenix.Endpoint, otp_app: :pxblog
socket "/socket", Pxblog.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :pxblog, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug Plug.Session,
store: :cookie,
key: "_pxblog_key",
signing_salt: "Ysh/+Hph"
plug Pxblog.Router
end
| 27.55814 | 69 | 0.711392 |
73ab021982dbe122065c7c96bc29e2b62df57e46 | 3,163 | exs | Elixir | test/wallaby/http_client_test.exs | alecho/wallaby | 90c34245e6340d49a2976f3f60b810c4435c19f8 | [
"MIT"
] | null | null | null | test/wallaby/http_client_test.exs | alecho/wallaby | 90c34245e6340d49a2976f3f60b810c4435c19f8 | [
"MIT"
] | null | null | null | test/wallaby/http_client_test.exs | alecho/wallaby | 90c34245e6340d49a2976f3f60b810c4435c19f8 | [
"MIT"
] | null | null | null | defmodule Wallaby.HTTPClientTest do
use Wallaby.HttpClientCase, async: true
alias Wallaby.HTTPClient, as: Client
describe "request/4" do
test "sends the request with the correct params and headers", %{bypass: bypass} do
Bypass.expect(bypass, fn conn ->
conn = parse_body(conn)
assert conn.method == "POST"
assert conn.request_path == "/my_url"
assert conn.body_params == %{"hello" => "world"}
assert get_req_header(conn, "accept") == ["application/json"]
assert get_req_header(conn, "content-type") == ["application/json"]
send_json_resp(conn, 200, ~s<{
"sessionId": "abc123",
"status": 0,
"value": null
}>)
end)
assert {:ok, _} = Client.request(:post, bypass_url(bypass, "/my_url"), %{hello: "world"})
end
test "with a 200 status response", %{bypass: bypass} do
Bypass.expect(bypass, fn conn ->
send_json_resp(conn, 200, ~s<{
"sessionId": "abc123",
"status": 0,
"value": null
}>)
end)
{:ok, response} = Client.request(:post, bypass_url(bypass, "/my_url"))
assert response == %{
"sessionId" => "abc123",
"status" => 0,
"value" => nil
}
end
test "with a 500 response and StaleElementReferenceException", %{bypass: bypass} do
Bypass.expect(bypass, fn conn ->
send_json_resp(conn, 500, ~s<{
"sessionId": "abc123",
"status": 10,
"value": {
"class": "org.openqa.selenium.StaleElementReferenceException"
}
}>)
end)
assert {:error, :stale_reference} = Client.request(:post, bypass_url(bypass, "/my_url"))
end
test "with an obscure status code", %{bypass: bypass} do
expected_message = "message from an obsure error"
Bypass.expect(bypass, fn conn ->
send_json_resp(conn, 200, ~s<{
"sessionId": "abc123",
"status": 13,
"value": {
"message": "#{expected_message}"
}
}>)
end)
assert {:error, ^expected_message} = Client.request(:post, bypass_url(bypass, "/my_url"))
end
test "includes the original HTTPoison error when there is one", %{bypass: bypass} do
expected_message =
"Wallaby had an internal issue with HTTPoison:\n%HTTPoison.Error{id: nil, reason: :econnrefused}"
Bypass.down(bypass)
assert_raise RuntimeError, expected_message, fn ->
Client.request(:post, bypass_url(bypass, "/my_url"))
end
end
test "raises a runtime error when the request returns a generic error", %{bypass: bypass} do
expected_message = "The session could not be created"
Bypass.expect(bypass, fn conn ->
send_json_resp(conn, 200, ~s<{
"sessionId": "abc123",
"value": {
"error": "An error",
"message": "#{expected_message}"
}
}>)
end)
assert_raise RuntimeError, expected_message, fn ->
Client.request(:post, bypass_url(bypass, "/my_url"))
end
end
end
end
| 30.413462 | 105 | 0.572242 |
73ab420b0447c286be5aa03d24d3b27bc1ede666 | 1,006 | ex | Elixir | lib/cafex/lock/consul/watch.ex | MishaConway/cafex | 32965b7e099bc45de24c229cc76f7b83b35ff7b4 | [
"Apache-2.0"
] | null | null | null | lib/cafex/lock/consul/watch.ex | MishaConway/cafex | 32965b7e099bc45de24c229cc76f7b83b35ff7b4 | [
"Apache-2.0"
] | null | null | null | lib/cafex/lock/consul/watch.ex | MishaConway/cafex | 32965b7e099bc45de24c229cc76f7b83b35ff7b4 | [
"Apache-2.0"
] | null | null | null | defmodule Cafex.Lock.Consul.Watch do
@moduledoc false
use GenServer
@wait "5m"
@retry_ms 30 * 1000
defmodule State do
@moduledoc false
defstruct [:path, :index, :from]
end
def start_link(path, index, from) do
GenServer.start_link __MODULE__, [path, index, from]
end
def init([path, index, from]) do
{:ok, %State{path: path, index: index, from: from}, 0}
end
def handle_info(:timeout, state) do
do_wait(state)
end
defp do_wait(%{path: path, index: index, from: from} = state) do
# blocking query
case Consul.Kv.fetch(path, wait: @wait, index: index) do
{:ok, %{body: _body} = response} ->
case Consul.Response.consul_index(response) do
^index ->
{:noreply, state, 0}
_ ->
send from, :lock_changed
{:stop, :normal, state}
end
{:error, %{reason: :timeout}} ->
{:noreply, state, 0}
{:error, _} ->
{:noreply, state, @retry_ms}
end
end
end
| 23.395349 | 66 | 0.583499 |
73ab705184b8322e16491e381d45572b951cf742 | 2,011 | ex | Elixir | lib/authable/authentications/token.ex | liberumed/authable | 6db9951aa07000b358f16ffe413a13aa9aa89192 | [
"Unlicense"
] | null | null | null | lib/authable/authentications/token.ex | liberumed/authable | 6db9951aa07000b358f16ffe413a13aa9aa89192 | [
"Unlicense"
] | null | null | null | lib/authable/authentications/token.ex | liberumed/authable | 6db9951aa07000b358f16ffe413a13aa9aa89192 | [
"Unlicense"
] | 1 | 2021-01-12T00:55:56.000Z | 2021-01-12T00:55:56.000Z | defmodule Authable.Authentication.Token do
@moduledoc """
Base token authentication helper, implements Authable.Authentication
behaviour. Differently from Bearer or Session, this module is a generic
helper module. It enables to match with any token type from
'token store(Authable.Token)'.
"""
use Authable.RepoBase
import Authable.Config, only: [repo: 0]
alias Authable.Authentication.Error, as: AuthenticationError
@behaviour Authable.Authentication
@doc """
Authenticates resource-owner using given token name and value pairs.
It matches resource owner with given token name and value.
If any resource owner matched given credentials,
it returns `Authable.Model.User` struct, otherwise
`{:error, Map, :http_status_code}`.
## Examples
# Suppose we store a confirmation_token at 'token store'
# with token value "ct123456789"
# If we pass the token value to the function,
# it will return resource-owner.
Authable.Authentication.Token.authenticate({"confirmation_token",
"ct123456789"}, ["read", "write"])
"""
def authenticate({token_name, token_value}, required_scopes) do
token_check(
repo().get_by(@token_store, value: token_value, name: token_name),
required_scopes
)
end
defp token_check(nil, _),
do: AuthenticationError.invalid_token("Token not found.")
defp token_check(token, required_scopes) do
if @token_store.is_expired?(token) do
AuthenticationError.invalid_token("Token expired.")
else
scopes = Authable.Utils.String.comma_split(token.details["scope"])
if Authable.Utils.List.subset?(scopes, required_scopes) do
resource_owner_check(repo().get(@resource_owner, token.user_id))
else
AuthenticationError.insufficient_scope(required_scopes)
end
end
end
defp resource_owner_check(nil),
do: AuthenticationError.invalid_token("User not found.")
defp resource_owner_check(resource_owner), do: {:ok, resource_owner}
end
| 32.967213 | 73 | 0.727996 |
73abe72391975e935d742f6dcdbe0d1b583e1ef7 | 4,073 | exs | Elixir | test/flow/window/global_test.exs | SirWerto/flow | 2506fcdb87297f516f7da467c9b2898e4f45e80f | [
"Apache-2.0"
] | 398 | 2020-01-21T16:28:14.000Z | 2022-03-29T11:51:21.000Z | test/flow/window/global_test.exs | SirWerto/flow | 2506fcdb87297f516f7da467c9b2898e4f45e80f | [
"Apache-2.0"
] | 21 | 2020-02-03T11:00:38.000Z | 2022-03-30T17:15:18.000Z | test/flow/window/global_test.exs | SirWerto/flow | 2506fcdb87297f516f7da467c9b2898e4f45e80f | [
"Apache-2.0"
] | 24 | 2020-03-08T17:35:32.000Z | 2022-03-22T17:54:20.000Z | defmodule Flow.Window.GlobalTest do
use ExUnit.Case, async: true
test "trigger keep with large demand" do
partition_opts = [window: Flow.Window.global() |> Flow.Window.trigger_every(10), stages: 1]
assert Flow.from_enumerable(1..100)
|> Flow.partition(partition_opts)
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.emit(:state)
|> Enum.to_list() == [55, 210, 465, 820, 1275, 1830, 2485, 3240, 4095, 5050, 5050]
end
test "trigger keep with small demand" do
partition_opts = [
window: Flow.Window.global() |> Flow.Window.trigger_every(10),
stages: 1,
max_demand: 5
]
assert Flow.from_enumerable(1..100)
|> Flow.partition(partition_opts)
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.emit(:state)
|> Enum.to_list() == [55, 210, 465, 820, 1275, 1830, 2485, 3240, 4095, 5050, 5050]
end
test "trigger discard with large demand" do
partition_opts = [
window: Flow.Window.global() |> Flow.Window.trigger_every(10),
stages: 1
]
assert Flow.from_enumerable(1..100)
|> Flow.partition(partition_opts)
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.on_trigger(&{[&1], 0})
|> Enum.to_list() == [55, 155, 255, 355, 455, 555, 655, 755, 855, 955, 0]
end
test "trigger discard with small demand" do
partition_opts = [
window: Flow.Window.global() |> Flow.Window.trigger_every(10),
stages: 1,
max_demand: 5
]
assert Flow.from_enumerable(1..100)
|> Flow.partition(partition_opts)
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.on_trigger(&{[&1], 0})
|> Enum.to_list() == [55, 155, 255, 355, 455, 555, 655, 755, 855, 955, 0]
end
test "trigger ordering" do
window =
Flow.Window.trigger(Flow.Window.global(), fn -> true end, fn events, true ->
{:cont, Enum.all?(events, &(rem(&1, 2) == 0))}
end)
assert Flow.from_enumerable(1..10)
|> Flow.partition(window: window, stages: 1)
|> Flow.map(&(&1 + 1))
|> Flow.map(&(&1 * 2))
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.emit(:state)
|> Enum.sort() == [130]
end
test "trigger names" do
partition_opts = [
window: Flow.Window.global() |> Flow.Window.trigger_every(10),
stages: 1
]
events =
Flow.from_enumerable(1..100)
|> Flow.partition(partition_opts)
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.on_trigger(fn state, _, {:global, :global, trigger} -> {[{trigger, state}], 0} end)
|> Enum.sort()
assert events == [
{:done, 0},
{{:every, 10}, 55},
{{:every, 10}, 155},
{{:every, 10}, 255},
{{:every, 10}, 355},
{{:every, 10}, 455},
{{:every, 10}, 555},
{{:every, 10}, 655},
{{:every, 10}, 755},
{{:every, 10}, 855},
{{:every, 10}, 955}
]
end
test "trigger based on intervals" do
partition_opts = [
window: Flow.Window.global() |> Flow.Window.trigger_periodically(100, :millisecond),
stages: 1,
max_demand: 10
]
assert Flow.from_enumerable(Stream.concat(1..10, Stream.timer(60_000)), max_demand: 5)
|> Flow.partition(partition_opts)
|> Flow.reduce(fn -> 0 end, &(&1 + &2))
|> Flow.on_trigger(&{[&1 * 2], &1})
|> Enum.take(1) == [110]
end
test "trigger based on timers" do
reduce_fun = fn ->
Process.send_after(self(), {:trigger, :sample}, 200)
0
end
assert Stream.concat(1..10, Stream.timer(60_000))
|> Flow.from_enumerable(max_demand: 5, stages: 2)
|> Flow.partition(stages: 1, max_demand: 10)
|> Flow.reduce(reduce_fun, &(&1 + &2))
|> Flow.on_trigger(&{[{&1 * 2, &2, &3}], reduce_fun.()})
|> Enum.take(1) == [{110, {0, 1}, {:global, :global, :sample}}]
end
end
| 32.325397 | 97 | 0.527866 |
73abe786bdffe29ce2def3589225db9f03081f04 | 101 | exs | Elixir | config/prod.exs | itsemilano/orbex | 301dfaad1369acfd68055f1868d9a1dcd7e51e16 | [
"Apache-2.0"
] | null | null | null | config/prod.exs | itsemilano/orbex | 301dfaad1369acfd68055f1868d9a1dcd7e51e16 | [
"Apache-2.0"
] | null | null | null | config/prod.exs | itsemilano/orbex | 301dfaad1369acfd68055f1868d9a1dcd7e51e16 | [
"Apache-2.0"
] | null | null | null | import Config
config :naive,
binance_client: Binance
config :streamer,
binance_client: Binance
| 12.625 | 25 | 0.782178 |
73ac038ed8aaf45fe311e4a7dd0b11717a0c586c | 243 | exs | Elixir | test/plug_helper.exs | brightroll/phoenix | b93022086322bcc1d797214a28e0c9710f537c22 | [
"MIT"
] | null | null | null | test/plug_helper.exs | brightroll/phoenix | b93022086322bcc1d797214a28e0c9710f537c22 | [
"MIT"
] | null | null | null | test/plug_helper.exs | brightroll/phoenix | b93022086322bcc1d797214a28e0c9710f537c22 | [
"MIT"
] | null | null | null | defmodule PlugHelper do
defmacro __using__(_opts) do
quote do
use Plug.Test
def simulate_request(router, http_method, path) do
conn = conn(http_method, path)
router.call(conn, [])
end
end
end
end
| 18.692308 | 56 | 0.633745 |
73ac3c9f6a9369dc5a52483958106ff05b35e331 | 3,216 | exs | Elixir | test/telemetria_test.exs | am-kantox/telemetria | 1198bd913c89ead397abd2e06a37cb05f557c188 | [
"MIT"
] | 15 | 2020-05-21T21:34:59.000Z | 2022-03-04T04:31:02.000Z | test/telemetria_test.exs | am-kantox/telemetria | 1198bd913c89ead397abd2e06a37cb05f557c188 | [
"MIT"
] | 16 | 2020-05-18T16:09:29.000Z | 2022-02-04T10:56:46.000Z | test/telemetria_test.exs | am-kantox/telemetria | 1198bd913c89ead397abd2e06a37cb05f557c188 | [
"MIT"
] | 4 | 2020-05-26T16:42:54.000Z | 2022-02-04T10:54:05.000Z | defmodule Telemetria.Test do
use ExUnit.Case
import ExUnit.CaptureLog
doctest Telemetria
alias Test.Telemetria.Example
setup_all do
Application.put_env(:logger, :console, [], persistent: true)
Application.put_env(:telemetria, :smart_log, false)
end
test "attaches telemetry events to module functions and spits out logs" do
log =
capture_log(fn ->
Example.sum_with_doubled(1, 3)
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :twice]"
assert log =~ "[:test, :telemetria, :example, :sum_with_doubled]"
assert log =~ "result: 7"
end
test "attaches telemetry events to anonymous local functions and spits out logs" do
log =
capture_log(fn ->
Example.half(42)
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :half]"
assert log =~ "args: [a: 42]"
assert log =~ "result: 21"
end
test "attaches telemetry events named and spits out logs" do
log =
capture_log(fn ->
Example.half_named(4)
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :half_named, :foo]"
assert log =~ "result: #Function<"
end
test "attaches telemetry events to random ast and spits out logs" do
log =
capture_log(fn ->
Example.tmed()
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :tmed]"
assert log =~ "result: 42"
end
test "attaches telemetry events to random ast with do-end syntax and spits out logs" do
log =
capture_log(fn ->
Example.tmed_do()
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :tmed_do]"
assert log =~ "result: 42"
end
test "attaches telemetry events to guarded function and spits out logs" do
log =
capture_log(fn ->
assert 84 == Example.guarded(42)
assert :ok == Example.guarded(:ok)
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :guarded]"
assert log =~ "result: 84"
assert log =~ "result: :ok"
end
test "@telemetry true" do
log =
capture_log(fn ->
assert 42 == Example.annotated_1(42)
Process.sleep(100)
end)
assert log =~ "[:test, :telemetria, :example, :annotated_1]"
assert log =~ "[:test, :telemetria, :example, :annotated_2]"
assert log =~ "result: 42"
end
test "@telemetry level:" do
log =
capture_log(fn ->
assert 42 == Example.annotated_1(42)
Process.sleep(100)
end)
assert log =~ "event: [:test, :telemetria, :example, :annotated_1]"
assert log =~ "event: [:test, :telemetria, :example, :annotated_2]"
assert log =~ "result: 42"
end
test "@telemetry deep pattern match" do
log =
capture_log(fn ->
assert {:ok, :bar} = Example.check_s(%Test.Telemetria.S{foo: :not_42})
assert {:error, _} = Example.check_s(%Test.Telemetria.S{foo: :not_42, bar: :not_baz})
assert {:ok, :foo} == Example.check_s(%Test.Telemetria.S{})
Process.sleep(100)
end)
assert log =~ "event: [:test, :telemetria, :example, :check_s]"
end
end
| 27.254237 | 93 | 0.611007 |
73ac5648ade73e39fd16b7f32ae6c9b32064fe43 | 2,152 | exs | Elixir | apps/day9/test/day9_test.exs | at7heb/aoc2021 | ab31881b40354e28da0feaf5309c9648def85e77 | [
"MIT"
] | null | null | null | apps/day9/test/day9_test.exs | at7heb/aoc2021 | ab31881b40354e28da0feaf5309c9648def85e77 | [
"MIT"
] | null | null | null | apps/day9/test/day9_test.exs | at7heb/aoc2021 | ab31881b40354e28da0feaf5309c9648def85e77 | [
"MIT"
] | null | null | null | defmodule Day9Test do
use ExUnit.Case
doctest Day9
test "UL corner" do
assert Day9.process("""
19999
99999
99999
99999
99999
""") == 2
end
test "UR corner" do
assert Day9.process("""
99991
99999
99999
99999
99999
""") == 2
end
test "LL corner" do
assert Day9.process("""
99999
99999
99999
99999
19999
""") == 2
end
test "LR corner" do
assert Day9.process("""
99999
99999
99999
99999
99991
""") == 2
end
test "ULH edge" do
assert Day9.process("""
91999
99999
99999
99999
99999
""") == 2
end
test "URH corner" do
assert Day9.process("""
99919
99999
99999
99999
99999
""") == 2
end
test "LUV edge" do
assert Day9.process("""
99999
19999
99999
99999
99999
""") == 2
end
test "RUV edge" do
assert Day9.process("""
99999
99991
99999
99999
99999
""") == 2
end
test "LLV edge" do
assert Day9.process("""
99999
99999
99999
19999
99999
""") == 2
end
test "RLV edge" do
assert Day9.process("""
99999
99999
99999
99991
99999
""") == 2
end
test "LLH edge" do
assert Day9.process("""
99999
99999
99999
99999
91999
""") == 2
end
test "LRH edge" do
assert Day9.process("""
99999
99999
99999
99999
99919
""") == 2
end
test "no low spots" do
assert Day9.process("""
99999
99999
99999
99999
99999
""") == 0
end
test "UL line" do
assert Day9.process("""
99999
91999
99999
99999
99999
""") == 2
end
test "mid liner" do
assert Day9.process("""
99999
99999
99919
99999
99999
""") == 2
end
test "bottom line" do
assert Day9.process("""
99999
99999
99999
99999
99199
""") == 2
end
end
| 13.042424 | 27 | 0.465613 |
73ac5ebac174dad08487a8ef85a857eb94945e4d | 2,831 | ex | Elixir | clients/books/lib/google_api/books/v1/model/bookshelf.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/books/lib/google_api/books/v1/model/bookshelf.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/books/lib/google_api/books/v1/model/bookshelf.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.Books.V1.Model.Bookshelf do
@moduledoc """
## Attributes
* `access` (*type:* `String.t`, *default:* `nil`) - Whether this bookshelf is PUBLIC or PRIVATE.
* `created` (*type:* `String.t`, *default:* `nil`) - Created time for this bookshelf (formatted UTC timestamp with millisecond resolution).
* `description` (*type:* `String.t`, *default:* `nil`) - Description of this bookshelf.
* `id` (*type:* `integer()`, *default:* `nil`) - Id of this bookshelf, only unique by user.
* `kind` (*type:* `String.t`, *default:* `nil`) - Resource type for bookshelf metadata.
* `selfLink` (*type:* `String.t`, *default:* `nil`) - URL to this resource.
* `title` (*type:* `String.t`, *default:* `nil`) - Title of this bookshelf.
* `updated` (*type:* `String.t`, *default:* `nil`) - Last modified time of this bookshelf (formatted UTC timestamp with millisecond resolution).
* `volumeCount` (*type:* `integer()`, *default:* `nil`) - Number of volumes in this bookshelf.
* `volumesLastUpdated` (*type:* `String.t`, *default:* `nil`) - Last time a volume was added or removed from this bookshelf (formatted UTC timestamp with millisecond resolution).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:access => String.t(),
:created => String.t(),
:description => String.t(),
:id => integer(),
:kind => String.t(),
:selfLink => String.t(),
:title => String.t(),
:updated => String.t(),
:volumeCount => integer(),
:volumesLastUpdated => String.t()
}
field(:access)
field(:created)
field(:description)
field(:id)
field(:kind)
field(:selfLink)
field(:title)
field(:updated)
field(:volumeCount)
field(:volumesLastUpdated)
end
defimpl Poison.Decoder, for: GoogleApi.Books.V1.Model.Bookshelf do
def decode(value, options) do
GoogleApi.Books.V1.Model.Bookshelf.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Books.V1.Model.Bookshelf do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.256757 | 182 | 0.665842 |
73ac75984e84faef47bcb566636311c61ebfbcf4 | 1,285 | exs | Elixir | test/club/accounts/projectors/user_test.exs | vheathen/club.wallprint.pro | d58d2409d8879d23ed4d60fe3b9c2e1bd82e924d | [
"MIT"
] | null | null | null | test/club/accounts/projectors/user_test.exs | vheathen/club.wallprint.pro | d58d2409d8879d23ed4d60fe3b9c2e1bd82e924d | [
"MIT"
] | 34 | 2019-11-10T11:31:37.000Z | 2019-11-27T21:26:48.000Z | test/club/accounts/projectors/user_test.exs | vheathen/club.wallprint.pro | d58d2409d8879d23ed4d60fe3b9c2e1bd82e924d | [
"MIT"
] | null | null | null | defmodule Club.Accounts.Projectors.UserTest do
use Club.DataCase
alias Club.ReadRepo, as: Repo
alias Club.Accounts
alias Club.Accounts.Projections.User, as: UserProjection
alias Club.Accounts.Events.{
UserRegistered
}
@topic "domain:accounts"
setup do
Phoenix.PubSub.subscribe(Club.EventBus, @topic)
user = build(:new_user)
{:ok, _} = Accounts.register_user(user, meta())
wait_for_event(Club.Commanded, UserRegistered)
[user: user]
end
describe "Accounts.Projectors.User on" do
@describetag :integration
test "UserRegistered event shoud insert a new user record", %{
user: %{user_uuid: user_uuid} = user
} do
assert_receive {:user_registered, %{user_uuid: ^user_uuid}}, 1_000
result = Repo.all(UserProjection)
assert length(result) == 1
[user_projection] = result
assert user.user_uuid == user_projection.user_uuid
assert user.name == user_projection.name
assert user.email == user_projection.email
assert false == user_projection.email_confirmed?
assert "unverified" == user_projection.state
[identity] = user_projection.identities
assert user.identity.prov == identity.prov
assert user.identity.uid == identity.uid
end
end
end
| 24.245283 | 72 | 0.69572 |
73acdb643a2bf26b15c872c2b588815bf05d82af | 1,036 | ex | Elixir | lib/app/helpers.ex | 4DA/bleroma | 26a533373f121e54f49d7ce59fd6e246fe51f738 | [
"MIT"
] | 5 | 2020-06-30T14:12:21.000Z | 2021-11-14T21:16:02.000Z | lib/app/helpers.ex | 4DA/bleroma | 26a533373f121e54f49d7ce59fd6e246fe51f738 | [
"MIT"
] | null | null | null | lib/app/helpers.ex | 4DA/bleroma | 26a533373f121e54f49d7ce59fd6e246fe51f738 | [
"MIT"
] | null | null | null | defmodule Bleroma.Helpers do
require Hunter.Config
require Hunter.Api
alias Hunter.{Api.Request, Config}
defp get_headers(nil), do: []
defp get_headers(%Hunter.Client{bearer_token: token}) do
[{:Authorization, "Bearer #{token}"}]
end
defp get_headers(headers) when is_list(headers), do: headers
def request_dump!(url, to, method, payload, conn \\ nil) do
headers = get_headers(conn)
case Request.request(method, url, payload, headers, Hunter.Config.http_options()) do
{:ok, body} ->
body
{:error, _} -> nil
end
end
defp process_url(endpoint, %Hunter.Client{base_url: base_url}) do
process_url(endpoint, base_url)
end
# defp process_url(endpoint, base_url) do
# base_url <> endpoint
# end
def status_dump(conn, id) do
"/api/v1/statuses/#{id}"
|> process_url(conn)
|> request_dump!(:status, :get, [], conn)
end
def status_dump_str(base_url, id) do
"#{base_url}/api/v1/statuses/#{id}"
|> request_dump!(:status, :get, [])
end
end
| 23.545455 | 88 | 0.656371 |
73ace80c73d327ea63356a53522e1deaf502a13d | 5,524 | exs | Elixir | test/avro_rpc/convert_record_test.exs | cafreeman/avro_rpc | e690ace1046499361819d58a71f5fa9507f2cdeb | [
"MIT"
] | null | null | null | test/avro_rpc/convert_record_test.exs | cafreeman/avro_rpc | e690ace1046499361819d58a71f5fa9507f2cdeb | [
"MIT"
] | null | null | null | test/avro_rpc/convert_record_test.exs | cafreeman/avro_rpc | e690ace1046499361819d58a71f5fa9507f2cdeb | [
"MIT"
] | null | null | null | defmodule ConvertRecordTest do
use ExUnit.Case
@sample_record {
{
:avro_record,
:Customer,
[
{"id", :string},
{"phoneNumber", :string},
{"data", :string},
{"createdAt", :long},
{"updatedAt", :long}
]
},
[
"1234e967-dac2-4534-a023-ffadba5ea87e",
"+14692882964",
"{\"agent\":{\"phoneNumber\":\"+17378885895\"},\"facts\":{\"Work\":[\"Work From Home\"],\"Yard\":[\"No Yard\"],\"Effort\":[\"Investment\"],\"Social\":[\"Social In\"],\"Hobbies\":[\"Outdoor Hobbies\"],\"Parking\":[\"Parking\",\"No Parking\"],\"Privacy\":[\"Private\"],\"Shopping\":[\"Bigbox\"],\"Aesthetic\":[\"Modern\"],\"Neighborhood\":[],\"Type Of Home\":[\"Single Family\"],\"Walking Area\":[\"Schools\"],\"Mls Constraint\":[\"tx_actris\"],\"User Archetype\":[\"type 2\"],\"Price Constraint\":{},\"Bedroom Constraint\":{\"min\":1},\"Size Accommodation\":[\"Family\"],\"Bathroom Constraint\":{\"min\":1},\"Photo Count Constraint\":{\"min\":1},\"Preferred Neighborhoods\":[],\"Listing Status Constraint\":[\"Active\"]}}",
1490649587612,
1495070863382
]
}
@sample_invalid_record {
{
:avro_record,
:Customer,
[
{"id", :string},
{"phoneNumber", :string},
{"data", :string},
{"createdAt", :long},
{"updatedAt", :long}
]
},
[
"1234e967-dac2-4534-a023-ffadba5ea87e",
"+14692882964",
"{\"agent\":{\"phoneNumber\":\"+17378885895\"},\"facts\":{\"Work\":[\"Work From Home\"],\"Yard\":[\"No Yard\"],\"Effort\":[\"Investment\"],\"Social\":[\"Social In\"],\"Hobbies\":[\"Outdoor Hobbies\"],\"Parking\":[\"Parking\",\"No Parking\"],\"Privacy\":[\"Private\"],\"Shopping\":[\"Bigbox\"],\"Aesthetic\":[\"Modern\"],\"Neighborhood\":[],\"Type Of Home\":[\"Single Family\"],\"Walking Area\":[\"Schools\"],\"Mls Constraint\":[\"tx_actris\"],\"User Archetype\":[\"type 2\"],\"Price Constraint\":{},\"Bedroom Constraint\":{\"min\":1},\"Size Accommodation\":[\"Family\"],\"Bathroom Constraint\":{\"min\":1},\"Photo Count Constraint\":{\"min\":1},\"Preferred Neighborhoods\":[],\"Listing Status Constraint\":[\"Active\"]}}",
]
}
@sample_map %{
"id" => "1234e967-dac2-4534-a023-ffadba5ea87e",
"phoneNumber" => "+14692882964",
"data" => "{\"agent\":{\"phoneNumber\":\"+17378885895\"},\"facts\":{\"Work\":[\"Work From Home\"],\"Yard\":[\"No Yard\"],\"Effort\":[\"Investment\"],\"Social\":[\"Social In\"],\"Hobbies\":[\"Outdoor Hobbies\"],\"Parking\":[\"Parking\",\"No Parking\"],\"Privacy\":[\"Private\"],\"Shopping\":[\"Bigbox\"],\"Aesthetic\":[\"Modern\"],\"Neighborhood\":[],\"Type Of Home\":[\"Single Family\"],\"Walking Area\":[\"Schools\"],\"Mls Constraint\":[\"tx_actris\"],\"User Archetype\":[\"type 2\"],\"Price Constraint\":{},\"Bedroom Constraint\":{\"min\":1},\"Size Accommodation\":[\"Family\"],\"Bathroom Constraint\":{\"min\":1},\"Photo Count Constraint\":{\"min\":1},\"Preferred Neighborhoods\":[],\"Listing Status Constraint\":[\"Active\"]}}",
"createdAt" => 1490649587612,
"updatedAt" => 1495070863382
}
@sample_record_struct {
%ExAvro.Record{
name: :Customer,
fields: [
%ExAvro.Field{
name: "id",
type: :string
},
%ExAvro.Field{
name: "phoneNumber",
type: :string
},
%ExAvro.Field{
name: "data",
type: :string
},
%ExAvro.Field{
name: "createdAt",
type: :long
},
%ExAvro.Field{
name: "updatedAt",
type: :long
}
]
},
[
"1234e967-dac2-4534-a023-ffadba5ea87e",
"+14692882964",
"{\"agent\":{\"phoneNumber\":\"+17378885895\"},\"facts\":{\"Work\":[\"Work From Home\"],\"Yard\":[\"No Yard\"],\"Effort\":[\"Investment\"],\"Social\":[\"Social In\"],\"Hobbies\":[\"Outdoor Hobbies\"],\"Parking\":[\"Parking\",\"No Parking\"],\"Privacy\":[\"Private\"],\"Shopping\":[\"Bigbox\"],\"Aesthetic\":[\"Modern\"],\"Neighborhood\":[],\"Type Of Home\":[\"Single Family\"],\"Walking Area\":[\"Schools\"],\"Mls Constraint\":[\"tx_actris\"],\"User Archetype\":[\"type 2\"],\"Price Constraint\":{},\"Bedroom Constraint\":{\"min\":1},\"Size Accommodation\":[\"Family\"],\"Bathroom Constraint\":{\"min\":1},\"Photo Count Constraint\":{\"min\":1},\"Preferred Neighborhoods\":[],\"Listing Status Constraint\":[\"Active\"]}}",
1490649587612,
1495070863382
]
}
test "can convert a valid record to map" do
{:ok, converted_record} = AvroRPC.Response.format(@sample_record)
assert is_map(converted_record)
assert converted_record |> Map.keys |> length == 5
assert Map.equal?(@sample_map, converted_record)
end
test "returns :invalid_length error tuple on record with missing fields" do
result = AvroRPC.Response.format(@sample_invalid_record)
assert elem(result, 0) == :error
assert {:invalid_length, "The number of fields do not match the number of values."} == elem(result, 1)
end
test "converts a record with an ExAvro.Record definition" do
{:ok, converted_record} = AvroRPC.Response.format(@sample_record_struct)
assert is_map(converted_record)
assert converted_record |> Map.keys |> length == 5
assert Map.equal?(@sample_map, converted_record)
end
@tag :skip
test "returns :invalid_type tuple on non-record" do
assert {:error, {:invalid_type, "You must pass an Erlang record."}} == AvroRPC.Response.format(%{hello: "world"})
end
end
| 48.45614 | 738 | 0.575308 |
73acfda9ef3880cd40fc1dc96dd9a6df5f04b111 | 1,155 | ex | Elixir | lib/phoenix/socket/pool_supervisor.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | 1 | 2019-07-15T21:58:09.000Z | 2019-07-15T21:58:09.000Z | lib/phoenix/socket/pool_supervisor.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | null | null | null | lib/phoenix/socket/pool_supervisor.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | null | null | null | defmodule Phoenix.Socket.PoolSupervisor do
@moduledoc false
use Supervisor
def start_link(args) do
Supervisor.start_link(__MODULE__, args)
end
def start_child(endpoint, name, key, args) do
ets = endpoint.config({:socket, name})
partitions = :ets.lookup_element(ets, :partitions, 2)
sup = :ets.lookup_element(ets, :erlang.phash2(key, partitions), 2)
Supervisor.start_child(sup, args)
end
@doc false
def start_pooled(worker, ref, i) do
case Supervisor.start_link([worker], strategy: :simple_one_for_one) do
{:ok, pid} ->
:ets.insert(ref, {i, pid})
{:ok, pid}
{:error, reason} ->
{:error, reason}
end
end
@doc false
def init({endpoint, name, partitions, worker}) do
import Supervisor.Spec
ref = :ets.new(name, [:public, read_concurrency: true])
:ets.insert(ref, {:partitions, partitions})
Phoenix.Config.permanent(endpoint, {:socket, name}, ref)
children =
for i <- 0..(partitions - 1) do
supervisor(__MODULE__, [worker, ref, i], id: i, function: :start_pooled)
end
supervise(children, strategy: :one_for_one)
end
end
| 26.25 | 80 | 0.652814 |
73ad233f32837c02337d546c8b8f2620269d0301 | 1,969 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/user_roles_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/user_roles_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/user_roles_list_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Model.UserRolesListResponse do
@moduledoc """
User Role List Response
## Attributes
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolesListResponse".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation.
* `userRoles` (*type:* `list(GoogleApi.DFAReporting.V34.Model.UserRole.t)`, *default:* `nil`) - User role collection.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t() | nil,
:nextPageToken => String.t() | nil,
:userRoles => list(GoogleApi.DFAReporting.V34.Model.UserRole.t()) | nil
}
field(:kind)
field(:nextPageToken)
field(:userRoles, as: GoogleApi.DFAReporting.V34.Model.UserRole, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.UserRolesListResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.UserRolesListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.UserRolesListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.150943 | 157 | 0.726765 |
73ad554ecdba67e01146ab8004d29c107a746023 | 1,944 | exs | Elixir | test/segment_tree_test.exs | adrienmo/segment_tree | f8bb7067e5e50069f93c4a0a50c735e658fdb36d | [
"MIT"
] | 1 | 2020-01-20T19:10:36.000Z | 2020-01-20T19:10:36.000Z | test/segment_tree_test.exs | adrienmo/segment_tree | f8bb7067e5e50069f93c4a0a50c735e658fdb36d | [
"MIT"
] | null | null | null | test/segment_tree_test.exs | adrienmo/segment_tree | f8bb7067e5e50069f93c4a0a50c735e658fdb36d | [
"MIT"
] | null | null | null | defmodule SegmentTreeTest do
use ExUnit.Case
doctest SegmentTree
test "create a new Segment Tree" do
assert SegmentTree.new(1_000, &Kernel.+/2) == %SegmentTree{
default: 0,
tree: %{},
aggregate_fun: &Kernel.+/2,
max_index: 1_023
}
assert SegmentTree.new(1_000, &Kernel.*/2, 1) == %SegmentTree{
default: 1,
tree: %{},
aggregate_fun: &Kernel.*/2,
max_index: 1_023
}
end
test "put a new value" do
segment_tree = SegmentTree.new(1_000, &Kernel.+/2)
segment_tree2 = SegmentTree.put(segment_tree, 1, 1)
assert %{
0 => 1,
1 => 1,
3 => 1,
7 => 1,
15 => 1,
31 => 1,
63 => 1,
127 => 1,
255 => 1,
511 => 1,
1024 => 1
} == segment_tree2.tree
segment_tree3 = SegmentTree.put(segment_tree2, 2, 2)
assert %{
0 => 3,
1 => 3,
3 => 3,
7 => 3,
15 => 3,
31 => 3,
63 => 3,
127 => 3,
255 => 3,
511 => 1,
512 => 2,
1024 => 1,
1025 => 2
} == segment_tree3.tree
end
test "test aggregate" do
segment_tree_sum = Enum.reduce(0..1000, SegmentTree.new(1_000, &Kernel.+/2), fn(x, acc) -> SegmentTree.put(acc, x, x) end)
assert SegmentTree.aggregate(segment_tree_sum, 101, 1_000) == (1_000 * (1_000 + 1)) / 2 - (100 * (100 + 1)) / 2
segment_tree_mul = Enum.reduce(1..1000, SegmentTree.new(1_000, &Kernel.*/2, 1), fn(x, acc) -> SegmentTree.put(acc, x, x) end)
assert SegmentTree.aggregate(segment_tree_mul, 101, 1_000) == div(factorial(1000), factorial(100))
end
defp factorial(0), do: 1
defp factorial(n) when n > 0, do: n * factorial(n - 1)
end
| 29.454545 | 129 | 0.476337 |
73ad86d6165d0e5ce7f605f1e7ebe4f3f6b2b10e | 10,106 | ex | Elixir | lib/chat_api/emails/email.ex | lastbit-io/papercups | 84ef2f647ee1f633e0d226b2312cd8f2e9fc59d7 | [
"MIT"
] | null | null | null | lib/chat_api/emails/email.ex | lastbit-io/papercups | 84ef2f647ee1f633e0d226b2312cd8f2e9fc59d7 | [
"MIT"
] | null | null | null | lib/chat_api/emails/email.ex | lastbit-io/papercups | 84ef2f647ee1f633e0d226b2312cd8f2e9fc59d7 | [
"MIT"
] | null | null | null | defmodule ChatApi.Emails.Email do
import Swoosh.Email
import Ecto.Changeset
alias ChatApi.Customers.Customer
alias ChatApi.Messages.Message
alias ChatApi.Users.UserProfile
@type t :: Swoosh.Email.t()
@from_address System.get_env("FROM_ADDRESS") || ""
@backend_url System.get_env("BACKEND_URL") || ""
defstruct to_address: nil, message: nil
def generic(to: to, from: from, subject: subject, text: text, html: html) do
new()
|> to(to)
|> from(from)
|> subject(subject)
|> text_body(text)
|> html_body(html)
end
def gmail(
%{
to: to,
from: from,
subject: subject,
text: text,
in_reply_to: in_reply_to,
references: references
} = params
) do
new()
|> to(to)
|> from(from)
|> subject(subject)
|> cc(Map.get(params, :cc, []))
|> bcc(Map.get(params, :bcc, []))
|> header("In-Reply-To", in_reply_to)
|> header("References", references)
|> text_body(text)
|> html_body(Map.get(params, :html))
end
def gmail(%{to: to, from: from, subject: subject, text: text} = params) do
new()
|> to(to)
|> from(from)
|> subject(subject)
|> cc(Map.get(params, :cc, []))
|> bcc(Map.get(params, :bcc, []))
|> text_body(text)
|> html_body(Map.get(params, :html))
end
# TODO: Add some recent messages for context, rather than just a single message
# (See the `conversation_reply` method for an example of this)
def new_message_alert(
to_address,
%Message{
body: body,
conversation_id: conversation_id,
customer_id: customer_id
} = _message
) do
customer =
case customer_id do
id when is_binary(id) -> ChatApi.Customers.get_customer!(id)
_ -> nil
end
{subject, intro} =
case customer do
%Customer{email: email, name: name} when is_binary(email) and is_binary(name) ->
{"#{name} (#{email}) has sent you a message", "New message from #{name} (#{email}):"}
%Customer{email: email} when is_binary(email) ->
{"#{email} has sent you a message", "New message from #{email}:"}
%Customer{name: name} when is_binary(name) ->
{"#{name} has sent you a message", "New message from #{name}:"}
_ ->
{"A customer has sent you a message (conversation #{conversation_id})",
"New message from an anonymous user:"}
end
link =
"<a href=\"https://#{@backend_url}/conversations/#{conversation_id}\">View in dashboard</a>"
html = intro <> "<br />" <> "<b>#{body}</b>" <> "<br /><br />" <> link
text = intro <> " " <> body
new()
|> to(to_address)
|> from({"Papercups", @from_address})
|> subject(subject)
|> html_body(html)
|> text_body(text)
end
def conversation_reply(
to: to,
from: from,
reply_to: reply_to,
company: company,
messages: messages,
customer: customer
) do
new()
|> to(to)
|> from({from, @from_address})
|> reply_to(reply_to)
|> subject("New message from #{company}!")
|> html_body(conversation_reply_html(messages, from: from, to: customer, company: company))
|> text_body(conversation_reply_text(messages, from: from, to: customer, company: company))
end
# TODO: figure out a better way to create templates for these
defp conversation_reply_text(messages, from: from, to: customer, company: company) do
"""
Hi #{customer.name || "there"}!
You've received a new message from your chat with #{company} (#{customer.current_url || ""}):
#{
Enum.map(messages, fn msg ->
format_sender(msg, company) <> ": " <> msg.body <> "\n"
end)
}
Best,
#{from}
"""
end
defp format_agent(user, company) do
case user do
%{email: email, profile: nil} ->
company || email
%{email: email, profile: %UserProfile{} = profile} ->
profile.display_name || profile.full_name || company || email
_ ->
company || "Agent"
end
end
defp format_sender(message, company) do
case message do
%{user: user, customer_id: nil} -> format_agent(user, company)
%{customer_id: _customer_id} -> "You"
end
end
defp conversation_reply_html(messages, from: from, to: customer, company: company) do
"""
<p>Hi #{customer.name || "there"}!</p>
<p>You've received a new message from your chat with
<a href="#{customer.current_url}">#{company}</a>:</p>
<hr />
#{Enum.map(messages, fn msg -> format_message_html(msg, company) end)}
<hr />
<p>
Best,<br />
#{from}
</p>
"""
end
defp format_message_html(message, company) do
markdown = """
**#{format_sender(message, company)}**\s\s
#{message.body}
"""
fallback = """
<p>
<strong>#{format_sender(message, company)}</strong><br />
#{message.body}
</p>
"""
case Earmark.as_html(markdown) do
{:ok, html, _} -> html
_ -> fallback
end
end
# TODO: use env variables instead, come up with a better message
def welcome(to_address) do
new()
|> to(to_address)
|> from({"Alex", @from_address})
|> reply_to("[email protected]")
|> subject("Welcome to Papercups!")
|> html_body(welcome_email_html())
|> text_body(welcome_email_text())
end
# TODO: figure out a better way to create templates for these
defp welcome_email_text() do
# TODO: include user's name if available
"""
Hi there!
Thanks for signing up for Papercups :)
I'm Alex, one of the founders of Papercups along with Kam. If you have any questions,
feedback, or need any help getting started, don't hesitate to reach out!
Feel free to reply directly to this email, or contact me at [email protected]
Best,
Alex
We also have a Slack channel if you'd like to see what we're up to :)
https://github.com/papercups-io/papercups#get-in-touch
"""
end
# TODO: figure out a better way to create templates for these
defp welcome_email_html() do
# TODO: include user's name if available
"""
<p>Hi there!</p>
<p>Thanks for signing up for Papercups :)</p>
<p>I'm Alex, one of the founders of Papercups along with Kam. If you have any questions,
feedback, or need any help getting started, don't hesitate to reach out!</p>
<p>Feel free to reply directly to this email, or contact me at [email protected]</p>
<p>
Best,<br />
Alex
</p>
<p>
PS: We also have a Slack channel if you'd like to see what we're up to :) <br/>
https://github.com/papercups-io/papercups#get-in-touch
</p>
"""
end
def user_invitation(
%{
company: company,
from_address: from_address,
from_name: from_name,
invitation_token: invitation_token,
to_address: to_address
} = _params
) do
subject =
if from_name == company,
do: "You've been invited to join #{company} on Papercups!",
else: "#{from_name} has invited you to join #{company} on Papercups!"
intro_line =
if from_name == company,
do: "#{from_address} has invited you to join #{company} on Papercups!",
else: "#{from_name} (#{from_address}) has invited you to join #{company} on Papercups!"
invitation_url =
"#{get_app_domain()}/register/#{invitation_token}?#{URI.encode_query(%{email: to_address})}"
new()
|> to(to_address)
|> from({"Alex", @from_address})
|> reply_to("[email protected]")
|> subject(subject)
|> html_body(
user_invitation_email_html(%{
intro_line: intro_line,
invitation_url: invitation_url
})
)
|> text_body(
user_invitation_email_text(%{
intro_line: intro_line,
invitation_url: invitation_url
})
)
end
defp user_invitation_email_text(
%{
invitation_url: invitation_url,
intro_line: intro_line
} = _params
) do
"""
Hi there!
#{intro_line}
Click the link below to sign up:
#{invitation_url}
Best,
Alex & Kam @ Papercups
"""
end
# TODO: figure out a better way to create templates for these
defp user_invitation_email_html(
%{
invitation_url: invitation_url,
intro_line: intro_line
} = _params
) do
"""
<p>Hi there!</p>
<p>#{intro_line}</p>
<p>Click the link below to sign up:</p>
<a href="#{invitation_url}">#{invitation_url}</a>
<p>
Best,<br />
Alex & Kam @ Papercups
</p>
"""
end
def password_reset(%ChatApi.Users.User{email: email, password_reset_token: token} = _user) do
new()
|> to(email)
|> from({"Papercups", @from_address})
|> subject("[Papercups] Link to reset your password")
|> html_body(password_reset_html(token))
|> text_body(password_reset_text(token))
end
defp get_app_domain() do
if Application.get_env(:chat_api, :environment) == :dev do
"http://localhost:3000"
else
"https://" <> System.get_env("BACKEND_URL", "app.papercups.io")
end
end
# TODO: figure out a better way to create templates for these
defp password_reset_text(token) do
"""
Hi there!
Click the link below to reset your Papercups password:
#{get_app_domain()}/reset?token=#{token}
Best,
Alex & Kam @ Papercups
"""
end
# TODO: figure out a better way to create templates for these
defp password_reset_html(token) do
link = "#{get_app_domain()}/reset?token=#{token}"
"""
<p>Hi there!</p>
<p>Click the link below to reset your Papercups password:</p>
<a href="#{link}">#{link}</a>
<p>
Best,<br />
Alex & Kam @ Papercups
</p>
"""
end
@spec changeset(any(), map()) :: Ecto.Changeset.t()
def changeset(email, attrs) do
email
|> cast(attrs, [:to_address, :message])
|> validate_required([:to_address, :message])
end
end
| 25.912821 | 98 | 0.598258 |
73adbb6a292269573f89b7e157614d782448507b | 29,741 | ex | Elixir | clients/firebase_rules/lib/google_api/firebase_rules/v1/api/projects.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/firebase_rules/lib/google_api/firebase_rules/v1/api/projects.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/firebase_rules/lib/google_api/firebase_rules/v1/api/projects.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.FirebaseRules.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.FirebaseRules.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Create a `Release`. Release names should reflect the developer's deployment practices. For example, the release name may include the environment name, application name, application version, or any other name meaningful to the developer. Once a `Release` refers to a `Ruleset`, the rules can be enforced by Firebase Rules-enabled services. More than one `Release` may be 'live' concurrently. Consider the following three `Release` names for `projects/foo` and the `Ruleset` to which they refer. Release Name | Ruleset Name --------------------------------|------------- projects/foo/releases/prod | projects/foo/rulesets/uuid123 projects/foo/releases/prod/beta | projects/foo/rulesets/uuid123 projects/foo/releases/prod/v23 | projects/foo/rulesets/uuid456 The table reflects the `Ruleset` rollout in progress. The `prod` and `prod/beta` releases refer to the same `Ruleset`. However, `prod/v23` refers to a new `Ruleset`. The `Ruleset` reference for a `Release` may be updated using the UpdateRelease method.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name for the project which owns this `Release`. Format: `projects/{project_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :body (Release):
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.Release{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_releases_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.Release.t()} | {:error, Tesla.Env.t()}
def firebaserules_projects_releases_create(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}/releases", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.Release{}])
end
@doc """
Delete a `Release` by resource name.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name for the `Release` to delete. Format: `projects/{project_id}/releases/{release_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.Empty{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_releases_delete(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def firebaserules_projects_releases_delete(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.Empty{}])
end
@doc """
Get a `Release` by name.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name of the `Release`. Format: `projects/{project_id}/releases/{release_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.Release{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_releases_get(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.Release.t()} | {:error, Tesla.Env.t()}
def firebaserules_projects_releases_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.Release{}])
end
@doc """
Get the `Release` executable to use when enforcing rules.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name of the `Release`. Format: `projects/{project_id}/releases/{release_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :executableVersion (String.t): The requested runtime executable version. Defaults to FIREBASE_RULES_EXECUTABLE_V1.
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.GetReleaseExecutableResponse{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_releases_get_executable(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.GetReleaseExecutableResponse.t()}
| {:error, Tesla.Env.t()}
def firebaserules_projects_releases_get_executable(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:executableVersion => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}:getExecutable", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.GetReleaseExecutableResponse{}]
)
end
@doc """
List the `Release` values for a project. This list may optionally be filtered by `Release` name, `Ruleset` name, `TestSuite` name, or any combination thereof.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name for the project. Format: `projects/{project_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :filter (String.t): `Release` filter. The list method supports filters with restrictions on the `Release.name`, `Release.ruleset_name`, and `Release.test_suite_name`. Example 1: A filter of 'name=prod*' might return `Release`s with names within 'projects/foo' prefixed with 'prod': Name | Ruleset Name ------------------------------|------------- projects/foo/releases/prod | projects/foo/rulesets/uuid1234 projects/foo/releases/prod/v1 | projects/foo/rulesets/uuid1234 projects/foo/releases/prod/v2 | projects/foo/rulesets/uuid8888 Example 2: A filter of `name=prod* ruleset_name=uuid1234` would return only `Release` instances for 'projects/foo' with names prefixed with 'prod' referring to the same `Ruleset` name of 'uuid1234': Name | Ruleset Name ------------------------------|------------- projects/foo/releases/prod | projects/foo/rulesets/1234 projects/foo/releases/prod/v1 | projects/foo/rulesets/1234 In the examples, the filter parameters refer to the search filters are relative to the project. Fully qualified prefixed may also be used. e.g. `test_suite_name=projects/foo/testsuites/uuid1`
- :pageSize (integer()): Page size to load. Maximum of 100. Defaults to 10. Note: `page_size` is just a hint and the service may choose to load fewer than `page_size` results due to the size of the output. To traverse all of the releases, the caller should iterate until the `page_token` on the response is empty.
- :pageToken (String.t): Next page token for the next batch of `Release` instances.
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.ListReleasesResponse{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_releases_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.ListReleasesResponse.t()}
| {:error, Tesla.Env.t()}
def firebaserules_projects_releases_list(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/releases", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.ListReleasesResponse{}])
end
@doc """
Update a `Release` via PATCH. Only updates to the `ruleset_name` and `test_suite_name` fields will be honored. `Release` rename is not supported. To create a `Release` use the CreateRelease method.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name for the project which owns this `Release`. Format: `projects/{project_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :body (UpdateReleaseRequest):
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.Release{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_releases_patch(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.Release.t()} | {:error, Tesla.Env.t()}
def firebaserules_projects_releases_patch(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.Release{}])
end
@doc """
Create a `Ruleset` from `Source`. The `Ruleset` is given a unique generated name which is returned to the caller. `Source` containing syntactic or semantics errors will result in an error response indicating the first error encountered. For a detailed view of `Source` issues, use TestRuleset.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name for Project which owns this `Ruleset`. Format: `projects/{project_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :body (Ruleset):
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.Ruleset{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_rulesets_create(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.Ruleset.t()} | {:error, Tesla.Env.t()}
def firebaserules_projects_rulesets_create(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}/rulesets", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.Ruleset{}])
end
@doc """
List `Ruleset` metadata only and optionally filter the results by `Ruleset` name. The full `Source` contents of a `Ruleset` may be retrieved with GetRuleset.
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Resource name for the project. Format: `projects/{project_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :filter (String.t): `Ruleset` filter. The list method supports filters with restrictions on `Ruleset.name`. Filters on `Ruleset.create_time` should use the `date` function which parses strings that conform to the RFC 3339 date/time specifications. Example: `create_time > date(\"2017-01-01\") AND name=UUID-*`
- :pageSize (integer()): Page size to load. Maximum of 100. Defaults to 10. Note: `page_size` is just a hint and the service may choose to load less than `page_size` due to the size of the output. To traverse all of the releases, caller should iterate until the `page_token` is empty.
- :pageToken (String.t): Next page token for loading the next batch of `Ruleset` instances.
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.ListRulesetsResponse{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_rulesets_list(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.ListRulesetsResponse.t()}
| {:error, Tesla.Env.t()}
def firebaserules_projects_rulesets_list(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/rulesets", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.ListRulesetsResponse{}])
end
@doc """
Test `Source` for syntactic and semantic correctness. Issues present, if any, will be returned to the caller with a description, severity, and source location. The test method may be executed with `Source` or a `Ruleset` name. Passing `Source` is useful for unit testing new rules. Passing a `Ruleset` name is useful for regression testing an existing rule. The following is an example of `Source` that permits users to upload images to a bucket bearing their user id and matching the correct metadata: _*Example*_ // Users are allowed to subscribe and unsubscribe to the blog. service firebase.storage { match /users/{userId}/images/{imageName} { allow write: if userId == request.auth.uid && (imageName.matches('*.png$') || imageName.matches('*.jpg$')) && resource.mimeType.matches('^image/') } }
## Parameters
- connection (GoogleApi.FirebaseRules.V1.Connection): Connection to server
- name (String.t): Tests may either provide `source` or a `Ruleset` resource name. For tests against `source`, the resource name must refer to the project: Format: `projects/{project_id}` For tests against a `Ruleset`, this must be the `Ruleset` resource name: Format: `projects/{project_id}/rulesets/{ruleset_id}`
- optional_params (KeywordList): [optional] Optional parameters
- :$.xgafv (String.t): V1 error format.
- :access_token (String.t): OAuth access token.
- :alt (String.t): Data format for response.
- :callback (String.t): JSONP
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
- :upload_protocol (String.t): Upload protocol for media (e.g. \"raw\", \"multipart\").
- :uploadType (String.t): Legacy upload protocol for media (e.g. \"media\", \"multipart\").
- :body (TestRulesetRequest):
## Returns
{:ok, %GoogleApi.FirebaseRules.V1.Model.TestRulesetResponse{}} on success
{:error, info} on failure
"""
@spec firebaserules_projects_test(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.FirebaseRules.V1.Model.TestRulesetResponse.t()}
| {:error, Tesla.Env.t()}
def firebaserules_projects_test(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:upload_protocol => :query,
:uploadType => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:test", %{
"name" => URI.encode_www_form(name)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.FirebaseRules.V1.Model.TestRulesetResponse{}])
end
end
| 53.587387 | 1,328 | 0.6718 |
73adf6094525aeff1043fb77e24c8566d34ec229 | 31,603 | ex | Elixir | data/auto_generated/video/f7bc9a5473aa1b8ec99b8a8635205521.ex | breunigs/veloroute | ac3b1eeb2ef2369c27186a138f6ffd8284652dab | [
"0BSD"
] | 12 | 2018-06-15T10:18:43.000Z | 2022-01-24T12:50:54.000Z | data/auto_generated/video/f7bc9a5473aa1b8ec99b8a8635205521.ex | breunigs/veloroute | ac3b1eeb2ef2369c27186a138f6ffd8284652dab | [
"0BSD"
] | 15 | 2018-06-21T18:04:12.000Z | 2021-10-16T12:54:39.000Z | data/auto_generated/video/f7bc9a5473aa1b8ec99b8a8635205521.ex | breunigs/veloroute | ac3b1eeb2ef2369c27186a138f6ffd8284652dab | [
"0BSD"
] | 2 | 2020-03-09T19:21:36.000Z | 2022-01-16T03:29:51.000Z | defmodule(Data.AutoGenerated.Video.Rendered_f7bc9a5473aa1b8ec99b8a8635205521) do
@moduledoc "#{"Alltagsroute 11: von Wilhelmsburg zur Veddel"}
AUTOGENERATED. To update this file, run mix velo.videos.generate.
See Video.Rendered for functionality.
"
@behaviour Video.Rendered
@impl Video.Rendered
def(name()) do
"Alltagsroute 11: von Wilhelmsburg zur Veddel"
end
@impl Video.Rendered
def(hash()) do
"f7bc9a5473aa1b8ec99b8a8635205521"
end
@impl Video.Rendered
def(length_ms()) do
124_615
end
@impl Video.Rendered
def(sources()) do
[
{"2021-07-17-gruenerring1-11whburg-haubach/GX012376", "00:00:06.840", "00:00:08.609"},
{"2021-07-04-veloroute11/GX012117", "00:00:08.308", "00:00:26.860"},
{"2021-04-17-freizeitrouten-6und-7/GX011303", "00:00:39.540", :end},
{"2021-04-17-freizeitrouten-6und-7/GX011304", :start, :end},
{"2021-07-18-whburg-and-on/GX012396", :start, :end},
{"2021-07-18-whburg-and-on/GX012397", :start, "00:00:03.270"}
]
end
@impl Video.Rendered
def(coords()) do
[
%Video.TimedPoint{lat: 53.50013767065868, lon: 9.997799676646707, time_offset_ms: 0},
%Video.TimedPoint{lat: 53.500166, lon: 9.997746, time_offset_ms: 166},
%Video.TimedPoint{lat: 53.500244, lon: 9.997643, time_offset_ms: 499},
%Video.TimedPoint{lat: 53.50034, lon: 9.997604, time_offset_ms: 833},
%Video.TimedPoint{lat: 53.500434, lon: 9.997617, time_offset_ms: 1166},
%Video.TimedPoint{lat: 53.500531, lon: 9.997623, time_offset_ms: 1500},
%Video.TimedPoint{lat: 53.50060912275449, lon: 9.997634275449101, time_offset_ms: 1769},
%Video.TimedPoint{lat: 53.50063118562874, lon: 9.997665754491019, time_offset_ms: 1854},
%Video.TimedPoint{lat: 53.50064, lon: 9.997667, time_offset_ms: 1886},
%Video.TimedPoint{lat: 53.500729, lon: 9.997677, time_offset_ms: 2220},
%Video.TimedPoint{lat: 53.50082, lon: 9.997689, time_offset_ms: 2553},
%Video.TimedPoint{lat: 53.500906, lon: 9.997712, time_offset_ms: 2887},
%Video.TimedPoint{lat: 53.500989, lon: 9.99773, time_offset_ms: 3220},
%Video.TimedPoint{lat: 53.501081, lon: 9.997744, time_offset_ms: 3554},
%Video.TimedPoint{lat: 53.50117, lon: 9.997752, time_offset_ms: 3888},
%Video.TimedPoint{lat: 53.50126, lon: 9.997761, time_offset_ms: 4221},
%Video.TimedPoint{lat: 53.501357, lon: 9.997776, time_offset_ms: 4555},
%Video.TimedPoint{lat: 53.501458, lon: 9.997785, time_offset_ms: 4888},
%Video.TimedPoint{lat: 53.501557, lon: 9.997799, time_offset_ms: 5222},
%Video.TimedPoint{lat: 53.501654, lon: 9.997814, time_offset_ms: 5556},
%Video.TimedPoint{lat: 53.501754, lon: 9.997824, time_offset_ms: 5889},
%Video.TimedPoint{lat: 53.501851, lon: 9.997838, time_offset_ms: 6223},
%Video.TimedPoint{lat: 53.50195, lon: 9.997849, time_offset_ms: 6556},
%Video.TimedPoint{lat: 53.50205, lon: 9.997861, time_offset_ms: 6890},
%Video.TimedPoint{lat: 53.50215, lon: 9.997875, time_offset_ms: 7224},
%Video.TimedPoint{lat: 53.502248, lon: 9.997888, time_offset_ms: 7557},
%Video.TimedPoint{lat: 53.502346, lon: 9.997898, time_offset_ms: 7891},
%Video.TimedPoint{lat: 53.502441, lon: 9.997907, time_offset_ms: 8224},
%Video.TimedPoint{lat: 53.502539, lon: 9.997919, time_offset_ms: 8558},
%Video.TimedPoint{lat: 53.502636, lon: 9.997938, time_offset_ms: 8892},
%Video.TimedPoint{lat: 53.502734, lon: 9.997952, time_offset_ms: 9225},
%Video.TimedPoint{lat: 53.502828, lon: 9.997963, time_offset_ms: 9559},
%Video.TimedPoint{lat: 53.502921, lon: 9.997975, time_offset_ms: 9892},
%Video.TimedPoint{lat: 53.503011, lon: 9.997987, time_offset_ms: 10226},
%Video.TimedPoint{lat: 53.503108, lon: 9.998004, time_offset_ms: 10560},
%Video.TimedPoint{lat: 53.503215, lon: 9.998024, time_offset_ms: 10893},
%Video.TimedPoint{lat: 53.503322, lon: 9.998042, time_offset_ms: 11227},
%Video.TimedPoint{lat: 53.503429, lon: 9.998064, time_offset_ms: 11560},
%Video.TimedPoint{lat: 53.503537, lon: 9.998094, time_offset_ms: 11894},
%Video.TimedPoint{lat: 53.503643, lon: 9.998124, time_offset_ms: 12228},
%Video.TimedPoint{lat: 53.50375, lon: 9.998142, time_offset_ms: 12561},
%Video.TimedPoint{lat: 53.50386, lon: 9.998145, time_offset_ms: 12895},
%Video.TimedPoint{lat: 53.503966, lon: 9.998141, time_offset_ms: 13228},
%Video.TimedPoint{lat: 53.504072, lon: 9.998133, time_offset_ms: 13562},
%Video.TimedPoint{lat: 53.50418, lon: 9.998131, time_offset_ms: 13896},
%Video.TimedPoint{lat: 53.504279, lon: 9.998139, time_offset_ms: 14229},
%Video.TimedPoint{lat: 53.504376, lon: 9.99815, time_offset_ms: 14563},
%Video.TimedPoint{lat: 53.504473, lon: 9.998163, time_offset_ms: 14896},
%Video.TimedPoint{lat: 53.504567, lon: 9.998182, time_offset_ms: 15230},
%Video.TimedPoint{lat: 53.504663, lon: 9.998197, time_offset_ms: 15563},
%Video.TimedPoint{lat: 53.504759, lon: 9.998217, time_offset_ms: 15897},
%Video.TimedPoint{lat: 53.504851, lon: 9.998234, time_offset_ms: 16231},
%Video.TimedPoint{lat: 53.504942, lon: 9.998246, time_offset_ms: 16564},
%Video.TimedPoint{lat: 53.505031, lon: 9.998261, time_offset_ms: 16898},
%Video.TimedPoint{lat: 53.505123, lon: 9.998274, time_offset_ms: 17231},
%Video.TimedPoint{lat: 53.505218, lon: 9.998279, time_offset_ms: 17565},
%Video.TimedPoint{lat: 53.505315, lon: 9.998267, time_offset_ms: 17899},
%Video.TimedPoint{lat: 53.505402, lon: 9.998239, time_offset_ms: 18232},
%Video.TimedPoint{lat: 53.50548, lon: 9.998207, time_offset_ms: 18566},
%Video.TimedPoint{lat: 53.505556, lon: 9.998175, time_offset_ms: 18899},
%Video.TimedPoint{lat: 53.505623, lon: 9.998143, time_offset_ms: 19233},
%Video.TimedPoint{lat: 53.505693, lon: 9.998133, time_offset_ms: 19567},
%Video.TimedPoint{lat: 53.505767, lon: 9.998146, time_offset_ms: 19900},
%Video.TimedPoint{lat: 53.505841, lon: 9.998149, time_offset_ms: 20234},
%Video.TimedPoint{lat: 53.50588077177177, lon: 9.998158297297298, time_offset_ms: 20406},
%Video.TimedPoint{lat: 53.5059311021021, lon: 9.99809354054054, time_offset_ms: 20491},
%Video.TimedPoint{lat: 53.505965, lon: 9.998107, time_offset_ms: 20657},
%Video.TimedPoint{lat: 53.506035, lon: 9.998156, time_offset_ms: 20991},
%Video.TimedPoint{lat: 53.506105, lon: 9.998223, time_offset_ms: 21325},
%Video.TimedPoint{lat: 53.506177, lon: 9.998293, time_offset_ms: 21658},
%Video.TimedPoint{lat: 53.506256, lon: 9.998334, time_offset_ms: 21992},
%Video.TimedPoint{lat: 53.506337, lon: 9.998359, time_offset_ms: 22326},
%Video.TimedPoint{lat: 53.506416, lon: 9.998378, time_offset_ms: 22659},
%Video.TimedPoint{lat: 53.506497, lon: 9.998398, time_offset_ms: 22993},
%Video.TimedPoint{lat: 53.506576, lon: 9.998418, time_offset_ms: 23327},
%Video.TimedPoint{lat: 53.506655, lon: 9.998432, time_offset_ms: 23660},
%Video.TimedPoint{lat: 53.50673, lon: 9.998448, time_offset_ms: 23994},
%Video.TimedPoint{lat: 53.5068, lon: 9.998463, time_offset_ms: 24328},
%Video.TimedPoint{lat: 53.506865, lon: 9.998476, time_offset_ms: 24661},
%Video.TimedPoint{lat: 53.506926, lon: 9.998489, time_offset_ms: 24995},
%Video.TimedPoint{lat: 53.506983, lon: 9.998501, time_offset_ms: 25329},
%Video.TimedPoint{lat: 53.50704, lon: 9.99851, time_offset_ms: 25662},
%Video.TimedPoint{lat: 53.507103, lon: 9.998533, time_offset_ms: 25996},
%Video.TimedPoint{lat: 53.507172, lon: 9.998551, time_offset_ms: 26330},
%Video.TimedPoint{lat: 53.507243, lon: 9.998567, time_offset_ms: 26663},
%Video.TimedPoint{lat: 53.507319, lon: 9.998583, time_offset_ms: 26997},
%Video.TimedPoint{lat: 53.507398, lon: 9.998605, time_offset_ms: 27331},
%Video.TimedPoint{lat: 53.507479, lon: 9.998625, time_offset_ms: 27664},
%Video.TimedPoint{lat: 53.507561, lon: 9.998641, time_offset_ms: 27998},
%Video.TimedPoint{lat: 53.50764, lon: 9.998659, time_offset_ms: 28332},
%Video.TimedPoint{lat: 53.507721, lon: 9.998676, time_offset_ms: 28665},
%Video.TimedPoint{lat: 53.507804, lon: 9.998695, time_offset_ms: 28999},
%Video.TimedPoint{lat: 53.507885, lon: 9.998715, time_offset_ms: 29333},
%Video.TimedPoint{lat: 53.507966, lon: 9.998732, time_offset_ms: 29666},
%Video.TimedPoint{lat: 53.508049, lon: 9.998749, time_offset_ms: 30000},
%Video.TimedPoint{lat: 53.508131, lon: 9.998767, time_offset_ms: 30334},
%Video.TimedPoint{lat: 53.508213, lon: 9.998784, time_offset_ms: 30667},
%Video.TimedPoint{lat: 53.508294, lon: 9.998799, time_offset_ms: 31001},
%Video.TimedPoint{lat: 53.508377, lon: 9.998819, time_offset_ms: 31335},
%Video.TimedPoint{lat: 53.508459, lon: 9.998834, time_offset_ms: 31668},
%Video.TimedPoint{lat: 53.508537, lon: 9.99885, time_offset_ms: 32002},
%Video.TimedPoint{lat: 53.508613, lon: 9.998871, time_offset_ms: 32336},
%Video.TimedPoint{lat: 53.508689, lon: 9.998887, time_offset_ms: 32669},
%Video.TimedPoint{lat: 53.508769, lon: 9.998905, time_offset_ms: 33003},
%Video.TimedPoint{lat: 53.50885, lon: 9.99891, time_offset_ms: 33337},
%Video.TimedPoint{lat: 53.508929, lon: 9.998918, time_offset_ms: 33670},
%Video.TimedPoint{lat: 53.509011, lon: 9.998932, time_offset_ms: 34004},
%Video.TimedPoint{lat: 53.509095, lon: 9.998953, time_offset_ms: 34338},
%Video.TimedPoint{lat: 53.509175, lon: 9.998967, time_offset_ms: 34671},
%Video.TimedPoint{lat: 53.509259, lon: 9.998975, time_offset_ms: 35005},
%Video.TimedPoint{lat: 53.509344, lon: 9.998984, time_offset_ms: 35339},
%Video.TimedPoint{lat: 53.509426, lon: 9.998997, time_offset_ms: 35672},
%Video.TimedPoint{lat: 53.509508, lon: 9.999011, time_offset_ms: 36006},
%Video.TimedPoint{lat: 53.509588, lon: 9.999031, time_offset_ms: 36340},
%Video.TimedPoint{lat: 53.509666, lon: 9.999043, time_offset_ms: 36673},
%Video.TimedPoint{lat: 53.509746, lon: 9.999053, time_offset_ms: 37007},
%Video.TimedPoint{lat: 53.509824, lon: 9.99906, time_offset_ms: 37341},
%Video.TimedPoint{lat: 53.509899, lon: 9.999069, time_offset_ms: 37674},
%Video.TimedPoint{lat: 53.509976, lon: 9.999074, time_offset_ms: 38008},
%Video.TimedPoint{lat: 53.510055, lon: 9.99908, time_offset_ms: 38342},
%Video.TimedPoint{lat: 53.510132, lon: 9.999094, time_offset_ms: 38675},
%Video.TimedPoint{lat: 53.510209, lon: 9.999108, time_offset_ms: 39009},
%Video.TimedPoint{lat: 53.51029, lon: 9.999115, time_offset_ms: 39343},
%Video.TimedPoint{lat: 53.510369, lon: 9.999123, time_offset_ms: 39676},
%Video.TimedPoint{lat: 53.510448, lon: 9.999136, time_offset_ms: 40010},
%Video.TimedPoint{lat: 53.510528, lon: 9.999151, time_offset_ms: 40344},
%Video.TimedPoint{lat: 53.51061, lon: 9.999161, time_offset_ms: 40677},
%Video.TimedPoint{lat: 53.510692, lon: 9.999171, time_offset_ms: 41011},
%Video.TimedPoint{lat: 53.510774, lon: 9.999177, time_offset_ms: 41345},
%Video.TimedPoint{lat: 53.510854, lon: 9.999177, time_offset_ms: 41678},
%Video.TimedPoint{lat: 53.51093, lon: 9.999181, time_offset_ms: 42012},
%Video.TimedPoint{lat: 53.511008, lon: 9.99919, time_offset_ms: 42346},
%Video.TimedPoint{lat: 53.511085, lon: 9.999203, time_offset_ms: 42679},
%Video.TimedPoint{lat: 53.511164, lon: 9.999218, time_offset_ms: 43013},
%Video.TimedPoint{lat: 53.511238, lon: 9.999231, time_offset_ms: 43347},
%Video.TimedPoint{lat: 53.511312, lon: 9.999245, time_offset_ms: 43680},
%Video.TimedPoint{lat: 53.511386, lon: 9.999255, time_offset_ms: 44014},
%Video.TimedPoint{lat: 53.511463, lon: 9.999267, time_offset_ms: 44348},
%Video.TimedPoint{lat: 53.511539, lon: 9.999291, time_offset_ms: 44681},
%Video.TimedPoint{lat: 53.51161, lon: 9.999312, time_offset_ms: 45015},
%Video.TimedPoint{lat: 53.511677, lon: 9.99934, time_offset_ms: 45349},
%Video.TimedPoint{lat: 53.51175, lon: 9.999364, time_offset_ms: 45682},
%Video.TimedPoint{lat: 53.51183, lon: 9.999381, time_offset_ms: 46016},
%Video.TimedPoint{lat: 53.511915, lon: 9.999401, time_offset_ms: 46350},
%Video.TimedPoint{lat: 53.511999, lon: 9.999426, time_offset_ms: 46683},
%Video.TimedPoint{lat: 53.51208, lon: 9.999453, time_offset_ms: 47017},
%Video.TimedPoint{lat: 53.512158, lon: 9.999476, time_offset_ms: 47351},
%Video.TimedPoint{lat: 53.512232, lon: 9.999497, time_offset_ms: 47684},
%Video.TimedPoint{lat: 53.512306, lon: 9.99952, time_offset_ms: 48018},
%Video.TimedPoint{lat: 53.512387, lon: 9.999539, time_offset_ms: 48352},
%Video.TimedPoint{lat: 53.512463, lon: 9.999559, time_offset_ms: 48685},
%Video.TimedPoint{lat: 53.512537, lon: 9.999584, time_offset_ms: 49019},
%Video.TimedPoint{lat: 53.512614, lon: 9.999608, time_offset_ms: 49353},
%Video.TimedPoint{lat: 53.512689, lon: 9.999632, time_offset_ms: 49686},
%Video.TimedPoint{lat: 53.512768, lon: 9.999663, time_offset_ms: 50020},
%Video.TimedPoint{lat: 53.512849, lon: 9.999694, time_offset_ms: 50354},
%Video.TimedPoint{lat: 53.512931, lon: 9.999718, time_offset_ms: 50687},
%Video.TimedPoint{lat: 53.513011, lon: 9.999742, time_offset_ms: 51021},
%Video.TimedPoint{lat: 53.513092, lon: 9.999765, time_offset_ms: 51355},
%Video.TimedPoint{lat: 53.513175, lon: 9.999789, time_offset_ms: 51688},
%Video.TimedPoint{lat: 53.513257, lon: 9.999812, time_offset_ms: 52022},
%Video.TimedPoint{lat: 53.51334, lon: 9.999836, time_offset_ms: 52356},
%Video.TimedPoint{lat: 53.513421, lon: 9.999859, time_offset_ms: 52689},
%Video.TimedPoint{lat: 53.513501, lon: 9.999888, time_offset_ms: 53023},
%Video.TimedPoint{lat: 53.513583, lon: 9.999908, time_offset_ms: 53357},
%Video.TimedPoint{lat: 53.513661, lon: 9.999929, time_offset_ms: 53690},
%Video.TimedPoint{lat: 53.513739, lon: 9.999952, time_offset_ms: 54024},
%Video.TimedPoint{lat: 53.513816, lon: 9.999972, time_offset_ms: 54358},
%Video.TimedPoint{lat: 53.513889, lon: 9.999992, time_offset_ms: 54691},
%Video.TimedPoint{lat: 53.513965, lon: 10.000013, time_offset_ms: 55025},
%Video.TimedPoint{lat: 53.514041, lon: 10.000042, time_offset_ms: 55359},
%Video.TimedPoint{lat: 53.514117, lon: 10.000073, time_offset_ms: 55692},
%Video.TimedPoint{lat: 53.514194, lon: 10.0001, time_offset_ms: 56026},
%Video.TimedPoint{lat: 53.514268, lon: 10.000128, time_offset_ms: 56360},
%Video.TimedPoint{lat: 53.514341, lon: 10.000158, time_offset_ms: 56693},
%Video.TimedPoint{lat: 53.514408, lon: 10.000194, time_offset_ms: 57027},
%Video.TimedPoint{lat: 53.514471, lon: 10.000234, time_offset_ms: 57361},
%Video.TimedPoint{lat: 53.514533, lon: 10.000275, time_offset_ms: 57694},
%Video.TimedPoint{lat: 53.514595, lon: 10.000312, time_offset_ms: 58028},
%Video.TimedPoint{lat: 53.514661, lon: 10.000338, time_offset_ms: 58362},
%Video.TimedPoint{lat: 53.514722, lon: 10.000372, time_offset_ms: 58695},
%Video.TimedPoint{lat: 53.514775, lon: 10.000412, time_offset_ms: 59029},
%Video.TimedPoint{lat: 53.514823, lon: 10.000463, time_offset_ms: 59363},
%Video.TimedPoint{lat: 53.514869, lon: 10.000503, time_offset_ms: 59696},
%Video.TimedPoint{lat: 53.514914, lon: 10.000541, time_offset_ms: 60030},
%Video.TimedPoint{lat: 53.514956, lon: 10.000581, time_offset_ms: 60364},
%Video.TimedPoint{lat: 53.51499, lon: 10.000627, time_offset_ms: 60697},
%Video.TimedPoint{lat: 53.515034, lon: 10.000668, time_offset_ms: 61031},
%Video.TimedPoint{lat: 53.515082, lon: 10.000704, time_offset_ms: 61365},
%Video.TimedPoint{lat: 53.515127, lon: 10.000733, time_offset_ms: 61698},
%Video.TimedPoint{lat: 53.515168, lon: 10.000759, time_offset_ms: 62032},
%Video.TimedPoint{lat: 53.515212, lon: 10.000789, time_offset_ms: 62366},
%Video.TimedPoint{lat: 53.515265, lon: 10.000826, time_offset_ms: 62699},
%Video.TimedPoint{lat: 53.515324, lon: 10.000864, time_offset_ms: 63033},
%Video.TimedPoint{lat: 53.515387, lon: 10.000906, time_offset_ms: 63367},
%Video.TimedPoint{lat: 53.515447, lon: 10.00095, time_offset_ms: 63700},
%Video.TimedPoint{lat: 53.515499, lon: 10.001021, time_offset_ms: 64034},
%Video.TimedPoint{lat: 53.515515, lon: 10.001121, time_offset_ms: 64368},
%Video.TimedPoint{lat: 53.515498, lon: 10.001219, time_offset_ms: 64701},
%Video.TimedPoint{lat: 53.515475, lon: 10.001318, time_offset_ms: 65035},
%Video.TimedPoint{lat: 53.515445, lon: 10.00141, time_offset_ms: 65369},
%Video.TimedPoint{lat: 53.515405, lon: 10.001499, time_offset_ms: 65702},
%Video.TimedPoint{lat: 53.515356, lon: 10.001586, time_offset_ms: 66036},
%Video.TimedPoint{lat: 53.515304, lon: 10.001672, time_offset_ms: 66370},
%Video.TimedPoint{lat: 53.515253, lon: 10.001768, time_offset_ms: 66703},
%Video.TimedPoint{lat: 53.515219, lon: 10.001886, time_offset_ms: 67037},
%Video.TimedPoint{lat: 53.515209, lon: 10.002022, time_offset_ms: 67371},
%Video.TimedPoint{lat: 53.515218, lon: 10.002161, time_offset_ms: 67704},
%Video.TimedPoint{lat: 53.515243, lon: 10.002297, time_offset_ms: 68038},
%Video.TimedPoint{lat: 53.515276, lon: 10.002437, time_offset_ms: 68372},
%Video.TimedPoint{lat: 53.515305, lon: 10.002577, time_offset_ms: 68705},
%Video.TimedPoint{lat: 53.515333, lon: 10.00272, time_offset_ms: 69039},
%Video.TimedPoint{lat: 53.51536, lon: 10.00286, time_offset_ms: 69373},
%Video.TimedPoint{lat: 53.515385, lon: 10.003002, time_offset_ms: 69706},
%Video.TimedPoint{lat: 53.515412, lon: 10.003143, time_offset_ms: 70040},
%Video.TimedPoint{lat: 53.515442, lon: 10.003284, time_offset_ms: 70374},
%Video.TimedPoint{lat: 53.515483, lon: 10.003417, time_offset_ms: 70707},
%Video.TimedPoint{lat: 53.515533, lon: 10.00354, time_offset_ms: 71041},
%Video.TimedPoint{lat: 53.515587, lon: 10.003658, time_offset_ms: 71375},
%Video.TimedPoint{lat: 53.515642, lon: 10.003774, time_offset_ms: 71708},
%Video.TimedPoint{lat: 53.515697, lon: 10.003889, time_offset_ms: 72042},
%Video.TimedPoint{lat: 53.515747, lon: 10.004005, time_offset_ms: 72376},
%Video.TimedPoint{lat: 53.515797, lon: 10.004119, time_offset_ms: 72709},
%Video.TimedPoint{lat: 53.515843, lon: 10.004237, time_offset_ms: 73043},
%Video.TimedPoint{lat: 53.515885, lon: 10.004361, time_offset_ms: 73377},
%Video.TimedPoint{lat: 53.515921, lon: 10.004492, time_offset_ms: 73710},
%Video.TimedPoint{lat: 53.515948, lon: 10.00463, time_offset_ms: 74044},
%Video.TimedPoint{lat: 53.515971, lon: 10.004772, time_offset_ms: 74378},
%Video.TimedPoint{lat: 53.515992, lon: 10.004912, time_offset_ms: 74711},
%Video.TimedPoint{lat: 53.516013, lon: 10.005049, time_offset_ms: 75045},
%Video.TimedPoint{lat: 53.516029, lon: 10.005184, time_offset_ms: 75379},
%Video.TimedPoint{lat: 53.516046, lon: 10.005317, time_offset_ms: 75712},
%Video.TimedPoint{lat: 53.51607, lon: 10.00545, time_offset_ms: 76046},
%Video.TimedPoint{lat: 53.516104, lon: 10.005582, time_offset_ms: 76380},
%Video.TimedPoint{lat: 53.516133, lon: 10.005717, time_offset_ms: 76713},
%Video.TimedPoint{lat: 53.51615, lon: 10.005848, time_offset_ms: 77047},
%Video.TimedPoint{lat: 53.516163, lon: 10.005983, time_offset_ms: 77381},
%Video.TimedPoint{lat: 53.516181, lon: 10.006114, time_offset_ms: 77714},
%Video.TimedPoint{lat: 53.516201, lon: 10.006243, time_offset_ms: 78048},
%Video.TimedPoint{lat: 53.51622, lon: 10.006375, time_offset_ms: 78382},
%Video.TimedPoint{lat: 53.516244, lon: 10.006504, time_offset_ms: 78715},
%Video.TimedPoint{lat: 53.516271, lon: 10.006638, time_offset_ms: 79049},
%Video.TimedPoint{lat: 53.516297, lon: 10.006773, time_offset_ms: 79383},
%Video.TimedPoint{lat: 53.516324, lon: 10.006908, time_offset_ms: 79716},
%Video.TimedPoint{lat: 53.516347, lon: 10.007049, time_offset_ms: 80050},
%Video.TimedPoint{lat: 53.516369, lon: 10.007188, time_offset_ms: 80384},
%Video.TimedPoint{lat: 53.51639, lon: 10.007321, time_offset_ms: 80717},
%Video.TimedPoint{lat: 53.516413, lon: 10.007451, time_offset_ms: 81051},
%Video.TimedPoint{lat: 53.51644, lon: 10.007583, time_offset_ms: 81385},
%Video.TimedPoint{lat: 53.516463, lon: 10.007726, time_offset_ms: 81718},
%Video.TimedPoint{lat: 53.516485, lon: 10.00787, time_offset_ms: 82052},
%Video.TimedPoint{lat: 53.516511, lon: 10.008009, time_offset_ms: 82386},
%Video.TimedPoint{lat: 53.51654, lon: 10.008151, time_offset_ms: 82719},
%Video.TimedPoint{lat: 53.516567, lon: 10.008293, time_offset_ms: 83053},
%Video.TimedPoint{lat: 53.516596, lon: 10.008433, time_offset_ms: 83387},
%Video.TimedPoint{lat: 53.516625, lon: 10.008572, time_offset_ms: 83720},
%Video.TimedPoint{lat: 53.51665, lon: 10.008708, time_offset_ms: 84054},
%Video.TimedPoint{lat: 53.516675, lon: 10.008844, time_offset_ms: 84388},
%Video.TimedPoint{lat: 53.516699, lon: 10.008977, time_offset_ms: 84721},
%Video.TimedPoint{lat: 53.516724, lon: 10.009112, time_offset_ms: 85055},
%Video.TimedPoint{lat: 53.51675, lon: 10.009246, time_offset_ms: 85389},
%Video.TimedPoint{lat: 53.516777, lon: 10.00938, time_offset_ms: 85722},
%Video.TimedPoint{lat: 53.516801, lon: 10.009512, time_offset_ms: 86056},
%Video.TimedPoint{lat: 53.516818, lon: 10.009646, time_offset_ms: 86390},
%Video.TimedPoint{lat: 53.516814, lon: 10.009777, time_offset_ms: 86723},
%Video.TimedPoint{lat: 53.516802, lon: 10.009897, time_offset_ms: 87057},
%Video.TimedPoint{lat: 53.516816, lon: 10.009983, time_offset_ms: 87391},
%Video.TimedPoint{lat: 53.516852, lon: 10.010052, time_offset_ms: 87724},
%Video.TimedPoint{lat: 53.516881, lon: 10.010133, time_offset_ms: 88058},
%Video.TimedPoint{lat: 53.516915, lon: 10.010232, time_offset_ms: 88392},
%Video.TimedPoint{lat: 53.51694, lon: 10.01029, time_offset_ms: 88725},
%Video.TimedPoint{lat: 53.516953, lon: 10.010315, time_offset_ms: 89059},
%Video.TimedPoint{lat: 53.516994, lon: 10.010354, time_offset_ms: 89393},
%Video.TimedPoint{lat: 53.517026, lon: 10.01042, time_offset_ms: 89726},
%Video.TimedPoint{lat: 53.517046, lon: 10.010529, time_offset_ms: 90060},
%Video.TimedPoint{lat: 53.517066, lon: 10.010717, time_offset_ms: 90394},
%Video.TimedPoint{lat: 53.517097, lon: 10.010901, time_offset_ms: 90727},
%Video.TimedPoint{lat: 53.517113, lon: 10.011089, time_offset_ms: 91061},
%Video.TimedPoint{lat: 53.517118, lon: 10.011258, time_offset_ms: 91395},
%Video.TimedPoint{lat: 53.517139, lon: 10.011411, time_offset_ms: 91728},
%Video.TimedPoint{lat: 53.517173, lon: 10.011551, time_offset_ms: 92062},
%Video.TimedPoint{lat: 53.51723, lon: 10.011658, time_offset_ms: 92396},
%Video.TimedPoint{lat: 53.517289, lon: 10.011769, time_offset_ms: 92729},
%Video.TimedPoint{lat: 53.517324, lon: 10.011907, time_offset_ms: 93063},
%Video.TimedPoint{lat: 53.517347, lon: 10.012049, time_offset_ms: 93397},
%Video.TimedPoint{lat: 53.517376, lon: 10.012191, time_offset_ms: 93730},
%Video.TimedPoint{lat: 53.517413, lon: 10.01233, time_offset_ms: 94064},
%Video.TimedPoint{lat: 53.517461, lon: 10.012469, time_offset_ms: 94398},
%Video.TimedPoint{lat: 53.517504, lon: 10.012599, time_offset_ms: 94731},
%Video.TimedPoint{lat: 53.517549, lon: 10.012721, time_offset_ms: 95065},
%Video.TimedPoint{lat: 53.517593, lon: 10.012843, time_offset_ms: 95399},
%Video.TimedPoint{lat: 53.517634, lon: 10.012958, time_offset_ms: 95732},
%Video.TimedPoint{lat: 53.517687, lon: 10.013075, time_offset_ms: 96066},
%Video.TimedPoint{lat: 53.517739, lon: 10.013189, time_offset_ms: 96400},
%Video.TimedPoint{lat: 53.517801, lon: 10.013291, time_offset_ms: 96733},
%Video.TimedPoint{lat: 53.51786, lon: 10.013381, time_offset_ms: 97067},
%Video.TimedPoint{lat: 53.517928, lon: 10.013466, time_offset_ms: 97401},
%Video.TimedPoint{lat: 53.517995, lon: 10.013553, time_offset_ms: 97734},
%Video.TimedPoint{lat: 53.518053, lon: 10.013656, time_offset_ms: 98068},
%Video.TimedPoint{lat: 53.518112, lon: 10.013765, time_offset_ms: 98402},
%Video.TimedPoint{lat: 53.518178, lon: 10.013865, time_offset_ms: 98735},
%Video.TimedPoint{lat: 53.518243, lon: 10.013959, time_offset_ms: 99069},
%Video.TimedPoint{lat: 53.518307, lon: 10.014052, time_offset_ms: 99403},
%Video.TimedPoint{lat: 53.518372, lon: 10.014145, time_offset_ms: 99736},
%Video.TimedPoint{lat: 53.518437, lon: 10.014233, time_offset_ms: 100_070},
%Video.TimedPoint{lat: 53.518502, lon: 10.014324, time_offset_ms: 100_404},
%Video.TimedPoint{lat: 53.51857, lon: 10.014413, time_offset_ms: 100_737},
%Video.TimedPoint{lat: 53.518638, lon: 10.014487, time_offset_ms: 101_071},
%Video.TimedPoint{lat: 53.518707, lon: 10.014559, time_offset_ms: 101_405},
%Video.TimedPoint{lat: 53.518776, lon: 10.014627, time_offset_ms: 101_738},
%Video.TimedPoint{lat: 53.518847, lon: 10.014696, time_offset_ms: 102_072},
%Video.TimedPoint{lat: 53.518912, lon: 10.014766, time_offset_ms: 102_406},
%Video.TimedPoint{lat: 53.518976, lon: 10.01483, time_offset_ms: 102_739},
%Video.TimedPoint{lat: 53.51904, lon: 10.014887, time_offset_ms: 103_073},
%Video.TimedPoint{lat: 53.519109, lon: 10.014948, time_offset_ms: 103_407},
%Video.TimedPoint{lat: 53.519179, lon: 10.015005, time_offset_ms: 103_740},
%Video.TimedPoint{lat: 53.519244, lon: 10.015063, time_offset_ms: 104_074},
%Video.TimedPoint{lat: 53.519312, lon: 10.015113, time_offset_ms: 104_408},
%Video.TimedPoint{lat: 53.519381, lon: 10.015151, time_offset_ms: 104_741},
%Video.TimedPoint{lat: 53.519446, lon: 10.015176, time_offset_ms: 105_075},
%Video.TimedPoint{lat: 53.519513, lon: 10.015206, time_offset_ms: 105_409},
%Video.TimedPoint{lat: 53.519579, lon: 10.015232, time_offset_ms: 105_742},
%Video.TimedPoint{lat: 53.519642, lon: 10.015248, time_offset_ms: 106_076},
%Video.TimedPoint{lat: 53.519701, lon: 10.015263, time_offset_ms: 106_410},
%Video.TimedPoint{lat: 53.51976, lon: 10.015278, time_offset_ms: 106_743},
%Video.TimedPoint{lat: 53.519818, lon: 10.015294, time_offset_ms: 107_077},
%Video.TimedPoint{lat: 53.519882, lon: 10.015303, time_offset_ms: 107_411},
%Video.TimedPoint{lat: 53.519948, lon: 10.015304, time_offset_ms: 107_744},
%Video.TimedPoint{lat: 53.520012, lon: 10.0153, time_offset_ms: 108_078},
%Video.TimedPoint{lat: 53.520081, lon: 10.015294, time_offset_ms: 108_412},
%Video.TimedPoint{lat: 53.520152, lon: 10.015288, time_offset_ms: 108_745},
%Video.TimedPoint{lat: 53.52022, lon: 10.01528, time_offset_ms: 109_079},
%Video.TimedPoint{lat: 53.520287, lon: 10.015255, time_offset_ms: 109_413},
%Video.TimedPoint{lat: 53.520355, lon: 10.015217, time_offset_ms: 109_746},
%Video.TimedPoint{lat: 53.520422, lon: 10.015192, time_offset_ms: 110_080},
%Video.TimedPoint{lat: 53.520489, lon: 10.01518, time_offset_ms: 110_414},
%Video.TimedPoint{lat: 53.520555, lon: 10.015175, time_offset_ms: 110_747},
%Video.TimedPoint{lat: 53.520617, lon: 10.015164, time_offset_ms: 111_081},
%Video.TimedPoint{lat: 53.520668, lon: 10.015153, time_offset_ms: 111_415},
%Video.TimedPoint{lat: 53.520717, lon: 10.01514, time_offset_ms: 111_748},
%Video.TimedPoint{lat: 53.520752, lon: 10.015135, time_offset_ms: 112_082},
%Video.TimedPoint{lat: 53.520779, lon: 10.015129, time_offset_ms: 112_416},
%Video.TimedPoint{lat: 53.520805, lon: 10.015123, time_offset_ms: 112_749},
%Video.TimedPoint{lat: 53.520831, lon: 10.015115, time_offset_ms: 113_083},
%Video.TimedPoint{lat: 53.520854, lon: 10.015105, time_offset_ms: 113_417},
%Video.TimedPoint{lat: 53.520873, lon: 10.015095, time_offset_ms: 113_750},
%Video.TimedPoint{lat: 53.520884, lon: 10.015091, time_offset_ms: 114_084},
%Video.TimedPoint{lat: 53.520893, lon: 10.015088, time_offset_ms: 114_169},
%Video.TimedPoint{lat: 53.520907, lon: 10.01509, time_offset_ms: 114_503},
%Video.TimedPoint{lat: 53.520942, lon: 10.015082, time_offset_ms: 114_836},
%Video.TimedPoint{lat: 53.520984, lon: 10.01507, time_offset_ms: 115_170},
%Video.TimedPoint{lat: 53.521024, lon: 10.015061, time_offset_ms: 115_504},
%Video.TimedPoint{lat: 53.521055, lon: 10.015054, time_offset_ms: 115_837},
%Video.TimedPoint{lat: 53.521081, lon: 10.01505, time_offset_ms: 116_171},
%Video.TimedPoint{lat: 53.521105, lon: 10.015039, time_offset_ms: 116_505},
%Video.TimedPoint{lat: 53.521127, lon: 10.015025, time_offset_ms: 116_838},
%Video.TimedPoint{lat: 53.521146, lon: 10.015009, time_offset_ms: 117_172},
%Video.TimedPoint{lat: 53.521161, lon: 10.014998, time_offset_ms: 117_505},
%Video.TimedPoint{lat: 53.521174, lon: 10.014989, time_offset_ms: 117_839},
%Video.TimedPoint{lat: 53.521182, lon: 10.014985, time_offset_ms: 118_173},
%Video.TimedPoint{lat: 53.521205, lon: 10.014932, time_offset_ms: 118_258},
%Video.TimedPoint{lat: 53.52122, lon: 10.014925, time_offset_ms: 118_592},
%Video.TimedPoint{lat: 53.521257, lon: 10.014899, time_offset_ms: 118_925},
%Video.TimedPoint{lat: 53.521296, lon: 10.014871, time_offset_ms: 119_259},
%Video.TimedPoint{lat: 53.521327, lon: 10.014888, time_offset_ms: 119_592},
%Video.TimedPoint{lat: 53.521333, lon: 10.014954, time_offset_ms: 119_926},
%Video.TimedPoint{lat: 53.521337, lon: 10.015038, time_offset_ms: 120_259},
%Video.TimedPoint{lat: 53.521344, lon: 10.015118, time_offset_ms: 120_593},
%Video.TimedPoint{lat: 53.521355, lon: 10.015179, time_offset_ms: 120_927},
%Video.TimedPoint{lat: 53.52137, lon: 10.015212, time_offset_ms: 121_260},
%Video.TimedPoint{lat: 53.521367, lon: 10.015247, time_offset_ms: 121_345},
%Video.TimedPoint{lat: 53.521374, lon: 10.015257, time_offset_ms: 121_679},
%Video.TimedPoint{lat: 53.521401, lon: 10.015292, time_offset_ms: 122_012},
%Video.TimedPoint{lat: 53.52144, lon: 10.015292, time_offset_ms: 122_346},
%Video.TimedPoint{lat: 53.521484, lon: 10.01524, time_offset_ms: 122_679},
%Video.TimedPoint{lat: 53.521536, lon: 10.015184, time_offset_ms: 123_013},
%Video.TimedPoint{lat: 53.521601, lon: 10.015144, time_offset_ms: 123_347},
%Video.TimedPoint{lat: 53.521671, lon: 10.015127, time_offset_ms: 123_680},
%Video.TimedPoint{lat: 53.521747, lon: 10.015115, time_offset_ms: 124_014},
%Video.TimedPoint{lat: 53.521825, lon: 10.0151, time_offset_ms: 124_347},
%Video.TimedPoint{lat: 53.521885982035926, lon: 10.015094383233533, time_offset_ms: 124_615}
]
end
@impl Video.Rendered
def(rendered?()) do
true
end
end | 74.185446 | 98 | 0.698446 |
73ae08dc72bbdbf3a71e8f2e5f53e98c96cb2d8f | 1,799 | exs | Elixir | test/teslamate/vehicles/vehicle/charging_sync_test.exs | ograff/teslamate | 677891833623df115c5d4fc8278c298697c45a61 | [
"MIT"
] | null | null | null | test/teslamate/vehicles/vehicle/charging_sync_test.exs | ograff/teslamate | 677891833623df115c5d4fc8278c298697c45a61 | [
"MIT"
] | 1 | 2021-05-12T00:04:50.000Z | 2021-05-12T00:04:50.000Z | test/teslamate/vehicles/vehicle/charging_sync_test.exs | ograff/teslamate | 677891833623df115c5d4fc8278c298697c45a61 | [
"MIT"
] | 1 | 2019-10-24T13:17:57.000Z | 2019-10-24T13:17:57.000Z | defmodule TeslaMate.Vehicles.Vehicle.ChargingSyncTest do
use TeslaMate.DataCase
use TeslaMate.VehicleCase
import ExUnit.CaptureLog
alias TeslaMate.Log
@log_opts format: "[$level] $message\n",
colors: [enabled: false]
@tag :capture_log
test "handles invalid charge data", %{test: name} do
car = car_fixture()
now_ts = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
events = [
{:ok, online_event()},
{:ok, online_event(drive_state: %{timestamp: now_ts, latitude: 0.0, longitude: 0.0})},
{:ok, charging_event(now_ts, "Charging", 0.1, range: nil)},
{:ok, charging_event(now_ts, "Charging", 0.1, range: nil)},
{:ok, charging_event(now_ts, "Charging", 0.2, range: 10)}
]
assert capture_log(@log_opts, fn ->
:ok = start_vehicle(name, events, car: car, log: false)
true =
name
|> Process.whereis()
|> Process.link()
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :online}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :charging}}}
assert_receive {:pubsub, {:broadcast, _, _, %Summary{state: :charging}}}
refute_receive _
end) =~
"""
[warn] Invalid charge data: %{ideal_battery_range_km: [\"can't be blank\"]}
[warn] Invalid charge data: %{ideal_battery_range_km: [\"can't be blank\"]}
"""
end
defp car_fixture(attrs \\ %{}) do
{:ok, car} =
attrs
|> Enum.into(%{
efficiency: 0.153,
eid: 13442,
model: "S",
vid: 13442,
name: "foo",
trim_badging: "P100D",
vin: "13412345F"
})
|> Log.create_car()
car
end
end
| 29.016129 | 92 | 0.558088 |
73ae3547efc2878442d37b4ac87c39eaba9ba6b5 | 1,002 | ex | Elixir | lib/logger_backend_sqlite/log.ex | ConnorRigby/logger_backend_sqlite | 3a6508e5342265548c91f8505dff9b8093e1f8ce | [
"MIT"
] | 5 | 2018-09-12T19:29:38.000Z | 2019-04-04T01:18:32.000Z | lib/logger_backend_sqlite/log.ex | ConnorRigby/logger_backend_sqlite | 3a6508e5342265548c91f8505dff9b8093e1f8ce | [
"MIT"
] | 1 | 2019-04-04T09:41:40.000Z | 2019-04-04T16:39:51.000Z | lib/logger_backend_sqlite/log.ex | ConnorRigby/logger_backend_sqlite | 3a6508e5342265548c91f8505dff9b8093e1f8ce | [
"MIT"
] | null | null | null | defmodule LoggerBackendSqlite.Log do
@moduledoc false
@default_meta [
:application,
:module,
:function,
:file,
:line,
:registered_name
]
defstruct [
:id,
:level,
:group_leader_node,
:message,
:logged_at_ndt,
:logged_at_dt,
:inserted_at,
:updated_at
] ++ @default_meta
@type t :: %__MODULE__{
id: 0 | pos_integer(),
level: String.t(),
group_leader_node: nil | String.t(),
message: String.t(),
logged_at_ndt: nil | NaiveDateTime.t(),
logged_at_dt: nil | DateTime.t(),
inserted_at: DateTime.t(),
updated_at: DateTime.t(),
application: nil | String.t(),
module: nil | String.t(),
function: nil | String.t(),
file: nil | Path.t(),
line: nil | pos_integer(),
registered_name: nil | String.t()
}
end
| 24.439024 | 49 | 0.492016 |
73ae577db1b6158ec74aefcab02831dc7dc58739 | 1,898 | ex | Elixir | apps/tai/lib/tai/commands/advisors.ex | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | 1 | 2019-12-19T05:16:26.000Z | 2019-12-19T05:16:26.000Z | apps/tai/lib/tai/commands/advisors.ex | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | null | null | null | apps/tai/lib/tai/commands/advisors.ex | ihorkatkov/tai | 09f9f15d2c385efe762ae138a8570f1e3fd41f26 | [
"MIT"
] | 1 | 2020-05-03T23:32:11.000Z | 2020-05-03T23:32:11.000Z | defmodule Tai.Commands.Advisors do
import Tai.Commands.Table, only: [render!: 2]
@header [
"Group ID",
"Advisor ID",
"Status",
"PID"
]
@spec list() :: no_return
@spec list(list) :: no_return
def list(args \\ []) do
store_id = Keyword.get(args, :store_id, Tai.Advisors.Store.default_store_id())
filters = Keyword.get(args, :where, [])
order_by = Keyword.get(args, :order, [:group_id, :advisor_id])
filters
|> Tai.Advisors.Instances.where(store_id)
|> Enumerati.order(order_by)
|> format_rows()
|> render!(@header)
end
@spec start() :: no_return
@spec start(list) :: no_return
def start(args \\ []) do
store_id = Keyword.get(args, :store_id, Tai.Advisors.Store.default_store_id())
filters = Keyword.get(args, :where, [])
{started, already_started} =
filters
|> Tai.Advisors.Instances.where(store_id)
|> Tai.Advisors.Instances.start()
IO.puts("Started advisors: #{started} new, #{already_started} already running")
IEx.dont_display_result()
end
@spec stop() :: no_return
@spec stop(list) :: no_return
def stop(args \\ []) do
store_id = Keyword.get(args, :store_id, Tai.Advisors.Store.default_store_id())
filters = Keyword.get(args, :where, [])
{stopped, already_stopped} =
filters
|> Tai.Advisors.Instances.where(store_id)
|> Tai.Advisors.Instances.stop()
IO.puts("Stopped advisors: #{stopped} new, #{already_stopped} already stopped")
IEx.dont_display_result()
end
defp format_rows(instances) do
instances
|> Enum.map(fn instance ->
[
instance.group_id,
instance.advisor_id,
instance.status,
instance.pid |> format_col
]
end)
end
defp format_col(val) when is_pid(val) or is_map(val), do: val |> inspect()
defp format_col(nil), do: "-"
defp format_col(val), do: val
end
| 26.732394 | 83 | 0.639621 |
73ae843e71cde15a627a54622d8fc16e510904f8 | 159 | ex | Elixir | testData/org/elixir_lang/reference/callable/issue_1270/outer_module_relative_qualifier.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/reference/callable/issue_1270/outer_module_relative_qualifier.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/reference/callable/issue_1270/outer_module_relative_qualifier.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | defmodule Autocomplete do
defmodule State do
def another_test do
end
end
def test do
State.<caret>
end
defp internal_test do
end
end
| 11.357143 | 25 | 0.685535 |
73aecf7810ae0a3f4aa5b5272dc7db0c2a1a5e68 | 1,487 | exs | Elixir | priv/perf/config/config.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | priv/perf/config/config.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | priv/perf/config/config.exs | boolafish/elixir-omg | 46b568404972f6e4b4da3195d42d4fb622edb934 | [
"Apache-2.0"
] | null | null | null | use Mix.Config
# Better adapter for tesla.
# default httpc would fail when doing post request without param.
# https://github.com/googleapis/elixir-google-api/issues/26#issuecomment-360209019
config :tesla, adapter: Tesla.Adapter.Hackney
ethereum_client_timeout_ms = 20_000
config :ethereumex,
http_options: [recv_timeout: ethereum_client_timeout_ms],
url: System.get_env("ETHEREUM_RPC_URL")
config :load_test,
pool_size: 5000,
max_connection: 5000,
child_chain_url: System.get_env("CHILD_CHAIN_URL"),
watcher_security_url: System.get_env("WATCHER_SECURITY_URL"),
watcher_info_url: System.get_env("WATCHER_INFO_URL"),
faucet_private_key: System.get_env("LOAD_TEST_FAUCET_PRIVATE_KEY"),
eth_vault_address: System.get_env("CONTRACT_ADDRESS_ETH_VAULT"),
erc20_vault_address: System.get_env("CONTRACT_ADDRESS_ERC20_VAULT"),
test_currency: "0x0000000000000000000000000000000000000000",
faucet_deposit_amount: trunc(:math.pow(10, 14)),
fee_amount: 1,
deposit_finality_margin: 10,
gas_price: 2_000_000_000
config :ex_plasma,
eip_712_domain: [
name: "OMG Network",
salt: "0xfad5c7f626d80f9256ef01929f3beb96e058b8b4b0e3fe52d84f054c0e2a7a83",
verifying_contract: System.get_env("CONTRACT_ADDRESS_PLASMA_FRAMEWORK"),
version: "1"
]
config :logger, :console,
format: "$date $time [$level] $metadata⋅$message⋅\n",
discard_threshold: 2000,
metadata: [:module, :function, :request_id, :trace_id, :span_id]
import_config "#{Mix.env()}.exs"
| 34.581395 | 82 | 0.781439 |
73aeffb1b116eb99452504b4fe0bf3c09b5c78ed | 1,231 | ex | Elixir | lib/api_elixir_films_web/views/error_helpers.ex | brandaoplaster/api_elixir_films | 9594761bb0d2463132b904c5adbed6d9664bb7ff | [
"MIT"
] | null | null | null | lib/api_elixir_films_web/views/error_helpers.ex | brandaoplaster/api_elixir_films | 9594761bb0d2463132b904c5adbed6d9664bb7ff | [
"MIT"
] | null | null | null | lib/api_elixir_films_web/views/error_helpers.ex | brandaoplaster/api_elixir_films | 9594761bb0d2463132b904c5adbed6d9664bb7ff | [
"MIT"
] | null | null | null | defmodule ApiElixirFilmsWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(ApiElixirFilmsWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(ApiElixirFilmsWeb.Gettext, "errors", msg, opts)
end
end
end
| 36.205882 | 83 | 0.676686 |
73af20ad222bb43891d18b4d519b2793309c3bb8 | 144 | exs | Elixir | test/broadcast_test.exs | kentaro/broadcast | 4d24d927a146bd57e2ea430978e6d38405d065fd | [
"MIT"
] | null | null | null | test/broadcast_test.exs | kentaro/broadcast | 4d24d927a146bd57e2ea430978e6d38405d065fd | [
"MIT"
] | null | null | null | test/broadcast_test.exs | kentaro/broadcast | 4d24d927a146bd57e2ea430978e6d38405d065fd | [
"MIT"
] | null | null | null | defmodule BroadcastTest do
use ExUnit.Case
doctest Broadcast
test "greets the world" do
assert Broadcast.hello() == :world
end
end
| 16 | 38 | 0.722222 |
73af287fa03940352a3057395a75b649e39d1380 | 1,426 | ex | Elixir | lib/mesh_relay_web/channels/user_socket.ex | NullVoxPopuli/mesh-relay-phoenix | 111bc650709eb6ee63fda8410948c33993a7f033 | [
"MIT"
] | 5 | 2019-03-31T13:02:49.000Z | 2021-01-01T05:18:45.000Z | lib/mesh_relay_web/channels/user_socket.ex | NullVoxPopuli/mesh-relay-phoenix | 111bc650709eb6ee63fda8410948c33993a7f033 | [
"MIT"
] | 4 | 2017-07-16T06:30:49.000Z | 2018-06-22T19:37:13.000Z | lib/mesh_relay_web/channels/user_socket.ex | NullVoxPopuli/mesh-relay-phoenix | 111bc650709eb6ee63fda8410948c33993a7f033 | [
"MIT"
] | 3 | 2017-10-18T00:12:57.000Z | 2021-07-27T08:10:39.000Z | defmodule MeshRelayWeb.UserSocket do
use Phoenix.Socket
require Logger
## Channels
# channel "room:*", MeshRelay.RoomChannel
channel "user:*", MeshRelayWeb.UserChannel
channel "stats", MeshRelayWeb.StatsChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# 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) do
uid = params["uid"]
socket = assign(socket, :uid, uid)
socket = assign(socket, :user_id, uid)
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "users_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# MeshRelay.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil #{}"socket-uid:#{socket.assigns.uid}"
end
| 31.688889 | 83 | 0.69986 |
73af3c8b326142c53f800247d780ed0070d9a1e1 | 906 | ex | Elixir | ex_mon/lib/ex_mon/trainer/pokemon.ex | cesaraugustomt/ExMon_API | c489c0fd5b928b7061102d6776a388dfe7aef8b7 | [
"MIT"
] | null | null | null | ex_mon/lib/ex_mon/trainer/pokemon.ex | cesaraugustomt/ExMon_API | c489c0fd5b928b7061102d6776a388dfe7aef8b7 | [
"MIT"
] | null | null | null | ex_mon/lib/ex_mon/trainer/pokemon.ex | cesaraugustomt/ExMon_API | c489c0fd5b928b7061102d6776a388dfe7aef8b7 | [
"MIT"
] | null | null | null | defmodule ExMon.Trainer.Pokemon do
use Ecto.Schema
import Ecto.Changeset
alias ExMon.Trainer
@primary_key {:id, Ecto.UUID, autogenerate: true}
@foreign_key_type Ecto.UUID
schema "pokemons" do
field :name, :string
field :nickname, :string
field :weight, :integer
field :types, {:array, :string}
belongs_to(:trainer, Trainer)
timestamps()
end
@required [:name, :nickname, :weight, :types, :trainer_id]
def build(params) do
params
|> changeset()
|> apply_action(:insert)
end
def changeset(params) do
%__MODULE__{}
|> cast(params, @required)
|> validate_required(@required)
|> assoc_constraint(:trainer)
|> validate_length(:nickname, min: 2)
end
def update_changeset(pokemon, params) do
pokemon
|> cast(params, [:nickname])
|> validate_required([:nickname])
|> validate_length(:nickname, min: 2)
end
end
| 22.097561 | 60 | 0.664459 |
73af4f0ec6f628f21628d94da9562a08c434123a | 33,843 | exs | Elixir | test/phoenix_live_view/engine_test.exs | nickolaich/phoenix_live_view | 2e9db09b11d42fabfd5a388980ff2b15d11da527 | [
"MIT"
] | null | null | null | test/phoenix_live_view/engine_test.exs | nickolaich/phoenix_live_view | 2e9db09b11d42fabfd5a388980ff2b15d11da527 | [
"MIT"
] | null | null | null | test/phoenix_live_view/engine_test.exs | nickolaich/phoenix_live_view | 2e9db09b11d42fabfd5a388980ff2b15d11da527 | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveView.EngineTest do
use ExUnit.Case, async: true
alias Phoenix.LiveView.{Engine, Rendered}
def safe(do: {:safe, _} = safe), do: safe
def unsafe(do: {:safe, content}), do: content
describe "rendering" do
test "escapes HTML" do
template = """
<start> <%= "<escaped>" %>
"""
assert render(template) == "<start> <escaped>\n"
end
test "escapes HTML from nested content" do
template = """
<%= Phoenix.LiveView.EngineTest.unsafe do %>
<foo>
<% end %>
"""
assert render(template) == "\n <foo>\n\n"
end
test "does not escape safe expressions" do
assert render("Safe <%= {:safe, \"<value>\"} %>") == "Safe <value>"
end
test "nested content is always safe" do
template = """
<%= Phoenix.LiveView.EngineTest.safe do %>
<foo>
<% end %>
"""
assert render(template) == "\n <foo>\n\n"
template = """
<%= Phoenix.LiveView.EngineTest.safe do %>
<%= "<foo>" %>
<% end %>
"""
assert render(template) == "\n <foo>\n\n"
end
test "handles assigns" do
assert render("<%= @foo %>", %{foo: "<hello>"}) == "<hello>"
end
test "supports non-output expressions" do
template = """
<% foo = @foo %>
<%= foo %>
"""
assert render(template, %{foo: "<hello>"}) == "\n<hello>\n"
end
test "supports mixed non-output expressions" do
template = """
prea
<% @foo %>
posta
<%= @foo %>
preb
<% @foo %>
middleb
<% @foo %>
postb
"""
assert render(template, %{foo: "<hello>"}) ==
"prea\n\nposta\n<hello>\npreb\n\nmiddleb\n\npostb\n"
end
test "raises ArgumentError for missing assigns" do
assert_raise ArgumentError,
~r/assign @foo not available in template.*Available assigns: \[:bar\]/s,
fn -> render("<%= @foo %>", %{bar: true}) end
end
end
describe "rendered structure" do
test "contains two static parts and one dynamic" do
%{static: static, dynamic: dynamic} = eval("foo<%= 123 %>bar")
assert dynamic.(true) == ["123"]
assert static == ["foo", "bar"]
end
test "contains one static part at the beginning and one dynamic" do
%{static: static, dynamic: dynamic} = eval("foo<%= 123 %>")
assert dynamic.(true) == ["123"]
assert static == ["foo", ""]
end
test "contains one static part at the end and one dynamic" do
%{static: static, dynamic: dynamic} = eval("<%= 123 %>bar")
assert dynamic.(true) == ["123"]
assert static == ["", "bar"]
end
test "contains one dynamic only" do
%{static: static, dynamic: dynamic} = eval("<%= 123 %>")
assert dynamic.(true) == ["123"]
assert static == ["", ""]
end
test "contains two dynamics only" do
%{static: static, dynamic: dynamic} = eval("<%= 123 %><%= 456 %>")
assert dynamic.(true) == ["123", "456"]
assert static == ["", "", ""]
end
test "contains two static parts and two dynamics" do
%{static: static, dynamic: dynamic} = eval("foo<%= 123 %><%= 456 %>bar")
assert dynamic.(true) == ["123", "456"]
assert static == ["foo", "", "bar"]
end
test "contains three static parts and two dynamics" do
%{static: static, dynamic: dynamic} = eval("foo<%= 123 %>bar<%= 456 %>baz")
assert dynamic.(true) == ["123", "456"]
assert static == ["foo", "bar", "baz"]
end
test "contains optimized comprehensions" do
template = """
before
<%= for point <- @points do %>
x: <%= point.x %>
y: <%= point.y %>
<% end %>
after
"""
%{static: static, dynamic: dynamic} =
eval(template, %{points: [%{x: 1, y: 2}, %{x: 3, y: 4}]})
assert static == ["before\n", "\nafter\n"]
assert [
%Phoenix.LiveView.Comprehension{
static: ["\n x: ", "\n y: ", "\n"],
dynamics: [
["1", "2"],
["3", "4"]
]
}
] = dynamic.(true)
end
end
describe "change tracking" do
test "does not render dynamic if it is unchanged" do
template = "<%= @foo %>"
assert changed(template, %{foo: 123}, nil) == ["123"]
assert changed(template, %{foo: 123}, %{}) == [nil]
assert changed(template, %{foo: 123}, %{foo: true}) == ["123"]
end
test "renders dynamic if any of the assigns change" do
template = "<%= @foo + @bar %>"
assert changed(template, %{foo: 123, bar: 456}, nil) == ["579"]
assert changed(template, %{foo: 123, bar: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: 456}, %{foo: true}) == ["579"]
assert changed(template, %{foo: 123, bar: 456}, %{bar: true}) == ["579"]
end
test "does not render dynamic without assigns" do
template = "<%= 1 + 2 %>"
assert changed(template, %{}, nil) == ["3"]
assert changed(template, %{}, %{}) == [nil]
end
test "does not render dynamic on bitstring modifiers" do
template = "<%= <<@foo::binary>> %>"
assert changed(template, %{foo: "123"}, nil) == ["123"]
assert changed(template, %{foo: "123"}, %{}) == [nil]
assert changed(template, %{foo: "123"}, %{foo: true}) == ["123"]
end
test "renders dynamic without change tracking" do
assert changed("<%= @foo %>", %{foo: 123}, %{foo: true}, false) == ["123"]
assert changed("<%= 1 + 2 %>", %{foo: 123}, %{}, false) == ["3"]
end
test "renders dynamic does not change track underscore" do
assert changed("<%= _ = 123 %>", %{}, nil) == ["123"]
assert changed("<%= _ = 123 %>", %{}, %{}) == [nil]
end
test "renders dynamic with dot tracking" do
template = "<%= @map.foo + @map.bar %>"
old = %{map: %{foo: 123, bar: 456}}
new_augmented = %{map: %{foo: 123, bar: 456, baz: 789}}
new_changed_foo = %{map: %{foo: 321, bar: 456}}
new_changed_bar = %{map: %{foo: 123, bar: 654}}
assert changed(template, old, nil) == ["579"]
assert changed(template, old, %{}) == [nil]
assert changed(template, old, %{map: true}) == ["579"]
assert changed(template, old, old) == [nil]
assert changed(template, new_augmented, old) == [nil]
assert changed(template, new_changed_foo, old) == ["777"]
assert changed(template, new_changed_bar, old) == ["777"]
end
test "renders dynamic with dot tracking 3-levels deeps" do
template = "<%= @root.map.foo + @root.map.bar %>"
old = %{root: %{map: %{foo: 123, bar: 456}}}
new_augmented = %{root: %{map: %{foo: 123, bar: 456, baz: 789}}}
new_changed_foo = %{root: %{map: %{foo: 321, bar: 456}}}
new_changed_bar = %{root: %{map: %{foo: 123, bar: 654}}}
assert changed(template, old, nil) == ["579"]
assert changed(template, old, %{}) == [nil]
assert changed(template, old, %{root: true}) == ["579"]
assert changed(template, old, %{root: %{map: true}}) == ["579"]
assert changed(template, old, old) == [nil]
assert changed(template, new_augmented, old) == [nil]
assert changed(template, new_changed_foo, old) == ["777"]
assert changed(template, new_changed_bar, old) == ["777"]
end
test "renders dynamic with access tracking" do
template = "<%= @not_map[:foo] + @not_map[:bar] %>"
old = %{not_map: [foo: 123, bar: 456]}
new_augmented = %{not_map: [foo: 123, bar: 456, baz: 789]}
new_changed_foo = %{not_map: [foo: 321, bar: 456]}
new_changed_bar = %{not_map: [foo: 123, bar: 654]}
assert changed(template, old, nil) == ["579"]
assert changed(template, old, %{}) == [nil]
assert changed(template, old, %{not_map: true}) == ["579"]
assert changed(template, old, old) == ["579"]
assert changed(template, new_augmented, old) == ["579"]
assert changed(template, new_changed_foo, old) == ["777"]
assert changed(template, new_changed_bar, old) == ["777"]
template = "<%= @map[:foo] + @map[:bar] %>"
old = %{map: %{foo: 123, bar: 456}}
new_augmented = %{map: %{foo: 123, bar: 456, baz: 789}}
new_changed_foo = %{map: %{foo: 321, bar: 456}}
new_changed_bar = %{map: %{foo: 123, bar: 654}}
assert changed(template, old, nil) == ["579"]
assert changed(template, old, %{}) == [nil]
assert changed(template, old, %{map: true}) == ["579"]
assert changed(template, new_augmented, old) == [nil]
assert changed(template, new_changed_foo, old) == ["777"]
assert changed(template, new_changed_bar, old) == ["777"]
end
test "renders dynamic with access tracking inside comprehension" do
template = """
<%= for x <- [:a, :b, :c] do %>
<%= @map[x] %>
<% end %>
"""
old = %{map: [a: 1, b: 2, c: 3]}
assert [%Phoenix.LiveView.Comprehension{}] = changed(template, old, nil)
assert [nil] = changed(template, old, %{})
assert [%Phoenix.LiveView.Comprehension{}] = changed(template, old, %{map: true})
assert [%Phoenix.LiveView.Comprehension{}] = changed(template, old, old)
end
test "renders dynamic if it has variables" do
template = "<%= foo = 1 + 2 %><%= foo %>"
assert changed(template, %{}, nil) == ["3", "3"]
assert changed(template, %{}, %{}) == ["3", "3"]
end
test "does not render dynamic for special variables" do
template = "<%= __MODULE__ %>"
assert changed(template, %{}, nil) == [""]
assert changed(template, %{}, %{}) == [nil]
end
test "renders dynamic if it has variables from assigns" do
template = "<%= foo = @foo %><%= foo %>"
assert changed(template, %{foo: 123}, nil) == ["123", "123"]
assert changed(template, %{foo: 123}, %{}) == ["123", "123"]
assert changed(template, %{foo: 123}, %{foo: true}) == ["123", "123"]
end
test "does not render dynamic if it has variables inside special form" do
template = "<%= cond do foo = @foo -> foo end %>"
assert changed(template, %{foo: 123}, nil) == ["123"]
assert changed(template, %{foo: 123}, %{}) == [nil]
assert changed(template, %{foo: 123}, %{foo: true}) == ["123"]
end
test "renders dynamic if it has variables from outside inside special form" do
template = "<% f = @foo %><%= cond do foo = f -> foo end %>"
assert changed(template, %{foo: 123}, nil) == ["123"]
assert changed(template, %{foo: 123}, %{}) == ["123"]
assert changed(template, %{foo: 123}, %{foo: true}) == ["123"]
end
test "does not render dynamic if it has variables inside unoptimized comprehension" do
template = "<%= for foo <- @foo, do: foo %>"
assert changed(template, %{foo: [1, 2, 3]}, nil) == [[1, 2, 3]]
assert changed(template, %{foo: [1, 2, 3]}, %{}) == [nil]
assert changed(template, %{foo: [1, 2, 3]}, %{foo: true}) == [[1, 2, 3]]
end
test "does not render dynamic if it has variables inside optimized comprehension" do
template = "<%= for foo <- @foo do %><%= foo %><% end %>"
assert [%{dynamics: [["1"], ["2"], ["3"]]}] =
changed(template, %{foo: ["1", "2", "3"]}, nil)
assert [nil] = changed(template, %{foo: ["1", "2", "3"]}, %{})
assert [%{dynamics: [["1"], ["2"], ["3"]]}] =
changed(template, %{foo: ["1", "2", "3"]}, %{foo: true})
end
test "does not render dynamic if it has a variable after a condition inside optimized comprehension" do
template =
"<%= for foo <- @foo do %><%= if foo == @selected, do: ~s(selected) %><%= foo %><% end %>"
assert [%{dynamics: [["", "1"], ["selected", "2"], ["", "3"]]}] =
changed(template, %{foo: ["1", "2", "3"], selected: "2"}, nil)
assert [nil] = changed(template, %{foo: ["1", "2", "3"], selected: "2"}, %{})
assert [%{dynamics: [["", "1"], ["selected", "2"], ["", "3"]]}] =
changed(template, %{foo: ["1", "2", "3"], selected: "2"}, %{foo: true})
end
test "does not render dynamic for nested optimized comprehensions with variables" do
template =
"<%= for x <- @foo do %>X: <%= for y <- @bar do %>Y: <%= x %><%= y %><% end %><% end %>"
assert [
%{
dynamics: [
[%{dynamics: [["1", "1"]], static: ["Y: ", "", ""]}]
],
static: ["X: ", ""]
}
] = changed(template, %{foo: [1], bar: [1]}, nil)
assert [nil] = changed(template, %{foo: [1], bar: [1]}, %{})
assert [
%{
dynamics: [
[%{dynamics: [["1", "1"]], static: ["Y: ", "", ""]}]
],
static: ["X: ", ""]
}
] = changed(template, %{foo: [1], bar: [1]}, %{foo: true, bar: true})
end
test "renders dynamics for nested comprehensions" do
template =
"<%= for foo <- @foo do %><%= for bar <- foo.bar do %><%= foo.x %><%= bar.y %><% end %><% end %>"
assert [
%{
dynamics: [
[%{dynamics: [["1", "1"]], static: ["", "", ""]}]
],
static: ["", ""]
}
] = changed(template, %{foo: [%{x: 1, bar: [%{y: 1}]}]}, %{foo: true})
end
test "renders dynamic if it uses assigns directly" do
template = "<%= for _ <- [1, 2, 3], do: assigns.foo %>"
assert changed(template, %{foo: "a"}, nil) == [["a", "a", "a"]]
assert changed(template, %{foo: "a"}, %{}) == [["a", "a", "a"]]
assert changed(template, %{foo: "a"}, %{foo: true}) == [["a", "a", "a"]]
end
end
describe "if" do
test "converts if-do into rendered" do
template = "<%= if true do %>one<%= @foo %>two<% end %>"
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, %{foo: true})
end
test "converts if-do into rendered with dynamic condition" do
template = "<%= if @bar do %>one<%= @foo %>two<% end %>"
# bar = true
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123, bar: true}, nil)
assert changed(template, %{foo: 123, bar: true}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123, bar: true}, %{foo: true})
assert [%Rendered{dynamic: [nil], static: ["one", "two"]}] =
changed(template, %{foo: 123, bar: true}, %{bar: true})
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123, bar: true}, %{foo: true, bar: true})
# bar = false
assert [""] = changed(template, %{foo: 123, bar: false}, nil)
assert changed(template, %{foo: 123, bar: false}, %{}) ==
[nil]
assert changed(template, %{foo: 123, bar: false}, %{bar: true}) ==
[""]
end
test "converts if-do with var into rendered" do
template = "<%= if var = @foo do %>one<%= var %>two<% end %>"
assert [%Rendered{dynamic: ["true"], static: ["one", "two"]}] =
changed(template, %{foo: true}, nil)
assert changed(template, %{foo: true}, %{}) == [nil]
assert changed(template, %{foo: false}, %{foo: true}) == [""]
end
test "converts if-do-else into rendered with dynamic condition" do
template = "<%= if @bar do %>one<%= @foo %>two<% else %>uno<%= @baz %>dos<% end %>"
# bar = true
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, nil)
assert [nil] = changed(template, %{foo: 123, bar: true, baz: 456}, %{})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true, baz: true})
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{foo: true})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{baz: true})
# bar = false
assert [%Rendered{dynamic: ["456"], static: ["uno", "dos"], fingerprint: fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, nil)
assert [nil] = changed(template, %{foo: 123, bar: false, baz: 456}, %{})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true, bar: true})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{bar: true})
assert [%Rendered{dynamic: ["456"], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{baz: true})
assert fptrue != fpfalse
end
test "converts if-do if-do into rendered" do
template = "<%= if true do %>one<%= if true do %>uno<%= @foo %>dos<% end %>two<% end %>"
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, %{foo: true})
end
test "converts if-do if-do with var into rendered" do
template = "<%= if var = @foo do %>one<%= if var do %>uno<%= var %>dos<% end %>two<% end %>"
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, %{foo: true})
end
test "does not convert if-do-else in the wrong format" do
template = "<%= if @bar do @foo else @baz end %>"
assert changed(template, %{foo: 123, bar: true, baz: 456}, nil) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true}) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{foo: true}) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{baz: true}) == ["123"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, nil) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{bar: true}) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true}) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{baz: true}) == ["456"]
end
test "converts unless-do into rendered" do
template = "<%= unless false do %>one<%= @foo %>two<% end %>"
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, %{foo: true})
end
end
describe "case" do
test "converts case into rendered" do
template = "<%= case true do %><% true -> %>one<%= @foo %>two<% end %>"
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, %{foo: true})
end
test "converts case into rendered with vars in head" do
template = "<%= case true do %><% x when x == true -> %>one<%= @foo %>two<% end %>"
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, %{foo: true})
template = "<%= case @foo do %><% x -> %>one<%= x %>two<% end %>"
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, %{foo: true})
end
test "converts case into rendered with vars in head and body" do
template = "<%= case 456 do %><% x -> %>one<%= @foo %>two<%= x %>three<% end %>"
assert [%Rendered{dynamic: ["123", "456"], static: ["one", "two", "three"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123", "456"], static: ["one", "two", "three"]}] =
changed(template, %{foo: 123}, %{foo: true})
template = "<%= case @bar do %><% x -> %>one<%= @foo %>two<%= x %>three<% end %>"
assert [%Rendered{dynamic: ["123", "456"], static: ["one", "two", "three"]}] =
changed(template, %{foo: 123, bar: 456}, nil)
assert changed(template, %{foo: 123, bar: 456}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123", "456"], static: ["one", "two", "three"]}] =
changed(template, %{foo: 123, bar: 456}, %{foo: true})
assert [%Rendered{dynamic: [nil, "456"], static: ["one", "two", "three"]}] =
changed(template, %{foo: 123, bar: 456}, %{bar: true})
end
test "converts multiple case into rendered with dynamic condition" do
template =
"<%= case @bar do %><% true -> %>one<%= @foo %>two<% false -> %>uno<%= @baz %>dos<% end %>"
# bar = true
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, nil)
assert [nil] = changed(template, %{foo: 123, bar: true, baz: 456}, %{})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true, baz: true})
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{foo: true})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{baz: true})
# bar = false
assert [%Rendered{dynamic: ["456"], static: ["uno", "dos"], fingerprint: fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, nil)
assert [nil] = changed(template, %{foo: 123, bar: false, baz: 456}, %{})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true, bar: true})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{bar: true})
assert [%Rendered{dynamic: ["456"], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{baz: true})
assert fptrue != fpfalse
end
test "converts nested case into rendered" do
template =
"<%= case true do %><% true -> %>one<%= case true do %><% true -> %>uno<%= @foo %>dos<% end %>two<% end %>"
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, %{foo: true})
end
test "converts case with for into rendered" do
template = "<%= case @foo do %><% val -> %><%= for i <- val do %><%= i %><% end %><% end %>"
assert [
%Phoenix.LiveView.Rendered{
dynamic: [
%Phoenix.LiveView.Comprehension{
static: ["", ""],
dynamics: [["1"], ["2"], ["3"]]
}
],
static: ["", ""]
}
] = changed(template, %{foo: 1..3}, nil)
assert changed(template, %{foo: 1..3}, %{}) ==
[nil]
assert [
%Phoenix.LiveView.Rendered{
dynamic: [
%Phoenix.LiveView.Comprehension{
static: ["", ""],
dynamics: [["1"], ["2"], ["3"]]
}
],
static: ["", ""]
}
] = changed(template, %{foo: 1..3}, %{foo: true})
end
test "does not convert cases in the wrong format" do
template = "<%= case @bar do true -> @foo; false -> @baz end %>"
assert changed(template, %{foo: 123, bar: true, baz: 456}, nil) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true}) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{foo: true}) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{baz: true}) == ["123"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, nil) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{bar: true}) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true}) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{baz: true}) == ["456"]
end
end
describe "cond" do
test "converts cond into rendered" do
template = "<%= cond do %><% true -> %>one<%= @foo %>two<% end %>"
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [%Rendered{dynamic: ["123"], static: ["one", "two"]}] =
changed(template, %{foo: 123}, %{foo: true})
end
test "converts multiple cond into rendered with dynamic condition" do
template =
"<%= cond do %><% @bar -> %>one<%= @foo %>two<% true -> %>uno<%= @baz %>dos<% end %>"
# bar = true
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, nil)
assert [nil] = changed(template, %{foo: 123, bar: true, baz: 456}, %{})
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true, baz: true})
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{foo: true})
assert [%Rendered{dynamic: ["123"], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true})
assert [%Rendered{dynamic: [nil], static: ["one", "two"], fingerprint: ^fptrue}] =
changed(template, %{foo: 123, bar: true, baz: 456}, %{baz: true})
# bar = false
assert [%Rendered{dynamic: ["456"], static: ["uno", "dos"], fingerprint: fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, nil)
assert [nil] = changed(template, %{foo: 123, bar: false, baz: 456}, %{})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true, bar: true})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true})
assert [%Rendered{dynamic: [nil], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{bar: true})
assert [%Rendered{dynamic: ["456"], static: ["uno", "dos"], fingerprint: ^fpfalse}] =
changed(template, %{foo: 123, bar: false, baz: 456}, %{baz: true})
assert fptrue != fpfalse
end
test "converts nested cond into rendered" do
template =
"<%= cond do %><% true -> %>one<%= cond do %><% true -> %>uno<%= @foo %>dos<% end %>two<% end %>"
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, nil)
assert changed(template, %{foo: 123}, %{}) ==
[nil]
assert [
%Rendered{
dynamic: [%Rendered{dynamic: ["123"], static: ["uno", "dos"]}],
static: ["one", "two"]
}
] = changed(template, %{foo: 123}, %{foo: true})
end
test "does not convert conds in the wrong format" do
template = "<%= cond do @bar -> @foo; true -> @baz end %>"
assert changed(template, %{foo: 123, bar: true, baz: 456}, nil) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{bar: true}) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{foo: true}) == ["123"]
assert changed(template, %{foo: 123, bar: true, baz: 456}, %{baz: true}) == ["123"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, nil) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{}) == [nil]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{bar: true}) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{foo: true}) == ["456"]
assert changed(template, %{foo: 123, bar: false, baz: 456}, %{baz: true}) == ["456"]
end
end
describe "fingerprints" do
test "are integers" do
rendered1 = eval("foo<%= @bar %>baz", %{bar: 123})
rendered2 = eval("foo<%= @bar %>baz", %{bar: 456})
assert is_integer(rendered1.fingerprint)
assert rendered1.fingerprint == rendered2.fingerprint
end
test "changes even with dynamic content" do
assert eval("<%= :foo %>").fingerprint != eval("<%= :bar %>").fingerprint
end
end
defp eval(string, assigns \\ %{}) do
EEx.eval_string(string, [assigns: assigns], file: __ENV__.file, engine: Engine)
end
defp changed(string, assigns, changed, track_changes? \\ true) do
%{dynamic: dynamic} = eval(string, Map.put(assigns, :__changed__, changed))
expand_dynamic(dynamic, track_changes?)
end
defp expand_dynamic(dynamic, track_changes?) do
Enum.map(dynamic.(track_changes?), &expand_rendered(&1, track_changes?))
end
defp expand_rendered(%Rendered{} = rendered, track_changes?) do
update_in(rendered.dynamic, &expand_dynamic(&1, track_changes?))
end
defp expand_rendered(other, _track_changes), do: other
defp render(string, assigns \\ %{}) do
string
|> eval(assigns)
|> Phoenix.HTML.Safe.to_iodata()
|> IO.iodata_to_binary()
end
end
| 39.352326 | 115 | 0.51207 |
73afaad3bcf2536a476a393f6dacc3e2c24ac20a | 869 | exs | Elixir | test/flawless/error_test.exs | colinsmetz/flawless | 87fd76f88758f16b42813b1e0f0f0ee8163d9185 | [
"MIT"
] | null | null | null | test/flawless/error_test.exs | colinsmetz/flawless | 87fd76f88758f16b42813b1e0f0f0ee8163d9185 | [
"MIT"
] | null | null | null | test/flawless/error_test.exs | colinsmetz/flawless | 87fd76f88758f16b42813b1e0f0f0ee8163d9185 | [
"MIT"
] | null | null | null | defmodule Flawless.ErrorTest do
use ExUnit.Case, async: true
alias Flawless.Error
test "new/2 builds a valid error" do
assert Error.new("my test error", ["a", "b"]) == %Error{
message: "my test error",
context: ["a", "b"]
}
end
test "message_from_template/2 replaces interpolated variables" do
assert Error.message_from_template("String %{value} must have at least %{n} characters.",
n: 10,
value: "plop"
) == "String plop must have at least 10 characters."
assert Error.message_from_template("Value %{x} is displayed here. Value %{x} is also here.",
x: 99
) == "Value 99 is displayed here. Value 99 is also here."
assert Error.message_from_template("A list: %{list}", list: inspect([1, 2, 3])) ==
"A list: [1, 2, 3]"
end
end
| 33.423077 | 96 | 0.589183 |
73afdf77f383fee92b14ab4b78b64d5cc6319161 | 116 | exs | Elixir | .formatter.exs | neysofu/securion | 5c2733b7891df1e754e8e23dc7d3bc3a9fcd7454 | [
"0BSD"
] | 143 | 2016-07-21T22:54:57.000Z | 2021-12-31T13:53:03.000Z | .formatter.exs | neysofu/securion | 5c2733b7891df1e754e8e23dc7d3bc3a9fcd7454 | [
"0BSD"
] | 154 | 2016-08-04T18:35:13.000Z | 2022-01-12T06:42:17.000Z | .formatter.exs | neysofu/securion | 5c2733b7891df1e754e8e23dc7d3bc3a9fcd7454 | [
"0BSD"
] | 21 | 2016-07-23T18:43:14.000Z | 2021-06-03T15:09:21.000Z | # Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
line_length: 79
]
| 19.333333 | 70 | 0.577586 |
73afec092f8ee471b084568a1b8c092ac19a72fc | 228 | exs | Elixir | ex_cubic_ods_ingestion/priv/repo/migrations/20220308235013_cubic_ods_load_table_not_null.exs | paulswartz/data_platform | 0d8a7d6a75026a68d0fa49777892e9edcbdaa71f | [
"MIT"
] | null | null | null | ex_cubic_ods_ingestion/priv/repo/migrations/20220308235013_cubic_ods_load_table_not_null.exs | paulswartz/data_platform | 0d8a7d6a75026a68d0fa49777892e9edcbdaa71f | [
"MIT"
] | 2 | 2022-03-10T22:29:35.000Z | 2022-03-18T19:52:27.000Z | ex_cubic_ods_ingestion/priv/repo/migrations/20220308235013_cubic_ods_load_table_not_null.exs | paulswartz/data_platform | 0d8a7d6a75026a68d0fa49777892e9edcbdaa71f | [
"MIT"
] | null | null | null | defmodule ExCubicOdsIngestion.Repo.Migrations.CubicOdsLoadTableNotNull do
use Ecto.Migration
def change do
alter table(:cubic_ods_loads) do
modify(:table_id, :bigint, null: false, from: :bigint)
end
end
end
| 22.8 | 73 | 0.745614 |
73b007e1b6449e2d4eec3798ba1a26afb4cf5218 | 3,986 | ex | Elixir | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/administrator_web_token_spec.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/administrator_web_token_spec.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/administrator_web_token_spec.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpec do
@moduledoc """
Specification for a token used to generate iframes. The token specifies
what data the admin is allowed to modify and the URI the iframe is
allowed to communiate with.
## Attributes
* `managedConfigurations` (*type:* `GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecManagedConfigurations.t`, *default:* `nil`) - Options for displaying the Managed Configuration page.
* `parent` (*type:* `String.t`, *default:* `nil`) - The URI of the parent frame hosting the iframe. To prevent XSS, the iframe
may not be hosted at other URIs. This URI must be https.
Use whitespaces to separate multiple parent URIs.
* `permission` (*type:* `list(String.t)`, *default:* `nil`) - Deprecated. Use <code>PlaySearch.approveApps</code>.
* `playSearch` (*type:* `GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecPlaySearch.t`, *default:* `nil`) - Options for displaying the managed Play Search apps page.
* `privateApps` (*type:* `GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecPrivateApps.t`, *default:* `nil`) - Options for displaying the Private Apps page.
* `storeBuilder` (*type:* `GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecStoreBuilder.t`, *default:* `nil`) - Options for displaying the Organize apps page.
* `webApps` (*type:* `GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecWebApps.t`, *default:* `nil`) - Options for displaying the Web Apps page.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:managedConfigurations =>
GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecManagedConfigurations.t(),
:parent => String.t(),
:permission => list(String.t()),
:playSearch =>
GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecPlaySearch.t(),
:privateApps =>
GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecPrivateApps.t(),
:storeBuilder =>
GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecStoreBuilder.t(),
:webApps => GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecWebApps.t()
}
field(:managedConfigurations,
as: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecManagedConfigurations
)
field(:parent)
field(:permission, type: :list)
field(:playSearch, as: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecPlaySearch)
field(:privateApps,
as: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecPrivateApps
)
field(:storeBuilder,
as: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecStoreBuilder
)
field(:webApps, as: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpecWebApps)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpec do
def decode(value, options) do
GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpec.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.AdministratorWebTokenSpec do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 48.024096 | 202 | 0.752383 |
73b06dc4dbd9b93bbb4752c88a402d7a7ebb9126 | 1,383 | ex | Elixir | test/support/data_case.ex | dukhniav/plausible | dfcbf9cc98637721698b2046eee205b66b204acb | [
"MIT"
] | null | null | null | test/support/data_case.ex | dukhniav/plausible | dfcbf9cc98637721698b2046eee205b66b204acb | [
"MIT"
] | null | null | null | test/support/data_case.ex | dukhniav/plausible | dfcbf9cc98637721698b2046eee205b66b204acb | [
"MIT"
] | null | null | null | defmodule Plausible.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,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
use Plausible.Repo
import Ecto.Changeset
import Plausible.DataCase
import Plausible.Factory
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Plausible.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Plausible.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} ->
Enum.reduce(opts, message, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
end
end
| 26.09434 | 77 | 0.685466 |
73b0b7e1b007b460d5d65d21bceb6afa5e488b5a | 4,449 | ex | Elixir | lib/blockchain_api/query/account_balance.ex | pakorn186c/blockchain-api | 3c9fbc892e645f9bb144414f3da36749603f37bc | [
"Apache-2.0"
] | 17 | 2019-11-03T03:02:41.000Z | 2022-01-13T17:03:32.000Z | lib/blockchain_api/query/account_balance.ex | AddressXception/blockchain-api | eea98fa78af2887cc84762f84532c602c3b8b666 | [
"Apache-2.0"
] | 5 | 2019-11-07T23:26:53.000Z | 2020-11-24T21:45:35.000Z | lib/blockchain_api/query/account_balance.ex | AddressXception/blockchain-api | eea98fa78af2887cc84762f84532c602c3b8b666 | [
"Apache-2.0"
] | 11 | 2019-12-04T07:03:16.000Z | 2022-01-13T17:03:50.000Z | defmodule BlockchainAPI.Query.AccountBalance do
@moduledoc false
import Ecto.Query, warn: false
use Timex
alias BlockchainAPI.{Repo, Util, Schema.AccountBalance}
def get_latest!(address) do
AccountBalance
|> where([a], a.account_address == ^address)
|> order_by([a], desc: a.block_height)
|> limit(1)
|> Repo.replica.one!()
end
def create(attrs \\ %{}) do
%AccountBalance{}
|> AccountBalance.changeset(attrs)
|> Repo.insert()
end
def get_history(address) do
%{
day: sample_daily_account_balance(address),
week: sample_weekly_account_balance(address),
month: sample_monthly_account_balance(address)
}
end
# ==================================================================
# Helper functions
# ==================================================================
defp get_account_balances_daily(address) do
start = Util.shifted_unix_time(hours: -24)
query_account_balance(address, start, Util.current_time())
end
defp get_account_balances_weekly(address) do
start = Util.shifted_unix_time(days: -7)
query_account_balance(address, start, Util.current_time())
end
defp get_account_balances_monthly(address) do
start = Util.shifted_unix_time(days: -30)
query_account_balance(address, start, Util.current_time())
end
defp query_account_balance(address, start, finish) do
query =
from(
a in AccountBalance,
where: a.account_address == ^address,
where: a.block_time >= ^start,
where: a.block_time <= ^finish,
select: %{
time: a.block_time,
balance: a.balance,
delta: a.delta
}
)
query |> Repo.replica.all()
end
defp sample_daily_account_balance(address) do
range = 1..24
range
|> balance_filter(address, &get_account_balances_daily/1, 1)
|> populated_time_data()
|> parse_balance_history(range, address)
end
defp sample_weekly_account_balance(address) do
range = 1..22
range
|> balance_filter(address, &get_account_balances_weekly/1, 8)
|> populated_time_data()
|> parse_balance_history(range, address)
end
defp sample_monthly_account_balance(address) do
range = 1..31
range
|> balance_filter(address, &get_account_balances_monthly/1, 24)
|> populated_time_data()
|> parse_balance_history(range, address)
end
defp balance_filter(range, address, fun, shift) do
address
|> interval_filter(range, fun, shift)
|> Enum.reduce([], fn list, acc ->
case list do
list when list != [] ->
x = list |> Enum.max_by(fn item -> item.time end)
y = list |> Enum.map(fn item -> item.delta end) |> Enum.sum()
[%{x | delta: y} | acc]
_ ->
[nil | acc]
end
end)
|> Enum.reverse()
end
defp interval_filter(address, range, fun, shift) do
hr_shift = 3600 * shift
offset = rem(Util.current_time(), hr_shift)
now = div(Util.current_time() - offset, hr_shift)
then = div(Util.current_time() - (offset + hr_shift * length(Enum.to_list(range))), hr_shift)
map =
Range.new(then, now)
|> Enum.map(fn key -> {key, []} end)
|> Map.new()
filtered_map =
address
|> fun.()
|> Enum.group_by(fn x -> div(x.time - offset, hr_shift) end)
map
|> Map.merge(filtered_map)
|> Map.values()
end
defp populated_time_data(filtered_time_data) do
filtered_time_data
|> Enum.reduce(
{0, nil, []},
fn
nil, {p, nil, acc} ->
{p + 1, nil, acc}
nil, {_, current_balance, acc} ->
{0, current_balance, acc ++ [current_balance]}
%{balance: balance}, {0, _, acc0} ->
{0, balance, acc0 ++ [balance]}
%{balance: balance, delta: delta}, {p, _, acc0} ->
acc1 =
1..p
|> Enum.to_list()
|> Enum.reduce([], fn _, a -> [balance - delta | a] end)
{0, balance, acc0 ++ acc1 ++ [balance]}
end
)
end
defp parse_balance_history(data, range, address) do
case data do
{0, _start, balances} -> balances
_ -> default_balance_history(range, address)
end
end
defp default_balance_history(range, address) do
range
|> Enum.map(fn _i ->
case get_latest!(address) do
nil -> 0
account_entry -> account_entry.balance
end
end)
end
end
| 25.866279 | 97 | 0.594066 |
73b0bc8dd2e9982c86eb6acdb80f193f08ce416b | 1,123 | exs | Elixir | features/fixtures/mix_umbrella/apps/awesome/config/config.exs | hexa2k9/LicenseFinder | 5413f00d87e80ea631743e6fe451d584d72966ca | [
"MIT"
] | 1,039 | 2015-01-02T03:34:44.000Z | 2022-03-28T09:51:55.000Z | features/fixtures/mix_umbrella/apps/awesome/config/config.exs | hexa2k9/LicenseFinder | 5413f00d87e80ea631743e6fe451d584d72966ca | [
"MIT"
] | 525 | 2015-01-02T22:05:58.000Z | 2022-03-31T11:21:02.000Z | features/fixtures/mix_umbrella/apps/awesome/config/config.exs | hexa2k9/LicenseFinder | 5413f00d87e80ea631743e6fe451d584d72966ca | [
"MIT"
] | 274 | 2015-01-03T21:18:23.000Z | 2022-03-30T03:11:05.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure your application as:
#
# config :awesome, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:awesome, :key)
#
# You can also configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.225806 | 73 | 0.751558 |
73b0bfed3f77e1e16126b8f3b8f6c10e12eb2176 | 1,105 | exs | Elixir | clients/compute/mix.exs | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/compute/mix.exs | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/compute/mix.exs | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | defmodule GoogleApi.Compute.V1.Mixfile do
use Mix.Project
@version "0.3.0"
def project() do
[
app: :google_api_compute,
version: @version,
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/compute"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.1.0"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Creates and runs virtual machines on Google Cloud Platform.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/compute",
"Homepage" => "https://cloud.google.com/compute/"
}
]
end
end
| 22.55102 | 107 | 0.584615 |
73b11a7eb935d8f4a596599c3d6af19ca5fafb92 | 770 | ex | Elixir | test/support/channel_case.ex | ctbucha/phoenix-reasonreact-example | cb6c34eaa74108e0cf14f838eac208ef8f073a22 | [
"MIT"
] | 11 | 2018-07-20T07:37:06.000Z | 2020-08-18T17:48:00.000Z | test/support/channel_case.ex | ctbucha/phoenix-reasonreact-example | cb6c34eaa74108e0cf14f838eac208ef8f073a22 | [
"MIT"
] | null | null | null | test/support/channel_case.ex | ctbucha/phoenix-reasonreact-example | cb6c34eaa74108e0cf14f838eac208ef8f073a22 | [
"MIT"
] | 1 | 2018-07-20T01:48:02.000Z | 2018-07-20T01:48:02.000Z | defmodule MyappWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common datastructures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint MyappWeb.Endpoint
end
end
setup _tags do
:ok
end
end
| 22.647059 | 58 | 0.724675 |
73b1301957a9230f3dcd595176fbb8ae65156cd0 | 1,681 | ex | Elixir | lib/nabo.ex | bechanh5/nabo | 3e406a5875622a8f702649ced30b39a296039f71 | [
"MIT"
] | null | null | null | lib/nabo.ex | bechanh5/nabo | 3e406a5875622a8f702649ced30b39a296039f71 | [
"MIT"
] | null | null | null | lib/nabo.ex | bechanh5/nabo | 3e406a5875622a8f702649ced30b39a296039f71 | [
"MIT"
] | null | null | null | defmodule Nabo do
@moduledoc """
Nabo is a simple, fast blog engine written in Elixir.
Nabo is designed to be integrate-able to other components in your application like
Phoenix or Plug. It does not include stuff like routing or html generating,
but only focuses on one thing and does it well: manages your blog posts.
## Post
Post is the heart of Nabo and is represented as `Nabo.Post` struct.
You can keep your blog posts in any directories you like in the source code,
but all posts should follow this format.
metadata (JSON, mandatory)
---
post excerpt (Markdown, optional)
---
post body (Markdown, mandatory)
### Example
{
"title": "First Nabo post",
"slug": "first-post",
"datetime": "2017-01-01T00:00:00Z"
}
---
This is my first blog post created with Nabo.
---
### Section 1
My first blog post created with Nabo.
### Section 2
...
See `Nabo.Post` for more information.
## Repo
To access your blog posts, you need to create a repo.
defmodule MyRepo do
use Nabo.Repo, root: "priv/posts"
end
To get all posts.
posts = MyRepo.all()
To get a post by its slug.
{:ok, post} = MyRepo.get("first-post")
See `Nabo.Repo` for more information.
## Compiler
Compiler is where your posts being compiled.
Nabo uses `Nabo.Compilers.Markdown` as the default compiler but you're free to have
your own options and compilers. See the documentation of `Nabo.Compilers.Markdown`
for more options.
If you want to build your own compiler, see `Nabo.Compiler` for more information.
"""
end
| 23.676056 | 85 | 0.653183 |
73b13d41fa736227b3d73901abf2753a940f5e06 | 3,024 | exs | Elixir | apps/gitgud_web/test/gitgud_web/controllers/ssh_key_controller_test.exs | rogervezaro/gitgud | 6656f8c2df16817a6c5325fb4c18b03f9d3f7140 | [
"MIT"
] | 1 | 2019-09-08T07:48:10.000Z | 2019-09-08T07:48:10.000Z | apps/gitgud_web/test/gitgud_web/controllers/ssh_key_controller_test.exs | rogervezaro/gitgud | 6656f8c2df16817a6c5325fb4c18b03f9d3f7140 | [
"MIT"
] | null | null | null | apps/gitgud_web/test/gitgud_web/controllers/ssh_key_controller_test.exs | rogervezaro/gitgud | 6656f8c2df16817a6c5325fb4c18b03f9d3f7140 | [
"MIT"
] | null | null | null | defmodule GitGud.Web.SSHKeyControllerTest do
use GitGud.Web.ConnCase, async: true
use GitGud.Web.DataFactory
alias GitGud.DB
alias GitGud.User
alias GitGud.SSHKey
setup :create_user
test "renders ssh authentication key creation form if authenticated", %{conn: conn, user: user} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = get(conn, Routes.ssh_key_path(conn, :new))
assert html_response(conn, 200) =~ ~s(<h2 class="subtitle">Add a new SSH key</h2>)
end
test "fails to render ssh authentication key creation form if not authenticated", %{conn: conn} do
conn = get(conn, Routes.ssh_key_path(conn, :new))
assert html_response(conn, 401) =~ "Unauthorized"
end
test "creates ssh authentication key with valid params", %{conn: conn, user: user} do
ssh_key_params = factory(:ssh_key)
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = post(conn, Routes.ssh_key_path(conn, :create), ssh_key: ssh_key_params)
assert get_flash(conn, :info) == "SSH key '#{ssh_key_params.name}' added."
assert redirected_to(conn) == Routes.ssh_key_path(conn, :index)
end
test "fails to create ssh authentication key with invalid public key", %{conn: conn, user: user} do
ssh_key_params = factory(:ssh_key)
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = post(conn, Routes.ssh_key_path(conn, :create), ssh_key: Map.update!(ssh_key_params, :data, &binary_part(&1, 0, 12)))
assert get_flash(conn, :error) == "Something went wrong! Please check error(s) below."
assert html_response(conn, 400) =~ ~s(<h2 class="subtitle">Add a new SSH key</h2>)
end
describe "when ssh authentication keys exist" do
setup :create_ssh_keys
test "renders user ssh authentication keys", %{conn: conn, user: user, ssh_keys: ssh_keys} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = get(conn, Routes.ssh_key_path(conn, :index))
assert html_response(conn, 200) =~ ~s(<h2 class="subtitle">SSH keys</h2>)
for ssh_key <- ssh_keys do
assert html_response(conn, 200) =~ ~s(<code class=\"is-size-7\">#{ssh_key.fingerprint}</code>)
end
end
test "deletes keys", %{conn: conn, user: user, ssh_keys: ssh_keys} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
for ssh_key <- ssh_keys do
conn = delete(conn, Routes.ssh_key_path(conn, :delete), ssh_key: %{id: to_string(ssh_key.id)})
assert get_flash(conn, :info) == "SSH key '#{ssh_key.name}' deleted."
assert redirected_to(conn) == Routes.ssh_key_path(conn, :index)
end
end
end
#
# Helpers
#
defp create_user(context) do
Map.put(context, :user, User.create!(factory(:user)))
end
defp create_ssh_keys(context) do
ssh_keys = Stream.repeatedly(fn -> SSHKey.create!(factory(:ssh_key, context.user)) end)
context
|> Map.put(:ssh_keys, Enum.take(ssh_keys, 2))
|> Map.update!(:user, &DB.preload(&1, :ssh_keys))
end
end
| 40.32 | 127 | 0.687169 |
73b17fbc041dc572415e3e60aa7eef58691f7a71 | 8,496 | ex | Elixir | lib/swoosh/adapters/amazon_ses.ex | feld/swoosh | 05e70573385830bb345e0fa5f5cc1d1ad524a90a | [
"MIT"
] | 1,214 | 2016-03-21T16:56:42.000Z | 2022-03-31T19:10:11.000Z | lib/swoosh/adapters/amazon_ses.ex | feld/swoosh | 05e70573385830bb345e0fa5f5cc1d1ad524a90a | [
"MIT"
] | 399 | 2016-03-21T23:11:32.000Z | 2022-03-04T10:52:28.000Z | deps/swoosh/lib/swoosh/adapters/amazon_ses.ex | adrianomota/blog | ef3b2d2ed54f038368ead8234d76c18983caa75b | [
"MIT"
] | 208 | 2016-03-21T21:12:11.000Z | 2022-03-04T06:35:33.000Z | defmodule Swoosh.Adapters.AmazonSES do
@moduledoc ~S"""
An adapter that sends email using the Amazon Simple Email Service Query API.
This email adapter makes use of the Amazon SES SendRawEmail action and generates
a SMTP style message containing the information to be emailed. This allows for
greater more customizable email message and ensures the capability to add
attachments. As a result, however, the `gen_smtp` dependency is required in order
to correctly generate the SMTP message that will be sent.
Ensure sure you have the dependency added in your mix.exs file.
def deps do
[
{:swoosh, "~> 1.0"},
{:gen_smtp, "~> 1.0"}
]
end
See Also:
[Amazon SES Query Api Docs](http://docs.aws.amazon.com/ses/latest/APIReference/Welcome.html)
[Amazon SES SendRawEmail Documentation](http://docs.aws.amazon.com/ses/latest/APIReference/API_SendRawEmail.html)
## Example
# config/config.exs
config :sample, Sample.Mailer,
adapter: Swoosh.Adapters.AmazonSES,
region: "region-endpoint",
access_key: "aws-access-key",
secret: "aws-secret-key"
# lib/sample/mailer.ex
defmodule Sample.Mailer do
use Swoosh.Mailer, otp_app: :sample
end
## Using with tags and configuration set
import Swoosh.Email
new()
|> from("[email protected]")
|> to("[email protected]")
|> subject("Mighty Pirate Newsletter")
|> text_body("Hello")
|> put_provider_option(:tags, [%{name: "name1", value: "test1"}])
|> put_provider_option(:configuration_set_name, "configuration_set_name1")
## IAM role
In case you use IAM role for authenticating AWS requests, you can fetch
temporary `access_key` and `secret_key` from that role, but you also need to
include additional `X-Amz-Security-Token` header to that request.
You can do that by adding `security_token` to `provider_options`.
"""
use Swoosh.Adapter,
required_config: [:region, :access_key, :secret],
required_deps: [gen_smtp: :mimemail]
alias Swoosh.Email
alias Swoosh.Adapters.XML.Helpers, as: XMLHelper
alias Swoosh.Adapters.SMTP.Helpers, as: SMTPHelper
@encoding "AWS4-HMAC-SHA256"
@host_prefix "email."
@host_suffix ".amazonaws.com"
@service_name "ses"
@action "SendRawEmail"
@base_headers %{"Content-Type" => "application/x-www-form-urlencoded"}
@version "2010-12-01"
@impl true
def deliver(%Email{} = email, config \\ []) do
query = email |> prepare_body(config) |> encode_body
url = base_url(config)
headers = prepare_headers(@base_headers, query, config, email.provider_options)
case Swoosh.ApiClient.post(url, headers, query, email) do
{:ok, 200, _headers, body} ->
{:ok, parse_response(body)}
{:ok, code, _headers, body} when code > 399 ->
{:error, parse_error_response(body)}
{_, reason} ->
{:error, reason}
end
end
defp parse_response(body) do
node = XMLHelper.parse(body)
message_id = XMLHelper.first_text(node, "//MessageId")
request_id = XMLHelper.first_text(node, "//RequestId")
%{id: message_id, request_id: request_id}
end
defp parse_error_response(body) do
node = XMLHelper.parse(body)
code = XMLHelper.first_text(node, "//Error/Code")
message = XMLHelper.first_text(node, "//Message")
%{code: code, message: message}
end
defp base_url(config) do
case config[:host] do
nil -> "https://" <> @host_prefix <> config[:region] <> @host_suffix
_ -> config[:host]
end
end
defp prepare_body(email, config) do
%{}
|> Map.put("Action", @action)
|> Map.put("Version", Keyword.get(config, :version, @version))
|> Map.put("RawMessage.Data", generate_raw_message_data(email, config))
|> prepare_configuration_set_name(email)
|> prepare_tags(email)
end
defp encode_body(body) do
body |> Enum.sort() |> URI.encode_query()
end
defp prepare_configuration_set_name(body, %{provider_options: %{configuration_set_name: name}}) do
Map.put(body, "ConfigurationSetName", name)
end
defp prepare_configuration_set_name(body, _email), do: body
defp prepare_tags(body, %{provider_options: %{tags: tags}}) do
Map.merge(
body,
tags
|> Enum.with_index(1)
|> Enum.flat_map(fn {%{name: name, value: value}, index} ->
[{"Tags.member.#{index}.Name", name}, {"Tags.member.#{index}.Value", value}]
end)
|> Enum.into(%{})
)
end
defp prepare_tags(body, _email), do: body
defp generate_raw_message_data(email, config) do
email
|> SMTPHelper.body(config)
|> Base.encode64()
|> URI.encode()
end
defp prepare_headers(headers, query, config, provider_options) do
current_date_time = DateTime.utc_now()
headers
|> prepare_header_host(config)
|> prepare_header_date(current_date_time)
|> prepare_header_length(query)
|> prepare_header_authorization(query, current_date_time, config)
|> prepare_header_security_token(provider_options)
|> Map.to_list()
end
defp prepare_header_authorization(headers, query, current_date_time, config) do
signed_header_list = generate_signed_header_list(headers)
headers_string = setup_headers_string(headers)
signature =
query
|> determine_request_hash(headers_string, signed_header_list)
|> generate_signing_string(config, current_date_time)
|> generate_signature(current_date_time, config[:region], config[:secret])
authorization =
prepare_authorization(config, signed_header_list, current_date_time, signature)
Map.put(headers, "Authorization", authorization)
end
defp setup_headers_string(headers) do
headers
|> Enum.sort()
|> Enum.map_join("\n", fn {k, v} -> "#{String.downcase(k)}:#{v}" end)
end
defp generate_signed_header_list(headers) do
headers
|> Map.keys()
|> Enum.map_join(";", &String.downcase/1)
end
defp determine_request_hash(query, headers, signed_header_list) do
hashed_query = :crypto.hash(:sha256, query) |> Base.encode16(case: :lower)
canonical_request =
[
"POST",
"/",
"",
"#{headers}",
"",
signed_header_list,
hashed_query
]
|> Enum.join("\n")
:crypto.hash(:sha256, canonical_request) |> Base.encode16(case: :lower)
end
defp prepare_header_host(headers, config) do
Map.put(headers, "Host", @host_prefix <> config[:region] <> @host_suffix)
end
defp prepare_header_date(headers, date_time) do
Map.put(headers, "X-Amz-Date", amz_datetime(date_time))
end
defp prepare_header_length(headers, query) do
Map.put(headers, "Content-Length", query |> String.length() |> to_string())
end
defp prepare_authorization(config, signed_header_list, date_time, signature) do
date = amz_date(date_time)
credential = "#{config[:access_key]}/#{date}/#{config[:region]}/#{@service_name}/aws4_request"
"#{@encoding} Credential=#{credential}, SignedHeaders=#{signed_header_list}, Signature=#{signature}"
end
defp prepare_header_security_token(headers, %{security_token: token}) do
Map.put(headers, "X-Amz-Security-Token", token)
end
defp prepare_header_security_token(headers, _provider_options), do: headers
defp generate_signature(string_to_sign, date_time, region, secret) do
("AWS4" <> secret)
|> encrypt_value(amz_date(date_time))
|> encrypt_value(region)
|> encrypt_value(@service_name)
|> encrypt_value("aws4_request")
|> encrypt_value(string_to_sign)
|> Base.encode16(case: :lower)
end
defp generate_signing_string(request_hash, config, dt) do
date = amz_date(dt)
normalized_date_time = amz_datetime(dt)
[
@encoding,
"#{normalized_date_time}",
"#{date}/#{config[:region]}/#{@service_name}/aws4_request",
request_hash
]
|> Enum.join("\n")
end
defp encrypt_value(secret, unencrypted_data),
do: :crypto.mac(:hmac, :sha256, secret, unencrypted_data)
defp amz_date(dt) do
date_string =
Enum.map_join(
[dt.month, dt.day],
&String.pad_leading(to_string(&1), 2, "0")
)
"#{dt.year}#{date_string}"
end
defp amz_datetime(dt) do
time_string =
Enum.map_join(
[dt.hour, dt.minute, dt.second],
&String.pad_leading(to_string(&1), 2, "0")
)
"#{amz_date(dt)}T#{time_string}Z"
end
end
| 29.397924 | 115 | 0.672081 |
73b1c714d73a6addd7ebe12e671f7123e3fde95a | 453 | ex | Elixir | lib/bencodelix/supervisor.ex | nodrygo/bencodelix | 7aa4787793ef0c362e7b4b19259eba7664445715 | [
"MIT"
] | 2 | 2016-04-01T21:03:17.000Z | 2016-04-01T21:04:00.000Z | lib/bencodelix/supervisor.ex | nodrygo/bencodelix | 7aa4787793ef0c362e7b4b19259eba7664445715 | [
"MIT"
] | null | null | null | lib/bencodelix/supervisor.ex | nodrygo/bencodelix | 7aa4787793ef0c362e7b4b19259eba7664445715 | [
"MIT"
] | null | null | null | defmodule Bencodelix.Supervisor do
use Supervisor.Behaviour
def start_link do
:supervisor.start_link(__MODULE__, [])
end
def init([]) do
children = [
# Define workers and child supervisors to be supervised
# worker(Bencodelix.Worker, [])
]
# See http://elixir-lang.org/docs/stable/Supervisor.Behaviour.html
# for other strategies and supported options
supervise(children, strategy: :one_for_one)
end
end
| 23.842105 | 70 | 0.701987 |
73b1f9689da20d4ff35b8d15add63f8b5e8e156f | 1,565 | exs | Elixir | deps/earmark/mix.exs | ench0/ex_identicon | b37e86984cb372d8981b43190b0052e35718f173 | [
"MIT"
] | null | null | null | deps/earmark/mix.exs | ench0/ex_identicon | b37e86984cb372d8981b43190b0052e35718f173 | [
"MIT"
] | null | null | null | deps/earmark/mix.exs | ench0/ex_identicon | b37e86984cb372d8981b43190b0052e35718f173 | [
"MIT"
] | null | null | null | Code.eval_file "tasks/readme.exs"
defmodule Earmark.Mixfile do
use Mix.Project
def project do
[
app: :earmark,
version: "1.0.3",
elixir: "~> 1.2",
elixirc_paths: elixirc_paths(Mix.env),
escript: escript_config(),
deps: deps(),
description: description(),
package: package(),
]
end
def application do
[applications: []]
end
defp deps do
[{:poison, "~> 3.0", only: [:dev, :test]},
{:credo, "~> 0.4.1", only: [:dev, :test]},
{:dialyxir, "~> 0.3.3", only: [:dev, :test]},
{:ex_doc, ">= 0.0.0", only: :dev},
]
end
defp description do
"""
Earmark is a pure-Elixir Markdown converter.
It is intended to be used as a library (just call Earmark.to_html),
but can also be used as a command-line tool (just run mix escript.build
first).
Output generation is pluggable.
"""
end
defp package do
[
files: [ "lib", "src", "tasks", "mix.exs", "README.md" ],
maintainers: [
"Robert Dober <[email protected]>",
"Dave Thomas <[email protected]>"
],
licenses: [ "Apache 2 (see the file LICENSE for details)" ],
links: %{
"GitHub" => "https://github.com/pragdave/earmark",
}
]
end
defp escript_config do
[ main_module: Earmark.CLI ]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
end
| 24.453125 | 75 | 0.52524 |
73b209bf2aa83f443ab525807daaeb49e9860ab5 | 882 | ex | Elixir | clients/reseller/lib/google_api/reseller/v1/metadata.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/reseller/lib/google_api/reseller/v1/metadata.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/reseller/lib/google_api/reseller/v1/metadata.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Reseller.V1 do
@moduledoc """
API client metadata for GoogleApi.Reseller.V1.
"""
@discovery_revision "20210206"
def discovery_revision(), do: @discovery_revision
end
| 32.666667 | 74 | 0.758503 |
73b20ec814a4ef7461cf1bd0558e3904bc3e607d | 834 | exs | Elixir | test/k8s/discovery/driver/file_test.exs | thephw/k8s | a4d157ad0191ac49b27ec9197f342d8d4d33e52a | [
"MIT"
] | 226 | 2019-02-03T00:49:32.000Z | 2022-03-30T15:02:22.000Z | test/k8s/discovery/driver/file_test.exs | thephw/k8s | a4d157ad0191ac49b27ec9197f342d8d4d33e52a | [
"MIT"
] | 109 | 2019-01-20T20:39:33.000Z | 2022-03-31T20:21:34.000Z | test/k8s/discovery/driver/file_test.exs | FreedomBen/k8s | 9cfd7bec869cd1f2d8a6c543923f3849710941a5 | [
"MIT"
] | 43 | 2019-02-07T01:18:31.000Z | 2022-03-08T04:15:33.000Z | # credo:disable-for-this-file
defmodule K8s.Discovery.Driver.FileTest do
use ExUnit.Case, async: true
alias K8s.Discovery.Driver.File
@example_config "test/support/discovery/example.json"
describe "resources/2" do
test "returns a list of API resources" do
{:ok, resources} = File.resources("v1", %K8s.Conn{}, config: @example_config)
resource_names = Enum.map(resources, & &1["name"])
sorted_resource_names = Enum.sort(resource_names)
assert sorted_resource_names == ["namespaces", "pods", "pods/eviction", "services"]
end
end
describe "versions/1" do
test "returns a list of API versions" do
{:ok, versions} = File.versions(%K8s.Conn{}, config: @example_config)
sorted_versions = Enum.sort(versions)
assert sorted_versions == ["apps/v1", "v1"]
end
end
end
| 30.888889 | 89 | 0.685851 |
73b21821f4322cd7de24cca3f350ae0ef1d2d03e | 400 | ex | Elixir | lib/militerm/data/flags.ex | jgsmith/militerm | c4252d0a93f5620b90750ac2b61baf282e9ef7eb | [
"Apache-2.0"
] | 6 | 2017-06-16T10:26:35.000Z | 2021-04-07T15:01:00.000Z | lib/militerm/data/flags.ex | jgsmith/militerm | c4252d0a93f5620b90750ac2b61baf282e9ef7eb | [
"Apache-2.0"
] | 2 | 2020-04-14T02:17:46.000Z | 2021-03-10T11:09:05.000Z | lib/militerm/data/flags.ex | jgsmith/militerm | c4252d0a93f5620b90750ac2b61baf282e9ef7eb | [
"Apache-2.0"
] | null | null | null | defmodule Militerm.Data.Flags do
use Ecto.Schema
import Ecto.Changeset
schema "flags" do
field :entity_id, :string
field :flags, {:array, :string}
timestamps()
end
@doc false
def changeset(flags, attrs) do
flags
|> cast(attrs, [
:entity_id,
:flags
])
|> validate_required([
:entity_id
])
|> unique_constraint(:entity_id)
end
end
| 16 | 36 | 0.6125 |
73b25282408a67851ff0fe05c20aa20999e925fa | 37,390 | ex | Elixir | lib/websockex.ex | valiot/websockex | 569392dc1262395463ed97135e34ea519955ba93 | [
"MIT"
] | null | null | null | lib/websockex.ex | valiot/websockex | 569392dc1262395463ed97135e34ea519955ba93 | [
"MIT"
] | null | null | null | lib/websockex.ex | valiot/websockex | 569392dc1262395463ed97135e34ea519955ba93 | [
"MIT"
] | null | null | null | defmodule WebSockex do
alias WebSockex.{Utils}
@handshake_guid "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
@moduledoc ~S"""
A client handles negotiating the connection, then sending frames, receiving
frames, closing, and reconnecting that connection.
A simple client implementation would be:
```
defmodule WsClient do
use WebSockex
def start_link(url, state) do
WebSockex.start_link(url, __MODULE__, state)
end
def handle_frame({:text, msg}, state) do
IO.puts "Received a message: #{msg}"
{:ok, state}
end
def handle_cast({:send, {type, msg} = frame}, state) do
IO.puts "Sending #{type} frame with payload: #{msg}"
{:reply, frame, state}
end
end
```
## Supervision
WebSockex is implemented as an OTP Special Process and as a result will fit
into supervision trees.
WebSockex also supports the Supervisor children format introduced in Elixir
1.5. Meaning that a child specification could be `{ClientModule, [state]}`.
However, since there is a possibility that you would like to provide a
`t:WebSockex.Conn/0` or a url as well as the state, there are two versions of
the `child_spec` function. If you need functionality beyond that it is
recommended that you override the function or define your own.
Just remember to use the version that corresponds with your `start_link`'s
arity.
"""
@type client :: pid | atom | {:via, module, term} | {:global, term}
@type frame ::
:ping
| :pong
| {:ping | :pong, nil | (message :: binary)}
| {:text | :binary, message :: binary}
@typedoc """
The frame sent when the negotiating a connection closure.
"""
@type close_frame :: {close_code, message :: binary}
@typedoc """
An integer between 1000 and 4999 that specifies the reason for closing the connection.
"""
@type close_code :: integer
@typedoc """
Debug options to be parsed by `:sys.debug_options/1`.
These options can also be set after the process is running using the functions in
the Erlang `:sys` module.
"""
@type debug_opts :: [
:trace
| :log
| {:log, log_depth :: pos_integer}
| :statistics
| {:log_to_file, Path.t()}
]
@type options :: [option]
@typedoc """
Options values for `start_link`.
- `:async` - Replies with `{:ok, pid}` before establishing the connection.
This is useful for when attempting to connect indefinitely, this way the
process doesn't block trying to establish a connection.
- `:handle_initial_conn_failure` - When set to `true` a connection failure
while establishing the initial connection won't immediately return an error
and instead will invoke the `c:handle_disconnect/2` callback. This option
only matters during process initialization. The `handle_disconnect`
callback is always invoked if an established connection is lost.
- `:debug` - Options to set the debug options for `:sys.handle_debug`.
- `:name` - An atom that the registers the process with name locally.
Can also be a `{:via, module, term}` or `{:global, term}` tuple.
Other possible option values include: `t:WebSockex.Conn.connection_option/0`
"""
@type option ::
WebSockex.Conn.connection_option()
| {:async, boolean}
| {:debug, debug_opts}
| {:name, atom | {:global, term} | {:via, module, term}}
| {:handle_initial_conn_failure, boolean}
@typedoc """
The reason a connection was closed.
A `:normal` reason is the same as a `1000` reason with no payload.
If the peer closes the connection abruptly without a close frame then the
close reason is `{:remote, :closed}`.
"""
@type close_reason ::
{:remote | :local, :normal}
| {:remote | :local, close_code, message :: binary}
| {:remote, :closed}
| {:error, term}
@typedoc """
The error returned when a connection fails to be established.
"""
@type close_error ::
%WebSockex.RequestError{}
| %WebSockex.ConnError{}
| %WebSockex.InvalidFrameError{}
| %WebSockex.FrameEncodeError{}
@typedoc """
A map that contains information about the failure to connect.
This map contains the error, attempt number, and the `t:WebSockex.Conn.t/0`
that was used to attempt the connection.
"""
@type connection_status_map :: %{
reason: close_reason | close_error,
attempt_number: integer,
conn: WebSockex.Conn.t()
}
@doc """
Invoked after a connection is established.
This is invoked after both the initial connection and a reconnect.
"""
@callback handle_connect(conn :: WebSockex.Conn.t(), state :: term) :: {:ok, new_state :: term}
@doc """
Invoked on the reception of a frame on the socket.
The control frames have possible payloads, when they don't have a payload
then the frame will have `nil` as the payload. e.g. `{:ping, nil}`
"""
@callback handle_frame(frame, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked to handle asynchronous `cast/2` messages.
"""
@callback handle_cast(msg :: term, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked to handle all other non-WebSocket messages.
"""
@callback handle_info(msg :: term, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked when the WebSocket disconnects from the server.
This callback is only invoked in the event of a connection failure. In cases
of crashes or other errors the process will terminate immediately
skipping this callback.
If the `handle_initial_conn_failure: true` option is provided during process
startup, then this callback will be invoked if the process fails to establish
an initial connection.
If a connection is established by reconnecting, the `c:handle_connect/2`
callback will be invoked.
The possible returns for this callback are:
- `{:ok, state}` will continue the process termination.
- `{:reconnect, state}` will attempt to reconnect instead of terminating.
- `{:reconnect, conn, state}` will attempt to reconnect with the connection
data in `conn`. `conn` is expected to be a `t:WebSockex.Conn.t/0`.
"""
@callback handle_disconnect(connection_status_map, state :: term) ::
{:ok, new_state}
| {:reconnect, new_state}
| {:reconnect, new_conn :: WebSockex.Conn.t(), new_state}
when new_state: term
@doc """
Invoked when the Websocket receives a ping frame
"""
@callback handle_ping(ping_frame :: :ping | {:ping, binary}, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked when the Websocket receives a pong frame.
"""
@callback handle_pong(pong_frame :: :pong | {:pong, binary}, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked when the process is terminating.
"""
@callback terminate(close_reason, state :: term) :: any
@doc """
Invoked when a new version the module is loaded during runtime.
"""
@callback code_change(old_vsn :: term | {:down, term}, state :: term, extra :: term) ::
{:ok, new_state :: term}
| {:error, reason :: term}
@doc """
Invoked to retrieve a formatted status of the state in a WebSockex process.
This optional callback is used when you want to edit the values returned when
invoking `:sys.get_status`.
The second argument is a two-element list with the order of `[pdict, state]`.
"""
@callback format_status(:normal, [process_dictionary | state]) :: status :: term
when process_dictionary: [{key :: term, val :: term}], state: term
@optional_callbacks format_status: 2
defmacro __using__(opts) do
quote location: :keep do
@behaviour WebSockex
if Kernel.function_exported?(Supervisor, :child_spec, 2) do
@doc false
def child_spec(conn_info, state) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [conn_info, state]}
}
|> Supervisor.child_spec(unquote(Macro.escape(opts)))
end
@doc false
def child_spec(state) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [state]}
}
|> Supervisor.child_spec(unquote(Macro.escape(opts)))
end
defoverridable child_spec: 2, child_spec: 1
end
@doc false
def handle_connect(_conn, state) do
{:ok, state}
end
@doc false
def handle_frame(frame, _state) do
raise "No handle_frame/2 clause in #{__MODULE__} provided for #{inspect(frame)}"
end
@doc false
def handle_cast(message, _state) do
raise "No handle_cast/2 clause in #{__MODULE__} provided for #{inspect(message)}"
end
@doc false
def handle_info(message, state) do
require Logger
Logger.error("No handle_info/2 clause in #{__MODULE__} provided for #{inspect(message)}")
{:ok, state}
end
@doc false
def handle_disconnect(_connection_status_map, state) do
{:ok, state}
end
@doc false
def handle_ping(:ping, state) do
{:reply, :pong, state}
end
def handle_ping({:ping, msg}, state) do
{:reply, {:pong, msg}, state}
end
@doc false
def handle_pong(:pong, state), do: {:ok, state}
def handle_pong({:pong, _}, state), do: {:ok, state}
@doc false
def terminate(_close_reason, _state), do: :ok
@doc false
def code_change(_old_vsn, state, _extra), do: {:ok, state}
defoverridable handle_connect: 2,
handle_frame: 2,
handle_cast: 2,
handle_info: 2,
handle_ping: 2,
handle_pong: 2,
handle_disconnect: 2,
terminate: 2,
code_change: 3
end
end
@doc """
Starts a `WebSockex` process.
Acts like `start_link/4`, except doesn't link the current process.
See `start_link/4` for more information.
"""
@spec start(url :: String.t() | WebSockex.Conn.t(), module, term, options) ::
{:ok, pid} | {:error, term}
def start(conn_info, module, state, opts \\ [])
def start(%WebSockex.Conn{} = conn, module, state, opts) do
Utils.spawn(:no_link, conn, module, state, opts)
end
def start(url, module, state, opts) do
case WebSockex.Conn.parse_url(url) do
{:ok, uri} ->
conn = WebSockex.Conn.new(uri, opts)
start(conn, module, state, opts)
{:error, error} ->
{:error, error}
end
end
@doc """
Starts a `WebSockex` process linked to the current process.
For available option values see `t:option/0`.
If a `WebSockex.Conn.t` is used in place of a url string, then the options
available in `t:WebSockex.Conn.connection_option/0` have effect.
The callback `c:handle_connect/2` is invoked after the connection is
established.
"""
@spec start_link(url :: String.t() | WebSockex.Conn.t(), module, term, options) ::
{:ok, pid} | {:error, term}
def start_link(conn_info, module, state, opts \\ [])
def start_link(conn = %WebSockex.Conn{}, module, state, opts) do
Utils.spawn(:link, conn, module, state, opts)
end
def start_link(url, module, state, opts) do
case WebSockex.Conn.parse_url(url) do
{:ok, uri} ->
conn = WebSockex.Conn.new(uri, opts)
start_link(conn, module, state, opts)
{:error, error} ->
{:error, error}
end
end
@doc """
Asynchronously sends a message to a client that is handled by `c:handle_cast/2`.
"""
@spec cast(client, term) :: :ok
def cast(client, message) do
Utils.send(client, {:"$websockex_cast", message})
:ok
end
@doc """
Sends a frame through the WebSocket.
If the connection is either connecting or closing then this will return an
error tuple with a `WebSockex.NotConnectedError` exception struct as the
second element.
If a connection failure is discovered while sending then it will return an
error tuple with a `WebSockex.ConnError` exception struct as the second
element.
"""
@spec send_frame(client, frame) ::
:ok
| {:error,
%WebSockex.FrameEncodeError{}
| %WebSockex.ConnError{}
| %WebSockex.NotConnectedError{}
| %WebSockex.InvalidFrameError{}}
| none
def send_frame(client, _) when client == self() do
raise %WebSockex.CallingSelfError{function: :send_frame}
end
def send_frame(client, frame) do
try do
{:ok, res} = :gen.call(client, :"$websockex_send", frame)
res
catch
_, reason ->
exit({reason, {__MODULE__, :call, [client, frame]}})
end
end
@doc false
@spec init(pid, WebSockex.Conn.t(), module, term, options) :: {:ok, pid} | {:error, term}
def init(parent, conn, module, module_state, opts) do
do_init(parent, self(), conn, module, module_state, opts)
end
@spec init(pid, atom, WebSockex.Conn.t(), module, term, options) :: {:ok, pid} | {:error, term}
def init(parent, name, conn, module, module_state, opts) do
case Utils.register(name) do
true ->
do_init(parent, name, conn, module, module_state, opts)
{:error, _} = error ->
:proc_lib.init_ack(parent, error)
end
end
## OTP Stuffs
@doc false
def system_continue(parent, debug, %{connection_status: :connected} = state) do
websocket_loop(parent, debug, Map.delete(state, :connection_status))
end
def system_continue(parent, debug, %{connection_status: :connecting} = state) do
open_loop(parent, debug, Map.delete(state, :connection_status))
end
def system_continue(parent, debug, %{connection_status: {:closing, reason}} = state) do
close_loop(reason, parent, debug, Map.delete(state, :connection_status))
end
@doc false
@spec system_terminate(term, pid, any, any) :: no_return
def system_terminate(reason, parent, debug, state) do
terminate(reason, parent, debug, state)
end
@doc false
def system_get_state(%{module_state: module_state}) do
{:ok, module_state}
end
@doc false
def system_replace_state(fun, state) do
new_module_state = fun.(state.module_state)
{:ok, new_module_state, %{state | module_state: new_module_state}}
end
@doc false
def system_code_change(state, _mod, old_vsn, extra) do
case apply(state.module, :code_change, [old_vsn, state.module_state, extra]) do
{:ok, new_module_state} ->
{:ok, %{state | module_state: new_module_state}}
other ->
other
end
catch
other -> other
end
@doc false
def format_status(opt, [pdict, sys_state, parent, debug, state]) do
log = :sys.get_log(debug)
module_misc = module_status(opt, state.module, pdict, state.module_state)
[
{:header, 'Status for WebSockex process #{inspect(self())}'},
{:data,
[
{"Status", sys_state},
{"Parent", parent},
{"Log", log},
{"Connection Status", state.connection_status},
{"Socket Buffer", state.buffer},
{"Socket Module", state.module}
]}
| module_misc
]
end
defp module_status(opt, module, pdict, module_state) do
default = [{:data, [{"State", module_state}]}]
if function_exported?(module, :format_status, 2) do
result = try_callback(module, :format_status, [opt, [pdict, module_state]])
case result do
{:"$EXIT", _} ->
require Logger
Logger.error("There was an error while invoking #{module}.format_status/2")
default
other when is_list(other) ->
other
other ->
[other]
end
else
default
end
end
# Internals! Yay
defp do_init(parent, name, conn, module, module_state, opts) do
# OTP stuffs
debug = Utils.parse_debug_options(self(), opts)
reply_fun =
case Keyword.get(opts, :async, false) do
true ->
:proc_lib.init_ack(parent, {:ok, self()})
&async_init_fun/1
false ->
&sync_init_fun(parent, &1)
end
state = %{
conn: conn,
module: module,
module_state: module_state,
name: name,
reply_fun: reply_fun,
buffer: <<>>,
fragment: nil
}
handle_conn_failure = Keyword.get(opts, :handle_initial_conn_failure, false)
case open_connection(parent, debug, state) do
{:ok, new_state} ->
debug = Utils.sys_debug(debug, :connected, state)
module_init(parent, debug, new_state)
{:error, error, new_state} when handle_conn_failure == true ->
init_conn_failure(error, parent, debug, new_state)
{:error, error, _} ->
state.reply_fun.({:error, error})
end
end
# Loops
defp open_loop(parent, debug, state) do
%{task: %{ref: ref}} = state
receive do
{:system, from, req} ->
state = Map.put(state, :connection_status, :connecting)
:sys.handle_system_msg(req, from, parent, __MODULE__, debug, state)
{:"$websockex_send", from, _frame} ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :opening}})
open_loop(parent, debug, state)
{:EXIT, ^parent, reason} ->
case state do
%{reply_fun: reply_fun} ->
reply_fun.(reason)
exit(reason)
_ ->
terminate(reason, parent, debug, state)
end
{^ref, {:ok, new_conn}} ->
Process.demonitor(ref, [:flush])
new_state =
Map.delete(state, :task)
|> Map.put(:conn, new_conn)
{:ok, new_state}
{^ref, {:error, reason}} ->
Process.demonitor(ref, [:flush])
new_state = Map.delete(state, :task)
{:error, reason, new_state}
end
end
defp websocket_loop(parent, debug, state) do
case WebSockex.Frame.parse_frame(state.buffer) do
{:ok, frame, buffer} ->
debug = Utils.sys_debug(debug, {:in, :frame, frame}, state)
execute_telemetry([:websockex, :frame, :received], state, %{frame: frame})
handle_frame(frame, parent, debug, %{state | buffer: buffer})
:incomplete ->
transport = state.conn.transport
socket = state.conn.socket
receive do
{:system, from, req} ->
state = Map.put(state, :connection_status, :connected)
:sys.handle_system_msg(req, from, parent, __MODULE__, debug, state)
{:"$websockex_cast", msg} ->
debug = Utils.sys_debug(debug, {:in, :cast, msg}, state)
common_handle({:handle_cast, msg}, parent, debug, state)
{:"$websockex_send", from, frame} ->
sync_send(frame, from, parent, debug, state)
{^transport, ^socket, message} ->
buffer = <<state.buffer::bitstring, message::bitstring>>
websocket_loop(parent, debug, %{state | buffer: buffer})
{:tcp_closed, ^socket} ->
handle_close({:remote, :closed}, parent, debug, state)
{:ssl_closed, ^socket} ->
handle_close({:remote, :closed}, parent, debug, state)
{:EXIT, ^parent, reason} ->
terminate(reason, parent, debug, state)
msg ->
debug = Utils.sys_debug(debug, {:in, :msg, msg}, state)
common_handle({:handle_info, msg}, parent, debug, state)
end
end
end
defp close_loop(reason, parent, debug, %{conn: conn, timer_ref: timer_ref} = state) do
transport = state.conn.transport
socket = state.conn.socket
receive do
{:system, from, req} ->
state = Map.put(state, :connection_status, {:closing, reason})
:sys.handle_system_msg(req, from, parent, __MODULE__, debug, state)
{:EXIT, ^parent, reason} ->
terminate(reason, parent, debug, state)
{^transport, ^socket, _} ->
close_loop(reason, parent, debug, state)
{:"$websockex_send", from, _frame} ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :closing}})
close_loop(reason, parent, debug, state)
{close_mod, ^socket} when close_mod in [:tcp_closed, :ssl_closed] ->
new_conn = %{conn | socket: nil}
debug = Utils.sys_debug(debug, :closed, state)
purge_timer(timer_ref, :websockex_close_timeout)
state = Map.delete(state, :timer_ref)
on_disconnect(reason, parent, debug, %{state | conn: new_conn})
:"$websockex_close_timeout" ->
new_conn = WebSockex.Conn.close_socket(conn)
debug = Utils.sys_debug(debug, :timeout_closed, state)
on_disconnect(reason, parent, debug, %{state | conn: new_conn})
end
end
# Frame Handling
defp handle_frame(:ping, parent, debug, state) do
common_handle({:handle_ping, :ping}, parent, debug, state)
end
defp handle_frame({:ping, msg}, parent, debug, state) do
common_handle({:handle_ping, {:ping, msg}}, parent, debug, state)
end
defp handle_frame(:pong, parent, debug, state) do
common_handle({:handle_pong, :pong}, parent, debug, state)
end
defp handle_frame({:pong, msg}, parent, debug, state) do
common_handle({:handle_pong, {:pong, msg}}, parent, debug, state)
end
defp handle_frame(:close, parent, debug, state) do
handle_close({:remote, :normal}, parent, debug, state)
end
defp handle_frame({:close, code, reason}, parent, debug, state) do
handle_close({:remote, code, reason}, parent, debug, state)
end
defp handle_frame({:fragment, _, _} = fragment, parent, debug, state) do
handle_fragment(fragment, parent, debug, state)
end
defp handle_frame({:continuation, _} = fragment, parent, debug, state) do
handle_fragment(fragment, parent, debug, state)
end
defp handle_frame({:finish, _} = fragment, parent, debug, state) do
handle_fragment(fragment, parent, debug, state)
end
defp handle_frame(frame, parent, debug, state) do
common_handle({:handle_frame, frame}, parent, debug, state)
end
defp handle_fragment({:fragment, type, part}, parent, debug, %{fragment: nil} = state) do
websocket_loop(parent, debug, %{state | fragment: {type, part}})
end
defp handle_fragment({:fragment, _, _}, parent, debug, state) do
handle_close(
{:local, 1002, "Endpoint tried to start a fragment without finishing another"},
parent,
debug,
state
)
end
defp handle_fragment({:continuation, _}, parent, debug, %{fragment: nil} = state) do
handle_close(
{:local, 1002, "Endpoint sent a continuation frame without starting a fragment"},
parent,
debug,
state
)
end
defp handle_fragment({:continuation, next}, parent, debug, %{fragment: {type, part}} = state) do
websocket_loop(parent, debug, %{state | fragment: {type, <<part::binary, next::binary>>}})
end
defp handle_fragment({:finish, next}, parent, debug, %{fragment: {type, part}} = state) do
frame = {type, <<part::binary, next::binary>>}
debug = Utils.sys_debug(debug, {:in, :completed_fragment, frame}, state)
handle_frame(frame, parent, debug, %{state | fragment: nil})
end
defp handle_close({:remote, :closed} = reason, parent, debug, state) do
debug = Utils.sys_debug(debug, {:close, :remote, :unexpected}, state)
new_conn = %{state.conn | socket: nil}
on_disconnect(reason, parent, debug, %{state | conn: new_conn})
end
defp handle_close({:remote, _} = reason, parent, debug, state) do
handle_remote_close(reason, parent, debug, state)
end
defp handle_close({:remote, _, _} = reason, parent, debug, state) do
handle_remote_close(reason, parent, debug, state)
end
defp handle_close({:local, _} = reason, parent, debug, state) do
handle_local_close(reason, parent, debug, state)
end
defp handle_close({:local, _, _} = reason, parent, debug, state) do
handle_local_close(reason, parent, debug, state)
end
defp handle_close({:error, _} = reason, parent, debug, state) do
handle_error_close(reason, parent, debug, state)
end
defp common_handle({function, msg}, parent, debug, state) do
result = try_callback(state.module, function, [msg, state.module_state])
case result do
{:ok, new_state} ->
websocket_loop(parent, debug, %{state | module_state: new_state})
{:reply, frame, new_state} ->
# A `with` that includes `else` clause isn't tail recursive (elixir-lang/elixir#6251)
res =
with {:ok, binary_frame} <- WebSockex.Frame.encode_frame(frame),
do: WebSockex.Conn.socket_send(state.conn, binary_frame)
case res do
:ok ->
debug = Utils.sys_debug(debug, {:reply, function, frame}, state)
websocket_loop(parent, debug, %{state | module_state: new_state})
{:error, error} ->
handle_close({:error, error}, parent, debug, %{state | module_state: new_state})
end
{:close, new_state} ->
handle_close({:local, :normal}, parent, debug, %{state | module_state: new_state})
{:close, {close_code, message}, new_state} ->
handle_close({:local, close_code, message}, parent, debug, %{
state
| module_state: new_state
})
{:"$EXIT", reason} ->
handle_terminate_close(reason, parent, debug, state)
badreply ->
error = %WebSockex.BadResponseError{
module: state.module,
function: function,
args: [msg, state.module_state],
response: badreply
}
terminate(error, parent, debug, state)
end
end
defp handle_remote_close(reason, parent, debug, state) do
debug = Utils.sys_debug(debug, {:close, :remote, reason}, state)
# If the socket is already closed then that's ok, but the spec says to send
# the close frame back in response to receiving it.
debug =
case send_close_frame(reason, state.conn) do
:ok -> Utils.sys_debug(debug, {:socket_out, :close, reason}, state)
_ -> debug
end
timer_ref = Process.send_after(self(), :"$websockex_close_timeout", 5000)
close_loop(reason, parent, debug, Map.put(state, :timer_ref, timer_ref))
end
defp handle_local_close(reason, parent, debug, state) do
debug = Utils.sys_debug(debug, {:close, :local, reason}, state)
case send_close_frame(reason, state.conn) do
:ok ->
debug = Utils.sys_debug(debug, {:socket_out, :close, reason}, state)
timer_ref = Process.send_after(self(), :"$websockex_close_timeout", 5000)
close_loop(reason, parent, debug, Map.put(state, :timer_ref, timer_ref))
{:error, %WebSockex.ConnError{original: reason}} when reason in [:closed, :einval] ->
handle_close({:remote, :closed}, parent, debug, state)
end
end
defp handle_error_close(reason, parent, debug, state) do
send_close_frame(:error, state.conn)
timer_ref = Process.send_after(self(), :"$websockex_close_timeout", 5000)
close_loop(reason, parent, debug, Map.put(state, :timer_ref, timer_ref))
end
@spec handle_terminate_close(any, pid, any, any) :: no_return
def handle_terminate_close(reason, parent, debug, state) do
debug = Utils.sys_debug(debug, {:close, :error, reason}, state)
debug =
case send_close_frame(:error, state.conn) do
:ok -> Utils.sys_debug(debug, {:socket_out, :close, :error}, state)
_ -> debug
end
# I'm not supposed to do this, but I'm going to go ahead and close the
# socket here. If people complain I'll come up with something else.
new_conn = WebSockex.Conn.close_socket(state.conn)
terminate(reason, parent, debug, %{state | conn: new_conn})
end
# Frame Sending
defp sync_send(frame, from, parent, debug, %{conn: conn} = state) do
res =
with {:ok, binary_frame} <- WebSockex.Frame.encode_frame(frame),
do: WebSockex.Conn.socket_send(conn, binary_frame)
case res do
:ok ->
execute_telemetry([:websockex, :frame, :sent], state, %{frame: frame})
:gen.reply(from, :ok)
debug = Utils.sys_debug(debug, {:socket_out, :sync_send, frame}, state)
websocket_loop(parent, debug, state)
{:error, %WebSockex.ConnError{original: reason}} = error
when reason in [:closed, :einval] ->
:gen.reply(from, error)
handle_close(error, parent, debug, state)
{:error, _} = error ->
:gen.reply(from, error)
websocket_loop(parent, debug, state)
end
end
defp send_close_frame(reason, conn) do
with {:ok, binary_frame} <- build_close_frame(reason),
do: WebSockex.Conn.socket_send(conn, binary_frame)
end
defp build_close_frame({_, :normal}) do
WebSockex.Frame.encode_frame(:close)
end
defp build_close_frame({_, code, msg}) do
WebSockex.Frame.encode_frame({:close, code, msg})
end
defp build_close_frame(:error) do
WebSockex.Frame.encode_frame({:close, 1011, ""})
end
# Connection Handling
defp init_conn_failure(reason, parent, debug, state, attempt \\ 1) do
case handle_disconnect(reason, state, attempt) do
{:ok, new_module_state} ->
init_failure(reason, parent, debug, %{state | module_state: new_module_state})
{:reconnect, new_conn, new_module_state} ->
state = %{state | conn: new_conn, module_state: new_module_state}
debug = Utils.sys_debug(debug, :reconnect, state)
case open_connection(parent, debug, state) do
{:ok, new_state} ->
debug = Utils.sys_debug(debug, :connected, state)
module_init(parent, debug, new_state)
{:error, new_reason, new_state} ->
init_conn_failure(new_reason, parent, debug, new_state, attempt + 1)
end
{:"$EXIT", reason} ->
init_failure(reason, parent, debug, state)
end
end
defp on_disconnect(reason, parent, debug, state, attempt \\ 1) do
case handle_disconnect(reason, state, attempt) do
{:ok, new_module_state} when is_tuple(reason) and elem(reason, 0) == :error ->
terminate(elem(reason, 1), parent, debug, %{state | module_state: new_module_state})
{:ok, new_module_state} ->
terminate(reason, parent, debug, %{state | module_state: new_module_state})
{:reconnect, new_conn, new_module_state} ->
state = %{state | conn: new_conn, module_state: new_module_state}
debug = Utils.sys_debug(debug, :reconnect, state)
case open_connection(parent, debug, state) do
{:ok, new_state} ->
debug = Utils.sys_debug(debug, :reconnected, state)
reconnect(parent, debug, new_state)
{:error, new_reason, new_state} ->
on_disconnect(new_reason, parent, debug, new_state, attempt + 1)
end
{:"$EXIT", reason} ->
terminate(reason, parent, debug, state)
end
end
defp reconnect(parent, debug, state) do
result = try_callback(state.module, :handle_connect, [state.conn, state.module_state])
case result do
{:ok, new_module_state} ->
state = Map.merge(state, %{buffer: <<>>, fragment: nil, module_state: new_module_state})
websocket_loop(parent, debug, state)
{:"$EXIT", reason} ->
terminate(reason, parent, debug, state)
badreply ->
reason = %WebSockex.BadResponseError{
module: state.module,
function: :handle_connect,
args: [state.conn, state.module_state],
response: badreply
}
terminate(reason, parent, debug, state)
end
end
defp open_connection(parent, debug, %{conn: conn} = state) do
my_pid = self()
debug = Utils.sys_debug(debug, :connect, state)
task =
Task.async(fn ->
with {:ok, conn} <- WebSockex.Conn.open_socket(conn),
key <- :crypto.strong_rand_bytes(16) |> Base.encode64(),
{:ok, request} <- WebSockex.Conn.build_request(conn, key),
:ok <- WebSockex.Conn.socket_send(conn, request),
{:ok, headers} <- WebSockex.Conn.handle_response(conn, my_pid),
:ok <- validate_handshake(headers, key) do
:ok = WebSockex.Conn.controlling_process(conn, my_pid)
:ok = WebSockex.Conn.set_active(conn)
{:ok, %{conn | resp_headers: headers}}
end
end)
open_loop(parent, debug, Map.put(state, :task, task))
end
# Other State Functions
defp module_init(parent, debug, state) do
execute_telemetry([:websockex, :connected], state)
result = try_callback(state.module, :handle_connect, [state.conn, state.module_state])
case result do
{:ok, new_module_state} ->
state.reply_fun.({:ok, self()})
state =
Map.put(state, :module_state, new_module_state)
|> Map.delete(:reply_fun)
websocket_loop(parent, debug, state)
{:"$EXIT", reason} ->
state.reply_fun.(reason)
badreply ->
reason =
{:error,
%WebSockex.BadResponseError{
module: state.module,
function: :handle_connect,
args: [state.conn, state.module_state],
response: badreply
}}
state.reply_fun.(reason)
end
end
@spec terminate(any, pid, any, any) :: no_return
defp terminate(reason, parent, debug, state) do
execute_telemetry([:websockex, :terminate], state, %{reason: reason})
do_terminate(reason, parent, debug, state)
end
defp do_terminate(reason, parent, debug, %{conn: %{socket: socket}} = state)
when not is_nil(socket) do
handle_terminate_close(reason, parent, debug, state)
end
defp do_terminate(reason, _parent, _debug, %{module: mod, module_state: mod_state}) do
mod.terminate(reason, mod_state)
case reason do
{_, :normal} ->
exit(:normal)
{_, 1000, _} ->
exit(:normal)
_ ->
exit(reason)
end
end
defp handle_disconnect(reason, state, attempt) do
status_map = %{conn: state.conn, reason: reason, attempt_number: attempt}
execute_telemetry([:websockex, :disconnected], state, status_map)
result = try_callback(state.module, :handle_disconnect, [status_map, state.module_state])
case result do
{:ok, new_state} ->
{:ok, new_state}
{:reconnect, new_state} ->
{:reconnect, state.conn, new_state}
{:reconnect, new_conn, new_state} ->
{:reconnect, new_conn, new_state}
{:"$EXIT", _} = res ->
res
badreply ->
{:"$EXIT",
%WebSockex.BadResponseError{
module: state.module,
function: :handle_disconnect,
args: [status_map, state.module_state],
response: badreply
}}
end
end
# Helpers (aka everything else)
defp try_callback(module, function, args) do
apply(module, function, args)
catch
:error, payload ->
stacktrace = __STACKTRACE__
reason = Exception.normalize(:error, payload, stacktrace)
{:"$EXIT", {reason, stacktrace}}
:exit, payload ->
{:"$EXIT", payload}
end
defp init_failure(reason, _parent, _debug, state) do
state.reply_fun.({:error, reason})
end
defp async_init_fun({:ok, _}), do: :noop
defp async_init_fun(exit_reason), do: exit(exit_reason)
defp sync_init_fun(parent, {error, stacktrace}) when is_list(stacktrace) do
:proc_lib.init_ack(parent, {:error, error})
end
defp sync_init_fun(parent, reply) do
:proc_lib.init_ack(parent, reply)
end
defp validate_handshake(headers, key) do
challenge = :crypto.hash(:sha, key <> @handshake_guid) |> Base.encode64()
{_, res} = List.keyfind(headers, "Sec-Websocket-Accept", 0)
if challenge == res do
:ok
else
{:error, %WebSockex.HandshakeError{response: res, challenge: challenge}}
end
end
defp purge_timer(ref, msg) do
case Process.cancel_timer(ref) do
i when is_integer(i) ->
:ok
false ->
receive do
^msg -> :ok
after
100 -> :ok
end
end
end
if WebSockex.Utils.otp_release() >= 21 do
defp execute_telemetry(event, state, extra_metadata \\ %{}) do
metadata = Map.merge(%{conn: state.conn, module: state.module}, extra_metadata)
:telemetry.execute(event, %{time: System.system_time()}, metadata)
end
else
defp execute_telemetry(_, _, _ \\ %{}), do: :ok
end
end
| 31.420168 | 98 | 0.626504 |
73b252d7cc95291fa629d37a5aee794baf7e1dd7 | 1,345 | ex | Elixir | lib/pub_sub_example.ex | kevindwells/broadway_cloud_pub_sub_example | 65109ac6f710527ee7ddf8e924f0f1c9c517abc3 | [
"Apache-2.0"
] | 2 | 2020-11-16T20:41:05.000Z | 2021-02-24T14:09:53.000Z | lib/pub_sub_example.ex | kevindwells/broadway_cloud_pub_sub_example | 65109ac6f710527ee7ddf8e924f0f1c9c517abc3 | [
"Apache-2.0"
] | null | null | null | lib/pub_sub_example.ex | kevindwells/broadway_cloud_pub_sub_example | 65109ac6f710527ee7ddf8e924f0f1c9c517abc3 | [
"Apache-2.0"
] | null | null | null | defmodule PubSubExample do
@moduledoc """
Example project for consuming Cloud Pub/Sub messages with `BroadwayCloudPubSub`.
"""
@doc """
Hello world.
## Examples
iex> PubSubExample.hello()
:world
"""
def hello do
:world
end
@doc """
Returns a value from the application config.
"""
def get_env(key, default \\ nil) do
Application.get_env(:broadway_cloud_pub_sub_example, key, default)
end
@doc """
Returns the `:project_id` from the `Goth` config.
"""
def project_id do
{:ok, project_id} = Goth.Config.get(:project_id)
project_id
end
@doc """
Publishes a message to the example topic.
"""
def publish(message) when is_binary(message) do
topic_id = get_env(PubSubExample.SetupTask)[:topic_id]
with {:ok, _} <- PubSubExample.Client.publish_message(topic_id, message) do
:ok
end
end
def publish(attrs) when is_map(attrs) do
topic_id = get_env(PubSubExample.SetupTask)[:topic_id]
with {:ok, _} <- PubSubExample.Client.publish_message(topic_id, nil, attrs) do
:ok
end
end
def publish({message, attrs}) when is_binary(message) and is_map(attrs) do
topic_id = get_env(PubSubExample.SetupTask)[:topic_id]
with {:ok, _} <- PubSubExample.Client.publish_message(topic_id, message, attrs) do
:ok
end
end
end
| 22.04918 | 86 | 0.671375 |
73b25dd89e064491a37508a7ed0c4731255455b0 | 1,604 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/vpn_gateway_vpn_gateway_interface.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/vpn_gateway_vpn_gateway_interface.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/vpn_gateway_vpn_gateway_interface.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.VpnGatewayVpnGatewayInterface do
@moduledoc """
A VPN gateway interface.
## Attributes
* `id` (*type:* `integer()`, *default:* `nil`) - The numeric ID of this VPN gateway interface.
* `ipAddress` (*type:* `String.t`, *default:* `nil`) - The external IP address for this VPN gateway interface.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:id => integer(),
:ipAddress => String.t()
}
field(:id)
field(:ipAddress)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.VpnGatewayVpnGatewayInterface do
def decode(value, options) do
GoogleApi.Compute.V1.Model.VpnGatewayVpnGatewayInterface.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.VpnGatewayVpnGatewayInterface do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.08 | 114 | 0.72818 |
73b2658077350fb4dac4afe24390026794273290 | 553 | exs | Elixir | test/ambry_web/static_files_test.exs | doughsay/ambry | c04e855bf06a6b00b8053c6eacb2eac14a56a37c | [
"MIT"
] | 12 | 2021-09-30T20:51:49.000Z | 2022-01-27T04:09:32.000Z | test/ambry_web/static_files_test.exs | doughsay/ambry | c04e855bf06a6b00b8053c6eacb2eac14a56a37c | [
"MIT"
] | 76 | 2021-10-01T05:45:11.000Z | 2022-03-28T04:12:39.000Z | test/ambry_web/static_files_test.exs | doughsay/ambry | c04e855bf06a6b00b8053c6eacb2eac14a56a37c | [
"MIT"
] | 2 | 2021-10-04T19:27:28.000Z | 2022-01-13T22:36:38.000Z | defmodule AmbryWeb.StaticFilesTest do
use AmbryWeb.ConnCase
setup :register_and_put_user_api_token
describe "GET /uploads/:path" do
test "returns 401 if missing api token", %{conn: conn} do
conn = remove_user_api_token(conn)
conn = get(conn, "/uploads/media/non-existent-file")
assert "Unauthorized" = response(conn, 401)
end
test "returns 404 for a non existent file", %{conn: conn} do
conn = get(conn, "/uploads/media/non-existent-file")
assert "Not Found" = response(conn, 404)
end
end
end
| 25.136364 | 64 | 0.679928 |
73b294d6e74bea98150496ad37959a61350d9816 | 57 | ex | Elixir | web/views/layout_view.ex | CaseyKelly/PhoenixAuthAPI | d3795f9dbc94efbd3aa869a6c4960add1a68e05f | [
"Apache-2.0"
] | null | null | null | web/views/layout_view.ex | CaseyKelly/PhoenixAuthAPI | d3795f9dbc94efbd3aa869a6c4960add1a68e05f | [
"Apache-2.0"
] | null | null | null | web/views/layout_view.ex | CaseyKelly/PhoenixAuthAPI | d3795f9dbc94efbd3aa869a6c4960add1a68e05f | [
"Apache-2.0"
] | null | null | null | defmodule MyApp.LayoutView do
use MyApp.Web, :view
end
| 14.25 | 29 | 0.77193 |
73b2a06d8580fcb8c7f02592c9ba15881ffa6d45 | 3,799 | exs | Elixir | test/chat_api/forwarding_addresses_test.exs | hakerspeak/hakerspeak.com | efd9e75f4854fdd19fc1873300deae0b160fb629 | [
"MIT"
] | null | null | null | test/chat_api/forwarding_addresses_test.exs | hakerspeak/hakerspeak.com | efd9e75f4854fdd19fc1873300deae0b160fb629 | [
"MIT"
] | null | null | null | test/chat_api/forwarding_addresses_test.exs | hakerspeak/hakerspeak.com | efd9e75f4854fdd19fc1873300deae0b160fb629 | [
"MIT"
] | null | null | null | defmodule ChatApi.ForwardingAddressesTest do
use ChatApi.DataCase, async: true
import ChatApi.Factory
alias ChatApi.ForwardingAddresses
describe "forwarding_addresses" do
alias ChatApi.ForwardingAddresses.ForwardingAddress
@update_attrs %{
forwarding_email_address: "[email protected]",
source_email_address: "[email protected]",
description: "some updated description",
state: "some updated state"
}
@invalid_attrs %{
forwarding_email_address: nil
}
setup do
account = insert(:account)
forwarding_address = insert(:forwarding_address, account: account)
{:ok, account: account, forwarding_address: forwarding_address}
end
test "list_forwarding_addresses/1 returns all forwarding_addresses", %{
account: account,
forwarding_address: forwarding_address
} do
forwarding_address_ids =
ForwardingAddresses.list_forwarding_addresses(account.id)
|> Enum.map(& &1.id)
assert forwarding_address_ids == [forwarding_address.id]
end
test "get_forwarding_address!/1 returns the forwarding_address with given id", %{
forwarding_address: forwarding_address
} do
found_forwarding_address =
ForwardingAddresses.get_forwarding_address!(forwarding_address.id)
|> Repo.preload([:account])
assert found_forwarding_address == forwarding_address
end
test "create_forwarding_address/1 with valid data creates a forwarding_address", %{
account: account
} do
attrs =
params_with_assocs(:forwarding_address,
account: account,
forwarding_email_address: "[email protected]"
)
assert {:ok, %ForwardingAddress{forwarding_email_address: "[email protected]"}} =
ForwardingAddresses.create_forwarding_address(attrs)
end
test "create_forwarding_address/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} =
ForwardingAddresses.create_forwarding_address(@invalid_attrs)
end
test "update_forwarding_address/2 with valid data updates the forwarding_address", %{
forwarding_address: forwarding_address
} do
assert {:ok, %ForwardingAddress{} = forwarding_address} =
ForwardingAddresses.update_forwarding_address(forwarding_address, @update_attrs)
assert forwarding_address.forwarding_email_address == "[email protected]"
assert forwarding_address.source_email_address == "[email protected]"
assert forwarding_address.description == "some updated description"
assert forwarding_address.state == "some updated state"
end
test "update_forwarding_address/2 with invalid data returns error changeset", %{
forwarding_address: forwarding_address
} do
assert {:error, %Ecto.Changeset{}} =
ForwardingAddresses.update_forwarding_address(forwarding_address, @invalid_attrs)
assert forwarding_address ==
ForwardingAddresses.get_forwarding_address!(forwarding_address.id)
|> Repo.preload([:account])
end
test "delete_forwarding_address/1 deletes the forwarding_address", %{
forwarding_address: forwarding_address
} do
assert {:ok, %ForwardingAddress{}} =
ForwardingAddresses.delete_forwarding_address(forwarding_address)
assert_raise Ecto.NoResultsError, fn ->
ForwardingAddresses.get_forwarding_address!(forwarding_address.id)
end
end
test "change_forwarding_address/1 returns a forwarding_address changeset", %{
forwarding_address: forwarding_address
} do
assert %Ecto.Changeset{} = ForwardingAddresses.change_forwarding_address(forwarding_address)
end
end
end
| 35.504673 | 98 | 0.71782 |
73b2a106113be721d78345c97c146ed9f6303ba1 | 544 | ex | Elixir | lib/ash/error/forbidden.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | 528 | 2019-12-08T01:51:54.000Z | 2022-03-30T10:09:45.000Z | lib/ash/error/forbidden.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | 278 | 2019-12-04T15:25:06.000Z | 2022-03-31T03:40:51.000Z | lib/ash/error/forbidden.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | 53 | 2020-08-17T22:08:09.000Z | 2022-03-24T01:58:59.000Z | defmodule Ash.Error.Forbidden do
@moduledoc "Used when authorization for an action fails"
use Ash.Error.Exception
def_ash_error([:errors, stacktraces?: true], class: :forbidden)
defimpl Ash.ErrorKind do
def id(_), do: Ash.UUID.generate()
def message(%{errors: errors, stacktraces?: stacktraces?}) when not is_nil(errors) do
Ash.Error.error_messages(errors, nil, stacktraces?)
end
def message(%{errors: errors}) do
Ash.Error.error_descriptions(errors)
end
def code(_), do: "Forbidden"
end
end
| 24.727273 | 89 | 0.698529 |
73b2db4b39c65914417094d58accd18770318f11 | 931 | ex | Elixir | apps/decoder_gtfs/lib/decoder/gtfs.ex | jdenen/hindsight | ef69b4c1a74c94729dd838a9a0849a48c9b6e04c | [
"Apache-2.0"
] | 12 | 2020-01-27T19:43:02.000Z | 2021-07-28T19:46:29.000Z | apps/decoder_gtfs/lib/decoder/gtfs.ex | jdenen/hindsight | ef69b4c1a74c94729dd838a9a0849a48c9b6e04c | [
"Apache-2.0"
] | 81 | 2020-01-28T18:07:23.000Z | 2021-11-22T02:12:13.000Z | apps/decoder_gtfs/lib/decoder/gtfs.ex | jdenen/hindsight | ef69b4c1a74c94729dd838a9a0849a48c9b6e04c | [
"Apache-2.0"
] | 10 | 2020-02-13T21:24:09.000Z | 2020-05-21T18:39:35.000Z | defmodule Decoder.Gtfs do
@moduledoc """
Defines a `Decoder` impl for GTFS data.
## Configuration
* `chunk_size` - Limits chunks by bytes. Defaults to 100.
"""
use Definition, schema: Decoder.Gtfs.V1
use JsonSerde, alias: "decoder_gtfs"
@derive Jason.Encoder
defstruct chunk_size: 100
defimpl Decoder do
def lines_or_bytes(_t), do: 2048
def decode(_t, messages) do
messages
|> TransitRealtime.FeedMessage.decode()
|> Map.get(:entity)
|> Enum.map(&Decoder.Gtfs.decode_struct/1)
end
end
def decode_struct(%_struct{} = entity) do
entity
|> Map.from_struct()
|> Map.new(fn {k, v} -> {Atom.to_string(k), decode_struct(v)} end)
end
def decode_struct(element), do: element
end
defmodule Decoder.Gtfs.V1 do
@moduledoc false
use Definition.Schema
@impl true
def s do
schema(%Decoder.Gtfs{
chunk_size: spec(is_integer())
})
end
end
| 20.23913 | 70 | 0.662728 |
73b2dbc9a967c5651cd54067b20e3ed939db1663 | 847 | ex | Elixir | test/bearings_web/features/pages/dailies_show_page.ex | tmecklem/bearings | 98efda7baba7a4170c46da6a4ccb4f954b0ddc5a | [
"MIT"
] | 3 | 2018-05-29T12:16:14.000Z | 2019-09-25T21:12:36.000Z | test/bearings_web/features/pages/dailies_show_page.ex | tmecklem/bearings | 98efda7baba7a4170c46da6a4ccb4f954b0ddc5a | [
"MIT"
] | 23 | 2018-05-25T21:09:43.000Z | 2021-12-16T05:45:25.000Z | test/bearings_web/features/pages/dailies_show_page.ex | tmecklem/bearings | 98efda7baba7a4170c46da6a4ccb4f954b0ddc5a | [
"MIT"
] | null | null | null | defmodule BearingsWeb.DailiesShowPage do
@moduledoc """
Module to interact with dailies show pages
"""
use Wallaby.DSL
import Wallaby.Query, only: [css: 1, css: 2]
alias BearingsWeb.Endpoint
alias BearingsWeb.Router.Helpers, as: Routes
def visit_page(session, owner, daily) do
visit(
session,
Routes.live_path(Endpoint, BearingsWeb.DailiesLive.Show, owner.username, daily)
)
end
def goal_body(goal) do
css("[data-test='goal'][data-test-id='#{goal.id}'] [data-test='body']", text: goal.body)
end
def personal_journal do
css("[data-test='personal_journal']")
end
def goal_completed(goal) do
text =
case goal.completed do
true -> "☑"
false -> "☐"
end
css("[data-test='goal'][data-test-id='#{goal.id}'] [data-test='completed']", text: text)
end
end
| 22.289474 | 92 | 0.645809 |
73b2f9f0ecd616efa2fdb0bbc7a0e8b7a5c31a85 | 1,398 | ex | Elixir | Microsoft.Azure.Management.Preview.Addons/lib/microsoft/azure/management/preview/addons/deserializer.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Preview.Addons/lib/microsoft/azure/management/preview/addons/deserializer.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Preview.Addons/lib/microsoft/azure/management/preview/addons/deserializer.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule Microsoft.Azure.Management.Preview.Addons.Deserializer do
@moduledoc """
Helper functions for deserializing responses into models
"""
@doc """
Update the provided model with a deserialization of a nested value
"""
@spec deserialize(struct(), :atom, :atom, struct(), keyword()) :: struct()
def deserialize(model, field, :list, mod, options) do
model
|> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: [struct(mod)]]))))
end
def deserialize(model, field, :struct, mod, options) do
model
|> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: struct(mod)]))))
end
def deserialize(model, field, :map, mod, options) do
model
|> Map.update!(field, &(Map.new(&1, fn {key, val} -> {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} end)))
end
def deserialize(model, field, :date, _, _options) do
value = Map.get(model, field)
case is_binary(value) do
true -> case DateTime.from_iso8601(value) do
{:ok, datetime, _offset} ->
Map.put(model, field, datetime)
_ ->
model
end
false -> model
end
end
end
| 35.846154 | 139 | 0.63877 |
73b320808018987a25510233134a71118c04c6cb | 1,182 | ex | Elixir | lib/lint/rules/trailing_question_mark.ex | VadymBerezdetskyi/accent | 19d2205c7594ac5f0de40e2aaa8ff3c5190a8518 | [
"BSD-3-Clause"
] | null | null | null | lib/lint/rules/trailing_question_mark.ex | VadymBerezdetskyi/accent | 19d2205c7594ac5f0de40e2aaa8ff3c5190a8518 | [
"BSD-3-Clause"
] | 6 | 2021-03-11T07:37:48.000Z | 2022-02-13T21:10:33.000Z | lib/lint/rules/trailing_question_mark.ex | doc-ai/accent | e337e16f3658cc0728364f952c0d9c13710ebb06 | [
"BSD-3-Clause"
] | 1 | 2020-05-29T21:47:35.000Z | 2020-05-29T21:47:35.000Z | defmodule Accent.Lint.Rules.TrailingQuestionMark do
@moduledoc """
Checks that question marks are replicated between both source and translation.
"""
@behaviour Accent.Lint.Rule
@regex ~r/.+\?$/
alias Accent.Lint.Message
def lint(value = %{entry: %{is_master: true}}, _), do: value
def lint(value, _) do
text = value.entry.value
master = value.entry.master_value
master_has_trailing_question_mark? = Regex.match?(@regex, master)
text_has_trailing_question_mark? = Regex.match?(@regex, text)
if master_has_trailing_question_mark? and !text_has_trailing_question_mark? do
Accent.Lint.add_message(
value,
%Message{
context: %Message.Context{
offset: 0,
length: String.length(text),
text: text
},
text: Accent.Lint.display_trailing_text(value.entry.master_value),
replacements: [%Message.Replacement{value: text <> "?"}],
rule: %Message.Rule{
id: "TRAILING_QUESTION_MARK",
description: "Translation does not match question mark of the source"
}
}
)
else
value
end
end
end
| 28.142857 | 82 | 0.633672 |
73b33ccff5fd84d6b19055e5e9c9e7827aa0dddb | 1,322 | ex | Elixir | lib/rdf/exceptions.ex | rdf-elixir/rdf-ex | 7d4280ec9a912ef6ee9fc96ecdfdf26647016d6a | [
"MIT"
] | 19 | 2020-06-05T16:55:54.000Z | 2022-03-22T10:30:11.000Z | lib/rdf/exceptions.ex | rdf-elixir/rdf-ex | 7d4280ec9a912ef6ee9fc96ecdfdf26647016d6a | [
"MIT"
] | 4 | 2020-07-03T21:02:55.000Z | 2021-11-18T07:22:06.000Z | lib/rdf/exceptions.ex | rdf-elixir/rdf-ex | 7d4280ec9a912ef6ee9fc96ecdfdf26647016d6a | [
"MIT"
] | 3 | 2020-07-03T13:25:36.000Z | 2021-04-04T12:33:51.000Z | defmodule RDF.IRI.InvalidError do
defexception [:message]
end
defmodule RDF.Literal.InvalidError do
defexception [:message]
end
defmodule RDF.Triple.InvalidSubjectError do
defexception [:subject]
def message(%{subject: subject}) do
"'#{inspect(subject)}' is not a valid subject of a RDF.Triple"
end
end
defmodule RDF.Triple.InvalidPredicateError do
defexception [:predicate]
def message(%{predicate: predicate}) do
"'#{inspect(predicate)}' is not a valid predicate of a RDF.Triple"
end
end
defmodule RDF.XSD.Datatype.Mismatch do
defexception [:value, :expected_type]
def message(%{value: value, expected_type: expected_type}) do
"'#{inspect(value)}' is not a #{expected_type}"
end
end
defmodule RDF.Quad.InvalidGraphContextError do
defexception [:graph_context]
def message(%{graph_context: graph_context}) do
"'#{inspect(graph_context)}' is not a valid graph context of a RDF.Quad"
end
end
defmodule RDF.Namespace.InvalidVocabBaseIRIError do
defexception [:message]
end
defmodule RDF.Namespace.InvalidTermError do
defexception [:message]
end
defmodule RDF.Namespace.InvalidAliasError do
defexception [:message]
end
defmodule RDF.Namespace.UndefinedTermError do
defexception [:message]
end
defmodule RDF.Query.InvalidError do
defexception [:message]
end
| 22.033333 | 76 | 0.760968 |
73b358abdbfb84dd6c82168a255b4c2ff2c926fd | 4,298 | ex | Elixir | lib/mix/tasks/ecto.rollback.ex | thenrio/ecto_sql | 151ff5076098a85c8cd415ca613bb1cb7dd290a5 | [
"Apache-2.0"
] | 4 | 2019-06-26T22:43:55.000Z | 2020-01-19T17:37:07.000Z | lib/mix/tasks/ecto.rollback.ex | thenrio/ecto_sql | 151ff5076098a85c8cd415ca613bb1cb7dd290a5 | [
"Apache-2.0"
] | 3 | 2019-07-15T06:54:40.000Z | 2020-02-09T16:36:44.000Z | lib/mix/tasks/ecto.rollback.ex | thenrio/ecto_sql | 151ff5076098a85c8cd415ca613bb1cb7dd290a5 | [
"Apache-2.0"
] | 15 | 2019-01-15T18:17:44.000Z | 2020-01-12T03:52:35.000Z | defmodule Mix.Tasks.Ecto.Rollback do
use Mix.Task
import Mix.Ecto
import Mix.EctoSQL
@shortdoc "Rolls back the repository migrations"
@aliases [
r: :repo,
n: :step
]
@switches [
all: :boolean,
step: :integer,
to: :integer,
quiet: :boolean,
prefix: :string,
pool_size: :integer,
log_sql: :boolean,
repo: [:keep, :string],
no_compile: :boolean,
no_deps_check: :boolean,
migrations_path: :keep
]
@moduledoc """
Reverts applied migrations in the given repository.
Migrations are expected at "priv/YOUR_REPO/migrations" directory
of the current application, where "YOUR_REPO" is the last segment
in your repository name. For example, the repository `MyApp.Repo`
will use "priv/repo/migrations". The repository `Whatever.MyRepo`
will use "priv/my_repo/migrations".
You can configure a repository to use another directory by specifying
the `:priv` key under the repository configuration. The "migrations"
part will be automatically appended to it. For instance, to use
"priv/custom_repo/migrations":
config :my_app, MyApp.Repo, priv: "priv/custom_repo"
This task rolls back the last applied migration by default. To roll
back to a version number, supply `--to version_number`. To roll
back a specific number of times, use `--step n`. To undo all applied
migrations, provide `--all`.
The repositories to rollback are the ones specified under the
`:ecto_repos` option in the current app configuration. However,
if the `-r` option is given, it replaces the `:ecto_repos` config.
If a repository has not yet been started, one will be started outside
your application supervision tree and shutdown afterwards.
## Examples
mix ecto.rollback
mix ecto.rollback -r Custom.Repo
mix ecto.rollback -n 3
mix ecto.rollback --step 3
mix ecto.rollback --to 20080906120000
## Command line options
* `-r`, `--repo` - the repo to rollback
* `--all` - revert all applied migrations
* `--step` / `-n` - revert n number of applied migrations
* `--to` - revert all migrations down to and including version
* `--quiet` - do not log migration commands
* `--prefix` - the prefix to run migrations on
* `--pool-size` - the pool size if the repository is started only for the task (defaults to 2)
* `--log-sql` - log the raw sql migrations are running
* `--no-compile` - does not compile applications before rolling back
* `--no-deps-check` - does not check depedendencies before rolling back
* `--migrations-path` - the path to load the migrations from, defaults to
`"priv/repo/migrations"`. This option may be given multiple times in which case the migrations
are loaded from all the given directories and sorted as if they were all in the same one.
Note, if you have migrations paths e.g. `a/` and `b/`, and run
`mix ecto.rollback --migrations-path a/`, only the latest migrations from `a/` will be
rolled back (even if `b/` contains the overall latest migrations.)
"""
@impl true
def run(args, migrator \\ &Ecto.Migrator.run/4) do
repos = parse_repo(args)
{opts, _} = OptionParser.parse! args, strict: @switches, aliases: @aliases
opts =
if opts[:to] || opts[:step] || opts[:all],
do: opts,
else: Keyword.put(opts, :step, 1)
opts =
if opts[:quiet],
do: Keyword.merge(opts, [log: false, log_sql: false]),
else: opts
# Start ecto_sql explicitly before as we don't need
# to restart those apps if migrated.
{:ok, _} = Application.ensure_all_started(:ecto_sql)
for repo <- repos do
ensure_repo(repo, args)
paths = ensure_migrations_paths(repo, opts)
pool = repo.config[:pool]
fun =
if Code.ensure_loaded?(pool) and function_exported?(pool, :unboxed_run, 2) do
&pool.unboxed_run(&1, fn -> migrator.(&1, paths, :down, opts) end)
else
&migrator.(&1, paths, :down, opts)
end
case Ecto.Migrator.with_repo(repo, fun, [mode: :temporary] ++ opts) do
{:ok, _migrated, _apps} -> :ok
{:error, error} -> Mix.raise "Could not start repo #{inspect repo}, error: #{inspect error}"
end
end
:ok
end
end
| 31.602941 | 100 | 0.663797 |
73b38fe4667002a4c7264182a698f2dab5fd6320 | 17,322 | ex | Elixir | lib/codes/codes_v32.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_v32.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_v32.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_V32 do
alias IcdCode.ICDCode
def _V320XXA do
%ICDCode{full_code: "V320XXA",
category_code: "V32",
short_code: "0XXA",
full_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
short_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
category_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter"
}
end
def _V320XXD do
%ICDCode{full_code: "V320XXD",
category_code: "V32",
short_code: "0XXD",
full_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
short_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
category_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter"
}
end
def _V320XXS do
%ICDCode{full_code: "V320XXS",
category_code: "V32",
short_code: "0XXS",
full_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
short_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
category_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela"
}
end
def _V321XXA do
%ICDCode{full_code: "V321XXA",
category_code: "V32",
short_code: "1XXA",
full_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
short_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
category_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter"
}
end
def _V321XXD do
%ICDCode{full_code: "V321XXD",
category_code: "V32",
short_code: "1XXD",
full_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
short_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
category_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter"
}
end
def _V321XXS do
%ICDCode{full_code: "V321XXS",
category_code: "V32",
short_code: "1XXS",
full_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
short_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
category_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela"
}
end
def _V322XXA do
%ICDCode{full_code: "V322XXA",
category_code: "V32",
short_code: "2XXA",
full_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
short_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
category_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter"
}
end
def _V322XXD do
%ICDCode{full_code: "V322XXD",
category_code: "V32",
short_code: "2XXD",
full_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
short_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
category_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter"
}
end
def _V322XXS do
%ICDCode{full_code: "V322XXS",
category_code: "V32",
short_code: "2XXS",
full_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
short_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
category_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela"
}
end
def _V323XXA do
%ICDCode{full_code: "V323XXA",
category_code: "V32",
short_code: "3XXA",
full_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
short_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter",
category_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, initial encounter"
}
end
def _V323XXD do
%ICDCode{full_code: "V323XXD",
category_code: "V32",
short_code: "3XXD",
full_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
short_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter",
category_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, subsequent encounter"
}
end
def _V323XXS do
%ICDCode{full_code: "V323XXS",
category_code: "V32",
short_code: "3XXS",
full_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
short_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela",
category_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in nontraffic accident, sequela"
}
end
def _V324XXA do
%ICDCode{full_code: "V324XXA",
category_code: "V32",
short_code: "4XXA",
full_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, initial encounter",
short_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, initial encounter",
category_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, initial encounter"
}
end
def _V324XXD do
%ICDCode{full_code: "V324XXD",
category_code: "V32",
short_code: "4XXD",
full_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, subsequent encounter",
short_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, subsequent encounter",
category_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, subsequent encounter"
}
end
def _V324XXS do
%ICDCode{full_code: "V324XXS",
category_code: "V32",
short_code: "4XXS",
full_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, sequela",
short_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, sequela",
category_name: "Person boarding or alighting a three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle, sequela"
}
end
def _V325XXA do
%ICDCode{full_code: "V325XXA",
category_code: "V32",
short_code: "5XXA",
full_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
short_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
category_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter"
}
end
def _V325XXD do
%ICDCode{full_code: "V325XXD",
category_code: "V32",
short_code: "5XXD",
full_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
short_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
category_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter"
}
end
def _V325XXS do
%ICDCode{full_code: "V325XXS",
category_code: "V32",
short_code: "5XXS",
full_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
short_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
category_name: "Driver of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela"
}
end
def _V326XXA do
%ICDCode{full_code: "V326XXA",
category_code: "V32",
short_code: "6XXA",
full_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
short_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
category_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter"
}
end
def _V326XXD do
%ICDCode{full_code: "V326XXD",
category_code: "V32",
short_code: "6XXD",
full_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
short_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
category_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter"
}
end
def _V326XXS do
%ICDCode{full_code: "V326XXS",
category_code: "V32",
short_code: "6XXS",
full_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
short_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
category_name: "Passenger in three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela"
}
end
def _V327XXA do
%ICDCode{full_code: "V327XXA",
category_code: "V32",
short_code: "7XXA",
full_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
short_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
category_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter"
}
end
def _V327XXD do
%ICDCode{full_code: "V327XXD",
category_code: "V32",
short_code: "7XXD",
full_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
short_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
category_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter"
}
end
def _V327XXS do
%ICDCode{full_code: "V327XXS",
category_code: "V32",
short_code: "7XXS",
full_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
short_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
category_name: "Person on outside of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela"
}
end
def _V329XXA do
%ICDCode{full_code: "V329XXA",
category_code: "V32",
short_code: "9XXA",
full_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
short_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter",
category_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, initial encounter"
}
end
def _V329XXD do
%ICDCode{full_code: "V329XXD",
category_code: "V32",
short_code: "9XXD",
full_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
short_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter",
category_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, subsequent encounter"
}
end
def _V329XXS do
%ICDCode{full_code: "V329XXS",
category_code: "V32",
short_code: "9XXS",
full_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
short_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela",
category_name: "Unspecified occupant of three-wheeled motor vehicle injured in collision with two- or three-wheeled motor vehicle in traffic accident, sequela"
}
end
end
| 69.288 | 185 | 0.726475 |
73b3908ce59933875eaccb7fb5e4eae8ff42f3d4 | 528 | ex | Elixir | lib/envio/data/channel.ex | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | 12 | 2018-07-25T08:38:05.000Z | 2020-05-16T07:29:11.000Z | lib/envio/data/channel.ex | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | 6 | 2018-07-26T17:09:44.000Z | 2021-10-19T06:39:44.000Z | lib/envio/data/channel.ex | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | null | null | null | defmodule Envio.Channel do
@moduledoc """
Channel description.
"""
defstruct ~w|source name|a
@typedoc "Channel data stored as a struct"
@type t :: %__MODULE__{
source: binary() | atom(),
name: binary() | atom()
}
@spec fq_name({binary() | atom(), binary() | atom()} | t()) :: binary()
def fq_name({source, name}),
do: fq_name(%Envio.Channel{source: source, name: name})
def fq_name(%Envio.Channel{source: source, name: name}),
do: Envio.Utils.fq_name(source, name)
end
| 25.142857 | 73 | 0.609848 |
73b398c6f8e5398f289e4045811335ba10d84dc8 | 2,083 | ex | Elixir | clients/spanner/lib/google_api/spanner/v1/model/update_database_ddl_metadata.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/spanner/lib/google_api/spanner/v1/model/update_database_ddl_metadata.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/spanner/lib/google_api/spanner/v1/model/update_database_ddl_metadata.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Spanner.V1.Model.UpdateDatabaseDdlMetadata do
@moduledoc """
Metadata type for the operation returned by UpdateDatabaseDdl.
## Attributes
- commitTimestamps ([String.t]): Reports the commit timestamps of all statements that have succeeded so far, where `commit_timestamps[i]` is the commit timestamp for the statement `statements[i]`. Defaults to: `null`.
- database (String.t): The database being modified. Defaults to: `null`.
- statements ([String.t]): For an update this list contains all the statements. For an individual statement, this list contains only that statement. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:commitTimestamps => list(any()),
:database => any(),
:statements => list(any())
}
field(:commitTimestamps, type: :list)
field(:database)
field(:statements, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.UpdateDatabaseDdlMetadata do
def decode(value, options) do
GoogleApi.Spanner.V1.Model.UpdateDatabaseDdlMetadata.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.UpdateDatabaseDdlMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.574074 | 239 | 0.741239 |
73b3bb1eb2f768276ff2a75e2313976f6c5ec85c | 288 | exs | Elixir | priv/repo/migrations/20180601082739_create_users.exs | Galanda/ectoproj | 9dadeb27cc7b54034ab19363bc569d0fc4be671b | [
"MIT"
] | null | null | null | priv/repo/migrations/20180601082739_create_users.exs | Galanda/ectoproj | 9dadeb27cc7b54034ab19363bc569d0fc4be671b | [
"MIT"
] | null | null | null | priv/repo/migrations/20180601082739_create_users.exs | Galanda/ectoproj | 9dadeb27cc7b54034ab19363bc569d0fc4be671b | [
"MIT"
] | null | null | null | defmodule Ectoproj.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :fname, :string
add :lname, :string
add :phone, :string
add :password, :string
add :wishlist, :map
timestamps()
end
end
end
| 16.941176 | 49 | 0.628472 |
73b3c97f81f557dfa99a930c3f0002dd9ac5ac6b | 83 | ex | Elixir | lib/places_alloverse_com_web/views/page_view.ex | alloverse/places_alloverse_com | 5c15ea08a88429378ce8f41047418e166cbde7e9 | [
"BSD-2-Clause"
] | null | null | null | lib/places_alloverse_com_web/views/page_view.ex | alloverse/places_alloverse_com | 5c15ea08a88429378ce8f41047418e166cbde7e9 | [
"BSD-2-Clause"
] | 1 | 2021-03-10T11:40:47.000Z | 2021-03-10T11:40:47.000Z | lib/places_alloverse_com_web/views/page_view.ex | alloverse/places_alloverse_com | 5c15ea08a88429378ce8f41047418e166cbde7e9 | [
"BSD-2-Clause"
] | null | null | null | defmodule PlacesAlloverseComWeb.PageView do
use PlacesAlloverseComWeb, :view
end
| 20.75 | 43 | 0.855422 |
73b3fce41a88460106546cedea73142ad2214660 | 325 | ex | Elixir | lib/ibm_speech_to_text/message/stop.ex | software-mansion-labs/elixir-ibm-speech-to-text | 2d1dec2f429071bb30a0568af8fec24787b8cd57 | [
"Apache-2.0"
] | 5 | 2019-11-15T10:44:36.000Z | 2021-05-15T21:14:49.000Z | lib/ibm_speech_to_text/message/stop.ex | software-mansion-labs/elixir-ibm-speech-to-text | 2d1dec2f429071bb30a0568af8fec24787b8cd57 | [
"Apache-2.0"
] | null | null | null | lib/ibm_speech_to_text/message/stop.ex | software-mansion-labs/elixir-ibm-speech-to-text | 2d1dec2f429071bb30a0568af8fec24787b8cd57 | [
"Apache-2.0"
] | null | null | null | defmodule IBMSpeechToText.Message.Stop do
@moduledoc """
Message (struct) marking the end of data to be recognized.
"""
@type t() :: %__MODULE__{}
defstruct []
end
defimpl Jason.Encoder, for: IBMSpeechToText.Message.Stop do
def encode(_value, opts) do
%{action: "stop"} |> Jason.Encode.map(opts)
end
end
| 20.3125 | 60 | 0.689231 |
73b41783555496ab91fd0e34152a7f43a59955ca | 12,624 | ex | Elixir | lib/mapper/latin2.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | null | null | null | lib/mapper/latin2.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | 1 | 2020-07-16T09:38:33.000Z | 2020-07-16T09:38:33.000Z | lib/mapper/latin2.ex | nikneroz/exconv | 31a9f424462f88024af3afb32d2cb80160f07ebf | [
"MIT"
] | null | null | null | defmodule Exconv.Mapper.Latin2 do
def to_unicode(255), do: 711 # <<203, 135>> | "ˇ"
def to_unicode(254), do: 290 # <<196, 162>> | "Ģ"
def to_unicode(253), do: 380 # <<197, 188>> | "ż"
def to_unicode(252), do: 321 # <<197, 129>> | "Ł"
def to_unicode(251), do: 379 # <<197, 187>> | "Ż"
def to_unicode(250), do: 311 # <<196, 183>> | "ķ"
def to_unicode(249), do: 253 # <<195, 189>> | "ý"
def to_unicode(248), do: 221 # <<195, 157>> | "Ý"
def to_unicode(247), do: 371 # <<197, 179>> | "ų"
def to_unicode(246), do: 370 # <<197, 178>> | "Ų"
def to_unicode(245), do: 369 # <<197, 177>> | "ű"
def to_unicode(244), do: 368 # <<197, 176>> | "Ű"
def to_unicode(243), do: 367 # <<197, 175>> | "ů"
def to_unicode(242), do: 218 # <<195, 154>> | "Ú"
def to_unicode(241), do: 366 # <<197, 174>> | "Ů"
def to_unicode(240), do: 363 # <<197, 171>> | "ū"
def to_unicode(239), do: 212 # <<195, 148>> | "Ô"
def to_unicode(238), do: 211 # <<195, 147>> | "Ó"
def to_unicode(237), do: 362 # <<197, 170>> | "Ū"
def to_unicode(236), do: 382 # <<197, 190>> | "ž"
def to_unicode(235), do: 381 # <<197, 189>> | "Ž"
def to_unicode(234), do: 205 # <<195, 141>> | "Í"
def to_unicode(233), do: 357 # <<197, 165>> | "ť"
def to_unicode(232), do: 356 # <<197, 164>> | "Ť"
def to_unicode(231), do: 193 # <<195, 129>> | "Á"
def to_unicode(230), do: 347 # <<197, 155>> | "ś"
def to_unicode(229), do: 346 # <<197, 154>> | "Ś"
def to_unicode(228), do: 353 # <<197, 161>> | "š"
def to_unicode(227), do: 8222 # <<226, 128, 158>> | "„"
def to_unicode(226), do: 8218 # <<226, 128, 154>> | "‚"
def to_unicode(225), do: 352 # <<197, 160>> | "Š"
def to_unicode(224), do: 343 # <<197, 151>> | "ŗ"
def to_unicode(223), do: 342 # <<197, 150>> | "Ŗ"
def to_unicode(222), do: 345 # <<197, 153>> | "ř"
def to_unicode(221), do: 8250 # <<226, 128, 186>> | "›"
def to_unicode(220), do: 8249 # <<226, 128, 185>> | "‹"
def to_unicode(219), do: 344 # <<197, 152>> | "Ř"
def to_unicode(218), do: 341 # <<197, 149>> | "ŕ"
def to_unicode(217), do: 340 # <<197, 148>> | "Ŕ"
def to_unicode(216), do: 333 # <<197, 141>> | "ō"
def to_unicode(215), do: 9674 # <<226, 151, 138>> | "◊"
def to_unicode(214), do: 247 # <<195, 183>> | "÷"
def to_unicode(213), do: 8217 # <<226, 128, 153>> | "’"
def to_unicode(212), do: 8216 # <<226, 128, 152>> | "‘"
def to_unicode(211), do: 8221 # <<226, 128, 157>> | "”"
def to_unicode(210), do: 8220 # <<226, 128, 156>> | "“"
def to_unicode(209), do: 8212 # <<226, 128, 148>> | "—"
def to_unicode(208), do: 8211 # <<226, 128, 147>> | "–"
def to_unicode(207), do: 332 # <<197, 140>> | "Ō"
def to_unicode(206), do: 337 # <<197, 145>> | "ő"
def to_unicode(205), do: 213 # <<195, 149>> | "Õ"
def to_unicode(204), do: 336 # <<197, 144>> | "Ő"
def to_unicode(203), do: 328 # <<197, 136>> | "ň"
def to_unicode(202), do: 160 # <<194, 160>> | " "
def to_unicode(201), do: 8230 # <<226, 128, 166>> | "…"
def to_unicode(200), do: 187 # <<194, 187>> | "»"
def to_unicode(199), do: 171 # <<194, 171>> | "«"
def to_unicode(198), do: 8710 # <<226, 136, 134>> | "∆"
def to_unicode(197), do: 327 # <<197, 135>> | "Ň"
def to_unicode(196), do: 324 # <<197, 132>> | "ń"
def to_unicode(195), do: 8730 # <<226, 136, 154>> | "√"
def to_unicode(194), do: 172 # <<194, 172>> | "¬"
def to_unicode(193), do: 323 # <<197, 131>> | "Ń"
def to_unicode(192), do: 326 # <<197, 134>> | "ņ"
def to_unicode(191), do: 325 # <<197, 133>> | "Ņ"
def to_unicode(190), do: 314 # <<196, 186>> | "ĺ"
def to_unicode(189), do: 313 # <<196, 185>> | "Ĺ"
def to_unicode(188), do: 318 # <<196, 190>> | "ľ"
def to_unicode(187), do: 317 # <<196, 189>> | "Ľ"
def to_unicode(186), do: 316 # <<196, 188>> | "ļ"
def to_unicode(185), do: 315 # <<196, 187>> | "Ļ"
def to_unicode(184), do: 322 # <<197, 130>> | "ł"
def to_unicode(183), do: 8721 # <<226, 136, 145>> | "∑"
def to_unicode(182), do: 8706 # <<226, 136, 130>> | "∂"
def to_unicode(181), do: 310 # <<196, 182>> | "Ķ"
def to_unicode(180), do: 299 # <<196, 171>> | "ī"
def to_unicode(179), do: 8805 # <<226, 137, 165>> | "≥"
def to_unicode(178), do: 8804 # <<226, 137, 164>> | "≤"
def to_unicode(177), do: 298 # <<196, 170>> | "Ī"
def to_unicode(176), do: 303 # <<196, 175>> | "į"
def to_unicode(175), do: 302 # <<196, 174>> | "Į"
def to_unicode(174), do: 291 # <<196, 163>> | "ģ"
def to_unicode(173), do: 8800 # <<226, 137, 160>> | "≠"
def to_unicode(172), do: 168 # <<194, 168>> | "¨"
def to_unicode(171), do: 281 # <<196, 153>> | "ę"
def to_unicode(170), do: 8482 # <<226, 132, 162>> | "™"
def to_unicode(169), do: 169 # <<194, 169>> | "©"
def to_unicode(168), do: 174 # <<194, 174>> | "®"
def to_unicode(167), do: 223 # <<195, 159>> | "ß"
def to_unicode(166), do: 182 # <<194, 182>> | "¶"
def to_unicode(165), do: 8226 # <<226, 128, 162>> | "•"
def to_unicode(164), do: 167 # <<194, 167>> | "§"
def to_unicode(163), do: 163 # <<194, 163>> | "£"
def to_unicode(162), do: 280 # <<196, 152>> | "Ę"
def to_unicode(161), do: 176 # <<194, 176>> | "°"
def to_unicode(160), do: 8224 # <<226, 128, 160>> | "†"
def to_unicode(159), do: 252 # <<195, 188>> | "ü"
def to_unicode(158), do: 283 # <<196, 155>> | "ě"
def to_unicode(157), do: 282 # <<196, 154>> | "Ě"
def to_unicode(156), do: 250 # <<195, 186>> | "ú"
def to_unicode(155), do: 245 # <<195, 181>> | "õ"
def to_unicode(154), do: 246 # <<195, 182>> | "ö"
def to_unicode(153), do: 244 # <<195, 180>> | "ô"
def to_unicode(152), do: 279 # <<196, 151>> | "ė"
def to_unicode(151), do: 243 # <<195, 179>> | "ó"
def to_unicode(150), do: 278 # <<196, 150>> | "Ė"
def to_unicode(149), do: 275 # <<196, 147>> | "ē"
def to_unicode(148), do: 274 # <<196, 146>> | "Ē"
def to_unicode(147), do: 271 # <<196, 143>> | "ď"
def to_unicode(146), do: 237 # <<195, 173>> | "í"
def to_unicode(145), do: 270 # <<196, 142>> | "Ď"
def to_unicode(144), do: 378 # <<197, 186>> | "ź"
def to_unicode(143), do: 377 # <<197, 185>> | "Ź"
def to_unicode(142), do: 233 # <<195, 169>> | "é"
def to_unicode(141), do: 263 # <<196, 135>> | "ć"
def to_unicode(140), do: 262 # <<196, 134>> | "Ć"
def to_unicode(139), do: 269 # <<196, 141>> | "č"
def to_unicode(138), do: 228 # <<195, 164>> | "ä"
def to_unicode(137), do: 268 # <<196, 140>> | "Č"
def to_unicode(136), do: 261 # <<196, 133>> | "ą"
def to_unicode(135), do: 225 # <<195, 161>> | "á"
def to_unicode(134), do: 220 # <<195, 156>> | "Ü"
def to_unicode(133), do: 214 # <<195, 150>> | "Ö"
def to_unicode(132), do: 260 # <<196, 132>> | "Ą"
def to_unicode(131), do: 201 # <<195, 137>> | "É"
def to_unicode(130), do: 257 # <<196, 129>> | "ā"
def to_unicode(129), do: 256 # <<196, 128>> | "Ā"
def to_unicode(128), do: 196 # <<195, 132>> | "Ä"
def to_unicode(127), do: 127 # <<127>> | "\d"
def to_unicode(126), do: 126 # <<126>> | "~"
def to_unicode(125), do: 125 # <<125>> | "}"
def to_unicode(124), do: 124 # <<124>> | "|"
def to_unicode(123), do: 123 # <<123>> | "{"
def to_unicode(122), do: 122 # <<122>> | "z"
def to_unicode(121), do: 121 # <<121>> | "y"
def to_unicode(120), do: 120 # <<120>> | "x"
def to_unicode(119), do: 119 # <<119>> | "w"
def to_unicode(118), do: 118 # <<118>> | "v"
def to_unicode(117), do: 117 # <<117>> | "u"
def to_unicode(116), do: 116 # <<116>> | "t"
def to_unicode(115), do: 115 # <<115>> | "s"
def to_unicode(114), do: 114 # <<114>> | "r"
def to_unicode(113), do: 113 # <<113>> | "q"
def to_unicode(112), do: 112 # <<112>> | "p"
def to_unicode(111), do: 111 # <<111>> | "o"
def to_unicode(110), do: 110 # <<110>> | "n"
def to_unicode(109), do: 109 # <<109>> | "m"
def to_unicode(108), do: 108 # <<108>> | "l"
def to_unicode(107), do: 107 # <<107>> | "k"
def to_unicode(106), do: 106 # <<106>> | "j"
def to_unicode(105), do: 105 # <<105>> | "i"
def to_unicode(104), do: 104 # <<104>> | "h"
def to_unicode(103), do: 103 # <<103>> | "g"
def to_unicode(102), do: 102 # <<102>> | "f"
def to_unicode(101), do: 101 # <<101>> | "e"
def to_unicode(100), do: 100 # <<100>> | "d"
def to_unicode(99), do: 99 # <<99>> | "c"
def to_unicode(98), do: 98 # <<98>> | "b"
def to_unicode(97), do: 97 # <<97>> | "a"
def to_unicode(96), do: 96 # <<96>> | "`"
def to_unicode(95), do: 95 # <<95>> | "_"
def to_unicode(94), do: 94 # <<94>> | "^"
def to_unicode(93), do: 93 # <<93>> | "]"
def to_unicode(92), do: 92 # <<92>> | "\\"
def to_unicode(91), do: 91 # <<91>> | "["
def to_unicode(90), do: 90 # <<90>> | "Z"
def to_unicode(89), do: 89 # <<89>> | "Y"
def to_unicode(88), do: 88 # <<88>> | "X"
def to_unicode(87), do: 87 # <<87>> | "W"
def to_unicode(86), do: 86 # <<86>> | "V"
def to_unicode(85), do: 85 # <<85>> | "U"
def to_unicode(84), do: 84 # <<84>> | "T"
def to_unicode(83), do: 83 # <<83>> | "S"
def to_unicode(82), do: 82 # <<82>> | "R"
def to_unicode(81), do: 81 # <<81>> | "Q"
def to_unicode(80), do: 80 # <<80>> | "P"
def to_unicode(79), do: 79 # <<79>> | "O"
def to_unicode(78), do: 78 # <<78>> | "N"
def to_unicode(77), do: 77 # <<77>> | "M"
def to_unicode(76), do: 76 # <<76>> | "L"
def to_unicode(75), do: 75 # <<75>> | "K"
def to_unicode(74), do: 74 # <<74>> | "J"
def to_unicode(73), do: 73 # <<73>> | "I"
def to_unicode(72), do: 72 # <<72>> | "H"
def to_unicode(71), do: 71 # <<71>> | "G"
def to_unicode(70), do: 70 # <<70>> | "F"
def to_unicode(69), do: 69 # <<69>> | "E"
def to_unicode(68), do: 68 # <<68>> | "D"
def to_unicode(67), do: 67 # <<67>> | "C"
def to_unicode(66), do: 66 # <<66>> | "B"
def to_unicode(65), do: 65 # <<65>> | "A"
def to_unicode(64), do: 64 # <<64>> | "@"
def to_unicode(63), do: 63 # <<63>> | "?"
def to_unicode(62), do: 62 # <<62>> | ">"
def to_unicode(61), do: 61 # <<61>> | "="
def to_unicode(60), do: 60 # <<60>> | "<"
def to_unicode(59), do: 59 # <<59>> | ";"
def to_unicode(58), do: 58 # <<58>> | ":"
def to_unicode(57), do: 57 # <<57>> | "9"
def to_unicode(56), do: 56 # <<56>> | "8"
def to_unicode(55), do: 55 # <<55>> | "7"
def to_unicode(54), do: 54 # <<54>> | "6"
def to_unicode(53), do: 53 # <<53>> | "5"
def to_unicode(52), do: 52 # <<52>> | "4"
def to_unicode(51), do: 51 # <<51>> | "3"
def to_unicode(50), do: 50 # <<50>> | "2"
def to_unicode(49), do: 49 # <<49>> | "1"
def to_unicode(48), do: 48 # <<48>> | "0"
def to_unicode(47), do: 47 # <<47>> | "/"
def to_unicode(46), do: 46 # <<46>> | "."
def to_unicode(45), do: 45 # <<45>> | "-"
def to_unicode(44), do: 44 # <<44>> | ","
def to_unicode(43), do: 43 # <<43>> | "+"
def to_unicode(42), do: 42 # <<42>> | "*"
def to_unicode(41), do: 41 # <<41>> | ")"
def to_unicode(40), do: 40 # <<40>> | "("
def to_unicode(39), do: 39 # <<39>> | "'"
def to_unicode(38), do: 38 # <<38>> | "&"
def to_unicode(37), do: 37 # <<37>> | "%"
def to_unicode(36), do: 36 # <<36>> | "$"
def to_unicode(35), do: 35 # <<35>> | "#"
def to_unicode(34), do: 34 # <<34>> | "\""
def to_unicode(33), do: 33 # <<33>> | "!"
def to_unicode(32), do: 32 # <<32>> | " "
def to_unicode(31), do: nil # <<31>> | <<31>>
def to_unicode(30), do: nil # <<30>> | <<30>>
def to_unicode(29), do: nil # <<29>> | <<29>>
def to_unicode(28), do: nil # <<28>> | <<28>>
def to_unicode(27), do: 27 # <<27>> | "\e"
def to_unicode(26), do: nil # <<26>> | <<26>>
def to_unicode(25), do: nil # <<25>> | <<25>>
def to_unicode(24), do: nil # <<24>> | <<24>>
def to_unicode(23), do: nil # <<23>> | <<23>>
def to_unicode(22), do: nil # <<22>> | <<22>>
def to_unicode(21), do: nil # <<21>> | <<21>>
def to_unicode(20), do: nil # <<20>> | <<20>>
def to_unicode(19), do: nil # <<19>> | <<19>>
def to_unicode(18), do: nil # <<18>> | <<18>>
def to_unicode(17), do: nil # <<17>> | <<17>>
def to_unicode(16), do: nil # <<16>> | <<16>>
def to_unicode(15), do: nil # <<15>> | <<15>>
def to_unicode(14), do: nil # <<14>> | <<14>>
def to_unicode(13), do: 13 # <<13>> | "\r"
def to_unicode(12), do: 12 # <<12>> | "\f"
def to_unicode(11), do: 11 # <<11>> | "\v"
def to_unicode(10), do: 10 # <<92, 110>> | "\\n"
def to_unicode(9), do: 9 # <<9>> | "\t"
def to_unicode(8), do: 8 # <<8>> | "\b"
def to_unicode(7), do: 7 # <<7>> | "\a"
def to_unicode(6), do: nil # <<6>> | <<6>>
def to_unicode(5), do: nil # <<5>> | <<5>>
def to_unicode(4), do: nil # <<4>> | <<4>>
def to_unicode(3), do: nil # <<3>> | <<3>>
def to_unicode(2), do: nil # <<2>> | <<2>>
def to_unicode(1), do: nil # <<1>> | <<1>>
def to_unicode(0), do: nil # <<0>> | <<0>>
end | 48.930233 | 57 | 0.519566 |
73b42958455c4508ed732a5028d46865ea64b142 | 231 | exs | Elixir | config/test.exs | Shopify/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 23 | 2021-02-05T01:50:07.000Z | 2021-12-10T13:24:41.000Z | config/test.exs | Shopify/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 5 | 2021-03-30T06:27:39.000Z | 2021-06-08T01:10:35.000Z | config/test.exs | saulecabrera/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 1 | 2020-10-24T09:02:22.000Z | 2020-10-24T09:02:22.000Z | use Mix.Config
config :asls, builder: AssemblyScriptLS.Server.Build.Mock
config :asls, rpc: AssemblyScriptLS.JsonRpc.Mock
config :asls, runtime: AssemblyScriptLS.Runtime.Mock
config :asls, analysis: AssemblyScriptLS.Analysis.Mock
| 33 | 57 | 0.822511 |
73b4384eac865fc564b520a64ae6600df2817129 | 16,504 | ex | Elixir | lib/money/exchange_rates/exchange_rates_retriever.ex | hamptokr/money | dac0965fb308a476008284fe83877e948f20d088 | [
"Apache-2.0"
] | 426 | 2016-10-10T08:53:20.000Z | 2022-03-17T04:28:00.000Z | lib/money/exchange_rates/exchange_rates_retriever.ex | hamptokr/money | dac0965fb308a476008284fe83877e948f20d088 | [
"Apache-2.0"
] | 131 | 2016-12-03T22:43:52.000Z | 2022-02-13T22:35:57.000Z | lib/money/exchange_rates/exchange_rates_retriever.ex | hamptokr/money | dac0965fb308a476008284fe83877e948f20d088 | [
"Apache-2.0"
] | 47 | 2017-02-18T08:11:26.000Z | 2022-01-26T19:31:34.000Z | defmodule Money.ExchangeRates.Retriever do
@moduledoc """
Implements a `GenServer` to retrieve exchange rates from
a configured retrieveal module on a periodic or on demand basis.
By default exchange rates are retrieved from [Open Exchange Rates](http://openexchangerates.org).
The default period of execution is 5 minutes (300_000 milliseconds). The
period of retrieval is configured in `config.exs` or the appropriate
environment configuration. For example:
config :ex_money,
retrieve_every: 300_000
"""
use GenServer
require Logger
@etag_cache :etag_cache
@doc """
Starts the exchange rates retrieval service
"""
def start(config \\ Money.ExchangeRates.config()) do
Money.ExchangeRates.Supervisor.start_retriever(config)
end
@doc """
Stop the exchange rates retrieval service.
The service can be restarted with `restart/0`.
"""
def stop do
Money.ExchangeRates.Supervisor.stop_retriever()
end
@doc """
Restart the exchange rates retrieval service
"""
def restart do
Money.ExchangeRates.Supervisor.restart_retriever()
end
@doc """
Delete the exchange rates retrieval service
The service can be started again with `start/1`
"""
def delete do
Money.ExchangeRates.Supervisor.delete_retriever()
end
@doc false
def start_link(name, config \\ Money.ExchangeRates.config()) do
GenServer.start_link(__MODULE__, config, name: name)
end
@doc """
Forces retrieval of the latest exchange rates
Sends a message ot the exchange rate retrieval worker to request
current rates be retrieved and stored.
Returns:
* `{:ok, rates}` if exchange rates request is successfully sent.
* `{:error, reason}` if the request cannot be send.
This function does not return exchange rates, for that see
`Money.ExchangeRates.latest_rates/0` or
`Money.ExchangeRates.historic_rates/1`.
"""
def latest_rates() do
case Process.whereis(__MODULE__) do
nil -> {:error, exchange_rate_service_error()}
_pid -> GenServer.call(__MODULE__, :latest_rates)
end
end
@doc """
Forces retrieval of historic exchange rates for a single date
* `date` is a date returned by `Date.new/3` or any struct with the
elements `:year`, `:month` and `:day` or
* a `Date.Range.t` created by `Date.range/2` that specifies a
range of dates to retrieve
Returns:
* `{:ok, rates}` if exchange rates request is successfully sent.
* `{:error, reason}` if the request cannot be send.
Sends a message ot the exchange rate retrieval worker to request
historic rates for a specified date or range be retrieved and
stored.
This function does not return exchange rates, for that see
`Money.ExchangeRates.latest_rates/0` or
`Money.ExchangeRates.historic_rates/1`.
"""
def historic_rates(%Date{calendar: Calendar.ISO} = date) do
case Process.whereis(__MODULE__) do
nil -> {:error, exchange_rate_service_error()}
_pid -> GenServer.call(__MODULE__, {:historic_rates, date})
end
end
def historic_rates(%{year: year, month: month, day: day}) do
case Date.new(year, month, day) do
{:ok, date} -> historic_rates(date)
error -> error
end
end
def historic_rates(%Date.Range{first: from, last: to}) do
historic_rates(from, to)
end
@doc """
Forces retrieval of historic exchange rates for a range of dates
* `from` is a date returned by `Date.new/3` or any struct with the
elements `:year`, `:month` and `:day`.
* `to` is a date returned by `Date.new/3` or any struct with the
elements `:year`, `:month` and `:day`.
Returns:
* `{:ok, rates}` if exchange rates request is successfully sent.
* `{:error, reason}` if the request cannot be send.
Sends a message to the exchange rate retrieval process for each
date in the range `from`..`to` to request historic rates be
retrieved.
"""
def historic_rates(%Date{calendar: Calendar.ISO} = from, %Date{calendar: Calendar.ISO} = to) do
case Process.whereis(__MODULE__) do
nil ->
{:error, exchange_rate_service_error()}
_pid ->
for date <- Date.range(from, to) do
historic_rates(date)
end
end
end
def historic_rates(%{year: y1, month: m1, day: d1}, %{year: y2, month: m2, day: d2}) do
with {:ok, from} <- Date.new(y1, m1, d1),
{:ok, to} <- Date.new(y2, m2, d2) do
historic_rates(from, to)
end
end
@doc """
Updated the configuration for the Exchange Rate
Service
"""
def reconfigure(%Money.ExchangeRates.Config{} = config) do
GenServer.call(__MODULE__, {:reconfigure, config})
end
@doc """
Return the current configuration of the Exchange Rates
Retrieval service
"""
def config do
GenServer.call(__MODULE__, :config)
end
@doc """
Retrieve exchange rates from an external HTTP
service.
This function is primarily intended for use by
an exchange rates api module.
"""
def retrieve_rates(url, config) when is_binary(url) do
url
|> String.to_charlist()
|> retrieve_rates(config)
end
def retrieve_rates(url, config) when is_list(url) do
headers = if_none_match_header(url)
:httpc.request(:get, {url, headers}, https_opts(config, url), [])
|> process_response(url, config)
end
defp process_response({:ok, {{_version, 200, 'OK'}, headers, body}}, url, config) do
rates = config.api_module.decode_rates(body)
cache_etag(headers, url)
{:ok, rates}
end
defp process_response({:ok, {{_version, 304, 'Not Modified'}, headers, _body}}, url, _config) do
cache_etag(headers, url)
{:ok, :not_modified}
end
defp process_response({_, {{_version, code, message}, _headers, _body}}, _url, _config) do
{:error, {Money.ExchangeRateError, "#{code} #{message}"}}
end
defp process_response({:error, {:failed_connect, [{_, {_host, _port}}, {_, _, sys_message}]}}, url, _config) do
{:error, {Money.ExchangeRateError, "Failed to connect to #{url}: #{inspect sys_message}"}}
end
defp process_response({:error, {:tls_alert, {:certificate_expired, _message}}}, url, _config) do
{:error, {Money.ExchangeRateError, "Certificate for #{inspect(url)} has expired"}}
end
defp if_none_match_header(url) do
case get_etag(url) do
{etag, date} ->
[
{'If-None-Match', etag},
{'If-Modified-Since', date}
]
_ ->
[]
end
end
defp cache_etag(headers, url) do
etag = :proplists.get_value('etag', headers)
date = :proplists.get_value('date', headers)
if etag?(etag, date) do
:ets.insert(@etag_cache, {url, {etag, date}})
else
:ets.delete(@etag_cache, url)
end
end
defp get_etag(url) do
case :ets.lookup(@etag_cache, url) do
[{^url, cached_value}] -> cached_value
[] -> nil
end
end
defp etag?(etag, date) do
etag != :undefined && date != :undefined
end
#
# Server implementation
#
@doc false
def init(config) do
:erlang.process_flag(:trap_exit, true)
config.cache_module.init()
if is_integer(config.retrieve_every) do
log(config, :info, log_init_message(config.retrieve_every))
schedule_work(0)
schedule_work(config.retrieve_every)
end
if config.preload_historic_rates do
log(config, :info, "Preloading historic rates for #{inspect(config.preload_historic_rates)}")
schedule_work(config.preload_historic_rates, config.cache_module)
end
if :ets.info(@etag_cache) == :undefined do
:ets.new(@etag_cache, [:named_table, :public])
end
{:ok, config}
end
@doc false
def terminate(:normal, config) do
config.cache_module.terminate()
end
@doc false
def terminate(:shutdown, config) do
config.cache_module.terminate()
end
@doc false
def terminate(other, _config) do
Logger.error("[ExchangeRates.Retriever] Terminate called with unhandled #{inspect(other)}")
end
@doc false
def handle_call(:latest_rates, _from, config) do
{:reply, retrieve_latest_rates(config), config}
end
@doc false
def handle_call({:historic_rates, date}, _from, config) do
{:reply, retrieve_historic_rates(date, config), config}
end
@doc false
def handle_call({:reconfigure, new_configuration}, _from, config) do
config.cache_module.terminate()
{:ok, new_config} = init(new_configuration)
{:reply, new_config, new_config}
end
@doc false
def handle_call(:config, _from, config) do
{:reply, config, config}
end
@doc false
def handle_call(:stop, _from, config) do
{:stop, :normal, :ok, config}
end
@doc false
def handle_call({:stop, reason}, _from, config) do
{:stop, reason, :ok, config}
end
@doc false
def handle_info(:latest_rates, config) do
retrieve_latest_rates(config)
schedule_work(config.retrieve_every)
{:noreply, config}
end
@doc false
def handle_info({:historic_rates, %Date{calendar: Calendar.ISO} = date}, config) do
retrieve_historic_rates(date, config)
{:noreply, config}
end
@doc false
def handle_info(:stop, config) do
{:stop, :normal, config}
end
@doc false
def handle_info({:stop, reason}, config) do
{:stop, reason, config}
end
@doc false
def handle_info(message, config) do
Logger.error("Invalid message for ExchangeRates.Retriever: #{inspect(message)}")
{:noreply, config}
end
defp retrieve_latest_rates(%{callback_module: callback_module} = config) do
case config.api_module.get_latest_rates(config) do
{:ok, :not_modified} ->
log(config, :success, "Retrieved latest exchange rates successfully. Rates unchanged.")
{:ok, config.cache_module.latest_rates()}
{:ok, rates} ->
retrieved_at = DateTime.utc_now()
config.cache_module.store_latest_rates(rates, retrieved_at)
apply(callback_module, :latest_rates_retrieved, [rates, retrieved_at])
log(config, :success, "Retrieved latest exchange rates successfully")
{:ok, rates}
{:error, reason} ->
log(config, :failure, "Could not retrieve latest exchange rates: #{inspect(reason)}")
{:error, reason}
end
end
defp retrieve_historic_rates(date, %{callback_module: callback_module} = config) do
case config.api_module.get_historic_rates(date, config) do
{:ok, :not_modified} ->
log(config, :success, "Historic exchange rates for #{Date.to_string(date)} are unchanged")
{:ok, config.cache_module.historic_rates(date)}
{:ok, rates} ->
config.cache_module.store_historic_rates(rates, date)
apply(callback_module, :historic_rates_retrieved, [rates, date])
log(
config,
:success,
"Retrieved historic exchange rates for #{Date.to_string(date)} successfully"
)
{:ok, rates}
{:error, reason} ->
log(
config,
:failure,
"Could not retrieve historic exchange rates " <>
"for #{Date.to_string(date)}: #{inspect(reason)}"
)
{:error, reason}
end
end
defp schedule_work(delay_ms) when is_integer(delay_ms) do
Process.send_after(self(), :latest_rates, delay_ms)
end
defp schedule_work(%Date.Range{} = date_range, cache_module) do
for date <- date_range do
schedule_work(date, cache_module)
end
end
# Don't retrieve historic rates if they are
# already cached. Note that this is only
# called at retriever initialization, not
# through the public api.
#
# This depends on:
# 1. The cache is persistent, like Cache.Dets
# 2. The assumption that historic rates don't change
# A persistent cache will reduce the number of
# external API calls and it means the cache
# will survive restarts both intentional and
# unintentional
defp schedule_work(%Date{calendar: Calendar.ISO} = date, cache_module) do
case cache_module.historic_rates(date) do
{:ok, _rates} ->
:ok
{:error, _} ->
Process.send(self(), {:historic_rates, date}, [])
end
end
defp schedule_work({%Date{} = from, %Date{} = to}, cache_module) do
schedule_work(Date.range(from, to), cache_module)
end
defp schedule_work(date_string, cache_module) when is_binary(date_string) do
parts = String.split(date_string, "..")
case parts do
[date] -> schedule_work(Date.from_iso8601(date), cache_module)
[from, to] -> schedule_work({Date.from_iso8601(from), Date.from_iso8601(to)}, cache_module)
end
end
# Any non-numeric value, or non-date value means
# we don't schedule work - ie there is no periodic
# retrieval
defp schedule_work(_, _cache_module) do
:ok
end
@doc false
def log(%{log_levels: log_levels}, key, message) do
case Map.get(log_levels, key) do
nil ->
nil
log_level ->
Logger.log(log_level, message)
end
end
defp log_init_message(every) do
{every, plural_every} = seconds(every)
"Exchange Rates will be retrieved now and then every #{every} #{plural_every}."
end
defp seconds(milliseconds) do
seconds = div(milliseconds, 1000)
plural = if seconds == 1, do: "second", else: "seconds"
{seconds, plural}
end
defp exchange_rate_service_error do
{Money.ExchangeRateError, "Exchange rate service does not appear to be running"}
end
#### Certificate verification
@certificate_locations [
# Configured cacertfile
Application.get_env(Cldr.Config.app_name(), :cacertfile),
# Populated if hex package CAStore is configured
if(Code.ensure_loaded?(CAStore), do: CAStore.file_path()),
# Populated if hex package certfi is configured
if(Code.ensure_loaded?(:certifi),
do: :certifi.cacertfile() |> List.to_string()
),
# Debian/Ubuntu/Gentoo etc.
"/etc/ssl/certs/ca-certificates.crt",
# Fedora/RHEL 6
"/etc/pki/tls/certs/ca-bundle.crt",
# OpenSUSE
"/etc/ssl/ca-bundle.pem",
# OpenELEC
"/etc/pki/tls/cacert.pem",
# CentOS/RHEL 7
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
# Open SSL on MacOS
"/usr/local/etc/openssl/cert.pem",
# MacOS, OpenBSD & Alpine Linux
"/etc/ssl/cert.pem"
]
|> Enum.reject(&is_nil/1)
@doc """
Returns the certificate store to be used when
retrieving exchange rates.
"""
def certificate_store do
@certificate_locations
|> Enum.find(&File.exists?/1)
|> raise_if_no_cacertfile
|> :erlang.binary_to_list()
end
defp raise_if_no_cacertfile(nil) do
raise RuntimeError, """
No certificate trust store was found.
Tried looking for: #{inspect(@certificate_locations)}
A certificate trust store is required in
order to download locales for your configuration.
Since ex_cldr could not detect a system
installed certificate trust store one of the
following actions may be taken:
1. Install the hex package `castore`. It will
be automatically detected after recompilation.
2. Install the hex package `certifi`. It will
be automatically detected after recomilation.
3. Specify the location of a certificate trust store
by configuring it in `config.exs`:
config :ex_cldr,
cacertfile: "/path/to/cacertfile",
...
"""
end
defp raise_if_no_cacertfile(file) do
file
end
# See https://erlef.github.io/security-wg/secure_coding_and_deployment_hardening/ssl.html
@otp_version :otp_release |> :erlang.system_info() |> List.to_integer
if @otp_version > 21 do
defp https_opts(%Money.ExchangeRates.Config{verify_peer: true}, _url) do
[
ssl: [
verify: :verify_peer,
cacertfile: certificate_store(),
depth: 99,
log_level: :alert,
log_alert: true,
customize_hostname_check: [
match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
]
]
]
end
else
defp https_opts(%Money.ExchangeRates.Config{verify_peer: true}, url) do
host = url |> :uri_string.parse() |> Map.fetch!(:host)
[
ssl: [
verify: :verify_peer,
verify_fun: {&:ssl_verify_hostname.verify_fun/3, check_hostname: host},
cacertfile: certificate_store(),
server_name_indication: host,
reuse_sessions: false,
depth: 99
]
]
end
end
defp https_opts(%Money.ExchangeRates.Config{verify_peer: false}, _url) do
[]
end
end
| 26.923328 | 113 | 0.667475 |
73b49b408be7cd8039cfe49aac5875857b71dd55 | 7,945 | ex | Elixir | lib/ex_bitmex/rest/http_client.ex | trexnix/ex_bitmex | 7669b6bb6dadaf5de57b49c3a571e36d6fa712b9 | [
"MIT"
] | null | null | null | lib/ex_bitmex/rest/http_client.ex | trexnix/ex_bitmex | 7669b6bb6dadaf5de57b49c3a571e36d6fa712b9 | [
"MIT"
] | null | null | null | lib/ex_bitmex/rest/http_client.ex | trexnix/ex_bitmex | 7669b6bb6dadaf5de57b49c3a571e36d6fa712b9 | [
"MIT"
] | null | null | null | defmodule ExBitmex.Rest.HTTPClient do
@type verb :: :get | :post | :put | :delete
@type credentials :: ExBitmex.Credentials.t()
@type params :: map
@type rate_limit :: ExBitmex.RateLimit.t()
@type message :: String.t()
@type bad_request :: {:bad_request, error :: map}
@type forbidden :: {:forbidden, message}
@type unauthorized :: {:unauthorized, message}
@type service_unavailable :: {:service_unavailable, message}
@type nonce_not_increasing :: {:nonce_not_increasing, message}
@type auth_error_reason ::
:timeout
| :not_found
| bad_request
| :overloaded
| service_unavailable
| nonce_not_increasing
| :ip_forbidden
| forbidden
| :invalid_signature
| unauthorized
| :banned
@type auth_error_response :: {:error, auth_error_reason, rate_limit | nil}
@type auth_success_response :: {:ok, map | [map], rate_limit}
@type auth_response :: auth_success_response | auth_error_response
@type non_auth_error_reason ::
:timeout
| :not_found
| bad_request
| :overloaded
| service_unavailable
@type non_auth_response ::
{:ok, map | [map], rate_limit} | {:error, non_auth_error_reason, rate_limit | nil}
@rest_protocol Application.get_env(:ex_bitmex, :rest_protocol, "https://")
@domain Application.get_env(:ex_bitmex, :domain, "www.bitmex.com")
@api_path Application.get_env(:ex_bitmex, :api_path, "/api/v1")
@origin @rest_protocol <> @domain
@spec auth_get(path :: String.t(), credentials, params) :: auth_response
def auth_get(path, credentials, params) do
auth_request(:get, path, credentials, params)
end
@spec auth_post(path :: String.t(), credentials, params) :: auth_response
def auth_post(path, credentials, params) do
auth_request(:post, path, credentials, params)
end
@spec auth_put(path :: String.t(), credentials, params) :: auth_response
def auth_put(path, credentials, params) do
auth_request(:put, path, credentials, params)
end
@spec auth_delete(path :: String.t(), credentials, params) :: auth_response
def auth_delete(path, credentials, params) do
auth_request(:delete, path, credentials, params)
end
@spec auth_request(verb, path :: String.t(), credentials, params) :: auth_response
def auth_request(verb, path, credentials, params) do
body = Jason.encode!(params)
headers =
verb
|> auth_headers(path, body, credentials)
|> put_content_type(:json)
%HTTPoison.Request{
method: verb,
url: path |> url,
headers: headers,
body: body
}
|> send
end
@spec non_auth_get(path :: String.t(), params) :: non_auth_response
def non_auth_get(path, params \\ %{}) do
non_auth_request(:get, path, params)
end
@spec non_auth_request(verb, path :: String.t(), params) :: non_auth_response
def non_auth_request(verb, path, params) do
body = Jason.encode!(params)
headers = [] |> put_content_type(:json)
%HTTPoison.Request{
method: verb,
url: path |> url,
headers: headers,
body: body
}
|> send
end
@spec domain :: String.t()
def domain, do: @domain
@spec url(path :: String.t()) :: String.t()
def url(path), do: @origin <> @api_path <> path
defp send(request) do
request
|> HTTPoison.request()
|> parse_rate_limits
|> parse_response
end
defp auth_headers(verb, path, data, credentials) do
nonce = ExBitmex.Auth.nonce()
normalized_verb = verb |> normalize_verb
signature =
ExBitmex.Auth.sign(
credentials.api_secret,
normalized_verb,
@api_path <> path,
nonce,
data
)
[
"api-nonce": nonce |> to_string(),
"api-key": credentials.api_key,
"api-signature": signature
]
end
defp normalize_verb(:get), do: "GET"
defp normalize_verb(:post), do: "POST"
defp normalize_verb(:put), do: "PUT"
defp normalize_verb(:delete), do: "DELETE"
defp put_content_type(headers, :json) do
Keyword.put(headers, :"Content-Type", "application/json")
end
@limit_header "X-RateLimit-Limit"
@remaining_header "X-RateLimit-Remaining"
@reset_header "X-RateLimit-Reset"
defp parse_rate_limits({result, %HTTPoison.Response{headers: headers} = response}) do
limit_headers =
headers
|> Enum.reduce(
%{},
fn {k, v}, acc ->
case k do
@limit_header -> Map.put(acc, :limit, v)
@remaining_header -> Map.put(acc, :remaining, v)
@reset_header -> Map.put(acc, :reset, v)
_ -> acc
end
end
)
rate_limit = limit_headers |> build_rate_limit
{result, response, rate_limit}
end
defp parse_rate_limits({result, %HTTPoison.Error{} = error}) do
{result, error, nil}
end
defp build_rate_limit(%{limit: limit, remaining: remaining, reset: reset}) do
%ExBitmex.RateLimit{
limit: limit |> String.to_integer(),
remaining: remaining |> String.to_integer(),
reset: reset |> String.to_integer()
}
end
defp build_rate_limit(%{}), do: nil
defp parse_response({:ok, %HTTPoison.Response{status_code: 200, body: body}, rate_limit}) do
json = body |> Jason.decode!()
{:ok, json, rate_limit}
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 400, body: body}, rate_limit}) do
json = Jason.decode!(body)
message =
json
|> Map.fetch!("error")
|> Map.fetch!("message")
reason =
if message =~ "Nonce is not increasing" do
{:nonce_not_increasing, message}
else
{:bad_request, json}
end
{:error, reason, rate_limit}
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 401, body: body}, rate_limit}) do
message =
body
|> Jason.decode!()
|> Map.fetch!("error")
|> Map.fetch!("message")
reason =
if message == "Signature not valid." do
:invalid_signature
else
{:unauthorized, message}
end
{:error, reason, rate_limit}
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 403, body: body}, rate_limit}) do
reason =
case Jason.decode(body) do
{:ok, decoded_body} ->
decoded_body
|> Map.fetch!("error")
|> Map.fetch!("message")
|> get_403_error_reason()
{:error, _reason} ->
:banned
end
{:error, reason, rate_limit}
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 404}, rate_limit}) do
{:error, :not_found, rate_limit}
end
defp parse_response({
:ok,
%HTTPoison.Response{status_code: status_code, body: body},
rate_limit
})
when status_code in 500..526 do
message =
case body |> Jason.decode() do
{:ok, decoded_body} ->
decoded_body
|> Map.fetch!("error")
|> Map.fetch!("message")
{:error, _} ->
body
end
reason =
if message =~ "The system is currently overloaded" do
:overloaded
else
{:service_unavailable, message}
end
{:error, reason, rate_limit}
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 429}, rate_limit}) do
{:error, :exceeded_rate_limit, rate_limit}
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 403}, rate_limit}) do
{:error, :forbidden, rate_limit}
end
defp parse_response({:error, %HTTPoison.Error{reason: "timeout"}, rate_limit}) do
{:error, :timeout, rate_limit}
end
defp parse_response({:error, %HTTPoison.Error{reason: :timeout}, nil}) do
{:error, :timeout, nil}
end
defp get_403_error_reason(message) do
if message == "This IP address is not allowed to use this key." do
:ip_forbidden
else
{:forbidden, message}
end
end
end
| 27.586806 | 94 | 0.625677 |
73b49ffac6fb714da2032f121fdac6acee5f6a26 | 7,184 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/api/tabledata.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/big_query/lib/google_api/big_query/v2/api/tabledata.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/api/tabledata.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.BigQuery.V2.Api.Tabledata do
@moduledoc """
API calls for all endpoints tagged `Tabledata`.
"""
alias GoogleApi.BigQuery.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Streams data into BigQuery one record at a time without needing to run a load job. Requires the WRITER dataset role.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the destination table.
* `dataset_id` (*type:* `String.t`) - Dataset ID of the destination table.
* `table_id` (*type:* `String.t`) - Table ID of the destination table.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.BigQuery.V2.Model.TableDataInsertAllRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.TableDataInsertAllResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tabledata_insert_all(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQuery.V2.Model.TableDataInsertAllResponse.t()}
| {:error, Tesla.Env.t()}
def bigquery_tabledata_insert_all(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}/insertAll",
%{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQuery.V2.Model.TableDataInsertAllResponse{}]
)
end
@doc """
Retrieves table data from a specified set of rows. Requires the READER dataset role.
## Parameters
* `connection` (*type:* `GoogleApi.BigQuery.V2.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Project ID of the table to read
* `dataset_id` (*type:* `String.t`) - Dataset ID of the table to read
* `table_id` (*type:* `String.t`) - Table ID of the table to read
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:maxResults` (*type:* `integer()`) - Maximum number of results to return
* `:pageToken` (*type:* `String.t`) - Page token, returned by a previous call, identifying the result set
* `:selectedFields` (*type:* `String.t`) - List of fields to return (comma-separated). If unspecified, all fields are returned
* `:startIndex` (*type:* `String.t`) - Zero-based index of the starting row to read
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQuery.V2.Model.TableDataList{}}` on success
* `{:error, info}` on failure
"""
@spec bigquery_tabledata_list(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.BigQuery.V2.Model.TableDataList.t()} | {:error, Tesla.Env.t()}
def bigquery_tabledata_list(
connection,
project_id,
dataset_id,
table_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:maxResults => :query,
:pageToken => :query,
:selectedFields => :query,
:startIndex => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data",
%{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"datasetId" => URI.encode(dataset_id, &URI.char_unreserved?/1),
"tableId" => URI.encode(table_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQuery.V2.Model.TableDataList{}])
end
end
| 40.818182 | 187 | 0.625696 |
73b4c330c99fe275e1db79f0f509c85748aee9b0 | 6,316 | ex | Elixir | clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_media.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_media.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_media.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.YouTubeReporting.V1.Model.GdataMedia do
@moduledoc """
gdata
## Attributes
- algorithm (String.t): gdata Defaults to: `null`.
- bigstoreObjectRef (binary()): gdata Defaults to: `null`.
- blobRef (binary()): gdata Defaults to: `null`.
- blobstore2Info (GdataBlobstore2Info): gdata Defaults to: `null`.
- compositeMedia ([GdataCompositeMedia]): gdata Defaults to: `null`.
- contentType (String.t): gdata Defaults to: `null`.
- contentTypeInfo (GdataContentTypeInfo): gdata Defaults to: `null`.
- cosmoBinaryReference (binary()): gdata Defaults to: `null`.
- crc32cHash (integer()): gdata Defaults to: `null`.
- diffChecksumsResponse (GdataDiffChecksumsResponse): gdata Defaults to: `null`.
- diffDownloadResponse (GdataDiffDownloadResponse): gdata Defaults to: `null`.
- diffUploadRequest (GdataDiffUploadRequest): gdata Defaults to: `null`.
- diffUploadResponse (GdataDiffUploadResponse): gdata Defaults to: `null`.
- diffVersionResponse (GdataDiffVersionResponse): gdata Defaults to: `null`.
- downloadParameters (GdataDownloadParameters): gdata Defaults to: `null`.
- filename (String.t): gdata Defaults to: `null`.
- hash (String.t): gdata Defaults to: `null`.
- hashVerified (boolean()): gdata Defaults to: `null`.
- inline (binary()): gdata Defaults to: `null`.
- isPotentialRetry (boolean()): gdata Defaults to: `null`.
- length (String.t): gdata Defaults to: `null`.
- md5Hash (binary()): gdata Defaults to: `null`.
- mediaId (binary()): gdata Defaults to: `null`.
- objectId (GdataObjectId): gdata Defaults to: `null`.
- path (String.t): gdata Defaults to: `null`.
- referenceType (String.t): gdata Defaults to: `null`.
- Enum - one of [PATH, BLOB_REF, INLINE, GET_MEDIA, COMPOSITE_MEDIA, BIGSTORE_REF, DIFF_VERSION_RESPONSE, DIFF_CHECKSUMS_RESPONSE, DIFF_DOWNLOAD_RESPONSE, DIFF_UPLOAD_REQUEST, DIFF_UPLOAD_RESPONSE, COSMO_BINARY_REFERENCE, ARBITRARY_BYTES]
- sha1Hash (binary()): gdata Defaults to: `null`.
- sha256Hash (binary()): gdata Defaults to: `null`.
- timestamp (String.t): gdata Defaults to: `null`.
- token (String.t): gdata Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:algorithm => any(),
:bigstoreObjectRef => any(),
:blobRef => any(),
:blobstore2Info => GoogleApi.YouTubeReporting.V1.Model.GdataBlobstore2Info.t(),
:compositeMedia => list(GoogleApi.YouTubeReporting.V1.Model.GdataCompositeMedia.t()),
:contentType => any(),
:contentTypeInfo => GoogleApi.YouTubeReporting.V1.Model.GdataContentTypeInfo.t(),
:cosmoBinaryReference => any(),
:crc32cHash => any(),
:diffChecksumsResponse =>
GoogleApi.YouTubeReporting.V1.Model.GdataDiffChecksumsResponse.t(),
:diffDownloadResponse =>
GoogleApi.YouTubeReporting.V1.Model.GdataDiffDownloadResponse.t(),
:diffUploadRequest => GoogleApi.YouTubeReporting.V1.Model.GdataDiffUploadRequest.t(),
:diffUploadResponse => GoogleApi.YouTubeReporting.V1.Model.GdataDiffUploadResponse.t(),
:diffVersionResponse => GoogleApi.YouTubeReporting.V1.Model.GdataDiffVersionResponse.t(),
:downloadParameters => GoogleApi.YouTubeReporting.V1.Model.GdataDownloadParameters.t(),
:filename => any(),
:hash => any(),
:hashVerified => any(),
:inline => any(),
:isPotentialRetry => any(),
:length => any(),
:md5Hash => any(),
:mediaId => any(),
:objectId => GoogleApi.YouTubeReporting.V1.Model.GdataObjectId.t(),
:path => any(),
:referenceType => any(),
:sha1Hash => any(),
:sha256Hash => any(),
:timestamp => any(),
:token => any()
}
field(:algorithm)
field(:bigstoreObjectRef)
field(:blobRef)
field(:blobstore2Info, as: GoogleApi.YouTubeReporting.V1.Model.GdataBlobstore2Info)
field(:compositeMedia, as: GoogleApi.YouTubeReporting.V1.Model.GdataCompositeMedia, type: :list)
field(:contentType)
field(:contentTypeInfo, as: GoogleApi.YouTubeReporting.V1.Model.GdataContentTypeInfo)
field(:cosmoBinaryReference)
field(:crc32cHash)
field(
:diffChecksumsResponse,
as: GoogleApi.YouTubeReporting.V1.Model.GdataDiffChecksumsResponse
)
field(:diffDownloadResponse, as: GoogleApi.YouTubeReporting.V1.Model.GdataDiffDownloadResponse)
field(:diffUploadRequest, as: GoogleApi.YouTubeReporting.V1.Model.GdataDiffUploadRequest)
field(:diffUploadResponse, as: GoogleApi.YouTubeReporting.V1.Model.GdataDiffUploadResponse)
field(:diffVersionResponse, as: GoogleApi.YouTubeReporting.V1.Model.GdataDiffVersionResponse)
field(:downloadParameters, as: GoogleApi.YouTubeReporting.V1.Model.GdataDownloadParameters)
field(:filename)
field(:hash)
field(:hashVerified)
field(:inline)
field(:isPotentialRetry)
field(:length)
field(:md5Hash)
field(:mediaId)
field(:objectId, as: GoogleApi.YouTubeReporting.V1.Model.GdataObjectId)
field(:path)
field(:referenceType)
field(:sha1Hash)
field(:sha256Hash)
field(:timestamp)
field(:token)
end
defimpl Poison.Decoder, for: GoogleApi.YouTubeReporting.V1.Model.GdataMedia do
def decode(value, options) do
GoogleApi.YouTubeReporting.V1.Model.GdataMedia.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTubeReporting.V1.Model.GdataMedia do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.167832 | 242 | 0.710893 |
73b4d524a59458fab64a7d4c7d006a524e7b9099 | 1,283 | ex | Elixir | lib/issues.ex | rbin/issues | ae50f5425c4f4da9ea4bf7fbff00f6a21a57e77c | [
"MIT"
] | null | null | null | lib/issues.ex | rbin/issues | ae50f5425c4f4da9ea4bf7fbff00f6a21a57e77c | [
"MIT"
] | null | null | null | lib/issues.ex | rbin/issues | ae50f5425c4f4da9ea4bf7fbff00f6a21a57e77c | [
"MIT"
] | null | null | null | defmodule Issues do
@moduledoc """
Handle HTTP GET request to Github API for issues.
"""
require Logger
@user_agent [{"User-agent", "Elixir [email protected]"}] # Keep the GitHub API happy with a UAgent const.
@github_url Application.get_env(:issues, :github_url) # Get github url from config at compile time.
def issues_url(user, project) do
"#{@github_url}/repos/#{user}/#{project}/issues"
end
@doc """
Dispatch Get request to `issues_url`, and pipe response to our `handle_response` func.
"""
def fetch(user, project) do
Logger.info "Fetching user #{user}'s project: #{project}"
issues_url(user, project)
|> HTTPoison.get(@user_agent)
|> handle_response
end
@doc """
Handle the response from GET request depending on HTTP statuscode. Return `:status, body` tuple.
"""
def handle_response({:ok, %HTTPoison.Response{status_code: 200, body: body}}) do
Logger.info "Successful response"
Logger.debug fn -> inspect(body) end
{:ok, :jsx.decode(body)}
end
def handle_response({:ok, %HTTPoison.Response{status_code: status, body: body}}) do
Logger.error "Error #{status} returned"
{:error, :jsx.decode(body)}
end
def handle_response({:error, body}) do
{:error, :jsx.decode(body)}
end
end | 29.837209 | 103 | 0.674981 |
73b4fbea235285378420cb5dd9adc13cefdf9656 | 226 | exs | Elixir | first_steps/functions-2.exs | karlosmid/book_programming_elixir_12 | 53769b35728a82eddde3a21d4cbd45c1c21596a4 | [
"MIT"
] | null | null | null | first_steps/functions-2.exs | karlosmid/book_programming_elixir_12 | 53769b35728a82eddde3a21d4cbd45c1c21596a4 | [
"MIT"
] | null | null | null | first_steps/functions-2.exs | karlosmid/book_programming_elixir_12 | 53769b35728a82eddde3a21d4cbd45c1c21596a4 | [
"MIT"
] | null | null | null | fizz_buzz = fn
0,0,_ -> IO.puts "FizzBuzz"
0,_,_ -> IO.puts "Fizz"
_,0,_ -> IO.puts "Buzz"
a,b,c -> IO.puts c
end
IO.puts fizz_buzz.(0,0,1)
IO.puts fizz_buzz.(0,1,1)
IO.puts fizz_buzz.(1,0,1)
IO.puts fizz_buzz.(1,1,3)
| 20.545455 | 29 | 0.615044 |
73b517340d7d2470b5642c9703fc741eb684bc53 | 2,544 | ex | Elixir | lib/delivery/packages.ex | Simon-Initiative/proving-ground | ab6ba03051e55edbaa09535f11d9192776c8d901 | [
"MIT"
] | null | null | null | lib/delivery/packages.ex | Simon-Initiative/proving-ground | ab6ba03051e55edbaa09535f11d9192776c8d901 | [
"MIT"
] | 4 | 2021-03-01T20:51:23.000Z | 2021-09-20T21:37:12.000Z | lib/delivery/packages.ex | Simon-Initiative/proving-ground | ab6ba03051e55edbaa09535f11d9192776c8d901 | [
"MIT"
] | null | null | null | defmodule Delivery.Packages do
@moduledoc """
The Packages context.
"""
import Ecto.Query, warn: false
alias Delivery.Repo
alias Delivery.Packages.Package
@doc """
Returns the list of packages.
## Examples
iex> list_packages()
[%Package{}, ...]
"""
def list_packages do
Repo.all(Package)
end
@doc """
Gets a single package.
Raises `Ecto.NoResultsError` if the Package does not exist.
## Examples
iex> get_package!(123)
%Package{}
iex> get_package!(456)
** (Ecto.NoResultsError)
"""
def get_package!(id), do: Repo.get!(Package, id)
@doc """
Creates a package.
## Examples
iex> create_package(%{field: value})
{:ok, %Package{}}
iex> create_package(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_package(attrs \\ %{}) do
%Package{}
|> Package.changeset(attrs)
|> Repo.insert()
end
def get_glossary_terms(id) do
sql =
"""
SELECT id, title, jsonb_path_query(content, '$.** ? (@.type == "definition")') FROM activities WHERE package_id = $1;
"""
{:ok, %{rows: results }} = Ecto.Adapters.SQL.query(
Delivery.Repo, sql, [id])
results = Enum.map(results, fn r -> %{
id: Enum.at(r, 0),
title: Enum.at(r, 1),
term: Enum.at(r, 2) |> Map.get("nodes") |> hd |> Map.get("text"),
definition: Enum.at(r, 2) |> Map.get("data") |> Map.get("definition"),
}
end)
mapped_results = Enum.reduce(results, %{}, fn e, m -> Map.put(m, Map.get(e, :term), e) end)
Map.keys(mapped_results) |> Enum.map(fn e -> Map.get(mapped_results, e) end)
end
@doc """
Updates a package.
## Examples
iex> update_package(package, %{field: new_value})
{:ok, %Package{}}
iex> update_package(package, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_package(%Package{} = package, attrs) do
package
|> Package.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Package.
## Examples
iex> delete_package(package)
{:ok, %Package{}}
iex> delete_package(package)
{:error, %Ecto.Changeset{}}
"""
def delete_package(%Package{} = package) do
Repo.delete(package)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking package changes.
## Examples
iex> change_package(package)
%Ecto.Changeset{source: %Package{}}
"""
def change_package(%Package{} = package) do
Package.changeset(package, %{})
end
end
| 19.72093 | 123 | 0.58805 |
73b51a19ba735fefc89b56d9f95f71895c736c50 | 1,434 | exs | Elixir | plugins/ucc_chat/test/ucc_chat/settings/message_test.exs | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | plugins/ucc_chat/test/ucc_chat/settings/message_test.exs | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | plugins/ucc_chat/test/ucc_chat/settings/message_test.exs | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | defmodule UccChatTest.Settings.Message do
use UccChat.DataCase
alias UccChat.Settings.Message
alias UccChat.Settings.Schema.Message, as: Schema
setup do
Message.init()
{:ok, message: Message.get()}
end
test "schema" do
assert Message.schema == UccChat.Settings.Schema.Message
end
test "changeset" do
changeset = Message.changeset Message.schema.__struct__, %{time_format: "aa"}
assert changeset.data == %Schema{}
assert changeset.valid?
assert changeset.changes == %{time_format: "aa"}
end
test "has values", %{message: message} do
assert message.hide_user_join == false
assert message.show_edited_status == true
assert message.time_format == "LT"
assert message.grouping_period_seconds == 300
end
test "get", %{message: message} do
assert Message.get(:time_format) == "LT"
assert Message.get(message, :time_format) == "LT"
end
test "getters", %{message: message} do
assert Message.time_format == "LT"
assert Message.time_format(struct(message, time_format: "bb")) == "bb"
end
test "update", %{message: message} do
{:ok, msgs} = Message.update :grouping_period_seconds, 100
assert Message.get(:grouping_period_seconds) == 100
assert msgs.grouping_period_seconds == 100
{:ok, msgs} = Message.update struct(message, hide_user_join: true)
assert Message.get(:hide_user_join)
assert msgs.hide_user_join
end
end
| 28.68 | 81 | 0.701534 |
73b524b77cdb49143f02233098b917dfeae8b066 | 5,333 | ex | Elixir | apps/re/lib/exporters/imovelweb.ex | caspg/backend | 34df9dc14ab8ed75de4578fefa2e087580c7e867 | [
"MIT"
] | 1 | 2021-01-19T05:01:15.000Z | 2021-01-19T05:01:15.000Z | apps/re/lib/exporters/imovelweb.ex | caspg/backend | 34df9dc14ab8ed75de4578fefa2e087580c7e867 | [
"MIT"
] | null | null | null | apps/re/lib/exporters/imovelweb.ex | caspg/backend | 34df9dc14ab8ed75de4578fefa2e087580c7e867 | [
"MIT"
] | null | null | null | defmodule Re.Exporters.Imovelweb do
@moduledoc """
Listing XML exporters for imovelweb
"""
alias Re.Listing
@exported_attributes ~w(internal_id id type subtype title description highlight state city neighborhood
street street_number zipcode show_address lat lng show_map area_unity area price maintenance_fee property_tax
rooms bathrooms garage_spots images)a
@default_options %{attributes: @exported_attributes, highlight_ids: [], super_highlight_ids: []}
@imovelweb_id Application.get_env(:re, :imovelweb_identity)
@image_url "https://res.cloudinary.com/emcasa/image/upload/f_auto/v1513818385/"
@tour_url "https://my.matterport.com"
def export_listings_xml(listings, options \\ %{}) do
options = merge_default_options(options)
listings
|> Enum.map(&build_node(&1, options))
|> build_root()
|> XmlBuilder.document()
|> XmlBuilder.generate(format: :none)
end
def merge_default_options(options), do: Map.merge(@default_options, options)
def build_node(listing, options) do
{"Imovel", %{}, convert_attributes(listing, options)}
end
defp build_root(nodes) do
{"Carga",
%{
:"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
:"xmlns:xsd" => "http://www.w3.org/2001/XMLSchema"
}, [{"Imoveis", %{}, nodes}]}
end
def convert_attributes(listing, %{attributes: attributes} = options) do
Enum.map(attributes, &convert_attribute(&1, listing, options))
end
defp convert_attribute(:internal_id, _, _), do: {"CodigoCentralVendas", %{}, @imovelweb_id}
defp convert_attribute(:id, listing, _), do: {"CodigoImovel", %{}, listing.id}
defp convert_attribute(:type, listing, _),
do: {"TipoImovel", %{}, Map.get(listing_type_map(), listing.type, "Outro")}
defp convert_attribute(:subtype, listing, _),
do: {"SubTipoImovel", %{}, Map.get(listing_subtype_map(), listing.type, "Outro")}
defp convert_attribute(:title, listing, _),
do: {"TituloImovel", %{}, "#{listing.type} a venda em #{listing.address.city}"}
defp convert_attribute(:description, listing, _),
do: {"Observacao", %{}, {:cdata, listing.description || ""}}
defp convert_attribute(:highlight, listing, options) do
{
"Modelo",
%{},
cond do
listing.id in Map.get(options, :super_highlight_ids, []) -> "HOME"
listing.id in Map.get(options, :highlight_ids, []) -> "DESTAQUE"
true -> "SIMPLES"
end
}
end
defp convert_attribute(:state, listing, _), do: {"UF", %{}, listing.address.state}
defp convert_attribute(:city, listing, _), do: {"Cidade", %{}, {:cdata, listing.address.city}}
defp convert_attribute(:neighborhood, listing, _),
do: {"Bairro", %{}, {:cdata, listing.address.neighborhood}}
defp convert_attribute(:street, listing, _),
do: {"Endereco", %{}, {:cdata, listing.address.street}}
defp convert_attribute(:street_number, listing, _),
do: {"Numero", %{}, listing.address.street_number}
defp convert_attribute(:zipcode, listing, _), do: {"CEP", %{}, listing.address.postal_code}
defp convert_attribute(:show_address, _, _), do: {"DivulgarEndereco", %{}, "APROX"}
defp convert_attribute(:lat, listing, _), do: {"Latitude", %{}, listing.address.lat}
defp convert_attribute(:lng, listing, _), do: {"Longitude", %{}, listing.address.lng}
defp convert_attribute(:show_map, _, _), do: {"VisualizarMapa", %{}, 1}
defp convert_attribute(:area_unity, _, _), do: {"UnidadeMetrica", %{}, "M2"}
defp convert_attribute(:area, listing, _), do: {"AreaUtil", %{}, listing.area}
defp convert_attribute(:price, listing, _), do: {"PrecoVenda", %{}, listing.price}
defp convert_attribute(:maintenance_fee, listing, _),
do: {"PrecoCondominio", %{}, listing.maintenance_fee}
defp convert_attribute(:property_tax, listing, _),
do: {"PrecoIptuImovel", %{}, listing.property_tax}
defp convert_attribute(:rooms, listing, _), do: {"QtdDormitorios", %{}, listing.rooms || 0}
defp convert_attribute(:bathrooms, listing, _),
do: {"QtdBanheiros", %{}, listing.bathrooms || 0}
defp convert_attribute(:garage_spots, listing, _),
do: {"QtdVagas", %{}, listing.garage_spots || 0}
defp convert_attribute(:images, listing, _),
do: {"Fotos", %{}, listing.images |> Enum.map(&build_image_node/1)}
defp convert_attribute(:tour, listing, _),
do: {"ToursVirtual360", %{}, build_tour_node(listing.matterport_code)}
def listing_type_map(),
do: Listing.listing_types() |> Enum.zip(~w(Apartamento Casa Apartamento)) |> Enum.into(%{})
def listing_subtype_map(),
do: Listing.listing_types() |> Enum.zip(~w(Padrão Padrão Cobertura)) |> Enum.into(%{})
defp build_image_node(image) do
{"Foto", %{},
[
{"NomeArquivo", %{}, {:cdata, image.filename}},
{"URLArquivo", %{}, {:cdata, build_url(@image_url, [image.filename])}},
{"Principal", %{}, 0},
{"Ordem", %{}, image.position}
]}
end
defp build_tour_node(nil), do: nil
defp build_tour_node(matterport_code) do
[
{"TourVirtual360", %{},
[
{"URLArquivo", %{}, {:cdata, build_url(@tour_url, ["show/", "?m=#{matterport_code}"])}}
]}
]
end
def build_url(host, params) do
params
|> Enum.reduce(host, fn item, acc -> URI.merge(acc, item) end)
|> URI.to_string()
end
end
| 36.278912 | 113 | 0.660604 |
73b52d009b4f72771900d0c679f34408bcfa1af9 | 1,644 | exs | Elixir | test/web/models/asset_test.exs | walterbm/hyperledger-beta | 493cd02597775be917427d2d75ff293f53d3bc9d | [
"Apache-2.0"
] | 1 | 2017-06-14T07:04:47.000Z | 2017-06-14T07:04:47.000Z | test/web/models/asset_test.exs | walterbm/hyperledger-beta | 493cd02597775be917427d2d75ff293f53d3bc9d | [
"Apache-2.0"
] | null | null | null | test/web/models/asset_test.exs | walterbm/hyperledger-beta | 493cd02597775be917427d2d75ff293f53d3bc9d | [
"Apache-2.0"
] | null | null | null | defmodule Hyperledger.AssetModelTest do
use Hyperledger.ModelCase
alias Hyperledger.Asset
alias Hyperledger.Account
setup do
hash = :crypto.hash(:sha256, "123")
{pk, _sk} = :crypto.generate_key(:ecdh, :secp256k1)
{pa_pk, _sk} = :crypto.generate_key(:ecdh, :secp256k1)
params =
%{
hash: Base.encode16(hash),
public_key: Base.encode16(pk),
primary_account_public_key: Base.encode16(pa_pk)
}
{:ok, params: params}
end
test "`changeset` checks encoding of fields", %{params: params} do
bad_enc_cs =
Asset.changeset(
%Asset{},
%{
hash: "GJ9D68b3RCw2HgjzEhtH+TjMcaiYTNntB4W8xa8FhA==",
public_key: "00",
primary_account_public_key: "foo bar"}
)
assert Enum.count(bad_enc_cs.errors) == 2
cs = Asset.changeset(%Asset{}, params)
assert cs.valid? == true
end
test "`create` inserts a changeset into the db", %{params: params} do
Asset.changeset(%Asset{}, params)
|> Asset.create
assert Repo.get(Asset, params.hash) != nil
end
test "`create` also creates an associated primary account", %{params: params} do
{:ok, asset} = Asset.changeset(%Asset{}, params)
|> Asset.create
primary_acc =
Account
|> Repo.get(params.primary_account_public_key)
|> Repo.preload(:asset)
assert primary_acc != nil
assert primary_acc.asset == asset
end
test "`create` returns the asset", %{params: params} do
cs = Asset.changeset(%Asset{}, params)
assert {:ok, %Asset{}} = Asset.create(cs)
end
end | 26.516129 | 82 | 0.613747 |
73b5415094855057592a231f972bb74a131cef66 | 246 | ex | Elixir | lib/membrane/element/callback_context/playback_change.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | 515 | 2018-06-18T11:09:44.000Z | 2020-07-31T07:54:35.000Z | lib/membrane/element/callback_context/playback_change.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | 120 | 2018-06-07T08:34:06.000Z | 2020-07-30T07:09:50.000Z | lib/membrane/element/callback_context/playback_change.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | 13 | 2018-07-27T11:58:15.000Z | 2020-05-06T15:19:55.000Z | defmodule Membrane.Element.CallbackContext.PlaybackChange do
@moduledoc """
Structure representing a context that is passed to the callback of the element
when it changes playback state
"""
use Membrane.Core.Element.CallbackContext
end
| 30.75 | 80 | 0.796748 |
73b573e6c3d239eacbd3854b1feccd252996bc10 | 228 | ex | Elixir | learn/LittleBook/pooly/lib/pooly/pools_supervisor.ex | idfumg/ElixirSynopsis | 74c668d84300812dd41eb18772aecfb89bc7628b | [
"MIT"
] | null | null | null | learn/LittleBook/pooly/lib/pooly/pools_supervisor.ex | idfumg/ElixirSynopsis | 74c668d84300812dd41eb18772aecfb89bc7628b | [
"MIT"
] | null | null | null | learn/LittleBook/pooly/lib/pooly/pools_supervisor.ex | idfumg/ElixirSynopsis | 74c668d84300812dd41eb18772aecfb89bc7628b | [
"MIT"
] | null | null | null | defmodule Pooly.PoolsSupervisor do
use Supervisor
def start_link do
Supervisor.start_link(__MODULE__, [], name: __MODULE__)
end
def init([]) do
opts = [strategy: :one_for_one]
supervise([], opts)
end
end
| 17.538462 | 59 | 0.688596 |
73b58421b8a09e154505f44ed681007b2656a94d | 79,147 | ex | Elixir | clients/access_context_manager/lib/google_api/access_context_manager/v1/api/access_policies.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/access_context_manager/lib/google_api/access_context_manager/v1/api/access_policies.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/access_context_manager/lib/google_api/access_context_manager/v1/api/access_policies.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"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.AccessContextManager.V1.Api.AccessPolicies do
@moduledoc """
API calls for all endpoints tagged `AccessPolicies`.
"""
alias GoogleApi.AccessContextManager.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Creates an access policy. This method fails if the organization already has an access policy. The long-running operation has a successful status after the access policy propagates to long-lasting storage. Syntactic and basic semantic errors are returned in `metadata` as a BadRequest proto.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.AccessPolicy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_create(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_create(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/accessPolicies", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Deletes an access policy based on the resource name. The long-running operation has a successful status after the access policy is removed from long-lasting storage.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the access policy to delete. Format `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Returns an access policy based on the name.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the access policy to get. Format `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.AccessPolicy{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.AccessPolicy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.AccessPolicy{}])
end
@doc """
Gets the IAM policy for the specified Access Context Manager access policy.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_get_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_get_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:getIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Policy{}])
end
@doc """
Lists all access policies in an organization.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Number of AccessPolicy instances to include in the list. Default 100.
* `:pageToken` (*type:* `String.t`) - Next page token for the next batch of AccessPolicy instances. Defaults to the first page of results.
* `:parent` (*type:* `String.t`) - Required. Resource name for the container to list AccessPolicy instances from. Format: `organizations/{org_id}`
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.ListAccessPoliciesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.ListAccessPoliciesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query,
:parent => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/accessPolicies", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.ListAccessPoliciesResponse{}]
)
end
@doc """
Updates an access policy. The long-running operation from this RPC has a successful status after the changes to the access policy propagate to long-lasting storage.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Output only. Resource name of the `AccessPolicy`. Format: `accessPolicies/{access_policy}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. Mask to control which fields get updated. Must be non-empty.
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.AccessPolicy.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Sets the IAM policy for the specified Access Context Manager access policy. This method replaces the existing IAM policy on the access policy. The IAM policy controls the set of users who can perform specific operations on the Access Context Manager access policy.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_set_iam_policy(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Policy.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_set_iam_policy(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:setIamPolicy", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Policy{}])
end
@doc """
Returns the IAM permissions that the caller has on the specified Access Context Manager resource. The resource can be an AccessPolicy, AccessLevel, or ServicePerimeter. This method does not support other resources.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Creates an access level. The long-running operation from this RPC has a successful status after the access level propagates to long-lasting storage. If access levels contain errors, an error response is returned for the first error encountered.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the access policy which owns this Access Level. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.AccessLevel.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/accessLevels", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Deletes an access level based on the resource name. The long-running operation from this RPC has a successful status after the access level has been removed from long-lasting storage.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the Access Level. Format: `accessPolicies/{policy_id}/accessLevels/{access_level_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Gets an access level based on the resource name.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the Access Level. Format: `accessPolicies/{policy_id}/accessLevels/{access_level_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:accessLevelFormat` (*type:* `String.t`) - Whether to return `BasicLevels` in the Cloud Common Expression Language rather than as `BasicLevels`. Defaults to AS_DEFINED, where Access Levels are returned as `BasicLevels` or `CustomLevels` based on how they were created. If set to CEL, all Access Levels are returned as `CustomLevels`. In the CEL case, `BasicLevels` are translated to equivalent `CustomLevels`.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.AccessLevel{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.AccessLevel.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:accessLevelFormat => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.AccessLevel{}])
end
@doc """
Lists all access levels for an access policy.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the access policy to list Access Levels from. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:accessLevelFormat` (*type:* `String.t`) - Whether to return `BasicLevels` in the Cloud Common Expression language, as `CustomLevels`, rather than as `BasicLevels`. Defaults to returning `AccessLevels` in the format they were defined.
* `:pageSize` (*type:* `integer()`) - Number of Access Levels to include in the list. Default 100.
* `:pageToken` (*type:* `String.t`) - Next page token for the next batch of Access Level instances. Defaults to the first page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.ListAccessLevelsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.ListAccessLevelsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:accessLevelFormat => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/accessLevels", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.ListAccessLevelsResponse{}]
)
end
@doc """
Updates an access level. The long-running operation from this RPC has a successful status after the changes to the access level propagate to long-lasting storage. If access levels contain errors, an error response is returned for the first error encountered.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the Access Level. The `short_name` component must begin with a letter and only include alphanumeric and '_'. Format: `accessPolicies/{access_policy}/accessLevels/{access_level}`. The maximum length of the `access_level` component is 50 characters.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. Mask to control which fields get updated. Must be non-empty.
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.AccessLevel.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Replaces all existing access levels in an access policy with the access levels provided. This is done atomically. The long-running operation from this RPC has a successful status after all replacements propagate to long-lasting storage. If the replacement contains errors, an error response is returned for the first error encountered. Upon error, the replacement is cancelled, and existing access levels are not affected. The Operation.response field contains ReplaceAccessLevelsResponse. Removing access levels contained in existing service perimeters result in an error.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the access policy which owns these Access Levels. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.ReplaceAccessLevelsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_replace_all(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_replace_all(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/accessLevels:replaceAll", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Returns the IAM permissions that the caller has on the specified Access Context Manager resource. The resource can be an AccessPolicy, AccessLevel, or ServicePerimeter. This method does not support other resources.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_access_levels_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_access_levels_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Commits the dry-run specification for all the service perimeters in an access policy. A commit operation on a service perimeter involves copying its `spec` field to the `status` field of the service perimeter. Only service perimeters with `use_explicit_dry_run_spec` field set to true are affected by a commit operation. The long-running operation from this RPC has a successful status after the dry-run specifications for all the service perimeters have been committed. If a commit fails, it causes the long-running operation to return an error response and the entire commit operation is cancelled. When successful, the Operation.response field contains CommitServicePerimetersResponse. The `dry_run` and the `spec` fields are cleared after a successful commit operation.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the parent Access Policy which owns all Service Perimeters in scope for the commit operation. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.CommitServicePerimetersRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_commit(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_commit(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/servicePerimeters:commit", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Creates a service perimeter. The long-running operation from this RPC has a successful status after the service perimeter propagates to long-lasting storage. If a service perimeter contains errors, an error response is returned for the first error encountered.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the access policy which owns this Service Perimeter. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.ServicePerimeter.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_create(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/servicePerimeters", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Deletes a service perimeter based on the resource name. The long-running operation from this RPC has a successful status after the service perimeter is removed from long-lasting storage.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the Service Perimeter. Format: `accessPolicies/{policy_id}/servicePerimeters/{service_perimeter_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_delete(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Gets a service perimeter based on the resource name.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the Service Perimeter. Format: `accessPolicies/{policy_id}/servicePerimeters/{service_perimeters_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.ServicePerimeter{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.ServicePerimeter.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_get(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.ServicePerimeter{}]
)
end
@doc """
Lists all service perimeters for an access policy.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the access policy to list Service Perimeters from. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Number of Service Perimeters to include in the list. Default 100.
* `:pageToken` (*type:* `String.t`) - Next page token for the next batch of Service Perimeter instances. Defaults to the first page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.ListServicePerimetersResponse{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.ListServicePerimetersResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_list(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/servicePerimeters", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.ListServicePerimetersResponse{}]
)
end
@doc """
Updates a service perimeter. The long-running operation from this RPC has a successful status after the service perimeter propagates to long-lasting storage. If a service perimeter contains errors, an error response is returned for the first error encountered.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name for the ServicePerimeter. The `short_name` component must begin with a letter and only include alphanumeric and '_'. Format: `accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. Mask to control which fields get updated. Must be non-empty.
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.ServicePerimeter.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_patch(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Replace all existing service perimeters in an access policy with the service perimeters provided. This is done atomically. The long-running operation from this RPC has a successful status after all replacements propagate to long-lasting storage. Replacements containing errors result in an error response for the first error encountered. Upon an error, replacement are cancelled and existing service perimeters are not affected. The Operation.response field contains ReplaceServicePerimetersResponse.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Resource name for the access policy which owns these Service Perimeters. Format: `accessPolicies/{policy_id}`
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.ReplaceServicePerimetersRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_replace_all(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_replace_all(
connection,
parent,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/servicePerimeters:replaceAll", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.Operation{}])
end
@doc """
Returns the IAM permissions that the caller has on the specified Access Context Manager resource. The resource can be an AccessPolicy, AccessLevel, or ServicePerimeter. This method does not support other resources.
## Parameters
* `connection` (*type:* `GoogleApi.AccessContextManager.V1.Connection.t`) - Connection to server
* `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec accesscontextmanager_access_policies_service_perimeters_test_iam_permissions(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:ok, list()}
| {:error, any()}
def accesscontextmanager_access_policies_service_perimeters_test_iam_permissions(
connection,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+resource}:testIamPermissions", %{
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.AccessContextManager.V1.Model.TestIamPermissionsResponse{}]
)
end
end
| 47.167461 | 775 | 0.627238 |
73b588f56dcfba192841769464948a0f08368e40 | 3,166 | ex | Elixir | lib/ex_hash_ring/info.ex | LaudateCorpus1/ex_hash_ring | 79ed3e67b28a65378e099ab5580079d34ae79d8f | [
"MIT"
] | 191 | 2017-09-20T04:54:10.000Z | 2020-03-20T21:21:02.000Z | lib/ex_hash_ring/info.ex | LaudateCorpus1/ex_hash_ring | 79ed3e67b28a65378e099ab5580079d34ae79d8f | [
"MIT"
] | 5 | 2017-12-01T00:56:08.000Z | 2020-01-04T19:49:06.000Z | lib/ex_hash_ring/info.ex | LaudateCorpus1/ex_hash_ring | 79ed3e67b28a65378e099ab5580079d34ae79d8f | [
"MIT"
] | 14 | 2017-09-28T21:21:16.000Z | 2020-03-19T00:32:14.000Z | defmodule ExHashRing.Info do
@moduledoc """
Provides an interface for querying information about Rings.
Each Ring has some associated information that is available at all times to aid in performing
client-context queries into the underlying ETS table.non_neg_integer()
"""
use GenServer
alias ExHashRing.Ring
@typedoc """
For any ring information can be looked up that will provide an entry containing specifics about
the table holding the ring data, the configured history depth, sizes for each generation in the
history, the current generation, and any overrides that should be applied during lookup.
"""
@type entry :: {
table :: :ets.tid(),
depth :: Ring.depth(),
sizes :: [Ring.size()],
generation :: Ring.generation(),
overrides :: Ring.overrides()
}
@type t :: %__MODULE__{
monitored_pids: %{pid() => reference()}
}
defstruct monitored_pids: %{}
## Client
@spec start_link() :: GenServer.on_start()
def start_link() do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@doc """
Retrieves the info entry for the specified ring.
"""
@spec get(name :: Ring.name()) :: {:ok, entry()} | {:error, :no_ring}
def get(name) when is_atom(name) do
case Process.whereis(name) do
nil ->
{:error, :no_ring}
pid ->
get(pid)
end
end
@spec get(pid()) :: {:ok, entry()} | {:error, :no_ring}
def get(pid) when is_pid(pid) do
case :ets.lookup(__MODULE__, pid) do
[{^pid, entry}] ->
{:ok, entry}
_ ->
{:error, :no_ring}
end
end
@doc """
Sets the info entry for the specified ring.
"""
@spec set(name :: Ring.name(), entry()) :: :ok | {:error, :no_ring}
def set(name, entry) when is_atom(name) do
case Process.whereis(name) do
nil ->
{:error, :no_ring}
pid ->
set(pid, entry)
end
end
@spec set(pid(), entry()) :: :ok
def set(pid, entry) when is_pid(pid) do
GenServer.call(__MODULE__, {:set, pid, entry})
end
## Server
@spec init(:ok) :: {:ok, t}
def init(:ok) do
:ets.new(__MODULE__, [
:protected,
:set,
:named_table,
{:read_concurrency, true}
])
{:ok, %__MODULE__{}}
end
def handle_call({:set, pid, entry}, _from, state) do
state = monitor_ring(state, pid)
true = :ets.insert(__MODULE__, {pid, entry})
{:reply, :ok, state}
end
def handle_info({:DOWN, monitor_ref, :process, pid, _reason}, %__MODULE__{} = state) do
monitored_pids =
case Map.pop(state.monitored_pids, pid) do
{nil, monitored_pids} ->
monitored_pids
{^monitor_ref, monitored_pids} ->
:ets.delete(__MODULE__, pid)
monitored_pids
end
{:noreply, %__MODULE__{state | monitored_pids: monitored_pids}}
end
## Private
@spec monitor_ring(state :: t(), pid()) :: t()
defp monitor_ring(%__MODULE__{} = state, pid) do
monitored_pids =
Map.put_new_lazy(state.monitored_pids, pid, fn ->
Process.monitor(pid)
end)
%__MODULE__{state | monitored_pids: monitored_pids}
end
end
| 24.542636 | 97 | 0.612129 |
73b5a38af16c6879f6306b89261b41c24d7f4fb6 | 1,084 | exs | Elixir | elixir/plt_builder/mix.exs | bshaffer/testing-infra-docker | 2e1b9c6461697fed36c9ab8792f8b3f9f1afaec1 | [
"Apache-2.0"
] | 17 | 2019-03-23T01:21:49.000Z | 2022-01-03T08:10:27.000Z | elixir/plt_builder/mix.exs | bshaffer/testing-infra-docker | 2e1b9c6461697fed36c9ab8792f8b3f9f1afaec1 | [
"Apache-2.0"
] | 80 | 2019-05-28T19:39:04.000Z | 2022-03-24T23:07:14.000Z | elixir/plt_builder/mix.exs | bshaffer/testing-infra-docker | 2e1b9c6461697fed36c9ab8792f8b3f9f1afaec1 | [
"Apache-2.0"
] | 30 | 2019-01-16T20:40:45.000Z | 2022-02-08T20:40:50.000Z | # Copyright 2018 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.
defmodule PltBuilder.MixProject do
use Mix.Project
def project do
[
app: :plt_builder,
version: "0.1.0",
elixir: "~> 1.4",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:dialyxir, "~> 1.0", only: [:dev], runtime: false}
]
end
end
| 25.809524 | 74 | 0.675277 |
73b5aed68676b8994c56045d068337f18159e26d | 991 | exs | Elixir | test/ex_doc/markdown_test.exs | ScrimpyCat/ex_doc | deabff56abc0c4f4890caebfd4a66630be032146 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | test/ex_doc/markdown_test.exs | ScrimpyCat/ex_doc | deabff56abc0c4f4890caebfd4a66630be032146 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | test/ex_doc/markdown_test.exs | ScrimpyCat/ex_doc | deabff56abc0c4f4890caebfd4a66630be032146 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | defmodule ExDoc.MarkdownTest do
use ExUnit.Case, async: true
alias ExDoc.Markdown, as: Markdown
test "add iex/elixir to markdown codeblocks" do
with_empty_class = ~S[<pre><code class="">mix run --no-halt path/to/file.exs]
without_class = "<pre><code>mix run --no-halt path/to/file.exs"
iex_detected_with_empty_class = ~S[<pre><code class="">iex> max(4, 5)]
iex_detected_without_class = ~S[<pre><code>iex> max(4, 5)]
assert Markdown.pretty_codeblocks(with_empty_class) ==
~S[<pre><code class="elixir">mix run --no-halt path/to/file.exs]
assert Markdown.pretty_codeblocks(without_class) ==
~S[<pre><code class="elixir">mix run --no-halt path/to/file.exs]
assert Markdown.pretty_codeblocks(iex_detected_with_empty_class) ==
~S[<pre><code class="iex elixir">iex> max(4, 5)]
assert Markdown.pretty_codeblocks(iex_detected_without_class) ==
~S[<pre><code class="iex elixir">iex> max(4, 5)]
end
end
| 45.045455 | 81 | 0.683148 |
73b5b0a0e8ede97dd7b78376f5cfeea6e62f0efd | 948 | ex | Elixir | lib/oli_web/views/api/product_view.ex | chrislawson/oli-torus | 94165b211ab74fac3e7c8a14110a394fa9a6f320 | [
"MIT"
] | null | null | null | lib/oli_web/views/api/product_view.ex | chrislawson/oli-torus | 94165b211ab74fac3e7c8a14110a394fa9a6f320 | [
"MIT"
] | null | null | null | lib/oli_web/views/api/product_view.ex | chrislawson/oli-torus | 94165b211ab74fac3e7c8a14110a394fa9a6f320 | [
"MIT"
] | null | null | null | defmodule OliWeb.Api.ProductView do
use OliWeb, :view
alias OliWeb.Api.ProductView
def render("index.json", %{products: products}) do
%{
result: "success",
products: render_many(products, ProductView, "product.json")
}
end
def render("show.json", %{product: product}) do
%{product: render_one(product, ProductView, "product.json")}
end
def render("product.json", %{product: product}) do
%{
slug: product.slug,
description: product.description,
title: product.title,
status: product.status,
requires_payment: product.requires_payment,
amount: amount(product.requires_payment, product.amount),
has_grace_period: product.has_grace_period,
grace_period_days: product.grace_period_days,
grace_period_strategy: product.grace_period_strategy
}
end
defp amount(false, _amount), do: nil
defp amount(true, amount), do: Money.to_string!(amount)
end
| 28.727273 | 66 | 0.695148 |
73b5b9331404e91ec3e1bbbd1deeac454dc36724 | 1,131 | exs | Elixir | config/config.exs | joshnuss/dependency | eb5962ebbb276a72043e99b0b908175f5c3d2ff5 | [
"MIT"
] | null | null | null | config/config.exs | joshnuss/dependency | eb5962ebbb276a72043e99b0b908175f5c3d2ff5 | [
"MIT"
] | null | null | null | config/config.exs | joshnuss/dependency | eb5962ebbb276a72043e99b0b908175f5c3d2ff5 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure your application as:
#
# config :dependency, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:dependency, :key)
#
# You can also configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env()}.exs"
| 36.483871 | 73 | 0.751547 |
73b5ced085a4988edef9de2e365ebe5cd67d16ed | 602 | ex | Elixir | sample/lib/sample/application.ex | jeffweiss/vault_ecto_example | 246ca951e52d5deec893d44a795fb6d225a4d3e7 | [
"MIT"
] | null | null | null | sample/lib/sample/application.ex | jeffweiss/vault_ecto_example | 246ca951e52d5deec893d44a795fb6d225a4d3e7 | [
"MIT"
] | null | null | null | sample/lib/sample/application.ex | jeffweiss/vault_ecto_example | 246ca951e52d5deec893d44a795fb6d225a4d3e7 | [
"MIT"
] | null | null | null | defmodule Sample.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Starts a worker by calling: Sample.Worker.start_link(arg)
# {Sample.Worker, arg}
{Sample.Repo, []}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Sample.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 26.173913 | 65 | 0.696013 |