hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
03665052b0c0ddd0a90e7095f376fba36c63e1c5
1,063
ex
Elixir
apps/omg/lib/omg/root_chain_coordinator/measure.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
1
2020-10-06T03:07:47.000Z
2020-10-06T03:07:47.000Z
apps/omg/lib/omg/root_chain_coordinator/measure.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
9
2020-09-16T15:31:17.000Z
2021-03-17T07:12:35.000Z
apps/omg/lib/omg/root_chain_coordinator/measure.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
1
2020-09-30T17:17:27.000Z
2020-09-30T17:17:27.000Z
# 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 OMG.RootChainCoordinator.Measure do @moduledoc """ Counting business metrics sent to Datadog """ import OMG.Status.Metric.Event, only: [name: 2] alias OMG.RootChainCoordinator alias OMG.Status.Metric.Datadog def handle_event([:process, RootChainCoordinator], _, state, _config) do value = self() |> Process.info(:message_queue_len) |> elem(1) _ = Datadog.gauge(name(state.service_name, :message_queue_len), value) end end
31.264706
74
0.736595
0366846dda453f12c11d2ba3d741350e6392abee
1,298
ex
Elixir
lib/slack/rtm.ex
aMikeChen/Elixir-Slack
8b425ecb2630712deb4049ac14399047eeb5edb1
[ "MIT" ]
null
null
null
lib/slack/rtm.ex
aMikeChen/Elixir-Slack
8b425ecb2630712deb4049ac14399047eeb5edb1
[ "MIT" ]
null
null
null
lib/slack/rtm.ex
aMikeChen/Elixir-Slack
8b425ecb2630712deb4049ac14399047eeb5edb1
[ "MIT" ]
null
null
null
defmodule Slack.JsonDecodeError do @moduledoc false defexception [:reason, :string] def message(%Slack.JsonDecodeError{reason: reason, string: string}) do "Poison could not decode string for reason: `:#{reason}`, string given:\n#{string}" end end defmodule Slack.Rtm do @moduledoc false def start(token) do with url <- slack_url(token), headers <- [], options <- Application.get_env(:slack, :web_http_client_opts, []) do url |> HTTPoison.get(headers, options) |> handle_response() end end defp handle_response({:ok, %HTTPoison.Response{body: body}}) do case Jason.decode!(body, keys: :atoms) do %{ok: true} = json -> {:ok, json} %{error: reason} -> {:error, "Slack API returned an error `#{reason}.\n Response: #{body}"} _ -> {:error, "Invalid RTM response"} end rescue error in Jason.DecodeError -> %Jason.DecodeError{data: reason, position: _, token: _} = error {:error, %Slack.JsonDecodeError{reason: reason, string: body}} end defp handle_response(error), do: error defp slack_url(token) do Application.get_env(:slack, :url, "https://slack.com") <> "/api/rtm.connect?token=#{token}&batch_presence_aware=true&presence_sub=true" end end
27.041667
87
0.640216
0366e2dc597e17536bd429724d579e970b2b22c2
1,389
ex
Elixir
web/views.ex
RokkinCat/rkkn_cloud
6f2dd1b2d1b6a2e32380f2400e0effbe1b82fdf4
[ "MIT" ]
null
null
null
web/views.ex
RokkinCat/rkkn_cloud
6f2dd1b2d1b6a2e32380f2400e0effbe1b82fdf4
[ "MIT" ]
null
null
null
web/views.ex
RokkinCat/rkkn_cloud
6f2dd1b2d1b6a2e32380f2400e0effbe1b82fdf4
[ "MIT" ]
null
null
null
defmodule RkknCloud.Views do import Plug.Conn, only: [get_req_header: 2, put_resp_header: 3, send_resp: 3, halt: 1] defmacro __using__(_options) do quote do use Phoenix.View import unquote(__MODULE__) # This block is expanded within all views for aliases, imports, etc import RkknCloud.I18n import RkknCloud.Router.Helpers end end # Functions defined here are available to all other views/templates def datetime_string(date_time) do date_time.to_erl |> Date.from |> DateFormat.format!("{RFC1123}") |> Poison.Encoder.BitString.encode end def authenticate(conn, _options) do conn |> get_req_header("authorization") |> parse_auth |> check_credentials(conn) end defp parse_auth(["Basic " <> encoded_creds | _]) do {:ok, decoded} = Base.decode64(encoded_creds) decoded end defp parse_auth([]), do: nil defp check_creds(api_key <> ":", conn) do case APIKey.fetch(api_key) do nil -> respond_with_login(conn) _ -> conn end end defp check_creds(_, conn) do: respond_with_login(conn) defp respond_with_login(conn) do conn |> put_resp_header("Www-Authenticate", "Basic realm=\"Private Area\"") |> send_resp(401, "") |> halt! end end
25.254545
74
0.616991
036733bc50ef8272b78a283494c51647abf88786
2,924
ex
Elixir
lib/aws/generated/health_lake.ex
salemove/aws-elixir
debdf6482158a71a57636ac664c911e682093395
[ "Apache-2.0" ]
null
null
null
lib/aws/generated/health_lake.ex
salemove/aws-elixir
debdf6482158a71a57636ac664c911e682093395
[ "Apache-2.0" ]
null
null
null
lib/aws/generated/health_lake.ex
salemove/aws-elixir
debdf6482158a71a57636ac664c911e682093395
[ "Apache-2.0" ]
null
null
null
# WARNING: DO NOT EDIT, AUTO-GENERATED CODE! # See https://github.com/aws-beam/aws-codegen for more details. defmodule AWS.HealthLake do @moduledoc """ Amazon HealthLake is a HIPAA eligibile service that allows customers to store, transform, query, and analyze their FHIR-formatted data in a consistent fashion in the cloud. """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: "HealthLake", api_version: "2017-07-01", content_type: "application/x-amz-json-1.0", credential_scope: nil, endpoint_prefix: "healthlake", global?: false, protocol: "json", service_id: "HealthLake", signature_version: "v4", signing_name: "healthlake", target_prefix: "HealthLake" } end @doc """ Creates a Data Store that can ingest and export FHIR formatted data. """ def create_fhir_datastore(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateFHIRDatastore", input, options) end @doc """ Deletes a Data Store. """ def delete_fhir_datastore(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteFHIRDatastore", input, options) end @doc """ Gets the properties associated with the FHIR Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint. """ def describe_fhir_datastore(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeFHIRDatastore", input, options) end @doc """ Displays the properties of a FHIR export job, including the ID, ARN, name, and the status of the job. """ def describe_fhir_export_job(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeFHIRExportJob", input, options) end @doc """ Displays the properties of a FHIR import job, including the ID, ARN, name, and the status of the job. """ def describe_fhir_import_job(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeFHIRImportJob", input, options) end @doc """ Lists all FHIR Data Stores that are in the user’s account, regardless of Data Store status. """ def list_fhir_datastores(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListFHIRDatastores", input, options) end @doc """ Begins a FHIR export job. """ def start_fhir_export_job(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "StartFHIRExportJob", input, options) end @doc """ Begins a FHIR Import job. """ def start_fhir_import_job(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "StartFHIRImportJob", input, options) end end
32.131868
85
0.69015
036778dcf5ee53e9b1962d21ecdfde66c068bfa4
2,292
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/dfp_settings.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/dfp_settings.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/dfp_settings.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.DFAReporting.V33.Model.DfpSettings do @moduledoc """ Google Ad Manager Settings ## Attributes * `dfpNetworkCode` (*type:* `String.t`, *default:* `nil`) - Ad Manager network code for this directory site. * `dfpNetworkName` (*type:* `String.t`, *default:* `nil`) - Ad Manager network name for this directory site. * `programmaticPlacementAccepted` (*type:* `boolean()`, *default:* `nil`) - Whether this directory site accepts programmatic placements. * `pubPaidPlacementAccepted` (*type:* `boolean()`, *default:* `nil`) - Whether this directory site accepts publisher-paid tags. * `publisherPortalOnly` (*type:* `boolean()`, *default:* `nil`) - Whether this directory site is available only via Publisher Portal. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :dfpNetworkCode => String.t(), :dfpNetworkName => String.t(), :programmaticPlacementAccepted => boolean(), :pubPaidPlacementAccepted => boolean(), :publisherPortalOnly => boolean() } field(:dfpNetworkCode) field(:dfpNetworkName) field(:programmaticPlacementAccepted) field(:pubPaidPlacementAccepted) field(:publisherPortalOnly) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.DfpSettings do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.DfpSettings.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.DfpSettings do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.847458
140
0.724695
0367d25f3c13eb06c75551db01901a13af9cf24a
334
ex
Elixir
apps/core/lib/common.ex
iporaitech/phoenix-webpack-react-docker
c454db0b851b9d00db868a64b96e567d4a0cc3d9
[ "MIT" ]
25
2016-08-09T15:04:37.000Z
2021-11-15T12:20:27.000Z
apps/core/lib/common.ex
iporaitech/phoenix-webpack-react-docker
c454db0b851b9d00db868a64b96e567d4a0cc3d9
[ "MIT" ]
62
2016-05-23T20:16:40.000Z
2017-04-18T18:36:29.000Z
apps/core/lib/common.ex
iporaitech/phoenix-webpack-react-docker
c454db0b851b9d00db868a64b96e567d4a0cc3d9
[ "MIT" ]
10
2016-08-17T15:29:21.000Z
2017-02-28T07:58:30.000Z
defmodule Core.Common do def model do quote do use Ecto.Schema import Ecto import Ecto.Changeset import Ecto.Query end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
17.578947
61
0.655689
0367eaf1cbbf378bd4e46ef3f0d71bc6ee442f59
385
exs
Elixir
apps/robby_web/priv/repo/migrations/20160318182913_create_message.exs
jeffweiss/openrobby
9fed2024e6ce87a6fe27ef3af85558f3116aca2a
[ "Apache-2.0" ]
null
null
null
apps/robby_web/priv/repo/migrations/20160318182913_create_message.exs
jeffweiss/openrobby
9fed2024e6ce87a6fe27ef3af85558f3116aca2a
[ "Apache-2.0" ]
null
null
null
apps/robby_web/priv/repo/migrations/20160318182913_create_message.exs
jeffweiss/openrobby
9fed2024e6ce87a6fe27ef3af85558f3116aca2a
[ "Apache-2.0" ]
null
null
null
defmodule RobbyWeb.Repo.Migrations.CreateMessage do use Ecto.Migration def change do create table(:messages) do add :user_id, references(:users, on_delete: :nothing) add :room_id, references(:rooms, on_delete: :nothing) add :body, :string timestamps() end create index(:messages, [:user_id]) create index(:messages, [:room_id]) end end
22.647059
59
0.675325
0367fb2388a6409a8c9625fbd4520d99f8c18bee
2,106
ex
Elixir
lib/nadia/bot/graph_api.ex
lightcyphers/nadia
b44535138aac3c61a40816d9460a731127360f1e
[ "MIT" ]
null
null
null
lib/nadia/bot/graph_api.ex
lightcyphers/nadia
b44535138aac3c61a40816d9460a731127360f1e
[ "MIT" ]
null
null
null
lib/nadia/bot/graph_api.ex
lightcyphers/nadia
b44535138aac3c61a40816d9460a731127360f1e
[ "MIT" ]
null
null
null
defmodule Nadia.Bot.GraphAPI do @moduledoc """ Provides basic functionalities for Telegram Bot API. """ alias Nadia.Graph.Model.Error alias Nadia.Bot.Config defp build_url(bot, method), do: Config.graph_base_url(bot) <> "/" <> method defp process_response(response, method) do case decode_response(response) do {:ok, true} -> :ok {:ok, result} -> {:ok, Nadia.Graph.Parser.parse_result(result, method)} %{ok: false, description: description} -> {:error, %Error{reason: description}} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %Error{reason: reason}} end end defp decode_response(response) do with {:ok, %HTTPoison.Response{body: body}} <- response, %{result: result} <- Jason.decode!(body, keys: :atoms), do: {:ok, result} end defp build_multipart_request(params, file_field) do {file_path, params} = Keyword.pop(params, file_field) params = for {k, v} <- params, do: {to_string(k), v} {:multipart, params ++ [ {:file, file_path, {"form-data", [{"name", to_string(file_field)}, {"filename", file_path}]}, []} ]} end defp build_request(params, file_field) do params = params |> Keyword.update(:reply_markup, nil, &Jason.encode!(&1)) |> Stream.filter(fn {_, v} -> v end) |> Enum.map(fn {k, v} -> {k, to_string(v)} end) if !is_nil(file_field) and File.exists?(params[file_field]) do build_multipart_request(params, file_field) else {:form, params} end end @doc """ Generic method to call Telegram Bot API. Args: * `bot` - name of the bot * `method` - name of API method * `options` - orddict of options * `file_field` - specify the key of file_field in `options` when sending files """ def request(bot, method, options \\ [], file_field \\ nil) do timeout = (Keyword.get(options, :timeout, 0) + Config.recv_timeout(bot)) * 1000 build_url(bot, method) |> HTTPoison.post(build_request(options, file_field), [], recv_timeout: timeout) |> process_response(method) end end
30.970588
88
0.632953
0368572d91b32b73cd84f348bca6e7d4576231f3
27,416
ex
Elixir
lib/elixir/lib/gen_event.ex
RyanBard/elixir
3e0f3b47cf26aa121470141b9a1aa55a366c066e
[ "Apache-2.0" ]
2
2018-11-15T06:38:14.000Z
2018-11-17T18:03:14.000Z
lib/elixir/lib/gen_event.ex
RyanBard/elixir
3e0f3b47cf26aa121470141b9a1aa55a366c066e
[ "Apache-2.0" ]
1
2018-09-10T23:36:45.000Z
2018-09-10T23:36:45.000Z
lib/elixir/lib/gen_event.ex
RyanBard/elixir
3e0f3b47cf26aa121470141b9a1aa55a366c066e
[ "Apache-2.0" ]
1
2018-09-10T23:32:56.000Z
2018-09-10T23:32:56.000Z
defmodule GenEvent do # TODO: Remove by 2.0 # Functions from this module are deprecated in elixir_dispatch. @moduledoc """ A event manager with event handlers behaviour. If you are interested in implementing an event manager, please read the "Alternatives" section below. If you have to implement an event handler to integrate with an existing system, such as Elixir's Logger, please use `:gen_event` instead. ## Alternatives There are a few suitable alternatives to replace GenEvent. Each of them can be the most beneficial based on the use case. ### Supervisor and GenServers One alternative to GenEvent is a very minimal solution consisting of using a supervisor and multiple GenServers started under it. The supervisor acts as the "event manager" and the children GenServers act as the "event handlers". This approach has some shortcomings (it provides no backpressure for example) but can still replace GenEvent for low-profile usages of it. [This blog post by José Valim](http://blog.plataformatec.com.br/2016/11/replacing-genevent-by-a-supervisor-genserver/) has more detailed information on this approach. ### GenStage If the use case where you were using GenEvent requires more complex logic, [GenStage](https://github.com/elixir-lang/gen_stage) provides a great alternative. GenStage is an external Elixir library maintained by the Elixir team; it provides a tool to implement systems that exchange events in a demand-driven way with built-in support for backpressure. See the [GenStage documentation](https://hexdocs.pm/gen_stage) for more information. ### `:gen_event` If your use case requires exactly what GenEvent provided, or you have to integrate with an existing `:gen_event`-based system, you can still use the [`:gen_event`](http://erlang.org/doc/man/gen_event.html) Erlang module. """ @moduledoc deprecated: "Use Erlang/OTP's :gen_event module instead" @callback init(args :: term) :: {:ok, state} | {:ok, state, :hibernate} | {:error, reason :: any} when state: any @callback handle_event(event :: term, state :: term) :: {:ok, new_state} | {:ok, new_state, :hibernate} | :remove_handler when new_state: term @callback handle_call(request :: term, state :: term) :: {:ok, reply, new_state} | {:ok, reply, new_state, :hibernate} | {:remove_handler, reply} when reply: term, new_state: term @callback handle_info(msg :: term, state :: term) :: {:ok, new_state} | {:ok, new_state, :hibernate} | :remove_handler when new_state: term @callback terminate(reason, state :: term) :: term when reason: :stop | {:stop, term} | :remove_handler | {:error, term} | term @callback code_change(old_vsn, state :: term, extra :: term) :: {:ok, new_state :: term} when old_vsn: term | {:down, term} @type on_start :: {:ok, pid} | {:error, {:already_started, pid}} @type name :: atom | {:global, term} | {:via, module, term} @type options :: [name: name] @type manager :: pid | name | {atom, node} @type handler :: atom | {atom, term} message = "Use one of the alternatives described in the documentation for the GenEvent module" @deprecated message @doc false defmacro __using__(_) do %{file: file, line: line} = __CALLER__ deprecation_message = "the GenEvent module is deprecated, see its documentation for alternatives" :elixir_errors.warn(line, file, deprecation_message) quote location: :keep do @behaviour :gen_event @doc false def init(args) do {:ok, args} end @doc false def handle_event(_event, state) do {:ok, state} end @doc false def handle_call(msg, state) do proc = case Process.info(self(), :registered_name) do {_, []} -> self() {_, name} -> name end # We do this to trick Dialyzer to not complain about non-local returns. case :erlang.phash2(1, 1) do 0 -> raise "attempted to call GenEvent #{inspect(proc)} but no handle_call/2 clause was provided" 1 -> {:remove_handler, {:bad_call, msg}} end end @doc false def handle_info(_msg, state) do {:ok, state} end @doc false def terminate(_reason, _state) do :ok end @doc false def code_change(_old, state, _extra) do {:ok, state} end defoverridable init: 1, handle_event: 2, handle_call: 2, handle_info: 2, terminate: 2, code_change: 3 end end @doc false @deprecated message @spec start_link(options) :: on_start def start_link(options \\ []) when is_list(options) do do_start(:link, options) end @doc false @deprecated message @spec start(options) :: on_start def start(options \\ []) when is_list(options) do do_start(:nolink, options) end @no_callback :"no callback module" defp do_start(mode, options) do case Keyword.get(options, :name) do nil -> :gen.start(GenEvent, mode, @no_callback, [], []) atom when is_atom(atom) -> :gen.start(GenEvent, mode, {:local, atom}, @no_callback, [], []) {:global, _term} = tuple -> :gen.start(GenEvent, mode, tuple, @no_callback, [], []) {:via, via_module, _term} = tuple when is_atom(via_module) -> :gen.start(GenEvent, mode, tuple, @no_callback, [], []) other -> raise ArgumentError, """ expected :name option to be one of the following: * nil * atom * {:global, term} * {:via, module, term} Got: #{inspect(other)} """ end end @doc false @deprecated message @spec stream(manager, keyword) :: GenEvent.Stream.t() def stream(manager, options \\ []) do %GenEvent.Stream{manager: manager, timeout: Keyword.get(options, :timeout, :infinity)} end @doc false @deprecated message @spec add_handler(manager, handler, term) :: :ok | {:error, term} def add_handler(manager, handler, args) do rpc(manager, {:add_handler, handler, args}) end @doc false @deprecated message @spec add_mon_handler(manager, handler, term) :: :ok | {:error, term} def add_mon_handler(manager, handler, args) do rpc(manager, {:add_mon_handler, handler, args, self()}) end @doc false @deprecated message @spec notify(manager, term) :: :ok def notify(manager, event) def notify({:global, name}, msg) do try do :global.send(name, {:notify, msg}) :ok catch _, _ -> :ok end end def notify({:via, mod, name}, msg) when is_atom(mod) do try do mod.send(name, {:notify, msg}) :ok catch _, _ -> :ok end end def notify(manager, msg) when is_pid(manager) when is_atom(manager) when tuple_size(manager) == 2 and is_atom(elem(manager, 0)) and is_atom(elem(manager, 1)) do send(manager, {:notify, msg}) :ok end @doc false @deprecated message @spec sync_notify(manager, term) :: :ok def sync_notify(manager, event) do rpc(manager, {:sync_notify, event}) end @doc false @deprecated message @spec ack_notify(manager, term) :: :ok def ack_notify(manager, event) do rpc(manager, {:ack_notify, event}) end @doc false @deprecated message @spec call(manager, handler, term, timeout) :: term | {:error, term} def call(manager, handler, request, timeout \\ 5000) do try do :gen.call(manager, self(), {:call, handler, request}, timeout) catch :exit, reason -> exit({reason, {__MODULE__, :call, [manager, handler, request, timeout]}}) else {:ok, res} -> res end end @doc false @deprecated message @spec remove_handler(manager, handler, term) :: term | {:error, term} def remove_handler(manager, handler, args) do rpc(manager, {:delete_handler, handler, args}) end @doc false @deprecated message @spec swap_handler(manager, handler, term, handler, term) :: :ok | {:error, term} def swap_handler(manager, handler1, args1, handler2, args2) do rpc(manager, {:swap_handler, handler1, args1, handler2, args2}) end @doc false @deprecated message @spec swap_mon_handler(manager, handler, term, handler, term) :: :ok | {:error, term} def swap_mon_handler(manager, handler1, args1, handler2, args2) do rpc(manager, {:swap_mon_handler, handler1, args1, handler2, args2, self()}) end @doc false @deprecated message @spec which_handlers(manager) :: [handler] def which_handlers(manager) do rpc(manager, :which_handlers) end @doc false @deprecated message @spec stop(manager, reason :: term, timeout) :: :ok def stop(manager, reason \\ :normal, timeout \\ :infinity) do :gen.stop(manager, reason, timeout) end defp rpc(module, cmd) do {:ok, reply} = :gen.call(module, self(), cmd, :infinity) reply end ## Init callbacks require Record Record.defrecordp(:handler, [:module, :id, :state, :pid, :ref]) @doc false def init_it(starter, :self, name, mod, args, options) do init_it(starter, self(), name, mod, args, options) end def init_it(starter, parent, name, _mod, _args, options) do Process.put(:"$initial_call", {__MODULE__, :init_it, 6}) debug = if function_exported?(:gen, :debug_options, 2) do :gen.debug_options(name, options) else :gen.debug_options(options) end :proc_lib.init_ack(starter, {:ok, self()}) loop(parent, name(name), [], debug, false) end @doc false def init_hib(parent, name, handlers, debug) do fetch_msg(parent, name, handlers, debug, true) end defp name({:local, name}), do: name defp name({:global, name}), do: name defp name({:via, _, name}), do: name defp name(pid) when is_pid(pid), do: pid ## Loop defp loop(parent, name, handlers, debug, true) do :proc_lib.hibernate(__MODULE__, :init_hib, [parent, name, handlers, debug]) end defp loop(parent, name, handlers, debug, false) do fetch_msg(parent, name, handlers, debug, false) end defp fetch_msg(parent, name, handlers, debug, hib) do receive do {:system, from, req} -> :sys.handle_system_msg(req, from, parent, __MODULE__, debug, [name, handlers, hib], hib) {:EXIT, ^parent, reason} -> server_terminate(reason, parent, handlers, name) msg when debug == [] -> handle_msg(msg, parent, name, handlers, []) msg -> debug = :sys.handle_debug(debug, &print_event/3, name, {:in, msg}) handle_msg(msg, parent, name, handlers, debug) end end defp handle_msg(msg, parent, name, handlers, debug) do case msg do {:notify, event} -> {hib, handlers} = server_event(:async, event, handlers, name) loop(parent, name, handlers, debug, hib) {_from, _tag, {:notify, event}} -> {hib, handlers} = server_event(:async, event, handlers, name) loop(parent, name, handlers, debug, hib) {_from, tag, {:ack_notify, event}} -> reply(tag, :ok) {hib, handlers} = server_event(:ack, event, handlers, name) loop(parent, name, handlers, debug, hib) {_from, tag, {:sync_notify, event}} -> {hib, handlers} = server_event(:sync, event, handlers, name) reply(tag, :ok) loop(parent, name, handlers, debug, hib) {:DOWN, ref, :process, _pid, reason} = other -> case handle_down(ref, reason, handlers, name) do {:ok, handlers} -> loop(parent, name, handlers, debug, false) :error -> {hib, handlers} = server_info(other, handlers, name) loop(parent, name, handlers, debug, hib) end {_from, tag, {:call, handler, query}} -> {hib, reply, handlers} = server_call(handler, query, handlers, name) reply(tag, reply) loop(parent, name, handlers, debug, hib) {_from, tag, {:add_handler, handler, args}} -> {hib, reply, handlers} = server_add_handler(handler, args, handlers) reply(tag, reply) loop(parent, name, handlers, debug, hib) {_from, tag, {:add_mon_handler, handler, args, notify}} -> {hib, reply, handlers} = server_add_mon_handler(handler, args, handlers, notify) reply(tag, reply) loop(parent, name, handlers, debug, hib) {_from, tag, {:add_process_handler, pid, notify}} -> {hib, reply, handlers} = server_add_process_handler(pid, handlers, notify) reply(tag, reply) loop(parent, name, handlers, debug, hib) {_from, tag, {:delete_handler, handler, args}} -> {reply, handlers} = server_remove_handler(handler, args, handlers, name) reply(tag, reply) loop(parent, name, handlers, debug, false) {_from, tag, {:swap_handler, handler1, args1, handler2, args2}} -> {hib, reply, handlers} = server_swap_handler(handler1, args1, handler2, args2, handlers, nil, name) reply(tag, reply) loop(parent, name, handlers, debug, hib) {_from, tag, {:swap_mon_handler, handler1, args1, handler2, args2, mon}} -> {hib, reply, handlers} = server_swap_handler(handler1, args1, handler2, args2, handlers, mon, name) reply(tag, reply) loop(parent, name, handlers, debug, hib) {_from, tag, :which_handlers} -> reply(tag, server_which_handlers(handlers)) loop(parent, name, handlers, debug, false) {_from, tag, :get_modules} -> reply(tag, server_get_modules(handlers)) loop(parent, name, handlers, debug, false) other -> {hib, handlers} = server_info(other, handlers, name) loop(parent, name, handlers, debug, hib) end end ## System callbacks @doc false def system_continue(parent, debug, [name, handlers, hib]) do loop(parent, name, handlers, debug, hib) end @doc false def system_terminate(reason, parent, _debug, [name, handlers, _hib]) do server_terminate(reason, parent, handlers, name) end @doc false def system_code_change([name, handlers, hib], module, old_vsn, extra) do handlers = for handler <- handlers do if handler(handler, :module) == module do {:ok, state} = module.code_change(old_vsn, handler(handler, :state), extra) handler(handler, state: state) else handler end end {:ok, [name, handlers, hib]} end @doc false def system_get_state([_name, handlers, _hib]) do tuples = for handler(module: mod, id: id, state: state) <- handlers do {mod, id, state} end {:ok, tuples} end @doc false def system_replace_state(fun, [name, handlers, hib]) do {handlers, states} = :lists.unzip( for handler <- handlers do handler(module: mod, id: id, state: state) = handler cur = {mod, id, state} try do new = {^mod, ^id, new_state} = fun.(cur) {handler(handler, state: new_state), new} catch _, _ -> {handler, cur} end end ) {:ok, states, [name, handlers, hib]} end @doc false def format_status(opt, status_data) do [pdict, sys_state, parent, _debug, [name, handlers, _hib]] = status_data header = :gen.format_status_header('Status for event handler', name) formatted = for handler <- handlers do handler(module: module, state: state) = handler if function_exported?(module, :format_status, 2) do try do state = module.format_status(opt, [pdict, state]) handler(handler, state: state) catch _, _ -> handler end else handler end end [ header: header, data: [{'Status', sys_state}, {'Parent', parent}], items: {'Installed handlers', formatted} ] end ## Loop helpers defp print_event(dev, {:in, msg}, name) do case msg do {:notify, event} -> IO.puts(dev, "*DBG* #{inspect(name)} got event #{inspect(event)}") {_, _, {:call, handler, query}} -> IO.puts( dev, "*DBG* #{inspect(name)} (handler #{inspect(handler)}) got call #{inspect(query)}" ) _ -> IO.puts(dev, "*DBG* #{inspect(name)} got #{inspect(msg)}") end end defp print_event(dev, dbg, name) do IO.puts(dev, "*DBG* #{inspect(name)}: #{inspect(dbg)}") end defp server_add_handler({module, id}, args, handlers) do handler = handler(module: module, id: {module, id}) do_add_handler(module, handler, args, handlers, :ok) end defp server_add_handler(module, args, handlers) do handler = handler(module: module, id: module) do_add_handler(module, handler, args, handlers, :ok) end defp server_add_mon_handler({module, id}, args, handlers, notify) do ref = Process.monitor(notify) handler = handler(module: module, id: {module, id}, pid: notify, ref: ref) do_add_handler(module, handler, args, handlers, :ok) end defp server_add_mon_handler(module, args, handlers, notify) do ref = Process.monitor(notify) handler = handler(module: module, id: module, pid: notify, ref: ref) do_add_handler(module, handler, args, handlers, :ok) end defp server_add_process_handler(pid, handlers, notify) do ref = Process.monitor(pid) handler = handler(module: GenEvent.Stream, id: {self(), ref}, pid: notify, ref: ref) do_add_handler(GenEvent.Stream, handler, {pid, ref}, handlers, {self(), ref}) end defp server_remove_handler(module, args, handlers, name) do do_take_handler(module, args, handlers, name, :remove, :normal) end defp server_swap_handler(module1, args1, module2, args2, handlers, sup, name) do {state, handlers} = do_take_handler(module1, args1, handlers, name, :swapped, {:swapped, module2, sup}) if sup do server_add_mon_handler(module2, {args2, state}, handlers, sup) else server_add_handler(module2, {args2, state}, handlers) end end defp server_info(event, handlers, name) do handlers = :lists.reverse(handlers) server_notify(event, :handle_info, handlers, name, handlers, [], false) end defp server_event(mode, event, handlers, name) do {handlers, streams} = server_split_process_handlers(mode, event, handlers, [], []) {hib, handlers} = server_notify(event, :handle_event, handlers, name, handlers, [], false) {hib, server_collect_process_handlers(mode, event, streams, handlers, name)} end defp server_split_process_handlers(mode, event, [handler | t], handlers, streams) do case handler(handler, :id) do {pid, _ref} when is_pid(pid) -> server_process_notify(mode, event, handler) server_split_process_handlers(mode, event, t, handlers, [handler | streams]) _ -> server_split_process_handlers(mode, event, t, [handler | handlers], streams) end end defp server_split_process_handlers(_mode, _event, [], handlers, streams) do {handlers, streams} end defp server_process_notify(mode, event, handler(state: {pid, ref})) do send(pid, {self(), {self(), ref}, {mode_to_tag(mode), event}}) end defp mode_to_tag(:ack), do: :ack_notify defp mode_to_tag(:sync), do: :sync_notify defp mode_to_tag(:async), do: :notify defp server_notify(event, fun, [handler | t], name, handlers, acc, hib) do case server_update(handler, fun, event, name, handlers) do {new_hib, handler} -> server_notify(event, fun, t, name, handlers, [handler | acc], hib or new_hib) :error -> server_notify(event, fun, t, name, handlers, acc, hib) end end defp server_notify(_, _, [], _, _, acc, hib) do {hib, acc} end defp server_update(handler, fun, event, name, _handlers) do handler(module: module, state: state) = handler case do_handler(module, fun, [event, state]) do {:ok, res} -> case res do {:ok, state} -> {false, handler(handler, state: state)} {:ok, state, :hibernate} -> {true, handler(handler, state: state)} :remove_handler -> do_terminate(handler, :remove_handler, event, name, :normal) :error other -> reason = {:bad_return_value, other} do_terminate(handler, {:error, reason}, event, name, reason) :error end {:error, reason} -> do_terminate(handler, {:error, reason}, event, name, reason) :error end end defp server_collect_process_handlers(:async, event, [handler | t], handlers, name) do server_collect_process_handlers(:async, event, t, [handler | handlers], name) end defp server_collect_process_handlers(mode, event, [handler | t], handlers, name) when mode in [:sync, :ack] do handler(ref: ref, id: id) = handler receive do {^ref, :ok} -> server_collect_process_handlers(mode, event, t, [handler | handlers], name) {_from, tag, {:delete_handler, ^id, args}} -> do_terminate(handler, args, :remove, name, :normal) reply(tag, :ok) server_collect_process_handlers(mode, event, t, handlers, name) {:DOWN, ^ref, _, _, reason} -> do_terminate(handler, {:stop, reason}, :DOWN, name, :shutdown) server_collect_process_handlers(mode, event, t, handlers, name) end end defp server_collect_process_handlers(_mode, _event, [], handlers, _name) do handlers end defp server_call(module, query, handlers, name) do case :lists.keyfind(module, handler(:id) + 1, handlers) do false -> {false, {:error, :not_found}, handlers} handler -> case server_call_update(handler, query, name, handlers) do {{hib, handler}, reply} -> {hib, reply, :lists.keyreplace(module, handler(:id) + 1, handlers, handler)} {:error, reply} -> {false, reply, :lists.keydelete(module, handler(:id) + 1, handlers)} end end end defp server_call_update(handler, query, name, _handlers) do handler(module: module, state: state) = handler case do_handler(module, :handle_call, [query, state]) do {:ok, res} -> case res do {:ok, reply, state} -> {{false, handler(handler, state: state)}, reply} {:ok, reply, state, :hibernate} -> {{true, handler(handler, state: state)}, reply} {:remove_handler, reply} -> do_terminate(handler, :remove_handler, query, name, :normal) {:error, reply} other -> reason = {:bad_return_value, other} do_terminate(handler, {:error, reason}, query, name, reason) {:error, {:error, reason}} end {:error, reason} -> do_terminate(handler, {:error, reason}, query, name, reason) {:error, {:error, reason}} end end defp server_get_modules(handlers) do for(handler(module: module) <- handlers, do: module) |> :ordsets.from_list() |> :ordsets.to_list() end defp server_which_handlers(handlers) do for handler(id: id) <- handlers, do: id end defp server_terminate(reason, _parent, handlers, name) do _ = for handler <- handlers do do_terminate(handler, :stop, :stop, name, :shutdown) end exit(reason) end defp reply({from, ref}, msg) do send(from, {ref, msg}) end defp handle_down(ref, reason, handlers, name) do case :lists.keyfind(ref, handler(:ref) + 1, handlers) do false -> :error handler -> do_terminate(handler, {:stop, reason}, :DOWN, name, :shutdown) {:ok, :lists.keydelete(ref, handler(:ref) + 1, handlers)} end end defp do_add_handler(module, handler, arg, handlers, succ) do case :lists.keyfind(handler(handler, :id), handler(:id) + 1, handlers) do false -> case do_handler(module, :init, [arg]) do {:ok, res} -> case res do {:ok, state} -> {false, succ, [handler(handler, state: state) | handlers]} {:ok, state, :hibernate} -> {true, succ, [handler(handler, state: state) | handlers]} {:error, _} = error -> {false, error, handlers} other -> {false, {:error, {:bad_return_value, other}}, handlers} end {:error, _} = error -> {false, error, handlers} end _ -> {false, {:error, :already_present}, handlers} end end defp do_take_handler(module, args, handlers, name, last_in, reason) do case :lists.keytake(module, handler(:id) + 1, handlers) do {:value, handler, handlers} -> {do_terminate(handler, args, last_in, name, reason), handlers} false -> {{:error, :not_found}, handlers} end end defp do_terminate(handler, arg, last_in, name, reason) do handler(module: module, state: state) = handler res = case do_handler(module, :terminate, [arg, state]) do {:ok, res} -> res {:error, _} = error -> error end report_terminate(handler, reason, state, last_in, name) res end defp do_handler(mod, fun, args) do try do apply(mod, fun, args) catch :throw, val -> {:ok, val} :error, val -> {:error, {val, __STACKTRACE__}} :exit, val -> {:error, val} else res -> {:ok, res} end end defp report_terminate(handler, reason, state, last_in, name) do report_error(handler, reason, state, last_in, name) if ref = handler(handler, :ref) do Process.demonitor(ref, [:flush]) end if pid = handler(handler, :pid) do send(pid, {:gen_event_EXIT, handler(handler, :id), reason}) end end defp report_error(_handler, :normal, _, _, _), do: :ok defp report_error(_handler, :shutdown, _, _, _), do: :ok defp report_error(_handler, {:swapped, _, _}, _, _, _), do: :ok defp report_error(handler, reason, state, last_in, name) do reason = case reason do {:undef, [{m, f, a, _} | _] = mfas} -> cond do :code.is_loaded(m) == false -> {:"module could not be loaded", mfas} function_exported?(m, f, length(a)) -> reason true -> {:"function not exported", mfas} end _ -> reason end formatted = report_status(handler, state) :error_logger.error_msg( '** gen_event handler ~p crashed.~n' ++ '** Was installed in ~p~n' ++ '** Last event was: ~p~n' ++ '** When handler state == ~p~n' ++ '** Reason == ~p~n', [handler(handler, :id), name, last_in, formatted, reason] ) end defp report_status(handler(module: module), state) do if function_exported?(module, :format_status, 2) do try do module.format_status(:terminate, [Process.get(), state]) catch _, _ -> state end else state end end end
29.962842
104
0.611869
03685d895f45efff957619f6e9b301a665675f39
1,057
exs
Elixir
examples/ecto_poll_queue/postgres/mix.exs
rodrigues/honeydew
05777189f30b3b13428027ce75bdecf6d7b760db
[ "MIT" ]
null
null
null
examples/ecto_poll_queue/postgres/mix.exs
rodrigues/honeydew
05777189f30b3b13428027ce75bdecf6d7b760db
[ "MIT" ]
null
null
null
examples/ecto_poll_queue/postgres/mix.exs
rodrigues/honeydew
05777189f30b3b13428027ce75bdecf6d7b760db
[ "MIT" ]
null
null
null
defmodule EctoPollQueueExample.MixProject do use Mix.Project def project do [ app: :ecto_poll_queue_example, version: "0.1.0", elixir: "~> 1.5", start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps(), dialyzer: [ flags: [ :unmatched_returns, :error_handling, :race_conditions, :no_opaque ] ] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {EctoPollQueueExample.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:honeydew, path: "../../.."}, {:ecto, "~> 2.0"}, {:postgrex, "~> 0.13"}, {:dialyxir, "~> 0.5", only: :test, runtime: false} ] end defp aliases do [ "ecto.setup": ["ecto.create --quiet", "ecto.migrate --quiet"], "ecto.reset": ["ecto.drop --quiet", "ecto.setup"], test: ["ecto.reset", "test"] ] end end
21.571429
68
0.535478
03686631da76bfdf5d5f46b72d82975a891b9601
9,444
ex
Elixir
lib/exprotobuf/define_message.ex
ngenic/exprotobuf
f7b3ca9e7baebab8a204780f9847042aea6289ce
[ "Apache-2.0" ]
null
null
null
lib/exprotobuf/define_message.ex
ngenic/exprotobuf
f7b3ca9e7baebab8a204780f9847042aea6289ce
[ "Apache-2.0" ]
null
null
null
lib/exprotobuf/define_message.ex
ngenic/exprotobuf
f7b3ca9e7baebab8a204780f9847042aea6289ce
[ "Apache-2.0" ]
null
null
null
defmodule Protobuf.DefineMessage do @moduledoc false alias Protobuf.Decoder alias Protobuf.Encoder alias Protobuf.Field alias Protobuf.OneOfField alias Protobuf.Delimited alias Protobuf.Utils def def_message(name, fields, inject: inject, doc: doc, syntax: syntax) when is_list(fields) do struct_fields = record_fields(fields) # Inject everything in 'using' module if inject do quote location: :keep do @root __MODULE__ @record unquote(struct_fields) defstruct @record fields = unquote(struct_fields) def record, do: @record def syntax, do: unquote(syntax) unquote(define_typespec(name, fields)) unquote(encode_decode(name)) unquote(fields_methods(fields)) unquote(oneof_fields_methods(fields)) unquote(meta_information()) unquote(constructors(name)) defimpl Protobuf.Serializable do def serialize(object), do: unquote(name).encode(object) end end # Or create a nested module, with use_in functionality else quote location: :keep do root = __MODULE__ fields = unquote(struct_fields) use_in = @use_in[unquote(name)] defmodule unquote(name) do @moduledoc false unquote(Protobuf.Config.doc_quote(doc)) @root root @record unquote(struct_fields) defstruct @record def record, do: @record def syntax, do: unquote(syntax) unquote(define_typespec(name, fields)) unquote(encode_decode(name)) unquote(fields_methods(fields)) unquote(oneof_fields_methods(fields)) unquote(meta_information()) unquote(constructors(name)) if use_in != nil do Module.eval_quoted(__MODULE__, use_in, [], __ENV__) end defimpl Protobuf.Serializable do def serialize(object), do: unquote(name).encode(object) end end unquote(define_oneof_modules(name, fields)) end end end defp constructors(name) do quote location: :keep do def new(), do: new([]) def new(values) do struct(unquote(name), values) end end end defp define_typespec(module, field_list) when is_list(field_list) when is_atom(module) do case field_list do [%Field{name: :value, type: scalar, occurrence: occurrence}] when is_atom(scalar) and is_atom(occurrence) -> scalar_wrapper? = Utils.is_standard_scalar_wrapper(module) cond do scalar_wrapper? and occurrence == :required -> quote do @type t() :: unquote(define_scalar_typespec(scalar)) end scalar_wrapper? -> quote do @type t() :: unquote(define_scalar_typespec(scalar)) | nil end :else -> define_trivial_typespec(field_list) end [%Field{name: :value, type: {:enum, enum_module}, occurrence: occurrence}] when is_atom(enum_module) -> enum_wrapper? = Utils.is_enum_wrapper(module, enum_module) cond do enum_wrapper? and occurrence == :required -> quote do @type t() :: unquote(enum_module).t() end enum_wrapper? -> quote do @type t() :: unquote(enum_module).t() | nil end :else -> define_trivial_typespec(field_list) end _ -> define_trivial_typespec(field_list) end end defp define_trivial_typespec([]), do: nil defp define_trivial_typespec(fields) when is_list(fields) do field_types = define_trivial_typespec_fields(fields, []) map_type = {:%{}, [], field_types} module_type = {:%, [], [{:__MODULE__, [], Elixir}, map_type]} quote generated: true do @type t() :: unquote(module_type) end end defp define_trivial_typespec_fields([], acc), do: Enum.reverse(acc) defp define_trivial_typespec_fields([field | rest], acc) do case field do %Protobuf.Field{name: name, occurrence: :required, type: type} -> ast = {name, define_field_typespec(type)} define_trivial_typespec_fields(rest, [ast | acc]) %Protobuf.Field{name: name, occurrence: :optional, type: type} -> ast = {name, quote do unquote(define_field_typespec(type)) | nil end} define_trivial_typespec_fields(rest, [ast | acc]) %Protobuf.Field{name: name, occurrence: :repeated, type: type} -> ast = {name, quote do [unquote(define_field_typespec(type))] end} define_trivial_typespec_fields(rest, [ast | acc]) %Protobuf.OneOfField{name: name, fields: fields} -> ast = {name, quote do unquote(define_algebraic_type(fields)) end} define_trivial_typespec_fields(rest, [ast | acc]) end end defp define_algebraic_type(fields) do ast = for %Protobuf.Field{name: name, type: type} <- fields do {name, define_field_typespec(type)} end Protobuf.Utils.define_algebraic_type([nil | ast]) end defp define_oneof_modules(namespace, fields) when is_list(fields) do ast = for %Protobuf.OneOfField{} = field <- fields do define_oneof_instance_module(namespace, field) end quote do (unquote_splicing(ast)) end end defp define_oneof_instance_module(namespace, %Protobuf.OneOfField{name: field, fields: fields}) do module_subname = field |> Atom.to_string() |> Macro.camelize() |> String.to_atom() fields = Enum.map(fields, &define_oneof_instance_macro/1) quote do defmodule unquote(Module.concat([namespace, :OneOf, module_subname])) do (unquote_splicing(fields)) end end end defp define_oneof_instance_macro(%Protobuf.Field{name: name}) do quote do defmacro unquote(name)(ast) do inner_name = unquote(name) quote do {unquote(inner_name), unquote(ast)} end end end end defp define_field_typespec(type) do case type do {:msg, field_module} -> quote do unquote(field_module).t() end {:enum, field_module} -> quote do unquote(field_module).t() end {:map, key_type, value_type} -> key_type_ast = define_field_typespec(key_type) value_type_ast = define_field_typespec(value_type) quote do [{unquote(key_type_ast), unquote(value_type_ast)}] end _ -> define_scalar_typespec(type) end end defp define_scalar_typespec(type) do case type do :double -> quote do float() end :float -> quote do float() end :int32 -> quote do integer() end :int64 -> quote do integer() end :uint32 -> quote do non_neg_integer() end :uint64 -> quote do non_neg_integer() end :sint32 -> quote do integer() end :sint64 -> quote do integer() end :fixed32 -> quote do non_neg_integer() end :fixed64 -> quote do non_neg_integer() end :sfixed32 -> quote do integer() end :sfixed64 -> quote do integer() end :bool -> quote do boolean() end :string -> quote do String.t() end :bytes -> quote do binary() end end end defp encode_decode(_name) do quote do def decode(data), do: Decoder.decode(data, __MODULE__) def encode(%{} = record), do: Encoder.encode(record, defs()) def decode_delimited(bytes), do: Delimited.decode(bytes, __MODULE__) def encode_delimited(messages), do: Delimited.encode(messages) end end defp fields_methods(fields) do for %Field{name: name, rnum: rnum} = field <- fields do quote location: :keep do def defs(:field, unquote(rnum)), do: unquote(Macro.escape(field)) def defs(:field, unquote(name)), do: defs(:field, unquote(rnum)) end end end defp oneof_fields_methods(fields) do for %OneOfField{name: name, rnum: rnum} = field <- fields do quote location: :keep do def defs(:field, unquote(rnum)), do: unquote(Macro.escape(field)) def defs(:field, unquote(name)), do: defs(:field, unquote(rnum)) end end end defp meta_information do quote do def defs, do: @root.defs def defs(:field, _), do: nil def defs(:field, field, _), do: defs(:field, field) defoverridable defs: 0 end end defp record_fields(fields) do fields |> Enum.map(fn field -> case field do %Field{name: name, occurrence: :repeated} -> {name, []} %Field{name: name, opts: [default: default]} -> {name, default} %Field{name: name} -> {name, nil} %OneOfField{name: name} -> {name, nil} _ -> nil end end) |> Enum.reject(&is_nil/1) end end
24.091837
100
0.58058
03687b54ef94bd71a18694a7aa609670a0224c82
1,900
exs
Elixir
test/plug_ribbon_test.exs
stnly/plug_ribbon
54f15042f93e1d6328b447f3828e6f097ce2dec9
[ "MIT" ]
25
2015-06-24T11:13:22.000Z
2021-06-07T17:58:51.000Z
test/plug_ribbon_test.exs
stnly/plug_ribbon
54f15042f93e1d6328b447f3828e6f097ce2dec9
[ "MIT" ]
1
2015-06-24T12:49:07.000Z
2015-06-25T00:11:07.000Z
test/plug_ribbon_test.exs
stnly/plug_ribbon
54f15042f93e1d6328b447f3828e6f097ce2dec9
[ "MIT" ]
3
2015-06-24T12:37:59.000Z
2018-01-08T12:10:29.000Z
defmodule PlugRibbonTest do use ExUnit.Case, async: true use Plug.Test setup do Logger.disable(self()) :ok end @ribbon_string ~s(<div class="plug-ribbon">) test "injects ribbon in dev environment" do Mix.env(:dev) conn = conn(:get, "/") |> put_resp_content_type("text/html") |> resp(200, "<html><body><h1>Phoenix</h1></body></html>") |> Plug.Ribbon.call([:dev, :test]) |> send_resp() assert conn.status == 200 assert to_string(conn.resp_body) =~ @ribbon_string end test "injects ribbon in test environment" do Mix.env(:test) conn = conn(:get, "/") |> put_resp_content_type("text/html") |> resp(200, "<html><body><h1>Phoenix</h1></body></html>") |> Plug.Ribbon.call([:dev, :test]) |> send_resp() assert conn.status == 200 assert to_string(conn.resp_body) =~ @ribbon_string end test "does not inject ribbon in prod environment" do Mix.env(:prod) conn = conn(:get, "/") |> put_resp_content_type("text/html") |> resp(200, "<html><body><h1>Phoenix</h1></body></html>") |> Plug.Ribbon.call([:dev, :test]) |> send_resp() assert conn.status == 200 refute to_string(conn.resp_body) =~ @ribbon_string end test "does not inject ribbon if html response missing body tag" do Mix.env(:dev) conn = conn(:get, "/") |> put_resp_content_type("text/html") |> resp(200, "<h1>Phoenix</h1>") |> Plug.Ribbon.call([:dev, :test]) |> send_resp() assert conn.status == 200 refute to_string(conn.resp_body) =~ @ribbon_string end test "does not inject ribbon if response is json" do Mix.env(:dev) conn = conn(:get, "/") |> put_resp_content_type("application/json") |> resp(200, "{}") |> Plug.Ribbon.call([:dev, :test]) |> send_resp() assert conn.status == 200 refute to_string(conn.resp_body) =~ @ribbon_string end end
26.388889
68
0.618421
03687ced8cbe7e04fea733eb98ef6d08162e8038
4,617
ex
Elixir
lib/iex/lib/iex/broker.ex
DmitryKakurin/elixir
a5df6a5a830d4cff8b7c8da54342b66cab999e0f
[ "Apache-2.0" ]
1
2019-10-11T01:36:26.000Z
2019-10-11T01:36:26.000Z
lib/iex/lib/iex/broker.ex
DmitryKakurin/elixir
a5df6a5a830d4cff8b7c8da54342b66cab999e0f
[ "Apache-2.0" ]
1
2015-06-09T15:52:43.000Z
2015-06-09T15:52:43.000Z
lib/iex/lib/iex/broker.ex
DmitryKakurin/elixir
a5df6a5a830d4cff8b7c8da54342b66cab999e0f
[ "Apache-2.0" ]
1
2018-01-09T20:10:59.000Z
2018-01-09T20:10:59.000Z
defmodule IEx.Broker do @moduledoc false @name IEx.Broker @type take_ref :: {takeover_ref :: reference(), server_ref :: reference()} use GenServer ## Shell API @doc """ Finds the IEx server running inside `:user_drv`, on this node exclusively. """ @spec shell :: pid | nil def shell() do # Locate top group leader when using the "new shell". if user = Process.whereis(:user) do case :group.interfaces(user) do # Old or no shell [] -> nil # Get current group from user_drv [user_drv: user_drv] -> case :user_drv.interfaces(user_drv) do [] -> nil [current_group: group] -> :group.interfaces(group)[:shell] end end end end @doc """ Finds the evaluator and server running inside `:user_drv`, on this node exclusively. """ @spec evaluator :: {evaluator :: pid, server :: pid} | nil def evaluator() do if pid = shell() do {:dictionary, dictionary} = Process.info(pid, :dictionary) {dictionary[:evaluator], pid} end end ## Broker API def start_link(_) do GenServer.start_link(__MODULE__, :ok, name: @name) end @doc """ Registers an IEx server in the broker. All instances, except shell ones, are registered. """ @spec register(pid) :: :ok def register(pid) do GenServer.call(@name, {:register, pid}) end @doc """ Client responds to a takeover request. The broker's PID is needed to support remote shells. """ @spec respond(pid, take_ref, boolean()) :: :ok | {:error, :refused | :already_accepted} def respond(broker_pid, take_ref, true) do GenServer.call(broker_pid, {:accept, take_ref, Process.group_leader()}) end def respond(broker_pid, take_ref, false) do GenServer.call(broker_pid, {:refuse, take_ref}) end @doc """ Client requests a takeover. """ @spec take_over(binary, keyword) :: {:ok, server :: pid, group_leader :: pid} | {:error, :no_iex | :refused} def take_over(identifier, opts) do case GenServer.whereis(@name) do nil -> {:error, :no_iex} _pid -> GenServer.call(@name, {:take_over, identifier, opts}, :infinity) end end ## Callbacks @impl true def init(:ok) do state = %{ servers: %{}, takeovers: %{} } {:ok, state} end @impl true def handle_call({:take_over, identifier, opts}, {_, ref} = from, state) do case servers(state) do [] -> {:reply, {:error, :no_iex}, state} servers -> server_refs = for {server_ref, server_pid} <- servers do send(server_pid, {:take_over, self(), {ref, server_ref}, identifier, opts}) server_ref end state = put_in(state.takeovers[ref], {from, server_refs}) {:noreply, state} end end def handle_call({:register, pid}, _from, state) do ref = Process.monitor(pid) state = put_in(state.servers[ref], pid) {:reply, :ok, state} end def handle_call({:accept, {ref, _server_ref}, group_leader}, {server, _}, state) do case pop_in(state.takeovers[ref]) do {nil, state} -> {:reply, {:error, :already_accepted}, state} {{from, _}, state} -> GenServer.reply(from, {:ok, server, group_leader}) {:reply, :ok, state} end end def handle_call({:refuse, {ref, server_ref}}, _from, state) do if takeover = state.takeovers[ref] do {:reply, {:error, :refused}, refuse(state, ref, takeover, server_ref)} else {:reply, {:error, :refused}, state} end end @impl true def handle_info({:DOWN, server_ref, _, _, _}, state) do {_pid, state} = pop_in(state.servers[server_ref]) state = Enum.reduce(state.takeovers, state, fn {ref, takeover}, state -> refuse(state, ref, takeover, server_ref) end) {:noreply, state} end defp refuse(state, ref, {from, server_refs}, server_ref) do case List.delete(server_refs, server_ref) do [] -> {_, state} = pop_in(state.takeovers[ref]) GenServer.reply(from, {:error, :refused}) state server_refs -> put_in(state.takeovers[ref], {from, server_refs}) end end defp servers(state) do if pid = local_or_remote_shell() do [{Process.monitor(pid), pid} | Enum.to_list(state.servers)] else Enum.to_list(state.servers) end end defp local_or_remote_shell() do Enum.find_value([node() | Node.list()], fn node -> server = :rpc.call(node, IEx.Broker, :shell, []) if is_pid(server), do: server end) end end
25.229508
89
0.605805
0368bf76f5b3776142f0d5ca4e1491f50857a88a
1,704
exs
Elixir
apps/definition_dictionary/test/dictionary/type/boolean_test.exs
NathanielScottStevens/hindsight
0dda1a931cff85b62eb53d623cc59cdb970ec33a
[ "Apache-2.0" ]
null
null
null
apps/definition_dictionary/test/dictionary/type/boolean_test.exs
NathanielScottStevens/hindsight
0dda1a931cff85b62eb53d623cc59cdb970ec33a
[ "Apache-2.0" ]
null
null
null
apps/definition_dictionary/test/dictionary/type/boolean_test.exs
NathanielScottStevens/hindsight
0dda1a931cff85b62eb53d623cc59cdb970ec33a
[ "Apache-2.0" ]
null
null
null
defmodule Dictionary.Type.BooleanTest do use ExUnit.Case import Checkov describe "new/1" do data_test "validates #{inspect(field)} against bad input" do assert {:error, [%{input: value, path: [field]} | _]} = put_in(%{}, [field], value) |> Dictionary.Type.Boolean.new() where [ [:field, :value], [:version, "1"], [:name, ""], [:name, nil], [:description, nil] ] end end test "can be encoded to json" do expected = %{ "version" => 1, "name" => "name", "description" => "do or do not", "type" => "boolean" } assert expected == Jason.encode!(%Dictionary.Type.Boolean{name: "name", description: "do or do not"}) |> Jason.decode!() end test "can be decoded back into struct" do boolean = Dictionary.Type.Boolean.new!(name: "name", description: "do or do not") json = Jason.encode!(boolean) assert {:ok, boolean} == Jason.decode!(json) |> Dictionary.Type.Boolean.new() end test "brook can serialize and deserialize" do boolean = Dictionary.Type.Boolean.new!(name: "name", description: "do or do not") assert {:ok, boolean} == Brook.Serializer.serialize(boolean) |> elem(1) |> Brook.Deserializer.deserialize() end data_test "validates booleans -- #{inspect(value)} --> #{inspect(result)}" do assert result == Dictionary.Type.Normalizer.normalize(%Dictionary.Type.Boolean{}, value) where [ [:value, :result], [true, {:ok, true}], ["false", {:ok, false}], ["sure", {:error, :invalid_boolean}], [nil, {:ok, nil}], ["", {:ok, nil}] ] end end
27.934426
95
0.568075
0368d29a4ac01722438e74d7b610dde52ee193c8
347
ex
Elixir
lib/supabase_surface/components/icons/icon_refresh_cw.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
5
2021-06-08T08:02:43.000Z
2022-02-09T23:13:46.000Z
lib/supabase_surface/components/icons/icon_refresh_cw.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
null
null
null
lib/supabase_surface/components/icons/icon_refresh_cw.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
1
2021-07-14T05:20:31.000Z
2021-07-14T05:20:31.000Z
defmodule SupabaseSurface.Components.Icons.IconRefreshCw do use SupabaseSurface.Components.Icon @impl true def render(assigns) do icon_size = IconContainer.get_size(assigns.size) ~F""" <IconContainer assigns={assigns}> {Feathericons.refresh_cw(width: icon_size, height: icon_size)} </IconContainer> """ end end
23.133333
68
0.723343
036903acb28651ff29bd604e2d0d10b2d94d2f36
1,827
ex
Elixir
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/update_device_metadata_in_batch_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/update_device_metadata_in_batch_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/update_device_metadata_in_batch_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateDeviceMetadataInBatchRequest do @moduledoc """ Request to update device metadata in batch. ## Attributes * `updates` (*type:* `list(GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateMetadataArguments.t)`, *default:* `nil`) - Required. The list of metadata updates. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :updates => list(GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateMetadataArguments.t()) | nil } field(:updates, as: GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateMetadataArguments, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateDeviceMetadataInBatchRequest do def decode(value, options) do GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateDeviceMetadataInBatchRequest.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.UpdateDeviceMetadataInBatchRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.625
164
0.755884
03691fa36666561c6c8cb32000e4039ce159b059
1,797
ex
Elixir
lib/rostrum2_web/controllers/user_reset_password_controller.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
null
null
null
lib/rostrum2_web/controllers/user_reset_password_controller.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
3
2021-11-25T05:44:03.000Z
2021-11-26T06:33:53.000Z
lib/rostrum2_web/controllers/user_reset_password_controller.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
null
null
null
defmodule RostrumWeb.UserResetPasswordController do use RostrumWeb, :controller alias Rostrum.Accounts plug :get_user_by_reset_password_token when action in [:edit, :update] def new(conn, _params) do render(conn, "new.html") end def create(conn, %{"user" => %{"email" => email}}) do if user = Accounts.get_user_by_email(email) do Accounts.deliver_user_reset_password_instructions( user, &Routes.user_reset_password_url(conn, :edit, &1) ) end # In order to prevent user enumeration attacks, regardless of the outcome, show an impartial success/error message. conn |> put_flash( :info, "If your email is in our system, you will receive instructions to reset your password shortly." ) |> redirect(to: "/") end def edit(conn, _params) do render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user)) end # Do not log in the user after reset password to avoid a # leaked token giving the user access to the account. def update(conn, %{"user" => user_params}) do case Accounts.reset_user_password(conn.assigns.user, user_params) do {:ok, _} -> conn |> put_flash(:info, "Password reset successfully.") |> redirect(to: Routes.user_session_path(conn, :new)) {:error, changeset} -> render(conn, "edit.html", changeset: changeset) end end defp get_user_by_reset_password_token(conn, _opts) do %{"token" => token} = conn.params if user = Accounts.get_user_by_reset_password_token(token) do conn |> assign(:user, user) |> assign(:token, token) else conn |> put_flash(:error, "Reset password link is invalid or it has expired.") |> redirect(to: "/") |> halt() end end end
29.95
119
0.664997
036931dd7b80eac67021ffc34375b3bd6224a03f
10,749
ex
Elixir
lib/webrtc_server/peer.ex
KalvadTech/webrtc-server
a9fbf41f83a644702946541342411f19e2806447
[ "Apache-2.0" ]
1
2021-07-12T12:30:38.000Z
2021-07-12T12:30:38.000Z
lib/webrtc_server/peer.ex
KalvadTech/webrtc-server
a9fbf41f83a644702946541342411f19e2806447
[ "Apache-2.0" ]
null
null
null
lib/webrtc_server/peer.ex
KalvadTech/webrtc-server
a9fbf41f83a644702946541342411f19e2806447
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.WebRTC.Server.Peer do @moduledoc """ Module that manages websocket lifecycle and communication with client. Adapts the [`:cowboy_websocket`](https://ninenines.eu/docs/en/cowboy/2.6/manual/cowboy_websocket/) behaviour. """ @behaviour :cowboy_websocket require Logger alias __MODULE__.{AuthData, Context, Options, State} alias Membrane.WebRTC.Server.{Message, Room} @timeout 15 * 60 * 1000 @typedoc """ Defines unique indetifier (UUIDv4) bound to peer. """ @type peer_id :: String.t() @typedoc """ Defines custom state of a peer, passed as argument and returned by callbacks. """ @type internal_state :: any() @doc """ Callback invoked to extract credentials and metadata from request. After successfully parsing the request, `{:ok, credentials, metadata, room_name}` should be returned. Credentials and metadata will be used to create `Membrane.WebRTC.Server.Peer.AuthData` which is passed to `c:on_init/3` and `c:Membrane.WebRTC.Server.Room.on_join/2`. Returning `{:error, details}` will abort initialization of WebSocket and return a response with status 400. Peer will later try to join the room registered under `room_name`. If no such room can be found, peer will abort initialization of WebSocket and return a response with status 404. """ @callback parse_request(request :: :cowboy_req.req()) :: {:ok, credentials :: map(), metadata :: any(), room_name :: String.t()} | {:error, cause :: any()} @doc """ Callback invoked when a peer process is started. Useful both for confirming the identity of the client, as well as setting up state and/or custom [Cowboy WebSocket](https://ninenines.eu/docs/en/cowboy/2.6/manual/cowboy_websocket/) options, like timeout or maximal frame size. Options argument is value given under the `:custom_options` field in `Membrane.WebRTC.Server.Options`. Returning `{:ok, websocket_options, state}` will set up WebSocket options to the ones returned. Returning `{:ok, state}` will set up default WebSocket options with #{div(@timeout, 60000)} minutes timeout. Returning `{:error, details}` will abort initialization of WebSocket and return a response with status 401. """ @callback on_init( context :: Context.t(), auth_data :: AuthData.t(), options :: any() ) :: {:ok, state :: internal_state} | {:ok, websocket_options :: :cowboy_websocket.opts(), state :: internal_state} | {:error, cause :: any()} @doc """ Callback invoked after successful decoding received JSON message. Peer will proceed to send message returned by this callback to room, ergo returning `{:ok, state}` will cause ignoring message. Useful for modifying or ignoring messages. """ @callback on_receive(message :: Message.t(), context :: Context.t(), state :: internal_state) :: {:ok, message :: Message.t(), state :: internal_state} | {:ok, state :: internal_state} @doc """ Callback invoked when a peer is shutting down. Useful for any cleanup required. """ @callback on_terminate( context :: Context.t(), state :: internal_state ) :: :ok @optional_callbacks on_init: 3, on_receive: 3, on_terminate: 2 @doc """ Encodes message into JSON and sends it to client. """ @spec send_to_client(peer :: pid(), message :: Message.t()) :: :ok def send_to_client(peer, message) do encoded = Jason.encode!(message) send(peer, {:message, encoded}) :ok end @doc """ Stops peer process. """ @spec stop(peer :: pid()) :: :ok def stop(peer) do send(peer, :stop) :ok end @impl true def init(request, %Options{} = options) do peer_id = UUID.uuid4() with {:ok, auth_data, room_name} <- callback_exec(:parse_request, [request], options, peer_id), {:ok, room} <- get_room_pid(room_name, options.registry), {:ok, websocket_options, internal_state} <- callback_exec( :on_init, [%Context{peer_id: peer_id, room: room}, auth_data], options ) do state = %State{ module: options.module, room: room, peer_id: peer_id, internal_state: internal_state, auth_data: auth_data, metadata: auth_data.metadata } {:cowboy_websocket, request, state, websocket_options} else {:error, {:could_not_parse, details}} -> Logger.error("Could not parse auth request, details: #{inspect(details)}") reply = :cowboy_req.reply(400, request) {:ok, reply, %{}} {:error, {:no_such_room, room}} -> Logger.error("Could not find room named #{room}") reply = :cowboy_req.reply(404, request) {:ok, reply, %{}} {:error, {:init_failed, details}} -> Logger.error("Authentication error, details: #{inspect(details)}") reply = :cowboy_req.reply(401, request) {:ok, reply, %{}} end end @impl true def websocket_init(%State{} = state) do case join_room(state) do :ok -> state = %State{state | auth_data: :already_authorised} message = %Message{ event: "authenticated", data: %{peer_id: state.peer_id}, to: [state.peer_id] } send_to_client(self(), message) {:ok, state} {:error, {error, details}} -> error_log = to_string(error) |> String.replace("_", " ") |> String.capitalize() Logger.error("#{error_log}, details: #{inspect(details)}") stop_and_send_error(self(), error_log, details, state) {:ok, state} end end @impl true def websocket_handle({:text, "ping"}, state) do {:reply, {:text, "pong"}, state} end @impl true def websocket_handle(:ping, state), do: {:reply, :pong, state} @impl true def websocket_handle({:ping, data}, state), do: {:reply, {:pong, data}, state} @impl true def websocket_handle({:text, message}, state), do: message |> Jason.decode() |> handle_message(state) @impl true def websocket_handle(_frame, state) do Logger.warn("Non-text frame") {:ok, state} end @impl true def websocket_info({:message, message}, state) do {:reply, {:text, message}, state} end @impl true def websocket_info(:stop, state) do {:stop, state} end @impl true def websocket_info({:DOWN, _ref, :process, room, reason}, %State{room: room} = state) do stop_and_send_error(self(), "Room closed", reason, state) {:ok, state} end @impl true def websocket_info(_message, state) do {:ok, state} end @impl true def terminate(_reason, _req, %State{} = state) do callback_exec(:on_terminate, [], state) end @impl true def terminate(_reason, _req, _options), do: :ok defp callback_exec(:parse_request, args, options, peer_id) do case apply_callback(:parse_request, args, options) do {:ok, credentials, metadata, room} -> auth_data = %AuthData{ credentials: credentials, metadata: metadata, peer_id: peer_id } {:ok, auth_data, room} {:error, details} -> {:error, {:could_not_parse, details}} end end defp callback_exec(:on_init, args, options) do case apply_callback(:on_init, args, options) do {:ok, internal_state} -> websocket_options = %{idle_timeout: @timeout} {:ok, websocket_options, internal_state} {:ok, websocket_options, internal_state} -> {:ok, websocket_options, internal_state} {:error, details} -> {:error, {:init_failed, details}} end end defp callback_exec(:on_receive, [message], state) do case apply_callback(:on_receive, [message], state) do {:ok, internal_state} -> {:ok, %State{state | internal_state: internal_state}} {:ok, %Message{} = message, internal_state} -> Room.forward_message(state.room, message) {:ok, %State{state | internal_state: internal_state}} end end defp callback_exec(:on_terminate, args, state) do apply_callback(:on_terminate, args, state) end defp apply_callback(:on_init, args, options) do args = args ++ [options.custom_options] apply(options.module, :on_init, args) end defp apply_callback(:parse_request, args, options) do apply(options.module, :parse_request, args) end defp apply_callback(callback, args, state) do args = args ++ [%Context{peer_id: state.peer_id, room: state.room}, state.internal_state] apply(state.module, callback, args) end defp join_room(state) do case GenServer.call(state.room, {:join, state.auth_data, self()}) do :ok -> Process.monitor(state.room) :ok {:error, error} -> {:error, {:could_not_join_room, error}} end end defp stop_and_send_error(peer, error, details, state) do message = %Message{ event: "error", data: %{description: error, details: details}, to: [state.peer_id] } send_to_client(peer, message) stop(peer) end defp handle_message( {:ok, %{"event" => _event} = message}, state ) do message = %Message{ data: message["data"], event: message["event"], from: state.peer_id, from_metadata: state.metadata, to: message["to"] } callback_exec(:on_receive, [message], state) end defp handle_message({:ok, _message}, state) do send_to_client(self(), %Message{ event: "error", data: %{desciption: "Invalid message"}, to: [state.peer_id] }) {:ok, state} end defp handle_message({:error, jason_error}, state) do Logger.warn("Wrong message") send_to_client(self(), %Message{ event: "error", data: %{description: "Invalid JSON", details: jason_error.data} }) {:ok, state} end defp get_room_pid(room, registry) do case Registry.lookup(registry, room) do [{room_pid, _value}] when is_pid(room_pid) -> {:ok, room_pid} [] -> {:error, {:no_such_room, room}} end end defmacro __using__(_) do quote location: :keep do @behaviour unquote(__MODULE__) @impl true def on_init(_context, _auth_data, options) do {:ok, options} end @impl true def on_receive(message, _context, state), do: {:ok, message, state} @impl true def on_terminate(_context, _state), do: :ok defoverridable on_init: 3, on_receive: 3, on_terminate: 2 end end end
27.992188
98
0.6235
03693781ac307b2028c21518b7547f1c5a9a4c3c
2,808
exs
Elixir
test/dogma/rule/function_parentheses_test.exs
lpil/dogma
e0f55c27ec3053be0313ac93f3d036437ee590a1
[ "MIT" ]
558
2015-06-21T18:20:59.000Z
2021-12-30T16:25:47.000Z
test/dogma/rule/function_parentheses_test.exs
lpil/dogma
e0f55c27ec3053be0313ac93f3d036437ee590a1
[ "MIT" ]
252
2015-06-19T13:00:47.000Z
2021-04-21T08:04:16.000Z
test/dogma/rule/function_parentheses_test.exs
lpil/dogma
e0f55c27ec3053be0313ac93f3d036437ee590a1
[ "MIT" ]
79
2015-06-21T14:18:30.000Z
2021-12-30T16:26:09.000Z
defmodule Dogma.Rule.FunctionParenthesesTest do use RuleCase, for: FunctionParentheses test "not error without parentheses and without argument" do script = """ def foo do end def foo_bar do end defp private_foo do end def baz, do: :baz """ |> Script.parse!("") assert [] == Rule.test( @rule, script ) end test "not error with parentheses and arguments" do script = """ def foo(a) do end def foo_bar(a, b, c) do end defp private_foo(x, y) do end def baz(z), do: z """ |> Script.parse!("") assert [] == Rule.test( @rule, script ) end test "error with public function with parentheses and without arguments" do script = """ def foo() do end """ |> Script.parse!("") expected_errors = [ %Error{ rule: FunctionParentheses, message: "Functions declarations should have parentheses if and " <> "only if they have arguments", line: 1 } ] assert expected_errors == Rule.test( @rule, script ) end test "error with private function with parentheses and without arguments" do script = """ defp foo() do end """ |> Script.parse!("") expected_errors = [ %Error{ rule: FunctionParentheses, message: "Functions declarations should have parentheses if and " <> "only if they have arguments", line: 1 } ] assert expected_errors == Rule.test( @rule, script ) end test "error with single-line function parentheses and without arguments" do script = """ def foo(), do: :bar """ |> Script.parse!("") expected_errors = [ %Error{ rule: FunctionParentheses, message: "Functions declarations should have parentheses if and " <> "only if they have arguments", line: 1 } ] assert expected_errors == Rule.test( @rule, script ) end test "error with public function without parentheses and with arguments" do script = """ def foo a, b do end """ |> Script.parse!("") expected_errors = [ %Error{ rule: FunctionParentheses, message: "Functions declarations should have parentheses if and " <> "only if they have arguments", line: 1 } ] assert expected_errors == Rule.test( @rule, script ) end test "error with private function without parentheses and with arguments" do script = """ defp foo a, b do end """ |> Script.parse!("") expected_errors = [ %Error{ rule: FunctionParentheses, message: "Functions declarations should have parentheses if and " <> "only if they have arguments", line: 1 } ] assert expected_errors == Rule.test( @rule, script ) end end
25.761468
78
0.59651
03694590107fbf3fd0aa6e617183109f13b58038
535
exs
Elixir
test/shenu/message/category_test.exs
jsdelivrbot/shenu
98acf65b915b62528eccd824020e8007931ee01c
[ "MIT" ]
3
2016-06-19T00:21:54.000Z
2021-09-28T22:04:07.000Z
test/shenu/message/category_test.exs
jsdelivrbot/shenu
98acf65b915b62528eccd824020e8007931ee01c
[ "MIT" ]
null
null
null
test/shenu/message/category_test.exs
jsdelivrbot/shenu
98acf65b915b62528eccd824020e8007931ee01c
[ "MIT" ]
1
2018-12-06T22:51:26.000Z
2018-12-06T22:51:26.000Z
defmodule Test.Shenu.Message.Category do use Test.Shenu.Message.Case test "default schema" do create_parser() |> parse("123") |> assert_message(%Category{value: "123"}) end test "default schema error" do create_parser() |> parse(1) |> assert_error() end test "enum schema" do create_parser(["1", "2", "3"]) |> parse("1") |> assert_message(%Category{value: "1"}) end test "enum schema error" do create_parser(["1", "2", "3"]) |> parse("4") |> assert_error() end end
19.107143
46
0.596262
03695c218411c3e62d33c54c73b1e8b8e068110e
799
ex
Elixir
lib/mollie/permissions.ex
LostKobrakai/mollie
dd697dfcf376eb1889d6371cc1179a335ef70b59
[ "MIT" ]
null
null
null
lib/mollie/permissions.ex
LostKobrakai/mollie
dd697dfcf376eb1889d6371cc1179a335ef70b59
[ "MIT" ]
null
null
null
lib/mollie/permissions.ex
LostKobrakai/mollie
dd697dfcf376eb1889d6371cc1179a335ef70b59
[ "MIT" ]
null
null
null
defmodule Mollie.Permissions do import Mollie alias Mollie.Client @doc """ List all permissions available with the current app access token. The list is not paginated. ## Example Mollie.Permissions.list client More info at: https://docs.mollie.com/reference/v2/permissions-api/list-permissions """ @spec list(Client.t()) :: Mollie.response() def list(client) do get("v2/permissions", client) end @doc """ Check if API action is still allowed with current authorization. ## Example Mollie.Permissions.find client, "payments.read" More info at: https://docs.mollie.com/reference/v2/permissions-api/get-permission """ @spec find(Client.t(), binary) :: Mollie.response() def find(client, id) do get("v2/permissions/#{id}", client) end end
24.212121
94
0.698373
036996af4933f442afc7c1fee2723c05d143445d
2,302
exs
Elixir
test/wechat_pay/plug/refund_test.exs
sjava/wechat_pay
101fd27668f01463d93c1a50033787cfb19bf3e5
[ "MIT" ]
null
null
null
test/wechat_pay/plug/refund_test.exs
sjava/wechat_pay
101fd27668f01463d93c1a50033787cfb19bf3e5
[ "MIT" ]
null
null
null
test/wechat_pay/plug/refund_test.exs
sjava/wechat_pay
101fd27668f01463d93c1a50033787cfb19bf3e5
[ "MIT" ]
null
null
null
defmodule WechatPay.Plug.RefundTest do use TestCase, async: false use Plug.Test alias MyPay.Plug.Refund, as: RefundPlug alias WechatPay.PlugTest.Handler defmodule Handler do use WechatPay.Handler @impl WechatPay.Handler def handle_data(_conn, data) do assert data.out_trade_no == "99999999999999999999999999999999" assert data.refund_status == "SUCCESS" :ok end @impl WechatPay.Handler def handle_error(_conn, error, data) do assert error == %WechatPay.Error{reason: "Malformed decrypted XML", type: :malformed_decrypted_xml} assert data.return_code == "FAIL" end end describe "receive notification from Wechat's Payment Gateway" do test "handle success refunding" do req = ~s""" <xml> <return_code>SUCCESS</return_code> <appid><![CDATA[wx2421b1c4370ec43b]]></appid> <mch_id><![CDATA[10000100]]></mch_id> <nonce_str><![CDATA[TeqClE3i0mvn3DrK]]></nonce_str> <req_info><![CDATA[4gS8kbcHysCW7bHqyEU0M4GTNkgJQP6/zKHbA/E3CvyZ1kyFxob5yLZ/MVNzuc8py3P9bZ/5q+YzfeCs3am4Fo/VN6EyCK9c1oSZIPajwNrIWt36UG9lhdGdYOi14ywDO+I0SWiENSkQgeWL8pB3YX1szHW8UA0nmExbrM7u1coa91uRG/rIpW4D72i3wR5to4kdZtN8E+omK6fkLxN+NkPSS3u2xvdRBans3+SZSRsGo/RlgDPSZRN8Oxyv8YDEQpnX7V42+wB2CTgWf4yAz2Nm6JFS+jUdfLWcHiwFOIAOKEvcACtqxboYmq/H5iiutISroTbDe2FgSOX9aUi8S6XqRsy0GinJWFNSK6KgJz1yFXMpjXLpcvNte2cIbsASEAW19ZEwpaYpiUvoORsbiXWksn0uzlJ0OFHQodqiS9lpoJBvJtrJ4jFajRtg9oiXdr9jpDJcXt2CDNGPgLYiAv55JpoM4nYOFfq5ZPpd+T1nuXNYkq3cldx+aDO8Pq3InAFmOYfMG/tg/CwivVFgPcBJye5c1l1Y41KJa1Wgpp4R6g1BBn1acfteCDdWTfNmkd+JXXXeW/g4CWpy2XpJjN2q5EGN6yPIwbte84KNgbAGoMkjls51B5uKGXtsscr9us7jBkMXlLCQ63swgU1RqVp2t3LTJB5+hbctiaZSYXfGL9XlJcEPqz8s4jTsg6X4Kg7+WNeTEg2BT1tBYOnQkTv1CsQlH1aRLh7eaYFi1isbY0X/BKFvaXglL4gqPf1+mWKfZZjxYFlSfmH+VnCau0s96ey3pTIhzp2YQtUkAm/f5vU3kPgAVi2C7HJ1/s958Iipdzi6ho4MzyZQQNkPlYNbPqmCs2mMCwn+7uNhqD37bWtRGyiQYc6tuPVLmkXfTxulIqCx9G9HdZ0qntkJfcKnZ1EwEQkw2YUu8VPCVCPAxxRqC8TFpqu3gKxheAMSTFVmxmICZXt4Gk746+vMdUrDJlkPnOkhHrRN06wnbiM+foR8ID/ZrIv/PdUCAXXw/B9aB9zNXVv0WZGleNFNA6qONbk/Ne95To6JzOLv2AtnYqMCnSIxGKe/ra5bDIokZSjdwZhoVNVwBb78Z6z3Ag==]]></req_info> </xml> """ conn = conn(:post, "/foo", req) opts = RefundPlug.init([handler: Handler]) RefundPlug.call(conn, opts) end end end
47.958333
1,153
0.804952
0369bc6bd2e077587c0b6c90f7420d2481bfb132
27,170
ex
Elixir
lib/aws/generated/app_config.ex
kw7oe/aws-elixir
4ba60502dde270c83143822c9964018c7770bad7
[ "Apache-2.0" ]
341
2018-04-04T19:06:19.000Z
2022-03-25T21:34:23.000Z
lib/aws/generated/app_config.ex
kw7oe/aws-elixir
4ba60502dde270c83143822c9964018c7770bad7
[ "Apache-2.0" ]
82
2018-04-04T17:32:33.000Z
2022-03-24T15:12:04.000Z
lib/aws/generated/app_config.ex
kw7oe/aws-elixir
4ba60502dde270c83143822c9964018c7770bad7
[ "Apache-2.0" ]
76
2018-04-10T20:19:44.000Z
2022-03-15T13:49:19.000Z
# WARNING: DO NOT EDIT, AUTO-GENERATED CODE! # See https://github.com/aws-beam/aws-codegen for more details. defmodule AWS.AppConfig do @moduledoc """ AWS AppConfig Use AWS AppConfig, a capability of AWS Systems Manager, to create, manage, and quickly deploy application configurations. AppConfig supports controlled deployments to applications of any size and includes built-in validation checks and monitoring. You can use AppConfig with applications hosted on Amazon EC2 instances, AWS Lambda, containers, mobile applications, or IoT devices. To prevent errors when deploying application configurations, especially for production systems where a simple typo could cause an unexpected outage, AppConfig includes validators. A validator provides a syntactic or semantic check to ensure that the configuration you want to deploy works as intended. To validate your application configuration data, you provide a schema or a Lambda function that runs against the configuration. The configuration deployment or update can only proceed when the configuration data is valid. During a configuration deployment, AppConfig monitors the application to ensure that the deployment is successful. If the system encounters an error, AppConfig rolls back the change to minimize impact for your application users. You can configure a deployment strategy for each application or environment that includes deployment criteria, including velocity, bake time, and alarms to monitor. Similar to error monitoring, if a deployment triggers an alarm, AppConfig automatically rolls back to the previous version. AppConfig supports multiple use cases. Here are some examples. * **Application tuning**: Use AppConfig to carefully introduce changes to your application that can only be tested with production traffic. * **Feature toggle**: Use AppConfig to turn on new features that require a timely deployment, such as a product launch or announcement. * **Allow list**: Use AppConfig to allow premium subscribers to access paid content. * **Operational issues**: Use AppConfig to reduce stress on your application when a dependency or other external factor impacts the system. This reference is intended to be used with the [AWS AppConfig User Guide](http://docs.aws.amazon.com/systems-manager/latest/userguide/appconfig.html). """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2019-10-09", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "appconfig", global?: false, protocol: "rest-json", service_id: "AppConfig", signature_version: "v4", signing_name: "appconfig", target_prefix: nil } end @doc """ An application in AppConfig is a logical unit of code that provides capabilities for your customers. For example, an application can be a microservice that runs on Amazon EC2 instances, a mobile application installed by your users, a serverless application using Amazon API Gateway and AWS Lambda, or any system you run on behalf of others. """ def create_application(%Client{} = client, input, options \\ []) do url_path = "/applications" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Information that enables AppConfig to access the configuration source. Valid configuration sources include Systems Manager (SSM) documents, SSM Parameter Store parameters, and Amazon S3 objects. A configuration profile includes the following information. * The Uri location of the configuration data. * The AWS Identity and Access Management (IAM) role that provides access to the configuration data. * A validator for the configuration data. Available validators include either a JSON Schema or an AWS Lambda function. For more information, see [Create a Configuration and a Configuration Profile](http://docs.aws.amazon.com/systems-manager/latest/userguide/appconfig-creating-configuration-and-profile.html) in the *AWS AppConfig User Guide*. """ def create_configuration_profile(%Client{} = client, application_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ A deployment strategy defines important criteria for rolling out your configuration to the designated targets. A deployment strategy includes: the overall duration required, a percentage of targets to receive the deployment during each interval, an algorithm that defines how percentage grows, and bake time. """ def create_deployment_strategy(%Client{} = client, input, options \\ []) do url_path = "/deploymentstrategies" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ For each application, you define one or more environments. An environment is a logical deployment group of AppConfig targets, such as applications in a `Beta` or `Production` environment. You can also define environments for application subcomponents such as the `Web`, `Mobile` and `Back-end` components for your application. You can configure Amazon CloudWatch alarms for each environment. The system monitors alarms during a configuration deployment. If an alarm is triggered, the system rolls back the configuration. """ def create_environment(%Client{} = client, application_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Create a new configuration in the AppConfig configuration store. """ def create_hosted_configuration_version( %Client{} = client, application_id, configuration_profile_id, input, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}/hostedconfigurationversions" {headers, input} = [ {"ContentType", "Content-Type"}, {"Description", "Description"}, {"LatestVersionNumber", "Latest-Version-Number"} ] |> Request.build_params(input) query_params = [] options = Keyword.put( options, :response_header_parameters, [ {"Application-Id", "ApplicationId"}, {"Configuration-Profile-Id", "ConfigurationProfileId"}, {"Content-Type", "ContentType"}, {"Description", "Description"}, {"Version-Number", "VersionNumber"} ] ) Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Delete an application. Deleting an application does not delete a configuration from a host. """ def delete_application(%Client{} = client, application_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Delete a configuration profile. Deleting a configuration profile does not delete a configuration from a host. """ def delete_configuration_profile( %Client{} = client, application_id, configuration_profile_id, input, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Delete a deployment strategy. Deleting a deployment strategy does not delete a configuration from a host. """ def delete_deployment_strategy(%Client{} = client, deployment_strategy_id, input, options \\ []) do url_path = "/deployementstrategies/#{AWS.Util.encode_uri(deployment_strategy_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Delete an environment. Deleting an environment does not delete a configuration from a host. """ def delete_environment(%Client{} = client, application_id, environment_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Delete a version of a configuration from the AppConfig configuration store. """ def delete_hosted_configuration_version( %Client{} = client, application_id, configuration_profile_id, version_number, input, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}/hostedconfigurationversions/#{AWS.Util.encode_uri(version_number)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Retrieve information about an application. """ def get_application(%Client{} = client, application_id, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Receive information about a configuration. AWS AppConfig uses the value of the `ClientConfigurationVersion` parameter to identify the configuration version on your clients. If you don’t send `ClientConfigurationVersion` with each call to `GetConfiguration`, your clients receive the current configuration. You are charged each time your clients receive a configuration. To avoid excess charges, we recommend that you include the `ClientConfigurationVersion` value with every call to `GetConfiguration`. This value must be saved on your client. Subsequent calls to `GetConfiguration` must pass this value by using the `ClientConfigurationVersion` parameter. """ def get_configuration( %Client{} = client, application, configuration, environment, client_configuration_version \\ nil, client_id, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application)}/environments/#{AWS.Util.encode_uri(environment)}/configurations/#{AWS.Util.encode_uri(configuration)}" headers = [] query_params = [] query_params = if !is_nil(client_id) do [{"client_id", client_id} | query_params] else query_params end query_params = if !is_nil(client_configuration_version) do [{"client_configuration_version", client_configuration_version} | query_params] else query_params end options = Keyword.put( options, :response_header_parameters, [ {"Configuration-Version", "ConfigurationVersion"}, {"Content-Type", "ContentType"} ] ) Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieve information about a configuration profile. """ def get_configuration_profile( %Client{} = client, application_id, configuration_profile_id, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieve information about a configuration deployment. """ def get_deployment( %Client{} = client, application_id, deployment_number, environment_id, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}/deployments/#{AWS.Util.encode_uri(deployment_number)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieve information about a deployment strategy. A deployment strategy defines important criteria for rolling out your configuration to the designated targets. A deployment strategy includes: the overall duration required, a percentage of targets to receive the deployment during each interval, an algorithm that defines how percentage grows, and bake time. """ def get_deployment_strategy(%Client{} = client, deployment_strategy_id, options \\ []) do url_path = "/deploymentstrategies/#{AWS.Util.encode_uri(deployment_strategy_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieve information about an environment. An environment is a logical deployment group of AppConfig applications, such as applications in a `Production` environment or in an `EU_Region` environment. Each configuration deployment targets an environment. You can enable one or more Amazon CloudWatch alarms for an environment. If an alarm is triggered during a deployment, AppConfig roles back the configuration. """ def get_environment(%Client{} = client, application_id, environment_id, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Get information about a specific configuration version. """ def get_hosted_configuration_version( %Client{} = client, application_id, configuration_profile_id, version_number, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}/hostedconfigurationversions/#{AWS.Util.encode_uri(version_number)}" headers = [] query_params = [] options = Keyword.put( options, :response_header_parameters, [ {"Application-Id", "ApplicationId"}, {"Configuration-Profile-Id", "ConfigurationProfileId"}, {"Content-Type", "ContentType"}, {"Description", "Description"}, {"Version-Number", "VersionNumber"} ] ) Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ List all applications in your AWS account. """ def list_applications(%Client{} = client, max_results \\ nil, next_token \\ nil, options \\ []) do url_path = "/applications" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next_token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max_results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the configuration profiles for an application. """ def list_configuration_profiles( %Client{} = client, application_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next_token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max_results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ List deployment strategies. """ def list_deployment_strategies( %Client{} = client, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/deploymentstrategies" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next_token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max_results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Lists the deployments for an environment. """ def list_deployments( %Client{} = client, application_id, environment_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}/deployments" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next_token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max_results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ List the environments for an application. """ def list_environments( %Client{} = client, application_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next_token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max_results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ View a list of configurations stored in the AppConfig configuration store by version. """ def list_hosted_configuration_versions( %Client{} = client, application_id, configuration_profile_id, max_results \\ nil, next_token \\ nil, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}/hostedconfigurationversions" headers = [] query_params = [] query_params = if !is_nil(next_token) do [{"next_token", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"max_results", max_results} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Retrieves the list of key-value tags assigned to the resource. """ def list_tags_for_resource(%Client{} = client, resource_arn, options \\ []) do url_path = "/tags/#{AWS.Util.encode_uri(resource_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, 200 ) end @doc """ Starts a deployment. """ def start_deployment(%Client{} = client, application_id, environment_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}/deployments" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 201 ) end @doc """ Stops a deployment. This API action works only on deployments that have a status of `DEPLOYING`. This action moves the deployment to a status of `ROLLED_BACK`. """ def stop_deployment( %Client{} = client, application_id, deployment_number, environment_id, input, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}/deployments/#{AWS.Util.encode_uri(deployment_number)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 202 ) end @doc """ Metadata to assign to an AppConfig resource. Tags help organize and categorize your AppConfig resources. Each tag consists of a key and an optional value, both of which you define. You can specify a maximum of 50 tags for a resource. """ def tag_resource(%Client{} = client, resource_arn, input, options \\ []) do url_path = "/tags/#{AWS.Util.encode_uri(resource_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end @doc """ Deletes a tag key and value from an AppConfig resource. """ def untag_resource(%Client{} = client, resource_arn, input, options \\ []) do url_path = "/tags/#{AWS.Util.encode_uri(resource_arn)}" headers = [] {query_params, input} = [ {"TagKeys", "tagKeys"} ] |> Request.build_params(input) Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, 204 ) end @doc """ Updates an application. """ def update_application(%Client{} = client, application_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :patch, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates a configuration profile. """ def update_configuration_profile( %Client{} = client, application_id, configuration_profile_id, input, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :patch, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates a deployment strategy. """ def update_deployment_strategy(%Client{} = client, deployment_strategy_id, input, options \\ []) do url_path = "/deploymentstrategies/#{AWS.Util.encode_uri(deployment_strategy_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :patch, url_path, query_params, headers, input, options, 200 ) end @doc """ Updates an environment. """ def update_environment(%Client{} = client, application_id, environment_id, input, options \\ []) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/environments/#{AWS.Util.encode_uri(environment_id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :patch, url_path, query_params, headers, input, options, 200 ) end @doc """ Uses the validators in a configuration profile to validate a configuration. """ def validate_configuration( %Client{} = client, application_id, configuration_profile_id, input, options \\ [] ) do url_path = "/applications/#{AWS.Util.encode_uri(application_id)}/configurationprofiles/#{AWS.Util.encode_uri(configuration_profile_id)}/validators" headers = [] {query_params, input} = [ {"ConfigurationVersion", "configuration_version"} ] |> Request.build_params(input) Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, 204 ) end end
24.477477
198
0.632389
0369d090b6b3d6f17e1074ba127803fb647fa0b2
298
ex
Elixir
lib/drunkard/protobuf/ingredientArray.pb.ex
shaddysignal/drunkard
8365c75cd98414dfe38481956e90dda26a177bdd
[ "Unlicense" ]
2
2020-07-05T21:27:33.000Z
2021-12-12T22:56:00.000Z
lib/drunkard/protobuf/ingredientArray.pb.ex
shaddysignal/drunkard
8365c75cd98414dfe38481956e90dda26a177bdd
[ "Unlicense" ]
1
2021-05-11T08:14:48.000Z
2021-05-11T08:14:48.000Z
lib/drunkard/protobuf/ingredientArray.pb.ex
shaddysignal/drunkard
8365c75cd98414dfe38481956e90dda26a177bdd
[ "Unlicense" ]
1
2020-07-05T21:27:46.000Z
2020-07-05T21:27:46.000Z
defmodule Drunkard.Protobuf.IngredientArray do @moduledoc false use Protobuf, syntax: :proto3 @type t :: %__MODULE__{ ingredient: [Drunkard.Protobuf.Ingredient.t()] } defstruct [:ingredient] field :ingredient, 1, repeated: true, type: Drunkard.Protobuf.Ingredient end
24.833333
74
0.708054
0369d44e008b03b60b6a848125b79b3e983c9fc0
1,895
exs
Elixir
mix.exs
hassanshaikley/ascii-quest
8b3b3af3b9c6c59b8155fe2e6cb2a794033c29f1
[ "MIT" ]
8
2019-01-15T09:31:05.000Z
2020-04-20T13:59:01.000Z
mix.exs
hassanshaikley/ascii-quest
8b3b3af3b9c6c59b8155fe2e6cb2a794033c29f1
[ "MIT" ]
2
2019-01-06T02:53:44.000Z
2019-05-30T20:30:20.000Z
mix.exs
hassanshaikley/ascii-quest
8b3b3af3b9c6c59b8155fe2e6cb2a794033c29f1
[ "MIT" ]
1
2019-01-04T04:37:21.000Z
2019-01-04T04:37:21.000Z
defmodule StabbyFlies.MixProject do use Mix.Project def project do [ app: :stabby_flies, version: "0.1.0", elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {StabbyFlies.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:credo, "~> 1.0.0", only: [:dev, :test], runtime: false}, {:phoenix, "~> 1.4.0"}, {:phoenix_pubsub, "~> 1.1"}, {:phoenix_ecto, "~> 4.0"}, {:ecto_sql, "~> 3.0"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:puid, "~> 1.0"}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, {:distillery, "~> 1.5", runtime: false}, {:sobelow, "~> 0.7.2"}, {:dialyxir, "~> 1.0.0-rc.6", only: [:dev], runtime: false} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
27.867647
79
0.563588
0369f4937b20ad3e69bf49cc9aaec3109ba85749
2,106
exs
Elixir
test/phoenix_html/format_test.exs
programisti/phoenix_html
082c785f0487098d6099ae254c502c5e7a6187e3
[ "MIT" ]
310
2015-05-03T13:08:41.000Z
2022-03-11T14:53:20.000Z
test/phoenix_html/format_test.exs
programisti/phoenix_html
082c785f0487098d6099ae254c502c5e7a6187e3
[ "MIT" ]
347
2015-05-03T19:01:00.000Z
2022-02-22T11:56:17.000Z
test/phoenix_html/format_test.exs
programisti/phoenix_html
082c785f0487098d6099ae254c502c5e7a6187e3
[ "MIT" ]
268
2015-05-03T18:53:32.000Z
2022-03-22T14:15:54.000Z
defmodule Phoenix.HTML.FormatTest do use ExUnit.Case, async: true import Phoenix.HTML.Format import Phoenix.HTML doctest Phoenix.HTML.Format test "wraps paragraphs" do formatted = format(""" Hello, Please come see me. Regards, The Boss. """) assert formatted == """ <p>Hello,</p> <p>Please come see me.</p> <p>Regards,<br> The Boss.</p> """ end test "wraps paragraphs with carriage returns" do formatted = format("Hello,\r\n\r\nPlease come see me.\r\n\r\nRegards,\r\nThe Boss.") assert formatted == """ <p>Hello,</p> <p>Please come see me.</p> <p>Regards,<br> The Boss.</p> """ end test "escapes html" do formatted = format(""" <script></script> """) assert formatted == """ <p>&lt;script&gt;&lt;/script&gt;</p> """ end test "skips escaping html" do formatted = format( """ <script></script> """, escape: false ) assert formatted == """ <p><script></script></p> """ end test "adds brs" do formatted = format(""" Hello, This is dog, How can I help you? """) assert formatted == """ <p>Hello,<br> This is dog,<br> How can I help you?</p> """ end test "adds brs with carriage return" do formatted = format("Hello,\r\nThis is dog,\r\nHow can I help you?\r\n\r\n\r\n") assert formatted == """ <p>Hello,<br> This is dog,<br> How can I help you?</p> """ end test "doesn't add brs" do formatted = format( """ Hello, This is dog, How can I help you? """, insert_brs: false ) assert formatted == """ <p>Hello, This is dog, How can I help you?</p> """ end defp format(text, opts \\ []) do text |> text_to_html(opts) |> safe_to_string end end
18.637168
88
0.480532
036a4c88d31e0076f220d0baa6661f300eeb010c
1,104
exs
Elixir
priv/repo/seeds.exs
abmBispo/elixir-ecommerce
0507f7621d68ba8f0f65409a1a503683b7c0d37b
[ "MIT" ]
4
2020-05-29T03:33:02.000Z
2021-08-21T23:01:48.000Z
priv/repo/seeds.exs
abmBispo/elixir-ecommerce
0507f7621d68ba8f0f65409a1a503683b7c0d37b
[ "MIT" ]
2
2020-07-29T01:50:46.000Z
2021-08-31T20:10:47.000Z
priv/repo/seeds.exs
abmBispo/elixir-ecommerce
0507f7621d68ba8f0f65409a1a503683b7c0d37b
[ "MIT" ]
1
2022-03-21T18:13:21.000Z
2022-03-21T18:13:21.000Z
# mix run priv/repo/seeds.exs import Ecto.Query ElixirEcommerce.UserManager.create_user(%{ email: "sr.alan.bispo@gmail.com", password: "123456", username: "abmbispo", role: "admin" }) ElixirEcommerce.Department.create(%{ name: "Sports" }) ElixirEcommerce.Department.create(%{ name: "Eletronics" }) ElixirEcommerce.Department.create(%{ name: "Bathroom" }) ElixirEcommerce.Department.create(%{ name: "Games" }) query = from ElixirEcommerce.Department, order_by: fragment("RANDOM()"), limit: 1 Enum.each(0..100, fn(x) -> product_names = [ "NBA shorts", "NBA shirts", "NBA shoes", "Plasma TV", "Led Shower", "GTA V", "PS5", "Xbox one" ] department = ElixirEcommerce.Repo.all(query) |> List.first {:ok, product} = %{ name: "#{Enum.at(product_names, Enum.random(0..7))} - #{x + 1}", description: Faker.Lorem.paragraph(Enum.random(15..50)), amount: Enum.random(0..100), price: Enum.random(1000..25000) } |> Map.put(:department, department) |> ElixirEcommerce.Product.create() product end)
18.4
70
0.631341
036a7113f5b5cf6ed1f6418c288c88b0eaedc4b5
1,684
ex
Elixir
lib/dispatch_web/endpoint.ex
mirego/dispatch
65f81e264e45676ece8a6dc5f203cf9f283d6ec7
[ "BSD-3-Clause" ]
21
2019-02-13T15:26:00.000Z
2021-09-18T13:05:42.000Z
lib/dispatch_web/endpoint.ex
mirego/dispatch
65f81e264e45676ece8a6dc5f203cf9f283d6ec7
[ "BSD-3-Clause" ]
26
2019-02-13T18:42:44.000Z
2021-09-16T15:40:05.000Z
lib/dispatch_web/endpoint.ex
mirego/dispatch
65f81e264e45676ece8a6dc5f203cf9f283d6ec7
[ "BSD-3-Clause" ]
2
2020-05-26T09:09:19.000Z
2021-04-21T20:43:07.000Z
defmodule DispatchWeb.Endpoint do use Phoenix.Endpoint, otp_app: :dispatch plug(:canonical_host) plug(:force_ssl) plug(:basic_auth) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do plug(Phoenix.CodeReloader) end plug(Plug.RequestId) plug(Plug.Logger) plug( Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Jason ) plug(Plug.MethodOverride) plug(Plug.Head) plug(DispatchWeb.Router) @doc """ Callback invoked for dynamically configuring the endpoint. It receives the endpoint configuration and checks if configuration should be loaded from the system environment. """ def init(_key, config) do if config[:load_from_system_env] do port = System.get_env("PORT") || raise "expected the PORT environment variable to be set" {:ok, Keyword.put(config, :http, [:inet6, port: port])} else {:ok, config} end end defp canonical_host(conn, _opts) do opts = PlugCanonicalHost.init(canonical_host: Application.get_env(:dispatch, :canonical_host)) PlugCanonicalHost.call(conn, opts) end defp force_ssl(conn, _opts) do if Application.get_env(:dispatch, :force_ssl) do opts = Plug.SSL.init(rewrite_on: [:x_forwarded_proto]) Plug.SSL.call(conn, opts) else conn end end defp basic_auth(conn, _opts) do basic_auth_config = Application.get_env(:dispatch, :basic_auth) if basic_auth_config do opts = BasicAuth.init(use_config: {:dispatch, :basic_auth}) BasicAuth.call(conn, opts) else conn end end end
23.388889
98
0.692399
036a98aba2c738ff3ee574da108f3e4ba83be0c5
9,907
ex
Elixir
lib/ex_admin/themes/admin_lte2/filter.ex
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
2
2019-12-21T12:59:19.000Z
2020-04-01T15:27:12.000Z
lib/ex_admin/themes/admin_lte2/filter.ex
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
null
null
null
lib/ex_admin/themes/admin_lte2/filter.ex
augnustin/ex_admin
218d0094de8186808924dcca6157875a7bb382c9
[ "MIT" ]
1
2020-02-29T22:13:24.000Z
2020-02-29T22:13:24.000Z
Code.ensure_compiled(ExAdmin.Utils) defmodule ExAdmin.Theme.AdminLte2.Filter do @moduledoc false require Logger require Ecto.Query import ExAdmin.Utils import ExAdmin.Gettext import ExAdmin.Filter use Xain def theme_filter_view(conn, defn, q, order, scope) do markup safe: true do div ".box.box-primary" do div ".box-header.with-border" do h3(".box-title " <> gettext("Filters")) end form "accept-charset": "UTF-8", action: admin_resource_path(conn, :index), class: "filter_form", id: "q_search", method: "get" do div ".box-body.sidebar_section" do if scope do input(type: :hidden, name: :scope, value: scope) end for field <- fields(defn), do: build_field(field, q, defn) for field <- associations(defn), do: build_field(field, q, defn) end div ".box-footer" do input( name: "commit", type: "submit", value: gettext("Filter"), class: "btn btn-primary" ) a( ".clear_filters_btn " <> gettext("Clear Filters"), href: "#", style: "padding-left: 10px" ) order_value = if order, do: order, else: "id_desc" input(id: "order", name: "order", type: :hidden, value: order_value) end end end end end def build_field({name, :string}, q, defn) do selected_name = string_selected_name(name, q) value = get_string_value(name, q) div ".form-group" do label_with_null_filter(name, q, defn) div ".row" do div ".col-xs-6", style: "padding-right: 0" do span ".input-group-addon" do div ".filter-select" do select onchange: ~s|document.getElementById("q_#{name}").name = "q[" + this.value + "]";| do for {suffix, text} <- string_options() do build_option(text, "#{name}_#{suffix}", selected_name) end end i(".fa.fa-sort", style: "margin-left: -20px") end end end div ".col-xs-6", style: "padding-left: 0px" do input( id: "q_#{name}", name: "q[#{selected_name}]", type: "text", value: value, class: "form-control" ) end end end end def build_field({name, type}, q, defn) when type in [ :date, NaiveDateTime, :naive_datetime, DateTime, :utc_datetime ] do gte_value = get_value("#{name}_gte", q) lte_value = get_value("#{name}_lte", q) div ".form-group" do label_with_null_filter(name, q, defn) div ".row" do div ".col-xs-6", style: "padding-right: 5px;" do div ".input-group" do div ".input-group-addon" do i(".fa.fa-calendar") end input( class: "datepicker form-control", id: "q_#{name}_gte", max: "10", name: "q[#{name}_gte]", size: "15", type: :text, placeholder: "Date min", value: gte_value ) end end div ".col-xs-6", style: "padding-left: 5px;" do div ".input-group" do div ".input-group-addon" do i(".fa.fa-calendar") end input( class: "datepicker form-control", id: "q_#{name}_lte", max: "10", name: "q[#{name}_lte]", size: "15", type: :text, placeholder: "Date max", value: lte_value ) end end end end end def build_field({name, num}, q, defn) when num in [:integer, :id, :decimal, :float] do unless check_and_build_association(name, q, defn) do selected_name = integer_selected_name(name, q) value = get_integer_value(name, q) div ".form-group" do label_with_null_filter(name, q, defn) div ".row" do div ".col-xs-6", style: "padding-right: 0" do span ".input-group-addon" do div ".filter-select" do select onchange: ~s|document.getElementById("#{name}_numeric").name = "q[" + this.value + "]";| do for {suffix, text} <- integer_options() do build_option(text, "#{name}_#{suffix}", selected_name) end end i(".fa.fa-sort", style: "margin-left: -20px") end end end div ".col-xs-6", style: "padding-left: 0px" do input( id: "#{name}_numeric", name: "q[#{selected_name}]", size: "10", type: "text", value: value, class: "form-control" ) end end end end end def build_field( {name, %Ecto.Association.BelongsTo{related: assoc, owner_key: owner_key}}, q, defn ) do id = "q_#{owner_key}" selected_key = case q["#{owner_key}_eq"] do nil -> nil val -> val end field_name = "q[#{owner_key}_eq]" name_label = field_label(name, defn) title = name_label |> String.replace(" Id", "") case filter_options(defn, name, :type) do :hidden -> input(id: id, name: field_name, type: :hidden, value: selected_key) :present_only -> div ".form-group" do label_with_null_filter(owner_key, q, defn, title) end _ -> div ".form-group" do label_with_null_filter(owner_key, q, defn, title) select "##{id}.form-control", name: field_name do option("Any", value: "") for r <- filter_resources(name, assoc, defn) do id = ExAdmin.Schema.get_id(r) name = ExAdmin.Helpers.display_name(r) selected = if "#{id}" == selected_key, do: [selected: :selected], else: [] option(name, [{:value, "#{id}"} | selected]) end end end end end def build_field( {name, %type{}}, q, defn ) when type in [Ecto.Association.Has, Ecto.Association.ManyToMany] do div ".form-group" do label_with_null_filter(name, q, defn, "With #{field_label(name, defn)}") end end def build_field({name, {:embed, %Ecto.Embedded{ }}}, q, defn) do div ".form-group" do label_with_null_filter(name, q, defn) end end def build_field({name, :boolean}, q, defn) do name_label = field_label(name, defn) name_field = "#{name}_eq" opts = [id: "q_#{name}", name: "q[#{name_field}]", type: :checkbox, value: "true"] new_opts = if q do if Map.get(q, name_field, nil), do: [{:checked, :checked} | opts], else: opts else opts end div ".form-group" do label(".label #{name_label}", for: "q_#{name}") input(new_opts) end end def build_field({name, Ecto.UUID}, q, defn) do repo = Application.get_env(:ex_admin, :repo) ids = repo.all(defn.resource_model) |> Enum.map(&Map.get(&1, name)) selected_key = case q["#{name}_eq"] do nil -> nil val -> val end div ".form-group" do label_with_null_filter(name, q, defn) select "##{name}", name: "q[#{name}_eq]", class: "form-control" do option("Any", value: "") for id <- ids do selected = if "#{id}" == selected_key, do: [selected: :selected], else: [] option(id, [{:value, "#{id}"} | selected]) end end end end def build_field({name, type}, _q, _) do Logger.debug("ExAdmin.Filter: unknown type: #{inspect(type)} for field: #{inspect(name)}") nil end def label_with_null_filter(name, q, defn, title \\nil) do title_with_default = title || field_label(name, defn) scope = filter_options(defn, name, :scope) not_null_opts = [ id: "q_#{name}_is_not_null", name: "q[#{name}_is]", type: :radio, value: "not_null", ] ++ (if q["#{name}_is"] == "not_null", do: [checked: :checked], else: []) null_opts = [ id: "q_#{name}_is_null", name: "q[#{name}_is]", type: :radio, value: "null", ] ++ (if q["#{name}_is"] == "null", do: [checked: :checked], else: []) p(".label.with-null-filter") do radio_label = if scope, do: "All", else: "Present" span("#{title_with_default}: ") label( ".label-inline", for: "q_#{name}_is_not_null", title: (radio_label) ) do input(not_null_opts) span(radio_label) end if scope do scoped_name = "#{scope}_#{String.downcase(field_label(name, defn))}" scope_title = ExAdmin.Utils.titleize(scope) scoped_opts = [ id: "q_#{scoped_name}_is_not_null", name: "q[#{scoped_name}_is]", type: :radio, value: "not_null", ] ++ (if q["#{scoped_name}_is"] == "not_null", do: [checked: :checked], else: []) span(" ") label( ".label-inline", for: "q_#{scoped_name}_is_not_null", title: scope_title ) do input(scoped_opts) span(scope_title) end end radio_label = if scope, do: "None", else: "Empty" span(" ") label( ".label-inline", for: "q_#{name}_is_null", title: radio_label ) do input(null_opts) span(radio_label) end end end end
27.519444
106
0.505703
036aa665e2e737b93660dd666bb5caeddb2fc5a5
1,109
exs
Elixir
config/config.exs
jespr/noegle
e14953085d38384c80993dd750aa85202db11418
[ "MIT" ]
null
null
null
config/config.exs
jespr/noegle
e14953085d38384c80993dd750aa85202db11418
[ "MIT" ]
1
2017-05-08T15:09:09.000Z
2017-05-10T06:05:24.000Z
config/config.exs
jespr/noegle
e14953085d38384c80993dd750aa85202db11418
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :noegle, key: :value # # And access this configuration in your application as: # # Application.get_env(:noegle, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # import_config "#{Mix.env}.exs"
35.774194
73
0.754734
036ad3b77151886daa64d6059a2f11e3ccc3936d
1,479
exs
Elixir
integration_test/all_test.exs
fasib/ecto_sqlite3
3ef1bf4d2a93fe07ea2571fb24dc7b6e320cf4cf
[ "MIT" ]
null
null
null
integration_test/all_test.exs
fasib/ecto_sqlite3
3ef1bf4d2a93fe07ea2571fb24dc7b6e320cf4cf
[ "MIT" ]
null
null
null
integration_test/all_test.exs
fasib/ecto_sqlite3
3ef1bf4d2a93fe07ea2571fb24dc7b6e320cf4cf
[ "MIT" ]
null
null
null
ecto = Mix.Project.deps_paths()[:ecto] Code.require_file "#{ecto}/integration_test/cases/assoc.exs", __DIR__ Code.require_file "#{ecto}/integration_test/cases/joins.exs", __DIR__ Code.require_file "#{ecto}/integration_test/cases/preload.exs", __DIR__ Code.require_file "#{ecto}/integration_test/cases/repo.exs", __DIR__ Code.require_file "#{ecto}/integration_test/cases/windows.exs", __DIR__ # Since sqlite does not have microsecond precision we forked these tests # and added some additionals tests for datetime types Code.require_file "./ecto/interval.exs", __DIR__ # we also added some fixes to their decimal precision tests # we also added the :like_match_blob tag Code.require_file "./ecto/type.exs", __DIR__ ecto_sql = Mix.Project.deps_paths()[:ecto_sql] # Code.require_file "#{ecto_sql}/integration_test/sql/lock.exs", __DIR__ Code.require_file "#{ecto_sql}/integration_test/sql/logging.exs", __DIR__ Code.require_file "#{ecto_sql}/integration_test/sql/sandbox.exs", __DIR__ Code.require_file "#{ecto_sql}/integration_test/sql/sql.exs", __DIR__ Code.require_file "#{ecto_sql}/integration_test/sql/stream.exs", __DIR__ Code.require_file "#{ecto_sql}/integration_test/sql/subquery.exs", __DIR__ Code.require_file "#{ecto_sql}/integration_test/sql/transaction.exs", __DIR__ # added :modify_column and :alter_foreign_key Code.require_file "./ecto_sql/migration.exs", __DIR__ # added :prefix and :lock_for_migrations Code.require_file "./ecto_sql/migrator.exs", __DIR__
46.21875
77
0.795132
036ae5826c2a53829808b9c69644840018788f3a
1,967
ex
Elixir
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/customer_list_customers_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/customer_list_customers_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/customer_list_customers_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidDeviceProvisioning.V1.Model.CustomerListCustomersResponse do @moduledoc """ Response message for listing my customers. ## Attributes - customers ([Company]): The customer accounts the calling user is a member of. Defaults to: `null`. - nextPageToken (String.t): A token used to access the next page of results. Omitted if no further results are available. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :customers => list(GoogleApi.AndroidDeviceProvisioning.V1.Model.Company.t()), :nextPageToken => any() } field(:customers, as: GoogleApi.AndroidDeviceProvisioning.V1.Model.Company, type: :list) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.CustomerListCustomersResponse do def decode(value, options) do GoogleApi.AndroidDeviceProvisioning.V1.Model.CustomerListCustomersResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.CustomerListCustomersResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.125
144
0.754448
036afd563212b15ae7e11d6cadc84ad14ad09e01
8,874
ex
Elixir
lib/protox/define_message.ex
ahamez/protox
1966fb5f26b546f95033fbe18850b6c69eb6617d
[ "MIT" ]
176
2017-02-01T13:09:25.000Z
2022-03-18T02:36:17.000Z
lib/protox/define_message.ex
ahamez/protox
1966fb5f26b546f95033fbe18850b6c69eb6617d
[ "MIT" ]
94
2020-07-20T05:54:51.000Z
2022-03-09T04:13:03.000Z
lib/protox/define_message.ex
ahamez/protox
1966fb5f26b546f95033fbe18850b6c69eb6617d
[ "MIT" ]
19
2017-02-13T09:17:14.000Z
2022-02-22T09:29:18.000Z
defmodule Protox.DefineMessage do @moduledoc false alias Protox.Field def define(messages, opts \\ []) do {keep_unknown_fields, _opts} = Keyword.pop(opts, :keep_unknown_fields, true) for {msg_name, syntax, fields} <- messages do fields = Enum.sort(fields, &(&1.tag < &2.tag)) unknown_fields = make_unknown_fields(:__uf__, fields) unknown_fields_funs = make_unknown_fields_funs(keep_unknown_fields, unknown_fields) struct_fields = make_struct_fields(fields, syntax, unknown_fields, keep_unknown_fields) required_fields = make_required_fields(fields) required_fields_typesecs = make_required_fields_typespec(required_fields) fields_map = make_fields_map(fields) fields_by_name_map = make_fields_by_name_map(fields) field_def_funs = make_field_funs(fields) encoder = Protox.DefineEncoder.define(fields, required_fields, syntax, opts) decoder = Protox.DefineDecoder.define(msg_name, fields, required_fields, opts) json_funs = make_json_funs(msg_name) default_fun = make_default_funs(fields) module_ast = quote do defstruct unquote(struct_fields) unquote(encoder) unquote(decoder) unquote(json_funs) @deprecated "Use fields_defs()/0 instead" @spec defs() :: %{ required(non_neg_integer) => {atom, Protox.Types.kind(), Protox.Types.type()} } def defs(), do: unquote(fields_map) @deprecated "Use fields_defs()/0 instead" @spec defs_by_name() :: %{ required(atom) => {non_neg_integer, Protox.Types.kind(), Protox.Types.type()} } def defs_by_name(), do: unquote(fields_by_name_map) @spec fields_defs() :: list(Protox.Field.t()) def fields_defs(), do: unquote(Macro.escape(fields)) unquote(field_def_funs) unquote(unknown_fields_funs) @spec required_fields() :: unquote(required_fields_typesecs) def required_fields(), do: unquote(required_fields) @spec syntax() :: atom def syntax(), do: unquote(syntax) unquote(default_fun) end quote do defmodule unquote(msg_name) do @moduledoc false unquote(module_ast) end end end end # -- Private defp make_json_funs(msg_name) do quote do @spec json_decode(iodata(), keyword()) :: {:ok, struct()} | {:error, any()} def json_decode(input, opts \\ []) do try do {:ok, json_decode!(input, opts)} rescue e in Protox.JsonDecodingError -> {:error, e} end end @spec json_decode!(iodata(), keyword()) :: struct() | no_return() def json_decode!(input, opts \\ []) do {json_library_wrapper, json_library} = Protox.JsonLibrary.get_library(opts, :decode) Protox.JsonDecode.decode!( input, unquote(msg_name), &json_library_wrapper.decode!(json_library, &1) ) end @spec json_encode(struct(), keyword()) :: {:ok, iodata()} | {:error, any()} def json_encode(msg, opts \\ []) do try do {:ok, json_encode!(msg, opts)} rescue e in Protox.JsonEncodingError -> {:error, e} end end @spec json_encode!(struct(), keyword()) :: iodata() | no_return() def json_encode!(msg, opts \\ []) do {json_library_wrapper, json_library} = Protox.JsonLibrary.get_library(opts, :encode) Protox.JsonEncode.encode!(msg, &json_library_wrapper.encode!(json_library, &1)) end end end defp make_unknown_fields_funs(true = _keep_unknown_fields, unknown_fields) do quote do @spec unknown_fields(struct) :: [{non_neg_integer, Protox.Types.tag(), binary}] def unknown_fields(msg), do: msg.unquote(unknown_fields) @spec unknown_fields_name() :: unquote(unknown_fields) def unknown_fields_name(), do: unquote(unknown_fields) @spec clear_unknown_fields(struct) :: struct def clear_unknown_fields(msg), do: struct!(msg, [{unknown_fields_name(), []}]) end end defp make_unknown_fields_funs(false = _keep_unknown_fields, _unknown_fields) do [] end # Generate the functions that provide a direct access to the default value of a field. defp make_default_funs(fields) do spec = quote do @spec default(atom) :: {:ok, boolean | integer | String.t() | float} | {:error, atom} end match_all = quote do def default(_), do: {:error, :no_such_field} end ast = Enum.map(fields, fn %Field{name: name, kind: {:scalar, default}} -> quote do def default(unquote(name)), do: {:ok, unquote(default)} end %Field{name: name} -> quote do def default(unquote(name)), do: {:error, :no_default_value} end end) List.flatten([spec, ast, match_all]) end # Generate the functions that provide a direct access to a field defininition. defp make_field_funs(fields) do spec = quote do @spec field_def(atom) :: {:ok, Protox.Field.t()} | {:error, :no_such_field} end match_all = quote do def field_def(_), do: {:error, :no_such_field} end ast = Enum.map(fields, fn %Field{} = field -> atom_name_as_string = Atom.to_string(field.name) maybe_fun_by_atom_name_as_string = if atom_name_as_string == field.json_name do [] else quote do def field_def(unquote(atom_name_as_string)), do: {:ok, unquote(Macro.escape(field))} end end quote do def field_def(unquote(field.name)), do: {:ok, unquote(Macro.escape(field))} def field_def(unquote(field.json_name)), do: {:ok, unquote(Macro.escape(field))} unquote(maybe_fun_by_atom_name_as_string) end end) List.flatten([spec, ast, match_all]) end # Make sure the name chosen for the struct fields that stores the unknow fields # of the protobuf message doesn't collide with already existing names. defp make_unknown_fields(name, fields) do name_in_fields = Enum.find(fields, fn %Field{name: n} -> n == name end) if name_in_fields do # Append a '_' while there's a collision name |> Atom.to_string() |> (fn x -> x <> "_" end).() |> String.to_atom() |> make_unknown_fields(fields) else name end end # Generate fields of the struct which is created for a message. defp make_struct_fields(fields, syntax, unknown_fields, keep_unknown_fields) do struct_fields = for %Field{label: label, name: name, kind: kind} <- fields do case kind do :map -> {name, Macro.escape(%{})} {:oneof, parent} -> make_oneof_field(label, name, parent) :packed -> {name, []} :unpacked -> {name, []} {:scalar, _} when syntax == :proto2 -> {name, nil} {:scalar, default_value} when syntax == :proto3 -> {name, default_value} end end struct_fields = case keep_unknown_fields do true -> struct_fields ++ [{unknown_fields, []}] false -> struct_fields end Enum.uniq(struct_fields) end defp make_oneof_field(:proto3_optional, name, _), do: {name, nil} defp make_oneof_field(_, _, parent), do: {parent, nil} # Get the list of fields that are marked as `required`. defp make_required_fields(fields) do for %Field{label: :required, name: name} <- fields, do: name end defp make_required_fields_typespec([]), do: quote(do: []) defp make_required_fields_typespec(fields) do specs = Enum.reduce( fields, fn field, acc -> quote(do: unquote(acc) | unquote(field)) end ) quote(do: [unquote(specs)]) end # Generate a map used to store a message's definitions. defp make_fields_map(fields) do fields |> Enum.reduce(%{}, fn %Field{tag: tag, name: name, kind: kind, type: type}, acc -> Map.put(acc, tag, {name, kind, make_type_field(kind, type)}) end) |> Macro.escape() end defp make_fields_by_name_map(fields) do fields |> Enum.reduce(%{}, fn %Field{tag: tag, name: name, kind: kind, type: type}, acc -> Map.put(acc, name, {tag, kind, make_type_field(kind, type)}) end) |> Macro.escape() end defp make_type_field(:map, {key_type, {:message, msg}}), do: {key_type, {:message, msg}} defp make_type_field(:map, {key_type, {:enum, enum}}), do: {key_type, {:enum, enum}} defp make_type_field(_, {:enum, enum}), do: {:enum, enum} defp make_type_field(_, {:message, enum}), do: {:message, enum} defp make_type_field(_, ty), do: ty end
30.919861
98
0.617309
036b4629b92264be979f447ecaf6a36759eaba32
4,538
ex
Elixir
clients/apps_activity/lib/google_api/apps_activity/v1/api/activities.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/apps_activity/lib/google_api/apps_activity/v1/api/activities.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/apps_activity/lib/google_api/apps_activity/v1/api/activities.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.AppsActivity.V1.Api.Activities do @moduledoc """ API calls for all endpoints tagged `Activities`. """ alias GoogleApi.AppsActivity.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Returns a list of activities visible to the current logged in user. Visible activities are determined by the visibility settings of the object that was acted on, e.g. Drive files a user can see. An activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped to activities from a given Google service using the source parameter. ## Parameters * `connection` (*type:* `GoogleApi.AppsActivity.V1.Connection.t`) - Connection to server * `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. * `:"drive.ancestorId"` (*type:* `String.t`) - Identifies the Drive folder containing the items for which to return activities. * `:"drive.fileId"` (*type:* `String.t`) - Identifies the Drive item to return activities for. * `:groupingStrategy` (*type:* `String.t`) - Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent object. * `:pageSize` (*type:* `integer()`) - The maximum number of events to return on a page. The response includes a continuation token if there are more events. * `:pageToken` (*type:* `String.t`) - A token to retrieve a specific page of results. * `:source` (*type:* `String.t`) - The Google service from which to return activities. Possible values of source are: - drive.google.com * `:userId` (*type:* `String.t`) - The ID used for ACL checks (does not filter the resulting event list by the assigned value). Use the special value me to indicate the currently authenticated user. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AppsActivity.V1.Model.ListActivitiesResponse{}}` on success * `{:error, info}` on failure """ @spec appsactivity_activities_list(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.AppsActivity.V1.Model.ListActivitiesResponse.t()} | {:error, Tesla.Env.t()} def appsactivity_activities_list(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :"drive.ancestorId" => :query, :"drive.fileId" => :query, :groupingStrategy => :query, :pageSize => :query, :pageToken => :query, :source => :query, :userId => :query } request = Request.new() |> Request.method(:get) |> Request.url("/activities", %{}) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AppsActivity.V1.Model.ListActivitiesResponse{}] ) end end
50.988764
377
0.67673
036b47a4e73d5db7b23e72079ec0291cc146fc7d
1,622
ex
Elixir
clients/android_management/lib/google_api/android_management/v1/model/application_reporting_settings.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/application_reporting_settings.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/application_reporting_settings.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidManagement.V1.Model.ApplicationReportingSettings do @moduledoc """ Settings controlling the behavior of application reports. ## Attributes - includeRemovedApps (boolean()): Whether removed apps are included in application reports. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :includeRemovedApps => any() } field(:includeRemovedApps) end defimpl Poison.Decoder, for: GoogleApi.AndroidManagement.V1.Model.ApplicationReportingSettings do def decode(value, options) do GoogleApi.AndroidManagement.V1.Model.ApplicationReportingSettings.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidManagement.V1.Model.ApplicationReportingSettings do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.791667
114
0.766338
036b684f56e79f48d0bc5bb5ead86da6783db4f2
216
ex
Elixir
lib/materia_file_transfer/google_cloud/config.ex
karabiner-inc/materia_file_transfer
d72f11d97a4ac87362225558aaf88909c9a10c64
[ "Apache-2.0" ]
null
null
null
lib/materia_file_transfer/google_cloud/config.ex
karabiner-inc/materia_file_transfer
d72f11d97a4ac87362225558aaf88909c9a10c64
[ "Apache-2.0" ]
null
null
null
lib/materia_file_transfer/google_cloud/config.ex
karabiner-inc/materia_file_transfer
d72f11d97a4ac87362225558aaf88909c9a10c64
[ "Apache-2.0" ]
null
null
null
defmodule MateriaFileTransfer.GoogleCloud.Config do @moduledoc false use Goth.Config def init(config) do {:ok, Keyword.put(config, :json, System.get_env("GCP_JSON_CREDENTIALS") |> File.read!())} end end
24
93
0.731481
036b89ed4cd88752b3248cd779ab59878f7a507c
117
ex
Elixir
lib/client/video/video_request.ex
factor18/pexels
c6655f7dd0e58a9a06b6b7a02e74b3f009cd7b01
[ "MIT" ]
5
2021-05-10T12:10:02.000Z
2021-05-24T08:15:42.000Z
lib/client/video/video_request.ex
factor18/pexels
c6655f7dd0e58a9a06b6b7a02e74b3f009cd7b01
[ "MIT" ]
null
null
null
lib/client/video/video_request.ex
factor18/pexels
c6655f7dd0e58a9a06b6b7a02e74b3f009cd7b01
[ "MIT" ]
1
2021-05-13T16:49:17.000Z
2021-05-13T16:49:17.000Z
defmodule Pexels.Client.Video.VideoRequest do use Accessible use Construct do field :id, :integer end end
14.625
45
0.74359
036ba02bc948b537c1f0e2a5049873753e5e1603
644
ex
Elixir
lib/autoformatbot/token.ex
maltoe/autoformatbot.ex
cedcf5471165eefe133f9ff6a71c8a91c0ddbcc3
[ "MIT" ]
null
null
null
lib/autoformatbot/token.ex
maltoe/autoformatbot.ex
cedcf5471165eefe133f9ff6a71c8a91c0ddbcc3
[ "MIT" ]
null
null
null
lib/autoformatbot/token.ex
maltoe/autoformatbot.ex
cedcf5471165eefe133f9ff6a71c8a91c0ddbcc3
[ "MIT" ]
null
null
null
defmodule Autoformatbot.Token do defstruct [ :config, :current_branch, :current_sha, :target_branch, :target_sha, :temporary_branch, :files, :adapter ] def pipeline(functions) do case Enum.reduce_while(functions, %__MODULE__{}, &step/2) do %__MODULE__{} -> :ok err -> err end end defp step({key, function}, token) do case function.(token) do {:ok, result} -> {:cont, Map.put(token, key, result)} err -> {:halt, err} end end defp step(function, token) do case function.(token) do :ok -> {:cont, token} err -> {:halt, err} end end end
18.941176
64
0.585404
036bb23594811ef4e030e84e585ceb80c55cfafb
449
ex
Elixir
lib/ghost.ex
Bhaskers-Blu-Org1/ghost
834d9a3c2ed93b81d37ee8cfcc9242ea6ba3970d
[ "Apache-2.0" ]
4
2019-05-16T21:43:59.000Z
2019-12-31T09:19:31.000Z
lib/ghost.ex
IBM/ghost
834d9a3c2ed93b81d37ee8cfcc9242ea6ba3970d
[ "Apache-2.0" ]
null
null
null
lib/ghost.ex
IBM/ghost
834d9a3c2ed93b81d37ee8cfcc9242ea6ba3970d
[ "Apache-2.0" ]
3
2019-11-04T01:28:36.000Z
2020-06-29T14:40:50.000Z
defmodule Ghost do @config Application.get_env(:ghost, __MODULE__) def produce_sync(topic, key, message) do client = Keyword.get(@config, :client) adapter = Keyword.get(@config, :adapter) adapter.produce_sync(client, topic, key, message) end def produce(topic, key, message) do client = Keyword.get(@config, :client) adapter = Keyword.get(@config, :adapter) adapter.produce(client, topic, key, message) end end
28.0625
53
0.699332
036bb48403583615b7278ccc9f47f21f4d9f75c8
1,782
exs
Elixir
test/bootleg/tasks/manage_tasks_test.exs
jayjun/bootleg
2283ad22810178625c45eb2661624fac914befdd
[ "MIT" ]
423
2017-07-19T18:40:45.000Z
2021-12-03T08:26:15.000Z
test/bootleg/tasks/manage_tasks_test.exs
jayjun/bootleg
2283ad22810178625c45eb2661624fac914befdd
[ "MIT" ]
115
2017-07-19T18:30:14.000Z
2020-10-27T20:53:32.000Z
test/bootleg/tasks/manage_tasks_test.exs
jayjun/bootleg
2283ad22810178625c45eb2661624fac914befdd
[ "MIT" ]
39
2017-07-20T03:14:18.000Z
2020-11-18T13:39:52.000Z
defmodule Bootleg.Tasks.ManageTasksTest do use Bootleg.{FunctionalCase, DSL}, async: false # use Bootleg.DSL alias Bootleg.SSH import ExUnit.CaptureIO setup %{hosts: [host]} do role( :app, [host.ip], port: host.port, user: host.user, password: host.password, silently_accept_hosts: true, workspace: "workspace" ) config :app, "build_me" config :version, "0.1.0" capture_io(fn -> conn = SSH.init(:app) SSH.run!(conn, "install-app build_me") send(self(), {:connection, conn}) end) assert_received {:connection, conn} %{conn: conn} end test "start" do capture_io(fn -> assert :ok = invoke(:start) end) end test "invoke start with app running", %{conn: conn} do capture_io(fn -> SSH.run!(conn, "bin/build_me start") assert :ok = invoke(:start) end) end test "invoke stop", %{conn: conn} do capture_io(fn -> SSH.run!(conn, "launch-app build_me") assert :ok = invoke(:stop) end) end test "invoke stop with app not running" do capture_io(fn -> assert_raise SSHError, fn -> invoke(:stop) end end) end test "invoke restart", %{conn: conn} do capture_io(fn -> SSH.run!(conn, "launch-app build_me") assert :ok = invoke(:restart) end) end test "invoke restart with app not running" do capture_io(fn -> assert_raise SSHError, fn -> invoke(:restart) end end) end test "invoke ping", %{conn: conn} do capture_io(fn -> SSH.run!(conn, "launch-app build_me") assert :ok = invoke(:ping) end) end test "invoke ping with app not running" do capture_io(fn -> assert_raise SSHError, fn -> invoke(:ping) end end) end end
21.214286
56
0.603816
036bc21cab70c0a146f31fe44be2ad6f4b0746ab
445
exs
Elixir
test/swiss/date_time_test.exs
myskoach/swiss
a906ec0c5afc7417a1b412116bf8b1018901d43f
[ "Apache-2.0" ]
2
2020-11-06T21:02:47.000Z
2020-11-06T23:27:35.000Z
test/swiss/date_time_test.exs
myskoach/swiss
a906ec0c5afc7417a1b412116bf8b1018901d43f
[ "Apache-2.0" ]
4
2020-03-05T17:37:46.000Z
2021-10-06T10:13:51.000Z
test/swiss/date_time_test.exs
myskoach/swiss
a906ec0c5afc7417a1b412116bf8b1018901d43f
[ "Apache-2.0" ]
1
2021-09-22T13:43:58.000Z
2021-09-22T13:43:58.000Z
defmodule Swiss.DateTimeTest do use ExUnit.Case, async: true doctest Swiss.DateTime describe "second_utc_now/0" do test "returns the current UTC date with second precision" do now = Swiss.DateTime.second_utc_now() assert_in_delta DateTime.to_unix(now), DateTime.to_unix(DateTime.utc_now()), 25 assert now.utc_offset == 0 assert now.time_zone == "Etc/UTC" refute now.microsecond == nil end end end
27.8125
85
0.707865
036bf7f9c95b265f8f9bd937af45da0d576f20ac
2,368
ex
Elixir
lib/oli/authoring/project_search.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
lib/oli/authoring/project_search.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
lib/oli/authoring/project_search.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Authoring.ProjectSearch do import Ecto.Query alias Oli.Authoring.Course.Project alias Oli.Publishing.Publication alias Oli.Repo @doc """ Searches the title, description, slug, and version of all active course projects for the search string. Returns an array of maps containing those same attributes of each matching course project. """ def search(search_string) do search_string |> normalize() |> run() end defmacro matching_title_description_slug(search_string) do quote do fragment( """ SELECT projects.id AS id, ts_rank( setweight(to_tsvector('english', projects.title), 'B') || setweight(to_tsvector('english', projects.description), 'C') || setweight(to_tsvector('simple', projects.slug), 'A') || setweight(to_tsvector('simple', projects.version), 'D'), plainto_tsquery(unaccent(?)) ) AS rank FROM projects WHERE setweight(to_tsvector('english', projects.title), 'B') || setweight(to_tsvector('english', projects.description), 'C') || setweight(to_tsvector('simple', projects.slug), 'A') || setweight(to_tsvector('simple', projects.version), 'D') @@ plainto_tsquery(unaccent(?)) OR projects.title ILIKE ? """, ^unquote(search_string), ^unquote(search_string), ^"%#{unquote(search_string)}%" ) end end defp run(search_string) do Repo.all( from(p in Project, as: :project, join: id_and_rank in matching_title_description_slug(search_string), on: id_and_rank.id == p.id, where: exists(from(pub in Publication, where: parent_as(:project).id == pub.project_id)) and p.status == :active, order_by: [desc: id_and_rank.rank], select: %{slug: p.slug, title: p.title, description: p.description, version: p.version} ) ) end defp normalize(search_string) do search_string |> String.downcase() # replace newlines with a space |> String.replace(~r/\n/, " ") # replace tabs with a space |> String.replace(~r/\t/, " ") # collapse all whitespace to single space |> String.replace(~r/\s{2,}/, " ") # remove leading and trailing whitespace |> String.trim() end end
31.573333
102
0.618666
036c0d6e939e96028b01f46d9054c3989fca40cf
259
ex
Elixir
phoenix_example/lib/spec_example.ex
saraid/rb-phoenix-socket
90558ced343763621a99e361cbb92e8e3c1d6d1d
[ "MIT" ]
9
2017-09-21T17:28:02.000Z
2019-09-19T11:13:07.000Z
phoenix_example/lib/spec_example.ex
saraid/rb-phoenix-socket
90558ced343763621a99e361cbb92e8e3c1d6d1d
[ "MIT" ]
2
2017-09-24T00:26:45.000Z
2021-03-04T15:54:11.000Z
phoenix_example/lib/spec_example.ex
saraid/rb-phoenix-socket
90558ced343763621a99e361cbb92e8e3c1d6d1d
[ "MIT" ]
1
2021-04-08T23:14:22.000Z
2021-04-08T23:14:22.000Z
defmodule SpecExample do @moduledoc """ SpecExample keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
25.9
66
0.760618
036c19af02913700ce113555ed89e2c3ae8c5e7f
776
ex
Elixir
lib/stein/time.ex
smartlogic/stein
785dff2d0400925b896d78b0f092fc501b685d0c
[ "MIT" ]
14
2019-03-07T22:06:51.000Z
2021-06-05T19:27:22.000Z
lib/stein/time.ex
smartlogic/stein
785dff2d0400925b896d78b0f092fc501b685d0c
[ "MIT" ]
1
2019-03-07T16:46:11.000Z
2019-03-07T16:46:11.000Z
lib/stein/time.ex
smartlogic/stein
785dff2d0400925b896d78b0f092fc501b685d0c
[ "MIT" ]
null
null
null
defmodule Stein.Time do @moduledoc """ Helpers for dealing with time """ @doc """ Get the current time """ @spec now() :: DateTime.t() def now() do :os.system_time() |> DateTime.from_unix!(:native) |> DateTime.truncate(:second) end @doc """ Determine if a time is after another time """ @spec after?(DateTime.t(), DateTime.t()) :: boolean() def after?(_time, nil), do: false def after?(time, other_time) do case DateTime.compare(time, other_time) do :gt -> true _ -> false end end @doc """ Check if a time is before another time """ def before?(time, other_time) do case DateTime.compare(time, other_time) do :lt -> true _ -> false end end end
17.244444
55
0.573454
036c67f7a6cf169e8c14e4a13286ebdf253c26cc
28,065
exs
Elixir
test/livebook/session_test.exs
axelson/livebook
78b9a11d8c3dac78c648cc7903343ea09f45efd9
[ "Apache-2.0" ]
null
null
null
test/livebook/session_test.exs
axelson/livebook
78b9a11d8c3dac78c648cc7903343ea09f45efd9
[ "Apache-2.0" ]
null
null
null
test/livebook/session_test.exs
axelson/livebook
78b9a11d8c3dac78c648cc7903343ea09f45efd9
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.SessionTest do use ExUnit.Case, async: true import Livebook.TestHelpers alias Livebook.{Session, Delta, Runtime, Utils, Notebook, FileSystem} alias Livebook.Notebook.{Section, Cell} alias Livebook.Session.Data setup do session = start_session() %{session: session} end describe "file_name_for_download/1" do @tag :tmp_dir test "uses associated file name if one is attached", %{tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "my_notebook.livemd") session = start_session(file: file) assert Session.file_name_for_download(session) == "my_notebook" end test "defaults to notebook name", %{session: session} do Session.set_notebook_name(session.pid, "Cat's guide to life!") # Get the updated struct session = Session.get_by_pid(session.pid) assert Session.file_name_for_download(session) == "cats_guide_to_life" end test "removes non-ascii characters from notebook name", %{session: session} do Session.set_notebook_name(session.pid, "Notebook 😺") # Get the updated struct session = Session.get_by_pid(session.pid) assert Session.file_name_for_download(session) == "notebook" end end describe "set_notebook_attributes/2" do test "sends an attributes update to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() attrs = %{set_notebook_attributes: true} Session.set_notebook_attributes(session.pid, attrs) assert_receive {:operation, {:set_notebook_attributes, ^pid, ^attrs}} end end describe "insert_section/2" do test "sends an insert opreation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() Session.insert_section(session.pid, 0) assert_receive {:operation, {:insert_section, ^pid, 0, _id}} end end describe "insert_cell/4" do test "sends an insert opreation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() Session.insert_section(session.pid, 0) assert_receive {:operation, {:insert_section, ^pid, 0, section_id}} Session.insert_cell(session.pid, section_id, 0, :code) assert_receive {:operation, {:insert_cell, ^pid, ^section_id, 0, :code, _id, _attrs}} end end describe "delete_section/3" do test "sends a delete opreation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {section_id, _cell_id} = insert_section_and_cell(session.pid) Session.delete_section(session.pid, section_id, false) assert_receive {:operation, {:delete_section, ^pid, ^section_id, false}} end end describe "delete_cell/2" do test "sends a delete opreation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) Session.delete_cell(session.pid, cell_id) assert_receive {:operation, {:delete_cell, ^pid, ^cell_id}} end end describe "restore_cell/2" do test "sends a restore opreation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) Session.delete_cell(session.pid, cell_id) Session.restore_cell(session.pid, cell_id) assert_receive {:operation, {:restore_cell, ^pid, ^cell_id}} end end describe "convert_smart_cell/2" do test "sends a delete and insert opreations to subscribers" do smart_cell = %{Notebook.Cell.new(:smart) | kind: "text", source: "content"} section = %{Notebook.Section.new() | cells: [smart_cell]} notebook = %{Notebook.new() | sections: [section]} session = start_session(notebook: notebook) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() Session.convert_smart_cell(session.pid, smart_cell.id) cell_id = smart_cell.id section_id = section.id assert_receive {:operation, {:delete_cell, ^pid, ^cell_id}} assert_receive {:operation, {:insert_cell, ^pid, ^section_id, 0, :code, _id, %{source: "content", outputs: []}}} end end describe "add_dependencies/2" do test "applies source change to the setup cell to include the given dependencies", %{session: session} do runtime = connected_noop_runtime() Session.set_runtime(session.pid, runtime) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") Session.add_dependencies(session.pid, [{:kino, "~> 0.5.0"}]) session_pid = session.pid assert_receive {:operation, {:apply_cell_delta, ^session_pid, "setup", :primary, _delta, 1}} assert %{ notebook: %{ setup_section: %{ cells: [ %{ source: """ Mix.install([ {:kino, "~> 0.5.0"} ])\ """ } ] } } } = Session.get_data(session.pid) end test "broadcasts an error if modifying the setup source fails" do notebook = Notebook.new() |> Notebook.update_cell("setup", &%{&1 | source: "[,]"}) session = start_session(notebook: notebook) runtime = connected_noop_runtime() Session.set_runtime(session.pid, runtime) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") Session.add_dependencies(session.pid, [{:kino, "~> 0.5.0"}]) assert_receive {:error, "failed to add dependencies to the setup cell, reason:" <> _} end end describe "queue_cell_evaluation/2" do test "triggers evaluation and sends update operation once it finishes", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) Session.queue_cell_evaluation(session.pid, cell_id) assert_receive {:operation, {:queue_cells_evaluation, ^pid, [^cell_id]}} assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, _, %{evaluation_time_ms: _time_ms}}} end end describe "cancel_cell_evaluation/2" do test "sends a cancel evaluation operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) Session.queue_cell_evaluation(session.pid, cell_id) Session.cancel_cell_evaluation(session.pid, cell_id) assert_receive {:operation, {:cancel_cell_evaluation, ^pid, ^cell_id}} end end describe "set_notebook_name/2" do test "sends a notebook name update operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() Session.set_notebook_name(session.pid, "Cat's guide to life") assert_receive {:operation, {:set_notebook_name, ^pid, "Cat's guide to life"}} end end describe "set_section_name/3" do test "sends a section name update operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {section_id, _cell_id} = insert_section_and_cell(session.pid) Session.set_section_name(session.pid, section_id, "Chapter 1") assert_receive {:operation, {:set_section_name, ^pid, ^section_id, "Chapter 1"}} end end describe "apply_cell_delta/4" do test "sends a cell delta operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) delta = Delta.new() |> Delta.insert("cats") revision = 1 Session.apply_cell_delta(session.pid, cell_id, :primary, delta, revision) assert_receive {:operation, {:apply_cell_delta, ^pid, ^cell_id, :primary, ^delta, ^revision}} end end describe "report_cell_revision/3" do test "sends a revision report operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) revision = 1 Session.report_cell_revision(session.pid, cell_id, :primary, revision) assert_receive {:operation, {:report_cell_revision, ^pid, ^cell_id, :primary, ^revision}} end end describe "set_cell_attributes/3" do test "sends an attributes update operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session.pid) attrs = %{disable_formatting: true} Session.set_cell_attributes(session.pid, cell_id, attrs) assert_receive {:operation, {:set_cell_attributes, ^pid, ^cell_id, ^attrs}} end end describe "connect_runtime/2" do test "sends a runtime update operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() runtime = connected_noop_runtime() Session.set_runtime(session.pid, runtime) assert_receive {:operation, {:set_runtime, ^pid, ^runtime}} end end describe "disconnect_runtime/1" do test "sends a runtime update operation to subscribers", %{session: session} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() runtime = connected_noop_runtime() Session.set_runtime(session.pid, runtime) assert_receive {:operation, {:set_runtime, ^pid, _}} # Calling twice can happen in a race, make sure it doesn't crash Session.disconnect_runtime(session.pid) Session.disconnect_runtime([session.pid]) assert_receive {:operation, {:set_runtime, ^pid, runtime}} refute Runtime.connected?(runtime) end end describe "set_file/1" do @tag :tmp_dir test "sends a file update operation to subscribers", %{session: session, tmp_dir: tmp_dir} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") pid = self() tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") Session.set_file(session.pid, file) assert_receive {:operation, {:set_file, ^pid, ^file}} end @tag :tmp_dir test "broadcasts an error if the path is already in use", %{session: session, tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") start_session(file: file) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") Session.set_file(session.pid, file) assert_receive {:error, "failed to set new file because it is already in use"} end @tag :tmp_dir test "moves images to the new directory", %{session: session, tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") %{images_dir: images_dir} = session image_file = FileSystem.File.resolve(images_dir, "test.jpg") :ok = FileSystem.File.write(image_file, "") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") Session.set_file(session.pid, file) # Wait for the session to deal with the files Process.sleep(500) assert {:ok, true} = FileSystem.File.exists?(FileSystem.File.resolve(tmp_dir, "images/test.jpg")) assert {:ok, false} = FileSystem.File.exists?(images_dir) end @tag :tmp_dir test "does not remove images from the previous dir if not temporary", %{session: session, tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") Session.set_file(session.pid, file) %{images_dir: images_dir} = session image_file = FileSystem.File.resolve(images_dir, "test.jpg") :ok = FileSystem.File.write(image_file, "") Session.set_file(session.pid, nil) # Wait for the session to deal with the files Process.sleep(500) assert {:ok, true} = FileSystem.File.exists?(image_file) %{images_dir: new_images_dir} = session assert {:ok, true} = FileSystem.File.exists?(FileSystem.File.resolve(new_images_dir, "test.jpg")) end end describe "save/1" do @tag :tmp_dir test "persists the notebook to the associated file and notifies subscribers", %{session: session, tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") Session.set_file(session.pid, file) # Perform a change, so the notebook is dirty Session.set_notebook_name(session.pid, "My notebook") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") assert {:ok, false} = FileSystem.File.exists?(file) Session.save(session.pid) assert_receive {:operation, {:mark_as_not_dirty, _}} assert {:ok, "# My notebook\n" <> _rest} = FileSystem.File.read(file) end @tag :tmp_dir test "creates nonexistent directories", %{session: session, tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "nonexistent/dir/notebook.livemd") Session.set_file(session.pid, file) # Perform a change, so the notebook is dirty Session.set_notebook_name(session.pid, "My notebook") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") assert {:ok, false} = FileSystem.File.exists?(file) Session.save(session.pid) assert_receive {:operation, {:mark_as_not_dirty, _}} assert {:ok, "# My notebook\n" <> _rest} = FileSystem.File.read(file) end end describe "close/1" do @tag :tmp_dir test "saves the notebook and notifies subscribers once the session is closed", %{session: session, tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") Session.set_file(session.pid, file) # Perform a change, so the notebook is dirty Session.set_notebook_name(session.pid, "My notebook") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") assert {:ok, false} = FileSystem.File.exists?(file) Process.flag(:trap_exit, true) # Calling twice can happen in a race, make sure it doesn't crash Session.close(session.pid) Session.close([session.pid]) assert_receive :session_closed assert {:ok, "# My notebook\n" <> _rest} = FileSystem.File.read(file) end test "clears session temporary directory", %{session: session} do %{images_dir: images_dir} = session :ok = FileSystem.File.create_dir(images_dir) assert {:ok, true} = FileSystem.File.exists?(images_dir) Process.flag(:trap_exit, true) Session.close(session.pid) # Wait for the session to deal with the files Process.sleep(50) assert {:ok, false} = FileSystem.File.exists?(images_dir) end end describe "start_link/1" do @tag :tmp_dir test "fails if the given path is already in use", %{tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") file = FileSystem.File.resolve(tmp_dir, "notebook.livemd") start_session(file: file) assert {:error, "the given file is already in use"} == Session.start_link(id: Utils.random_id(), file: file) end @tag :tmp_dir test "copies images when :copy_images_from option is specified", %{tmp_dir: tmp_dir} do tmp_dir = FileSystem.File.local(tmp_dir <> "/") image_file = FileSystem.File.resolve(tmp_dir, "image.jpg") :ok = FileSystem.File.write(image_file, "") session = start_session(copy_images_from: tmp_dir) %{images_dir: images_dir} = session assert {:ok, true} = FileSystem.File.exists?(FileSystem.File.resolve(images_dir, "image.jpg")) end test "saves images when :images option is specified" do images = %{"image.jpg" => "binary content"} session = start_session(images: images) %{images_dir: images_dir} = session assert FileSystem.File.resolve(images_dir, "image.jpg") |> FileSystem.File.read() == {:ok, "binary content"} end end # For most tests we use the lightweight embedded runtime, # so that they are cheap to run. Here go several integration # tests that actually start a Elixir standalone runtime (default in production) # to verify session integrates well with it properly. test "starts a standalone runtime upon first evaluation if there was none set explicitly" do session = start_session() Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") {_section_id, cell_id} = insert_section_and_cell(session.pid) Session.queue_cell_evaluation(session.pid, cell_id) # Give it a bit more time as this involves starting a system process. assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, _, %{evaluation_time_ms: _time_ms}}} end test "if the runtime node goes down, notifies the subscribers" do session = start_session() {:ok, runtime} = Runtime.ElixirStandalone.new() |> Runtime.connect() Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") # Wait for the runtime to be set Session.set_runtime(session.pid, runtime) assert_receive {:operation, {:set_runtime, _, ^runtime}} # Terminate the other node, the session should detect that Node.spawn(runtime.node, System, :halt, []) assert_receive {:operation, {:set_runtime, _, runtime}} refute Runtime.connected?(runtime) assert_receive {:info, "runtime node terminated unexpectedly"} end test "on user change sends an update operation subscribers", %{session: session} do user = Livebook.Users.User.new() Session.register_client(session.pid, self(), user) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") updated_user = %{user | name: "Jake Peralta"} Livebook.Users.broadcast_change(updated_user) assert_receive {:operation, {:update_user, _pid, ^updated_user}} end # Integration tests concerning input communication # between runtime and session @livebook_put_input_code """ input = %{id: "input1", type: :number, label: "Name", default: "hey"} send( Process.group_leader(), {:io_request, self(), make_ref(), {:livebook_put_output, {:input, input}}} ) """ @livebook_get_input_value_code """ ref = make_ref() send(Process.group_leader(), {:io_request, self(), ref, {:livebook_get_input_value, "input1"}}) receive do {:io_reply, ^ref, reply} -> reply end """ describe "user input" do test "replies to runtime input request" do input_code_cell = %{Notebook.Cell.new(:code) | source: @livebook_put_input_code} code_cell = %{Notebook.Cell.new(:code) | source: @livebook_get_input_value_code} notebook = %{ Notebook.new() | sections: [ %{Notebook.Section.new() | cells: [input_code_cell, code_cell]} ] } session = start_session(notebook: notebook) cell_id = code_cell.id Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") Session.queue_cell_evaluation(session.pid, cell_id) assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, {:text, text_output}, %{evaluation_time_ms: _time_ms}}} assert text_output =~ "hey" end test "replies with error when no matching input is found" do code_cell = %{Notebook.Cell.new(:code) | source: @livebook_get_input_value_code} notebook = %{ Notebook.new() | sections: [ %{Notebook.Section.new() | cells: [code_cell]} ] } session = start_session(notebook: notebook) cell_id = code_cell.id Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") Session.queue_cell_evaluation(session.pid, cell_id) assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, {:text, text_output}, %{evaluation_time_ms: _time_ms}}} assert text_output =~ ":error" end end describe "smart cells" do test "notifies subcribers when a smart cell starts and passes source diff as delta" do smart_cell = %{Notebook.Cell.new(:smart) | kind: "text", source: "content"} notebook = %{Notebook.new() | sections: [%{Notebook.Section.new() | cells: [smart_cell]}]} session = start_session(notebook: notebook) runtime = connected_noop_runtime() Session.set_runtime(session.pid, runtime) send( session.pid, {:runtime_smart_cell_definitions, [%{kind: "text", name: "Text", requirement: nil}]} ) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") send( session.pid, {:runtime_smart_cell_started, smart_cell.id, %{source: "content!", js_view: %{}, editor: nil}} ) delta = Delta.new() |> Delta.retain(7) |> Delta.insert("!") cell_id = smart_cell.id assert_receive {:operation, {:smart_cell_started, _, ^cell_id, ^delta, %{}, nil}} end test "sends an event to the smart cell server when the editor source changes" do smart_cell = %{Notebook.Cell.new(:smart) | kind: "text", source: ""} notebook = %{Notebook.new() | sections: [%{Notebook.Section.new() | cells: [smart_cell]}]} session = start_session(notebook: notebook) runtime = connected_noop_runtime() Session.set_runtime(session.pid, runtime) send( session.pid, {:runtime_smart_cell_definitions, [%{kind: "text", name: "Text", requirement: nil}]} ) server_pid = self() send( session.pid, {:runtime_smart_cell_started, smart_cell.id, %{ source: "content", js_view: %{ref: smart_cell.id, pid: server_pid, assets: %{}}, editor: %{language: nil, placement: :bottom, source: "content"} }} ) Session.register_client(session.pid, self(), Livebook.Users.User.new()) delta = Delta.new() |> Delta.retain(7) |> Delta.insert("!") Session.apply_cell_delta(session.pid, smart_cell.id, :secondary, delta, 1) assert_receive {:editor_source, "content!"} end end describe "find_base_locator/3" do test "given cell in main flow returns previous Code cell" do cell1 = %{Cell.new(:code) | id: "c1"} cell2 = %{Cell.new(:markdown) | id: "c2"} section1 = %{Section.new() | id: "s1", cells: [cell1, cell2]} cell3 = %{Cell.new(:code) | id: "c3"} section2 = %{Section.new() | id: "s2", cells: [cell3]} notebook = %{Notebook.new() | sections: [section1, section2]} data = Data.new(notebook) assert {:main_flow, "c1"} = Session.find_base_locator(data, cell3, section2) end test "given cell in branching section returns previous Code cell in that section" do section1 = %{Section.new() | id: "s1"} cell1 = %{Cell.new(:code) | id: "c1"} cell2 = %{Cell.new(:markdown) | id: "c2"} cell3 = %{Cell.new(:code) | id: "c3"} section2 = %{ Section.new() | id: "s2", parent_id: "s1", cells: [cell1, cell2, cell3] } notebook = %{Notebook.new() | sections: [section1, section2]} data = Data.new(notebook) assert {"s2", "c1"} = Session.find_base_locator(data, cell3, section2) end test "given cell in main flow returns nil if there is no previous cell" do %{setup_section: %{cells: [setup_cell]} = setup_section} = notebook = Notebook.new() data = Data.new(notebook) assert {:main_flow, nil} = Session.find_base_locator(data, setup_cell, setup_section) end test "when :existing is set ignores fresh and aborted cells" do cell1 = %{Cell.new(:code) | id: "c1"} cell2 = %{Cell.new(:code) | id: "c2"} section1 = %{Section.new() | id: "s1", cells: [cell1, cell2]} cell3 = %{Cell.new(:code) | id: "c3"} section2 = %{Section.new() | id: "s2", cells: [cell3]} notebook = %{Notebook.new() | sections: [section1, section2]} data = Data.new(notebook) assert {:main_flow, nil} = Session.find_base_locator(data, cell3, section2, existing: true) data = data_after_operations!(data, [ {:set_runtime, self(), connected_noop_runtime()}, {:queue_cells_evaluation, self(), ["c1"]}, {:add_cell_evaluation_response, self(), "setup", {:ok, nil}, %{evaluation_time_ms: 10}}, {:add_cell_evaluation_response, self(), "c1", {:ok, nil}, %{evaluation_time_ms: 10}} ]) assert {:main_flow, "c1"} = Session.find_base_locator(data, cell3, section2, existing: true) data = data_after_operations!(data, [ {:reflect_main_evaluation_failure, self()} ]) assert {:main_flow, nil} = Session.find_base_locator(data, cell3, section2, existing: true) end end test "session has created_at attribute when it is created", %{session: session} do assert Map.has_key?(session, :created_at) end test "session created_at attribute is a date time", %{session: session} do assert %DateTime{} = session.created_at end test "session created_at is before now", %{session: session} do assert DateTime.compare(session.created_at, DateTime.utc_now()) == :lt end @tag :tmp_dir test "session without a file is persisted to autosave path", %{tmp_dir: tmp_dir} do session = start_session(autosave_path: tmp_dir) notebook_glob = Path.join(tmp_dir, "**/*.livemd") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session.id}") Session.save(session.pid) assert_receive {:operation, {:mark_as_not_dirty, _}} assert [notebook_path] = Path.wildcard(notebook_glob) assert Path.basename(notebook_path) =~ "untitled_notebook" # After the name is changed we should save to a different file Session.set_notebook_name(session.pid, "Cat's guide to life") Session.save(session.pid) assert_receive {:operation, {:mark_as_not_dirty, _}} assert [notebook_path] = Path.wildcard(notebook_glob) assert Path.basename(notebook_path) =~ "cats_guide_to_life" end defp start_session(opts \\ []) do opts = Keyword.merge([id: Utils.random_id()], opts) pid = start_supervised!({Session, opts}, id: opts[:id]) Session.get_by_pid(pid) end defp insert_section_and_cell(session_pid) do Session.insert_section(session_pid, 0) assert_receive {:operation, {:insert_section, _, 0, section_id}} Session.insert_cell(session_pid, section_id, 0, :code) assert_receive {:operation, {:insert_cell, _, ^section_id, 0, :code, cell_id, _attrs}} {section_id, cell_id} end defp connected_noop_runtime() do {:ok, runtime} = Livebook.Runtime.NoopRuntime.new() |> Livebook.Runtime.connect() runtime end end
34.605425
98
0.655585
036c6d8ff38342e84b6dd0d610cc57939a37750b
966
exs
Elixir
spec/assertions/boolean/be_false_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
spec/assertions/boolean/be_false_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
spec/assertions/boolean/be_false_spec.exs
bblaszkow06/espec
4d9819ca5c68c6eb70276c7d9c9630ded01ba778
[ "Apache-2.0" ]
null
null
null
defmodule ESpec.Assertions.Boolean.BeFalseSpec do require CheckErrorSharedSpec use ESpec, async: true context "Success" do it "checks success with `to`" do message = expect(false).to(be_false()) expect(message) |> to(eq "`false` is false.") end it "checks success with `not_to`" do message = expect(1).to_not(be_false()) expect(message) |> to(eq "`1` is not false.") end end context "Errors" do context "with `to`" do before do {:shared, expectation: fn -> expect(true).to(be_false()) end, message: "Expected `true` to be false but it isn't."} end it_behaves_like(CheckErrorSharedSpec) end context "with `not_to`" do before do {:shared, expectation: fn -> expect(false).not_to(be_false()) end, message: "Expected `false` not to be false but it is."} end it_behaves_like(CheckErrorSharedSpec) end end end
24.769231
65
0.614907
036c7effef8bc61080a0d5b80b3ac7f8fbbe9cfb
2,042
exs
Elixir
test/guilda_web/live/podcast/podcast_episode_live_as_guest_test.exs
clcmo/GuildaEx
0e30fb8d9b7dfd54c35ae237329791003d6a46bf
[ "MIT" ]
10
2020-09-05T20:25:05.000Z
2022-01-28T14:02:36.000Z
test/guilda_web/live/podcast/podcast_episode_live_as_guest_test.exs
clcmo/GuildaEx
0e30fb8d9b7dfd54c35ae237329791003d6a46bf
[ "MIT" ]
11
2020-09-07T01:09:55.000Z
2022-02-06T00:58:48.000Z
test/guilda_web/live/podcast/podcast_episode_live_as_guest_test.exs
clcmo/GuildaEx
0e30fb8d9b7dfd54c35ae237329791003d6a46bf
[ "MIT" ]
3
2020-10-03T01:53:08.000Z
2022-01-28T14:03:09.000Z
defmodule GuildaWeb.PodcastEpisodeAsGuestLiveTest do use GuildaWeb.ConnCase, async: true import Phoenix.LiveViewTest import Guilda.PodcastsFixtures defp create_episode(_) do %{episode: insert(:episode)} end defp path(:index, assigns) do Routes.podcast_episode_index_path(assigns.conn, :index) end defp path(:new, assigns) do Routes.podcast_episode_index_path(assigns.conn, :new) end defp path(:edit, episode, assigns) do Routes.podcast_episode_index_path(assigns.conn, :edit, episode) end describe "index" do setup :create_episode test "list all podcast episodes", %{conn: conn, episode: episode} = opts do {:ok, _live, html} = live(conn, path(:index, opts)) assert html =~ "Quem Programa?, o podcast da Guilda" assert html =~ episode.title end test "does not display a button to add a new episode", %{conn: conn} = opts do {:ok, view, _html} = live(conn, path(:index, opts)) refute has_element?(view, "a[href='#{path(:new, opts)}']") end test "does not display a button to edit the episode", %{conn: conn, episode: episode} = opts do {:ok, view, _html} = live(conn, path(:index, opts)) refute has_element?(view, "a[href='#{path(:edit, episode, opts)}']") end test "does not display a button to delete the episode", %{conn: conn, episode: episode} = opts do {:ok, view, _html} = live(conn, path(:index, opts)) refute has_element?(view, "button[phx-click=delete][phx-value-id='#{episode.id}']") end end describe "adding a new episode" do test "redirects", %{conn: conn} = opts do podcast_index = path(:index, opts) assert {:error, {:live_redirect, %{to: ^podcast_index}}} = live(conn, path(:new, opts)) end end describe "editting an episode" do setup :create_episode test "redirects", %{conn: conn} = opts do podcast_index = path(:index, opts) assert {:error, {:live_redirect, %{to: ^podcast_index}}} = live(conn, path(:new, opts)) end end end
30.939394
101
0.656219
036cb250b19bda06c6127a29e871dbf225b8fbde
9
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_match_operation_parsing_test_case/Variable.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/parser_definition/matched_match_operation_parsing_test_case/Variable.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/parser_definition/matched_match_operation_parsing_test_case/Variable.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
one = two
9
9
0.666667
036ccdbcc7e700ec45553bcc7c6d353ad680dceb
479
ex
Elixir
lib/credo/test/source_files.ex
hrzndhrn/credo
71a7b24a5ca8e7a48416e0cdfb42cf8a0fef9593
[ "MIT" ]
4,590
2015-09-28T06:01:43.000Z
2022-03-29T08:48:57.000Z
lib/credo/test/source_files.ex
hrzndhrn/credo
71a7b24a5ca8e7a48416e0cdfb42cf8a0fef9593
[ "MIT" ]
890
2015-11-16T21:07:07.000Z
2022-03-29T08:52:07.000Z
lib/credo/test/source_files.ex
hrzndhrn/credo
71a7b24a5ca8e7a48416e0cdfb42cf8a0fef9593
[ "MIT" ]
479
2015-11-17T19:42:40.000Z
2022-03-29T00:09:21.000Z
defmodule Credo.Test.SourceFiles do def to_source_file(source) do filename = "test-untitled#{System.unique_integer()}.ex" to_source_file(source, filename) end def to_source_file(source, filename) do case Credo.SourceFile.parse(source, filename) do %{status: :valid} = source_file -> source_file _ -> raise "Source could not be parsed!" end end def to_source_files(list) do Enum.map(list, &to_source_file/1) end end
21.772727
59
0.678497
036d0933d5ac983bc6000d15c4fdcd99fb674ee1
67
ex
Elixir
apps/bookmarker/web/views/folder_view.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
apps/bookmarker/web/views/folder_view.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
apps/bookmarker/web/views/folder_view.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
null
null
null
defmodule Bookmarker.FolderView do use Bookmarker.Web, :view end
16.75
34
0.80597
036d0a77481ef84e5762d61c3d101b79cef13050
2,092
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_product_search_results_result.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_product_search_results_result.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_product_search_results_result.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.Vision.V1.Model.GoogleCloudVisionV1p4beta1ProductSearchResultsResult do @moduledoc """ Information about a product. ## Attributes * `image` (*type:* `String.t`, *default:* `nil`) - The resource name of the image from the product that is the closest match to the query. * `product` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1Product.t`, *default:* `nil`) - The Product. * `score` (*type:* `number()`, *default:* `nil`) - A confidence level on the match, ranging from 0 (no confidence) to 1 (full confidence). """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :image => String.t(), :product => GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1Product.t(), :score => number() } field(:image) field(:product, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1Product) field(:score) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1ProductSearchResultsResult do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1ProductSearchResultsResult.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1ProductSearchResultsResult do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.866667
128
0.730402
036d2569db69567f3e8536861b7173ca926674a1
1,915
exs
Elixir
clients/games_management/mix.exs
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/games_management/mix.exs
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/games_management/mix.exs
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.GamesManagement.Mixfile do use Mix.Project @version "0.17.1" def project() do [ app: :google_api_games_management, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/games_management" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Google Play Game Management client library. The Google Play Game Management API allows developers to manage resources from the Google Play Game service. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/games_management", "Homepage" => "https://developers.google.com/games/" } ] end end
28.58209
156
0.665274
036d449e71c0e645170e576d2ef71b361becae17
7,397
ex
Elixir
lib/oban/queue/executor.ex
jaimeiniesta/oban
4e7ca86371722762d5bd620a43dba6c8df7b2dde
[ "Apache-2.0" ]
null
null
null
lib/oban/queue/executor.ex
jaimeiniesta/oban
4e7ca86371722762d5bd620a43dba6c8df7b2dde
[ "Apache-2.0" ]
null
null
null
lib/oban/queue/executor.ex
jaimeiniesta/oban
4e7ca86371722762d5bd620a43dba6c8df7b2dde
[ "Apache-2.0" ]
null
null
null
defmodule Oban.Queue.Executor do @moduledoc false alias Oban.{ Breaker, Config, CrashError, Job, PerformError, Telemetry, TimeoutError, Worker } alias Oban.Queue.Engine require Logger @type success :: {:success, Job.t()} @type failure :: {:failure, Job.t(), Worker.t(), atom(), term()} @type t :: %__MODULE__{ conf: Config.t(), duration: pos_integer(), job: Job.t(), kind: any(), meta: map(), queue_time: integer(), result: term(), start_mono: integer(), start_time: integer(), stop_mono: integer(), worker: Worker.t(), safe: boolean(), snooze: pos_integer(), stacktrace: Exception.stacktrace(), state: :unset | :discard | :failure | :success | :snoozed } @enforce_keys [:conf, :job] defstruct [ :conf, :error, :job, :meta, :result, :snooze, :start_mono, :start_time, :stop_mono, :worker, safe: true, duration: 0, kind: :error, queue_time: 0, stacktrace: [], state: :unset ] @spec new(Config.t(), Job.t()) :: t() def new(%Config{} = conf, %Job{} = job) do struct!(__MODULE__, conf: conf, job: %{job | conf: conf}, meta: event_metadata(conf, job), start_mono: System.monotonic_time(), start_time: System.system_time() ) end @spec put(t(), :safe, boolean()) :: t() def put(%__MODULE__{} = exec, :safe, value) when is_boolean(value) do %{exec | safe: value} end @spec call(t()) :: :success | :failure def call(%__MODULE__{} = exec) do exec = exec |> record_started() |> resolve_worker() |> perform() |> record_finished() Breaker.with_retry(fn -> report_finished(exec).state end) end def record_started(%__MODULE__{} = exec) do Telemetry.execute([:oban, :job, :start], %{system_time: exec.start_time}, exec.meta) exec end @spec resolve_worker(t()) :: t() def resolve_worker(%__MODULE__{} = exec) do case Worker.from_string(exec.job.worker) do {:ok, worker} -> %{exec | worker: worker} {:error, error} -> unless exec.safe, do: raise(error) %{exec | state: :failure, error: error} end end @spec perform(t()) :: t() def perform(%__MODULE__{state: :unset} = exec) do case exec.worker.timeout(exec.job) do :infinity -> perform_inline(exec) timeout when is_integer(timeout) -> perform_timed(exec, timeout) end end def perform(%__MODULE__{} = exec), do: exec @spec record_finished(t()) :: t() def record_finished(%__MODULE__{} = exec) do stop_mono = System.monotonic_time() duration = stop_mono - exec.start_mono queue_time = DateTime.diff(exec.job.attempted_at, exec.job.scheduled_at, :nanosecond) %{exec | duration: duration, queue_time: queue_time, stop_mono: stop_mono} end @spec report_finished(t()) :: t() def report_finished(%__MODULE__{} = exec) do exec |> ack_event() |> emit_event() end @spec ack_event(t()) :: t() def ack_event(%__MODULE__{state: :success} = exec) do Engine.complete_job(exec.conf, exec.job) exec end def ack_event(%__MODULE__{state: :failure} = exec) do job = job_with_unsaved_error(exec) Engine.error_job(exec.conf, job, backoff(exec.worker, job)) %{exec | job: job} end def ack_event(%__MODULE__{state: :snoozed} = exec) do Engine.snooze_job(exec.conf, exec.job, exec.snooze) exec end def ack_event(%__MODULE__{state: :discard} = exec) do job = job_with_unsaved_error(exec) Engine.discard_job(exec.conf, job) %{exec | job: job} end @spec emit_event(t()) :: t() def emit_event(%__MODULE__{state: :failure} = exec) do measurements = %{duration: exec.duration, queue_time: exec.queue_time} meta = Map.merge(exec.meta, %{ job: exec.job, kind: exec.kind, error: exec.error, stacktrace: exec.stacktrace, state: exec.state }) Telemetry.execute([:oban, :job, :exception], measurements, meta) exec end def emit_event(%__MODULE__{state: state} = exec) when state in [:success, :snoozed, :discard] do measurements = %{duration: exec.duration, queue_time: exec.queue_time} meta = Map.merge(exec.meta, %{ job: exec.job, state: exec.state, result: exec.result }) Telemetry.execute([:oban, :job, :stop], measurements, meta) exec end defp perform_inline(%{safe: true} = exec) do perform_inline(%{exec | safe: false}) rescue error -> %{exec | state: :failure, error: error, stacktrace: __STACKTRACE__} catch kind, reason -> error = CrashError.exception({kind, reason, __STACKTRACE__}) %{exec | state: :failure, error: error, stacktrace: __STACKTRACE__} end defp perform_inline(%{worker: worker, job: job} = exec) do case worker.perform(job) do :ok -> %{exec | state: :success, result: :ok} {:ok, _value} = result -> %{exec | state: :success, result: result} :discard = result -> %{ exec | result: result, state: :discard, error: PerformError.exception({worker, :discard}) } {:discard, reason} = result -> %{ exec | result: result, state: :discard, error: PerformError.exception({worker, {:discard, reason}}) } {:error, reason} = result -> %{ exec | result: result, state: :failure, error: PerformError.exception({worker, {:error, reason}}) } {:snooze, seconds} = result when is_integer(seconds) and seconds > 0 -> %{exec | result: result, state: :snoozed, snooze: seconds} returned -> maybe_log_warning(exec, returned) %{exec | state: :success} end end defp perform_timed(exec, timeout) do task = Task.async(fn -> perform_inline(exec) end) case Task.yield(task, timeout) || Task.shutdown(task) do {:ok, reply} -> reply nil -> error = TimeoutError.exception({exec.worker, timeout}) %{exec | state: :failure, error: error} end end defp backoff(nil, job), do: Worker.backoff(job) defp backoff(worker, job), do: worker.backoff(job) defp event_metadata(conf, job) do job |> Map.take([:id, :args, :queue, :worker, :attempt, :max_attempts, :tags]) |> Map.put(:conf, conf) |> Map.put(:prefix, conf.prefix) end defp job_with_unsaved_error(%__MODULE__{} = exec) do unsaved_error = %{kind: exec.kind, reason: exec.error, stacktrace: exec.stacktrace} %{exec.job | unsaved_error: unsaved_error} end defp maybe_log_warning(exec, returned) defp maybe_log_warning(%__MODULE__{safe: false}, _returned), do: :noop defp maybe_log_warning(%__MODULE__{worker: worker}, returned) do Logger.warn(fn -> """ Expected #{worker}.perform/1 to return: - `:ok` - `:discard` - `{:ok, value}` - `{:error, reason}`, - `{:discard, reason}` - `{:snooze, seconds}` Instead received: #{inspect(returned, pretty: true)} The job will be considered a success. """ end) end end
24.332237
98
0.589023
036d4a7a98f3ffaf805ffb6bb8e0c896f974c6b0
11,055
exs
Elixir
test/elixir/test/security_validation_test.exs
denyadb/couchdb
ac33e853cef2a6a108aa64269eb196d32b235529
[ "Apache-2.0" ]
1
2020-09-11T19:23:27.000Z
2020-09-11T19:23:27.000Z
test/elixir/test/security_validation_test.exs
denyadb/couchdb
ac33e853cef2a6a108aa64269eb196d32b235529
[ "Apache-2.0" ]
null
null
null
test/elixir/test/security_validation_test.exs
denyadb/couchdb
ac33e853cef2a6a108aa64269eb196d32b235529
[ "Apache-2.0" ]
null
null
null
defmodule SecurityValidationTest do use CouchTestCase @moduletag :security @moduletag kind: :single_node @moduledoc """ Test CouchDB Security Validations This is a port of the security_validation.js suite """ @auth_headers %{ jerry: [ # jerry:mouse authorization: "Basic amVycnk6bW91c2U=" ], tom: [ # tom:cat authorization: "Basic dG9tOmNhdA==" ], spike_cat: [ # spike:cat - which is wrong authorization: "Basic c3Bpa2U6Y2F0" ] } @ddoc %{ _id: "_design/test", language: "javascript", validate_doc_update: ~s""" (function (newDoc, oldDoc, userCtx, secObj) { if (secObj.admin_override) { if (userCtx.roles.indexOf('_admin') != -1) { // user is admin, they can do anything return true; } } // docs should have an author field. if (!newDoc._deleted && !newDoc.author) { throw {forbidden: \"Documents must have an author field\"}; } if (oldDoc && oldDoc.author != userCtx.name) { throw {unauthorized: \"You are '\" + userCtx.name + \"', not the author '\" + oldDoc.author + \"' of this document. You jerk.\"}; } }) """ } setup_all do auth_db_name = random_db_name() {:ok, _} = create_db(auth_db_name) on_exit(fn -> delete_db(auth_db_name) end) configs = [ {"httpd", "authentication_handlers", "{couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}"}, {"couch_httpd_auth", "authentication_db", auth_db_name}, {"chttpd_auth", "authentication_db", auth_db_name} ] Enum.each(configs, &set_config/1) # port of comment from security_validation.js # the special case handler does not exist (any longer) in clusters, so we have # to replicate the behavior using a "normal" DB even though tests might no more # run universally (why the "X-Couch-Test-Auth" header was introduced). # btw: this needs to be INSIDE configured server to propagate correctly ;-) # At least they'd run in the build, though users = [{"tom", "cat"}, {"jerry", "mouse"}, {"spike", "dog"}] Enum.each(users, fn {name, pass} -> doc = %{ :_id => "org.couchdb.user:#{name}", :name => name, :roles => [], :password => pass } assert Couch.post("/#{auth_db_name}", body: doc).body["ok"] end) {:ok, [auth_db_name: auth_db_name]} end @tag :with_db_name test "Saving document using the wrong credentials", context do # spike:cat - which is wrong headers = @auth_headers[:spike_cat] resp = Couch.post("/#{context[:db_name]}", body: %{foo: 1}, headers: headers) assert resp.body["error"] == "unauthorized" assert resp.status_code == 401 end test "Force basic login" do # spike:cat - which is wrong headers = @auth_headers[:spike_cat] resp = Couch.get("/_session", query: %{basic: true}, headers: headers) assert resp.status_code == 401 assert resp.body["error"] == "unauthorized" end @tag :with_db test "Jerry can save a document normally", context do headers = @auth_headers[:jerry] assert Couch.get("/_session", headers: headers).body["userCtx"]["name"] == "jerry" doc = %{_id: "testdoc", foo: 1, author: "jerry"} assert Couch.post("/#{context[:db_name]}", body: doc).body["ok"] end @tag :with_db test "Non-admin user cannot save a ddoc", context do headers = @auth_headers[:jerry] resp = Couch.post("/#{context[:db_name]}", body: @ddoc, headers: headers) assert resp.status_code == 403 assert resp.body["error"] == "forbidden" end @tag :with_db test "Ddoc writes with admin and replication contexts", context do db_name = context[:db_name] sec_obj = %{admins: %{names: ["jerry"]}} assert Couch.put("/#{db_name}/_security", body: sec_obj).body["ok"] assert Couch.post("/#{db_name}", body: @ddoc).body["ok"] new_rev = "2-642e20f96624a0aae6025b4dba0c6fb2" ddoc = @ddoc |> Map.put(:_rev, new_rev) |> Map.put(:foo, "bar") headers = @auth_headers[:tom] # attempt to save doc in replication context, eg ?new_edits=false resp = Couch.put( "/#{db_name}/#{ddoc[:_id]}", body: ddoc, headers: headers, query: %{new_edits: false} ) assert resp.status_code == 403 assert resp.body["error"] == "forbidden" end test "_session API" do headers = @auth_headers[:jerry] resp = Couch.get("/_session", headers: headers) assert resp.body["userCtx"]["name"] == "jerry" assert resp.body["userCtx"]["roles"] == [] end @tag :with_db test "Author presence and user security", context do db_name = context[:db_name] sec_obj = %{admin_override: false, admins: %{names: ["jerry"]}} jerry = @auth_headers[:jerry] tom = @auth_headers[:tom] assert Couch.put("/#{db_name}/_security", body: sec_obj).body["ok"] assert Couch.post("/#{db_name}", body: @ddoc).body["ok"] retry_until(fn -> resp = Couch.put("/#{db_name}/test_doc", body: %{foo: 1}, headers: jerry) assert resp.status_code == 403 assert resp.body["error"] == "forbidden" assert resp.body["reason"] == "Documents must have an author field" end) # Jerry can write the document assert Couch.put( "/#{db_name}/test_doc", body: %{foo: 1, author: "jerry"}, headers: jerry ).body["ok"] test_doc = Couch.get("/#{db_name}/test_doc").body # Tom cannot write the document resp = Couch.post("/#{db_name}", body: %{foo: 1}, headers: tom) assert resp.status_code == 403 assert resp.body["error"] == "forbidden" # Enable admin override for changing author values assert Couch.put("/#{db_name}/_security", body: %{sec_obj | admin_override: true}).body[ "ok" ] # Change owner to Tom test_doc = Map.put(test_doc, "author", "tom") resp = Couch.put("/#{db_name}/test_doc", body: test_doc) assert resp.body["ok"] test_doc = Map.put(test_doc, "_rev", resp.body["rev"]) # Now Tom can update the document test_doc = Map.put(test_doc, "foo", "asdf") resp = Couch.put("/#{db_name}/test_doc", body: test_doc, headers: tom) assert resp.body["ok"] test_doc = Map.put(test_doc, "_rev", resp.body["rev"]) # Jerry can't delete it retry_until(fn -> opts = [headers: jerry] resp = Couch.delete("/#{db_name}/test_doc?rev=#{test_doc["_rev"]}", opts) resp.status_code == 401 and resp.body["error"] == "unauthorized" end) end end # TODO: port remainder of security_validation.js suite # remaining bits reproduced below: # # // try to do something lame # try { # db.setDbProperty("_security", ["foo"]); # T(false && "can't do this"); # } catch(e) {} # # // go back to normal # T(db.setDbProperty("_security", {admin_override : false}).ok); # # // Now delete document # T(user2Db.deleteDoc(doc).ok); # # // now test bulk docs # var docs = [{_id:"bahbah",author:"jerry",foo:"bar"},{_id:"fahfah",foo:"baz"}]; # # // Create the docs # var results = db.bulkSave(docs); # # T(results[0].rev) # T(results[0].error == undefined) # T(results[1].rev === undefined) # T(results[1].error == "forbidden") # # T(db.open("bahbah")); # T(db.open("fahfah") == null); # # # // now all or nothing with a failure - no more available on cluster # /* var docs = [ # {_id:"booboo",author:"Damien Katz",foo:"bar"},{_id:"foofoo",foo:"baz"} # ]; # # // Create the docs # var results = db.bulkSave(docs, {all_or_nothing:true}); # # T(results.errors.length == 1); # T(results.errors[0].error == "forbidden"); # T(db.open("booboo") == null); # T(db.open("foofoo") == null); # */ # # // Now test replication # var AuthHeaders = {"Authorization": "Basic c3Bpa2U6ZG9n"}; // spike # adminDbA = new CouchDB("" + db_name + "_a", {"X-Couch-Full-Commit":"false"}); # adminDbB = new CouchDB("" + db_name + "_b", {"X-Couch-Full-Commit":"false"}); # var dbA = new CouchDB("" + db_name + "_a", AuthHeaders); # var dbB = new CouchDB("" + db_name + "_b", AuthHeaders); # // looping does not really add value as the scenario is the same anyway # // (there's nothing 2 be gained from it) # var A = CouchDB.protocol + CouchDB.host + "/" + db_name + "_a"; # var B = CouchDB.protocol + CouchDB.host + "/" + db_name + "_b"; # # // (the databases never exist b4 - and we made sure they're deleted below) # //adminDbA.deleteDb(); # adminDbA.createDb(); # //adminDbB.deleteDb(); # adminDbB.createDb(); # # // save and replicate a documents that will and will not pass our design # // doc validation function. # T(dbA.save({_id:"foo1",value:"a",author:"tom"}).ok); # T(dbA.save({_id:"foo2",value:"a",author:"spike"}).ok); # T(dbA.save({_id:"bad1",value:"a"}).ok); # # T(CouchDB.replicate(A, B, {headers:AuthHeaders}).ok); # T(CouchDB.replicate(B, A, {headers:AuthHeaders}).ok); # # T(dbA.open("foo1")); # T(dbB.open("foo1")); # T(dbA.open("foo2")); # T(dbB.open("foo2")); # # // save the design doc to dbA # delete designDoc._rev; // clear rev from previous saves # T(adminDbA.save(designDoc).ok); # # // no affect on already saved docs # T(dbA.open("bad1")); # # // Update some docs on dbB. Since the design hasn't replicated, anything # // is allowed. # # // this edit will fail validation on replication to dbA (no author) # T(dbB.save({_id:"bad2",value:"a"}).ok); # # // this edit will fail security on replication to dbA (wrong author # // replicating the change) # var foo1 = dbB.open("foo1"); # foo1.value = "b"; # T(dbB.save(foo1).ok); # # // this is a legal edit # var foo2 = dbB.open("foo2"); # foo2.value = "b"; # T(dbB.save(foo2).ok); # # var results = CouchDB.replicate({"url": B, "headers": AuthHeaders}, # {"url": A, "headers": AuthHeaders}, {headers:AuthHeaders}); # T(results.ok); # TEquals(1, results.history[0].docs_written); # TEquals(2, results.history[0].doc_write_failures); # # // bad2 should not be on dbA # T(dbA.open("bad2") == null); # # // The edit to foo1 should not have replicated. # T(dbA.open("foo1").value == "a"); # # // The edit to foo2 should have replicated. # T(dbA.open("foo2").value == "b"); # }); # # // cleanup # db.deleteDb(); # if(adminDbA){ # adminDbA.deleteDb(); # } # if(adminDbB){ # adminDbB.deleteDb(); # } # authDb.deleteDb(); # // have to clean up authDb on the backside :( # var req = CouchDB.newXhr(); # req.open("DELETE", "http://127.0.0.1:15986/" + authDb_name, false); # req.send(""); # CouchDB.maybeThrowError(req); # };
32.514706
124
0.593578
036d52eafa2bd045ef68ab8eb0d238f6df2e8030
1,711
ex
Elixir
lib/credo/cli/command/list/list_output.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
null
null
null
lib/credo/cli/command/list/list_output.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
null
null
null
lib/credo/cli/command/list/list_output.ex
codeclimate-community/credo
b960a25d604b4499a2577321f9d61b39dc4b0437
[ "MIT" ]
1
2020-09-25T11:48:49.000Z
2020-09-25T11:48:49.000Z
defmodule Credo.CLI.Command.List.ListOutput do @moduledoc false use Credo.CLI.Output.FormatDelegator, default: Credo.CLI.Command.List.Output.Default, flycheck: Credo.CLI.Command.List.Output.FlyCheck, oneline: Credo.CLI.Command.List.Output.Oneline, json: Credo.CLI.Command.List.Output.Json alias Credo.CLI.Output.UI def print_help(exec) do usage = ["Usage: ", :olive, "mix credo list [paths] [options]"] description = """ Lists objects that Credo thinks can be improved ordered by their priority. """ example = [ "Example: ", :olive, :faint, "$ mix credo list lib/**/*.ex --format=oneline" ] options = """ Arrows (↑ ↗ → ↘ ↓) hint at the importance of an issue. List options: -a, --all Show all issues -A, --all-priorities Show all issues including low priority ones --min-priority Minimum priority to show issues (high,medium,normal,low,lower or number) -c, --checks Only include checks that match the given strings --config-file Use the given config file -C, --config-name Use the given config instead of "default" -i, --ignore-checks Ignore checks that match the given strings --format Display the list in a specific format (oneline,flycheck) --mute-exit-status Exit with status zero even if there are issues General options: --[no-]color Toggle colored output -v, --version Show version -h, --help Show this help """ UI.puts(usage) UI.puts(description) UI.puts(example) UI.puts(options) exec end end
30.553571
102
0.613676
036da3ca5da28cdf530ccb9d3440e8ce4853db16
239
exs
Elixir
config/prod.exs
Angarsk8/todoapp_cowboy_elixir
38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd
[ "MIT" ]
134
2017-03-28T14:47:37.000Z
2021-11-25T10:40:15.000Z
config/prod.exs
Angarsk8/todoapp_cowboy_elixir
38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd
[ "MIT" ]
5
2017-03-30T05:56:55.000Z
2018-01-17T09:22:51.000Z
config/prod.exs
Angarsk8/todoapp_cowboy_elixir
38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd
[ "MIT" ]
14
2017-03-28T17:04:31.000Z
2021-08-07T07:09:21.000Z
use Mix.Config config :todo_app, http: [port: {:system, "PORT", 80}] config :logger, level: :info config :todo_app, TodoApp.Repo, adapter: Ecto.Adapters.Postgres, url: {:system, "DB_URL"}, pool_size: {:system, "DB_POOL_SIZE", 20}
21.727273
53
0.682008
036de9666a1903b5d634b6e8276a1127b202e961
399
ex
Elixir
apps/mishka_user/lib/guardian/auth_error_handler.ex
mojtaba-naserei/mishka-cms
1f31f61347bab1aae6ba0d47c5515a61815db6c9
[ "Apache-2.0" ]
35
2021-06-26T09:05:50.000Z
2022-03-30T15:41:22.000Z
apps/mishka_user/lib/guardian/auth_error_handler.ex
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
101
2021-01-01T09:54:07.000Z
2022-03-28T10:02:24.000Z
apps/mishka_user/lib/guardian/auth_error_handler.ex
iArazar/mishka-cms
8b579101d607d91e80834527c1508fe5f4ceefef
[ "Apache-2.0" ]
8
2021-01-17T17:08:07.000Z
2022-03-11T16:12:06.000Z
defmodule MishkaUser.AuthErrorHandler do import Plug.Conn @behaviour Guardian.Plug.ErrorHandler @impl Guardian.Plug.ErrorHandler def auth_error(conn, {type, _reason}, _opts) do body = Jason.encode!(%{ action: :access_token, system: :user, message: to_string(type) }) conn |> put_resp_content_type("application/json") |> send_resp(401, body) end end
22.166667
49
0.681704
036df94ae43dec9a284479a750756fd0d0fc8060
291
exs
Elixir
test/quatern/quatern_pitch_test.exs
crertel/graphmath
798e51d21d509e397a86d9ca855ef18a92243583
[ "Unlicense" ]
70
2015-01-07T10:13:38.000Z
2021-09-29T05:06:14.000Z
test/quatern/quatern_pitch_test.exs
crertel/graphmath
798e51d21d509e397a86d9ca855ef18a92243583
[ "Unlicense" ]
28
2015-01-22T22:38:24.000Z
2021-06-24T06:15:38.000Z
test/quatern/quatern_pitch_test.exs
crertel/graphmath
798e51d21d509e397a86d9ca855ef18a92243583
[ "Unlicense" ]
17
2015-01-22T18:35:41.000Z
2020-12-24T22:42:40.000Z
defmodule GraphmathTest.Quatern.PitchQuatern do use ExUnit.Case @tag :quatern @tag :get_pitch # values obtained through another calculator test "get_pitch({5,6,7,8}) returns 2.428842693496242" do assert 2.428842693496242 == Graphmath.Quatern.get_pitch({5, 6, 7, 8}) end end
26.454545
73
0.738832
036e16258b852447492f9064bbad91411f9357f8
853
ex
Elixir
exercism/elixir/bread-and-potions/lib/rpg.ex
Tyyagoo/studies
f8fcc3a539cfb6d04a149174c88bf2208e220b96
[ "Unlicense" ]
null
null
null
exercism/elixir/bread-and-potions/lib/rpg.ex
Tyyagoo/studies
f8fcc3a539cfb6d04a149174c88bf2208e220b96
[ "Unlicense" ]
null
null
null
exercism/elixir/bread-and-potions/lib/rpg.ex
Tyyagoo/studies
f8fcc3a539cfb6d04a149174c88bf2208e220b96
[ "Unlicense" ]
null
null
null
defmodule RPG do defmodule Character do defstruct health: 100, mana: 0 end defmodule LoafOfBread do defstruct [] end defmodule ManaPotion do defstruct strength: 10 end defmodule Poison do defstruct [] end defmodule EmptyBottle do defstruct [] end defprotocol Edible do def eat(item, character) end defimpl Edible, for: LoafOfBread do def eat(_, %Character{health: health} = character) do {nil, %Character{character | health: health + 5}} end end defimpl Edible, for: ManaPotion do def eat(%ManaPotion{strength: str}, %Character{mana: mana} = character) do {%EmptyBottle{}, %Character{character | mana: mana + str}} end end defimpl Edible, for: Poison do def eat(_, character) do {%EmptyBottle{}, %Character{character | health: 0}} end end end
19.386364
78
0.662368
036e4ba0289da4f978f961227eccd9b08acca0b0
4,734
ex
Elixir
lib/rostrum2/accounts/user.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
null
null
null
lib/rostrum2/accounts/user.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
3
2021-11-25T05:44:03.000Z
2021-11-26T06:33:53.000Z
lib/rostrum2/accounts/user.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
null
null
null
defmodule Rostrum.Accounts.User do use Ecto.Schema import Ecto.Changeset alias Rostrum.Accounts.Unit @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id schema "users" do field :email, :string field :password, :string, virtual: true, redact: true field :hashed_password, :string, redact: true field :confirmed_at, :naive_datetime belongs_to :unit, Unit field :role, :string, default: "base" timestamps() end @doc """ A user changeset for registration. It is important to validate the length of both email and password. Otherwise databases may truncate the email without warnings, which could lead to unpredictable or insecure behaviour. Long passwords may also be very expensive to hash for certain algorithms. ## Options * `:hash_password` - Hashes the password so it can be stored securely in the database and ensures the password field is cleared to prevent leaks in the logs. If password hashing is not needed and clearing the password field is not desired (like when using this changeset for validations on a LiveView form), this option can be set to `false`. Defaults to `true`. """ def registration_changeset(user, attrs, opts \\ []) do user |> cast(attrs, [:email, :password]) |> validate_email() |> validate_password(opts) end defp validate_email(changeset) do changeset |> validate_required([:email]) |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces") |> validate_length(:email, max: 160) |> unsafe_validate_unique(:email, Rostrum.Repo) |> unique_constraint(:email) end defp validate_password(changeset, opts) do changeset |> validate_required([:password]) |> validate_length(:password, min: 12, max: 72) # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character") # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character") # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character") |> maybe_hash_password(opts) end defp maybe_hash_password(changeset, opts) do hash_password? = Keyword.get(opts, :hash_password, true) password = get_change(changeset, :password) if hash_password? && password && changeset.valid? do changeset # If using Bcrypt, then further validate it is at most 72 bytes long |> validate_length(:password, max: 72, count: :bytes) |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) |> delete_change(:password) else changeset end end @doc """ A user changeset for changing the email. It requires the email to change otherwise an error is added. """ def email_changeset(user, attrs) do user |> cast(attrs, [:email]) |> validate_email() |> case do %{changes: %{email: _}} = changeset -> changeset %{} = changeset -> add_error(changeset, :email, "did not change") end end @doc """ A user changeset for changing the password. ## Options * `:hash_password` - Hashes the password so it can be stored securely in the database and ensures the password field is cleared to prevent leaks in the logs. If password hashing is not needed and clearing the password field is not desired (like when using this changeset for validations on a LiveView form), this option can be set to `false`. Defaults to `true`. """ def password_changeset(user, attrs, opts \\ []) do user |> cast(attrs, [:password]) |> validate_confirmation(:password, message: "does not match password") |> validate_password(opts) end @doc """ Confirms the account by setting `confirmed_at`. """ def confirm_changeset(user) do now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) change(user, confirmed_at: now) end @doc """ Verifies the password. If there is no user or the user doesn't have a password, we call `Bcrypt.no_user_verify/0` to avoid timing attacks. """ def valid_password?(%Rostrum.Accounts.User{hashed_password: hashed_password}, password) when is_binary(hashed_password) and byte_size(password) > 0 do Bcrypt.verify_pass(password, hashed_password) end def valid_password?(_, _) do Bcrypt.no_user_verify() false end @doc """ Validates the current password otherwise adds an error to the changeset. """ def validate_current_password(changeset, password) do if valid_password?(changeset.data, password) do changeset else add_error(changeset, :current_password, "is not valid") end end end
32.204082
112
0.686946
036e5ec2b206c2593c009233fbad7695b350fdda
178
exs
Elixir
priv/repo/migrations/20210602181317_create_authors.exs
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
12
2021-09-30T20:51:49.000Z
2022-01-27T04:09:32.000Z
priv/repo/migrations/20210602181317_create_authors.exs
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
76
2021-10-01T05:45:11.000Z
2022-03-28T04:12:39.000Z
priv/repo/migrations/20210602181317_create_authors.exs
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
2
2021-10-04T19:27:28.000Z
2022-01-13T22:36:38.000Z
defmodule Ambry.Repo.Migrations.CreateAuthors do use Ecto.Migration def change do create table(:authors) do timestamps() add :name, :text end end end
14.833333
48
0.674157
036e6e697ce99d9ba919a94119b1d5a496718cbb
1,412
ex
Elixir
lib/elasticsearch/storage/document.ex
steffkes/elasticsearch-elixir
ce904e5dea959a5caefe2cde15669bba43ac3fa6
[ "MIT" ]
null
null
null
lib/elasticsearch/storage/document.ex
steffkes/elasticsearch-elixir
ce904e5dea959a5caefe2cde15669bba43ac3fa6
[ "MIT" ]
null
null
null
lib/elasticsearch/storage/document.ex
steffkes/elasticsearch-elixir
ce904e5dea959a5caefe2cde15669bba43ac3fa6
[ "MIT" ]
null
null
null
defprotocol Elasticsearch.Document do @moduledoc """ A protocol for converting a struct into an Elasticsearch document. ## Example defimpl Elasticsearch.Document, for: MyStruct do def id(struct), do: struct.id def type(_struct), do: "struct" def parent(_struct), do: false def encode(struct) do %{ id: struct.id, name: struct.name } end end """ @doc """ Returns the Elasticsearch `_id` for the item. ## Example def id(item), do: item.id """ @spec id(any) :: any def id(item) @doc """ Returns the Elasticsearch `_type` for the object. ## Example def type(_item), do: "item" """ @spec type(any) :: String.t() def type(item) @doc """ Returns the parent ID of the document, or `false` if there is no parent. ## Examples # For structs that have parents def parent(%{parent_id: id}) when id != nil, do: id # For structs that don't have parents def parent(_item), do: false """ @spec parent(any) :: false | any def parent(item) @doc """ Returns a map of fields, which will be converted to JSON and stored in Elasticsearch as a document. ## Example def encode(item) do %{ title: item.title, author: item.author } end """ @spec encode(any) :: map def encode(item) end
20.171429
74
0.580028
036e839a887b082d2ef5b37ca2264387d1152d51
3,755
ex
Elixir
generated-sources/elixir/mojang-status/lib/com/github/asyncmc/mojang/status/elixir/server/request_builder.ex
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/elixir/mojang-status/lib/com/github/asyncmc/mojang/status/elixir/server/request_builder.ex
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/elixir/mojang-status/lib/com/github/asyncmc/mojang/status/elixir/server/request_builder.ex
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule com.github.asyncmc.mojang.status.elixir.server.RequestBuilder do @moduledoc """ Helper functions for building Tesla requests """ @doc """ Specify the request method when building a request ## Parameters - request (Map) - Collected request options - m (atom) - Request method ## Returns Map """ @spec method(map(), atom) :: map() def method(request, m) do Map.put_new(request, :method, m) end @doc """ Specify the request method when building a request ## Parameters - request (Map) - Collected request options - u (String) - Request URL ## Returns Map """ @spec url(map(), String.t) :: map() def url(request, u) do Map.put_new(request, :url, u) end @doc """ Add optional parameters to the request ## Parameters - request (Map) - Collected request options - definitions (Map) - Map of parameter name to parameter location. - options (KeywordList) - The provided optional parameters ## Returns Map """ @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map() def add_optional_params(request, _, []), do: request def add_optional_params(request, definitions, [{key, value} | tail]) do case definitions do %{^key => location} -> request |> add_param(location, key, value) |> add_optional_params(definitions, tail) _ -> add_optional_params(request, definitions, tail) end end @doc """ Add optional parameters to the request ## Parameters - request (Map) - Collected request options - location (atom) - Where to put the parameter - key (atom) - The name of the parameter - value (any) - The value of the parameter ## Returns Map """ @spec add_param(map(), atom, atom, any()) :: map() def add_param(request, :body, :body, value), do: Map.put(request, :body, value) def add_param(request, :body, key, value) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) |> Map.update!(:body, &(Tesla.Multipart.add_field(&1, key, Poison.encode!(value), headers: [{:"Content-Type", "application/json"}]))) end def add_param(request, :headers, key, value) do request |> Map.update(:headers, %{key => value}, &(Map.put(&1, key, value))) end def add_param(request, :file, name, path) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) |> Map.update!(:body, &(Tesla.Multipart.add_file(&1, path, name: name))) end def add_param(request, :form, name, value) do request |> Map.update(:body, %{name => value}, &(Map.put(&1, name, value))) end def add_param(request, location, key, value) do Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}])) end @doc """ Handle the response for a Tesla request ## Parameters - arg1 (Tesla.Env.t | term) - The response object - arg2 (:false | struct | [struct]) - The shape of the struct to deserialize into ## Returns {:ok, struct} on success {:error, term} on failure """ @spec decode(Tesla.Env.t | term()) :: {:ok, struct()} | {:error, Tesla.Env.t} | {:error, term()} def decode(%Tesla.Env{status: 200, body: body}), do: Poison.decode(body) def decode(response), do: {:error, response} @spec decode(Tesla.Env.t | term(), :false | struct() | [struct()]) :: {:ok, struct()} | {:error, Tesla.Env.t} | {:error, term()} def decode(%Tesla.Env{status: 200} = env, false), do: {:ok, env} def decode(%Tesla.Env{status: 200, body: body}, struct), do: Poison.decode(body, as: struct) def decode(response, _struct), do: {:error, response} end
28.884615
137
0.643675
036eeed619774c3a8921b1c2a4c2d7fb476e9725
650
ex
Elixir
apps/blunt_data/lib/blunt/data/factories/values/build.ex
blunt-elixir/blunt
a88b88984022db7ba2110204248fdb541121e3a0
[ "MIT" ]
1
2022-03-07T11:54:47.000Z
2022-03-07T11:54:47.000Z
apps/blunt_data/lib/blunt/data/factories/values/build.ex
elixir-cqrs/cqrs_tools
afbf82da522a10d2413547a46f316ed3aadebba5
[ "MIT" ]
null
null
null
apps/blunt_data/lib/blunt/data/factories/values/build.ex
elixir-cqrs/cqrs_tools
afbf82da522a10d2413547a46f316ed3aadebba5
[ "MIT" ]
null
null
null
defmodule Blunt.Data.Factories.Values.Build do @moduledoc false defstruct [:field, :factory_name] alias Blunt.Data.Factories.Factory alias Blunt.Data.Factories.Values.Build defimpl Blunt.Data.Factories.Value do def evaluate(%Build{field: field, factory_name: factory_name}, acc, current_factory) do factory_name = String.to_existing_atom("#{factory_name}_factory") value = apply(current_factory.factory_module, factory_name, [acc]) value = Factory.log_value(current_factory, value, field, false, "child") Map.put(acc, field, value) end def declared_props(%Build{field: field}), do: [field] end end
32.5
91
0.733846
036f46d975f48caa264416efe88ccaa5e8b98422
7,097
ex
Elixir
lib/bitcoin/tx/tx_maker.ex
coinscript/bitcoinsv-elixir
2dda03c81edc5662743ed2922abb5b1910d9c09a
[ "Apache-2.0" ]
2
2019-08-12T04:53:57.000Z
2019-09-03T03:47:33.000Z
lib/bitcoin/tx/tx_maker.ex
coinscript/bitcoinsv-elixir
2dda03c81edc5662743ed2922abb5b1910d9c09a
[ "Apache-2.0" ]
null
null
null
lib/bitcoin/tx/tx_maker.ex
coinscript/bitcoinsv-elixir
2dda03c81edc5662743ed2922abb5b1910d9c09a
[ "Apache-2.0" ]
null
null
null
defmodule Bitcoin.Tx.TxMaker do alias Bitcoin.Base58Check alias Bitcoin.Protocol.Types.VarInteger alias Bitcoin.Key alias Bitcoin.Crypto require Logger defmodule Resource do def utxos(addr) do {:ok, data} = SvApi.Bitindex.utxos(addr) utxos = for d <- data do %{ txid: d["txid"], txindex: d["vout"], amount: d["value"], script: d["scriptPubKey"] } end utxos end # def balance(_addr) do # # TODO # 0 # end end def broadcast(hex) do txid = get_txid_from_raw_tx(hex) %{ txid: txid, result: SvApi.Bitindex.broadcast(hex) } end def get_txid_from_raw_tx(hex) do Crypto.double_sha256(Binary.from_hex(hex)) |> Binary.reverse() |> Binary.to_hex() end def address_to_public_key_hash(addr) do {:ok, <<_prefix::bytes-size(1), pubkeyhash::binary>>} = Base58Check.decode(addr) pubkeyhash end def len(x) when is_binary(x), do: byte_size(x) def len(x) when is_list(x), do: length(x) def to_bytes(x, size, endian \\ :big) when is_integer(x) do s = 8 * size case endian do :big -> <<x::size(s)-big>> :little -> <<x::size(s)-little>> end end def scriptcode(private_key) do pkhash = Key.privkey_to_pubkey_hash(private_key) [ 0x76, 0xA9, 0x14, pkhash, 0x88, 0xAC ] |> join() end def int_to_varint(x) do VarInteger.serialize(x) end def hex_to_bytes(hex) do Binary.from_hex(hex) end def bytes_to_hex(b), do: Binary.to_hex(b) def double_sha256(x) do x |> sha256() |> sha256() end def sha256(x), do: :crypto.hash(:sha256, x) def join(list), do: IO.iodata_to_binary(list) def construct_input_block(inputs) do for txin <- inputs do join([ txin.txid, txin.txindex, txin.script_len, txin.script, sequence() ]) end |> join() end def construct_output_block(outputs) do Enum.map(outputs, fn output -> script = case output do {dest, amount} -> [ 0x76, 0xA9, 0x14, address_to_public_key_hash(dest), 0x88, 0xAC ] |> join() ## what is "safe" type: https://blog.moneybutton.com/2019/08/02/money-button-now-supports-safe-on-chain-data/ %{type: "safe", data: data} -> safe_type_pkscript(data) %{type: "script", script: script} -> script end amount = case output do {_dest, amount} -> amount %{type: "safe"} -> 0 %{type: "script"} -> 0 end [ amount |> to_bytes(8, :little), int_to_varint(len(script)), script ] end) |> join() end def safe_type_pkscript(data) do data = if is_list(data), do: data, else: [data] [ 0, 106, for(x <- data, do: [byte_size(x) |> op_push(), x]) |> IO.inspect() ] |> join() end def op_push(size) when size <= 75, do: size def op_push(size) do bytes = :binary.encode_unsigned size, :little case byte_size(bytes) do 1 -> [0x4c, bytes] 2 -> [0x4d, bytes] _ -> [0x4e, Binary.pad_trailing(bytes, 4)] end end def newTxIn(script, script_len, txid, txindex, amount) do %{ script: script, script_len: script_len, txid: txid, txindex: txindex, amount: amount } end def sequence(), do: 0xFFFFFFFF |> to_bytes(4, :little) def create_p2pkh_transaction(private_key, unspents, outputs) do public_key = Key.privkey_to_pubkey(private_key) public_key_len = len(public_key) |> to_bytes(1, :little) scriptCode = scriptcode(private_key) scriptCode_len = int_to_varint(len(scriptCode)) version = 0x01 |> to_bytes(4, :little) sequence = sequence() lock_time = 0x00 |> to_bytes(4, :little) hash_type = 0x41 |> to_bytes(4, :little) input_count = int_to_varint(len(unspents)) output_count = int_to_varint(len(outputs)) output_block = construct_output_block(outputs) inputs = for unspent <- unspents do script = hex_to_bytes(unspent.script) script_len = int_to_varint(len(script)) txid = hex_to_bytes(unspent.txid) |> Binary.reverse() txindex = unspent.txindex |> to_bytes(4, :little) amount = unspent.amount |> to_bytes(8, :little) newTxIn(script, script_len, txid, txindex, amount) end hashPrevouts = double_sha256(join(for i <- inputs, do: [i.txid, i.txindex])) hashSequence = double_sha256(join(for _i <- inputs, do: sequence)) hashOutputs = double_sha256(output_block) inputs = for txin <- inputs do to_be_hashed = join([ version, hashPrevouts, hashSequence, txin.txid, txin.txindex, scriptCode_len, scriptCode, txin.amount, sequence, hashOutputs, lock_time, hash_type ]) hashed = sha256(to_be_hashed) signature = Crypto.sign(private_key, hashed) <> <<0x41>> script_sig = join([ len(signature) |> to_bytes(1, :little), signature, public_key_len, public_key ]) %{ txin | script: script_sig, script_len: int_to_varint(len(script_sig)) } end bytes_to_hex( join([ version, input_count, construct_input_block(inputs), output_count, output_block, lock_time ]) ) end def estimate_tx_fee(n_in, n_out, satoshis, compressed, op_return_size \\ 0) do # 费率未知, 返回 0 if !satoshis do 0 else # 估算交易体积 # version # input count 的长度 # excluding op_return outputs, dealt with separately # output count 的长度 # grand total size of op_return outputs(s) and related field(s) # time lock estimated_size = 4 + n_in * if(compressed, do: 148, else: 180) + len(int_to_varint(n_in)) + n_out * 34 + len(int_to_varint(n_out)) + op_return_size + 4 # 体积乘以费率得到估计的手续费 estimated_fee = estimated_size * satoshis Logger.debug("Estimated fee: #{estimated_fee} satoshis for #{estimated_size} bytes") estimated_fee end end @doc """ This function just for testing. send all balance back to sender, just minus fee. """ def quick_send() do priv = "1AEB4829D9E92290EF35A3812B363B0CA87DFDA2B628060648339E9452BC923A" |> Binary.from_hex() addr = "1EMHJsiXjZmffBUWevGS5mWdoacmpt8vdH" utxos = [Resource.utxos(addr) |> IO.inspect() |> Enum.max_by(fn x -> x.amount end)] outputs = [ {addr, hd(utxos).amount - 230} ] create_p2pkh_transaction(priv, utxos, outputs) |> broadcast() end end
23.042208
119
0.569255
036f733c346fe3183db8b82f3e51d49063c2f392
2,151
ex
Elixir
lib/comspec/event.ex
andyl/phx-cmdd
f72319d81b264b4deba4831ee1d0eb725d2b5adb
[ "MIT" ]
5
2019-05-23T23:25:25.000Z
2019-05-31T12:10:59.000Z
lib/comspec/event.ex
andyl/comgen
f72319d81b264b4deba4831ee1d0eb725d2b5adb
[ "MIT" ]
3
2019-05-31T04:42:02.000Z
2019-06-01T06:42:14.000Z
lib/comspec/event.ex
andyl/comgen
f72319d81b264b4deba4831ee1d0eb725d2b5adb
[ "MIT" ]
1
2019-06-01T05:04:14.000Z
2019-06-01T05:04:14.000Z
defmodule Comspec.Event do @moduledoc """ A struct to handle an Event and generate Event Resources. """ @dirtype "events" @modtype "Events" use TypedStruct import ComspecUtil typedstruct do field(:name, String.t()) field(:fields, list()) end @doc """ Build the directories, code and test cases for Events """ def build_events(comspec) do comspec |> event_directories() |> Enum.each(&Mix.Comgen.gen_dir(&1)) %ComspecToken{comspec: comspec} |> event_filedata() |> generate_event_files() end @doc """ Return a list of generated directories for the event. """ def event_directories(comspec) do ["lib", "test"] |> Enum.map(&dirname(comspec, &1, @dirtype)) end @doc """ Add filedata to ComspecToken """ def event_filedata(%ComspecToken{} = token) do name = token.comspec |> Comspec.name() |> Mix.Comgen.snake() data = token.comspec.events |> Enum.map(&Map.put(&1, :templates, template_paths(token.comspec, &1))) |> Enum.map(&Map.put(&1, :snake_name, name)) |> Enum.map(&Map.put(&1, :module_long, module_long(token.comspec, &1, @modtype))) |> Enum.map(&Map.put(&1, :module_short, module_short(&1))) |> Enum.map(&Map.put(&1, :string_fields, string_fields(&1))) %ComspecToken{token | filedata: data} end def event_filedata(%{} = comspec) do event_filedata(%ComspecToken{comspec: comspec}) end # --------------------------------------------------------- defp generate_event_files(%ComspecToken{} = token) do token.filedata |> Enum.each(&generate_event_files(token.comspec, &1)) end defp generate_event_files(comspec, event) do generate_files(comspec, event) end defp template_paths(comspec, event) do ev_name = Mix.Comgen.snake(event[:name]) %{ lib: %{ src: Comspec.template_dir() <> "event.ex", dst: dirname(comspec, "lib", @dirtype) <> "/" <> ev_name <> ".ex" }, test: %{ src: Comspec.template_dir() <> "event_test.exs", dst: dirname(comspec, "test", @dirtype) <> "/" <> ev_name <> "_test.exs" } } end end
25.607143
87
0.608089
036fd0bae7388dddb421ae3801aece3d8fc51d73
2,742
ex
Elixir
deps/makeup/lib/makeup/styles/html/pygments/samba.ex
arduino-man/fona_modern
61845bbbbc46a61a50e59a97c68709f2722078a6
[ "MIT" ]
null
null
null
deps/makeup/lib/makeup/styles/html/pygments/samba.ex
arduino-man/fona_modern
61845bbbbc46a61a50e59a97c68709f2722078a6
[ "MIT" ]
null
null
null
deps/makeup/lib/makeup/styles/html/pygments/samba.ex
arduino-man/fona_modern
61845bbbbc46a61a50e59a97c68709f2722078a6
[ "MIT" ]
null
null
null
defmodule Makeup.Styles.HTML.SambaStyle do @moduledoc false @styles %{ :error => "#a40000 border:#ef2929", :other => "#000000", :keyword => "bold #204a87", :keyword_constant => "bold #204a87", :keyword_declaration => "bold #204a87", :keyword_namespace => "bold #204a87", :keyword_pseudo => "bold #204a87", :keyword_reserved => "bold #204a87", :keyword_type => "bold #204a87", :name => "#000000", :name_attribute => "#c4a000", :name_builtin => "#204a87", :name_builtin_pseudo => "#3465a4", :name_class => "#5c35cc", :name_constant => "#000000", :name_decorator => "bold #5c35cc", :name_entity => "#ce5c00", :name_exception => "bold #cc0000", :name_function => "#000000", :name_property => "#000000", :name_label => "#f57900", :name_namespace => "#000000", :name_other => "#000000", :name_tag => "bold #204a87", :name_variable => "#000000", :name_variable_class => "#000000", :name_variable_global => "#000000", :name_variable_instance => "#000000", :literal => "#000000", :string => "#4e9a06", :string_backtick => "#4e9a06", :string_char => "#4e9a06", :string_doc => "italic #8f5902", :string_double => "#4e9a06", :string_escape => "#4e9a06", :string_heredoc => "#4e9a06", :string_interpol => "#4e9a06", :string_other => "#4e9a06", :string_regex => "#4e9a06", :string_single => "#4e9a06", :string_symbol => "#4e9a06", :number => "bold #0000cf", :number_float => "bold #0000cf", :number_hex => "bold #0000cf", :number_integer => "bold #0000cf", :number_integer_long => "bold #0000cf", :number_oct => "bold #0000cf", :operator => "bold #ce5c00", :operator_word => "bold #204a87", :punctuation => "#000000", :comment => "#8e908c", :comment_multiline => "#8e908c", :comment_preproc => "#8e908c", :comment_single => "#8e908c", :comment_special => "#8e908c", :generic => "#000000", :generic_deleted => "#a40000", :generic_emph => "italic #000000", :generic_error => "#ef2929", :generic_heading => "bold #000080", :generic_inserted => "#00A000", :generic_output => "italic #000000", :generic_prompt => "#8f5902", :generic_strong => "bold #000000", :generic_subheading => "bold #800080", :generic_traceback => "bold #a40000" } alias Makeup.Styles.HTML.Style @style_struct Style.make_style( short_name: "samba", long_name: "Samba Style", background_color: "#f8f8f8", highlight_color: "#ffffcc", styles: @styles) def style() do @style_struct end end
31.517241
44
0.578045
036fd6ea91e981eae87faad69bc9588eb24a9894
10,311
ex
Elixir
turtle/lib/turtle/motion.ex
jaimeiniesta/turtle
9376c7dc29d755f3a7c2fea053bfd68db9c47c10
[ "Apache-2.0" ]
13
2019-09-18T15:58:23.000Z
2022-02-17T11:16:59.000Z
turtle/lib/turtle/motion.ex
jaimeiniesta/turtle
9376c7dc29d755f3a7c2fea053bfd68db9c47c10
[ "Apache-2.0" ]
1
2020-11-05T18:23:48.000Z
2022-02-12T20:56:35.000Z
turtle/lib/turtle/motion.ex
jaimeiniesta/turtle
9376c7dc29d755f3a7c2fea053bfd68db9c47c10
[ "Apache-2.0" ]
1
2022-02-12T22:57:08.000Z
2022-02-12T22:57:08.000Z
defmodule Turtle.Motion do @moduledoc """ Motion for Turtle """ alias Turtle.Vector @type distance :: number @type angle :: number @doc """ Move the turtle forward by the given amount of distance. Move the turtle forward by the specified distance, in the direction the turtle is headed ## Examples iex> turtle = %{%Turtle{} | angle: 0} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.position(turtle) {0, 0} iex> turtle = Turtle.Motion.forward(turtle, 25) %Turtle{angle: 0, pen_down?: true, x: 25.0, y: 0.0} iex> Turtle.Motion.position(turtle) {25.0, 0.0} iex> turtle = Turtle.Motion.forward(turtle, -75) %Turtle{angle: 0, pen_down?: true, x: -50.0, y: 0.0} iex> Turtle.Motion.position(turtle) {-50.0, 0.0} """ @spec forward(Turtle.t(), distance()) :: Turtle.t() def forward(%Turtle{} = turtle, distance), do: go(turtle, distance) @doc """ Move the turtle backward by the given amount of distance. Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle’s heading. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.position(turtle) {0, 0} iex> turtle = Turtle.Motion.backward(turtle, 30) %Turtle{angle: 0, pen_down?: true, x: -30.0, y: 0.0} iex> Turtle.Motion.position(turtle) {-30.0, 0.0} """ @spec backward(Turtle.t(), distance()) :: Turtle.t() def backward(%Turtle{} = turtle, distance), do: go(turtle, -distance) @doc """ Turn turtle right (clockwise) by the given angle degrees. ## Examples iex> turtle = Turtle.new(angle: 22) %Turtle{angle: 22, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.heading(turtle) 22 iex> turtle = Turtle.Motion.right(turtle, 45) %Turtle{angle: 337, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.heading(turtle) 337 """ @spec right(Turtle.t(), angle()) :: Turtle.t() def right(%Turtle{angle: angle} = turtle, ang) do new_angle = angle - ang %{turtle | angle: Integer.mod(new_angle, 360)} end @doc """ Turn turtle left (counterclockwise) by the given angle (degress) ## Examples iex> turtle = Turtle.new(angle: 22) %Turtle{angle: 22, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.heading(turtle) 22 iex> turtle = Turtle.Motion.left(turtle, 45) %Turtle{angle: 67, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.heading(turtle) 67 """ @spec left(Turtle.t(), angle()) :: Turtle.t() def left(%Turtle{} = turtle, angle), do: right(turtle, -1 * angle) @doc """ Move turtle to an absolute position. Do not change the turtle’s orientation ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.position(turtle) {0, 0} iex> turtle = Turtle.Motion.go_to(turtle, 60, 30) %Turtle{angle: 0, pen_down?: true, x: 60, y: 30} iex> Turtle.Motion.position(turtle) {60, 30} """ @spec go_to(Turtle.t(), number(), number()) :: Turtle.t() def go_to(%Turtle{} = turtle, x, y), do: %{turtle | x: x, y: y} @doc """ Move turtle to an absolute position. Do not change the turtle’s orientation ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.position(turtle) {0, 0} iex> Turtle.Motion.go_to(turtle, {20, 80}) %Turtle{angle: 0, pen_down?: true, x: 20, y: 80} """ @spec go_to(Turtle.t(), Vector.t()) :: Turtle.t() def go_to(%Turtle{} = turtle, {x, y}), do: go_to(turtle, x, y) @doc """ Set the turtle's first coordinate to x, leave second coordinate unchanged. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.position(turtle) {0, 0} iex> Turtle.Motion.set_x(turtle, 10) %Turtle{angle: 0, pen_down?: true, x: 10, y: 0} """ @spec set_x(Turtle.t(), number()) :: Turtle.t() def set_x(%Turtle{y: y} = turtle, x), do: go_to(turtle, x, y) @doc """ Set the turtle's second coordinate to y, leave first coordinate unchanged. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.position(turtle) {0, 0} iex> Turtle.Motion.set_y(turtle, 10) %Turtle{angle: 0, pen_down?: true, x: 0, y: 10} """ @spec set_y(Turtle.t(), number()) :: Turtle.t() def set_y(%Turtle{x: x} = turtle, y), do: go_to(turtle, x, y) @doc """ Set the orientation of the turtle to `to_angle`, given in degress In this scenario, 0 is to the right, 90 is up, 180 is left, and 270 is down. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.set_heading(turtle, 45) %Turtle{angle: 45, pen_down?: true, x: 0, y: 0} """ @spec set_heading(Turtle.t(), number()) :: Turtle.t() def set_heading(%Turtle{} = turtle, to_angle) do %{turtle | angle: to_angle} end @doc """ Move turtle to the origin Move the turtle to the origin (coordinates: {0, 0}) and set its heading to its start-orientation (90 degress) ## Examples iex> turtle = %Turtle{x: 3, y: 20, angle: 45} %Turtle{angle: 45, pen_down?: true, x: 3, y: 20} iex> Turtle.Motion.home(turtle) %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} """ def home(%Turtle{} = turtle) do turtle |> go_to(0, 0) |> set_heading(0) end @doc """ Returns the turtle's current position {x, y}, as a Vector 2D. ## Examples iex> Turtle.Motion.position(%Turtle{}) {0, 0} """ @spec position(Turtle.t()) :: Vector.t() def position(%Turtle{x: x, y: y}), do: {x, y} @doc """ Returns the turtle's current heading ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> turtle = Turtle.Motion.left(turtle, 67) %Turtle{angle: 67, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.heading(turtle) 67 """ @spec heading(Turtle.t()) :: angle def heading(%Turtle{angle: angle}), do: angle @doc """ Returns the turtle's x coordinate. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> turtle = Turtle.Motion.right(turtle, 90) %Turtle{angle: 270, pen_down?: true, x: 0, y: 0} iex> turtle = Turtle.Motion.forward(turtle, 60) %Turtle{angle: 270, pen_down?: true, x: 0.0, y: -60.0} iex> Turtle.Motion.x_cor(turtle) 0.0 """ @spec x_cor(Turtle.t()) :: number() def x_cor(%Turtle{x: x}), do: x @doc """ Returns the turtle's y coordinate. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> turtle = Turtle.Motion.forward(turtle, 60) %Turtle{angle: 0, pen_down?: true, x: 60.0, y: 0.0} iex> Turtle.Motion.y_cor(turtle) 0.0 """ @spec y_cor(Turtle.t()) :: number() def y_cor(%Turtle{y: y}), do: y @doc """ Return the angle of the line from the turtle's position to {x, y}. ## Examples iex> turtle = Turtle.new(x: 10, y: 10) %Turtle{angle: 0, pen_down?: true, x: 10, y: 10} iex> Turtle.Motion.towards(turtle, {0, 0}) 225.0 """ @spec towards(Turtle.t(), Vector.t() | Turtle.t()) :: number() def towards(%Turtle{} = turtle, %Turtle{x: x, y: y}) do towards(turtle, {x, y}) end def towards(%Turtle{x: x, y: y}, vector) do {x1, y1} = Vector.sub(vector, {x, y}) y1 |> :math.atan2(x1) |> Kernel.*(180.0) |> Kernel./(:math.pi()) |> fmod() end @doc """ Return the angle of the line from the turtle's position to {x, y}. ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> turtle = Turtle.Motion.go_to(turtle, 10, 10) %Turtle{angle: 0, pen_down?: true, x: 10, y: 10} iex> Turtle.Motion.towards(turtle, 0, 0) 225.0 """ @spec towards(Turtle.t(), number(), number()) :: number() def towards(%Turtle{} = turtle, x, y), do: towards(turtle, {x, y}) @doc """ Return the distance from the turtle to {x,y} in turtle step units ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.distance(turtle, {30, 40}) 50.0 iex> pen = Turtle.new() %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> pen = Turtle.Motion.forward(pen, 77) %Turtle{angle: 0, pen_down?: true, x: 77.0, y: 0.0} iex> Turtle.Motion.distance(turtle, pen) 77.0 """ @spec distance(Turtle.t(), Vector.t() | Turtle.t()) :: number() def distance(%Turtle{} = turtle, %Turtle{x: x, y: y}) do distance(turtle, {x, y}) end def distance(turtle, vector) do turtle |> position() |> Vector.sub(vector) |> Vector.abs() end @doc """ Return the distance from the turtle to {x,y} in turtle step units ## Examples iex> turtle = %Turtle{} %Turtle{angle: 0, pen_down?: true, x: 0, y: 0} iex> Turtle.Motion.distance(turtle, 30, 40) 50.0 """ @spec distance(Turtle.t(), number(), number()) :: number() def distance(%Turtle{} = turtle, x, y), do: distance(turtle, {x, y}) ## Helpers @spec radians(number()) :: number() def radians(degress), do: degress * :math.pi() / 180 @spec degress(number()) :: number() def degress(radians), do: radians * 180 / :math.pi() @spec truncate(number(), number()) :: number() defp truncate(number, decimals \\ 2) do number |> :erlang.float_to_list(decimals: decimals) |> :erlang.list_to_float() end @spec go(Turtle.t(), number()) :: Turtle.t() defp go(%Turtle{angle: angle, x: x, y: y} = turtle, distance) do radians = radians(angle) dx = distance * :math.cos(radians) dy = distance * :math.sin(radians) %{turtle | x: truncate(x + dx), y: truncate(y + dy)} end defp fmod(number, fullcircle \\ 360) defp fmod(number, fullcircle) when number >= 0, do: :math.fmod(number, fullcircle) defp fmod(number, fullcircle), do: :math.fmod(fullcircle + number, fullcircle) end
27.569519
84
0.590728
037044e18b44af5a8146812bf4a6a7545837018b
2,471
exs
Elixir
strings_and_binaries.exs
karlosmid/book_programming_elixir_12
53769b35728a82eddde3a21d4cbd45c1c21596a4
[ "MIT" ]
null
null
null
strings_and_binaries.exs
karlosmid/book_programming_elixir_12
53769b35728a82eddde3a21d4cbd45c1c21596a4
[ "MIT" ]
null
null
null
strings_and_binaries.exs
karlosmid/book_programming_elixir_12
53769b35728a82eddde3a21d4cbd45c1c21596a4
[ "MIT" ]
null
null
null
defmodule StringsAndBinaries do def contains_all_ascii_printables([h|_]) when h < ?\s or h > ?~, do: false def contains_all_ascii_printables([_|t]), do: contains_all_ascii_printables(t) def contains_all_ascii_printables([]), do: true def anagram?(word1,word2), do: _anagram(prepare_words(word1) -- prepare_words(word2)) and _anagram(prepare_words(word2) -- prepare_words(word1)) def prepare_words(words), do: words |> List.to_string |> String.replace(" ","") |> String.upcase |> String.to_charlist defp _anagram([]), do: true defp _anagram(_), do: false def calculate(expression) do case Regex.named_captures(~r/(?<first>[123456789]\d*)\s*(?<operand>[\+-\\*\/])\s*0*(?<second>[123456789]\d*)/, expression) do %{"first" => a, "operand" => "+", "second" => b} -> elem(Integer.parse(a),0) + elem(Integer.parse(b),0) %{"first" => a, "operand" => "-", "second" => b} -> elem(Integer.parse(a),0) - elem(Integer.parse(b),0) %{"first" => a, "operand" => "*", "second" => b} -> elem(Integer.parse(a),0) * elem(Integer.parse(b),0) %{"first" => a, "operand" => "/", "second" => b} -> elem(Integer.parse(a),0) / elem(Integer.parse(b),0) %{"first" => _, "operand" => non_support, "second" => _} -> raise "Not supported operand '#{non_support}'" _ -> raise "Not parsable input" end end def center(list), do: _center(Enum.sort_by(list,&String.length/1)) defp _center(sorted_by_length) do longest = String.length(Enum.at(sorted_by_length,-1)) sorted_by_length |> Enum.each(fn(x) -> IO.puts String.pad_leading(x,_calc_pad(longest,String.length(x))) end) end defp _calc_pad(longest_length,current_length), do: round(Float.ceil(longest_length/2) - Float.ceil(current_length/2) + current_length) def capitalize_sentences(input) do input |> String.split(". ") |> Enum.map(&String.capitalize/1) |> Enum.join(". ") end def read_orders(file_name) do {:ok, data} = File.read(file_name) data_list = Enum.drop(String.split(data,"\n"),-1) header = String.split(Enum.at(data_list,0),",") |> Enum.map(&String.to_atom/1) data_list |> Enum.drop(1) |> Enum.map(&_transform/1) |> Enum.map(fn(x) -> Enum.zip(header,x) end) end defp _transform(data) do data_as_list = String.split(data,",") [String.to_integer(Enum.at(data_as_list,0)),String.to_atom(String.replace(Enum.at(data_as_list,1),":","")),String.to_float(Enum.at(data_as_list,2))] end end
56.159091
152
0.648321
03704965cdcc124978079a179551a5ce62988f4f
279
exs
Elixir
test/controllers/page_controller_test.exs
silentdragonz/chen
a1a1f48a9540ace93c22d16bd2dfae594bd753d2
[ "MIT" ]
3
2015-06-26T03:56:16.000Z
2019-04-29T14:57:43.000Z
test/controllers/page_controller_test.exs
silentdragonz/chen
a1a1f48a9540ace93c22d16bd2dfae594bd753d2
[ "MIT" ]
null
null
null
test/controllers/page_controller_test.exs
silentdragonz/chen
a1a1f48a9540ace93c22d16bd2dfae594bd753d2
[ "MIT" ]
null
null
null
defmodule Chen.PageControllerTest do use Chen.ConnCase test "GET /" do conn = get conn(), "/" assert html_response(conn, 200) =~ "Honk! Honk!" end test "GET /faq" do conn = get conn(), "/faq" assert html_response(conn, 200) =~ "Chen does NOT" end end
19.928571
54
0.623656
037076c53bf965d8ede1609352f36bf324cc271b
82,733
ex
Elixir
clients/service_directory/lib/google_api/service_directory/v1/api/projects.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/service_directory/lib/google_api/service_directory/v1/api/projects.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/service_directory/lib/google_api/service_directory/v1/api/projects.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ServiceDirectory.V1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.ServiceDirectory.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets information about a location. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Resource name for the location. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Location{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Location.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/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.ServiceDirectory.V1.Model.Location{}]) end @doc """ Lists information about the supported locations for this service. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - A filter to narrow down results to a preferred subset. The filtering language accepts strings like "displayName=tokyo", and is documented in more detail in [AIP-160](https://google.aip.dev/160). * `:pageSize` (*type:* `integer()`) - The maximum number of results to return. If not set, the service selects a default. * `:pageToken` (*type:* `String.t`) - A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.ListLocationsResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.ListLocationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_list( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}/locations", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.ServiceDirectory.V1.Model.ListLocationsResponse{}] ) end @doc """ Creates a namespace, and returns the new namespace. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name of the project and location the namespace will be created in. * `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"). * `:namespaceId` (*type:* `String.t`) - Required. The Resource ID must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * `:body` (*type:* `GoogleApi.ServiceDirectory.V1.Model.Namespace.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Namespace{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Namespace.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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, :namespaceId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/namespaces", %{ "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.ServiceDirectory.V1.Model.Namespace{}]) end @doc """ Deletes a namespace. This also deletes all services and endpoints in the namespace. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the namespace to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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.ServiceDirectory.V1.Model.Empty{}]) end @doc """ Gets a namespace. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the namespace to retrieve. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Namespace{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Namespace.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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.ServiceDirectory.V1.Model.Namespace{}]) end @doc """ Gets the IAM Policy for a resource (namespace or service only). ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See the operation documentation 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.ServiceDirectory.V1.Model.GetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_get_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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.ServiceDirectory.V1.Model.Policy{}]) end @doc """ Lists all namespaces. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name of the project and location whose namespaces you'd like to list. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - Optional. The filter to list results by. General `filter` string syntax: ` ()` * `` can be `name` or `labels.` for map field * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` means `HAS`, and is roughly the same as `=` * `` must be the same data type as field * `` can be `AND`, `OR`, `NOT` Examples of valid filters: * `labels.owner` returns namespaces that have a label with the key `owner`, this is the same as `labels:owner` * `labels.owner=sd` returns namespaces that have key/value `owner=sd` * `name>projects/my-project/locations/us-east1/namespaces/namespace-c` returns namespaces that have name that is alphabetically later than the string, so "namespace-e" is returned but "namespace-a" is not * `labels.owner!=sd AND labels.foo=bar` returns namespaces that have `owner` in label key but value is not `sd` AND have key/value `foo=bar` * `doesnotexist.foo=bar` returns an empty list. Note that namespace doesn't have a field called "doesnotexist". Since the filter does not match any namespaces, it returns no results For more information about filtering, see [API Filtering](https://aip.dev/160). * `:orderBy` (*type:* `String.t`) - Optional. The order to list results by. General `order_by` string syntax: ` () (,)` * `` allows value: `name` * `` ascending or descending order by ``. If this is left blank, `asc` is used Note that an empty `order_by` string results in default order, which is order by `name` in ascending order. * `:pageSize` (*type:* `integer()`) - Optional. The maximum number of items to return. * `:pageToken` (*type:* `String.t`) - Optional. The next_page_token value returned from a previous List request, if any. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.ListNamespacesResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.ListNamespacesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/namespaces", %{ "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.ServiceDirectory.V1.Model.ListNamespacesResponse{}] ) end @doc """ Updates a namespace. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Immutable. The resource name for the namespace in the format `projects/*/locations/*/namespaces/*`. * `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. List of fields to be updated in this request. * `:body` (*type:* `GoogleApi.ServiceDirectory.V1.Model.Namespace.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Namespace{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Namespace.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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.ServiceDirectory.V1.Model.Namespace{}]) end @doc """ Sets the IAM Policy for a resource (namespace or service only). ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See the operation documentation 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.ServiceDirectory.V1.Model.SetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_set_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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.ServiceDirectory.V1.Model.Policy{}]) end @doc """ Tests IAM permissions for a resource (namespace or service only). ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation 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.ServiceDirectory.V1.Model.TestIamPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.TestIamPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_test_iam_permissions( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.TestIamPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_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.ServiceDirectory.V1.Model.TestIamPermissionsResponse{}] ) end @doc """ Creates a service, and returns the new service. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name of the namespace this service will belong to. * `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"). * `:serviceId` (*type:* `String.t`) - Required. The Resource ID must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * `:body` (*type:* `GoogleApi.ServiceDirectory.V1.Model.Service.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Service{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Service.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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, :serviceId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/services", %{ "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.ServiceDirectory.V1.Model.Service{}]) end @doc """ Deletes a service. This also deletes all endpoints associated with the service. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the service to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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.ServiceDirectory.V1.Model.Empty{}]) end @doc """ Gets a service. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the service to get. * `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.ServiceDirectory.V1.Model.Service{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Service.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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.ServiceDirectory.V1.Model.Service{}]) end @doc """ Gets the IAM Policy for a resource (namespace or service only). ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being requested. See the operation documentation 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.ServiceDirectory.V1.Model.GetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_get_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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.ServiceDirectory.V1.Model.Policy{}]) end @doc """ Lists all services belonging to a namespace. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name of the namespace whose services you'd like to list. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - Optional. The filter to list results by. General `filter` string syntax: ` ()` * `` can be `name` or `annotations.` for map field * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` means `HAS`, and is roughly the same as `=` * `` must be the same data type as field * `` can be `AND`, `OR`, `NOT` Examples of valid filters: * `annotations.owner` returns services that have a annotation with the key `owner`, this is the same as `annotations:owner` * `annotations.protocol=gRPC` returns services that have key/value `protocol=gRPC` * `name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/service-c` returns services that have name that is alphabetically later than the string, so "service-e" is returned but "service-a" is not * `annotations.owner!=sd AND annotations.foo=bar` returns services that have `owner` in annotation key but value is not `sd` AND have key/value `foo=bar` * `doesnotexist.foo=bar` returns an empty list. Note that service doesn't have a field called "doesnotexist". Since the filter does not match any services, it returns no results For more information about filtering, see [API Filtering](https://aip.dev/160). * `:orderBy` (*type:* `String.t`) - Optional. The order to list results by. General `order_by` string syntax: ` () (,)` * `` allows value: `name` * `` ascending or descending order by ``. If this is left blank, `asc` is used Note that an empty `order_by` string results in default order, which is order by `name` in ascending order. * `:pageSize` (*type:* `integer()`) - Optional. The maximum number of items to return. * `:pageToken` (*type:* `String.t`) - Optional. The next_page_token value returned from a previous List request, if any. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.ListServicesResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.ListServicesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/services", %{ "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.ServiceDirectory.V1.Model.ListServicesResponse{}] ) end @doc """ Updates a service. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Immutable. The resource name for the service in the format `projects/*/locations/*/namespaces/*/services/*`. * `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. List of fields to be updated in this request. * `:body` (*type:* `GoogleApi.ServiceDirectory.V1.Model.Service.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Service{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Service.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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.ServiceDirectory.V1.Model.Service{}]) end @doc """ Returns a service and its associated endpoints. Resolving a service is not considered an active developer method. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the service to resolve. * `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.ServiceDirectory.V1.Model.ResolveServiceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.ResolveServiceResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_resolve( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.ResolveServiceResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_resolve( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:resolve", %{ "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.ServiceDirectory.V1.Model.ResolveServiceResponse{}] ) end @doc """ Sets the IAM Policy for a resource (namespace or service only). ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy is being specified. See the operation documentation 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.ServiceDirectory.V1.Model.SetIamPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_set_iam_policy( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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.ServiceDirectory.V1.Model.Policy{}]) end @doc """ Tests IAM permissions for a resource (namespace or service only). ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `resource` (*type:* `String.t`) - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation 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.ServiceDirectory.V1.Model.TestIamPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.TestIamPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_test_iam_permissions( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.TestIamPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_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.ServiceDirectory.V1.Model.TestIamPermissionsResponse{}] ) end @doc """ Creates an endpoint, and returns the new endpoint. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name of the service that this endpoint provides. * `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"). * `:endpointId` (*type:* `String.t`) - Required. The Resource ID must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * `:body` (*type:* `GoogleApi.ServiceDirectory.V1.Model.Endpoint.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Endpoint{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_endpoints_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Endpoint.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_endpoints_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, :endpointId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/endpoints", %{ "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.ServiceDirectory.V1.Model.Endpoint{}]) end @doc """ Deletes an endpoint. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the endpoint to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_endpoints_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_endpoints_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.ServiceDirectory.V1.Model.Empty{}]) end @doc """ Gets an endpoint. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the endpoint to get. * `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.ServiceDirectory.V1.Model.Endpoint{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_endpoints_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Endpoint.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_endpoints_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.ServiceDirectory.V1.Model.Endpoint{}]) end @doc """ Lists all endpoints. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The resource name of the service whose endpoints you'd like to list. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - Optional. The filter to list results by. General `filter` string syntax: ` ()` * `` can be `name`, `address`, `port`, or `annotations.` for map field * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` means `HAS`, and is roughly the same as `=` * `` must be the same data type as field * `` can be `AND`, `OR`, `NOT` Examples of valid filters: * `annotations.owner` returns endpoints that have a annotation with the key `owner`, this is the same as `annotations:owner` * `annotations.protocol=gRPC` returns endpoints that have key/value `protocol=gRPC` * `address=192.108.1.105` returns endpoints that have this address * `port>8080` returns endpoints that have port number larger than 8080 * `name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c` returns endpoints that have name that is alphabetically later than the string, so "endpoint-e" is returned but "endpoint-a" is not * `annotations.owner!=sd AND annotations.foo=bar` returns endpoints that have `owner` in annotation key but value is not `sd` AND have key/value `foo=bar` * `doesnotexist.foo=bar` returns an empty list. Note that endpoint doesn't have a field called "doesnotexist". Since the filter does not match any endpoints, it returns no results For more information about filtering, see [API Filtering](https://aip.dev/160). * `:orderBy` (*type:* `String.t`) - Optional. The order to list results by. General `order_by` string syntax: ` () (,)` * `` allows values: `name`, `address`, `port` * `` ascending or descending order by ``. If this is left blank, `asc` is used Note that an empty `order_by` string results in default order, which is order by `name` in ascending order. * `:pageSize` (*type:* `integer()`) - Optional. The maximum number of items to return. * `:pageToken` (*type:* `String.t`) - Optional. The next_page_token value returned from a previous List request, if any. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.ListEndpointsResponse{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_endpoints_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.ListEndpointsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_endpoints_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/endpoints", %{ "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.ServiceDirectory.V1.Model.ListEndpointsResponse{}] ) end @doc """ Updates an endpoint. ## Parameters * `connection` (*type:* `GoogleApi.ServiceDirectory.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Immutable. The resource name for the endpoint in the format `projects/*/locations/*/namespaces/*/services/*/endpoints/*`. * `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. List of fields to be updated in this request. * `:body` (*type:* `GoogleApi.ServiceDirectory.V1.Model.Endpoint.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.ServiceDirectory.V1.Model.Endpoint{}}` on success * `{:error, info}` on failure """ @spec servicedirectory_projects_locations_namespaces_services_endpoints_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.ServiceDirectory.V1.Model.Endpoint.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def servicedirectory_projects_locations_namespaces_services_endpoints_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.ServiceDirectory.V1.Model.Endpoint{}]) end end
46.34902
1,404
0.614519
0370922755ebf8a6d14908081d354f33cadf1c02
840
exs
Elixir
test/jwt_claims/string_or_uri_test.exs
pablodavila95/jwt_claims_ex
d83bc51de170d771fcdb8f46bb2f8ad3b80cf98f
[ "MIT" ]
10
2015-08-22T21:13:09.000Z
2020-01-13T19:32:44.000Z
test/jwt_claims/string_or_uri_test.exs
pablodavila95/jwt_claims_ex
d83bc51de170d771fcdb8f46bb2f8ad3b80cf98f
[ "MIT" ]
5
2016-06-23T21:36:54.000Z
2019-05-22T14:26:42.000Z
test/jwt_claims/string_or_uri_test.exs
pablodavila95/jwt_claims_ex
d83bc51de170d771fcdb8f46bb2f8ad3b80cf98f
[ "MIT" ]
3
2016-01-25T23:57:06.000Z
2020-10-01T17:21:52.000Z
defmodule JwtClaims.Claim.StringOrUriTest do use ExUnit.Case alias JwtClaims.StringOrUri doctest StringOrUri test "present_and_equal?/2 w equality" do assert StringOrUri.present_and_equal?("foo", "foo") end defp with_blank_or_not_equal(a, b) do refute StringOrUri.present_and_equal?(a, b) end test "present_and_equal?/2 w 1st argument blank", do: with_blank_or_not_equal("", "b") test "present_and_equal?/2 w 2nd argument blank", do: with_blank_or_not_equal("a", "") test "present_and_equal?/2 w/o equality", do: with_blank_or_not_equal("foo", "bar") test "blank?/1" do assert StringOrUri.blank?(nil) assert StringOrUri.blank?("") assert StringOrUri.blank?(" ") assert StringOrUri.blank?("\t\n\r") refute StringOrUri.blank?("foo") refute StringOrUri.blank?("bar ") end end
26.25
88
0.710714
0370a021986e29c7f13c132715d1a4f37cc72517
1,290
exs
Elixir
test/bitcoin/protocol/messages/get_data_test.exs
anthdm/bitcoin-elixir
5ca9f8bf4e9b2b38527670e80568a85e0aa612c0
[ "Apache-2.0" ]
81
2017-04-20T17:42:59.000Z
2022-02-08T03:49:22.000Z
test/bitcoin/protocol/messages/get_data_test.exs
anthdm/bitcoin-elixir
5ca9f8bf4e9b2b38527670e80568a85e0aa612c0
[ "Apache-2.0" ]
4
2017-03-26T12:56:59.000Z
2021-05-29T01:26:57.000Z
test/bitcoin/protocol/messages/get_data_test.exs
anthdm/bitcoin-elixir
5ca9f8bf4e9b2b38527670e80568a85e0aa612c0
[ "Apache-2.0" ]
22
2017-08-16T14:19:44.000Z
2021-12-22T04:36:57.000Z
defmodule Bitcoin.Protocol.Messages.GetDataTest do use ExUnit.Case alias Bitcoin.Protocol.Messages.GetData alias Bitcoin.Protocol.Types.InventoryVector test "getdata message with 2 inventory vectors" do payload = Base.decode16!("02" <> # 2 vectors in this message # Inventory Vector 1 "03000000" <> # type: 03 - MsgFilteredBlock "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855" <> # hash # Inventory Vector 2 "01000000" <> # type: 01 - MsgTx "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855") # hash struct = %GetData{ inventory_vectors: [ %InventoryVector{ reference_type: :msg_filtered_block, hash: Base.decode16!("E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855")}, %InventoryVector{ reference_type: :msg_tx, hash: Base.decode16!("E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855")} ] } assert GetData.parse(payload) == struct assert GetData.serialize(struct) == payload end end
40.3125
107
0.602326
0370a82dfbf60fc679660ff10e954a3248a5b921
6,501
exs
Elixir
test/utils_test.exs
jeffweiss/exirc
d56e1d93ef83d350606e489021a276f8a49e9480
[ "MIT" ]
147
2015-01-12T15:05:12.000Z
2022-03-17T06:32:41.000Z
test/utils_test.exs
jeffweiss/exirc
d56e1d93ef83d350606e489021a276f8a49e9480
[ "MIT" ]
74
2015-01-24T23:07:53.000Z
2021-04-23T14:27:43.000Z
test/utils_test.exs
jeffweiss/exirc
d56e1d93ef83d350606e489021a276f8a49e9480
[ "MIT" ]
51
2015-02-13T21:00:38.000Z
2022-03-03T15:38:12.000Z
defmodule ExIRC.UtilsTest do use ExUnit.Case, async: true use ExIRC.Commands alias ExIRC.Utils, as: Utils alias ExIRC.Client.ClientState, as: ClientState doctest ExIRC.Utils test "Given a local date/time as a tuple, can retrieve get the CTCP formatted time" do local_time = {{2013,12,6},{14,5,0}} # Mimics output of :calendar.local_time() assert Utils.ctcp_time(local_time) == "Fri Dec 06 14:05:00 2013" end test "Can parse a CTCP command" do message = ':pschoenf NOTICE #testchan :' ++ '#{<<0o001>>}' ++ 'ACTION mind explodes!!' ++ '#{<<0o001>>}' expected = %ExIRC.Message{ nick: "pschoenf", cmd: "ACTION", ctcp: true, args: ["#testchan", "mind explodes!!"] } result = Utils.parse(message) assert expected == result end test "Parse cloaked user" do message = ':foo!foo@unaffiliated/foo PRIVMSG #bar Hiya.' expected = %ExIRC.Message{ nick: "foo", cmd: "PRIVMSG", host: "unaffiliated/foo", ctcp: false, user: "foo", args: ["#bar", "Hiya."] } result = Utils.parse(message) assert expected == result end test "Parse uncloaked (normal) user" do message = ':foo!foo@80.21.56.43 PRIVMSG #bar Hiya.' expected = %ExIRC.Message{ nick: "foo", cmd: "PRIVMSG", host: "80.21.56.43", ctcp: false, user: "foo", args: ["#bar", "Hiya."] } result = Utils.parse(message) assert expected == result end test "Parse INVITE message" do message = ':pschoenf INVITE testuser #awesomechan' assert %ExIRC.Message{ :nick => "pschoenf", :cmd => "INVITE", :args => ["testuser", "#awesomechan"] } = Utils.parse(message) end test "Parse KICK message" do message = ':pschoenf KICK #testchan lameuser' assert %ExIRC.Message{ :nick => "pschoenf", :cmd => "KICK", :args => ["#testchan", "lameuser"] } = Utils.parse(message) end test "Can parse RPL_ISUPPORT commands" do message = ':irc.example.org 005 nick NETWORK=Freenode PREFIX=(ov)@+ CHANTYPES=#&' parsed = Utils.parse(message) state = %ClientState{} assert %ClientState{ :channel_prefixes => ["#", "&"], :user_prefixes => [{?o, ?@}, {?v, ?+}], :network => "Freenode" } = Utils.isup(parsed.args, state) end test "Can parse full prefix in messages" do assert %ExIRC.Message{ nick: "WiZ", user: "jto", host: "tolsun.oulu.fi", } = Utils.parse(':WiZ!jto@tolsun.oulu.fi NICK Kilroy') end test "Can parse prefix with only hostname in messages" do assert %ExIRC.Message{ nick: "WiZ", host: "tolsun.oulu.fi", } = Utils.parse(':WiZ!tolsun.oulu.fi NICK Kilroy') end test "Can parse reduced prefix in messages" do assert %ExIRC.Message{ nick: "Trillian", } = Utils.parse(':Trillian SQUIT cm22.eng.umd.edu :Server out of control') end test "Can parse server-only prefix in messages" do assert %ExIRC.Message{ server: "ircd.stealth.net" } = Utils.parse(':ircd.stealth.net 302 yournick :syrk=+syrk@millennium.stealth.net') end test "Can parse FULL STOP in username in prefixes" do assert %ExIRC.Message{ nick: "nick", user: "user.name", host: "irc.example.org" } = Utils.parse(':nick!user.name@irc.example.org PART #channel') end test "Can parse EXCLAMATION MARK in username in prefixes" do assert %ExIRC.Message{ nick: "nick", user: "user!name", host: "irc.example.org" } = Utils.parse(':nick!user!name@irc.example.org PART #channel') end test "parse join message" do message = ':pschoenf JOIN #elixir-lang' assert %ExIRC.Message{ nick: "pschoenf", cmd: "JOIN", args: ["#elixir-lang"] } = Utils.parse(message) end test "Parse Slack's inappropriate RPL_TOPIC message as if it were an RPL_NOTOPIC" do # NOTE: This is not a valid message per the RFC. If there's no topic # (which is the case for Slack in this instance), they should instead send # us a RPL_NOTOPIC (331). # # Two things: # # 1) Bad slack! Read your RFCs! (because my code has never had bugs yup obv) # 2) Don't care, still want to talk to them without falling over dead! # # Parsing this as if it were actually an RPL_NOTOPIC (331) seems especially like # a good idea when I realized that there's nothing in ExIRc that does anything # with 331 at all - they just fall on the floor, no crashes to be seen (ideally) message = ':irc.tinyspeck.com 332 jadams #elm-playground-news :' assert %ExIRC.Message{ nick: "jadams", cmd: "331", args: ["#elm-playground-news", "No topic is set"] } = Utils.parse(message) end test "Can parse simple unicode" do # ':foo!~user@172.17.0.1 PRIVMSG #bar :éáçíóö\r\n' message = [58, 102, 111, 111, 33, 126, 117, 115, 101, 114, 64, 49, 55, 50, 46, 49, 55, 46, 48, 46, 49, 32, 80, 82, 73, 86, 77, 83, 71, 32, 35, 98, 97, 114, 32, 58, 195, 169, 195, 161, 195, 167, 195, 173, 195, 179, 195, 182, 13, 10] assert %ExIRC.Message{ args: ["#bar", "éáçíóö"], cmd: "PRIVMSG", ctcp: false, host: "172.17.0.1", nick: "foo", server: [], user: "~user" } = Utils.parse(message) end test "Can parse complex unicode" do # ':foo!~user@172.17.0.1 PRIVMSG #bar :Ĥélłø 차\r\n' message = [58, 102, 111, 111, 33, 126, 117, 115, 101, 114, 64, 49, 55, 50, 46, 49, 55, 46, 48, 46, 49, 32, 80, 82, 73, 86, 77, 83, 71, 32, 35, 98, 97, 114, 32, 58, 196, 164, 195, 169, 108, 197, 130, 195, 184, 32, 236, 176, 168, 13, 10] assert %ExIRC.Message{ args: ["#bar", "Ĥélłø 차"], cmd: "PRIVMSG", ctcp: false, host: "172.17.0.1", nick: "foo", server: [], user: "~user" } = Utils.parse(message) end test "Can parse latin1" do # ':foo!~user@172.17.0.1 PRIVMSG #bar :ééé\r\n' message = [58, 102, 111, 111, 33, 126, 117, 115, 101, 114, 64, 49, 55, 50, 46, 49, 55, 46, 48, 46, 49, 32, 80, 82, 73, 86, 77, 83, 71, 32, 35, 98, 97, 114, 32, 58, 233, 233, 233, 13, 10] assert %ExIRC.Message{ args: ["#bar", "ééé"], cmd: "PRIVMSG", ctcp: false, host: "172.17.0.1", nick: "foo", server: [], user: "~user" } = Utils.parse(message) end end
30.957143
108
0.583756
0370bb9a8ccb0210103c4b5dbdd95704eb679764
19,294
exs
Elixir
test/ecto/query_test.exs
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
test/ecto/query_test.exs
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
test/ecto/query_test.exs
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
Code.require_file "../support/eval_helpers.exs", __DIR__ defmodule Ecto.QueryTest do use ExUnit.Case, async: true import Support.EvalHelpers import Ecto.Query alias Ecto.Query defmacrop macro_equal(column, value) do quote do unquote(column) == unquote(value) end end defmacro macro_map(key) do quote do %{"1" => unquote(key), "2" => unquote(key)} end end describe "query building" do test "allows macros" do test_data = "test" query = from(p in "posts") |> where([q], macro_equal(q.title, ^test_data)) assert "&0.title() == ^0" == Macro.to_string(hd(query.wheres).expr) end test "allows macros in select" do key = "hello" from(p in "posts", select: [macro_map(^key)]) end defmacrop macrotest(x), do: quote(do: is_nil(unquote(x)) or unquote(x) == "A") defmacrop deeper_macrotest(x), do: quote(do: macrotest(unquote(x)) or unquote(x) == "B") test "allows macro in where" do _ = from(p in "posts", where: p.title == "C" or macrotest(p.title)) _ = from(p in "posts", where: p.title == "C" or deeper_macrotest(p.title)) end test "does not allow nils in comparison at compile time" do assert_raise Ecto.Query.CompileError, ~r"comparison with nil is forbidden as it is unsafe", fn -> quote_and_eval from p in "posts", where: p.id == nil end end test "does not allow nils in comparison at runtime" do assert_raise ArgumentError, ~r"comparison with nil is forbidden as it is unsafe", fn -> Post |> where([p], p.title == ^nil) end end end describe "from" do test "does not allow non-queryable" do assert_raise Protocol.UndefinedError, fn -> from(p in 123, []) |> select([p], p.title) end assert_raise UndefinedFunctionError, fn -> from(p in NotASchema, []) |> select([p], p.title) end end test "normalizes expressions" do quote_and_eval(from("posts", [])) assert_raise ArgumentError, fn -> quote_and_eval(from("posts", [123])) end assert_raise ArgumentError, fn -> quote_and_eval(from("posts", 123)) end end end describe "subqueries" do test "builds a subquery struct" do assert subquery("posts").query.from.source == {"posts", nil} assert subquery(subquery("posts")).query.from.source == {"posts", nil} assert subquery(subquery("posts").query).query.from.source == {"posts", nil} end test "prefix is not applied if left blank" do assert subquery("posts").query.prefix == nil assert subquery(subquery("posts")).query.prefix == nil assert subquery(subquery("posts").query).query.prefix == nil end test "applies prefix to the subquery's query if provided" do assert subquery("posts", prefix: "my_prefix").query.prefix == "my_prefix" assert subquery(subquery("posts", prefix: "my_prefix")).query.prefix == "my_prefix" assert subquery(subquery("posts", prefix: "my_prefix").query).query.prefix == "my_prefix" end end describe "bindings" do test "are not required by macros" do _ = from(p in "posts") |> limit(1) _ = from(p in "posts") |> order_by([asc: :title]) _ = from(p in "posts") |> where(title: "foo") _ = from(p in "posts") |> having(title: "foo") _ = from(p in "posts") |> offset(1) _ = from(p in "posts") |> update(set: [title: "foo"]) _ = from(p in "posts") |> select([:title]) _ = from(p in "posts") |> group_by([:title]) _ = from(p in "posts") |> distinct(true) _ = from(p in "posts") |> join(:inner, "comments") end test "must be a list of variables" do assert_raise Ecto.Query.CompileError, "binding list should contain only variables or `{as, var}` tuples, got: 0", fn -> quote_and_eval select(%Query{}, [0], 1) end end test "ignore unbound _ var" do assert_raise Ecto.Query.CompileError, fn -> quote_and_eval("posts" |> select([], _.x)) end "posts" |> select([_], 0) "posts" |> join(:inner, [], "comments") |> select([_, c], c.text) "posts" |> join(:inner, [], "comments") |> select([p, _], p.title) "posts" |> join(:inner, [], "comments") |> select([_, _], 0) end test "can be added through joins" do from(c in "comments", join: p in "posts", select: {p.title, c.text}) "comments" |> join(:inner, [c], p in "posts", on: true) |> select([c, p], {p.title, c.text}) end test "can be added through joins with a counter" do base = join("comments", :inner, [c], p in "posts", on: true) assert select(base, [{p, 1}], p) == select(base, [c, p], p) end test "raise on binding collision" do assert_raise Ecto.Query.CompileError, "variable `x` is bound twice", fn -> quote_and_eval("posts" |> from("comments") |> select([x, x], x.id)) end end test "raise on too many vars" do assert from(a in %Query{}, []) assert from([] in %Query{}, []) assert from([a] in %Query{}, []) assert_raise Ecto.Query.CompileError, fn -> comment = "comments" from([a, b] in comment, []) end end end describe "trailing bindings (...)" do test "match on last bindings" do query = "posts" |> join(:inner, [], "comments") |> join(:inner, [], "votes") assert select(query, [..., v], v).select.expr == {:&, [], [2]} assert select(query, [p, ..., v], {p, v}).select.expr == {:{}, [], [{:&, [], [0]}, {:&, [], [2]}]} assert select(query, [p, c, v, ...], v).select.expr == {:&, [], [2]} assert select(query, [..., c, v], {c, v}).select.expr == {:{}, [], [{:&, [], [1]}, {:&, [], [2]}]} end test "match on last bindings with multiple constructs" do query = "posts" |> join(:inner, [], "comments") |> where([..., c], c.public) |> join(:inner, [], "votes") |> select([..., v], v) assert query.select.expr == {:&, [], [2]} assert hd(query.wheres).expr == {{:., [], [{:&, [], [1]}, :public]}, [], []} end test "match on last bindings inside joins" do query = "posts" |> join(:inner, [], "comments") |> join(:inner, [..., c], v in "votes", on: c.id == v.id) assert hd(tl(query.joins)).on.expr == {:==, [], [ {{:., [], [{:&, [], [1]}, :id]}, [], []}, {{:., [], [{:&, [], [2]}, :id]}, [], []} ]} end test "match on last bindings on keyword query" do posts = "posts" query = from [..., p] in posts, join: c in "comments", on: p.id == c.id assert hd(query.joins).on.expr == {:==, [], [ {{:., [], [{:&, [], [0]}, :id]}, [], []}, {{:., [], [{:&, [], [1]}, :id]}, [], []} ]} end end describe "named bindings" do test "assigns a name to a join" do query = from(p in "posts", join: b in "blogs", join: c in "comments", as: :comment, join: l in "links", on: l.valid, as: :link) assert %{comment: 2, link: 3} == query.aliases end test "assigns a name to query source" do query = from p in "posts", as: :post assert %{post: 0} == query.aliases end test "assign to source fails when non-atom name passed" do message = ~r"`as` must be a compile time atom, got: `\"post\"`" assert_raise Ecto.Query.CompileError, message, fn -> quote_and_eval(from(p in "posts", as: "post")) end end test "crashes on duplicate as for keyword query" do message = ~r"`as` keyword was given more than once to the same join" assert_raise Ecto.Query.CompileError, message, fn -> quote_and_eval(from(p in "posts", join: b in "blogs", as: :foo, as: :bar)) end end test "crashes on assigning the same name twice at compile time" do message = ~r"alias `:foo` already exists" assert_raise Ecto.Query.CompileError, message, fn -> quote_and_eval(from(p in "posts", join: b in "blogs", as: :foo, join: c in "comments", as: :foo)) end end test "crashes on assigning the same name twice at runtime" do message = ~r"alias `:foo` already exists" assert_raise Ecto.Query.CompileError, message, fn -> query = "posts" from(p in query, join: b in "blogs", as: :foo, join: c in "comments", as: :foo) end end test "match on binding by name" do query = "posts" |> join(:inner, [p], c in "comments", as: :comment) |> where([comment: c], c.id == 0) assert inspect(query) == ~s[#Ecto.Query<from p in \"posts\", join: c in \"comments\", as: :comment, on: true, where: c.id == 0>] end test "match on binding by name for source" do query = from(p in "posts", as: :post) |> where([post: p], p.id == 0) assert inspect(query) == ~s[#Ecto.Query<from p in \"posts\", as: :post, where: p.id == 0>] end test "match on binding by name with ... in the middle" do query = "posts" |> join(:inner, [p], c in "comments") |> join(:inner, [], a in "authors", as: :authors) |> where([p, ..., authors: a], a.id == 0) assert inspect(query) == ~s[#Ecto.Query<from p in \"posts\", join: c in \"comments\", on: true, join: a in \"authors\", as: :authors, on: true, where: a.id == 0>] end test "referring to non-existing binding" do assert_raise Ecto.QueryError, ~r"unknown bind name `:nope`", fn -> "posts" |> join(:inner, [p], c in "comments", as: :comment) |> where([nope: c], c.id == 0) end end test "named bind not in tail of the list" do message = ~r"tuples must be at the end of the binding list" assert_raise Ecto.Query.CompileError, message, fn -> quote_and_eval( "posts" |> join(:inner, [p], c in "comments", as: :comment) |> where([{:comment, c}, p], c.id == 0) ) end end end describe "keyword queries" do test "are supported through from/2" do # queries need to be on the same line or == wont work assert from(p in "posts", select: 1 < 2) == from(p in "posts", []) |> select([p], 1 < 2) assert from(p in "posts", where: 1 < 2) == from(p in "posts", []) |> where([p], 1 < 2) query = "posts" assert (query |> select([p], p.title)) == from(p in query, select: p.title) end test "are built at compile time with binaries" do quoted = quote do from(p in "posts", join: b in "blogs", join: c in "comments", on: c.text == "", limit: 0, where: p.id == 0 and b.id == 0 and c.id == 0, select: p) end assert {:%{}, _, list} = Macro.expand(quoted, __ENV__) assert List.keyfind(list, :__struct__, 0) == {:__struct__, Query} end test "are built at compile time with atoms" do quoted = quote do from(p in Post, join: b in Blog, join: c in Comment, on: c.text == "", limit: 0, where: p.id == 0 and b.id == 0 and c.id == 0, select: p) end assert {:%{}, _, list} = Macro.expand(quoted, __ENV__) assert List.keyfind(list, :__struct__, 0) == {:__struct__, Query} end test "are built at compile time even with joins" do from(c in "comments", join: p in "posts", on: c.text == "", select: c) from(c in "comments", join: p in {"user_posts", Post}, on: c.text == "", select: c) from(p in "posts", join: c in assoc(p, :comments), select: p) message = ~r"`on` keyword must immediately follow a join" assert_raise Ecto.Query.CompileError, message, fn -> quote_and_eval(from(c in "comments", on: c.text == "", select: c)) end end end describe "exclude/2" do test "removes the given field" do base = %Ecto.Query{} query = from(p in "posts", join: b in "blogs", join: c in "comments", where: p.id == 0 and b.id == 0, or_where: c.id == 0, order_by: p.title, limit: 2, offset: 10, group_by: p.author, having: p.comments > 10, distinct: p.category, lock: "FOO", select: p) # Pre-exclusion assertions refute query.joins == base.joins refute query.wheres == base.wheres refute query.order_bys == base.order_bys refute query.group_bys == base.group_bys refute query.havings == base.havings refute query.distinct == base.distinct refute query.select == base.select refute query.limit == base.limit refute query.offset == base.offset refute query.lock == base.lock excluded_query = query |> exclude(:join) |> exclude(:where) |> exclude(:order_by) |> exclude(:group_by) |> exclude(:having) |> exclude(:distinct) |> exclude(:select) |> exclude(:limit) |> exclude(:offset) |> exclude(:lock) # Post-exclusion assertions assert excluded_query.joins == base.joins assert excluded_query.wheres == base.wheres assert excluded_query.order_bys == base.order_bys assert excluded_query.group_bys == base.group_bys assert excluded_query.havings == base.havings assert excluded_query.distinct == base.distinct assert excluded_query.select == base.select assert excluded_query.limit == base.limit assert excluded_query.offset == base.offset assert excluded_query.lock == base.lock end test "works on any queryable" do query = "posts" |> exclude(:select) assert query.from refute query.select end test "does not set a non-existent field to nil" do query = from(p in "posts", select: p) msg = ~r"no function clause matching in Ecto.Query" assert_raise FunctionClauseError, msg, fn -> Ecto.Query.exclude(query, :fake_field) end end test "does not reset :from" do query = from(p in "posts", select: p) msg = ~r"no function clause matching in Ecto.Query" assert_raise FunctionClauseError, msg, fn -> Ecto.Query.exclude(query, :from) end end test "resets both preloads and assocs if :preloads is passed in" do base = %Ecto.Query{} query = from p in "posts", join: c in assoc(p, :comments), preload: [:author, comments: c] refute query.preloads == base.preloads refute query.assocs == base.assocs excluded_query = query |> exclude(:preload) assert excluded_query.preloads == base.preloads assert excluded_query.assocs == base.assocs end test "removes join qualifiers" do base = %Ecto.Query{} inner_query = from p in "posts", inner_join: b in "blogs" cross_query = from p in "posts", cross_join: b in "blogs" left_query = from p in "posts", left_join: b in "blogs" right_query = from p in "posts", right_join: b in "blogs" full_query = from p in "posts", full_join: b in "blogs" inner_lateral_query = from p in "posts", inner_lateral_join: b in "blogs" left_lateral_query = from p in "posts", left_lateral_join: b in "blogs" refute inner_query.joins == base.joins refute cross_query.joins == base.joins refute left_query.joins == base.joins refute right_query.joins == base.joins refute full_query.joins == base.joins refute inner_lateral_query.joins == base.joins refute left_lateral_query.joins == base.joins excluded_inner_query = exclude(inner_query, :inner_join) assert excluded_inner_query.joins == base.joins excluded_cross_query = exclude(cross_query, :cross_join) assert excluded_cross_query.joins == base.joins excluded_left_query = exclude(left_query, :left_join) assert excluded_left_query.joins == base.joins excluded_right_query = exclude(right_query, :right_join) assert excluded_right_query.joins == base.joins excluded_full_query = exclude(full_query, :full_join) assert excluded_full_query.joins == base.joins excluded_inner_lateral_query = exclude(inner_lateral_query, :inner_lateral_join) assert excluded_inner_lateral_query.joins == base.joins excluded_left_lateral_query = exclude(left_lateral_query, :left_lateral_join) assert excluded_left_lateral_query.joins == base.joins end end describe "fragment/1" do test "raises at runtime when interpolation is not a keyword list" do assert_raise ArgumentError, ~r/fragment\(...\) allows only keyword lists/s, fn -> clause = ["1 = ?"] from p in "posts", where: fragment(^clause) end end test "raises at runtime when interpolation is a binary string" do assert_raise ArgumentError, ~r/fragment\(...\) allows only keyword lists/, fn -> clause = "1 = ?" from p in "posts", where: fragment(^clause) end end test "keeps UTF-8 encoding" do assert inspect(from p in "posts", where: fragment("héllò")) == ~s[#Ecto.Query<from p in \"posts\", where: fragment("héllò")>] end end describe "unsafe_fragment/1" do test "raises with non interpolated binary fragment" do message = ~r"unsafe_fragment\(...\) expects the first argument" assert_raise Ecto.Query.CompileError, message, fn -> quote_and_eval( from p in "posts", where: unsafe_fragment("1 = 1") ) end end test "raises at runtime when interpolation is not a string" do assert_raise ArgumentError, ~r"unsafe_fragment\(...\) expects the first argument", fn -> clause = ["foo": "bar"] from p in "posts", where: unsafe_fragment(^clause) end end test "raises at runtime on parameter mismatch" do assert_raise ArgumentError, ~r"unsafe_fragment\(...\) expects extra arguments", fn -> from p in "posts", where: unsafe_fragment(^"foo = bar", 1) end end test "works with interpolated binary fragment" do val = 1 clause = "1 = #{val}" query = from p in "posts", where: unsafe_fragment(^clause) assert inspect(query) == ~s[#Ecto.Query<from p in \"posts\", where: fragment(\"1 = 1\")>] end test "works with interpolated binary fragment and question marks" do clause = "? = ?" query = from p in "posts", where: unsafe_fragment(^clause, 1, 2) assert inspect(query) == ~s[#Ecto.Query<from p in \"posts\", where: fragment(\"? = ?\", 1, 2)>] end test "keeps UTF-8 encoding" do clause = "héllò" assert inspect(from p in "posts", where: unsafe_fragment(^clause)) == ~s[#Ecto.Query<from p in \"posts\", where: fragment("héllò")>] end end end
34.20922
145
0.57308
0370f92fad3738b1fdc9a42b5c5444585a29a027
2,313
ex
Elixir
apps/asf_web/lib/asf_web/controllers/user_settings_controller.ex
LazarRistic/asf
2c557f06839a129b35174142c91f60696be2fa89
[ "MIT" ]
null
null
null
apps/asf_web/lib/asf_web/controllers/user_settings_controller.ex
LazarRistic/asf
2c557f06839a129b35174142c91f60696be2fa89
[ "MIT" ]
null
null
null
apps/asf_web/lib/asf_web/controllers/user_settings_controller.ex
LazarRistic/asf
2c557f06839a129b35174142c91f60696be2fa89
[ "MIT" ]
null
null
null
defmodule AsfWeb.UserSettingsController do use AsfWeb, :controller alias Asf.Accounts alias AsfWeb.UserAuth plug :assign_email_and_password_changesets def edit(conn, _params) do conn = assign(conn, :page_title, "Settings") render(conn, "edit.html") end def update(conn, %{"action" => "update_email"} = params) do %{"current_password" => password, "user" => user_params} = params user = conn.assigns.current_user case Accounts.apply_user_email(user, password, user_params) do {:ok, applied_user} -> Accounts.deliver_update_email_instructions( applied_user, user.email, &Routes.user_settings_url(conn, :confirm_email, &1) ) conn |> put_flash( :info, "A link to confirm your email change has been sent to the new address." ) |> redirect(to: Routes.user_settings_path(conn, :edit)) {:error, changeset} -> render(conn, "edit.html", email_changeset: changeset) end end def update(conn, %{"action" => "update_password"} = params) do %{"current_password" => password, "user" => user_params} = params user = conn.assigns.current_user case Accounts.update_user_password(user, password, user_params) do {:ok, user} -> conn |> put_flash(:info, "Password updated successfully.") |> put_session(:user_return_to, Routes.user_settings_path(conn, :edit)) |> UserAuth.log_in_user(user) {:error, changeset} -> render(conn, "edit.html", password_changeset: changeset) end end def confirm_email(conn, %{"token" => token}) do case Accounts.update_user_email(conn.assigns.current_user, token) do :ok -> conn |> put_flash(:info, "Email changed successfully.") |> redirect(to: Routes.user_settings_path(conn, :edit)) :error -> conn |> put_flash(:error, "Email change link is invalid or it has expired.") |> redirect(to: Routes.user_settings_path(conn, :edit)) end end defp assign_email_and_password_changesets(conn, _opts) do user = conn.assigns.current_user conn |> assign(:email_changeset, Accounts.change_user_email(user)) |> assign(:password_changeset, Accounts.change_user_password(user)) end end
30.434211
81
0.651967
0371025454a0367f5c1bc1103ab9c74846cc1a38
171
ex
Elixir
lib/idvote_web/static.ex
boisebrigade/idvote
fb1d3f348db094e0578d6976a0a349971bf7aab7
[ "ISC" ]
2
2018-08-15T02:03:36.000Z
2019-02-06T23:27:56.000Z
lib/idvote_web/static.ex
boisebrigade/idvote
fb1d3f348db094e0578d6976a0a349971bf7aab7
[ "ISC" ]
14
2018-08-11T19:47:56.000Z
2018-08-29T22:44:22.000Z
lib/idvote_web/static.ex
boisebrigade/idvote
fb1d3f348db094e0578d6976a0a349971bf7aab7
[ "ISC" ]
2
2018-08-11T16:44:02.000Z
2018-08-28T03:45:55.000Z
defmodule IdvoteWeb.StaticPlug do @behaviour Plug import Plug.Conn def init(_), do: [] def call(conn, _), do: send_file(conn, 200, "priv/static/index.html") end
19
71
0.695906
037109cba46e38a2b709be9aee424a4912d38514
4,655
ex
Elixir
debian/manpage.sgml.ex
MacroFab/gerber-to-svg
213253e0eb0dfd44c224953593203766e0c46ccb
[ "MIT" ]
5
2016-04-20T11:12:56.000Z
2018-01-15T09:50:45.000Z
debian/manpage.sgml.ex
MacroFab/gerber-to-svg
213253e0eb0dfd44c224953593203766e0c46ccb
[ "MIT" ]
null
null
null
debian/manpage.sgml.ex
MacroFab/gerber-to-svg
213253e0eb0dfd44c224953593203766e0c46ccb
[ "MIT" ]
1
2017-02-27T17:36:52.000Z
2017-02-27T17:36:52.000Z
<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [ <!-- Process this file with docbook-to-man to generate an nroff manual page: `docbook-to-man manpage.sgml > manpage.1'. You may view the manual page with: `docbook-to-man manpage.sgml | nroff -man | less'. A typical entry in a Makefile or Makefile.am is: manpage.1: manpage.sgml docbook-to-man $< > $@ The docbook-to-man binary is found in the docbook-to-man package. Please remember that if you create the nroff version in one of the debian/rules file targets (such as build), you will need to include docbook-to-man in your Build-Depends control field. --> <!-- Fill in your name for FIRSTNAME and SURNAME. --> <!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>"> <!ENTITY dhsurname "<surname>SURNAME</surname>"> <!-- Please adjust the date whenever revising the manpage. --> <!ENTITY dhdate "<date>July 10, 2015</date>"> <!-- SECTION should be 1-8, maybe w/ subsection other parameters are allowed: see man(7), man(1). --> <!ENTITY dhsection "<manvolnum>SECTION</manvolnum>"> <!ENTITY dhemail "<email>dholm@unknown</email>"> <!ENTITY dhusername "Dan Holm"> <!ENTITY dhucpackage "<refentrytitle>GERBER-TO-SVG</refentrytitle>"> <!ENTITY dhpackage "gerber-to-svg"> <!ENTITY debian "<productname>Debian</productname>"> <!ENTITY gnu "<acronym>GNU</acronym>"> <!ENTITY gpl "&gnu; <acronym>GPL</acronym>"> ]> <refentry> <refentryinfo> <address> &dhemail; </address> <author> &dhfirstname; &dhsurname; </author> <copyright> <year>2003</year> <holder>&dhusername;</holder> </copyright> &dhdate; </refentryinfo> <refmeta> &dhucpackage; &dhsection; </refmeta> <refnamediv> <refname>&dhpackage;</refname> <refpurpose>program to do something</refpurpose> </refnamediv> <refsynopsisdiv> <cmdsynopsis> <command>&dhpackage;</command> <arg><option>-e <replaceable>this</replaceable></option></arg> <arg><option>--example <replaceable>that</replaceable></option></arg> </cmdsynopsis> </refsynopsisdiv> <refsect1> <title>DESCRIPTION</title> <para>This manual page documents briefly the <command>&dhpackage;</command> and <command>bar</command> commands.</para> <para>This manual page was written for the &debian; distribution because the original program does not have a manual page. Instead, it has documentation in the &gnu; <application>Info</application> format; see below.</para> <para><command>&dhpackage;</command> is a program that...</para> </refsect1> <refsect1> <title>OPTIONS</title> <para>These programs follow the usual &gnu; command line syntax, with long options starting with two dashes (`-'). A summary of options is included below. For a complete description, see the <application>Info</application> files.</para> <variablelist> <varlistentry> <term><option>-h</option> <option>--help</option> </term> <listitem> <para>Show summary of options.</para> </listitem> </varlistentry> <varlistentry> <term><option>-v</option> <option>--version</option> </term> <listitem> <para>Show version of program.</para> </listitem> </varlistentry> </variablelist> </refsect1> <refsect1> <title>SEE ALSO</title> <para>bar (1), baz (1).</para> <para>The programs are documented fully by <citetitle>The Rise and Fall of a Fooish Bar</citetitle> available via the <application>Info</application> system.</para> </refsect1> <refsect1> <title>AUTHOR</title> <para>This manual page was written by &dhusername; &dhemail; for the &debian; system (and may be used by others). Permission is granted to copy, distribute and/or modify this document under the terms of the &gnu; General Public License, Version 2 any later version published by the Free Software Foundation. </para> <para> On Debian systems, the complete text of the GNU General Public License can be found in /usr/share/common-licenses/GPL. </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:2 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:nil sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: -->
30.032258
75
0.657358
03710fbd88d81d43016d23d92a6c70df69cca391
1,250
exs
Elixir
clients/jobs/mix.exs
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/jobs/mix.exs
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
clients/jobs/mix.exs
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.Jobs.V2.Mixfile do use Mix.Project @version "0.3.0" def project do [app: :google_api_jobs, 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/FIXME" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1"}, {:ex_doc, "~> 0.16", only: :dev}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false} ] end defp description() do """ Cloud Talent Solution provides the capability to create, read, update, and delete job postings, as well as search jobs based on keywords and filters. """ 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/FIXME", "Homepage" => "https://cloud.google.com/talent-solution/job-search/docs/" } ] end end
25.510204
154
0.604
037112a06535bfca983bac14a0ea3bd81c16c97a
2,016
ex
Elixir
lib/plug/exceptions.ex
VinogradovAlexandr/plug
baad2c4fa48a9c288545e4581e30c0d6a007f3d1
[ "Apache-2.0" ]
1
2020-09-01T12:50:36.000Z
2020-09-01T12:50:36.000Z
lib/plug/exceptions.ex
VinogradovAlexandr/plug
baad2c4fa48a9c288545e4581e30c0d6a007f3d1
[ "Apache-2.0" ]
null
null
null
lib/plug/exceptions.ex
VinogradovAlexandr/plug
baad2c4fa48a9c288545e4581e30c0d6a007f3d1
[ "Apache-2.0" ]
null
null
null
# This file defines the Plug.Exception protocol and # the exceptions that implement such protocol. defprotocol Plug.Exception do @moduledoc """ A protocol that extends exceptions to be status-code aware. By default, it looks for an implementation of the protocol, otherwise checks if the exception has the `:plug_status` field or simply returns 500. """ @fallback_to_any true @type action :: %{label: String.t(), handler: {module(), atom(), list()}} @doc """ Receives an exception and returns its HTTP status code. """ @spec status(t) :: Plug.Conn.status() def status(exception) @doc """ Receives an exception and returns the possible actions that could be triggered for that error. Should return a list of actions in the following structure: %{ label: "Text that will be displayed in the button", handler: {Module, :function, [args]} } Where: * `label` a string/binary that names this action * `handler` a MFArgs that will be executed when this action is triggered It will be rendered in the `Plug.Debugger` generated error page as buttons showing the `label` that upon pressing executes the MFArgs defined in the `handler`. ## Examples defimpl Plug.Exception, for: ActionableExample do def actions(_), do: %{label: "Print HI", handler: {IO, :puts, ["Hi!"]}}} end """ @spec actions(t) :: [action()] def actions(exception) end defimpl Plug.Exception, for: Any do def status(%{plug_status: status}) when is_integer(status), do: status def status(_), do: 500 def actions(_exception), do: [] end defmodule Plug.BadRequestError do @moduledoc """ The request will not be processed due to a client error. """ defexception message: "could not process the request due to client error", plug_status: 400 end defmodule Plug.TimeoutError do @moduledoc """ Timeout while waiting for the request. """ defexception message: "timeout while waiting for request data", plug_status: 408 end
28.394366
96
0.698909
03712878d020871ae3dbb4511d4b2355c8df4c8e
545
exs
Elixir
test/cog/chat/hipchat/templates/embedded/group_member_add_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
1,003
2016-02-23T17:21:12.000Z
2022-02-20T14:39:35.000Z
test/cog/chat/hipchat/templates/embedded/group_member_add_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
906
2016-02-22T22:54:19.000Z
2022-03-11T15:19:43.000Z
test/cog/chat/hipchat/templates/embedded/group_member_add_test.exs
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
95
2016-02-23T13:42:31.000Z
2021-11-30T14:39:55.000Z
defmodule Cog.Chat.HipChat.Templates.Embedded.GroupMemberAddTest do use Cog.TemplateCase test "group-member-add template" do data = %{"results" => [%{"name" => "testgroup", "members_added" => ["member1", "member2"]}]} expected = """ Added user 'member1' to group 'testgroup'<br/>\ Added user 'member2' to group 'testgroup' """ |> String.strip() assert_rendered_template(:hipchat, :embedded, "group-member-add", data, expected) end end
34.0625
85
0.574312
03713feb7564987bc9d6a1619a49502faef4a091
603
ex
Elixir
lib/ex_diet_web/views/error_view.ex
mugimaru/ex_diet
9602c07af27255decbb32fd7ae0c12b3ffe662a3
[ "Apache-2.0" ]
2
2020-06-25T11:51:46.000Z
2020-09-30T14:00:40.000Z
lib/ex_diet_web/views/error_view.ex
mugimaru/ex_diet
9602c07af27255decbb32fd7ae0c12b3ffe662a3
[ "Apache-2.0" ]
null
null
null
lib/ex_diet_web/views/error_view.ex
mugimaru/ex_diet
9602c07af27255decbb32fd7ae0c12b3ffe662a3
[ "Apache-2.0" ]
1
2020-01-29T08:43:07.000Z
2020-01-29T08:43:07.000Z
defmodule ExDietWeb.ErrorView do use ExDietWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end def render("401.json", assigns) do %{errors: [%{message: "Not authorized", code: assigns[:reason]}]} end end
28.714286
69
0.713101
037142867cf0e81868cabddf9d50cfb8b886079e
700
ex
Elixir
lib/particle/device.ex
skruger/particle-elixir
a545ca921b239c2e2edb291cfc98f7d00c2e7310
[ "MIT" ]
4
2017-04-30T22:16:10.000Z
2018-05-03T19:52:24.000Z
lib/particle/device.ex
skruger/particle-elixir
a545ca921b239c2e2edb291cfc98f7d00c2e7310
[ "MIT" ]
5
2016-09-30T10:05:57.000Z
2019-06-03T22:55:25.000Z
lib/particle/device.ex
skruger/particle-elixir
a545ca921b239c2e2edb291cfc98f7d00c2e7310
[ "MIT" ]
3
2016-09-27T07:42:26.000Z
2020-11-04T06:00:53.000Z
defmodule Particle.Device do alias Particle.Base alias Particle.Error defstruct [:id, :name, :connected, variables: %{}, functions: []] @type t :: %__MODULE__{ id: binary, name: binary, connected: Boolean, variables: %{Atom => binary}, functions: [binary] } @endpoint "devices" @moduledoc """ This module defines the actions that can be taken on the Device endpoint. """ @spec get(binary) :: {:ok, t} | Error.t() def get(device_id) do Base.get(@endpoint, device_id, __MODULE__) end @spec events(binary) :: Enumerable.t() def events(device_id) do Base.stream(@endpoint, "#{device_id}/events") end end
22.580645
75
0.615714
03717d6624106fce84315400f693f7e96c56d38b
1,194
ex
Elixir
web/models/item/food/ingredient_list.ex
ZURASTA/bonbon
231888326535a11aa7e7c4ed93e0a0ba01411d95
[ "BSD-2-Clause" ]
1
2017-06-15T11:20:27.000Z
2017-06-15T11:20:27.000Z
web/models/item/food/ingredient_list.ex
ScrimpyCat/bonbon
231888326535a11aa7e7c4ed93e0a0ba01411d95
[ "BSD-2-Clause" ]
null
null
null
web/models/item/food/ingredient_list.ex
ScrimpyCat/bonbon
231888326535a11aa7e7c4ed93e0a0ba01411d95
[ "BSD-2-Clause" ]
2
2017-07-25T10:16:19.000Z
2017-08-02T06:54:22.000Z
defmodule Bonbon.Model.Item.Food.IngredientList do use Bonbon.Web, :model @moduledoc """ A model representing the different ingredients of food available to order. """ schema "food_ingredient_list" do belongs_to :food, Bonbon.Model.Item.Food belongs_to :ingredient, Bonbon.Model.Ingredient #todo: Below is to handle optional ingredients/addons, however this approach # might mess with diet tags. As they're being applied to food not # optional collections of ingredients. field :addon, :boolean, default: false field :price, :decimal field :currency, :string timestamps end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:food_id, :ingredient_id, :addon, :price, :currency]) |> validate_required([:food_id, :ingredient_id, :addon]) |> validate_length(:currency, is: 3) |> format_uppercase(:currency) |> assoc_constraint(:food) |> assoc_constraint(:ingredient) |> unique_constraint(:food_id_ingredient_id) end end
36.181818
84
0.639866
03718e434b79f69e8ac74fd911706d3fb90addad
1,924
ex
Elixir
lib/10_parse/30_example_functions.ex
marick/ecto_test_dsl
6d460af093367098b7c78db709753deb45904d77
[ "Unlicense" ]
4
2021-02-09T17:26:34.000Z
2021-08-08T01:42:52.000Z
lib/10_parse/30_example_functions.ex
marick/transformer_test_support
6d460af093367098b7c78db709753deb45904d77
[ "Unlicense" ]
null
null
null
lib/10_parse/30_example_functions.ex
marick/transformer_test_support
6d460af093367098b7c78db709753deb45904d77
[ "Unlicense" ]
null
null
null
defmodule EctoTestDSL.Parse.ExampleFunctions do use EctoTestDSL.Drink.Me use T.Drink.AndParse use EctoTestDSL.Drink.Assertively @moduledoc """ There are three special categories of example-level commands, as reflected in their names: `*_of` functions record the intention to derefence an EEN a test-run time and replace the "of" value with a field from the persistent value.__struct__ id_of(een) `*_from` are like `of` functions, but they substitute many fields. They are used for things like having one `Repo.insert` create not just a single primary value but also other associated values (belongs_to, etc.) params_from(een, except: ...) `*_like` functions are akin to uses of macros. They are expanded to include the params (and only the params) from an example defined in the same module. params_like(:example_name) """ # ---------------------------------------------------------------------------- def params(opts \\ []), do: {:params, Pnode.Params.parse(opts)} def params_like(example_name, opts), do: {:params, Pnode.ParamsLike.parse(example_name, opts)} def params_like(example_name), do: params_like(example_name, except: []) def params_from(een, opts), do: {:params, Pnode.ParamsFrom.parse(een, opts)} def params_from(een), do: params_from(een, except: []) # ---------------------------------------------------------------------------- def previously(opts), do: {:previously, Pnode.Previously.parse(opts)} def changeset(opts), do: {:validation_changeset_checks, Pnode.ChangesetChecks.parse(opts)} def constraint_changeset(opts), do: {:constraint_changeset_checks, Pnode.ChangesetChecks.parse(opts)} def result(opts), do: {:result_fields, Pnode.Fields.parse(opts)} def result_matches(een_or_name, opts \\ []), do: {:result_matches, Pnode.FieldsFrom.parse(een_or_name, opts)} end
32.610169
80
0.656965
0371a3077b0778acd049cb5bdb07c934dd53560a
1,262
ex
Elixir
lib/extwitter/api/shared/auth_parser.ex
PJUllrich/extwitter
edee88d5b9411bd0e3226c295362e328ae73255d
[ "MIT" ]
null
null
null
lib/extwitter/api/shared/auth_parser.ex
PJUllrich/extwitter
edee88d5b9411bd0e3226c295362e328ae73255d
[ "MIT" ]
null
null
null
lib/extwitter/api/shared/auth_parser.ex
PJUllrich/extwitter
edee88d5b9411bd0e3226c295362e328ae73255d
[ "MIT" ]
null
null
null
defmodule ExTwitter.API.AuthParser do @doc """ Parse request_token response """ @spec parse_request_token(map) :: ExTwitter.Model.RequestToken.t() def parse_request_token(object) do ExTwitter.Model.RequestToken |> struct(object) |> Map.put(:raw_data, object) end @doc """ Parse access_token response. """ @spec parse_access_token(map) :: ExTwitter.Model.AccessToken.t() def parse_access_token(object) do ExTwitter.Model.AccessToken |> struct(object) |> Map.put(:raw_data, object) end @doc """ Parse request parameters for the API. """ @spec parse_request_params(keyword) :: [{String.t(), String.t()}] def parse_request_params(options) do Enum.map(options, &stringify_params/1) end @doc """ Parse batch user/lookup request parameters for the API. """ @spec parse_batch_user_lookup_params(keyword) :: [{String.t(), String.t()}] def parse_batch_user_lookup_params(options) do Enum.map(options, &stringify_params/1) end @spec stringify_params({any, [any] | any}) :: {String.t(), String.t()} defp stringify_params({key, values}) when is_list(values) do {to_string(key), Enum.join(values, ",")} end defp stringify_params({key, value}) do {to_string(key), to_string(value)} end end
29.348837
80
0.698098
0371c9493b549702bc1036c5e8cb082f4ebaf209
31,360
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/images.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/images.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/images.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.Api.Images do @moduledoc """ API calls for all endpoints tagged `Images`. """ alias GoogleApi.Compute.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Deletes the specified image. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `image` (*type:* `String.t`) - Name of the image resource to delete. * `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. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_images_delete(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_delete(connection, project, image, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/{project}/global/images/{image}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "image" => URI.encode(image, &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.Compute.V1.Model.Operation{}]) end @doc """ Sets the deprecation status of an image. If an empty request body is given, clears the deprecation status instead. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `image` (*type:* `String.t`) - Image name. * `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. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.DeprecationStatus.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_images_deprecate(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_deprecate(connection, project, image, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/images/{image}/deprecate", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "image" => URI.encode(image, &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.Compute.V1.Model.Operation{}]) end @doc """ Returns the specified image. Gets a list of available images by making a list() request. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `image` (*type:* `String.t`) - Name of the image resource to return. * `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. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Image{}}` on success * `{:error, info}` on failure """ @spec compute_images_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Image.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_get(connection, project, image, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/images/{image}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "image" => URI.encode(image, &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.Compute.V1.Model.Image{}]) end @doc """ Returns the latest image that is part of an image family and is not deprecated. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `family` (*type:* `String.t`) - Name of the image family to search for. * `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. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Image{}}` on success * `{:error, info}` on failure """ @spec compute_images_get_from_family( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Image.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_get_from_family( connection, project, family, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/images/family/{family}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "family" => URI.encode(family, &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.Compute.V1.Model.Image{}]) end @doc """ Gets the access control policy for a resource. May be empty if no such policy or resource exists. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `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. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec compute_images_get_iam_policy( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_get_iam_policy( connection, project, resource, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/images/{resource}/getIamPolicy", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "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.Compute.V1.Model.Policy{}]) end @doc """ Creates an image in the specified project using the data included in the request. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `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. * `:forceCreate` (*type:* `boolean()`) - Force image creation if true. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.Image.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_images_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_insert(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :forceCreate => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/images", %{ "project" => URI.encode(project, &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.Compute.V1.Model.Operation{}]) end @doc """ Retrieves the list of custom images available to the specified project. Custom images are images you create that belong to your project. This method does not get any images that belong to other projects, including publicly-available images, like Debian 8. If you want to get a list of publicly-available images, use this method to make a request to the respective image project, such as debian-cloud or windows-cloud. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `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. * `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` * `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) * `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by `name` or `creationTimestamp desc` is supported. * `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.ImageList{}}` on success * `{:error, info}` on failure """ @spec compute_images_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.ImageList.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_list(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/images", %{ "project" => URI.encode(project, &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.Compute.V1.Model.ImageList{}]) end @doc """ Sets the access control policy on the specified resource. Replaces any existing policy. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `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.Compute.V1.Model.GlobalSetPolicyRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Policy{}}` on success * `{:error, info}` on failure """ @spec compute_images_set_iam_policy( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_set_iam_policy( connection, project, resource, 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("/{project}/global/images/{resource}/setIamPolicy", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "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.Compute.V1.Model.Policy{}]) end @doc """ Sets the labels on an image. To learn more about labels, read the Labeling Resources documentation. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `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.Compute.V1.Model.GlobalSetLabelsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_images_set_labels( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_set_labels(connection, project, resource, 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("/{project}/global/images/{resource}/setLabels", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "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.Compute.V1.Model.Operation{}]) end @doc """ Returns permissions that a caller has on the specified resource. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `resource` (*type:* `String.t`) - Name or id of the resource for this request. * `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.Compute.V1.Model.TestPermissionsRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}}` on success * `{:error, info}` on failure """ @spec compute_images_test_iam_permissions( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.TestPermissionsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def compute_images_test_iam_permissions( connection, project, resource, 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("/{project}/global/images/{resource}/testIamPermissions", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "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.Compute.V1.Model.TestPermissionsResponse{}]) end end
47.659574
434
0.636767
0371cf8d9e581d13d9740616c91b54b10391021a
7,416
exs
Elixir
test/plug/adapters/cowboy/conn_test.exs
niku/plug
807faed1e97868f130331c1c9b2eb710efa55164
[ "Apache-2.0" ]
null
null
null
test/plug/adapters/cowboy/conn_test.exs
niku/plug
807faed1e97868f130331c1c9b2eb710efa55164
[ "Apache-2.0" ]
null
null
null
test/plug/adapters/cowboy/conn_test.exs
niku/plug
807faed1e97868f130331c1c9b2eb710efa55164
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Adapters.Cowboy.ConnTest do use ExUnit.Case, async: true alias Plug.Conn import Plug.Conn defmodule Dummy do def init(opts) do opts end end ## Cowboy setup for testing # # We use hackney to perform an HTTP request against the cowboy/plug running # on port 8001. Plug then uses Kernel.apply/3 to dispatch based on the first # element of the URI's path. # # e.g. `assert {204, _, _} = request :get, "/build/foo/bar"` will perform a # GET http://127.0.0.1:8001/build/foo/bar and Plug will call build/1. setup_all do {:ok, _pid} = Plug.Adapters.Cowboy.http __MODULE__, [], port: 8001 on_exit fn -> :ok = Plug.Adapters.Cowboy.shutdown(__MODULE__.HTTP) end :ok end @already_sent {:plug_conn, :sent} def init(opts) do opts end def call(conn, []) do # Assert we never have a lingering @already_sent entry in the inbox refute_received @already_sent function = String.to_atom List.first(conn.path_info) || "root" apply __MODULE__, function, [conn] rescue exception -> receive do {:plug_conn, :sent} -> :erlang.raise(:error, exception, :erlang.get_stacktrace) after 0 -> send_resp(conn, 500, exception.message <> "\n" <> Exception.format_stacktrace(System.stacktrace)) end end ## Tests def root(%Conn{} = conn) do assert conn.method == "HEAD" assert conn.path_info == [] assert conn.query_string == "foo=bar&baz=bat" resp(conn, 200, "ok") end def build(%Conn{} = conn) do assert {Plug.Adapters.Cowboy.Conn, _} = conn.adapter assert conn.path_info == ["build", "foo", "bar"] assert conn.query_string == "" assert conn.scheme == :http assert conn.host == "127.0.0.1" assert conn.port == 8001 assert conn.method == "GET" assert {{127, 0, 0, 1}, _} = conn.peer assert conn.remote_ip == {127, 0, 0, 1} resp(conn, 200, "ok") end test "builds a connection" do assert {200, _, _} = request :head, "/?foo=bar&baz=bat" assert {200, _, _} = request :get, "/build/foo/bar" assert {200, _, _} = request :get, "//build//foo//bar" end def headers(conn) do assert get_req_header(conn, "foo") == ["bar"] assert get_req_header(conn, "baz") == ["bat"] resp(conn, 200, "ok") end test "stores request headers" do assert {200, _, _} = request :get, "/headers", [{"foo", "bar"}, {"baz", "bat"}] end def send_200(conn) do assert conn.state == :unset assert conn.resp_body == nil conn = send_resp(conn, 200, "OK") assert conn.state == :sent assert conn.resp_body == nil conn end def send_500(conn) do conn |> delete_resp_header("cache-control") |> put_resp_header("x-sample", "value") |> send_resp(500, ["ERR", ["OR"]]) end test "sends a response with status, headers and body" do assert {200, headers, "OK"} = request :get, "/send_200" assert List.keyfind(headers, "cache-control", 0) == {"cache-control", "max-age=0, private, must-revalidate"} assert {500, headers, "ERROR"} = request :get, "/send_500" assert List.keyfind(headers, "cache-control", 0) == nil assert List.keyfind(headers, "x-sample", 0) == {"x-sample", "value"} end test "skips body on head" do assert {200, _, ""} = request :head, "/send_200" end def send_file(conn) do conn = send_file(conn, 200, __ENV__.file) assert conn.state == :sent assert conn.resp_body == nil conn end test "sends a file with status and headers" do assert {200, headers, body} = request :get, "/send_file" assert body =~ "sends a file with status and headers" assert List.keyfind(headers, "cache-control", 0) == {"cache-control", "max-age=0, private, must-revalidate"} assert List.keyfind(headers, "content-length", 0) == {"content-length", File.stat!(__ENV__.file).size |> Integer.to_string} end test "skips file on head" do assert {200, _, ""} = request :head, "/send_file" end def send_chunked(conn) do conn = send_chunked(conn, 200) assert conn.state == :chunked {:ok, conn} = chunk(conn, "HELLO\n") {:ok, conn} = chunk(conn, ["WORLD", ["\n"]]) conn end test "sends a chunked response with status and headers" do assert {200, headers, "HELLO\nWORLD\n"} = request :get, "/send_chunked" assert List.keyfind(headers, "cache-control", 0) == {"cache-control", "max-age=0, private, must-revalidate"} assert List.keyfind(headers, "transfer-encoding", 0) == {"transfer-encoding", "chunked"} end def read_req_body(conn) do expected = :binary.copy("abcdefghij", 100_000) assert {:ok, ^expected, conn} = read_body(conn) assert {:ok, "", conn} = read_body(conn) resp(conn, 200, "ok") end def read_req_body_partial(conn) do assert {:more, _body, conn} = read_body(conn, length: 5, read_length: 5) resp(conn, 200, "ok") end test "reads body" do body = :binary.copy("abcdefghij", 100_000) assert {200, _, "ok"} = request :get, "/read_req_body", [], body assert {200, _, "ok"} = request :post, "/read_req_body", [], body assert {200, _, "ok"} = request :post, "/read_req_body_partial", [], body end def multipart(conn) do conn = Plug.Parsers.call(conn, parsers: [Plug.Parsers.MULTIPART], limit: 8_000_000) assert conn.params["name"] == "hello" assert %Plug.Upload{} = file = conn.params["pic"] assert File.read!(file.path) == "hello\n\n" assert file.content_type == "text/plain" assert file.filename == "foo.txt" resp(conn, 200, "ok") end test "parses multipart requests" do multipart = "------WebKitFormBoundaryw58EW1cEpjzydSCq\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nhello\r\n------WebKitFormBoundaryw58EW1cEpjzydSCq\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"foo.txt\"\r\nContent-Type: text/plain\r\n\r\nhello\n\n\r\n------WebKitFormBoundaryw58EW1cEpjzydSCq\r\nContent-Disposition: form-data; name=\"commit\"\r\n\r\nCreate User\r\n------WebKitFormBoundaryw58EW1cEpjzydSCq--\r\n" headers = [{"Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryw58EW1cEpjzydSCq"}, {"Content-Length", byte_size(multipart)}] assert {200, _, _} = request :post, "/multipart", headers, multipart assert {200, _, _} = request :post, "/multipart?name=overriden", headers, multipart end def https(conn) do assert conn.scheme == :https send_resp(conn, 200, "OK") end @https_options [ port: 8002, password: "cowboy", keyfile: Path.expand("../../../fixtures/ssl/key.pem", __DIR__), certfile: Path.expand("../../../fixtures/ssl/cert.pem", __DIR__) ] test "https" do {:ok, _pid} = Plug.Adapters.Cowboy.https __MODULE__, [], @https_options assert {:ok, 200, _headers, client} = :hackney.get("https://127.0.0.1:8002/https", [], "", []) assert {:ok, "OK"} = :hackney.body(client) :hackney.close(client) after :ok = Plug.Adapters.Cowboy.shutdown __MODULE__.HTTPS end ## Helpers defp request(verb, path, headers \\ [], body \\ "") do {:ok, status, headers, client} = :hackney.request(verb, "http://127.0.0.1:8001" <> path, headers, body, []) {:ok, body} = :hackney.body(client) :hackney.close(client) {status, headers, body} end end
32.103896
443
0.628641
0371efe411de00ec4257c67bd52610ea1b610b69
2,260
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/password_validation_policy.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/password_validation_policy.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/password_validation_policy.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.SQLAdmin.V1beta4.Model.PasswordValidationPolicy do @moduledoc """ Database instance local user password validation policy ## Attributes * `complexity` (*type:* `String.t`, *default:* `nil`) - The complexity of the password. * `disallowUsernameSubstring` (*type:* `boolean()`, *default:* `nil`) - Disallow username as a part of the password. * `minLength` (*type:* `integer()`, *default:* `nil`) - Minimum number of characters allowed. * `passwordChangeInterval` (*type:* `String.t`, *default:* `nil`) - Minimum interval after which the password can be changed. * `reuseInterval` (*type:* `integer()`, *default:* `nil`) - Number of previous passwords that cannot be reused. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :complexity => String.t() | nil, :disallowUsernameSubstring => boolean() | nil, :minLength => integer() | nil, :passwordChangeInterval => String.t() | nil, :reuseInterval => integer() | nil } field(:complexity) field(:disallowUsernameSubstring) field(:minLength) field(:passwordChangeInterval) field(:reuseInterval) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.PasswordValidationPolicy do def decode(value, options) do GoogleApi.SQLAdmin.V1beta4.Model.PasswordValidationPolicy.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.PasswordValidationPolicy do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.305085
129
0.717257
0371fd4465c1b60f7f9cc5b535d280f2f6a052b2
2,902
ex
Elixir
lib/credo/check/runner.ex
ayrat555/credo
517699f82fc6ebe266152d997b64878b334e7bd8
[ "MIT" ]
null
null
null
lib/credo/check/runner.ex
ayrat555/credo
517699f82fc6ebe266152d997b64878b334e7bd8
[ "MIT" ]
null
null
null
lib/credo/check/runner.ex
ayrat555/credo
517699f82fc6ebe266152d997b64878b334e7bd8
[ "MIT" ]
null
null
null
defmodule Credo.Check.Runner do alias Credo.CLI.Output.UI alias Credo.Execution alias Credo.SourceFile alias Credo.Execution.Issues @doc false def run(source_files, exec) when is_list(source_files) do {_time_run_on_all, _source_files_after_run_on_all} = :timer.tc(fn -> run_checks_that_run_on_all(source_files, exec) end) {_time_run, _source_files} = :timer.tc(fn -> source_files |> Enum.map(&Task.async(fn -> run(&1, exec) end)) |> Enum.map(&Task.await(&1, :infinity)) end) :ok end def run(%SourceFile{} = source_file, exec) do checks = exec |> Execution.checks() |> Enum.reject(&run_on_all_check?/1) case run_checks(source_file, checks, exec) do [] -> nil issues -> Issues.append(exec, source_file, issues) end :ok end @doc "Runs the ConfigCommentFinder" def run_config_comment_finder(source_files, exec) do {Credo.Check.ConfigCommentFinder} |> run_check(source_files, exec) |> Enum.into(%{}) end defp run_checks_that_run_on_all(source_files, exec) do checks = exec |> Execution.checks() |> Enum.filter(&run_on_all_check?/1) checks |> Enum.map( &Task.async(fn -> run_check(&1, source_files, exec) end) ) |> Enum.each(&Task.await(&1, :infinity)) :ok end defp run_checks(%SourceFile{} = source_file, checks, exec) when is_list(checks) do Enum.flat_map(checks, &run_check(&1, source_file, exec)) end # Returns issues defp run_check({_check, false}, source_files, _exec) when is_list(source_files) do source_files end defp run_check({_check, false}, _source_file, _exec) do [] end defp run_check({check}, source_file, exec) do run_check({check, []}, source_file, exec) end defp run_check({check, params}, source_files, exec) when is_list(source_files) do try do check.run(source_files, exec, params) rescue error -> warn_about_failed_run(check, source_files) if exec.crash_on_error do reraise error, System.stacktrace() else [] end end end defp run_check({check, params}, source_file, exec) do try do check.run(source_file, params) rescue error -> warn_about_failed_run(check, source_file) if exec.crash_on_error do reraise error, System.stacktrace() else [] end end end defp warn_about_failed_run(check, %SourceFile{} = source_file) do UI.warn("Error while running #{check} on #{source_file.filename}") end defp warn_about_failed_run(check, _) do UI.warn("Error while running #{check}") end defp run_on_all_check?({check}), do: check.run_on_all? defp run_on_all_check?({check, _params}), do: check.run_on_all? end
23.031746
70
0.634735
0372322f3194ceed9a7d996d32a4f7e8c8a83a33
44,871
ex
Elixir
lib/elixir/lib/gen_server.ex
jwarwick/elixir
de103c0f4e3240aa38967298ccb5f483a9e40c16
[ "Apache-2.0" ]
1
2021-05-05T02:11:24.000Z
2021-05-05T02:11:24.000Z
lib/elixir/lib/gen_server.ex
jwarwick/elixir
de103c0f4e3240aa38967298ccb5f483a9e40c16
[ "Apache-2.0" ]
6
2021-03-19T12:33:21.000Z
2021-04-02T17:52:45.000Z
lib/elixir/lib/gen_server.ex
jwarwick/elixir
de103c0f4e3240aa38967298ccb5f483a9e40c16
[ "Apache-2.0" ]
null
null
null
defmodule GenServer do @moduledoc """ A behaviour module for implementing the server of a client-server relation. A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on. The advantage of using a generic server process (GenServer) implemented using this module is that it will have a standard set of interface functions and include functionality for tracing and error reporting. It will also fit into a supervision tree. ## Example The GenServer behaviour abstracts the common client-server interaction. Developers are only required to implement the callbacks and functionality they are interested in. Let's start with a code example and then explore the available callbacks. Imagine we want a GenServer that works like a stack, allowing us to push and pop elements: defmodule Stack do use GenServer # Callbacks @impl true def init(stack) do {:ok, stack} end @impl true def handle_call(:pop, _from, [head | tail]) do {:reply, head, tail} end @impl true def handle_cast({:push, element}, state) do {:noreply, [element | state]} end end # Start the server {:ok, pid} = GenServer.start_link(Stack, [:hello]) # This is the client GenServer.call(pid, :pop) #=> :hello GenServer.cast(pid, {:push, :world}) #=> :ok GenServer.call(pid, :pop) #=> :world We start our `Stack` by calling `start_link/2`, passing the module with the server implementation and its initial argument (a list representing the stack containing the element `:hello`). We can primarily interact with the server by sending two types of messages. **call** messages expect a reply from the server (and are therefore synchronous) while **cast** messages do not. Every time you do a `GenServer.call/3`, the client will send a message that must be handled by the `c:handle_call/3` callback in the GenServer. A `cast/2` message must be handled by `c:handle_cast/2`. There are 8 possible callbacks to be implemented when you use a `GenServer`. The only required callback is `c:init/1`. ## Client / Server APIs Although in the example above we have used `GenServer.start_link/3` and friends to directly start and communicate with the server, most of the time we don't call the `GenServer` functions directly. Instead, we wrap the calls in new functions representing the public API of the server. Here is a better implementation of our Stack module: defmodule Stack do use GenServer # Client def start_link(default) when is_list(default) do GenServer.start_link(__MODULE__, default) end def push(pid, element) do GenServer.cast(pid, {:push, element}) end def pop(pid) do GenServer.call(pid, :pop) end # Server (callbacks) @impl true def init(stack) do {:ok, stack} end @impl true def handle_call(:pop, _from, [head | tail]) do {:reply, head, tail} end @impl true def handle_cast({:push, element}, state) do {:noreply, [element | state]} end end In practice, it is common to have both server and client functions in the same module. If the server and/or client implementations are growing complex, you may want to have them in different modules. ## How to supervise A `GenServer` is most commonly started under a supervision tree. When we invoke `use GenServer`, it automatically defines a `child_spec/1` function that allows us to start the `Stack` directly under a supervisor. To start a default stack of `[:hello]` under a supervisor, one may do: children = [ {Stack, [:hello]} ] Supervisor.start_link(children, strategy: :one_for_all) Note you can also start it simply as `Stack`, which is the same as `{Stack, []}`: children = [ Stack # The same as {Stack, []} ] Supervisor.start_link(children, strategy: :one_for_all) In both cases, `Stack.start_link/1` is always invoked. `use GenServer` also accepts a list of options which configures the child specification and therefore how it runs under a supervisor. The generated `child_spec/1` can be customized with the following options: * `:id` - the child specification identifier, defaults to the current module * `:restart` - when the child should be restarted, defaults to `:permanent` * `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down For example: use GenServer, restart: :transient, shutdown: 10_000 See the "Child specification" section in the `Supervisor` module for more detailed information. The `@doc` annotation immediately preceding `use GenServer` will be attached to the generated `child_spec/1` function. ## Name registration Both `start_link/3` and `start/3` support the `GenServer` to register a name on start via the `:name` option. Registered names are also automatically cleaned up on termination. The supported values are: * an atom - the GenServer is registered locally with the given name using `Process.register/2`. * `{:global, term}` - the GenServer is registered globally with the given term using the functions in the [`:global` module](`:global`). * `{:via, module, term}` - the GenServer is registered with the given mechanism and name. The `:via` option expects a module that exports `register_name/2`, `unregister_name/1`, `whereis_name/1` and `send/2`. One such example is the [`:global` module](`:global`) which uses these functions for keeping the list of names of processes and their associated PIDs that are available globally for a network of Elixir nodes. Elixir also ships with a local, decentralized and scalable registry called `Registry` for locally storing names that are generated dynamically. For example, we could start and register our `Stack` server locally as follows: # Start the server and register it locally with name MyStack {:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack) # Now messages can be sent directly to MyStack GenServer.call(MyStack, :pop) #=> :hello Once the server is started, the remaining functions in this module (`call/3`, `cast/2`, and friends) will also accept an atom, or any `{:global, ...}` or `{:via, ...}` tuples. In general, the following formats are supported: * a PID * an atom if the server is locally registered * `{atom, node}` if the server is locally registered at another node * `{:global, term}` if the server is globally registered * `{:via, module, name}` if the server is registered through an alternative registry If there is an interest to register dynamic names locally, do not use atoms, as atoms are never garbage-collected and therefore dynamically generated atoms won't be garbage-collected. For such cases, you can set up your own local registry by using the `Registry` module. ## Receiving "regular" messages The goal of a `GenServer` is to abstract the "receive" loop for developers, automatically handling system messages, supporting code change, synchronous calls and more. Therefore, you should never call your own "receive" inside the GenServer callbacks as doing so will cause the GenServer to misbehave. Besides the synchronous and asynchronous communication provided by `call/3` and `cast/2`, "regular" messages sent by functions such as `Kernel.send/2`, `Process.send_after/4` and similar, can be handled inside the `c:handle_info/2` callback. `c:handle_info/2` can be used in many situations, such as handling monitor DOWN messages sent by `Process.monitor/1`. Another use case for `c:handle_info/2` is to perform periodic work, with the help of `Process.send_after/4`: defmodule MyApp.Periodically do use GenServer def start_link(_) do GenServer.start_link(__MODULE__, %{}) end @impl true def init(state) do # Schedule work to be performed on start schedule_work() {:ok, state} end @impl true def handle_info(:work, state) do # Do the desired work here # ... # Reschedule once more schedule_work() {:noreply, state} end defp schedule_work do # We schedule the work to happen in 2 hours (written in milliseconds). # Alternatively, one might write :timer.hours(2) Process.send_after(self(), :work, 2 * 60 * 60 * 1000) end end ## Timeouts The return value of `c:init/1` or any of the `handle_*` callbacks may include a timeout value in milliseconds; if not, `:infinity` is assumed. The timeout can be used to detect a lull in incoming messages. The `timeout()` value is used as follows: * If the process has any message already waiting when the `timeout()` value is returned, the timeout is ignored and the waiting message is handled as usual. This means that even a timeout of `0` milliseconds is not guaranteed to execute (if you want to take another action immediately and unconditionally, use a `:continue` instruction instead). * If any message arrives before the specified number of milliseconds elapse, the timeout is cleared and that message is handled as usual. * Otherwise, when the specified number of milliseconds have elapsed with no message arriving, `handle_info/2` is called with `:timeout` as the first argument. ## When (not) to use a GenServer So far, we have learned that a `GenServer` can be used as a supervised process that handles sync and async calls. It can also handle system messages, such as periodic messages and monitoring events. GenServer processes may also be named. A GenServer, or a process in general, must be used to model runtime characteristics of your system. A GenServer must never be used for code organization purposes. In Elixir, code organization is done by modules and functions, processes are not necessary. For example, imagine you are implementing a calculator and you decide to put all the calculator operations behind a GenServer: def add(a, b) do GenServer.call(__MODULE__, {:add, a, b}) end def subtract(a, b) do GenServer.call(__MODULE__, {:subtract, a, b}) end def handle_call({:add, a, b}, _from, state) do {:reply, a + b, state} end def handle_call({:subtract, a, b}, _from, state) do {:reply, a - b, state} end This is an anti-pattern not only because it convolutes the calculator logic but also because you put the calculator logic behind a single process that will potentially become a bottleneck in your system, especially as the number of calls grow. Instead just define the functions directly: def add(a, b) do a + b end def subtract(a, b) do a - b end If you don't need a process, then you don't need a process. Use processes only to model runtime properties, such as mutable state, concurrency and failures, never for code organization. ## Debugging with the :sys module GenServers, as [special processes](https://erlang.org/doc/design_principles/spec_proc.html), can be debugged using the [`:sys` module](`:sys`). Through various hooks, this module allows developers to introspect the state of the process and trace system events that happen during its execution, such as received messages, sent replies and state changes. Let's explore the basic functions from the [`:sys` module](`:sys`) used for debugging: * `:sys.get_state/2` - allows retrieval of the state of the process. In the case of a GenServer process, it will be the callback module state, as passed into the callback functions as last argument. * `:sys.get_status/2` - allows retrieval of the status of the process. This status includes the process dictionary, if the process is running or is suspended, the parent PID, the debugger state, and the state of the behaviour module, which includes the callback module state (as returned by `:sys.get_state/2`). It's possible to change how this status is represented by defining the optional `c:GenServer.format_status/2` callback. * `:sys.trace/3` - prints all the system events to `:stdio`. * `:sys.statistics/3` - manages collection of process statistics. * `:sys.no_debug/2` - turns off all debug handlers for the given process. It is very important to switch off debugging once we're done. Excessive debug handlers or those that should be turned off, but weren't, can seriously damage the performance of the system. * `:sys.suspend/2` - allows to suspend a process so that it only replies to system messages but no other messages. A suspended process can be reactivated via `:sys.resume/2`. Let's see how we could use those functions for debugging the stack server we defined earlier. iex> {:ok, pid} = Stack.start_link([]) iex> :sys.statistics(pid, true) # turn on collecting process statistics iex> :sys.trace(pid, true) # turn on event printing iex> Stack.push(pid, 1) *DBG* <0.122.0> got cast {push,1} *DBG* <0.122.0> new state [1] :ok iex> :sys.get_state(pid) [1] iex> Stack.pop(pid) *DBG* <0.122.0> got call pop from <0.80.0> *DBG* <0.122.0> sent 1 to <0.80.0>, new state [] 1 iex> :sys.statistics(pid, :get) {:ok, [ start_time: {{2016, 7, 16}, {12, 29, 41}}, current_time: {{2016, 7, 16}, {12, 29, 50}}, reductions: 117, messages_in: 2, messages_out: 0 ]} iex> :sys.no_debug(pid) # turn off all debug handlers :ok iex> :sys.get_status(pid) {:status, #PID<0.122.0>, {:module, :gen_server}, [ [ "$initial_call": {Stack, :init, 1}, # process dictionary "$ancestors": [#PID<0.80.0>, #PID<0.51.0>] ], :running, # :running | :suspended #PID<0.80.0>, # parent [], # debugger state [ header: 'Status for generic server <0.122.0>', # module status data: [ {'Status', :running}, {'Parent', #PID<0.80.0>}, {'Logged events', []} ], data: [{'State', [1]}] ] ]} ## Learn more If you wish to find out more about GenServers, the Elixir Getting Started guide provides a tutorial-like introduction. The documentation and links in Erlang can also provide extra insight. * [GenServer - Elixir's Getting Started Guide](https://elixir-lang.org/getting-started/mix-otp/genserver.html) * [`:gen_server` module documentation](`:gen_server`) * [gen_server Behaviour - OTP Design Principles](https://erlang.org/doc/design_principles/gen_server_concepts.html) * [Clients and Servers - Learn You Some Erlang for Great Good!](http://learnyousomeerlang.com/clients-and-servers) """ @doc """ Invoked when the server is started. `start_link/3` or `start/3` will block until it returns. `init_arg` is the argument term (second argument) passed to `start_link/3`. Returning `{:ok, state}` will cause `start_link/3` to return `{:ok, pid}` and the process to enter its loop. Returning `{:ok, state, timeout}` is similar to `{:ok, state}`, except that it also sets a timeout. See the "Timeouts" section in the module documentation for more information. Returning `{:ok, state, :hibernate}` is similar to `{:ok, state}` except the process is hibernated before entering the loop. See `c:handle_call/3` for more information on hibernation. Returning `{:ok, state, {:continue, continue}}` is similar to `{:ok, state}` except that immediately after entering the loop, the `c:handle_continue/2` callback will be invoked with the value `continue` as first argument. Returning `:ignore` will cause `start_link/3` to return `:ignore` and the process will exit normally without entering the loop or calling `c:terminate/2`. If used when part of a supervision tree the parent supervisor will not fail to start nor immediately try to restart the `GenServer`. The remainder of the supervision tree will be started and so the `GenServer` should not be required by other processes. It can be started later with `Supervisor.restart_child/2` as the child specification is saved in the parent supervisor. The main use cases for this are: * The `GenServer` is disabled by configuration but might be enabled later. * An error occurred and it will be handled by a different mechanism than the `Supervisor`. Likely this approach involves calling `Supervisor.restart_child/2` after a delay to attempt a restart. Returning `{:stop, reason}` will cause `start_link/3` to return `{:error, reason}` and the process to exit with reason `reason` without entering the loop or calling `c:terminate/2`. """ @callback init(init_arg :: term) :: {:ok, state} | {:ok, state, timeout | :hibernate | {:continue, term}} | :ignore | {:stop, reason :: any} when state: any @doc """ Invoked to handle synchronous `call/3` messages. `call/3` will block until a reply is received (unless the call times out or nodes are disconnected). `request` is the request message sent by a `call/3`, `from` is a 2-tuple containing the caller's PID and a term that uniquely identifies the call, and `state` is the current state of the `GenServer`. Returning `{:reply, reply, new_state}` sends the response `reply` to the caller and continues the loop with new state `new_state`. Returning `{:reply, reply, new_state, timeout}` is similar to `{:reply, reply, new_state}` except that it also sets a timeout. See the "Timeouts" section in the module documentation for more information. Returning `{:reply, reply, new_state, :hibernate}` is similar to `{:reply, reply, new_state}` except the process is hibernated and will continue the loop once a message is in its message queue. However, if a message is already in the message queue, the process will continue the loop immediately. Hibernating a `GenServer` causes garbage collection and leaves a continuous heap that minimises the memory used by the process. Returning `{:reply, reply, new_state, {:continue, continue}}` is similar to `{:reply, reply, new_state}` except `c:handle_continue/2` will be invoked immediately after with the value `continue` as first argument. Hibernating should not be used aggressively as too much time could be spent garbage collecting. Normally it should only be used when a message is not expected soon and minimising the memory of the process is shown to be beneficial. Returning `{:noreply, new_state}` does not send a response to the caller and continues the loop with new state `new_state`. The response must be sent with `reply/2`. There are three main use cases for not replying using the return value: * To reply before returning from the callback because the response is known before calling a slow function. * To reply after returning from the callback because the response is not yet available. * To reply from another process, such as a task. When replying from another process the `GenServer` should exit if the other process exits without replying as the caller will be blocking awaiting a reply. Returning `{:noreply, new_state, timeout | :hibernate | {:continue, continue}}` is similar to `{:noreply, new_state}` except a timeout, hibernation or continue occurs as with a `:reply` tuple. Returning `{:stop, reason, reply, new_state}` stops the loop and `c:terminate/2` is called with reason `reason` and state `new_state`. Then, the `reply` is sent as the response to call and the process exits with reason `reason`. Returning `{:stop, reason, new_state}` is similar to `{:stop, reason, reply, new_state}` except a reply is not sent. This callback is optional. If one is not implemented, the server will fail if a call is performed against it. """ @callback handle_call(request :: term, from, state :: term) :: {:reply, reply, new_state} | {:reply, reply, new_state, timeout | :hibernate | {:continue, term}} | {:noreply, new_state} | {:noreply, new_state, timeout | :hibernate | {:continue, term}} | {:stop, reason, reply, new_state} | {:stop, reason, new_state} when reply: term, new_state: term, reason: term @doc """ Invoked to handle asynchronous `cast/2` messages. `request` is the request message sent by a `cast/2` and `state` is the current state of the `GenServer`. Returning `{:noreply, new_state}` continues the loop with new state `new_state`. Returning `{:noreply, new_state, timeout}` is similar to `{:noreply, new_state}` except that it also sets a timeout. See the "Timeouts" section in the module documentation for more information. Returning `{:noreply, new_state, :hibernate}` is similar to `{:noreply, new_state}` except the process is hibernated before continuing the loop. See `c:handle_call/3` for more information. Returning `{:noreply, new_state, {:continue, continue}}` is similar to `{:noreply, new_state}` except `c:handle_continue/2` will be invoked immediately after with the value `continue` as first argument. Returning `{:stop, reason, new_state}` stops the loop and `c:terminate/2` is called with the reason `reason` and state `new_state`. The process exits with reason `reason`. This callback is optional. If one is not implemented, the server will fail if a cast is performed against it. """ @callback handle_cast(request :: term, state :: term) :: {:noreply, new_state} | {:noreply, new_state, timeout | :hibernate | {:continue, term}} | {:stop, reason :: term, new_state} when new_state: term @doc """ Invoked to handle all other messages. `msg` is the message and `state` is the current state of the `GenServer`. When a timeout occurs the message is `:timeout`. Return values are the same as `c:handle_cast/2`. This callback is optional. If one is not implemented, the received message will be logged. """ @callback handle_info(msg :: :timeout | term, state :: term) :: {:noreply, new_state} | {:noreply, new_state, timeout | :hibernate | {:continue, term}} | {:stop, reason :: term, new_state} when new_state: term @doc """ Invoked to handle `continue` instructions. It is useful for performing work after initialization or for splitting the work in a callback in multiple steps, updating the process state along the way. Return values are the same as `c:handle_cast/2`. This callback is optional. If one is not implemented, the server will fail if a continue instruction is used. """ @callback handle_continue(continue :: term, state :: term) :: {:noreply, new_state} | {:noreply, new_state, timeout | :hibernate | {:continue, term}} | {:stop, reason :: term, new_state} when new_state: term @doc """ Invoked when the server is about to exit. It should do any cleanup required. `reason` is exit reason and `state` is the current state of the `GenServer`. The return value is ignored. `c:terminate/2` is called if the `GenServer` traps exits (using `Process.flag/2`) *and* the parent process sends an exit signal, or a callback (except `c:init/1`) does one of the following: * returns a `:stop` tuple * raises (via `Kernel.raise/2`) or exits (via `Kernel.exit/1`) * returns an invalid value If part of a supervision tree, a `GenServer` will receive an exit signal when the tree is shutting down. The exit signal is based on the shutdown strategy in the child's specification, where this value can be: * `:brutal_kill`: the `GenServer` is killed and so `c:terminate/2` is not called. * a timeout value, where the supervisor will send the exit signal `:shutdown` and the `GenServer` will have the duration of the timeout to terminate. If after duration of this timeout the process is still alive, it will be killed immediately. For a more in-depth explanation, please read the "Shutdown values (:shutdown)" section in the `Supervisor` module. If the `GenServer` receives an exit signal (that is not `:normal`) from any process when it is not trapping exits it will exit abruptly with the same reason and so not call `c:terminate/2`. Note that a process does *NOT* trap exits by default and an exit signal is sent when a linked process exits or its node is disconnected. Therefore it is not guaranteed that `c:terminate/2` is called when a `GenServer` exits. For such reasons, we usually recommend important clean-up rules to happen in separated processes either by use of monitoring or by links themselves. There is no cleanup needed when the `GenServer` controls a `port` (for example, `:gen_tcp.socket`) or `t:File.io_device/0`, because these will be closed on receiving a `GenServer`'s exit signal and do not need to be closed manually in `c:terminate/2`. If `reason` is neither `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is logged. This callback is optional. """ @callback terminate(reason, state :: term) :: term when reason: :normal | :shutdown | {:shutdown, term} | term @doc """ Invoked to change the state of the `GenServer` when a different version of a module is loaded (hot code swapping) and the state's term structure should be changed. `old_vsn` is the previous version of the module (defined by the `@vsn` attribute) when upgrading. When downgrading the previous version is wrapped in a 2-tuple with first element `:down`. `state` is the current state of the `GenServer` and `extra` is any extra data required to change the state. Returning `{:ok, new_state}` changes the state to `new_state` and the code change is successful. Returning `{:error, reason}` fails the code change with reason `reason` and the state remains as the previous state. If `c:code_change/3` raises the code change fails and the loop will continue with its previous state. Therefore this callback does not usually contain side effects. This callback is optional. """ @callback code_change(old_vsn, state :: term, extra :: term) :: {:ok, new_state :: term} | {:error, reason :: term} when old_vsn: term | {:down, term} @doc """ Invoked in some cases to retrieve a formatted version of the `GenServer` status. This callback can be useful to control the *appearance* of the status of the `GenServer`. For example, it can be used to return a compact representation of the `GenServer`'s state to avoid having large state terms printed. * one of `:sys.get_status/1` or `:sys.get_status/2` is invoked to get the status of the `GenServer`; in such cases, `reason` is `:normal` * the `GenServer` terminates abnormally and logs an error; in such cases, `reason` is `:terminate` `pdict_and_state` is a two-elements list `[pdict, state]` where `pdict` is a list of `{key, value}` tuples representing the current process dictionary of the `GenServer` and `state` is the current state of the `GenServer`. """ @callback format_status(reason, pdict_and_state :: list) :: term when reason: :normal | :terminate @optional_callbacks code_change: 3, terminate: 2, handle_info: 2, handle_cast: 2, handle_call: 3, format_status: 2, handle_continue: 2 @typedoc "Return values of `start*` functions" @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term} @typedoc "The GenServer name" @type name :: atom | {:global, term} | {:via, module, term} @typedoc "Options used by the `start*` functions" @type options :: [option] @typedoc "Option values used by the `start*` functions" @type option :: {:debug, debug} | {:name, name} | {:timeout, timeout} | {:spawn_opt, [Process.spawn_opt()]} | {:hibernate_after, timeout} @typedoc "Debug options supported by the `start*` functions" @type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t()}] @typedoc """ The server reference. This is either a plain PID or a value representing a registered name. See the "Name registration" section of this document for more information. """ @type server :: pid | name | {atom, node} @typedoc """ Tuple describing the client of a call request. `pid` is the PID of the caller and `tag` is a unique term used to identify the call. """ @type from :: {pid, tag :: term} @doc false defmacro __using__(opts) do quote location: :keep, bind_quoted: [opts: opts] do @behaviour GenServer unless Module.has_attribute?(__MODULE__, :doc) do @doc """ Returns a specification to start this module under a supervisor. See `Supervisor`. """ end def child_spec(init_arg) do default = %{ id: __MODULE__, start: {__MODULE__, :start_link, [init_arg]} } Supervisor.child_spec(default, unquote(Macro.escape(opts))) end defoverridable child_spec: 1 # TODO: Remove this on v2.0 @before_compile GenServer @doc false def handle_call(msg, _from, state) do proc = case Process.info(self(), :registered_name) do {_, []} -> self() {_, name} -> name end # We do this to trick Dialyzer to not complain about non-local returns. case :erlang.phash2(1, 1) do 0 -> raise "attempted to call GenServer #{inspect(proc)} but no handle_call/3 clause was provided" 1 -> {:stop, {:bad_call, msg}, state} end end @doc false def handle_info(msg, state) do proc = case Process.info(self(), :registered_name) do {_, []} -> self() {_, name} -> name end :logger.error( %{ label: {GenServer, :no_handle_info}, report: %{ module: __MODULE__, message: msg, name: proc } }, %{ domain: [:otp, :elixir], error_logger: %{tag: :error_msg}, report_cb: &GenServer.format_report/1 } ) {:noreply, state} end @doc false def handle_cast(msg, state) do proc = case Process.info(self(), :registered_name) do {_, []} -> self() {_, name} -> name end # We do this to trick Dialyzer to not complain about non-local returns. case :erlang.phash2(1, 1) do 0 -> raise "attempted to cast GenServer #{inspect(proc)} but no handle_cast/2 clause was provided" 1 -> {:stop, {:bad_cast, msg}, state} end end @doc false def terminate(_reason, _state) do :ok end @doc false def code_change(_old, state, _extra) do {:ok, state} end defoverridable code_change: 3, terminate: 2, handle_info: 2, handle_cast: 2, handle_call: 3 end end defmacro __before_compile__(env) do unless Module.defines?(env.module, {:init, 1}) do message = """ function init/1 required by behaviour GenServer is not implemented \ (in module #{inspect(env.module)}). We will inject a default implementation for now: def init(init_arg) do {:ok, init_arg} end You can copy the implementation above or define your own that converts \ the arguments given to GenServer.start_link/3 to the server state. """ IO.warn(message, Macro.Env.stacktrace(env)) quote do @doc false def init(init_arg) do {:ok, init_arg} end defoverridable init: 1 end end end @doc """ Starts a `GenServer` process linked to the current process. This is often used to start the `GenServer` as part of a supervision tree. Once the server is started, the `c:init/1` function of the given `module` is called with `init_arg` as its argument to initialize the server. To ensure a synchronized start-up procedure, this function does not return until `c:init/1` has returned. Note that a `GenServer` started with `start_link/3` is linked to the parent process and will exit in case of crashes from the parent. The GenServer will also exit due to the `:normal` reasons in case it is configured to trap exits in the `c:init/1` callback. ## Options * `:name` - used for name registration as described in the "Name registration" section in the documentation for `GenServer` * `:timeout` - if present, the server is allowed to spend the given number of milliseconds initializing or it will be terminated and the start function will return `{:error, :timeout}` * `:debug` - if present, the corresponding function in the [`:sys` module](`:sys`) is invoked * `:spawn_opt` - if present, its value is passed as options to the underlying process as in `Process.spawn/4` * `:hibernate_after` - if present, the GenServer process awaits any message for the given number of milliseconds and if no message is received, the process goes into hibernation automatically (by calling `:proc_lib.hibernate/3`). ## Return values If the server is successfully created and initialized, this function returns `{:ok, pid}`, where `pid` is the PID of the server. If a process with the specified server name already exists, this function returns `{:error, {:already_started, pid}}` with the PID of that process. If the `c:init/1` callback fails with `reason`, this function returns `{:error, reason}`. Otherwise, if it returns `{:stop, reason}` or `:ignore`, the process is terminated and this function returns `{:error, reason}` or `:ignore`, respectively. """ @spec start_link(module, any, options) :: on_start def start_link(module, init_arg, options \\ []) when is_atom(module) and is_list(options) do do_start(:link, module, init_arg, options) end @doc """ Starts a `GenServer` process without links (outside of a supervision tree). See `start_link/3` for more information. """ @spec start(module, any, options) :: on_start def start(module, init_arg, options \\ []) when is_atom(module) and is_list(options) do do_start(:nolink, module, init_arg, options) end defp do_start(link, module, init_arg, options) do case Keyword.pop(options, :name) do {nil, opts} -> :gen.start(:gen_server, link, module, init_arg, opts) {atom, opts} when is_atom(atom) -> :gen.start(:gen_server, link, {:local, atom}, module, init_arg, opts) {{:global, _term} = tuple, opts} -> :gen.start(:gen_server, link, tuple, module, init_arg, opts) {{:via, via_module, _term} = tuple, opts} when is_atom(via_module) -> :gen.start(:gen_server, link, tuple, module, init_arg, opts) {other, _} -> raise ArgumentError, """ expected :name option to be one of the following: * nil * atom * {:global, term} * {:via, module, term} Got: #{inspect(other)} """ end end @doc """ Synchronously stops the server with the given `reason`. The `c:terminate/2` callback of the given `server` will be invoked before exiting. This function returns `:ok` if the server terminates with the given reason; if it terminates with another reason, the call exits. This function keeps OTP semantics regarding error reporting. If the reason is any other than `:normal`, `:shutdown` or `{:shutdown, _}`, an error report is logged. """ @spec stop(server, reason :: term, timeout) :: :ok def stop(server, reason \\ :normal, timeout \\ :infinity) do case whereis(server) do nil -> exit({:noproc, {__MODULE__, :stop, [server, reason, timeout]}}) pid when pid == self() -> exit({:calling_self, {__MODULE__, :stop, [server, reason, timeout]}}) pid -> try do :proc_lib.stop(pid, reason, timeout) catch :exit, err -> exit({err, {__MODULE__, :stop, [server, reason, timeout]}}) end end end @doc """ Makes a synchronous call to the `server` and waits for its reply. The client sends the given `request` to the server and waits until a reply arrives or a timeout occurs. `c:handle_call/3` will be called on the server to handle the request. `server` can be any of the values described in the "Name registration" section of the documentation for this module. ## Timeouts `timeout` is an integer greater than zero which specifies how many milliseconds to wait for a reply, or the atom `:infinity` to wait indefinitely. The default value is `5000`. If no reply is received within the specified time, the function call fails and the caller exits. If the caller catches the failure and continues running, and the server is just late with the reply, it may arrive at any time later into the caller's message queue. The caller must in this case be prepared for this and discard any such garbage messages that are two-element tuples with a reference as the first element. """ @spec call(server, term, timeout) :: term def call(server, request, timeout \\ 5000) when (is_integer(timeout) and timeout >= 0) or timeout == :infinity do case whereis(server) do nil -> exit({:noproc, {__MODULE__, :call, [server, request, timeout]}}) pid when pid == self() -> exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}}) pid -> try do :gen.call(pid, :"$gen_call", request, timeout) catch :exit, reason -> exit({reason, {__MODULE__, :call, [server, request, timeout]}}) else {:ok, res} -> res end end end @doc """ Sends an asynchronous request to the `server`. This function always returns `:ok` regardless of whether the destination `server` (or node) exists. Therefore it is unknown whether the destination `server` successfully handled the message. `server` can be any of the values described in the "Name registration" section of the documentation for this module. """ @spec cast(server, term) :: :ok def cast(server, request) def cast({:global, name}, request) do try do :global.send(name, cast_msg(request)) :ok catch _, _ -> :ok end end def cast({:via, mod, name}, request) do try do mod.send(name, cast_msg(request)) :ok catch _, _ -> :ok end end def cast({name, node}, request) when is_atom(name) and is_atom(node), do: do_send({name, node}, cast_msg(request)) def cast(dest, request) when is_atom(dest) or is_pid(dest), do: do_send(dest, cast_msg(request)) @doc """ Casts all servers locally registered as `name` at the specified nodes. This function returns immediately and ignores nodes that do not exist, or where the server name does not exist. See `multi_call/4` for more information. """ @spec abcast([node], name :: atom, term) :: :abcast def abcast(nodes \\ [node() | Node.list()], name, request) when is_list(nodes) and is_atom(name) do msg = cast_msg(request) _ = for node <- nodes, do: do_send({name, node}, msg) :abcast end defp cast_msg(req) do {:"$gen_cast", req} end defp do_send(dest, msg) do try do send(dest, msg) :ok catch _, _ -> :ok end end @doc """ Calls all servers locally registered as `name` at the specified `nodes`. First, the `request` is sent to every node in `nodes`; then, the caller waits for the replies. This function returns a two-element tuple `{replies, bad_nodes}` where: * `replies` - is a list of `{node, reply}` tuples where `node` is the node that replied and `reply` is its reply * `bad_nodes` - is a list of nodes that either did not exist or where a server with the given `name` did not exist or did not reply `nodes` is a list of node names to which the request is sent. The default value is the list of all known nodes (including this node). To avoid that late answers (after the timeout) pollute the caller's message queue, a middleman process is used to do the actual calls. Late answers will then be discarded when they arrive to a terminated process. ## Examples Assuming the `Stack` GenServer mentioned in the docs for the `GenServer` module is registered as `Stack` in the `:"foo@my-machine"` and `:"bar@my-machine"` nodes: GenServer.multi_call(Stack, :pop) #=> {[{:"foo@my-machine", :hello}, {:"bar@my-machine", :world}], []} """ @spec multi_call([node], name :: atom, term, timeout) :: {replies :: [{node, term}], bad_nodes :: [node]} def multi_call(nodes \\ [node() | Node.list()], name, request, timeout \\ :infinity) do :gen_server.multi_call(nodes, name, request, timeout) end @doc """ Replies to a client. This function can be used to explicitly send a reply to a client that called `call/3` or `multi_call/4` when the reply cannot be specified in the return value of `c:handle_call/3`. `client` must be the `from` argument (the second argument) accepted by `c:handle_call/3` callbacks. `reply` is an arbitrary term which will be given back to the client as the return value of the call. Note that `reply/2` can be called from any process, not just the GenServer that originally received the call (as long as that GenServer communicated the `from` argument somehow). This function always returns `:ok`. ## Examples def handle_call(:reply_in_one_second, from, state) do Process.send_after(self(), {:reply, from}, 1_000) {:noreply, state} end def handle_info({:reply, from}, state) do GenServer.reply(from, :one_second_has_passed) {:noreply, state} end """ @spec reply(from, term) :: :ok def reply(client, reply) def reply({to, tag}, reply) when is_pid(to) do send(to, {tag, reply}) :ok end @doc """ Returns the `pid` or `{name, node}` of a GenServer process, `nil` otherwise. To be precise, `nil` is returned whenever a `pid` or `{name, node}` cannot be returned. Note there is no guarantee the returned `pid` or `{name, node}` is alive, as a process could terminate immediately after it is looked up. ## Examples For example, to lookup a server process, monitor it and send a cast to it: process = GenServer.whereis(server) monitor = Process.monitor(process) GenServer.cast(process, :hello) """ @spec whereis(server) :: pid | {atom, node} | nil def whereis(server) def whereis(pid) when is_pid(pid), do: pid def whereis(name) when is_atom(name) do Process.whereis(name) end def whereis({:global, name}) do case :global.whereis_name(name) do pid when is_pid(pid) -> pid :undefined -> nil end end def whereis({:via, mod, name}) do case apply(mod, :whereis_name, [name]) do pid when is_pid(pid) -> pid :undefined -> nil end end def whereis({name, local}) when is_atom(name) and local == node() do Process.whereis(name) end def whereis({name, node} = server) when is_atom(name) and is_atom(node) do server end @doc false def format_report(%{ label: {GenServer, :no_handle_info}, report: %{module: mod, message: msg, name: proc} }) do {'~p ~p received unexpected message in handle_info/2: ~p~n', [mod, proc, msg]} end end
36.480488
119
0.6627
03724f1f885ce7a19e26c8c06c678da89740f983
1,772
ex
Elixir
web/controllers/user_controller.ex
cjeich/MysteryNightServer
36f37187c67562ceb4d6383b0d22b43cbe504515
[ "Apache-2.0" ]
null
null
null
web/controllers/user_controller.ex
cjeich/MysteryNightServer
36f37187c67562ceb4d6383b0d22b43cbe504515
[ "Apache-2.0" ]
null
null
null
web/controllers/user_controller.ex
cjeich/MysteryNightServer
36f37187c67562ceb4d6383b0d22b43cbe504515
[ "Apache-2.0" ]
null
null
null
defmodule MysteryNight.UserController do use MysteryNight.Web, :controller alias MysteryNight.User def index(conn, _params) do users = Repo.all(User) render(conn, "index.html", users: users) end def new(conn, _params) do changeset = User.changeset(%User{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"user" => user_params}) do changeset = User.changeset(%User{}, user_params) case Repo.insert(changeset) do {:ok, _user} -> conn |> put_flash(:info, "User created successfully.") |> redirect(to: user_path(conn, :index)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end def show(conn, %{"id" => id}) do user = Repo.get!(User, id) render(conn, "show.html", user: user) end def edit(conn, %{"id" => id}) do user = Repo.get!(User, id) changeset = User.changeset(user) render(conn, "edit.html", user: user, changeset: changeset) end def update(conn, %{"id" => id, "user" => user_params}) do user = Repo.get!(User, id) changeset = User.changeset(user, user_params) case Repo.update(changeset) do {:ok, user} -> conn |> put_flash(:info, "User updated successfully.") |> redirect(to: user_path(conn, :show, user)) {:error, changeset} -> render(conn, "edit.html", user: user, changeset: changeset) end end def delete(conn, %{"id" => id}) do user = Repo.get!(User, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(user) conn |> put_flash(:info, "User deleted successfully.") |> redirect(to: user_path(conn, :index)) end end
26.848485
67
0.612867
037256071926f189547ecf4135720212821fcf2a
22,990
ex
Elixir
lib/ex_doc/formatter/html/autolink.ex
chulkilee/ex_doc
c393cae07a35d891177be0b5f47ed31bf67c2213
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
lib/ex_doc/formatter/html/autolink.ex
chulkilee/ex_doc
c393cae07a35d891177be0b5f47ed31bf67c2213
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
lib/ex_doc/formatter/html/autolink.ex
chulkilee/ex_doc
c393cae07a35d891177be0b5f47ed31bf67c2213
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
defmodule ExDoc.Formatter.HTML.Autolink do @moduledoc """ Conveniences for autolinking. """ import ExDoc.Formatter.HTML.Templates, only: [h: 1, enc_h: 1] @type language :: :elixir | :erlang | :markdown @type kind :: :function | :module | :mix_task @type link_type :: :normal | :custom @backtick_token "<B706848484895T>" @elixir_docs "https://hexdocs.pm/" @erlang_docs "http://www.erlang.org/doc/man/" @basic_types_page "typespecs.html#basic-types" @built_in_types_page "typespecs.html#built-in-types" @basic_types [ any: 0, none: 0, atom: 0, map: 0, pid: 0, port: 0, reference: 0, struct: 0, tuple: 0, integer: 0, float: 0, neg_integer: 0, non_neg_integer: 0, pos_integer: 0, list: 1, nonempty_list: 1, improper_list: 2, maybe_improper_list: 2 ] @built_in_types [ term: 0, arity: 0, as_boolean: 1, binary: 0, bitstring: 0, boolean: 0, byte: 0, char: 0, charlist: 0, nonempty_charlist: 0, fun: 0, function: 0, identifier: 0, iodata: 0, iolist: 0, keyword: 0, keyword: 1, list: 0, nonempty_list: 0, maybe_improper_list: 0, nonempty_maybe_improper_list: 0, mfa: 0, module: 0, no_return: 0, node: 0, number: 0, struct: 0, timeout: 0 ] kernel_exports = Kernel.__info__(:functions) ++ Kernel.__info__(:macros) special_form_exports = Kernel.SpecialForms.__info__(:macros) @basic_type_strings for {f, a} <- @basic_types, do: "t:#{f}/#{a}" @built_in_type_strings for {f, a} <- @built_in_types, do: "t:#{f}/#{a}" @kernel_function_strings for {f, a} <- kernel_exports, do: "#{f}/#{a}" @special_form_strings for {f, a} <- special_form_exports, do: "#{f}/#{a}" @doc """ Compiles information used during autolinking. """ def compile(modules, extension, config) do aliases = Enum.map(modules, & &1.module) modules_refs = Enum.map(aliases, &inspect/1) types_refs = for module <- modules, type <- module.typespecs, do: "t:" <> module.id <> "." <> type.id docs_refs = for module <- modules, doc <- module.docs, prefix = doc_prefix(doc), entry <- [doc.id | doc.defaults], do: prefix <> module.id <> "." <> entry lib_dirs = config.deps ++ default_lib_dirs() %{ aliases: aliases, docs_refs: docs_refs ++ types_refs, extension: extension, lib_dirs: lib_dirs, modules_refs: modules_refs, skip_undefined_reference_warnings_on: config.skip_undefined_reference_warnings_on } end @regexes [ {:module, :elixir, :normal}, {:module, :elixir, :custom}, {:function, :elixir, :normal}, {:function, :elixir, :custom}, {:function, :erlang, :normal}, {:function, :erlang, :custom}, {:mix_task, :elixir, :normal} ] @doc """ Autolinks any documentation in the project. This is the main API to autolink any project documentation. """ def project_doc(nil, _id, _compiled), do: nil def project_doc(string, id, compiled) when is_binary(string) and is_map(compiled) do config = compiled |> Map.put(:id, id) |> Map.put_new(:module_id, nil) |> Map.put_new(:locals, []) string = preprocess(string) string = Enum.reduce(@regexes, string, fn {kind, language, link_type}, acc -> link(acc, language, kind, link_type, config) end) postprocess(string) end @doc """ Autolinks all module nodes. This is the main API to autolink any module nodes. """ def all(modules, compiled) do opts = [timeout: :infinity] modules |> Task.async_stream(&(&1 |> all_docs(compiled) |> all_typespecs(compiled)), opts) |> Enum.map(&elem(&1, 1)) end defp all_docs(module, compiled) do funs = for doc <- module.docs, prefix = doc_prefix(doc), entry <- [doc.id | doc.defaults], do: prefix <> entry types = Enum.map(module.typespecs, &("t:" <> &1.id)) compiled = compiled |> Map.put(:module_id, module.id) |> Map.put(:locals, funs ++ types) moduledoc = project_doc(module.doc, id(module, nil), compiled) docs = for node <- module.docs do doc = project_doc(node.doc, id(module, node), compiled) %{node | doc: doc} end typedocs = for node <- module.typespecs do doc = project_doc(node.doc, id(module, node), compiled) %{node | doc: doc} end %{module | doc: moduledoc, docs: docs, typespecs: typedocs} end defp id(%{id: id}, nil), do: id defp id(%{id: mod_id}, %ExDoc.FunctionNode{id: id, type: :callback}), do: "c:#{mod_id}.#{id}" defp id(%{id: mod_id}, %ExDoc.FunctionNode{id: id}), do: "#{mod_id}.#{id}" defp id(%{id: mod_id}, %ExDoc.TypeNode{id: id}), do: "t:#{mod_id}.#{id}" defp all_typespecs(module, compiled) do %{aliases: aliases, lib_dirs: lib_dirs} = compiled locals = Enum.map(module.typespecs, fn %ExDoc.TypeNode{name: name, arity: arity} -> {name, arity} end) typespecs = for typespec <- module.typespecs do %{typespec | spec: typespec(typespec.spec, locals, aliases, lib_dirs)} end docs = for module_node <- module.docs do %{ module_node | specs: Enum.map(module_node.specs, &typespec(&1, locals, aliases, lib_dirs)) } end %{module | typespecs: typespecs, docs: docs} end @doc """ Helper function for autolinking typespecs. It converts the given `ast` to string while linking the locals given by `typespecs` as HTML. """ def typespec(ast, typespecs, aliases \\ [], lib_dirs \\ default_lib_dirs()) do {formatted, placeholders} = format_and_extract_typespec_placeholders(ast, typespecs, aliases, lib_dirs) replace_placeholders(formatted, placeholders) end @doc false def format_and_extract_typespec_placeholders(ast, typespecs, aliases, lib_dirs) do ref = make_ref() elixir_docs = get_elixir_docs(aliases, lib_dirs) {formatted_ast, placeholders} = Macro.prewalk(ast, %{}, fn {:::, _, [{name, meta, args}, right]}, placeholders when is_atom(name) and is_list(args) -> {{:::, [], [{{ref, name}, meta, args}, right]}, placeholders} # Consume this form so that we don't autolink `foo` in `foo :: bar` {{^ref, name}, _, args}, placeholders when is_atom(name) and is_list(args) -> {{name, [], args}, placeholders} {name, _, args} = form, placeholders when is_atom(name) and is_list(args) -> arity = length(args) cond do {name, arity} in @basic_types -> url = elixir_docs <> @basic_types_page put_placeholder(form, url, placeholders) {name, arity} in @built_in_types -> url = elixir_docs <> @built_in_types_page put_placeholder(form, url, placeholders) {name, arity} in typespecs -> n = enc_h("#{name}") url = "#t:#{n}/#{arity}" put_placeholder(form, url, placeholders) true -> {form, placeholders} end {{:., _, [alias, name]}, _, args} = form, placeholders when is_atom(name) and is_list(args) -> alias = expand_alias(alias) if source = get_source(alias, aliases, lib_dirs) do url = type_remote_url(source, alias, name, args) put_placeholder(form, url, placeholders) else {form, placeholders} end form, placeholders -> {form, placeholders} end) {format_ast(formatted_ast), placeholders} end defp type_remote_url(@erlang_docs = source, module, name, _args) do module = enc_h("#{module}") name = enc_h("#{name}") "#{source}#{module}.html#type-#{name}" end defp type_remote_url(source, alias, name, args) do name = enc_h("#{name}") "#{source}#{enc_h(inspect(alias))}.html#t:#{name}/#{length(args)}" end defp typespec_string_to_link(string, url) do {string_to_link, _string_with_parens} = split_string_to_link(string) ~s[<a href="#{url}">#{h(string_to_link)}</a>] end defp put_placeholder(form, url, placeholders) do string = Macro.to_string(form) link = typespec_string_to_link(string, url) case Enum.find(placeholders, fn {_key, value} -> value == link end) do {placeholder, _} -> form = put_elem(form, 0, placeholder) {form, placeholders} nil -> count = map_size(placeholders) + 1 placeholder = placeholder(string, count) form = put_elem(form, 0, placeholder) {form, Map.put(placeholders, placeholder, link)} end end defp placeholder(string, count) do [name | _] = String.split(string, "(", trim: true) name_size = String.length(name) int_size = count |> Integer.digits() |> length() underscores_size = 2 pad = String.duplicate("p", max(name_size - int_size - underscores_size, 1)) :"_#{pad}#{count}_" end defp replace_placeholders(string, placeholders) do Regex.replace(~r"_p+\d+_", string, &Map.fetch!(placeholders, String.to_atom(&1))) end defp format_ast(ast) do ast |> Macro.to_string() |> Code.format_string!(line_length: 80) |> IO.iodata_to_binary() end # Helper function for autolinking functions and modules. # # It autolinks all links for a certain `language` and of a certain `kind`. # # `language` can be: `:elixir`, `:erlang` or `:markdown`. # # `kind` is either `:function`, `:module`, or `:mix_task`. # # It accepts a list of `options` used in the replacement functions. # - `:aliases # - `:docs_refs` # - `:extension` - Default value is `".html"` # - `:lib_dirs` # - `:locals` - A list of local functions # - `:module_id` - Module of the current doc. Default value is `nil` # - `:modules_refs` - List of modules available # # Internal options: # - `:preprocess?` - `true` or `false`. Do preprocessing and postprocessing, such as replacing backticks # with a token defp link(string, language, kind, link_type, options) when is_map(options) do regex = re_kind_language_link_type(kind, language, link_type) replace_fun = replace_fun(kind, language, link_type, options) Regex.replace(regex, string, replace_fun) end defp preprocess(string) do regex = ~r{ \[([^\]]*?`[^\]]*?)\] \(([^\)]*?)\) }x Regex.replace(regex, string, fn _all, text, link -> new_text = String.replace(text, :binary.compile_pattern("`"), @backtick_token) "[#{new_text}](#{link})" end) end defp postprocess(string) do String.replace(string, :binary.compile_pattern(@backtick_token), "`") end # The heart of the autolinking logic defp replace_fun(kind, :erlang, link_type, options) do lib_dirs = options[:lib_dirs] || default_lib_dirs(:erlang) fn all, text, match -> pmfa = {_prefix, module, function, arity} = split_function(match) text = default_text(:erlang, link_type, match, pmfa, text) if doc = module_docs(:erlang, module, lib_dirs) do case kind do :module -> "[#{text}](#{doc}#{module}.html)" :function -> "[#{text}](#{doc}#{module}.html##{function}-#{arity})" end else all end end end defp replace_fun(:module, :elixir, _link_type, options) do extension = options[:extension] || ".html" lib_dirs = options[:lib_dirs] || default_lib_dirs(:elixir) module_id = options[:module_id] || nil modules_refs = options[:modules_refs] || [] fn all, _text, match -> cond do match == module_id -> "[`#{match}`](#{match}#{extension}#content)" match in modules_refs -> "[`#{match}`](#{match}#{extension})" doc = module_docs(:elixir, match, lib_dirs) -> "[`#{match}`](#{doc}#{match}.html)" true -> all end end end defp replace_fun(:function, :elixir, link_type, options) do aliases = options[:aliases] || [] docs_refs = options[:docs_refs] || [] modules_refs = options[:modules_refs] || [] extension = options[:extension] || ".html" lib_dirs = options[:lib_dirs] || default_lib_dirs(:elixir) locals = options[:locals] || [] elixir_docs = get_elixir_docs(aliases, lib_dirs) id = options[:id] module_id = options[:module_id] skip_warnings_on = options[:skip_undefined_reference_warnings_on] || [] fn all, text, match -> pmfa = {prefix, module, function, arity} = split_function(match) text = default_text(:elixir, link_type, match, pmfa, text) cond do match in locals -> "[#{text}](##{prefix}#{enc_h(function)}/#{arity})" match in docs_refs -> "[#{text}](#{module}#{extension}##{prefix}#{enc_h(function)}/#{arity})" match in @basic_type_strings -> "[#{text}](#{elixir_docs}#{@basic_types_page})" match in @built_in_type_strings -> "[#{text}](#{elixir_docs}#{@built_in_types_page})" match in @kernel_function_strings -> "[#{text}](#{elixir_docs}Kernel#{extension}##{prefix}#{enc_h(function)}/#{arity})" match in @special_form_strings -> "[#{text}](#{elixir_docs}Kernel.SpecialForms" <> "#{extension}##{prefix}#{enc_h(function)}/#{arity})" module in modules_refs -> if module_id not in skip_warnings_on and id not in skip_warnings_on do IO.warn( "documentation references #{match} but it doesn't exist " <> "or it's listed as @doc false (parsing #{id} docs)", [] ) end all doc = module_docs(:elixir, module, lib_dirs) -> "[#{text}](#{doc}#{module}.html##{prefix}#{enc_h(function)}/#{arity})" true -> all end end end defp replace_fun(:mix_task, :elixir, :normal, options) do extension = options[:extension] || ".html" lib_dirs = options[:lib_dirs] || default_lib_dirs(:elixir) module_id = options[:module_id] || nil modules_refs = options[:modules_refs] || [] fn all, text, "mix " <> task_name -> match = task_module(task_name) cond do match == module_id -> "[#{text}](#{match}#{extension}#content)" match in modules_refs -> "[#{text}](#{match}#{extension})" doc = module_docs(:elixir, match, lib_dirs) -> "[#{text}](#{doc}#{match}.html)" true -> all end end end defp task_module("help " <> task_name) do task_module(task_name) end defp task_module(task_name) do task_module = task_name |> String.split(".") |> Enum.map(&Macro.camelize/1) |> Enum.join(".") "Mix.Tasks." <> task_module end ## Helpers defp default_text(_, :custom, _match, _pmfa, text), do: text defp default_text(:erlang, _link_type, match, _pmfa, _text), do: "`#{match}`" defp default_text(:elixir, _link_type, _match, {_prefix, module, function, arity}, _text) do if module == "" do # local "`#{function}/#{arity}`" else "`#{module}.#{function}/#{arity}`" end end defp default_lib_dirs(), do: default_lib_dirs(:elixir) ++ default_lib_dirs(:erlang) defp default_lib_dirs(:elixir), do: elixir_lib_dirs() ++ hex_lib_dirs() defp default_lib_dirs(:erlang), do: erlang_lib_dirs() defp module_docs(:elixir, module, lib_dirs), do: lib_dirs_to_doc("Elixir." <> module, lib_dirs) defp module_docs(:erlang, module, lib_dirs), do: lib_dirs_to_doc(module, lib_dirs) @doc false def split_function(string) when is_binary(string), do: split_function_string(string) defp split_function_string("c:" <> string) do {_, mod, fun, arity} = split_function(string) {"c:", mod, fun, arity} end defp split_function_string("t:" <> string) do {_, mod, fun, arity} = split_function_string(string) {"t:", mod, fun, arity} end defp split_function_string(":" <> string) do {_, mod, fun, arity} = split_function_string(string) {":", mod, fun, arity} end defp split_function_string(string) do string |> String.split("/") |> split_function_list() end # handles a single module defp split_function_list([module]) do {"", module, "", ""} end defp split_function_list([modules, arity]) do {mod, name} = modules # this handles the case of the ".." function |> String.replace(~r{([^\.])\.}, "\\1 ") |> String.split(" ") |> Enum.split(-1) {"", Enum.join(mod, "."), hd(name), arity} end # handles "/" function defp split_function_list([modules, "", arity]) when is_binary(modules) do split_function_list([modules <> "/", arity]) end defp doc_prefix(%{type: c}) when c in [:callback, :macrocallback], do: "c:" defp doc_prefix(%{type: _}), do: "" defp lib_dirs_to_doc(module, lib_dirs) do case :code.where_is_file('#{module}.beam') do :non_existing -> nil path -> path = path |> List.to_string() |> Path.expand() lib_dirs |> Enum.filter(fn {lib_dir, _} -> String.starts_with?(path, lib_dir) end) |> Enum.sort_by(fn {lib_dir, _} -> -byte_size(lib_dir) end) |> case do [{_, doc} | _] -> doc _ -> nil end end end defp elixir_lib_dirs do case Application.fetch_env(:ex_doc, :elixir_lib_dirs) do {:ok, lib_dirs} -> lib_dirs :error -> lib_dirs = for app <- ~w(elixir eex iex logger mix ex_unit) do {elixir_lib_dir(app), @elixir_docs <> app <> "/"} end Application.put_env(:ex_doc, :elixir_lib_dirs, lib_dirs) lib_dirs end end defp elixir_lib_dir(app) do path = case :code.where_is_file('Elixir.Kernel.beam') do :non_existing -> "" path -> path |> List.to_string() |> Path.expand() end if File.exists?(path) do elixir_root_lib = path |> Path.dirname() |> Path.dirname() |> Path.dirname() elixir_root_lib <> "/" <> app <> "/ebin" else # if beam file doesn't exists it's likely an escript Path.dirname(path) end end defp hex_lib_dirs() do if Application.spec(:hex, :vsn) do [{Application.app_dir(:hex, "ebin"), @elixir_docs <> "hex/"}] else # if Hex is not loaded it's likely an escript [] end end defp erlang_lib_dirs do case Application.fetch_env(:ex_doc, :erlang_lib_dirs) do {:ok, lib_dirs} -> lib_dirs :error -> lib_dirs = [{Path.expand(:code.lib_dir()), @erlang_docs}] Application.put_env(:ex_doc, :erlang_lib_dirs, lib_dirs) lib_dirs end end defp split_string_to_link(string) do case :binary.split(string, "(") do [head, tail] -> {head, "(" <> tail} [head] -> {head, ""} end end defp expand_alias({:__aliases__, _, [h | t]}) when is_atom(h), do: Module.concat([h | t]) defp expand_alias(atom) when is_atom(atom), do: atom defp expand_alias(_), do: nil defp get_source(alias, aliases, lib_dirs) do cond do is_nil(alias) -> nil alias in aliases -> "" doc = lib_dirs_to_doc(alias, lib_dirs) -> doc true -> nil end end defp get_elixir_docs(aliases, lib_dirs) do get_source(Kernel, aliases, lib_dirs) end @doc false def backtick_token(), do: @backtick_token ## REGULAR EXPRESSION HELPERS # Returns a the string source of a regular expression, # given the `name` and `language` defp re_source(name, language \\ :elixir) do Regex.source(re(name, language)) end # Returns a regular expression # given the `name` and `language` defp re(:prefix, :elixir) do ~r{ [ct]: # c:, t: }x end defp re(:m, :elixir) do ~r{ ( [A-Z] # start with uppercase letter [_a-zA-Z0-9]*\.? # followed by optional letter, number or underscore )+ # this pattern could be repeated (?<!\.) # it must not end with a "." }x end defp re(:m, :erlang) do ~r{ : # prefix [A-Za-z_]+ # module_name }x end defp re(:f, :elixir) do ~r{ ([a-z_][_a-zA-Z0-9]*[\\?\\!]?) # regular function_name | # OR [\{\}=&\\|\\.<>~*^@\\+\\%\\!-\/]+ # special_form }x end defp re(:f, :erlang) do ~r{ ([a-z_][_a-zA-Z0-9]*[\\?\\!]?) }x end defp re(:fa, language) when language in [:elixir, :erlang] do ~r{ (#{re_source(:f, language)}) # function_name /\d+ # /arity }x end defp re(:mfa, :elixir) do ~r{ (#{re_source(:prefix)})? # optional callback/type identifier or ":" ( (#{re_source(:m)}\.) #{re_source(:fa)} ) }x end defp re(:mfa, :erlang) do ~r{ #{re_source(:m, :erlang)} # module_name \. # "." #{re_source(:fa, :erlang)} # function_name/arity }x end defp re(:local, :elixir) do ~r{ (#{re_source(:prefix)})? # optional callback or type identifier #{re_source(:fa)} # function_name/arity }x end defp re_kind_language(:module, :elixir) do ~r{ #{re_source(:m)} }x end defp re_kind_language(:module, :erlang) do ~r{ #{re_source(:m, :erlang)} }x end defp re_kind_language(:function, :elixir) do ~r{ (#{re_source(:local)}) | (#{re_source(:mfa)}) }x end defp re_kind_language(:function, :erlang) do ~r{ #{re_source(:mfa, :erlang)} }x end defp re_kind_language(:mix_task, :elixir) do ~r{ mix\ (help\ )?([a-z][a-z0-9\._]*) }x end defp re_kind_language_link_type(kind, language, link_type) do source = Regex.source(re_kind_language(kind, language)) case link_type do :normal -> # Capture 1 is ignored ~r{ (?<!\]\() # it shouldn't be preceded by "](" (?<!``) (`\s* # leading backtick (#{source}) # CAPTURE 2 \s*`) # trailing backtick (?!`) # (?!\)\]) # it shouldn't be followed by ")]" }x :custom -> ~r{ \[(.*?)\] # CAPTURE 1 \(`(#{source})`\) # CAPTURE 2 }x end end end
27.59904
106
0.573815
03727cf6d084a810656e7b5fd8b7f4a73356d57d
3,002
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_symbol.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_symbol.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_symbol.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Symbol do @moduledoc """ A single symbol representation. ## Attributes * `boundingBox` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1BoundingPoly.t`, *default:* `nil`) - The bounding box for the symbol. The vertices are in the order of top-left, top-right, bottom-right, bottom-left. When a rotation of the bounding box is detected the rotation is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: * when the text is horizontal it might look like: 0----1 | | 3----2 * when it's rotated 180 degrees around the top-left corner it becomes: 2----3 | | 1----0 and the vertice order will still be (0, 1, 2, 3). * `confidence` (*type:* `number()`, *default:* `nil`) - Confidence of the OCR results for the symbol. Range [0, 1]. * `property` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1TextAnnotationTextProperty.t`, *default:* `nil`) - Additional information detected for the symbol. * `text` (*type:* `String.t`, *default:* `nil`) - The actual UTF-8 representation of the symbol. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :boundingBox => GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1BoundingPoly.t(), :confidence => number(), :property => GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1TextAnnotationTextProperty.t(), :text => String.t() } field(:boundingBox, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1BoundingPoly) field(:confidence) field( :property, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1TextAnnotationTextProperty ) field(:text) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Symbol do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Symbol.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1Symbol do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.5
177
0.706196
03729f0500bd17531f99ea28b3aa8e8d6eece34f
1,915
ex
Elixir
clients/content/lib/google_api/content/v2/model/orderreturns_list_response.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orderreturns_list_response.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orderreturns_list_response.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Content.V2.Model.OrderreturnsListResponse do @moduledoc """ ## Attributes - kind (String.t): Identifies what kind of resource this is. Value: the fixed string \&quot;content#orderreturnsListResponse\&quot;. Defaults to: `null`. - nextPageToken (String.t): The token for the retrieval of the next page of returns. Defaults to: `null`. - resources ([MerchantOrderReturn]): Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => any(), :nextPageToken => any(), :resources => list(GoogleApi.Content.V2.Model.MerchantOrderReturn.t()) } field(:kind) field(:nextPageToken) field(:resources, as: GoogleApi.Content.V2.Model.MerchantOrderReturn, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrderreturnsListResponse do def decode(value, options) do GoogleApi.Content.V2.Model.OrderreturnsListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrderreturnsListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.462963
155
0.738903
0372b1f84bd236e1b4070b9b4233585f99de79f4
2,276
exs
Elixir
mix.exs
sasanchezag/elixir_xdr
a367bd6ad4b636c1f8236efbe59e1136e992cec1
[ "MIT" ]
null
null
null
mix.exs
sasanchezag/elixir_xdr
a367bd6ad4b636c1f8236efbe59e1136e992cec1
[ "MIT" ]
null
null
null
mix.exs
sasanchezag/elixir_xdr
a367bd6ad4b636c1f8236efbe59e1136e992cec1
[ "MIT" ]
null
null
null
defmodule XDR.MixProject do use Mix.Project @github_url "https://github.com/kommitters/elixir_xdr" @version "0.1.5" def project do [ app: :elixir_xdr, version: @version, elixir: ">= 1.7.0", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, name: "Elixir XDR", source_url: @github_url, description: description(), package: package(), deps: deps(), docs: docs(), test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ] ] end def deps do [ {:ex_doc, "~> 0.21", only: :dev, runtime: false}, {:credo, "~> 1.4", only: [:dev, :test], runtime: false}, {:excoveralls, "~> 0.10", only: :test} ] end defp description() do "Process XDR data with elixir. Based on the RFC4506 standard." end defp docs() do [ main: "readme", name: "Elixir XDR", source_ref: "v#{@version}", canonical: "http://hexdocs.pm/elixir_xdr", source_url: @github_url, extras: extras(), groups_for_extras: groups_for_extras() ] end defp extras() do [ "README.md", "CHANGELOG.md", "guides/examples/integer.md", "guides/examples/unsigned_integer.md", "guides/examples/enumeration.md", "guides/examples/boolean.md", "guides/examples/hyper_integer.md", "guides/examples/unsigned_hyper_integer.md", "guides/examples/floating_point.md", "guides/examples/double_floating_point.md", "guides/examples/fixed_length_opaque.md", "guides/examples/variable_length_opaque.md", "guides/examples/string.md", "guides/examples/fixed_length_array.md", "guides/examples/variable_length_array.md", "guides/examples/structure.md", "guides/examples/discriminated_union.md", "guides/examples/void.md", "guides/examples/optional_data.md" ] end defp groups_for_extras do [ Examples: ~r/guides\/examples\/.?/ ] end defp package() do [ name: "elixir_xdr", licenses: ["MIT"], links: %{"GitHub" => @github_url} ] end end
24.73913
66
0.598418
0372d64d42a14e74e4ed52b7f6fb79ac3824b754
3,839
exs
Elixir
test/credo/check/readability/large_numbers_test.exs
sevenseacat/credo
48837401040d9c2340b5fb9c7d786d31f89f6426
[ "MIT" ]
null
null
null
test/credo/check/readability/large_numbers_test.exs
sevenseacat/credo
48837401040d9c2340b5fb9c7d786d31f89f6426
[ "MIT" ]
null
null
null
test/credo/check/readability/large_numbers_test.exs
sevenseacat/credo
48837401040d9c2340b5fb9c7d786d31f89f6426
[ "MIT" ]
null
null
null
defmodule Credo.Check.Readability.LargeNumbersTest do use Credo.TestHelper @described_check Credo.Check.Readability.LargeNumbers # # cases NOT raising issues # @tag needs_elixir: "1.3.2" test "it should NOT report expected code" do """ @budgets %{ "budget1": 100_000, "budget2": 200_000, "budget3": 300_000, "budget4": 500_000, "budget5": 1_000_000, "budget6": 2_000_000 } @int32_min -2_147_483_648 @int32_max 2_147_483_647 @int64_min -9_223_372_036_854_775_808 @int64_max 9_223_372_036_854_775_807 def numbers do 1024 + 1_000_000 + 11_000 + 22_000 + 33_000 10_000..20_000 end """ |> to_source_file |> refute_issues(@described_check) end test "it should allow multiple large floats on a line" do """ def numbers do 100_000.1 + 5_000_000.2 + 66_000.3 end """ |> to_source_file |> refute_issues(@described_check) end test "it should not complain about non-decimal numbers" do """ def numbers do 0xFFFF 0b1111_1111_1111_1111 0o777_777 end """ |> to_source_file |> refute_issues(@described_check) end test "check old false positive is fixed /1" do " defmacro oid_ansi_x9_62, do: quote do: {1,2,840,10_045}" |> to_source_file |> refute_issues(@described_check) end @tag needs_elixir: "1.3.2" test "check old false positive is fixed /2" do """ %{ bounds: [ 0, 1, 2, 5, 10, 20, 30, 65, 85, 100, 200, 400, 800, 1_000, 2_000, 4_000, 8_000, 16_000] } """ |> to_source_file |> refute_issues(@described_check) end # # cases raising issues # test "it should report a violation" do """ def numbers do 1024 + 1000000 + 43534 end """ |> to_source_file |> assert_issues(@described_check) end test "it should report a violation, since it is formatted incorrectly" do """ def numbers do 1024 + 10_00_00_0 + 43534 end """ |> to_source_file |> assert_issues(@described_check) end test "it should report only one violation" do """ def numbers do 1024 + 1000000 + 43534 end """ |> to_source_file |> assert_issue(@described_check, only_greater_than: 50000) end test "it should report only one violation for ranges /1" do """ def numbers do 10000..20_000 end """ |> to_source_file |> assert_issue(@described_check) end test "it should report only one violation for ranges /2" do """ def numbers do 10_000..20000 end """ |> to_source_file |> assert_issue(@described_check) end test "it should report only two violation for ranges" do """ def numbers do 10000..20000 end """ |> to_source_file |> assert_issues(@described_check) end test "it should report a violation /2" do """ defp numbers do 1024 + 43534 end """ |> to_source_file |> assert_issue(@described_check) end test "it should report a violation /3" do """ defp numbers do 1024 + 43534.0 end """ |> to_source_file |> assert_issue(@described_check) end test "it should report a violation /4" do """ defmacro numbers do 1024 + 1_000000 end """ |> to_source_file |> assert_issue(@described_check) end test "it should format floating point numbers nicely" do """ def numbers do 10000.00001 end """ |> to_source_file |> assert_issue(@described_check, fn(%Credo.Issue{message: message}) -> assert Regex.run(~r/[\d\._]+/, message) |> hd == "10_000.00001" end) end test "it should report all digits from the source" do """ def numbers do 10000.000010 end """ |> to_source_file |> assert_issue(@described_check, fn(%Credo.Issue{message: message}) -> assert Regex.run(~r/[\d\._]+/, message) |> hd == "10_000.000010" end) end test "it should detect report issues with multiple large floats on a line" do """ def numbers do 100_000.1 + 5_000_000.2 + 66000.3 end """ |> to_source_file |> assert_issue(@described_check) end end
19.687179
79
0.679083
0372d8e26ce57cb9f6a451616d655de24de0818d
10,017
ex
Elixir
apps/irc/lib/irc/admin_handler.ex
friendshipismagic/Hekateros
0d340b6818583e2e65b0395227c9bb91796e5f89
[ "MIT" ]
2
2019-03-22T12:29:37.000Z
2021-01-08T17:25:32.000Z
apps/irc/lib/irc/admin_handler.ex
friendshipismagic/Hecateros
0d340b6818583e2e65b0395227c9bb91796e5f89
[ "MIT" ]
8
2017-12-04T16:53:35.000Z
2018-04-08T11:01:46.000Z
apps/irc/lib/irc/admin_handler.ex
friendshipismagic/Hekateros
0d340b6818583e2e65b0395227c9bb91796e5f89
[ "MIT" ]
null
null
null
defmodule IRC.AdminHandler do alias IRC.State import IRC.Helpers, only: [get_whois: 1, check_auth: 1] import Core.Users, only: [check_admin: 2, add_admin: 2] alias Core.{Chan,Repo} require Logger use GenServer def start_link(%State{}=state) do GenServer.start_link(__MODULE__, state.client, name: __MODULE__) end def init(client) do ExIRC.Client.add_handler(client, self()) {:ok, client} end #### Messages #### def handle_info({:received, "summary " <> channel, sender}, client=state) do channel = channel |> String.downcase |> String.trim response = sender |> is_admin(channel, client) |> process_auth({:summary, channel}) |> String.split("\n") Enum.each(response, fn msg -> ExIRC.Client.msg(client, :privmsg, sender.nick, msg) end) {:noreply, state} end def handle_info({:received, "show url " <> rest, sender}, client=state) do channel = rest |> String.downcase |> String.trim response = sender |> is_admin(channel, client) |> process_auth({:show_url, channel}) ExIRC.Client.msg(client, :privmsg, sender.nick, response) {:noreply, state} end def handle_info({:received, "add admin " <> rest, sender}, client=state) do [channel, nick] = String.split(rest, " ") response = sender |> is_admin(channel, client) |> process_auth({:add_admin, channel, nick}) ExIRC.Client.msg(client, :privmsg, sender.nick, response) {:noreply, state} end def handle_info({:received, "url filter " <> rest, sender}, client=state) do IO.puts rest case String.split(String.downcase(rest), " ") do [channel, "show"] -> response = sender |> is_admin(channel, client) |> process_auth({:show_filter_url, channel}) ExIRC.Client.msg(client, :privmsg, sender.nick, response) [channel, switch] when switch in ["on", "off"] -> response = sender |> is_admin(channel, client) |> process_auth({:filter_url, channel, switch}) ExIRC.Client.msg(client, :privmsg, sender.nick, response) [channel, command, urls] when command in ["add", "delete", "replace"] -> urllist = MapSet.new(String.split(urls, ",")) response = case command do "add" -> sender |> is_admin(channel, client) |> process_auth({:add_url_filter, channel, urllist}) "delete" -> sender |> is_admin(channel, client) |> process_auth({:delete_url_filter, channel, urllist}) "replace" -> sender |> is_admin(channel, client) |> process_auth({:replace_url_filter, channel, urllist}) end ExIRC.Client.msg(client, :privmsg, sender.nick, response) _ -> ExIRC.Client.msg(client, :privmsg, sender.nick, "Invalid syntax. Please use `url filter <#channel> <on|off>`") end {:noreply, state} end def handle_info({:received, "tag filter " <> rest, sender}, client=state) do IO.puts rest case String.split(String.downcase(rest), " ") do [channel, "show"] -> response = sender |> is_admin(channel, client) |> process_auth({:show_filter_tag, channel}) ExIRC.Client.msg(client, :privmsg, sender.nick, response) [channel, switch] when switch in ["on", "off"] -> response = sender |> is_admin(channel, client) |> process_auth({:filter_tag, channel, switch}) ExIRC.Client.msg(client, :privmsg, sender.nick, response) [channel, command, tags] when command in ["add", "delete", "replace"] -> taglist = MapSet.new(String.split(tags, ",")) response = case command do "add" -> sender |> is_admin(channel, client) |> process_auth({:add_tag_filter, channel, taglist}) "delete" -> sender |> is_admin(channel, client) |> process_auth({:delete_tag_filter, channel, taglist}) "replace" -> sender |> is_admin(channel, client) |> process_auth({:replace_tag_filter, channel, taglist}) end ExIRC.Client.msg(client, :privmsg, sender.nick, response) _ -> ExIRC.Client.msg(client, :privmsg, sender.nick, "Invalid syntax. Please use `tag filter <#channel> <on|off>`") end {:noreply, state} end def handle_info({:received, msg, sender}, state) do Logger.debug "[Privmsg] “#{sender.nick}: #{msg}”" ExIRC.Client.msg(state, :privmsg, sender.nick, "I'm afraid I can't do that Dave…") {:noreply, state} end ################## def handle_info(_, state) do {:noreply, state} end @spec check_and_add_admin(String.t, String.t) :: {:ok, Ecto.Changeset.t} | {:error, atom()} defp check_and_add_admin(channel, nick) do if channel == "" || nick == "" do {:error, :invalid} else user = get_whois(nick) add_admin(channel, user) end end def is_admin(sender, channel, client) do ExIRC.Client.whois(client, sender.nick) user = get_whois(sender.nick) with {:ok, :authed} <- check_auth(user), {:ok, :admin} <- check_admin(user, channel), do: {:ok, :admin} end def process_auth({:ok, :admin}, message) do process_message(message) end def process_auth({:error, :noadmin}, _) do "You're not an admin for this channel." end def process_auth({:error, :nochan}, _) do "Am I getting old or did you misspell the channel's name?" end def process_auth({:error, :unauthed}) do "You don't seem registered with NickServ…" end ### URL filter ### def process_message({:show_filter_url, channel}) do urllist = Repo.get_by(Chan, name: channel) |> Map.get(:settings) |> Map.get(:url_filters) if (urllist != [] and urllist != nil) do "Forbidden URLs for #{channel} are: #{Enum.join(urllist, ", ")}." else "No URLs are currently filtered…" end end def process_message({:filter_url, channel, switch}) do Chan.switch_url_filters(String.to_atom(switch), channel) "Switched urls filter #{switch} on #{channel}" end def process_message({:add_url_filter, channel, urllist}) do chan = Repo.get_by(Chan, name: channel) Chan.add_url_filters(chan, urllist) "URL(s) #{Enum.join(urllist, ", ")} added to the filter." end def process_message({:delete_url_filter, channel, urllist}) do chan = Repo.get_by(Chan, name: channel) Chan.delete_url_filters(chan, urllist) "URL(s) #{Enum.join(urllist, ", ")} deleted from the filter." end def process_message({:replace_url_filter, channel, urllist}) do chan = Repo.get_by(Chan, name: channel) Chan.replace_url_filters(chan, urllist) "URL(s) #{Enum.join(urllist, ", ")} are now the filter." end ### Tag filter ### def process_message({:show_filter_tag, channel}) do taglist = Repo.get_by(Chan, name: channel) |> Map.get(:settings) |> Map.get(:tag_filters) if (taglist != [] and taglist != nil) do "Authorized tags for #{channel} are: #{Enum.join(taglist, ", ")}." else "No tags are currently filtered…" end end def process_message({:filter_tag, channel, switch}) do Chan.switch_tag_filters(String.to_atom(switch), channel) "Switched tags filter #{switch} on #{channel}" end def process_message({:add_tag_filter, channel, taglist}) do chan = Repo.get_by(Chan, name: channel) Chan.add_tag_filters(chan, taglist) "Tag(s) #{Enum.join(taglist, ", ")} added to the filter." end def process_message({:delete_tag_filter, channel, taglist}) do chan = Repo.get_by(Chan, name: channel) Chan.delete_tag_filters(chan, taglist) "Tag(s) #{Enum.join(taglist, ", ")} deleted from the filter." end def process_message({:replace_tag_filter, channel, taglist}) do chan = Repo.get_by(Chan, name: channel) Chan.replace_tag_filters(chan, taglist) "Tag(s) #{Enum.join(taglist, ", ")} are now the filter." end ### Misc ### def process_message({:summary, channel_name}) do chan = Repo.get_by(Chan, name: channel_name) |> Repo.preload(:admins) tag_filters_status = if chan.settings.has_tag_filter? do "[\x02\x0303activated\x03\x0F] " else "[\x02\x0304deactivated\x03\x0F]" end url_filters_status = if chan.settings.has_url_filter? do "[\x02\x0303activated\x03\x0F] " else "[\x02\x0304deactivated\x03\x0F]" end url_filters = Enum.join(chan.settings.url_filters, ", ") tag_filters = Enum.join(chan.settings.tag_filters, ", ") admins = Enum.map(chan.admins, fn a -> a.account_name end) |> Enum.join(", ") """ \x03\x1FSummary for #{channel_name}\x0F URL: #{process_message({:show_url, channel_name})}   \x03\x02Admins:\x0F\x03 #{admins}   #{tag_filters_status} Tag filters: #{tag_filters} #{url_filters_status} URL filters: #{url_filters} """ end def process_message({:show_url, channel}) do {:ok, slug} = Chan.gib_slug(channel) Web.Router.Helpers.chan_url(Web.Endpoint, :show, slug) end def process_message({:add_admin, channel, nick}) do case check_and_add_admin(channel, nick) do {:ok, _} -> "Admin #{nick} succesfully added for #{channel}." {:error, :invalid} -> "Invalid syntax. Please use `add admin <#channel> <nickname>." end end end
34.304795
118
0.588799
037301f18040f82f3f29fe39bc5984d624d2210a
383
exs
Elixir
test/test_helper.exs
athonet-open/ex_sieve
19d4e977f60d032f2267f1324bb5643b4deb3bf3
[ "MIT" ]
null
null
null
test/test_helper.exs
athonet-open/ex_sieve
19d4e977f60d032f2267f1324bb5643b4deb3bf3
[ "MIT" ]
null
null
null
test/test_helper.exs
athonet-open/ex_sieve
19d4e977f60d032f2267f1324bb5643b4deb3bf3
[ "MIT" ]
null
null
null
defmodule ExSieve.TestCase do use ExUnit.CaseTemplate alias Ecto.Adapters.SQL.Sandbox using(opts) do quote do alias ExSieve.Repo use ExUnit.Case, unquote(opts) import Ecto.Query import ExSieve.Factory end end setup do Sandbox.mode(ExSieve.Repo, :manual) :ok = Sandbox.checkout(ExSieve.Repo) end end ExSieve.Repo.start_link()
15.958333
40
0.686684
037336b2fb715d32f865949bab483c3f135c77ad
109
ex
Elixir
lib/absinthe/language/list_value.ex
scrogson/absinthe
aa7e9c83dc10603c72f80e09a60d12495bc1c6b7
[ "Unlicense" ]
1
2019-05-07T15:05:52.000Z
2019-05-07T15:05:52.000Z
lib/absinthe/language/list_value.ex
scrogson/absinthe
aa7e9c83dc10603c72f80e09a60d12495bc1c6b7
[ "Unlicense" ]
null
null
null
lib/absinthe/language/list_value.ex
scrogson/absinthe
aa7e9c83dc10603c72f80e09a60d12495bc1c6b7
[ "Unlicense" ]
null
null
null
defmodule Absinthe.Language.ListValue do @moduledoc false defstruct values: [], loc: %{start: nil} end
15.571429
42
0.724771