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
0870c436a16f1f7abf24a1850d803b7b8de72e2e
362
ex
Elixir
web/controllers/blog_post_controller.ex
codebender/5280elixir
f7dee84b785b70f61b44f4dccacfe0311ad39617
[ "MIT" ]
null
null
null
web/controllers/blog_post_controller.ex
codebender/5280elixir
f7dee84b785b70f61b44f4dccacfe0311ad39617
[ "MIT" ]
null
null
null
web/controllers/blog_post_controller.ex
codebender/5280elixir
f7dee84b785b70f61b44f4dccacfe0311ad39617
[ "MIT" ]
null
null
null
defmodule Elixir5280.BlogPostController do use Elixir5280.Web, :controller alias Elixir5280.BlogPost def index(conn, _params) do blog_posts = BlogPost.all() render(conn, "index.json", blog_posts: blog_posts) end def show(conn, %{"id" => id}) do blog_post = BlogPost.get!(id) render(conn, "show.json", blog_post: blog_post) end end
22.625
54
0.698895
0870dddac397c3ca3022f94d5167fe0f1b3d7091
431
ex
Elixir
lib/bgg/supervisor.ex
peralmq/bgg-elixir
50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8
[ "MIT" ]
3
2016-01-19T14:40:39.000Z
2020-07-07T16:37:55.000Z
lib/bgg/supervisor.ex
peralmq/bgg-elixir
50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8
[ "MIT" ]
null
null
null
lib/bgg/supervisor.ex
peralmq/bgg-elixir
50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8
[ "MIT" ]
null
null
null
defmodule BGG.Supervisor do use Supervisor def start_link do :supervisor.start_link(__MODULE__, []) end def init([]) do children = [ # Define workers and child supervisors to be supervised # worker(BGG.Worker, []) ] # See http://elixir-lang.org/docs/stable/Supervisor.Behaviour.html # for other strategies and supported options supervise(children, strategy: :one_for_one) end end
20.52381
70
0.684455
0870e7eddbeb00950e04230da9cac2d0e48959a8
1,504
ex
Elixir
lib/google_api/you_tube/v3/model/playlist_snippet.ex
jesteracer/ytb
67e3cab899e4f69e586383f7be2c3855c6beea49
[ "Apache-2.0" ]
null
null
null
lib/google_api/you_tube/v3/model/playlist_snippet.ex
jesteracer/ytb
67e3cab899e4f69e586383f7be2c3855c6beea49
[ "Apache-2.0" ]
null
null
null
lib/google_api/you_tube/v3/model/playlist_snippet.ex
jesteracer/ytb
67e3cab899e4f69e586383f7be2c3855c6beea49
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.YouTube.V3.Model.PlaylistSnippet do @moduledoc """ Basic details about a playlist, including title, description and thumbnails. """ @derive [Poison.Encoder] defstruct [ :"tags", :"channelId", :"channelTitle", :"defaultLanguage", :"description", :"localized", :"publishedAt", :"thumbnails", :"title" ] end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.PlaylistSnippet do import GoogleApi.YouTube.V3.Deserializer def decode(value, options) do value |> deserialize(:"localized", :struct, GoogleApi.YouTube.V3.Model.PlaylistLocalization, options) |> deserialize(:"thumbnails", :struct, GoogleApi.YouTube.V3.Model.ThumbnailDetails, options) end end
31.333333
99
0.732048
0870f811ee2d6306153404038204be2be06b87bc
3,832
ex
Elixir
lib/changelog_web/helpers/admin_helpers.ex
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
null
null
null
lib/changelog_web/helpers/admin_helpers.ex
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
null
null
null
lib/changelog_web/helpers/admin_helpers.ex
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
null
null
null
defmodule ChangelogWeb.Helpers.AdminHelpers do use Phoenix.HTML alias Changelog.Repo alias ChangelogWeb.TimeView alias ChangelogWeb.Helpers.SharedHelpers def error_class(form, field) do if form.errors[field], do: "error", else: "" end def error_message(form, field) do case form.errors[field] do {message, _} -> content_tag :div, class: "ui pointing red basic label" do message end nil -> "" end end def file_toggle_buttons() do content_tag(:span) do [ content_tag(:a, "(use url)", href: "javascript:void(0);", class: "field-action use-url"), content_tag(:a, "(use file)", href: "javascript:void(0);", class: "field-action use-file", style: "display: none;"), ] end end def filter_select(filter, options) when is_binary(filter), do: filter_select(String.to_atom(filter), options) def filter_select(filter, options) do content_tag(:select, class: "ui fluid selection dropdown js-filter") do Enum.map(options, fn({value, label}) -> args = if filter == value do [value: value, selected: true] else [value: value] end content_tag(:option, label, args) end) end end def help_icon(help_text) do ~e""" <i class="help circle icon fluid" data-popup="true" data-variation="wide" data-content="<%= help_text %>"></i> """ end def info_icon(info_text) do ~e""" <i class="info circle icon fluid" data-popup="true" data-variation="wide" data-content="<%= info_text %>"></i> """ end def icon_link(icon_name, options) do options = Keyword.put(options, :class, "ui icon button") link content_tag(:i, "", class: "#{icon_name} icon"), options end def is_persisted(struct), do: is_integer(struct.id) def is_loaded(nil), do: false def is_loaded(%Ecto.Association.NotLoaded{}), do: false def is_loaded(_association), do: true def label_with_clear(attr, text) do content_tag(:label, for: attr) do [content_tag(:span, text), content_tag(:a, "(clear)", href: "javascript:void(0);", class: "field-action js-clear")] end end # Attempts to load an associated record on a form. Starts with direct # relationship on form data, then tries querying Repo. def load_from_form(form, module, relationship) do form_data = Map.get(form.data, relationship) foreign_key = "#{relationship}_id" record_id = Map.get(form.data, String.to_existing_atom(foreign_key)) || form.params[foreign_key] cond do is_loaded(form_data) -> form_data is_nil(record_id) -> nil true -> Repo.get(module, record_id) end end def next_param(conn, default \\ nil), do: Map.get(conn.params, "next", default) def download_count(ep_or_pod), do: ep_or_pod.download_count |> round() |> SharedHelpers.comma_separated() def reach_count(ep_or_pod) do if ep_or_pod.reach_count > ep_or_pod.download_count do SharedHelpers.comma_separated(ep_or_pod.reach_count) else download_count(ep_or_pod) end end def semantic_calendar_field(form, field) do ~e""" <div class="ui calendar"> <div class="ui input left icon"> <i class="calendar icon"></i> <%= text_input(form, field, name: "", id: "") %> <%= hidden_input(form, field) %> </div> </div> """ end def submit_button(type, text, next \\ "") do content_tag(:button, text, class: "ui #{type} fluid basic button", type: "submit", name: "next", value: next) end def ts(ts), do: TimeView.ts(ts) def ts(ts, style), do: TimeView.ts(ts, style) def up_or_down_class(a, b) when is_integer(a) and is_integer(b) do if a > b do "green" else "red" end end def yes_no_options do [{"Yes", true}, {"No", false}] end end
29.476923
124
0.643267
0870fb3264de52cfacec8f809565d6387d4bf994
103,667
ex
Elixir
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/api/customers.ex
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
null
null
null
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/api/customers.ex
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
null
null
null
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/api/customers.ex
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "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.SASPortal.V1alpha1.Api.Customers do @moduledoc """ API calls for all endpoints tagged `Customers`. """ alias GoogleApi.SASPortal.V1alpha1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Returns a requested customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the customer. * `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.SASPortal.V1alpha1.Model.SasPortalCustomer{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalCustomer.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalCustomer{}]) end @doc """ Returns a list of requested customers. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of customers to return in the response. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListCustomers method that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListCustomersResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_list(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListCustomersResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_list(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/customers", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListCustomersResponse{}] ) end @doc """ Updates an existing customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. Resource name of the customer. * `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`) - Fields to be updated. * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalCustomer.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalCustomer{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalCustomer.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalCustomer{}]) end @doc """ Creates a new deployment. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name where the deployment is to be created. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/deployments", %{ "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.SASPortal.V1alpha1.Model.SasPortalDeployment{}] ) end @doc """ Deletes a deployment. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the deployment. * `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.SASPortal.V1alpha1.Model.SasPortalEmpty{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalEmpty{}]) end @doc """ Returns a requested deployment. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the deployment. * `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.SASPortal.V1alpha1.Model.SasPortalDeployment{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalDeployment{}] ) end @doc """ Lists deployments. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name, for example, "nodes/1", customer/1/nodes/2. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of deployments to return in the response. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListDeployments method that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDeploymentsResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDeploymentsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_list(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/deployments", %{ "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.SASPortal.V1alpha1.Model.SasPortalListDeploymentsResponse{}] ) end @doc """ Moves a deployment under another node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the deployment to move. * `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.SASPortal.V1alpha1.Model.SasPortalMoveDeploymentRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalOperation{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_move(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalOperation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_move(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("/v1alpha1/{+name}:move", %{ "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.SASPortal.V1alpha1.Model.SasPortalOperation{}]) end @doc """ Updates an existing deployment. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. Resource name. * `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`) - Fields to be updated. * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalDeployment{}] ) end @doc """ Creates a device under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_devices_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_devices_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/devices", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Creates a signed device under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalCreateSignedDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_devices_create_signed( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_devices_create_signed( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/devices:createSigned", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Lists devices under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The filter expression. The filter should have one of the following formats: "sn=123454" or "display_name=MyDevice". sn corresponds to serial_number of the device. The filter is case insensitive. * `:pageSize` (*type:* `integer()`) - The maximum number of devices to return in the response. If empty or zero, all devices will be listed. Must be in the range [0, 1000]. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListDevices that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_deployments_devices_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_deployments_devices_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/devices", %{ "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.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse{}] ) end @doc """ Creates a device under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_create(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/devices", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Creates a signed device under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalCreateSignedDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_create_signed( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_create_signed( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/devices:createSigned", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Deletes a device. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the device. * `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.SASPortal.V1alpha1.Model.SasPortalEmpty{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalEmpty{}]) end @doc """ Gets details about a device. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the device. * `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.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Lists devices under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The filter expression. The filter should have one of the following formats: "sn=123454" or "display_name=MyDevice". sn corresponds to serial_number of the device. The filter is case insensitive. * `:pageSize` (*type:* `integer()`) - The maximum number of devices to return in the response. If empty or zero, all devices will be listed. Must be in the range [0, 1000]. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListDevices that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_list(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/devices", %{ "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.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse{}] ) end @doc """ Moves a device under another node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the device to move. * `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.SASPortal.V1alpha1.Model.SasPortalMoveDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalOperation{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_move(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalOperation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_move(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("/v1alpha1/{+name}:move", %{ "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.SASPortal.V1alpha1.Model.SasPortalOperation{}]) end @doc """ Updates a device. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. The resource path name. * `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`) - Fields to be updated. * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Signs a device. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. The resource path name. * `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.SASPortal.V1alpha1.Model.SasPortalSignDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_sign_device( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_sign_device(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("/v1alpha1/{+name}:signDevice", %{ "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.SASPortal.V1alpha1.Model.SasPortalEmpty{}]) end @doc """ Updates a signed device. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the device to update. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalUpdateSignedDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_devices_update_signed( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_devices_update_signed( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1alpha1/{+name}:updateSigned", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Creates a new node. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name where the node is to be created. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_create(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_create(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/nodes", %{ "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.SASPortal.V1alpha1.Model.SasPortalNode{}]) end @doc """ Deletes a node. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the node. * `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.SASPortal.V1alpha1.Model.SasPortalEmpty{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalEmpty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalEmpty{}]) end @doc """ Returns a requested node. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the node. * `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.SASPortal.V1alpha1.Model.SasPortalNode{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalNode{}]) end @doc """ Lists nodes. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name, for example, "nodes/1". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of nodes to return in the response. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListNodes method that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListNodesResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListNodesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_list(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/nodes", %{ "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.SASPortal.V1alpha1.Model.SasPortalListNodesResponse{}] ) end @doc """ Moves a node under another node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the node to move. * `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.SASPortal.V1alpha1.Model.SasPortalMoveNodeRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalOperation{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_move(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalOperation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_move(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("/v1alpha1/{+name}:move", %{ "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.SASPortal.V1alpha1.Model.SasPortalOperation{}]) end @doc """ Updates an existing node. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. Resource name. * `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`) - Fields to be updated. * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_patch(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_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("/v1alpha1/{+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.SASPortal.V1alpha1.Model.SasPortalNode{}]) end @doc """ Creates a new deployment. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name where the deployment is to be created. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_deployments_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeployment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_deployments_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/deployments", %{ "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.SASPortal.V1alpha1.Model.SasPortalDeployment{}] ) end @doc """ Lists deployments. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name, for example, "nodes/1", customer/1/nodes/2. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of deployments to return in the response. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListDeployments method that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDeploymentsResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_deployments_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDeploymentsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_deployments_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/deployments", %{ "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.SASPortal.V1alpha1.Model.SasPortalListDeploymentsResponse{}] ) end @doc """ Creates a device under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_devices_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_devices_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/devices", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Creates a signed device under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalCreateSignedDeviceRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_devices_create_signed( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalDevice.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_devices_create_signed( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/devices:createSigned", %{ "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.SASPortal.V1alpha1.Model.SasPortalDevice{}]) end @doc """ Lists devices under a node or customer. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The name of the parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The filter expression. The filter should have one of the following formats: "sn=123454" or "display_name=MyDevice". sn corresponds to serial_number of the device. The filter is case insensitive. * `:pageSize` (*type:* `integer()`) - The maximum number of devices to return in the response. If empty or zero, all devices will be listed. Must be in the range [0, 1000]. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListDevices that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_devices_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_devices_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/devices", %{ "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.SASPortal.V1alpha1.Model.SasPortalListDevicesResponse{}] ) end @doc """ Creates a new node. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name where the node is to be created. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_nodes_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalNode.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_nodes_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1alpha1/{+parent}/nodes", %{ "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.SASPortal.V1alpha1.Model.SasPortalNode{}]) end @doc """ Lists nodes. ## Parameters * `connection` (*type:* `GoogleApi.SASPortal.V1alpha1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource name, for example, "nodes/1". * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:pageSize` (*type:* `integer()`) - The maximum number of nodes to return in the response. * `:pageToken` (*type:* `String.t`) - A pagination token returned from a previous call to ListNodes method that indicates where this listing should continue from. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.SASPortal.V1alpha1.Model.SasPortalListNodesResponse{}}` on success * `{:error, info}` on failure """ @spec sasportal_customers_nodes_nodes_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.SASPortal.V1alpha1.Model.SasPortalListNodesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def sasportal_customers_nodes_nodes_list(connection, parent, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1alpha1/{+parent}/nodes", %{ "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.SASPortal.V1alpha1.Model.SasPortalListNodesResponse{}] ) end end
45.587951
237
0.614323
08711950859c9c778705b88a72501a58c1a659c7
882
ex
Elixir
clients/calendar/lib/google_api/calendar/v3/metadata.ex
corp-momenti/elixir-google-api
fe1580e305789ab2ca0741791b8ffe924bd3240c
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/calendar/lib/google_api/calendar/v3/metadata.ex
corp-momenti/elixir-google-api
fe1580e305789ab2ca0741791b8ffe924bd3240c
[ "Apache-2.0" ]
null
null
null
clients/calendar/lib/google_api/calendar/v3/metadata.ex
corp-momenti/elixir-google-api
fe1580e305789ab2ca0741791b8ffe924bd3240c
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Calendar.V3 do @moduledoc """ API client metadata for GoogleApi.Calendar.V3. """ @discovery_revision "20210807" def discovery_revision(), do: @discovery_revision end
32.666667
74
0.758503
08714ab616695ee523b40156356c14b51ab30d5d
1,328
exs
Elixir
test/mysql/test_helper.exs
alesasnouski/ecto_enum
b32cdd58abf4e05d61f4ced951f124944cc549ec
[ "MIT" ]
null
null
null
test/mysql/test_helper.exs
alesasnouski/ecto_enum
b32cdd58abf4e05d61f4ced951f124944cc549ec
[ "MIT" ]
null
null
null
test/mysql/test_helper.exs
alesasnouski/ecto_enum
b32cdd58abf4e05d61f4ced951f124944cc549ec
[ "MIT" ]
null
null
null
Logger.configure(level: :info) ExUnit.start() alias Ecto.Integration.TestRepo alias Ecto.Integration.PoolRepo Code.require_file("ecto_migration.exs", __DIR__) Application.put_env(:ecto, TestRepo, url: "ecto://root@localhost/ecto_test", pool: Ecto.Adapters.SQL.Sandbox ) defmodule TestRepo do use Ecto.Repo, otp_app: :ecto, adapter: Ecto.Adapters.MySQL end Application.put_env(:ecto, PoolRepo, adapter: Ecto.Adapters.MySQL, url: "ecto://root@localhost/ecto_test", pool_size: 10 ) defmodule PoolRepo do use Ecto.Repo, otp_app: :ecto, adapter: Ecto.Adapters.MySQL def create_prefix(prefix) do "create database #{prefix}" end def drop_prefix(prefix) do "drop database #{prefix}" end end defmodule Ecto.Integration.Case do use ExUnit.CaseTemplate setup do :ok = Ecto.Adapters.SQL.Sandbox.checkout(TestRepo) end end {:ok, _} = Ecto.Adapters.MySQL.ensure_all_started(TestRepo, :temporary) # Load up the repository, start it, and run migrations _ = Ecto.Adapters.MySQL.storage_down(TestRepo.config()) :ok = Ecto.Adapters.MySQL.storage_up(TestRepo.config()) {:ok, _pid} = TestRepo.start_link() # {:ok, _pid} = PoolRepo.start_link :ok = Ecto.Migrator.up(TestRepo, 0, Ecto.Integration.Migration, log: false) Ecto.Adapters.SQL.Sandbox.mode(TestRepo, :auto) Process.flag(:trap_exit, true)
24.592593
75
0.746235
087170f4a25a0c989506e66b9500ba847ab6131d
1,535
ex
Elixir
lib/demo_web/endpoint.ex
pthompson/liveview_javascript_examples
93296a400a7214156c54c17c34ef11331a987984
[ "MIT" ]
null
null
null
lib/demo_web/endpoint.ex
pthompson/liveview_javascript_examples
93296a400a7214156c54c17c34ef11331a987984
[ "MIT" ]
1
2021-05-11T18:42:35.000Z
2021-05-11T18:42:35.000Z
lib/demo_web/endpoint.ex
pthompson/liveview_javascript_examples
93296a400a7214156c54c17c34ef11331a987984
[ "MIT" ]
1
2020-09-03T05:15:50.000Z
2020-09-03T05:15:50.000Z
defmodule DemoWeb.Endpoint do use Phoenix.Endpoint, otp_app: :demo # The session will be stored in the cookie and signed, # this means its contents can be read but not tampered with. # Set :encryption_salt if you would also like to encrypt it. @session_options [ store: :cookie, key: "_demo_key", signing_salt: "54NmfsZm" ] socket "/socket", DemoWeb.UserSocket, websocket: true, longpoll: false socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phx.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :demo, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Phoenix.LiveDashboard.RequestLogger, param_key: "request_logger", cookie_key: "request_logger" plug Plug.RequestId plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Phoenix.json_library() plug Plug.MethodOverride plug Plug.Head plug Plug.Session, @session_options plug DemoWeb.Router end
28.425926
97
0.713355
0871a460388aafda35649aaec697fa0a15f89465
50
exs
Elixir
config/test.exs
axelson/lifx
9ac02474d181001efc6bc08d7d39a6f6e3bb0d2a
[ "Apache-2.0" ]
null
null
null
config/test.exs
axelson/lifx
9ac02474d181001efc6bc08d7d39a6f6e3bb0d2a
[ "Apache-2.0" ]
null
null
null
config/test.exs
axelson/lifx
9ac02474d181001efc6bc08d7d39a6f6e3bb0d2a
[ "Apache-2.0" ]
null
null
null
use Mix.Config config :lifx, udp: Lifx.UdpMock
10
19
0.72
0871b0b463fb416182a4ca9b4af66385c42dade4
1,593
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1/model/sql_server_audit_config.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/sql_admin/lib/google_api/sql_admin/v1/model/sql_server_audit_config.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/sql_admin/lib/google_api/sql_admin/v1/model/sql_server_audit_config.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.SQLAdmin.V1.Model.SqlServerAuditConfig do @moduledoc """ SQL Server specific audit configuration. ## Attributes * `bucket` (*type:* `String.t`, *default:* `nil`) - The name of the destination bucket (e.g., gs://mybucket). * `kind` (*type:* `String.t`, *default:* `nil`) - This is always sql#sqlServerAuditConfig """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :bucket => String.t() | nil, :kind => String.t() | nil } field(:bucket) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1.Model.SqlServerAuditConfig do def decode(value, options) do GoogleApi.SQLAdmin.V1.Model.SqlServerAuditConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1.Model.SqlServerAuditConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.86
113
0.720025
0871b27e9337ed54d4939c373b8d59d1d1e39fcb
2,499
ex
Elixir
lib/mix/tasks/ecto.load.ex
IcyEagle/ecto
26237057d4ffff2daf5258e181eccc3238b71490
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/ecto.load.ex
IcyEagle/ecto
26237057d4ffff2daf5258e181eccc3238b71490
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/ecto.load.ex
IcyEagle/ecto
26237057d4ffff2daf5258e181eccc3238b71490
[ "Apache-2.0" ]
1
2018-09-21T16:05:29.000Z
2018-09-21T16:05:29.000Z
defmodule Mix.Tasks.Ecto.Load do use Mix.Task import Mix.Ecto @shortdoc "Loads previously dumped database structure" @default_opts [force: false, quiet: false] @aliases [ d: :dump_path, f: :force, q: :quiet ] @switches [ dump_path: :string, force: :boolean, quiet: :boolean ] @moduledoc """ Loads the current environment's database structure for the given repository from a previously dumped structure file. The repository must be set under `:ecto_repos` in the current app configuration or given via the `-r` option. This task needs some shell utility to be present on the machine running the task. Database | Utility needed :--------- | :------------- PostgreSQL | psql MySQL | mysql ## Example mix ecto.load ## Command line options * `-r`, `--repo` - the repo to load the structure info into * `-d`, `--dump-path` - the path of the dump file to load from * `-q`, `--quiet` - run the command quietly * `-f`, `--force` - do not ask for confirmation when loading data. Configuration is asked only when `:start_permanent` is set to true (typically in production) """ def run(args) do {opts, _, _} = OptionParser.parse args, switches: @switches, aliases: @aliases opts = Keyword.merge(@default_opts, opts) Enum.each parse_repo(args), fn repo -> ensure_repo(repo, args) ensure_implements(repo.__adapter__, Ecto.Adapter.Structure, "load structure for #{inspect repo}") if skip_safety_warnings?() or opts[:force] or Mix.shell.yes?("Are you sure you want to load a new structure for #{inspect repo}? Any existing data in this repo may be lost.") do load_structure(repo, opts) end end end defp skip_safety_warnings? do Mix.Project.config[:start_permanent] != true end defp load_structure(repo, opts) do config = Keyword.merge(repo.config, opts) case repo.__adapter__.structure_load(source_repo_priv(repo), config) do {:ok, location} -> unless opts[:quiet] do Mix.shell.info "The structure for #{inspect repo} has been loaded from #{location}" end {:error, term} when is_binary(term) -> Mix.raise "The structure for #{inspect repo} couldn't be loaded: #{term}" {:error, term} -> Mix.raise "The structure for #{inspect repo} couldn't be loaded: #{inspect term}" end end end
28.724138
141
0.636655
0871bfbf61c4a7333cfb6a2dddd80635eae93472
2,576
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/par_do_instruction.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/dataflow/lib/google_api/dataflow/v1b3/model/par_do_instruction.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/par_do_instruction.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.Dataflow.V1b3.Model.ParDoInstruction do @moduledoc """ An instruction that does a ParDo operation. Takes one main input and zero or more side inputs, and produces zero or more outputs. Runs user code. ## Attributes * `input` (*type:* `GoogleApi.Dataflow.V1b3.Model.InstructionInput.t`, *default:* `nil`) - The input. * `multiOutputInfos` (*type:* `list(GoogleApi.Dataflow.V1b3.Model.MultiOutputInfo.t)`, *default:* `nil`) - Information about each of the outputs, if user_fn is a MultiDoFn. * `numOutputs` (*type:* `integer()`, *default:* `nil`) - The number of outputs. * `sideInputs` (*type:* `list(GoogleApi.Dataflow.V1b3.Model.SideInputInfo.t)`, *default:* `nil`) - Zero or more side inputs. * `userFn` (*type:* `map()`, *default:* `nil`) - The user function to invoke. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :input => GoogleApi.Dataflow.V1b3.Model.InstructionInput.t(), :multiOutputInfos => list(GoogleApi.Dataflow.V1b3.Model.MultiOutputInfo.t()), :numOutputs => integer(), :sideInputs => list(GoogleApi.Dataflow.V1b3.Model.SideInputInfo.t()), :userFn => map() } field(:input, as: GoogleApi.Dataflow.V1b3.Model.InstructionInput) field(:multiOutputInfos, as: GoogleApi.Dataflow.V1b3.Model.MultiOutputInfo, type: :list) field(:numOutputs) field(:sideInputs, as: GoogleApi.Dataflow.V1b3.Model.SideInputInfo, type: :list) field(:userFn, type: :map) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.ParDoInstruction do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.ParDoInstruction.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.ParDoInstruction do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.548387
177
0.71972
0871cc8535b7a98564ee4f609eeda8ec43fa8eff
79,168
ex
Elixir
lib/elixir/lib/enum.ex
eproxus/elixir
1c3a3bde539bc96c80d917fbcf3c9dc9e123860b
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/enum.ex
eproxus/elixir
1c3a3bde539bc96c80d917fbcf3c9dc9e123860b
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/enum.ex
eproxus/elixir
1c3a3bde539bc96c80d917fbcf3c9dc9e123860b
[ "Apache-2.0" ]
null
null
null
defprotocol Enumerable do @moduledoc """ Enumerable protocol used by `Enum` and `Stream` modules. When you invoke a function in the `Enum` module, the first argument is usually a collection that must implement this protocol. For example, the expression: Enum.map([1, 2, 3], &(&1 * 2)) invokes `Enumerable.reduce/3` to perform the reducing operation that builds a mapped list by calling the mapping function `&(&1 * 2)` on every element in the collection and consuming the element with an accumulated list. Internally, `Enum.map/2` is implemented as follows: def map(enum, fun) do reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse() end Notice the user-supplied function is wrapped into a `t:reducer/0` function. The `t:reducer/0` function must return a tagged tuple after each step, as described in the `t:acc/0` type. The reason the accumulator requires a tagged tuple is to allow the `t:reducer/0` function to communicate the end of enumeration to the underlying enumerable, allowing any open resources to be properly closed. It also allows suspension of the enumeration, which is useful when interleaving between many enumerables is required (as in zip). Finally, `Enumerable.reduce/3` will return another tagged tuple, as represented by the `t:result/0` type. """ @typedoc """ The accumulator value for each step. It must be a tagged tuple with one of the following "tags": * `:cont` - the enumeration should continue * `:halt` - the enumeration should halt immediately * `:suspend` - the enumeration should be suspended immediately Depending on the accumulator value, the result returned by `Enumerable.reduce/3` will change. Please check the `t:result/0` type documentation for more information. In case a `t:reducer/0` function returns a `:suspend` accumulator, it must be explicitly handled by the caller and never leak. """ @type acc :: {:cont, term} | {:halt, term} | {:suspend, term} @typedoc """ The reducer function. Should be called with the enumerable element and the accumulator contents. Returns the accumulator for the next enumeration step. """ @type reducer :: (term, term -> acc) @typedoc """ The result of the reduce operation. It may be *done* when the enumeration is finished by reaching its end, or *halted*/*suspended* when the enumeration was halted or suspended by the `t:reducer/0` function. In case a `t:reducer/0` function returns the `:suspend` accumulator, the `:suspended` tuple must be explicitly handled by the caller and never leak. In practice, this means regular enumeration functions just need to be concerned about `:done` and `:halted` results. Furthermore, a `:suspend` call must always be followed by another call, eventually halting or continuing until the end. """ @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation} @typedoc """ A partially applied reduce function. The continuation is the closure returned as a result when the enumeration is suspended. When invoked, it expects a new accumulator and it returns the result. A continuation is easily implemented as long as the reduce function is defined in a tail recursive fashion. If the function is tail recursive, all the state is passed as arguments, so the continuation would simply be the reducing function partially applied. """ @type continuation :: (acc -> result) @doc """ Reduces the enumerable into an element. Most of the operations in `Enum` are implemented in terms of reduce. This function should apply the given `t:reducer/0` function to each item in the enumerable and proceed as expected by the returned accumulator. As an example, here is the implementation of `reduce` for lists: def reduce(_, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([h | t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun) """ @spec reduce(t, acc, reducer) :: result def reduce(enumerable, acc, fun) @doc """ Checks if an element exists within the enumerable. It should return `{:ok, boolean}`. If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and the match (`===`) operator is used. This algorithm runs in linear time. _Please force use of the default algorithm unless you can implement an algorithm that is significantly faster._ """ @spec member?(t, term) :: {:ok, boolean} | {:error, module} def member?(enumerable, element) @doc """ Retrieves the enumerable's size. It should return `{:ok, size}`. If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and the match (`===`) operator is used. This algorithm runs in linear time. _Please force use of the default algorithm unless you can implement an algorithm that is significantly faster._ """ @spec count(t) :: {:ok, non_neg_integer} | {:error, module} def count(enumerable) end defmodule Enum do import Kernel, except: [max: 2, min: 2] @moduledoc """ Provides a set of algorithms that enumerate over enumerables according to the `Enumerable` protocol. iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end) [2, 4, 6] Some particular types, like maps, yield a specific format on enumeration. For example, the argument is always a `{key, value}` tuple for maps: iex> map = %{a: 1, b: 2} iex> Enum.map(map, fn {k, v} -> {k, v * 2} end) [a: 2, b: 4] Note that the functions in the `Enum` module are eager: they always start the enumeration of the given enumerable. The `Stream` module allows lazy enumeration of enumerables and provides infinite streams. Since the majority of the functions in `Enum` enumerate the whole enumerable and return a list as result, infinite streams need to be carefully used with such functions, as they can potentially run forever. For example: Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1) """ @compile :inline_list_funcs @type t :: Enumerable.t @type element :: any @type index :: integer @type default :: any # Require Stream.Reducers and its callbacks require Stream.Reducers, as: R defmacrop skip(acc) do acc end defmacrop next(_, entry, acc) do quote do: [unquote(entry) | unquote(acc)] end defmacrop acc(h, n, _) do quote do: {unquote(h), unquote(n)} end defmacrop next_with_acc(f, entry, h, n, _) do quote do {[unquote(entry) | unquote(h)], unquote(n)} end end @doc """ Invokes the given `fun` for each item in the enumerable. It stops the iteration at the first invocation that returns `false` or `nil`. It returns `false` if at least one invocation returns `false` or `nil`. Otherwise returns `true`. ## Examples iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end) true iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end) false If no function is given, it defaults to checking if all items in the enumerable are truthy values. iex> Enum.all?([1, 2, 3]) true iex> Enum.all?([1, nil, 3]) false """ @spec all?(t) :: boolean @spec all?(t, (element -> as_boolean(term))) :: boolean def all?(enumerable, fun \\ fn(x) -> x end) def all?(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_all?(enumerable, fun) end def all?(enumerable, fun) when is_function(fun, 1) do Enumerable.reduce(enumerable, {:cont, true}, fn(entry, _) -> if fun.(entry), do: {:cont, true}, else: {:halt, false} end) |> elem(1) end @doc """ Invokes the given `fun` for each item in the enumerable. It stops the iteration at the first invocation that returns a truthy value. Returns `true` if at least one invocation returns a truthy value. Otherwise returns `false`. ## Examples iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) false iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) true If no function is given, it defaults to checking if at least one item in the enumerable is a truthy value. iex> Enum.any?([false, false, false]) false iex> Enum.any?([false, true, false]) true """ @spec any?(t) :: boolean @spec any?(t, (element -> as_boolean(term))) :: boolean def any?(enumerable, fun \\ fn(x) -> x end) def any?(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_any?(enumerable, fun) end def any?(enumerable, fun) when is_function(fun, 1) do Enumerable.reduce(enumerable, {:cont, false}, fn(entry, _) -> if fun.(entry), do: {:halt, true}, else: {:cont, false} end) |> elem(1) end @doc """ Finds the element at the given `index` (zero-based). Returns `default` if `index` is out of bounds. A negative `index` can be passed, which means the `enumerable` is enumerated once and the `index` is counted from the end (e.g. `-1` finds the last element). Note this operation takes linear time. In order to access the element at index `index`, it will need to traverse `index` previous elements. ## Examples iex> Enum.at([2, 4, 6], 0) 2 iex> Enum.at([2, 4, 6], 2) 6 iex> Enum.at([2, 4, 6], 4) nil iex> Enum.at([2, 4, 6], 4, :none) :none """ @spec at(t, index, default) :: element | default def at(enumerable, index, default \\ nil) do case fetch(enumerable, index) do {:ok, h} -> h :error -> default end end @doc """ Shortcut to `chunk(enumerable, count, count)`. """ @spec chunk(t, pos_integer) :: [list] def chunk(enumerable, count), do: chunk(enumerable, count, count, nil) @doc """ Returns list of lists containing `count` items each, where each new chunk starts `step` elements into the enumerable. `step` is optional and, if not passed, defaults to `count`, i.e. chunks do not overlap. If the final chunk does not have `count` elements to fill the chunk, elements are taken as necessary from `leftover` if it was passed. If `leftover` is passed and does not have enough elements to fill the chunk, then a partial chunk is returned with less than `count` elements. If `leftover` is not passed at all or is `nil`, then the partial chunk is discarded from the result. If `count` is greater than the number of elements in the enumerable and `leftover` is not passed, empty list will be returned. ## Examples iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2) [[1, 2], [3, 4], [5, 6]] iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2) [[1, 2, 3], [3, 4, 5]] iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7]) [[1, 2, 3], [3, 4, 5], [5, 6, 7]] iex> Enum.chunk([1, 2, 3, 4], 3, 3, []) [[1, 2, 3], [4]] iex> Enum.chunk([1, 2, 3, 4], 10) [] iex> Enum.chunk([1, 2, 3, 4], 10, 10, []) [[1, 2, 3, 4]] """ @spec chunk(t, pos_integer, pos_integer, t | nil) :: [list] def chunk(enumerable, count, step, leftover \\ nil) when is_integer(count) and count > 0 and is_integer(step) and step > 0 do limit = :erlang.max(count, step) {acc, {buffer, i}} = reduce(enumerable, {[], {[], 0}}, R.chunk(count, step, limit)) if is_nil(leftover) || i == 0 do :lists.reverse(acc) else buffer = :lists.reverse(buffer, take(leftover, count - i)) :lists.reverse([buffer | acc]) end end @doc """ Splits enumerable on every element for which `fun` returns a new value. Returns a list of lists. ## Examples iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1)) [[1], [2, 2], [3], [4, 4, 6], [7, 7]] """ @spec chunk_by(t, (element -> any)) :: [list] def chunk_by(enumerable, fun) when is_function(fun, 1) do {acc, res} = reduce(enumerable, {[], nil}, R.chunk_by(fun)) case res do {buffer, _} -> :lists.reverse([:lists.reverse(buffer) | acc]) nil -> [] end end @doc """ Given an enumerable of enumerables, concatenates the enumerables into a single list. ## Examples iex> Enum.concat([1..3, 4..6, 7..9]) [1, 2, 3, 4, 5, 6, 7, 8, 9] iex> Enum.concat([[1, [2], 3], [4], [5, 6]]) [1, [2], 3, 4, 5, 6] """ @spec concat(t) :: t def concat(enumerables) do do_concat(enumerables) end @doc """ Concatenates the enumerable on the right with the enumerable on the left. This function produces the same result as the `Kernel.++/2` operator for lists. ## Examples iex> Enum.concat(1..3, 4..6) [1, 2, 3, 4, 5, 6] iex> Enum.concat([1, 2, 3], [4, 5, 6]) [1, 2, 3, 4, 5, 6] """ @spec concat(t, t) :: t def concat(left, right) when is_list(left) and is_list(right) do left ++ right end def concat(left, right) do do_concat([left, right]) end defp do_concat(enumerable) do fun = &[&1 | &2] reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse end @doc """ Returns the size of the enumerable. ## Examples iex> Enum.count([1, 2, 3]) 3 """ @spec count(t) :: non_neg_integer def count(enumerable) when is_list(enumerable) do :erlang.length(enumerable) end def count(enumerable) do case Enumerable.count(enumerable) do {:ok, value} when is_integer(value) -> value {:error, module} -> module.reduce(enumerable, {:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1) end end @doc """ Returns the count of items in the enumerable for which `fun` returns a truthy value. ## Examples iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end) 2 """ @spec count(t, (element -> as_boolean(term))) :: non_neg_integer def count(enumerable, fun) when is_function(fun, 1) do Enumerable.reduce(enumerable, {:cont, 0}, fn(entry, acc) -> {:cont, if(fun.(entry), do: acc + 1, else: acc)} end) |> elem(1) end @doc """ Enumerates the `enumerable`, returning a list where all consecutive duplicated elements are collapsed to a single element. Elements are compared using `===`. If you want to remove all duplicated elements, regardless of order, see `uniq/1`. ## Examples iex> Enum.dedup([1, 2, 3, 3, 2, 1]) [1, 2, 3, 2, 1] iex> Enum.dedup([1, 1, 2, 2.0, :three, :"three"]) [1, 2, 2.0, :three] """ @spec dedup(t) :: list def dedup(enumerable) do dedup_by(enumerable, fn x -> x end) end @doc """ Enumerates the `enumerable`, returning a list where all consecutive duplicated elements are collapsed to a single element. The function `fun` maps every element to a term which is used to determine if two elements are duplicates. ## Examples iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end) [{1, :a}, {2, :b}, {1, :a}] iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end) [5, 1, 3, 2] """ @spec dedup_by(t, (element -> term)) :: list def dedup_by(enumerable, fun) when is_function(fun, 1) do {list, _} = reduce(enumerable, {[], []}, R.dedup(fun)) :lists.reverse(list) end @doc """ Drops the first `n` items from the enumerable. If a negative value `n` is given, the last `n` values will be dropped. The `enumerable` is enumerated once to retrieve the proper index and the remaining calculation is performed from the end. ## Examples iex> Enum.drop([1, 2, 3], 2) [3] iex> Enum.drop([1, 2, 3], 10) [] iex> Enum.drop([1, 2, 3], 0) [1, 2, 3] iex> Enum.drop([1, 2, 3], -1) [1, 2] """ @spec drop(t, integer) :: list def drop(enumerable, n) when is_list(enumerable) and is_integer(n) and n >= 0 do do_drop(enumerable, n) end def drop(enumerable, n) when is_integer(n) and n >= 0 do res = reduce(enumerable, n, fn x, acc when is_list(acc) -> [x | acc] x, 0 -> [x] _, acc when acc > 0 -> acc - 1 end) if is_list(res), do: :lists.reverse(res), else: [] end def drop(enumerable, n) when is_integer(n) and n < 0 do do_drop(reverse(enumerable), abs(n)) |> :lists.reverse end @doc """ Returns a list of every `nth` item in the enumerable dropped, starting with the first element. The first item is always dropped, unless `nth` is 0. The second argument specifying every `nth` item must be a non-negative integer, otherwise `FunctionClauseError` will be raised. ## Examples iex> Enum.drop_every(1..10, 2) [2, 4, 6, 8, 10] iex> Enum.drop_every(1..10, 0) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] iex> Enum.drop_every([1, 2, 3], 1) [] """ @spec drop_every(t, non_neg_integer) :: list | no_return def drop_every(enumerable, nth) def drop_every(_enumerable, 1), do: [] def drop_every(enumerable, 0), do: to_list(enumerable) def drop_every([], nth) when is_integer(nth), do: [] def drop_every(enumerable, nth) when is_integer(nth) and nth > 1 do {res, _} = reduce(enumerable, {[], :first}, R.drop_every(nth)) :lists.reverse(res) end @doc """ Drops items at the beginning of the enumerable while `fun` returns a truthy value. ## Examples iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end) [3, 4, 5] """ @spec drop_while(t, (element -> as_boolean(term))) :: list def drop_while(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_drop_while(enumerable, fun) end def drop_while(enumerable, fun) do {res, _} = reduce(enumerable, {[], true}, R.drop_while(fun)) :lists.reverse(res) end @doc """ Invokes the given `fun` for each item in the enumerable. Returns `:ok`. ## Examples Enum.each(["some", "example"], fn(x) -> IO.puts x end) "some" "example" #=> :ok """ @spec each(t, (element -> any)) :: :ok def each(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do :lists.foreach(fun, enumerable) :ok end def each(enumerable, fun) when is_function(fun, 1) do reduce(enumerable, nil, fn(entry, _) -> fun.(entry) nil end) :ok end @doc """ Determines if the enumerable is empty. Returns `true` if `enumerable` is empty, otherwise `false`. ## Examples iex> Enum.empty?([]) true iex> Enum.empty?([1, 2, 3]) false """ @spec empty?(t) :: boolean def empty?(enumerable) when is_list(enumerable) do enumerable == [] end def empty?(enumerable) do case Enumerable.count(enumerable) do {:ok, value} when is_integer(value) -> value == 0 {:error, module} -> module.reduce(enumerable, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1) end end @doc """ Finds the element at the given `index` (zero-based). Returns `{:ok, element}` if found, otherwise `:error`. A negative `index` can be passed, which means the `enumerable` is enumerated once and the `index` is counted from the end (e.g. `-1` fetches the last element). Note this operation takes linear time. In order to access the element at index `index`, it will need to traverse `index` previous elements. ## Examples iex> Enum.fetch([2, 4, 6], 0) {:ok, 2} iex> Enum.fetch([2, 4, 6], -3) {:ok, 2} iex> Enum.fetch([2, 4, 6], 2) {:ok, 6} iex> Enum.fetch([2, 4, 6], 4) :error """ @spec fetch(t, index) :: {:ok, element} | :error def fetch(enumerable, index) def fetch(first..last, index) when is_integer(index) do fetch_range(first, last, index) end def fetch(enumerable, index) when is_integer(index) and index < 0 do case Enumerable.count(enumerable) do {:ok, count} when (count + index) < 0 -> :error {:ok, count} -> fetch_enumerable(enumerable, count + index, Enumerable) {:error, _} -> enumerable |> reverse() |> fetch_list((-index) - 1) end end def fetch(enumerable, index) when is_list(enumerable) and is_integer(index) do fetch_list(enumerable, index) end def fetch(enumerable, index) when is_integer(index) do count_result = case Enumerable.count(enumerable) do {:ok, count} when (count - 1 - index) < 0 -> :error {:ok, _} -> {:ok, Enumerable} {:error, module} -> {:ok, module} end case count_result do :error -> :error {:ok, module} -> fetch_enumerable(enumerable, index, module) end end defp fetch_enumerable(enumerable, index, module) do reduce_result = module.reduce(enumerable, {:cont, 0}, fn entry, ^index -> {:halt, entry} _entry, acc -> {:cont, acc + 1} end) case reduce_result do {:halted, entry} -> {:ok, entry} {:done, _} -> :error end end @doc """ Finds the element at the given `index` (zero-based). Raises `OutOfBoundsError` if the given `index` is outside the range of the enumerable. Note this operation takes linear time. In order to access the element at index `index`, it will need to traverse `index` previous elements. ## Examples iex> Enum.fetch!([2, 4, 6], 0) 2 iex> Enum.fetch!([2, 4, 6], 2) 6 iex> Enum.fetch!([2, 4, 6], 4) ** (Enum.OutOfBoundsError) out of bounds error """ @spec fetch!(t, index) :: element | no_return def fetch!(enumerable, index) do case fetch(enumerable, index) do {:ok, h} -> h :error -> raise Enum.OutOfBoundsError end end @doc """ Filters the enumerable, i.e. returns only those elements for which `fun` returns a truthy value. See also `reject/2`. ## Examples iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end) [2] """ @spec filter(t, (element -> as_boolean(term))) :: list def filter(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do for item <- enumerable, fun.(item), do: item end def filter(enumerable, fun) when is_function(fun, 1) do reduce(enumerable, [], R.filter(fun)) |> :lists.reverse end @doc """ Filters the enumerable and maps its elements in one pass. ## Examples iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2)) [4] """ @spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list def filter_map(enumerable, filter, mapper) when is_list(enumerable) and is_function(filter, 1) and is_function(mapper, 1) do for item <- enumerable, filter.(item), do: mapper.(item) end def filter_map(enumerable, filter, mapper) when is_function(filter, 1) and is_function(mapper, 1) do reduce(enumerable, [], R.filter_map(filter, mapper)) |> :lists.reverse end @doc """ Returns the first item for which `fun` returns a truthy value. If no such item is found, returns `default`. ## Examples iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) nil iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end) 0 iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) 3 """ @spec find(t, default, (element -> any)) :: element | default def find(enumerable, default \\ nil, fun) def find(enumerable, default, fun) when is_list(enumerable) and is_function(fun, 1) do do_find(enumerable, default, fun) end def find(enumerable, default, fun) when is_function(fun, 1) do Enumerable.reduce(enumerable, {:cont, default}, fn(entry, default) -> if fun.(entry), do: {:halt, entry}, else: {:cont, default} end) |> elem(1) end @doc """ Similar to `find/3`, but returns the index (zero-based) of the element instead of the element itself. ## Examples iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) nil iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) 1 """ @spec find_index(t, (element -> any)) :: non_neg_integer | nil def find_index(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_find_index(enumerable, 0, fun) end def find_index(enumerable, fun) when is_function(fun, 1) do res = Enumerable.reduce(enumerable, {:cont, {:not_found, 0}}, fn(entry, {status, index}) -> if fun.(entry), do: {:halt, {:found, index}}, else: {:cont, {:not_found, index + 1}} end) case res do {_, {:found, index}} -> index {_, {:not_found, _}} -> nil end end @doc """ Similar to `find/3`, but returns the value of the function invocation instead of the element itself. ## Examples iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end) nil iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end) true iex> Enum.find_value([1, 2, 3], "no bools!", &is_boolean/1) "no bools!" """ @spec find_value(t, any, (element -> any)) :: any | nil def find_value(enumerable, default \\ nil, fun) def find_value(enumerable, default, fun) when is_list(enumerable) and is_function(fun, 1) do do_find_value(enumerable, default, fun) end def find_value(enumerable, default, fun) when is_function(fun, 1) do Enumerable.reduce(enumerable, {:cont, default}, fn(entry, default) -> fun_entry = fun.(entry) if fun_entry, do: {:halt, fun_entry}, else: {:cont, default} end) |> elem(1) end @doc """ Returns a new enumerable appending the result of invoking `fun` on each corresponding item of `enumerable`. The given function must return an enumerable. ## Examples iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end) [:a, :a, :b, :b, :c, :c] iex> Enum.flat_map([{1, 3}, {4, 6}], fn({x, y}) -> x..y end) [1, 2, 3, 4, 5, 6] iex> Enum.flat_map([:a, :b, :c], fn(x) -> [[x]] end) [[:a], [:b], [:c]] """ @spec flat_map(t, (element -> t)) :: list def flat_map(enumerable, fun) when is_function(fun, 1) do reduce(enumerable, [], fn(entry, acc) -> reduce(fun.(entry), acc, &[&1 | &2]) end) |> :lists.reverse end @doc """ Maps and reduces an enumerable, flattening the given results (only one level deep). It expects an accumulator and a function that receives each enumerable item, and must return a tuple containing a new enumerable (often a list) with the new accumulator or a tuple with `:halt` as first element and the accumulator as second. ## Examples iex> enum = 1..100 iex> n = 3 iex> Enum.flat_map_reduce(enum, 0, fn i, acc -> ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc} ...> end) {[1, 2, 3], 3} iex> Enum.flat_map_reduce(1..5, 0, fn(i, acc) -> {[[i]], acc + i} end) {[[1], [2], [3], [4], [5]], 15} """ @spec flat_map_reduce(t, acc, fun) :: {[any], any} when fun: (element, acc -> {t, acc} | {:halt, acc}), acc: any def flat_map_reduce(enumerable, acc, fun) when is_function(fun, 2) do {_, {list, acc}} = Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn(entry, {list, acc}) -> case fun.(entry, acc) do {:halt, acc} -> {:halt, {list, acc}} {[], acc} -> {:cont, {list, acc}} {[entry], acc} -> {:cont, {[entry | list], acc}} {entries, acc} -> {:cont, {reduce(entries, list, &[&1 | &2]), acc}} end end) {:lists.reverse(list), acc} end @doc """ Splits the enumerable into groups based on `fun`. The result is a map where each key is given by `key_fun` and each value is a list of elements given by `value_fun`. Ordering is preserved. ## Examples iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1) %{3 => ["ant", "cat"], 7 => ["buffalo"], 5 => ["dingo"]} iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1, &String.first/1) %{3 => ["a", "c"], 7 => ["b"], 5 => ["d"]} """ @spec group_by(t, (element -> any), (element -> any)) :: map def group_by(enumerable, key_fun, mapper_fun \\ fn x -> x end) def group_by(enumerable, key_fun, value_fun) when is_function(key_fun, 1) and is_function(value_fun, 1) do reduce(reverse(enumerable), %{}, fn entry, categories -> value = value_fun.(entry) Map.update(categories, key_fun.(entry), [value], &[value | &1]) end) end # TODO: Remove on 2.0 def group_by(enumerable, dict, fun) when is_function(fun, 1) do IO.warn "Enum.group_by/3 with a map/dictionary as second element is deprecated. " <> "A map is used by default and it is no longer required to pass one to this function" reduce(reverse(enumerable), dict, fn(entry, categories) -> Dict.update(categories, fun.(entry), [entry], &[entry | &1]) end) end @doc """ Intersperses `element` between each element of the enumeration. Complexity: O(n). ## Examples iex> Enum.intersperse([1, 2, 3], 0) [1, 0, 2, 0, 3] iex> Enum.intersperse([1], 0) [1] iex> Enum.intersperse([], 0) [] """ @spec intersperse(t, element) :: list def intersperse(enumerable, element) do list = reduce(enumerable, [], fn(x, acc) -> [x, element | acc] end) |> :lists.reverse() case list do [] -> [] [_ | t] -> t # Head is a superfluous intersperser element end end @doc """ Inserts the given `enumerable` into a `collectable`. ## Examples iex> Enum.into([1, 2], [0]) [0, 1, 2] iex> Enum.into([a: 1, b: 2], %{}) %{a: 1, b: 2} iex> Enum.into(%{a: 1}, %{b: 2}) %{a: 1, b: 2} iex> Enum.into([a: 1, a: 2], %{}) %{a: 2} """ @spec into(Enumerable.t, Collectable.t) :: Collectable.t def into(enumerable, collectable) when is_list(collectable) do collectable ++ to_list(enumerable) end def into(%_{} = enumerable, collectable) do do_into(enumerable, collectable) end def into(enumerable, %_{} = collectable) do do_into(enumerable, collectable) end def into(%{} = enumerable, %{} = collectable) do Map.merge(collectable, enumerable) end def into(enumerable, %{} = collectable) when is_list(enumerable) do Map.merge(collectable, :maps.from_list(enumerable)) end def into(enumerable, %{} = collectable) do reduce(enumerable, collectable, fn {key, val}, acc -> Map.put(acc, key, val) end) end def into(enumerable, collectable) do do_into(enumerable, collectable) end defp do_into(enumerable, collectable) do {initial, fun} = Collectable.into(collectable) into(enumerable, initial, fun, fn entry, acc -> fun.(acc, {:cont, entry}) end) end @doc """ Inserts the given `enumerable` into a `collectable` according to the transformation function. ## Examples iex> Enum.into([2, 3], [3], fn x -> x * 3 end) [3, 6, 9] """ @spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t def into(enumerable, collectable, transform) when is_list(collectable) and is_function(transform, 1) do collectable ++ map(enumerable, transform) end def into(enumerable, collectable, transform) when is_function(transform, 1) do {initial, fun} = Collectable.into(collectable) into(enumerable, initial, fun, fn entry, acc -> fun.(acc, {:cont, transform.(entry)}) end) end defp into(enumerable, initial, fun, callback) do try do reduce(enumerable, initial, callback) catch kind, reason -> stacktrace = System.stacktrace fun.(initial, :halt) :erlang.raise(kind, reason, stacktrace) else acc -> fun.(acc, :done) end end @doc """ Joins the given enumerable into a binary using `joiner` as a separator. If `joiner` is not passed at all, it defaults to the empty binary. All items in the enumerable must be convertible to a binary, otherwise an error is raised. ## Examples iex> Enum.join([1, 2, 3]) "123" iex> Enum.join([1, 2, 3], " = ") "1 = 2 = 3" """ @spec join(t, String.t) :: String.t def join(enumerable, joiner \\ "") def join(enumerable, joiner) when is_binary(joiner) do reduced = reduce(enumerable, :first, fn entry, :first -> enum_to_string(entry) entry, acc -> [acc, joiner | enum_to_string(entry)] end) if reduced == :first do "" else IO.iodata_to_binary reduced end end @doc """ Returns a list where each item is the result of invoking `fun` on each corresponding item of `enumerable`. For maps, the function expects a key-value tuple. ## Examples iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end) [2, 4, 6] iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end) [a: -1, b: -2] """ @spec map(t, (element -> any)) :: list def map(enumerable, fun) def map(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do :lists.map(fun, enumerable) end def map(enumerable, fun) when is_function(fun, 1) do reduce(enumerable, [], R.map(fun)) |> :lists.reverse end @doc """ Maps and joins the given enumerable in one pass. `joiner` can be either a binary or a list and the result will be of the same type as `joiner`. If `joiner` is not passed at all, it defaults to an empty binary. All items in the enumerable must be convertible to a binary, otherwise an error is raised. ## Examples iex> Enum.map_join([1, 2, 3], &(&1 * 2)) "246" iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2)) "2 = 4 = 6" """ @spec map_join(t, String.t, (element -> any)) :: String.t def map_join(enumerable, joiner \\ "", mapper) def map_join(enumerable, joiner, mapper) when is_binary(joiner) and is_function(mapper, 1) do reduced = reduce(enumerable, :first, fn entry, :first -> enum_to_string(mapper.(entry)) entry, acc -> [acc, joiner | enum_to_string(mapper.(entry))] end) if reduced == :first do "" else IO.iodata_to_binary reduced end end @doc """ Invokes the given function to each item in the enumerable to reduce it to a single element, while keeping an accumulator. Returns a tuple where the first element is the mapped enumerable and the second one is the final accumulator. The function, `fun`, receives two arguments: the first one is the element, and the second one is the accumulator. `fun` must return a tuple with two elements in the form of `{result, accumulator}`. For maps, the first tuple element must be a `{key, value}` tuple. ## Examples iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end) {[2, 4, 6], 6} """ @spec map_reduce(t, any, (element, any -> {any, any})) :: {any, any} def map_reduce(enumerable, acc, fun) when is_list(enumerable) and is_function(fun) do :lists.mapfoldl(fun, acc, enumerable) end def map_reduce(enumerable, acc, fun) when is_function(fun, 2) do {list, acc} = reduce(enumerable, {[], acc}, fn(entry, {list, acc}) -> {new_entry, acc} = fun.(entry, acc) {[new_entry | list], acc} end) {:lists.reverse(list), acc} end @doc """ Returns the maximal element in the enumerable according to Erlang's term ordering. If multiple elements are considered maximal, the first one that was found is returned. Raises `Enum.EmptyError` if `enumerable` is empty. ## Examples iex> Enum.max([1, 2, 3]) 3 """ @spec max(t) :: element | no_return def max(enumerable) do reduce(enumerable, &Kernel.max(&1, &2)) end @doc """ Returns the maximal element in the enumerable as calculated by the given function. If multiple elements are considered maximal, the first one that was found is returned. Raises `Enum.EmptyError` if `enumerable` is empty. ## Examples iex> Enum.max_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end) "aaa" iex> Enum.max_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1) "aaa" """ @spec max_by(t, (element -> any)) :: element | no_return def max_by([h | t], fun) when is_function(fun, 1) do reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) -> fun_entry = fun.(entry) if(fun_entry > fun_max, do: {entry, fun_entry}, else: old) end) |> elem(0) end def max_by([], _fun) do raise Enum.EmptyError end def max_by(enumerable, fun) when is_function(fun, 1) do result = reduce(enumerable, :first, fn entry, {_, fun_max} = old -> fun_entry = fun.(entry) if(fun_entry > fun_max, do: {entry, fun_entry}, else: old) entry, :first -> {entry, fun.(entry)} end) case result do :first -> raise Enum.EmptyError {entry, _} -> entry end end @doc """ Checks if `element` exists within the enumerable. Membership is tested with the match (`===`) operator. ## Examples iex> Enum.member?(1..10, 5) true iex> Enum.member?(1..10, 5.0) false iex> Enum.member?([1.0, 2.0, 3.0], 2) false iex> Enum.member?([1.0, 2.0, 3.0], 2.000) true iex> Enum.member?([:a, :b, :c], :d) false """ @spec member?(t, element) :: boolean def member?(enumerable, element) when is_list(enumerable) do :lists.member(element, enumerable) end def member?(enumerable, element) do case Enumerable.member?(enumerable, element) do {:ok, element} when is_boolean(element) -> element {:error, module} -> module.reduce(enumerable, {:cont, false}, fn v, _ when v === element -> {:halt, true} _, _ -> {:cont, false} end) |> elem(1) end end @doc """ Returns the minimal element in the enumerable according to Erlang's term ordering. If multiple elements are considered minimal, the first one that was found is returned. Raises `Enum.EmptyError` if `enumerable` is empty. ## Examples iex> Enum.min([1, 2, 3]) 1 """ @spec min(t) :: element | no_return def min(enumerable) do reduce(enumerable, &Kernel.min(&1, &2)) end @doc """ Returns the minimal element in the enumerable as calculated by the given function. If multiple elements are considered minimal, the first one that was found is returned. Raises `Enum.EmptyError` if `enumerable` is empty. ## Examples iex> Enum.min_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end) "a" iex> Enum.min_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1) "a" """ @spec min_by(t, (element -> any)) :: element | no_return def min_by([h | t], fun) when is_function(fun, 1) do reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) -> fun_entry = fun.(entry) if(fun_entry < fun_min, do: {entry, fun_entry}, else: old) end) |> elem(0) end def min_by([], _fun) do raise Enum.EmptyError end def min_by(enumerable, fun) when is_function(fun, 1) do result = reduce(enumerable, :first, fn entry, {_, fun_min} = old -> fun_entry = fun.(entry) if(fun_entry < fun_min, do: {entry, fun_entry}, else: old) entry, :first -> {entry, fun.(entry)} end) case result do :first -> raise Enum.EmptyError {entry, _} -> entry end end @doc """ Returns a tuple with the minimal and the maximal elements in the enumerable according to Erlang's term ordering. If multiple elements are considered maximal or minimal, the first one that was found is returned. Raises `Enum.EmptyError` if `enumerable` is empty. ## Examples iex> Enum.min_max([2, 3, 1]) {1, 3} """ @spec min_max(t) :: {element, element} | no_return def min_max(enumerable) do result = Enum.reduce(enumerable, :first, fn entry, {min_value, max_value} -> {Kernel.min(entry, min_value), Kernel.max(entry, max_value)} entry, :first -> {entry, entry} end) case result do :first -> raise Enum.EmptyError result -> result end end @doc """ Returns a tuple with the minimal and the maximal elements in the enumerable as calculated by the given function. If multiple elements are considered maximal or minimal, the first one that was found is returned. Raises `Enum.EmptyError` if `enumerable` is empty. ## Examples iex> Enum.min_max_by(["aaa", "bb", "c"], fn(x) -> String.length(x) end) {"c", "aaa"} iex> Enum.min_max_by(["aaa", "a", "bb", "c", "ccc"], &String.length/1) {"a", "aaa"} """ @spec min_max_by(t, (element -> any)) :: {element, element} | no_return def min_max_by(enumerable, fun) when is_function(fun, 1) do result = Enum.reduce(enumerable, :first, fn entry, {{_, fun_min} = acc_min, {_, fun_max} = acc_max} -> fun_entry = fun.(entry) acc_min = if fun_entry < fun_min, do: {entry, fun_entry}, else: acc_min acc_max = if fun_entry > fun_max, do: {entry, fun_entry}, else: acc_max {acc_min, acc_max} entry, :first -> fun_entry = fun.(entry) {{entry, fun_entry}, {entry, fun_entry}} end) case result do :first -> raise Enum.EmptyError {{min_entry, _}, {max_entry, _}} -> {min_entry, max_entry} end end @doc """ Splits the `enumerable` in two lists according to the given function `fun`. Splits the given `enumerable` in two lists by calling `fun` with each element in the `enumerable` as its only argument. Returns a tuple with the first list containing all the elements in `enumerable` for which applying `fun` returned a truthy value, and a second list with all the elements for which applying `fun` returned a falsey value (`false` or `nil`). The elements in both the returned lists are in the same relative order as they were in the original enumerable (if such enumerable was ordered, e.g., a list); see the examples below. ## Examples iex> Enum.split_with([1, 2, 3], fn(x) -> rem(x, 2) == 0 end) {[2], [1, 3]} """ @spec split_with(t, (element -> any)) :: {list, list} def split_with(enumerable, fun) when is_function(fun, 1) do {acc1, acc2} = reduce(enumerable, {[], []}, fn(entry, {acc1, acc2}) -> if fun.(entry) do {[entry | acc1], acc2} else {acc1, [entry | acc2]} end end) {:lists.reverse(acc1), :lists.reverse(acc2)} end @doc false # TODO: Deprecate by v1.5 @spec partition(t, (element -> any)) :: {list, list} def partition(enumerable, fun) when is_function(fun, 1) do split_with(enumerable, fun) end @doc """ Returns a random element of an enumerable. Raises `Enum.EmptyError` if `enumerable` is empty. This function uses Erlang's `:rand` module to calculate the random value. Check its documentation for setting a different random algorithm or a different seed. The implementation is based on the [reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle) algorithm. It assumes that the sample being returned can fit into memory; the input `enumerable` doesn't have to, as it is traversed just once. ## Examples # Although not necessary, let's seed the random algorithm iex> :rand.seed(:exsplus, {101, 102, 103}) iex> Enum.random([1, 2, 3]) 2 iex> Enum.random([1, 2, 3]) 1 """ @spec random(t) :: element | no_return def random(enumerable) def random(first..last), do: random_integer(first, last) def random(enumerable) do case Enumerable.count(enumerable) do {:ok, 0} -> raise Enum.EmptyError {:ok, count} -> at(enumerable, random_integer(0, count - 1)) {:error, _} -> case take_random(enumerable, 1) do [] -> raise Enum.EmptyError [elem] -> elem end end end @doc """ Invokes `fun` for each element in the `enumerable`, passing that element and the accumulator as arguments. `fun`'s return value is stored in the accumulator. The first element of the enumerable is used as the initial value of the accumulator. If you wish to use another value for the accumulator, use `Enumerable.reduce/3`. This function won't call the specified function for enumerables that are one-element long. Returns the accumulator. Note that since the first element of the enumerable is used as the initial value of the accumulator, `fun` will only be executed `n - 1` times where `n` is the length of the enumerable. ## Examples iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end) 24 """ @spec reduce(t, (element, any -> any)) :: any def reduce(enumerable, fun) def reduce([h | t], fun) when is_function(fun, 2) do reduce(t, h, fun) end def reduce([], _fun) do raise Enum.EmptyError end def reduce(enumerable, fun) when is_function(fun, 2) do result = Enumerable.reduce(enumerable, {:cont, :first}, fn x, :first -> {:cont, {:acc, x}} x, {:acc, acc} -> {:cont, {:acc, fun.(x, acc)}} end) |> elem(1) case result do :first -> raise Enum.EmptyError {:acc, acc} -> acc end end @doc """ Invokes `fun` for each element in the `enumerable`, passing that element and the accumulator `acc` as arguments. `fun`'s return value is stored in `acc`. Returns the accumulator. ## Examples iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end) 6 """ @spec reduce(t, any, (element, any -> any)) :: any def reduce(enumerable, acc, fun) when is_list(enumerable) and is_function(fun, 2) do :lists.foldl(fun, acc, enumerable) end def reduce(%{__struct__: _} = enumerable, acc, fun) when is_function(fun, 2) do Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1) end def reduce(%{} = enumerable, acc, fun) when is_function(fun, 2) do :maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, enumerable) end def reduce(enumerable, acc, fun) when is_function(fun, 2) do Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1) end @doc """ Reduces the enumerable until `fun` returns `{:halt, term}`. The return value for `fun` is expected to be * `{:cont, acc}` to continue the reduction with `acc` as the new accumulator or * `{:halt, acc}` to halt the reduction and return `acc` as the return value of this function ## Examples iex> Enum.reduce_while(1..100, 0, fn i, acc -> ...> if i < 3, do: {:cont, acc + i}, else: {:halt, acc} ...> end) 3 """ @spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any def reduce_while(enumerable, acc, fun) when is_function(fun, 2) do Enumerable.reduce(enumerable, {:cont, acc}, fun) |> elem(1) end @doc """ Returns elements of `enumerable` for which the function `fun` returns `false` or `nil`. See also `filter/2`. ## Examples iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end) [1, 3] """ @spec reject(t, (element -> as_boolean(term))) :: list def reject(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do for item <- enumerable, !fun.(item), do: item end def reject(enumerable, fun) when is_function(fun, 1) do reduce(enumerable, [], R.reject(fun)) |> :lists.reverse end @doc """ Returns a list of elements in `enumerable` in reverse order. ## Examples iex> Enum.reverse([1, 2, 3]) [3, 2, 1] """ @spec reverse(t) :: list def reverse(enumerable) do reverse(enumerable, []) end @doc """ Reverses the elements in `enumerable`, appends the tail, and returns it as a list. This is an optimization for `Enum.concat(Enum.reverse(enumerable), tail)`. ## Examples iex> Enum.reverse([1, 2, 3], [4, 5, 6]) [3, 2, 1, 4, 5, 6] """ @spec reverse(t, t) :: list def reverse(enumerable, tail) when is_list(enumerable) do :lists.reverse(enumerable, to_list(tail)) end def reverse(enumerable, tail) do reduce(enumerable, to_list(tail), fn(entry, acc) -> [entry | acc] end) end @doc """ Reverses the enumerable in the range from initial position `start` through `count` elements. If `count` is greater than the size of the rest of the enumerable, then this function will reverse the rest of the enumerable. ## Examples iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4) [1, 2, 6, 5, 4, 3] """ @spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list def reverse_slice(enumerable, start, count) when is_integer(start) and start >= 0 and is_integer(count) and count >= 0 do list = reverse(enumerable) length = length(list) count = Kernel.min(count, length - start) if count > 0 do reverse_slice(list, length, start + count, count, []) else :lists.reverse(list) end end @doc """ Applies the given function to each element in the enumerable, storing the result in a list and passing it as the accumulator for the next computation. ## Examples iex> Enum.scan(1..5, &(&1 + &2)) [1, 3, 6, 10, 15] """ @spec scan(t, (element, any -> any)) :: list def scan(enumerable, fun) when is_function(fun, 2) do {res, _} = reduce(enumerable, {[], :first}, R.scan_2(fun)) :lists.reverse(res) end @doc """ Applies the given function to each element in the enumerable, storing the result in a list and passing it as the accumulator for the next computation. Uses the given `acc` as the starting value. ## Examples iex> Enum.scan(1..5, 0, &(&1 + &2)) [1, 3, 6, 10, 15] """ @spec scan(t, any, (element, any -> any)) :: list def scan(enumerable, acc, fun) when is_function(fun, 2) do {res, _} = reduce(enumerable, {[], acc}, R.scan_3(fun)) :lists.reverse(res) end @doc """ Returns a list with the elements of `enumerable` shuffled. This function uses Erlang's `:rand` module to calculate the random value. Check its documentation for setting a different random algorithm or a different seed. ## Examples # Although not necessary, let's seed the random algorithm iex> :rand.seed(:exsplus, {1, 2, 3}) iex> Enum.shuffle([1, 2, 3]) [2, 1, 3] iex> Enum.shuffle([1, 2, 3]) [2, 3, 1] """ @spec shuffle(t) :: list def shuffle(enumerable) do randomized = reduce(enumerable, [], fn x, acc -> [{:rand.uniform, x} | acc] end) unwrap(:lists.keysort(1, randomized), []) end @doc """ Returns a subset list of the given enumerable. Drops elements until element position `range.first`, then takes elements until element position `range.last` (inclusive). Positions are calculated by adding the number of items in the enumerable to negative positions (e.g. position -3 in an enumerable with count 5 becomes position 2). The first position (after adding count to negative positions) must be smaller or equal to the last position. If the start of the range is not a valid index for the given enumerable or if the range is in descending order, it returns `[]`. ## Examples iex> Enum.slice(1..100, 5..10) [6, 7, 8, 9, 10, 11] iex> Enum.slice(1..10, 5..20) [6, 7, 8, 9, 10] iex> Enum.slice(1..10, 11..20) [] iex> Enum.slice(1..10, 6..5) [] """ @spec slice(t, Range.t) :: list def slice(enumerable, range) def slice(enumerable, first..last) when first >= 0 and last >= 0 do # Simple case, which works on infinite enumerables if last - first >= 0 do slice(enumerable, first, last - first + 1) else [] end end def slice(enumerable, first..last) do {list, count} = enumerate_and_count(enumerable, 0) corr_first = if first >= 0, do: first, else: first + count corr_last = if last >= 0, do: last, else: last + count length = corr_last - corr_first + 1 if corr_first >= 0 and length > 0 do slice(list, corr_first, length) else [] end end @doc """ Returns a subset list of the given enumerable. Drops elements until element position `start`, then takes `count` elements. If the count is greater than `enumerable` length, it returns as many as possible. If zero, then it returns `[]`. ## Examples iex> Enum.slice(1..100, 5, 10) [6, 7, 8, 9, 10, 11, 12, 13, 14, 15] iex> Enum.slice(1..10, 5, 100) [6, 7, 8, 9, 10] iex> Enum.slice(1..10, 5, 0) [] """ @spec slice(t, integer, non_neg_integer) :: list def slice(_enumerable, start, 0) when is_integer(start), do: [] def slice(enumerable, start, count) when is_integer(start) and start < 0 and is_integer(count) and count >= 0 do {list, new_start} = enumerate_and_count(enumerable, start) if new_start >= 0 do slice(list, new_start, count) else [] end end def slice(enumerable, start, count) when is_list(enumerable) and is_integer(start) and start >= 0 and is_integer(count) and count > 0 do do_slice(enumerable, start, count) end def slice(enumerable, start, count) when is_integer(start) and start >= 0 and is_integer(count) and count > 0 do {_, _, list} = Enumerable.reduce(enumerable, {:cont, {start, count, []}}, fn _entry, {start, count, _list} when start > 0 -> {:cont, {start-1, count, []}} entry, {start, count, list} when count > 1 -> {:cont, {start, count-1, [entry | list]}} entry, {start, count, list} -> {:halt, {start, count, [entry | list]}} end) |> elem(1) :lists.reverse(list) end @doc """ Sorts the enumerable according to Erlang's term ordering. Uses the merge sort algorithm. ## Examples iex> Enum.sort([3, 2, 1]) [1, 2, 3] """ @spec sort(t) :: list def sort(enumerable) when is_list(enumerable) do :lists.sort(enumerable) end def sort(enumerable) do sort(enumerable, &(&1 <= &2)) end @doc """ Sorts the enumerable by the given function. This function uses the merge sort algorithm. The given function should compare two arguments, and return `false` if the first argument follows the second one. ## Examples iex> Enum.sort([1, 2, 3], &(&1 >= &2)) [3, 2, 1] The sorting algorithm will be stable as long as the given function returns `true` for values considered equal: iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2)) ["of", "some", "kind", "monster"] If the function does not return `true` for equal values, the sorting is not stable and the order of equal terms may be shuffled. For example: iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2)) ["of", "kind", "some", "monster"] """ @spec sort(t, (element, element -> boolean)) :: list def sort(enumerable, fun) when is_list(enumerable) and is_function(fun, 2) do :lists.sort(fun, enumerable) end def sort(enumerable, fun) when is_function(fun, 2) do reduce(enumerable, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun) end @doc """ Sorts the mapped results of the enumerable according to the `sorter` function. This function maps each element of the enumerable using the `mapper` function. The enumerable is then sorted by the mapped elements using the `sorter` function, which defaults to `Kernel.<=/2` `sort_by/3` differs from `sort/2` in that it only calculates the comparison value for each element in the enumerable once instead of once for each element in each comparison. If the same function is being called on both element, it's also more compact to use `sort_by/3`. This technique is also known as a _[Schwartzian Transform](https://en.wikipedia.org/wiki/Schwartzian_transform)_, or the _Lisp decorate-sort-undecorate idiom_ as the `mapper` is decorating the original `enumerable`; then `sorter` is sorting the decorations; and finally the enumerable is being undecorated so only the original elements remain, but now in sorted order. ## Examples Using the default `sorter` of `<=/2`: iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1 ["of", "some", "kind", "monster"] Using a custom `sorter` to override the order: iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1, &>=/2 ["monster", "some", "kind", "of"] """ @spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) :: list when mapped_element: element def sort_by(enumerable, mapper, sorter \\ &<=/2) when is_function(sorter, 2) do enumerable |> map(&{&1, mapper.(&1)}) |> sort(&sorter.(elem(&1, 1), elem(&2, 1))) |> map(&elem(&1, 0)) end @doc """ Splits the `enumerable` into two enumerables, leaving `count` elements in the first one. If `count` is a negative number, it starts counting from the back to the beginning of the enumerable. Be aware that a negative `count` implies the `enumerable` will be enumerated twice: once to calculate the position, and a second time to do the actual splitting. ## Examples iex> Enum.split([1, 2, 3], 2) {[1, 2], [3]} iex> Enum.split([1, 2, 3], 10) {[1, 2, 3], []} iex> Enum.split([1, 2, 3], 0) {[], [1, 2, 3]} iex> Enum.split([1, 2, 3], -1) {[1, 2], [3]} iex> Enum.split([1, 2, 3], -5) {[], [1, 2, 3]} """ @spec split(t, integer) :: {list, list} def split(enumerable, count) when is_list(enumerable) and count >= 0 do do_split(enumerable, count, []) end def split(enumerable, count) when count >= 0 do {_, list1, list2} = reduce(enumerable, {count, [], []}, fn(entry, {counter, acc1, acc2}) -> if counter > 0 do {counter - 1, [entry | acc1], acc2} else {counter, acc1, [entry | acc2]} end end) {:lists.reverse(list1), :lists.reverse(list2)} end def split(enumerable, count) when count < 0 do do_split_reverse(reverse(enumerable), abs(count), []) end @doc """ Splits enumerable in two at the position of the element for which `fun` returns `false` for the first time. ## Examples iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end) {[1, 2], [3, 4]} """ @spec split_while(t, (element -> as_boolean(term))) :: {list, list} def split_while(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_split_while(enumerable, fun, []) end def split_while(enumerable, fun) do {list1, list2} = reduce(enumerable, {[], []}, fn entry, {acc1, []} -> if(fun.(entry), do: {[entry | acc1], []}, else: {acc1, [entry]}) entry, {acc1, acc2} -> {acc1, [entry | acc2]} end) {:lists.reverse(list1), :lists.reverse(list2)} end @doc """ Returns the sum of all elements. Raises `ArithmeticError` if `enumerable` contains a non-numeric value. ## Examples iex> Enum.sum([1, 2, 3]) 6 """ @spec sum(t) :: number def sum(enumerable) def sum(first..first), do: first def sum(first..last) when last < first, do: sum(last..first) def sum(first..last) when last > first do div((last + first) * (last - first + 1), 2) end def sum(enumerable) do reduce(enumerable, 0, &+/2) end @doc """ Takes the first `count` items from the enumerable. `count` must be an integer. If a negative `count` is given, the last `count` values will be taken. For such, the enumerable is fully enumerated keeping up to `2 * count` elements in memory. Once the end of the enumerable is reached, the last `count` elements are returned. ## Examples iex> Enum.take([1, 2, 3], 2) [1, 2] iex> Enum.take([1, 2, 3], 10) [1, 2, 3] iex> Enum.take([1, 2, 3], 0) [] iex> Enum.take([1, 2, 3], -1) [3] """ @spec take(t, integer) :: list def take(enumerable, count) def take(_enumerable, 0), do: [] def take([], _count), do: [] def take(enumerable, count) when is_list(enumerable) and is_integer(count) and count > 0 do do_take(enumerable, count, []) end def take(enumerable, count) when is_integer(count) and count > 0 do {_, {res, _}} = Enumerable.reduce(enumerable, {:cont, {[], count}}, fn(entry, {list, n}) -> case n do 0 -> {:halt, {list, n}} 1 -> {:halt, {[entry | list], n - 1}} _ -> {:cont, {[entry | list], n - 1}} end end) :lists.reverse(res) end def take(enumerable, count) when is_integer(count) and count < 0 do count = abs(count) {_count, buf1, buf2} = reduce(enumerable, {0, [], []}, fn entry, {n, buf1, buf2} -> buf1 = [entry | buf1] n = n + 1 if n == count do {0, [], buf1} else {n, buf1, buf2} end end) do_take_last(buf1, buf2, count, []) end defp do_take_last(_buf1, _buf2, 0, acc), do: acc defp do_take_last([], [], _, acc), do: acc defp do_take_last([], [h | t], count, acc), do: do_take_last([], t, count-1, [h | acc]) defp do_take_last([h | t], buf2, count, acc), do: do_take_last(t, buf2, count-1, [h | acc]) @doc """ Returns a list of every `nth` item in the enumerable, starting with the first element. The first item is always included, unless `nth` is 0. The second argument specifying every `nth` item must be a non-negative integer, otherwise `FunctionClauseError` will be raised. ## Examples iex> Enum.take_every(1..10, 2) [1, 3, 5, 7, 9] iex> Enum.take_every(1..10, 0) [] iex> Enum.take_every([1, 2, 3], 1) [1, 2, 3] """ @spec take_every(t, non_neg_integer) :: list | no_return def take_every(enumerable, nth) def take_every(enumerable, 1), do: to_list(enumerable) def take_every(_enumerable, 0), do: [] def take_every([], nth) when is_integer(nth) and nth > 1, do: [] def take_every(enumerable, nth) when is_integer(nth) and nth > 1 do {res, _} = reduce(enumerable, {[], :first}, R.take_every(nth)) :lists.reverse(res) end @doc """ Takes `count` random items from `enumerable`. Notice this function will traverse the whole `enumerable` to get the random sublist. See `random/1` for notes on implementation and random seed. ## Examples # Although not necessary, let's seed the random algorithm iex> :rand.seed(:exsplus, {1, 2, 3}) iex> Enum.take_random(1..10, 2) [5, 4] iex> Enum.take_random(?a..?z, 5) 'ipybz' """ @spec take_random(t, non_neg_integer) :: list def take_random(enumerable, count) def take_random(_enumerable, 0), do: [] def take_random(first..first, count) when is_integer(count) and count >= 1, do: [first] def take_random(enumerable, count) when is_integer(count) and count > 128 do reducer = fn(elem, {idx, sample}) -> jdx = random_integer(0, idx) cond do idx < count -> value = Map.get(sample, jdx) {idx + 1, Map.put(sample, idx, value) |> Map.put(jdx, elem)} jdx < count -> {idx + 1, Map.put(sample, jdx, elem)} true -> {idx + 1, sample} end end {size, sample} = reduce(enumerable, {0, %{}}, reducer) take_random(sample, Kernel.min(count, size), []) end def take_random(enumerable, count) when is_integer(count) and count > 0 do sample = Tuple.duplicate(nil, count) reducer = fn(elem, {idx, sample}) -> jdx = random_integer(0, idx) cond do idx < count -> value = elem(sample, jdx) {idx + 1, put_elem(sample, idx, value) |> put_elem(jdx, elem)} jdx < count -> {idx + 1, put_elem(sample, jdx, elem)} true -> {idx + 1, sample} end end {size, sample} = reduce(enumerable, {0, sample}, reducer) sample |> Tuple.to_list |> take(Kernel.min(count, size)) end defp take_random(_sample, 0, acc), do: acc defp take_random(sample, position, acc) do position = position - 1 take_random(sample, position, [Map.get(sample, position) | acc]) end @doc """ Takes the items from the beginning of the enumerable while `fun` returns a truthy value. ## Examples iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end) [1, 2] """ @spec take_while(t, (element -> as_boolean(term))) :: list def take_while(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_take_while(enumerable, fun, []) end def take_while(enumerable, fun) when is_function(fun, 1) do {_, res} = Enumerable.reduce(enumerable, {:cont, []}, fn(entry, acc) -> if fun.(entry) do {:cont, [entry | acc]} else {:halt, acc} end end) :lists.reverse(res) end @doc """ Converts `enumerable` to a list. ## Examples iex> Enum.to_list(1..3) [1, 2, 3] """ @spec to_list(t) :: [element] def to_list(enumerable) when is_list(enumerable) do enumerable end def to_list(enumerable) do reverse(enumerable) |> :lists.reverse end @doc """ Enumerates the `enumerable`, removing all duplicated elements. ## Examples iex> Enum.uniq([1, 2, 3, 3, 2, 1]) [1, 2, 3] """ @spec uniq(t) :: list def uniq(enumerable) do uniq_by(enumerable, fn x -> x end) end @doc false # TODO: Deprecate by 1.4 def uniq(enumerable, fun) do uniq_by(enumerable, fun) end @doc """ Enumerates the `enumerable`, by removing the elements for which function `fun` returned duplicate items. The function `fun` maps every element to a term which is used to determine if two elements are duplicates. ## Example iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end) [{1, :x}, {2, :y}] iex> Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end) [a: {:tea, 2}, c: {:coffee, 1}] """ @spec uniq_by(t, (element -> term)) :: list def uniq_by(enumerable, fun) when is_list(enumerable) and is_function(fun, 1) do do_uniq(enumerable, %{}, fun, []) end def uniq_by(enumerable, fun) when is_function(fun, 1) do {list, _} = reduce(enumerable, {[], %{}}, R.uniq_by(fun)) :lists.reverse(list) end @doc """ Opposite of `Enum.zip/2`; extracts a two-element tuples from the enumerable and groups them together. It takes an enumerable with items being two-element tuples and returns a tuple with two lists, each of which is formed by the first and second element of each tuple, respectively. This function fails unless `enumerable` is or can be converted into a list of tuples with *exactly* two elements in each tuple. ## Examples iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}]) {[:a, :b, :c], [1, 2, 3]} iex> Enum.unzip(%{a: 1, b: 2}) {[:a, :b], [1, 2]} """ @spec unzip(t) :: {[element], [element]} def unzip(enumerable) do {list1, list2} = reduce(enumerable, {[], []}, fn({el1, el2}, {list1, list2}) -> {[el1 | list1], [el2 | list2]} end) {:lists.reverse(list1), :lists.reverse(list2)} end @doc """ Returns the enumerable with each element wrapped in a tuple alongside its index. If an `offset` is given, we will index from the given offset instead of from zero. ## Examples iex> Enum.with_index([:a, :b, :c]) [a: 0, b: 1, c: 2] iex> Enum.with_index([:a, :b, :c], 3) [a: 3, b: 4, c: 5] """ @spec with_index(t) :: [{element, index}] @spec with_index(t, integer) :: [{element, index}] def with_index(enumerable, offset \\ 0) do map_reduce(enumerable, offset, fn x, acc -> {{x, acc}, acc + 1} end) |> elem(0) end @doc """ Zips corresponding elements from two enumerables into one list of tuples. The zipping finishes as soon as any enumerable completes. ## Examples iex> Enum.zip([1, 2, 3], [:a, :b, :c]) [{1, :a}, {2, :b}, {3, :c}] iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c]) [{1, :a}, {2, :b}, {3, :c}] """ @spec zip(t, t) :: [{any, any}] def zip(enumerable1, enumerable2) when is_list(enumerable1) and is_list(enumerable2) do do_zip(enumerable1, enumerable2, []) end def zip(enumerable1, enumerable2) do Stream.zip(enumerable1, enumerable2).({:cont, []}, &{:cont, [&1 | &2]}) |> elem(1) |> :lists.reverse end ## Helpers @compile {:inline, enum_to_string: 1} defp enumerate_and_count(enumerable, count) when is_list(enumerable) do {enumerable, length(enumerable) - abs(count)} end defp enumerate_and_count(enumerable, count) do map_reduce(enumerable, -abs(count), fn(x, acc) -> {x, acc + 1} end) end defp enum_to_string(entry) when is_binary(entry), do: entry defp enum_to_string(entry), do: String.Chars.to_string(entry) defp random_integer(limit, limit) when is_integer(limit), do: limit defp random_integer(lower_limit, upper_limit) when upper_limit < lower_limit, do: random_integer(upper_limit, lower_limit) defp random_integer(lower_limit, upper_limit) do lower_limit + :rand.uniform(upper_limit - lower_limit + 1) - 1 end ## Implementations ## all? defp do_all?([h | t], fun) do if fun.(h) do do_all?(t, fun) else false end end defp do_all?([], _) do true end ## any? defp do_any?([h | t], fun) do if fun.(h) do true else do_any?(t, fun) end end defp do_any?([], _) do false end ## drop defp do_drop([_ | t], counter) when counter > 0 do do_drop(t, counter - 1) end defp do_drop(list, 0) do list end defp do_drop([], _) do [] end ## drop_while defp do_drop_while([h | t], fun) do if fun.(h) do do_drop_while(t, fun) else [h | t] end end defp do_drop_while([], _) do [] end ## fetch defp fetch_list([], _index), do: :error defp fetch_list([head | _], 0), do: {:ok, head} defp fetch_list([_ | tail], index), do: fetch_list(tail, index - 1) defp fetch_range(first, last, index) when first <= last and index >= 0 do item = first + index if item > last, do: :error, else: {:ok, item} end defp fetch_range(first, last, index) when first <= last do item = last + index + 1 if item < first, do: :error, else: {:ok, item} end defp fetch_range(first, last, index) when index >= 0 do item = first - index if item < last, do: :error, else: {:ok, item} end defp fetch_range(first, last, index) do item = last - index - 1 if item > first, do: :error, else: {:ok, item} end ## find defp do_find([h | t], default, fun) do if fun.(h) do h else do_find(t, default, fun) end end defp do_find([], default, _) do default end ## find_index defp do_find_index([h | t], counter, fun) do if fun.(h) do counter else do_find_index(t, counter + 1, fun) end end defp do_find_index([], _, _) do nil end ## find_value defp do_find_value([h | t], default, fun) do fun.(h) || do_find_value(t, default, fun) end defp do_find_value([], default, _) do default end ## shuffle defp unwrap([{_, h} | enumerable], t) do unwrap(enumerable, [h | t]) end defp unwrap([], t), do: t ## reverse_slice defp reverse_slice(rest, idx, idx, count, acc) do {slice, rest} = head_slice(rest, count, []) :lists.reverse(rest, :lists.reverse(slice, acc)) end defp reverse_slice([elem | rest], idx, start, count, acc) do reverse_slice(rest, idx - 1, start, count, [elem | acc]) end defp head_slice(rest, 0, acc), do: {acc, rest} defp head_slice([elem | rest], count, acc) do head_slice(rest, count - 1, [elem | acc]) end ## slice defp do_slice([], _start, _count) do [] end defp do_slice(_list, _start, 0) do [] end defp do_slice([h | t], 0, count) do [h | do_slice(t, 0, count-1)] end defp do_slice([_ | t], start, count) do do_slice(t, start-1, count) end ## sort defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do cond do fun.(y, entry) == bool -> {:split, entry, y, [x | r], rs, bool} fun.(x, entry) == bool -> {:split, y, entry, [x | r], rs, bool} r == [] -> {:split, y, x, [entry], rs, bool} true -> {:pivot, y, x, r, rs, entry, bool} end end defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do cond do fun.(y, entry) == bool -> {:pivot, entry, y, [x | r], rs, s, bool} fun.(x, entry) == bool -> {:pivot, y, entry, [x | r], rs, s, bool} fun.(s, entry) == bool -> {:split, entry, s, [], [[y, x | r] | rs], bool} true -> {:split, s, entry, [], [[y, x | r] | rs], bool} end end defp sort_reducer(entry, [x], fun) do {:split, entry, x, [], [], fun.(x, entry)} end defp sort_reducer(entry, acc, _fun) do [entry | acc] end defp sort_terminator({:split, y, x, r, rs, bool}, fun) do sort_merge([[y, x | r] | rs], fun, bool) end defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do sort_merge([[s], [y, x | r] | rs], fun, bool) end defp sort_terminator(acc, _fun) do acc end defp sort_merge(list, fun, true), do: reverse_sort_merge(list, [], fun, true) defp sort_merge(list, fun, false), do: sort_merge(list, [], fun, false) defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do: sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true) defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do: sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false) defp sort_merge([l], [], _fun, _bool), do: l defp sort_merge([l], acc, fun, bool), do: reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool) defp sort_merge([], acc, fun, bool), do: reverse_sort_merge(acc, [], fun, bool) defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do: reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true) defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do: reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false) defp reverse_sort_merge([l], acc, fun, bool), do: sort_merge([:lists.reverse(l, []) | acc], [], fun, bool) defp reverse_sort_merge([], acc, fun, bool), do: sort_merge(acc, [], fun, bool) defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do if fun.(h1, h2) == bool do sort_merge_2(h1, t1, t2, [h2 | m], fun, bool) else sort_merge_1(t1, h2, t2, [h1 | m], fun, bool) end end defp sort_merge_1([], h2, t2, m, _fun, _bool), do: :lists.reverse(t2, [h2 | m]) defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do if fun.(h1, h2) == bool do sort_merge_2(h1, t1, t2, [h2 | m], fun, bool) else sort_merge_1(t1, h2, t2, [h1 | m], fun, bool) end end defp sort_merge_2(h1, t1, [], m, _fun, _bool), do: :lists.reverse(t1, [h1 | m]) ## split defp do_split([h | t], counter, acc) when counter > 0 do do_split(t, counter - 1, [h | acc]) end defp do_split(list, 0, acc) do {:lists.reverse(acc), list} end defp do_split([], _, acc) do {:lists.reverse(acc), []} end defp do_split_reverse([h | t], counter, acc) when counter > 0 do do_split_reverse(t, counter - 1, [h | acc]) end defp do_split_reverse(list, 0, acc) do {:lists.reverse(list), acc} end defp do_split_reverse([], _, acc) do {[], acc} end ## split_while defp do_split_while([h | t], fun, acc) do if fun.(h) do do_split_while(t, fun, [h | acc]) else {:lists.reverse(acc), [h | t]} end end defp do_split_while([], _, acc) do {:lists.reverse(acc), []} end ## take defp do_take([h | t], counter, acc) when counter > 0 do do_take(t, counter - 1, [h | acc]) end defp do_take(_list, 0, acc) do :lists.reverse(acc) end defp do_take([], _, acc) do :lists.reverse(acc) end ## take_while defp do_take_while([h | t], fun, acc) do if fun.(h) do do_take_while(t, fun, [h | acc]) else :lists.reverse(acc) end end defp do_take_while([], _, acc) do :lists.reverse(acc) end ## uniq defp do_uniq([h | t], set, fun, acc) do value = fun.(h) case set do %{^value => true} -> do_uniq(t, set, fun, acc) %{} -> do_uniq(t, Map.put(set, value, true), fun, [h | acc]) end end defp do_uniq([], _set, _fun, acc) do :lists.reverse(acc) end ## zip defp do_zip([h1 | next1], [h2 | next2], acc) do do_zip(next1, next2, [{h1, h2} | acc]) end defp do_zip(_, [], acc), do: :lists.reverse(acc) defp do_zip([], _, acc), do: :lists.reverse(acc) end defimpl Enumerable, for: List do def count(_list), do: {:error, __MODULE__} def member?(_list, _value), do: {:error, __MODULE__} def reduce(_, {:halt, acc}, _fun), do: {:halted, acc} def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)} def reduce([], {:cont, acc}, _fun), do: {:done, acc} def reduce([h | t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun) end defimpl Enumerable, for: Map do def count(map) do {:ok, map_size(map)} end def member?(map, {key, value}) do {:ok, match?({:ok, ^value}, :maps.find(key, map))} end def member?(_map, _other) do {:ok, false} end def reduce(map, acc, fun) do do_reduce(:maps.to_list(map), acc, fun) end defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc} defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)} defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc} defp do_reduce([h | t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun) end defimpl Enumerable, for: Function do def count(_function), do: {:error, __MODULE__} def member?(_function, _value), do: {:error, __MODULE__} def reduce(function, acc, fun) when is_function(function, 2), do: function.(acc, fun) end
26.611092
105
0.604297
08721d5bb7faa7a98fc4beca179c5a26aa3f74c6
352
exs
Elixir
test/dextruct_use_test.exs
taiansu/dextruct
13459db2b4a6d79d13ab7542717d3b2829bc9422
[ "Apache-2.0" ]
1
2017-10-21T09:44:44.000Z
2017-10-21T09:44:44.000Z
test/dextruct_use_test.exs
taiansu/dextruct
13459db2b4a6d79d13ab7542717d3b2829bc9422
[ "Apache-2.0" ]
null
null
null
test/dextruct_use_test.exs
taiansu/dextruct
13459db2b4a6d79d13ab7542717d3b2829bc9422
[ "Apache-2.0" ]
null
null
null
defmodule DextructUseTest do use ExUnit.Case use Dextruct, fill: 0 describe "use different filler" do test "Destruct with list" do [a, b] <~ [1] assert [a, b] == [1, 0] end test "Destruct with map" do %{a: a, b: b, c: foo} <~ %{a: 1} assert a == 1 assert b == 0 assert foo == 0 end end end
18.526316
38
0.53125
087222b5e834945668de568c600c77ebf35ebf9e
1,154
ex
Elixir
lib/surgex/parser/parsers/float_parser.ex
surgeventures/surgex
b3acdd6a9a010c26f0081b9cb23aeb072459be30
[ "MIT" ]
10
2017-09-15T08:55:48.000Z
2021-07-08T09:26:24.000Z
lib/surgex/parser/parsers/float_parser.ex
surgeventures/surgex
b3acdd6a9a010c26f0081b9cb23aeb072459be30
[ "MIT" ]
17
2017-07-24T11:27:22.000Z
2022-01-24T22:28:18.000Z
lib/surgex/parser/parsers/float_parser.ex
surgeventures/surgex
b3acdd6a9a010c26f0081b9cb23aeb072459be30
[ "MIT" ]
2
2018-04-12T15:01:00.000Z
2018-05-27T12:14:34.000Z
defmodule Surgex.Parser.FloatParser do @moduledoc false @type errors :: :invalid_float | :out_of_range @type option :: {:min, number()} | {:max, number()} @spec call(term(), [option()]) :: {:ok, float() | nil} | {:error, errors()} def call(input, opts \\ []) def call(nil, _opts), do: {:ok, nil} def call("", _opts), do: {:ok, nil} def call(input, opts) when is_integer(input) do call(input / 1, opts) end def call(input, opts) when is_float(input) do min = Keyword.get(opts, :min) max = Keyword.get(opts, :max) validate_range(input, min, max) end def call(input, opts) when is_binary(input) do min = Keyword.get(opts, :min) max = Keyword.get(opts, :max) case Float.parse(input) do {float, ""} -> validate_range(float, min, max) _ -> {:error, :invalid_float} end end def call(_input, _opts), do: {:error, :invalid_float} defp validate_range(input, min, max) do case input do float when (is_number(min) and float < min) or (is_number(max) and float > max) -> {:error, :out_of_range} float -> {:ok, float} end end end
24.553191
88
0.598787
08723bc92517d6e66e5cf21ea3ca071fda49d472
238
ex
Elixir
lib/phone/es/cc.ex
ajmath/phone
0c7c7033ea93d028d3bd2a9e445d3aa93a6bc2fa
[ "Apache-2.0" ]
null
null
null
lib/phone/es/cc.ex
ajmath/phone
0c7c7033ea93d028d3bd2a9e445d3aa93a6bc2fa
[ "Apache-2.0" ]
null
null
null
lib/phone/es/cc.ex
ajmath/phone
0c7c7033ea93d028d3bd2a9e445d3aa93a6bc2fa
[ "Apache-2.0" ]
null
null
null
defmodule Phone.ES.CC do @moduledoc false use Helper.Area def regex, do: ~r/^(34)(927|827)(.{6})/ def area_name, do: "Cáceres" def area_type, do: "province" def area_abbreviation, do: "CC" matcher(["34927", "34827"]) end
18.307692
41
0.647059
08725140f2656f59c36890bf6d784eb8045d589a
1,290
ex
Elixir
lib/conduit/blog/slugger.ex
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
null
null
null
lib/conduit/blog/slugger.ex
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
2
2022-01-15T02:09:30.000Z
2022-01-22T10:18:43.000Z
lib/conduit/blog/slugger.ex
rudyyazdi/conduit
8defa60962482fb81f5093ea5d58b71a160db3c4
[ "MIT" ]
null
null
null
defmodule Conduit.Blog.Slugger do alias Conduit.Blog @doc """ Slugify the given text and ensure that it is unique. A slug will contain only alphanumeric characters (`a-z`, `0-9`) and the default separator character (`-`). If the generated slug is already taken, append a numeric suffix and keep incrementing until a unique slug is found. ## Examples - "Example article" => "example-article", "example-article-2", "example-article-3", etc. """ @spec slugify(String.t) :: {:ok, slug :: String.t} | {:error, reason :: term} def slugify(title) do title |> Slugger.slugify_downcase() |> ensure_unique_slug() end # Ensure the given slug is unique, if not increment the suffix and try again. defp ensure_unique_slug(slug, suffix \\ 1) defp ensure_unique_slug("", _suffix), do: "" defp ensure_unique_slug(slug, suffix) do suffixed_slug = suffixed(slug, suffix) case exists?(suffixed_slug) do true -> ensure_unique_slug(slug, suffix + 1) false -> {:ok, suffixed_slug} end end # Does the slug exist? defp exists?(slug) do case Blog.article_by_slug(slug) do nil -> false _ -> true end end defp suffixed(slug, 1), do: slug defp suffixed(slug, suffix), do: slug <> "-" <> to_string(suffix) end
28.666667
117
0.669767
087282dce7ff4c21cebc33ea25c8b6448a7b9ba8
76
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_arrow_operation_parsing_test_case/DecimalWholeNumber.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_arrow_operation_parsing_test_case/DecimalWholeNumber.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_arrow_operation_parsing_test_case/DecimalWholeNumber.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
1 <~ 2 1 |> 2 1 ~> 2 1 <<< 2 1 <<~ 2 1 <|> 2 1 <~> 2 1 >>> 2 1 ~>> 2 1 ^^^ 2
7.6
7
0.263158
08729605688fbb96037bf0b5b6c8f714b302a79f
782
exs
Elixir
test/token_test.exs
cjsuite/bpxe
4b4759b7e2e8ced9f6f76ab55e5da26eb319a7c9
[ "Apache-2.0" ]
null
null
null
test/token_test.exs
cjsuite/bpxe
4b4759b7e2e8ced9f6f76ab55e5da26eb319a7c9
[ "Apache-2.0" ]
null
null
null
test/token_test.exs
cjsuite/bpxe
4b4759b7e2e8ced9f6f76ab55e5da26eb319a7c9
[ "Apache-2.0" ]
null
null
null
defmodule BPXETest.Token do use ExUnit.Case, async: true doctest BPXE.Token test "generating new generation ID always generates non-duplicate, monotonic IDs" do activation = BPXE.Engine.Process.Activation.new() token = BPXE.Token.new(activation: activation) pid = self() for _ <- 1..1000 do spawn_link(fn -> {_activation, id} = BPXE.Token.next_generation(token) send(pid, id) end) end tokens = receive_all(1000) |> Enum.uniq() |> Enum.sort() assert length(tokens) == 1000 assert 1..1000 |> Enum.to_list() == tokens BPXE.Engine.Process.Activation.discard(activation) end defp receive_all(0), do: [] defp receive_all(n) do receive do token -> [token | receive_all(n - 1)] end end end
23
86
0.648338
08730dc1561b709de33040df2918c17257b551a2
1,170
exs
Elixir
rustler_tests/test/thread_test.exs
sthagen/rusterlium-rustler
5f0b052e6ae96185794bb5dae6594f0fc48689d7
[ "Apache-2.0", "MIT" ]
2,075
2019-03-10T02:30:23.000Z
2022-03-31T21:34:49.000Z
rustler_tests/test/thread_test.exs
sthagen/rusterlium-rustler
5f0b052e6ae96185794bb5dae6594f0fc48689d7
[ "Apache-2.0", "MIT" ]
194
2019-03-10T00:14:16.000Z
2022-03-30T13:37:00.000Z
rustler_tests/test/thread_test.exs
sthagen/rusterlium-rustler
5f0b052e6ae96185794bb5dae6594f0fc48689d7
[ "Apache-2.0", "MIT" ]
130
2019-03-13T05:31:10.000Z
2022-03-27T15:34:05.000Z
defmodule RustlerTest.ThreadTest do use ExUnit.Case, async: true test "simple threaded nif" do RustlerTest.threaded_fac(19) receive do x -> assert x == 121_645_100_408_832_000 end end test "sleeping nif" do RustlerTest.threaded_sleep(200) receive do _ -> raise "timeout_expected" after 100 -> nil end receive do x -> assert x == 200 after 1000 -> raise "message_expected" end end test "many threads" do # Spawn 50 threads. times = Enum.map(1..50, fn x -> x * 10 end) Enum.map(times, &RustlerTest.threaded_sleep/1) # Wait for them all to respond. results = Enum.map(times, fn _ -> receive do y -> y after 1000 -> :timeout end end) # The OS scheduler guarantees virtually nothing about sleep(). # Answers may arrive out of order. assert Enum.sort(results) == times end test "thread panic" do # overflows u64 and panics RustlerTest.threaded_fac(100) receive do msg -> assert msg == {:error, "threaded_fac: integer overflow"} end end end
19.5
69
0.594872
0873174d396d26ec78e5d7fc4a63e524abc72224
7,288
exs
Elixir
test/oli_web/live/progress_live_test.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
test/oli_web/live/progress_live_test.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
test/oli_web/live/progress_live_test.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule OliWeb.ProgressLiveTest do use ExUnit.Case use OliWeb.ConnCase import Phoenix.LiveViewTest import Oli.Factory alias Lti_1p3.Tool.{ContextRoles, PlatformRoles} alias Oli.Accounts alias Oli.Delivery.Sections defp live_view_student_resource_route(section_slug, user_id, resource_id) do Routes.live_path( OliWeb.Endpoint, OliWeb.Progress.StudentResourceView, section_slug, user_id, resource_id ) end describe "user cannot access when is not logged in" do setup [:create_resource] test "redirects to new session when accessing the student resource view", %{ conn: conn, section: section, resource: resource, user: user } do redirect_path = "/session/new?request_path=%2Fsections%2F#{section.slug}%2Fprogress%2F#{user.id}%2F#{resource.id}&section=#{section.slug}" {:error, {:redirect, %{to: ^redirect_path}}} = live(conn, live_view_student_resource_route(section.slug, user.id, resource.id)) end end describe "user cannot access when is logged in as an author but is not a system admin" do setup [:author_conn, :create_resource] test "redirects to section enroll page when accessing the student resource view", %{ conn: conn, section: section, resource: resource, user: user } do conn = get(conn, live_view_student_resource_route(section.slug, user.id, resource.id)) redirect_path = "/session/new?request_path=%2Fsections%2F#{section.slug}%2Fprogress%2F#{user.id}%2F#{resource.id}&amp;section=#{section.slug}" assert conn |> get(live_view_student_resource_route(section.slug, user.id, resource.id)) |> html_response(302) =~ "<html><body>You are being <a href=\"#{redirect_path}\">redirected</a>.</body></html>" end end describe "student resource" do setup [:admin_conn, :create_resource] test "loads student resource progress data correctly", %{ conn: conn, section: section, resource: resource, user: user } do {:ok, view, _html} = live(conn, live_view_student_resource_route(section.slug, user.id, resource.id)) html = render(view) assert html =~ "Details" assert html =~ "Attempt History" end end describe "admin breadcrumbs" do setup [:admin_conn, :create_resource] test "manual grading view", %{ conn: conn, section: section } do conn = get(conn, Routes.live_path(OliWeb.Endpoint, OliWeb.ManualGrading.ManualGradingView, section.slug)) {:ok, _view, html} = live(conn) assert html =~ "<nav class=\"breadcrumb-bar" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Admin.AdminView)}\"" assert html =~ "Manual Scoring" end test "student view", %{ conn: conn, section: section, user: user } do {:ok, _view, html} = live(conn, Routes.live_path(OliWeb.Endpoint, OliWeb.Progress.StudentView, section.slug, user.id)) assert html =~ "<nav class=\"breadcrumb-bar" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Admin.AdminView)}\"" assert html =~ "Student Progress" end test "student resource view", %{ conn: conn, section: section, user: user, resource: resource } do {:ok, _view, html} = live(conn, live_view_student_resource_route(section.slug, user.id, resource.id)) assert html =~ "<nav class=\"breadcrumb-bar" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Admin.AdminView)}\"" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Progress.StudentView, section.slug, user.id)}\"" assert html =~ "View Resource Progress" end end describe "instructor breadcrumbs" do setup [:create_resource, :setup_instructor_session] test "manual grading view", %{ conn: conn, section: section } do conn = get(conn, Routes.live_path(OliWeb.Endpoint, OliWeb.ManualGrading.ManualGradingView, section.slug)) {:ok, _view, html} = live(conn) assert html =~ "<nav class=\"breadcrumb-bar" refute html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Admin.AdminView)}\"" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.OverviewView, section.slug)}\"" assert html =~ "Manual Scoring" end test "student view", %{ conn: conn, section: section, user: user } do {:ok, _view, html} = live(conn, Routes.live_path(OliWeb.Endpoint, OliWeb.Progress.StudentView, section.slug, user.id)) assert html =~ "<nav class=\"breadcrumb-bar" refute html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Admin.AdminView)}\"" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.OverviewView, section.slug)}\"" assert html =~ "Student Progress" end test "student resource view", %{ conn: conn, section: section, user: user, resource: resource } do {:ok, _view, html} = live(conn, live_view_student_resource_route(section.slug, user.id, resource.id)) assert html =~ "<nav class=\"breadcrumb-bar" refute html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Admin.AdminView)}\"" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Sections.OverviewView, section.slug)}\"" assert html =~ "<a href=\"#{Routes.live_path(OliWeb.Endpoint, OliWeb.Progress.StudentView, section.slug, user.id)}\"" assert html =~ "View Resource Progress" end end def create_resource(_context) do user = insert(:user) project = insert(:project, authors: [user.author]) section = insert(:section, type: :enrollable) section_project_publication = insert(:section_project_publication, %{section: section, project: project}) revision = insert(:revision, resource_type_id: Oli.Resources.ResourceType.get_id_by_type("page")) section_resource = insert(:section_resource, %{ section: section, project: project, resource_id: revision.resource.id }) Sections.update_section(section, %{root_section_resource_id: section_resource.id}) insert(:published_resource, %{ resource: revision.resource, revision: revision, publication: section_project_publication.publication, author: user.author }) {:ok, section: section, resource: revision.resource, user: user} end defp setup_instructor_session(%{conn: conn, user: user, section: section}) do {:ok, user} = Accounts.update_user(user, %{can_create_sections: true, independent_learner: true}) {:ok, instructor} = Accounts.update_user_platform_roles(user, [PlatformRoles.get_role(:institution_instructor)]) Sections.enroll(instructor.id, section.id, [ContextRoles.get_role(:context_instructor)]) conn = conn |> Plug.Test.init_test_session(lti_session: nil) |> Pow.Plug.assign_current_user(instructor, OliWeb.Pow.PowHelpers.get_pow_config(:user)) {:ok, %{conn: conn, instructor: instructor, section: section}} end end
33.585253
134
0.662184
08732ecf8c91b022c496600a15fe26db0fc684da
1,190
ex
Elixir
apps/core/lib/core/schema/upgrade.ex
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
59
2021-09-16T19:29:39.000Z
2022-03-31T20:44:24.000Z
apps/core/lib/core/schema/upgrade.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
111
2021-08-15T09:56:37.000Z
2022-03-31T23:59:32.000Z
apps/core/lib/core/schema/upgrade.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
4
2021-12-13T09:43:01.000Z
2022-03-29T18:08:44.000Z
defmodule Core.Schema.Upgrade do use Piazza.Ecto.Schema alias Core.Schema.{UpgradeQueue, Repository} alias Piazza.Ecto.UUID defenum Type, deploy: 0, approval: 1, bounce: 2 schema "upgrades" do field :type, Type field :message, :string belongs_to :queue, UpgradeQueue belongs_to :repository, Repository timestamps() end def after_seq(query \\ __MODULE__, id) def after_seq(query, nil), do: query def after_seq(query, id) do from(u in query, where: u.id > ^id) end def ordered(query \\ __MODULE__, order \\ [asc: :id]) do from(u in query, order_by: ^order) end def limit(query \\ __MODULE__, limit \\ 1) do from(u in query, limit: ^limit) end def for_queue(query \\ __MODULE__, id) do from(u in query, where: u.queue_id == ^id) end @valid ~w(type message repository_id queue_id)a def changeset(model, attrs \\ %{}) do model |> cast(attrs, @valid) |> put_change(:id, UUID.generate_monotonic()) |> validate_length(:message, max: 10_000) |> foreign_key_constraint(:queue_id) |> foreign_key_constraint(:repository_id) |> validate_required([:queue_id, :repository_id]) end end
24.791667
58
0.668067
08733f16621e31e0ebb3b511ec0b8f4bea844d1d
2,251
ex
Elixir
clients/monitoring/lib/google_api/monitoring/v3/model/distribution_cut.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/monitoring/lib/google_api/monitoring/v3/model/distribution_cut.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/monitoring/lib/google_api/monitoring/v3/model/distribution_cut.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Monitoring.V3.Model.DistributionCut do @moduledoc """ A DistributionCut defines a TimeSeries and thresholds used for measuring good service and total service. The TimeSeries must have ValueType = DISTRIBUTION and MetricKind = DELTA or MetricKind = CUMULATIVE. The computed good_service will be the count of values x in the Distribution such that range.min <= x < range.max. ## Attributes * `distributionFilter` (*type:* `String.t`, *default:* `nil`) - A monitoring filter (https://cloud.google.com/monitoring/api/v3/filters) specifying a TimeSeries aggregating values. Must have ValueType = DISTRIBUTION and MetricKind = DELTA or MetricKind = CUMULATIVE. * `range` (*type:* `GoogleApi.Monitoring.V3.Model.GoogleMonitoringV3Range.t`, *default:* `nil`) - Range of values considered "good." For a one-sided range, set one bound to an infinite value. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :distributionFilter => String.t() | nil, :range => GoogleApi.Monitoring.V3.Model.GoogleMonitoringV3Range.t() | nil } field(:distributionFilter) field(:range, as: GoogleApi.Monitoring.V3.Model.GoogleMonitoringV3Range) end defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.DistributionCut do def decode(value, options) do GoogleApi.Monitoring.V3.Model.DistributionCut.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.DistributionCut do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.02
321
0.753443
0873682de65ad87a3d9a6f56b638355f7779052d
113
ex
Elixir
lib/cereal/errors.ex
APB9785/cereal_ex
7405122553aacfc0a37b69bb4b14ae013be99f0c
[ "MIT" ]
4
2018-09-29T18:34:04.000Z
2019-11-24T17:18:57.000Z
lib/cereal/errors.ex
APB9785/cereal_ex
7405122553aacfc0a37b69bb4b14ae013be99f0c
[ "MIT" ]
4
2018-07-25T17:09:21.000Z
2020-01-23T15:06:21.000Z
lib/cereal/errors.ex
APB9785/cereal_ex
7405122553aacfc0a37b69bb4b14ae013be99f0c
[ "MIT" ]
1
2021-11-01T19:32:18.000Z
2021-11-01T19:32:18.000Z
defmodule Cereal.Errors do @moduledoc """ A serializer to handle errors and correctly encode them. """ end
18.833333
58
0.725664
08739d3b89863d3341eaa44456d9be6a2fc9013a
1,257
exs
Elixir
mix.exs
wkhere/webassembly
f24b43a7383c73da907095d03bfdf54ea6ecbabe
[ "BSD-2-Clause" ]
44
2017-01-22T03:54:32.000Z
2022-01-24T16:06:19.000Z
mix.exs
wkhere/webassembly
f24b43a7383c73da907095d03bfdf54ea6ecbabe
[ "BSD-2-Clause" ]
2
2018-09-28T03:07:30.000Z
2022-01-13T00:02:46.000Z
mix.exs
wkhere/webassembly
f24b43a7383c73da907095d03bfdf54ea6ecbabe
[ "BSD-2-Clause" ]
6
2018-03-03T16:45:11.000Z
2021-05-28T16:09:20.000Z
defmodule WebAssembly.Mixfile do use Mix.Project def project do [app: :webassembly, docs: [main: WebAssembly], version: "0.6.2-dev", elixir: "~> 1.0", deps: deps, description: description, package: package, test_coverage: [tool: ExCoveralls]] end def application do [applications: [], description: 'Web DSL'] end defp deps, do: [ {:excoveralls, "== 0.3.6", only: :test}, {:ex_doc, "~> 0.8.0", only: :dev}, {:dialyze, "== 0.1.3", only: :dev}, ] defp description do ~S""" WebAssembly is a web DSL for Elixir. You create html structure straight using do blocks. Means, you can intermix html-building blocks with full Elixir syntax. DSL output is an iolist, which you can flatten to string, but better use is to just feed it to the socket (via Plug & Cowboy). WebAssembly aims to have 100% test coverage. """ end defp package do [ maintainers: ["Wojciech Kaczmarek", "Roman Heinrich"], licenses: ["BSD"], description: description, links: %{ "GitHub" => "https://github.com/herenowcoder/webassembly", "HexDocs" => "http://hexdocs.pm/webassembly", }, ] end end
24.173077
73
0.595863
0873c364e067a7eb88e011cbde8b68ed1eeb8c9c
1,003
exs
Elixir
config/test.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
null
null
null
config/test.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
null
null
null
config/test.exs
calleluks/ex-remit
893dbc42c9ace6db6ee044f82371075198089fdc
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database # # The MIX_TEST_PARTITION environment variable can be used # to provide built-in test partitioning in CI environment. # Run `mix help test` for more information. config :remit, Remit.Repo, database: "remit_test#{System.get_env("MIX_TEST_PARTITION")}", hostname: "localhost", username: System.get_env("POSTGRES_USER") || System.get_env("USER"), password: System.get_env("POSTGRES_PASSWORD") || "", pool: Ecto.Adapters.SQL.Sandbox # We don't run a server during test. If one is required, # you can enable the server option below. config :remit, RemitWeb.Endpoint, http: [port: 4002], server: false config :remit, auth_key: "test_auth_key", webhook_key: "test_webhook_key", github_api_token: "test_github_api_token", github_api_client: GitHubAPIClient.Mock config :tesla, adapter: Tesla.Mock # Print only warnings and errors during test config :logger, level: :warn config :honeybadger, environment_name: :test, api_key: "not-used"
28.657143
70
0.749751
0873dba327d114a912e9828aec8891937f02ce61
116
exs
Elixir
test/breaker_configuration_test.exs
BobbyMcWho/breaker_box
bb5c2c6f676251cb658293e9eb7452bd22a94f4e
[ "MIT" ]
3
2019-09-24T22:11:57.000Z
2022-01-19T22:34:21.000Z
test/breaker_configuration_test.exs
BobbyMcWho/breaker_box
bb5c2c6f676251cb658293e9eb7452bd22a94f4e
[ "MIT" ]
1
2021-05-18T01:47:02.000Z
2021-05-18T01:47:02.000Z
test/breaker_configuration_test.exs
BobbyMcWho/breaker_box
bb5c2c6f676251cb658293e9eb7452bd22a94f4e
[ "MIT" ]
3
2021-01-08T02:46:14.000Z
2022-01-13T15:30:52.000Z
defmodule BreakerConfigurationTest do use ExUnit.Case, async: true doctest BreakerBox.BreakerConfiguration end
19.333333
41
0.836207
08740cf0237327371bc485824220c8a8d324d380
1,239
ex
Elixir
exercises/practice/rectangles/.meta/example.ex
jaimeiniesta/elixir-1
e8ddafeb313822645e0cd76743955a5c728a84c5
[ "MIT" ]
343
2017-06-22T16:28:28.000Z
2022-03-25T21:33:32.000Z
exercises/practice/rectangles/.meta/example.ex
jaimeiniesta/elixir-1
e8ddafeb313822645e0cd76743955a5c728a84c5
[ "MIT" ]
583
2017-06-19T10:48:40.000Z
2022-03-28T21:43:12.000Z
exercises/practice/rectangles/.meta/example.ex
jaimeiniesta/elixir-1
e8ddafeb313822645e0cd76743955a5c728a84c5
[ "MIT" ]
228
2017-07-05T07:09:32.000Z
2022-03-27T08:59:08.000Z
defmodule Rectangles do @doc """ Count the number of ASCII rectangles. """ @spec count(input :: String.t()) :: integer def count(input) do input = input |> String.split("\n") |> Enum.map(&to_charlist/1) coord = for {row, r} <- Enum.with_index(input), {char, c} <- Enum.with_index(row), char != ?\s, into: %{}, do: {{r, c}, char} corners = coord |> Enum.filter(fn {_pos, char} -> char == ?+ end) |> Enum.map(fn {pos, _char} -> pos end) for {r1, c1} <- corners, {r2, c2} <- corners, r1 < r2 and c1 < c2, coord[{r1, c2}] == ?+ and coord[{r2, c1}] == ?+, connected?(coord, {r1, c1}, {r2, c2}) do :ok end |> length end defp connected?(coord, {r1, c1}, {r2, c2}) do Enum.all?([ connected?(coord, r1, r2, column: c1), connected?(coord, r1, r2, column: c2), connected?(coord, c1, c2, row: r1), connected?(coord, c1, c2, row: r1) ]) end defp connected?(coord, r1, r2, column: c), do: Enum.all?(r1..r2, fn r -> coord[{r, c}] in '+|' end) defp connected?(coord, c1, c2, row: r), do: Enum.all?(c1..c2, fn c -> coord[{r, c}] in '+-' end) end
25.285714
60
0.497175
08741186645337da5d2786b71e8778b193b44116
524
ex
Elixir
lib/hook/inbounds/github/http.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
806
2018-04-07T20:40:33.000Z
2022-03-30T01:39:57.000Z
lib/hook/inbounds/github/http.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
194
2018-04-07T13:49:37.000Z
2022-03-30T19:58:45.000Z
lib/hook/inbounds/github/http.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
89
2018-04-09T13:55:49.000Z
2022-03-24T07:09:31.000Z
defmodule Accent.Hook.Inbounds.GitHub.FileServer.HTTP do use HTTPoison.Base @behaviour Accent.Hook.Inbounds.GitHub.FileServer @base_url "https://api.github.com/repos/" @impl true def get_path(path, options), do: get(path, options) @impl true def process_url(@base_url <> path), do: process_url(path) def process_url(path), do: @base_url <> path @impl true def process_response_body(body) do body |> Jason.decode() |> case do {:ok, body} -> body _ -> :error end end end
20.96
59
0.669847
08742615caea4896a4ea4fe3f8481dd4670755a3
1,525
ex
Elixir
core/alert/handler_config.ex
wses-yoshida/antikythera
e108e59d2339edd0b0fad31ad4f41f56df45be55
[ "Apache-2.0" ]
null
null
null
core/alert/handler_config.ex
wses-yoshida/antikythera
e108e59d2339edd0b0fad31ad4f41f56df45be55
[ "Apache-2.0" ]
null
null
null
core/alert/handler_config.ex
wses-yoshida/antikythera
e108e59d2339edd0b0fad31ad4f41f56df45be55
[ "Apache-2.0" ]
null
null
null
# Copyright(c) 2015-2019 ACCESS CO., LTD. All rights reserved. use Croma defmodule AntikytheraCore.Alert.HandlerConfig do @moduledoc """ Type module for map of configurations for a single alert handler. Fields are treated as opaque at this layer; details are defined by each handler implementation. """ alias Antikythera.GearName alias AntikytheraCore.Alert.HandlerConfigsMap use Croma.SubtypeOfMap, key_module: Croma.String, value_module: Croma.Any defun get(handler :: v[module], otp_app_name :: v[:antikythera | GearName.t]) :: t do HandlerConfigsMap.get(otp_app_name) |> Map.get(key(handler), %{}) end defunp key(handler :: v[module]) :: String.t do handler |> Module.split() |> List.last() |> Macro.underscore() end end defmodule AntikytheraCore.Alert.HandlerConfigsMap do @moduledoc """ Type module for map of all alert configurations for a single OTP application (antikythera or a gear). Keys must be snake-cased handler names and values must be maps of each alert handler's configurations. These maps are stored in core/gear configs. """ alias Antikythera.GearName alias AntikytheraCore.Ets.ConfigCache use Croma.SubtypeOfMap, key_module: Croma.String, value_module: AntikytheraCore.Alert.HandlerConfig defun get(otp_app_name :: v[:antikythera | GearName.t]) :: t do case otp_app_name do :antikythera -> ConfigCache.Core.read() |> Map.get(:alerts, %{}) gear_name -> ConfigCache.Gear.read(gear_name).alerts end end end
30.5
104
0.729836
087445a3db572643788d568ce5d0916e1e3a2796
5,391
ex
Elixir
lib/stripe/core_resources/refund.ex
Rutaba/stripity_stripe
12c525301c781f9c8c7e578cc0d933f5d35183d5
[ "BSD-3-Clause" ]
555
2016-11-29T05:02:27.000Z
2022-03-30T00:47:59.000Z
lib/stripe/core_resources/refund.ex
Rutaba/stripity_stripe
12c525301c781f9c8c7e578cc0d933f5d35183d5
[ "BSD-3-Clause" ]
532
2016-11-28T18:22:25.000Z
2022-03-30T17:04:32.000Z
lib/stripe/core_resources/refund.ex
Rutaba/stripity_stripe
12c525301c781f9c8c7e578cc0d933f5d35183d5
[ "BSD-3-Clause" ]
296
2016-12-05T14:04:09.000Z
2022-03-28T20:39:37.000Z
defmodule Stripe.Refund do @moduledoc """ Work with [Stripe `refund` objects](https://stripe.com/docs/api/refunds/object). You can: - [Create a refund](https://stripe.com/docs/api/refunds/create) - [Retrieve a refund](https://stripe.com/docs/api/refunds/retrieve) - [Update a refund](https://stripe.com/docs/api/update) - [List all refunds](https://stripe.com/docs/api/refunds/list) """ use Stripe.Entity import Stripe.Request @type t :: %__MODULE__{ id: Stripe.id(), object: String.t(), amount: non_neg_integer, balance_transaction: Stripe.id() | Stripe.BalanceTransaction.t() | nil, charge: Stripe.id() | Stripe.Charge.t() | nil, created: Stripe.timestamp(), currency: String.t(), failure_balance_transaction: Stripe.id() | Stripe.BalanceTransaction.t() | nil, failure_reason: String.t() | nil, metadata: Stripe.Types.metadata(), payment_intent: Stripe.id() | Stripe.PaymentIntent.t() | nil, reason: String.t() | nil, receipt_number: String.t() | nil, source_transfer_reversal: Stripe.id() | Stripe.TransferReversal.t() | nil, status: String.t() | nil, transfer_reversal: Stripe.id() | Stripe.TransferReversal.t() | nil } defstruct [ :id, :object, :amount, :balance_transaction, :charge, :created, :currency, :failure_balance_transaction, :failure_reason, :metadata, :payment_intent, :reason, :receipt_number, :source_transfer_reversal, :status, :transfer_reversal ] @plural_endpoint "refunds" @doc """ Create a refund. When you create a new refund, you must specify a charge to create it on. Creating a new refund will refund a charge that has previously been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged. You can optionally refund only part of a charge. You can do so as many times as you wish until the entire charge has been refunded. Once entirely refunded, a charge can't be refunded again. This method will return an error when called on an already-refunded charge, or when trying to refund more money than is left on a charge. See the [Stripe docs](https://stripe.com/docs/api/refunds/create). """ @spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()} when params: %{ optional(:charge) => Stripe.Charge.t() | Stripe.id(), optional(:payment_intent) => Stripe.PaymentIntent.t() | Stripe.id(), optional(:amount) => pos_integer, optional(:metadata) => Stripe.Types.metadata(), optional(:reason) => String.t(), optional(:refund_application_fee) => boolean, optional(:reverse_transfer) => boolean } | %{} def create(params, opts \\ []) do new_request(opts) |> put_endpoint(@plural_endpoint) |> put_method(:post) |> put_params(params) |> cast_to_id([:charge, :payment_intent]) |> make_request() end @doc """ Retrieve a refund. Retrieves the details of an existing refund. See the [Stripe docs](https://stripe.com/docs/api/refunds/retrieve). """ @spec retrieve(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()} def retrieve(id, opts \\ []) do new_request(opts) |> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}") |> put_method(:get) |> make_request() end @doc """ Update a refund. Updates the specified refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. This request only accepts `:metadata` as an argument. See the [Stripe docs](https://stripe.com/docs/api/refunds/update). """ @spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()} when params: %{ optional(:metadata) => Stripe.Types.metadata() } | %{} def update(id, params, opts \\ []) do new_request(opts) |> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}") |> put_method(:post) |> put_params(params) |> make_request() end @doc """ List all refunds. Returns a list of all refunds you’ve previously created. The refunds are returned in sorted order, with the most recent refunds appearing first. For convenience, the 10 most recent refunds are always available by default on the charge object. See the [Stripe docs](https://stripe.com/docs/api/refunds/list). """ @spec list(params, Stripe.options()) :: {:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()} when params: %{ optional(:charget) => Stripe.id() | Stripe.Charge.t(), optional(:ending_before) => t | Stripe.id(), optional(:limit) => 1..100, optional(:starting_after) => t | Stripe.id() } | %{} def list(params \\ %{}, opts \\ []) do new_request(opts) |> prefix_expansions() |> put_endpoint(@plural_endpoint) |> put_method(:get) |> put_params(params) |> cast_to_id([:charge, :ending_before, :starting_after]) |> make_request() end end
33.277778
98
0.612502
08746d1f2f6936198388bc8945b95dc989f06986
2,155
ex
Elixir
lib/rfx/edit/credo/multi_alias1.ex
pcorey/rfx
db5be95d93b7aba0cf9799db273d8583c21bfc26
[ "MIT" ]
31
2021-05-29T22:57:04.000Z
2022-03-13T16:24:57.000Z
lib/rfx/edit/credo/multi_alias1.ex
pcorey/rfx
db5be95d93b7aba0cf9799db273d8583c21bfc26
[ "MIT" ]
4
2021-06-04T23:34:38.000Z
2021-07-16T16:01:20.000Z
lib/rfx/edit/credo/multi_alias1.ex
pcorey/rfx
db5be95d93b7aba0cf9799db273d8583c21bfc26
[ "MIT" ]
4
2021-06-11T13:10:04.000Z
2022-02-11T13:33:16.000Z
defmodule Rfx.Edit.Credo.MultiAlias1 do @behaviour Rfx.Edit @moduledoc false @impl true def edit(source) do source |> Sourceror.parse_string!() |> expand_aliases() |> Sourceror.to_string() end defp expand_aliases(quoted) do Sourceror.postwalk(quoted, fn {:alias, _, [{{:., _, [_, :{}]}, _, _}]} = quoted, state -> {aliases, state} = expand_alias(quoted, state) {{:__block__, [unwrap_me?: true], aliases}, state} {:__block__, meta, args}, state -> args = Enum.reduce(args, [], &unwrap_aliases/2) {{:__block__, meta, args}, state} quoted, state -> {quoted, state} end) end defp unwrap_aliases({:__block__, [unwrap_me?: true], aliases}, args) do args ++ aliases end defp unwrap_aliases(quoted, args) do args ++ [quoted] end defp expand_alias({:alias, alias_meta, [{{:., _, [left, :{}]}, call_meta, right}]}, state) do {_, _, base_segments} = left leading_comments = alias_meta[:leading_comments] || [] trailing_comments = call_meta[:trailing_comments] || [] aliases = right |> Enum.map(&segments_to_alias(base_segments, &1)) |> put_leading_comments(leading_comments) |> put_trailing_comments(trailing_comments) {aliases, state} end defp segments_to_alias(base_segments, {_, meta, segments}) do {:alias, meta, [{:__aliases__, [], base_segments ++ segments}]} end defp put_leading_comments([first | rest], comments) do [Sourceror.prepend_comments(first, comments) | rest] end defp put_trailing_comments(list, comments) do case List.pop_at(list, -1) do {nil, list} -> list {last, list} -> last = {:__block__, [ trailing_comments: comments, # End of expression newlines higher than 1 will cause the formatter to add an # additional line break after the node. This is entirely optional and only showcased # here to improve the readability of the output end_of_expression: [newlines: 2] ], [last]} list ++ [last] end end end
26.280488
97
0.612065
08747697ab98f745a5f514c20a3351c2ffd1f462
586
ex
Elixir
lib/les/invoices/invoice.ex
gpad/les
2317b8055ab24aa857a6cda06f6e529c992c668c
[ "Apache-2.0" ]
11
2018-04-06T14:02:15.000Z
2020-12-09T10:44:03.000Z
lib/les/invoices/invoice.ex
gpad/les
2317b8055ab24aa857a6cda06f6e529c992c668c
[ "Apache-2.0" ]
1
2018-11-18T02:35:23.000Z
2018-11-18T02:35:23.000Z
lib/les/invoices/invoice.ex
gpad/les
2317b8055ab24aa857a6cda06f6e529c992c668c
[ "Apache-2.0" ]
null
null
null
defmodule Les.Invoices.Invoice do use Ecto.Schema import Ecto.Changeset alias Les.Invoices.Invoice schema "invoices" do field :amount, :integer field :status, :string belongs_to :user, Les.Accounts.User belongs_to :cart, Les.Carts.Cart has_many :items, Les.Invoices.InvoiceItem, on_replace: :delete, on_delete: :delete_all timestamps() end @doc false def changeset(%Invoice{} = invoice, attrs) do invoice |> cast(attrs, [:amount, :status, :cart_id, :user_id]) |> validate_required([:amount, :status, :cart_id, :user_id]) end end
23.44
90
0.691126
08747e0ab91f73a5306b3c95eff4d1bd39c1830f
525
exs
Elixir
test/stemmer_test.exs
fredwu/stemmer
750514636c399350e7ee7fbef5b731ea1cf0335c
[ "MIT" ]
149
2016-07-18T14:21:16.000Z
2022-02-24T01:23:17.000Z
test/stemmer_test.exs
fredwu/stemmer
750514636c399350e7ee7fbef5b731ea1cf0335c
[ "MIT" ]
1
2022-01-09T03:18:14.000Z
2022-01-09T13:16:43.000Z
test/stemmer_test.exs
fredwu/stemmer
750514636c399350e7ee7fbef5b731ea1cf0335c
[ "MIT" ]
8
2016-07-19T09:23:31.000Z
2022-01-08T14:29:33.000Z
defmodule StemmerTest do use ExUnit.Case, async: true doctest Stemmer test "official diffs.txt" do file_path = Path.join(File.cwd!(), "test/samples/diffs.tar.gz") temp_path = Path.join(File.cwd!(), "test/temp") System.cmd("tar", ["xzvf", file_path, "-C", temp_path], stderr_to_stdout: true) Path.join(temp_path, "diffs.txt") |> File.stream!() |> Enum.each(fn line -> [word, official_stemmed] = String.split(line) assert Stemmer.stem(word) == official_stemmed end) end end
25
83
0.651429
08747ecb8e364f2bdd5c4046875227a9411da180
448
ex
Elixir
lib/okr_app_web/serializers/linked_objective.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
12
2019-05-10T21:48:06.000Z
2021-11-07T14:04:30.000Z
lib/okr_app_web/serializers/linked_objective.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
2
2019-05-14T19:07:10.000Z
2019-05-20T21:06:27.000Z
lib/okr_app_web/serializers/linked_objective.ex
sb8244/okr_app_pub
933872107bd13390a0a5ea119d7997d4cb5ea7db
[ "MIT" ]
3
2019-05-19T18:24:20.000Z
2019-10-31T20:29:12.000Z
defmodule OkrAppWeb.Serializer.LinkedObjective do use Remodel alias OkrAppWeb.Serializer attributes([:id, :content, :cancelled_at, :inserted_at, :updated_at, :owner]) def owner(%{user: user}) when not is_nil(user) do Serializer.PlainUser.to_map(user) |> Map.put("owner_type", "user") end def owner(%{group: group}) when not is_nil(group) do Serializer.Group.to_map(group) |> Map.put("owner_type", "group") end end
24.888889
79
0.700893
08749e3a6ec0edcef267edb8334ee29eb04e1c8f
974
exs
Elixir
config/travis.exs
karabiner-inc/materia_file_transfer
d72f11d97a4ac87362225558aaf88909c9a10c64
[ "Apache-2.0" ]
null
null
null
config/travis.exs
karabiner-inc/materia_file_transfer
d72f11d97a4ac87362225558aaf88909c9a10c64
[ "Apache-2.0" ]
null
null
null
config/travis.exs
karabiner-inc/materia_file_transfer
d72f11d97a4ac87362225558aaf88909c9a10c64
[ "Apache-2.0" ]
null
null
null
use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :materia_file_transfer, MateriaFileTransferWeb.Test.Endpoint, http: [port: 4001], # server: false, debug_errors: true, code_reloader: false, check_origin: false, watchers: [] # Print only warnings and errors during test config :logger, level: :info # Configure your database config :materia_file_transfer, MateriaFileTransfer.Test.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "", database: "materia_file_transfer_test", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox config :materia_file_transfer, repo: MateriaFileTransfer.Test.Repo # Configures GuardianDB config :guardian, Guardian.DB, repo: MateriaFileTransfer.Test.Repo, # default schema_name: "guardian_tokens", # token_types: ["refresh_token"], # store all token types if not set # default: 60 minutes sweep_interval: 60
27.828571
70
0.755647
08749e82389b42fc289c6fd1bc39c788e5b40d09
4,602
ex
Elixir
lib/absinthe/phase/schema/hydrate.ex
jscheid/absinthe
5b5079f03402f482c5f52a35efc263a5a6ccaf64
[ "MIT" ]
null
null
null
lib/absinthe/phase/schema/hydrate.ex
jscheid/absinthe
5b5079f03402f482c5f52a35efc263a5a6ccaf64
[ "MIT" ]
null
null
null
lib/absinthe/phase/schema/hydrate.ex
jscheid/absinthe
5b5079f03402f482c5f52a35efc263a5a6ccaf64
[ "MIT" ]
null
null
null
defmodule Absinthe.Phase.Schema.Hydrate do @moduledoc false @behaviour Absinthe.Schema.Hydrator use Absinthe.Phase alias Absinthe.Blueprint @hydrate [ Blueprint.Schema.DirectiveDefinition, Blueprint.Schema.EnumTypeDefinition, Blueprint.Schema.EnumValueDefinition, Blueprint.Schema.FieldDefinition, Blueprint.Schema.InputObjectTypeDefinition, Blueprint.Schema.InputValueDefinition, Blueprint.Schema.InterfaceTypeDefinition, Blueprint.Schema.ObjectTypeDefinition, Blueprint.Schema.ScalarTypeDefinition, Blueprint.Schema.SchemaDefinition, Blueprint.Schema.UnionTypeDefinition ] @impl Absinthe.Phase def run(blueprint, opts \\ []) do {:ok, schema} = Keyword.fetch(opts, :schema) hydrator = Keyword.get(opts, :hydrator, __MODULE__) blueprint = Blueprint.prewalk(blueprint, &handle_node(&1, [], schema, hydrator)) {:ok, blueprint} end defp handle_node(%Blueprint{} = node, ancestors, schema, hydrator) do node |> hydrate_node(ancestors, schema, hydrator) |> set_children(ancestors, schema, hydrator) end defp handle_node(%node_module{} = node, ancestors, schema, hydrator) when node_module in @hydrate do case Absinthe.Type.built_in_module?(node.module) do true -> {:halt, node} false -> node |> hydrate_node(ancestors, schema, hydrator) |> set_children(ancestors, schema, hydrator) end end defp handle_node(node, ancestors, schema, hydrator) do set_children(node, ancestors, schema, hydrator) end defp set_children(parent, ancestors, schema, hydrator) do Blueprint.prewalk(parent, fn ^parent -> parent child -> {:halt, handle_node(child, [parent | ancestors], schema, hydrator)} end) end defp hydrate_node(%{} = node, ancestors, schema, hydrator) do hydrations = schema.hydrate(node, ancestors) apply_hydrations(node, hydrations, hydrator) end defp apply_hydrations(node, hydrations, hydrator) do hydrations |> List.wrap() |> Enum.reduce(node, fn hydration, node -> hydrator.apply_hydration(node, hydration) end) end @impl Absinthe.Schema.Hydrator def apply_hydration(node, {:description, text}) do %{node | description: text} end def apply_hydration(node, {:resolve, resolver}) do %{node | middleware: [{Absinthe.Resolution, resolver}]} end def apply_hydration(node, {:resolve_type, resolve_type}) do %{node | resolve_type: resolve_type} end @hydration_level1 [ Blueprint.Schema.DirectiveDefinition, Blueprint.Schema.EnumTypeDefinition, Blueprint.Schema.InputObjectTypeDefinition, Blueprint.Schema.InterfaceTypeDefinition, Blueprint.Schema.ObjectTypeDefinition, Blueprint.Schema.ScalarTypeDefinition, Blueprint.Schema.UnionTypeDefinition ] @hydration_level2 [ Blueprint.Schema.FieldDefinition, Blueprint.Schema.EnumValueDefinition ] @hydration_level3 [ Blueprint.Schema.InputValueDefinition ] def apply_hydration(%Absinthe.Blueprint{} = root, %{} = sub_hydrations) do {root, _} = Blueprint.prewalk(root, nil, fn %module{identifier: ident} = node, nil when module in @hydration_level1 -> case Map.fetch(sub_hydrations, ident) do :error -> {node, nil} {:ok, type_hydrations} -> {apply_hydrations(node, type_hydrations, __MODULE__), nil} end node, nil -> {node, nil} end) root end def apply_hydration(%module{} = root, %{} = sub_hydrations) when module in @hydration_level1 do {root, _} = Blueprint.prewalk(root, nil, fn %module{identifier: ident} = node, nil when module in @hydration_level2 -> case Map.fetch(sub_hydrations, ident) do :error -> {node, nil} {:ok, type_hydrations} -> {apply_hydrations(node, type_hydrations, __MODULE__), nil} end node, nil -> {node, nil} end) root end def apply_hydration(%module{} = root, %{} = sub_hydrations) when module in @hydration_level2 do {root, _} = Blueprint.prewalk(root, nil, fn %module{identifier: ident} = node, nil when module in @hydration_level3 -> case Map.fetch(sub_hydrations, ident) do :error -> {node, nil} {:ok, type_hydrations} -> {apply_hydrations(node, type_hydrations, __MODULE__), nil} end node, nil -> {node, nil} end) root end end
27.890909
84
0.659713
08749fe4c0887214cd11b37cb880c695c30ff879
928
exs
Elixir
config/config.exs
leodag/phoenix
25da1373693eab8f9a7e51c135862ba8084a2d3f
[ "MIT" ]
null
null
null
config/config.exs
leodag/phoenix
25da1373693eab8f9a7e51c135862ba8084a2d3f
[ "MIT" ]
null
null
null
config/config.exs
leodag/phoenix
25da1373693eab8f9a7e51c135862ba8084a2d3f
[ "MIT" ]
null
null
null
import Config config :logger, :console, colors: [enabled: false] config :phoenix, :stacktrace_depth, 20 config :phoenix, :json_library, Jason config :phoenix, :trim_on_html_eex_engine, false if Mix.env() == :dev do esbuild = fn args -> [ args: ~w(./js/phoenix --bundle) ++ args, cd: Path.expand("../assets", __DIR__), env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} ] end config :esbuild, version: "0.12.18", module: esbuild.(~w(--format=esm --sourcemap --outfile=../priv/static/phoenix.esm.js)), main: esbuild.(~w(--format=cjs --sourcemap --outfile=../priv/static/phoenix.cjs.js)), cdn: esbuild.( ~w(--target=es2016 --format=iife --global-name=Phoenix --outfile=../priv/static/phoenix.js) ), cdn_min: esbuild.( ~w(--target=es2016 --format=iife --global-name=Phoenix --minify --outfile=../priv/static/phoenix.min.js) ) end
28.121212
112
0.619612
0874ab0d03bfd9a82f4646d36a5ce54bd292be5e
1,615
ex
Elixir
lib/phoenix/html/safe.ex
wojtekmach/phoenix
a6b3bf301c7088b8824a39a165582dc85dfdd2a4
[ "MIT" ]
null
null
null
lib/phoenix/html/safe.ex
wojtekmach/phoenix
a6b3bf301c7088b8824a39a165582dc85dfdd2a4
[ "MIT" ]
null
null
null
lib/phoenix/html/safe.ex
wojtekmach/phoenix
a6b3bf301c7088b8824a39a165582dc85dfdd2a4
[ "MIT" ]
null
null
null
alias Phoenix.HTML defprotocol Phoenix.HTML.Safe do @moduledoc """ Defines the HTML safe protocol. In order to promote HTML safety, Phoenix templates do not use `Kernel.to_string/1` to convert data types to strings in templates. Instead, Phoenix uses this protocol which must be implemented by data structures and guarantee that a HTML safe representation is returned. """ def to_string(data) end defimpl Phoenix.HTML.Safe, for: Atom do def to_string(nil), do: "" def to_string(atom), do: HTML.html_escape(Atom.to_string(atom)) end defimpl Phoenix.HTML.Safe, for: BitString do def to_string(data) when is_binary(data) do HTML.html_escape(data) end end defimpl Phoenix.HTML.Safe, for: List do def to_string(list) do do_to_string(list) |> IO.iodata_to_binary end defp do_to_string([h|t]) do [do_to_string(h)|do_to_string(t)] end defp do_to_string([]) do [] end # TODO: We could inline the escape for integers ?>, ?<, # ?&, ?" and ?' instead of calling Phoenix.HTML.html_escape/1 defp do_to_string(h) when is_integer(h) do HTML.html_escape(<<h :: utf8>>) end defp do_to_string(h) when is_binary(h) do HTML.html_escape(h) end defp do_to_string({:safe, h}) when is_binary(h) do h end end defimpl Phoenix.HTML.Safe, for: Integer do def to_string(data), do: Integer.to_string(data) end defimpl Phoenix.HTML.Safe, for: Float do def to_string(data) do IO.iodata_to_binary(:io_lib_format.fwrite_g(data)) end end defimpl Phoenix.HTML.Safe, for: Tuple do def to_string({:safe, data}) when is_binary(data), do: data end
23.405797
65
0.715789
0874ee09a3e8b8df42f81af0309bda2632efc02b
1,866
ex
Elixir
clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1_document_revision_human_review.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1_document_revision_human_review.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/document_ai/lib/google_api/document_ai/v1/model/google_cloud_documentai_v1_document_revision_human_review.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.DocumentAI.V1.Model.GoogleCloudDocumentaiV1DocumentRevisionHumanReview do @moduledoc """ Human Review information of the document. ## Attributes * `state` (*type:* `String.t`, *default:* `nil`) - Human review state. e.g. `requested`, `succeeded`, `rejected`. * `stateMessage` (*type:* `String.t`, *default:* `nil`) - A message providing more details about the current state of processing. For example, the rejection reason when the state is `rejected`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :state => String.t() | nil, :stateMessage => String.t() | nil } field(:state) field(:stateMessage) end defimpl Poison.Decoder, for: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1DocumentRevisionHumanReview do def decode(value, options) do GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1DocumentRevisionHumanReview.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DocumentAI.V1.Model.GoogleCloudDocumentaiV1DocumentRevisionHumanReview do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.927273
197
0.736334
087521a92c71c1fded6373a11e167c4a8fff59c7
1,996
ex
Elixir
lib/oli_web/live/manual_grading/filters.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli_web/live/manual_grading/filters.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli_web/live/manual_grading/filters.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule OliWeb.ManualGrading.Filters do use Surface.Component alias OliWeb.ManualGrading.FilterButton prop options, :struct, required: true prop selection, :boolean, required: true def render(assigns) do ~F""" <div style="display: inline;"> <FilterButton selection={@selection} tooltip="Only show attempts from this same user" label="User" key={:user_id} active={is_active(assigns, :user_id)} clicked={"filters_changed"}/> <FilterButton selection={@selection} tooltip="Only show attempts for this same activity" label="Activity" key={:activity_id} active={is_active(assigns, :activity_id)} clicked={"filters_changed"}/> <FilterButton selection={@selection} tooltip="Only show attempts for this same page" label="Page" key={:page_id} active={is_active(assigns, :page_id)} clicked={"filters_changed"}/> <FilterButton selection={@selection} tooltip="Only show attempts of this same purpose" label="Purpose" key={:graded} active={is_active(assigns, :graded)} clicked={"filters_changed"}/> </div> """ end def is_active(assigns, key), do: !(Map.get(assigns.options, key) |> is_nil) def handle_delegated(event, params, socket, patch_fn) do delegate_handle_event(event, params, socket, patch_fn) end def delegate_handle_event("filters_changed", %{"key" => key, "active" => "false"}, socket, patch_fn) do changes = Map.put(%{}, String.to_existing_atom(key), nil) patch_fn.(socket, changes) end def delegate_handle_event("filters_changed", %{"key" => key}, socket, patch_fn) do value = case key do "user_id" -> socket.assigns.attempt.user.id "activity_id" -> socket.assigns.attempt.resource_id "page_id" -> socket.assigns.attempt.page_id "graded" -> socket.assigns.attempt.graded end changes = Map.put(%{}, String.to_existing_atom(key), value) patch_fn.(socket, changes) end def delegate_handle_event(_, _, _, _) do :not_handled end end
39.137255
115
0.695892
08760162513af95197eaaadd815479014da82dd5
1,665
ex
Elixir
clients/dataproc/lib/google_api/dataproc/v1/model/cluster_metrics.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dataproc/lib/google_api/dataproc/v1/model/cluster_metrics.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dataproc/lib/google_api/dataproc/v1/model/cluster_metrics.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dataproc.V1.Model.ClusterMetrics do @moduledoc """ Contains cluster daemon metrics, such as HDFS and YARN stats.Beta Feature: This report is available for testing purposes only. It may be changed before final release. ## Attributes * `hdfsMetrics` (*type:* `map()`, *default:* `nil`) - The HDFS metrics. * `yarnMetrics` (*type:* `map()`, *default:* `nil`) - The YARN metrics. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :hdfsMetrics => map(), :yarnMetrics => map() } field(:hdfsMetrics, type: :map) field(:yarnMetrics, type: :map) end defimpl Poison.Decoder, for: GoogleApi.Dataproc.V1.Model.ClusterMetrics do def decode(value, options) do GoogleApi.Dataproc.V1.Model.ClusterMetrics.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataproc.V1.Model.ClusterMetrics do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.3
168
0.723123
08760bddf5df5f87d35f9b35b0ed683783aeb7eb
3,920
ex
Elixir
lib/saxy/xml.ex
marcelotto/saxy
a942d8d2d3ff028294b667487b9251d690ca9364
[ "MIT" ]
1
2020-04-29T08:08:22.000Z
2020-04-29T08:08:22.000Z
lib/saxy/xml.ex
marcelotto/saxy
a942d8d2d3ff028294b667487b9251d690ca9364
[ "MIT" ]
null
null
null
lib/saxy/xml.ex
marcelotto/saxy
a942d8d2d3ff028294b667487b9251d690ca9364
[ "MIT" ]
null
null
null
defmodule Saxy.XML do alias Saxy.Builder @moduledoc """ Helper functions for building XML elements. """ @type characters() :: {:characters, String.t()} @type cdata() :: {:cdata, String.t()} @type comment() :: {:comment, String.t()} @type ref() :: entity_ref() | hex_ref() | dec_ref() @type entity_ref() :: {:reference, {:entity, String.t()}} @type hex_ref() :: {:reference, {:hexadecimal, integer()}} @type dec_ref() :: {:reference, {:decimal, integer()}} @type processing_instruction() :: {:processing_instruction, name :: String.t(), instruction :: String.t()} @type element() :: { name :: String.t(), attributes :: [{key :: String.t(), value :: String.t()}], children :: [content] } @type content() :: element() | characters() | cdata() | ref() | comment() @compile { :inline, [ element: 3, characters: 1, cdata: 1, comment: 1, reference: 2, processing_instruction: 2 ] } @doc """ Builds empty element in simple form. """ @spec empty_element( name :: term(), attributes :: [{key :: term(), value :: term()}] ) :: element() def empty_element(name, attributes) when not is_nil(name) do { to_string(name), attributes(attributes), [] } end @doc """ Builds element in simple form. """ @spec element( name :: term(), attributes :: [{key :: term(), value :: term()}], children :: list() ) :: element() def element(name, attributes, children) when not is_nil(name) and is_list(children) do { to_string(name), attributes(attributes), children(children) } end def element(name, attributes, child) when not is_nil(name) do element(name, attributes, [child]) end @doc """ Builds characters in simple form. """ @spec characters(text :: term()) :: characters() def characters(text) do {:characters, to_string(text)} end @doc """ Builds CDATA in simple form. """ @spec cdata(text :: term()) :: cdata() def cdata(text) do {:cdata, to_string(text)} end @doc """ Builds comment in simple form. """ @spec comment(text :: term()) :: comment() def comment(text) do {:comment, to_string(text)} end @doc """ Builds reference in simple form. """ @spec reference( character_type :: :entity | :hexadecimal | :decimal, value :: term() ) :: ref() def reference(:entity, name) when not is_nil(name) do {:reference, {:entity, to_string(name)}} end def reference(character_type, integer) when character_type in [:hexadecimal, :decimal] and is_integer(integer) do {:reference, {character_type, integer}} end @doc """ Builds processing instruction in simple form. """ @spec processing_instruction( name :: String.t(), instruction :: String.t() ) :: processing_instruction() def processing_instruction(name, instruction) when not is_nil(name) do {:processing_instruction, to_string(name), instruction} end defp attributes(attributes) do Enum.map(attributes, &attribute/1) end defp children(children, acc \\ []) defp children([binary | children], acc) when is_binary(binary) do children(children, [binary | acc]) end defp children([{type, _} = form | children], acc) when type in [:characters, :comment, :cdata, :reference], do: children(children, [form | acc]) defp children([{_name, _attributes, _content} = form | children], acc) do children(children, [form | acc]) end defp children([], acc), do: Enum.reverse(acc) defp children([child | children], acc) do children(children, [Builder.build(child) | acc]) end defp attribute({name, value}) when not is_nil(name) do { to_string(name), to_string(value) } end end
22.4
108
0.596939
087639ec3b5ec6fa617ac052d33a0ae2518487a9
906
ex
Elixir
apps/omg_watcher/lib/omg_watcher/release_tasks/set_application.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/lib/omg_watcher/release_tasks/set_application.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/lib/omg_watcher/release_tasks/set_application.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2019 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.Watcher.ReleaseTasks.SetApplication do @moduledoc false @behaviour Config.Provider def init(args) do args end def load(config, release: release, current_version: current_version) do Config.Reader.merge(config, omg_watcher: [release: release, current_version: current_version]) end end
33.555556
98
0.764901
08763d6d83ba6cc121fb00105984300727811966
4,922
exs
Elixir
test/models/old_animal_test.exs
marick/eecrit
50b1ebeadc5cf21ea9f9df6add65e4d7037e2482
[ "MIT" ]
10
2016-07-15T15:57:33.000Z
2018-06-09T00:40:46.000Z
test/models/old_animal_test.exs
marick/eecrit
50b1ebeadc5cf21ea9f9df6add65e4d7037e2482
[ "MIT" ]
null
null
null
test/models/old_animal_test.exs
marick/eecrit
50b1ebeadc5cf21ea9f9df6add65e4d7037e2482
[ "MIT" ]
6
2016-07-15T15:57:41.000Z
2018-03-22T16:38:00.000Z
defmodule Eecrit.OldAnimalTest do use Eecrit.ModelCase alias Eecrit.OldAnimal, as: S @valid_date "2012-02-29" @invalid_date "2011-01-32" @invalid_species "catine" @valid_attrs %{kind: "kind", name: "name", procedure_description_kind: hd(S.valid_species)} @optional_attrs %{nickname: "nickname", date_removed_from_service: @valid_date} # @invalid_attrs %{} test "a starting changeset" do changeset = S.new_action_changeset() refute changeset.valid? end # Creation test "changeset with only required attributes" do changeset = S.create_action_changeset(@valid_attrs) assert changeset.valid? assert changeset.changes == @valid_attrs end test "changeset with all attributes" do attrs = Map.merge(@valid_attrs, @optional_attrs) changeset = S.create_action_changeset(attrs) assert changeset.valid? assert changeset.changes.date_removed_from_service == Ecto.Date.cast!(@valid_date) end test "an invalid changeset: bad date" do attrs = Map.put(@valid_attrs, :date_removed_from_service, @invalid_date) changeset = S.create_action_changeset(attrs) refute changeset.valid? assert Keyword.get(changeset.errors, :date_removed_from_service) end test "an invalid changeset: bad species" do attrs = Map.put(@valid_attrs, :procedure_description_kind, @invalid_species) changeset = S.create_action_changeset(attrs) refute changeset.valid? assert Keyword.get(changeset.errors, :procedure_description_kind) end test "a blank date is *not* an invalid changeset: null is allowed" do attrs = Map.put(@valid_attrs, :date_removed_from_service, "") changeset = S.create_action_changeset(attrs) assert changeset.valid? assert changeset.changes[:date_removed_from_service] == nil end test "the notion of 'already out of service'" do today = ~D[2016-08-03] e_yesterday = Ecto.Date.cast!(~D[2016-08-02]) e_today = Ecto.Date.cast!(today) e_tomorrow = Ecto.Date.cast!(~D[2016-08-04]) out_before_today = make_old_animal(date_removed_from_service: e_yesterday) out_today = make_old_animal(date_removed_from_service: e_today) out_after_today = make_old_animal(date_removed_from_service: e_tomorrow) assert S.already_out_of_service?(out_before_today, today) assert S.already_out_of_service?(out_today, today) refute S.already_out_of_service?(out_after_today, today) # Really uses a default argument for today animal = make_old_animal(date_removed_from_service: Ecto.Date.cast!("2000-01-01")) assert S.already_out_of_service?(animal) end test "sorting a list of animals in a pleasing way" do animals = [make_old_animal(name: "AM"), make_old_animal(name: "aa"), make_old_animal(name: "K"), make_old_animal(name: "m"), make_old_animal(name: "1")] assert S.alphabetical_names(animals) == ["1", "aa", "AM", "K", "m"] end describe "calculating use-days" do @a1 %{id: "a1"} @a2 %{id: "a2"} @a3 %{id: "a3"} @p1 %{id: "p1"} @p2 %{id: "p2"} @p3 %{id: "p3"} @single_day {Ecto.Date.cast!("2012-12-12"), Ecto.Date.cast!("2012-12-12")} @another_single_day {Ecto.Date.cast!("2012-12-13"), Ecto.Date.cast!("2012-12-13")} @ten_days {Ecto.Date.cast!("2012-11-01"), Ecto.Date.cast!("2012-11-10")} test "flattening these composite results" do one = %{animals: [@a1, @a2], procedures: [@p1, @p2], date_range: @ten_days} assert S.flatten_condensed_reservations([one]) == [{@a1, @p1, 10}, {@a1, @p2, 10}, {@a2, @p1, 10}, {@a2, @p2, 10}] end test "how the reduce step is started" do assert S.reduce_step({@a1, @p1, 3}, %{}) == %{@a1 => %{@p1 => 3}} end test "adding a new animal" do already = %{@a1 => %{@p1 => 3}} assert S.reduce_step({@a2, @p1, 5}, already) == Map.merge(already, %{@a2 => %{@p1 => 5}}) end test "adding a new procedure to an existing animal" do already = %{@a1 => %{@p1 => 3}} assert S.reduce_step({@a1, @p2, 5}, already) == %{@a1 => %{@p1 => 3, @p2 => 5}} end test "updating the count of an existing animal/procedure pair" do already = %{@a1 => %{@p1 => 3}} assert S.reduce_step({@a1, @p1, 5}, already) == %{@a1 => %{@p1 => 8}} end test "final calculation" do raw = [%{animals: [@a1, @a2], procedures: [@p1, @p2], date_range: @single_day}, %{animals: [@a2, @a3], procedures: [@p2, @p3], date_range: @another_single_day}, %{animals: [@a2], procedures: [@p1], date_range: @ten_days} ] expected = %{@a1 => %{@p1 => 1, @p2 => 1, }, @a2 => %{@p1 => 11, @p2 => 2, @p3 => 1}, @a3 => %{ @p2 => 1, @p3 => 1}} assert S.use_days(raw) == expected end end end
35.410072
93
0.626371
087688ba2f1d838754224a9597e3c273918cc98b
1,239
exs
Elixir
test/publickey_test.exs
PinkDiamond1/ecdsa-elixir
dd1953cc48974b5bfb9461d3a2179d1d937b264d
[ "MIT" ]
23
2020-01-31T17:45:09.000Z
2022-02-12T03:52:11.000Z
test/publickey_test.exs
PinkDiamond1/ecdsa-elixir
dd1953cc48974b5bfb9461d3a2179d1d937b264d
[ "MIT" ]
1
2020-02-04T22:26:14.000Z
2020-02-05T01:03:42.000Z
test/publickey_test.exs
PinkDiamond1/ecdsa-elixir
dd1953cc48974b5bfb9461d3a2179d1d937b264d
[ "MIT" ]
2
2020-01-30T22:00:07.000Z
2021-11-05T15:41:05.000Z
defmodule PublicKeyTest do use ExUnit.Case alias EllipticCurve.{PrivateKey, PublicKey} test "pem conversion" do privateKey = PrivateKey.generate() publicKey1 = PrivateKey.getPublicKey(privateKey) pem = PublicKey.toPem(publicKey1) {:ok, publicKey2} = PublicKey.fromPem(pem) assert publicKey1.point.x == publicKey2.point.x assert publicKey1.point.y == publicKey2.point.y assert publicKey1.curve.name == publicKey2.curve.name end test "der conversion" do privateKey = PrivateKey.generate() publicKey1 = PrivateKey.getPublicKey(privateKey) der = PublicKey.toDer(publicKey1) {:ok, publicKey2} = PublicKey.fromDer(der) assert publicKey1.point.x == publicKey2.point.x assert publicKey1.point.y == publicKey2.point.y assert publicKey1.curve.name == publicKey2.curve.name end test "string conversion" do privateKey = PrivateKey.generate() publicKey1 = PrivateKey.getPublicKey(privateKey) string = PublicKey.toString(publicKey1) {:ok, publicKey2} = PublicKey.fromString(string) assert publicKey1.point.x == publicKey2.point.x assert publicKey1.point.y == publicKey2.point.y assert publicKey1.curve.name == publicKey2.curve.name end end
27.533333
57
0.728006
0876aaff10e4fbe2dc89acd0470de1cb3701f218
3,609
exs
Elixir
test/mix/tasks/phx.new_test.exs
TheMushrr00m/phoenix
5f15107d6e102d5ceafc92b1ec1c397b601b9b66
[ "MIT" ]
null
null
null
test/mix/tasks/phx.new_test.exs
TheMushrr00m/phoenix
5f15107d6e102d5ceafc92b1ec1c397b601b9b66
[ "MIT" ]
null
null
null
test/mix/tasks/phx.new_test.exs
TheMushrr00m/phoenix
5f15107d6e102d5ceafc92b1ec1c397b601b9b66
[ "MIT" ]
null
null
null
for pattern <- ["../../../installer/lib/phx_new/project.ex", "../../../installer/lib/phx_new/generator.ex", "../../../installer/lib/phx_new/*.ex", "../../../installer/lib/mix/tasks/phx.new.ex", "../../../installer/test/mix_helper.exs"], file <- [_|_] = Path.wildcard(Path.expand(pattern, __DIR__)), do: Code.require_file(file, __DIR__) # Define a fake live reload socket. defmodule Phoenix.LiveReloader.Socket do def child_spec(_) do Supervisor.Spec.worker(Task, [fn -> :ok end], restart: :temporary) end end # Here we test the installer is up to date. defmodule Mix.Tasks.Phx.NewTest do use ExUnit.Case use RouterHelper import MixHelper import ExUnit.CaptureIO @moduletag :phx_new @epoch {{1970, 1, 1}, {0, 0, 0}} setup do # The shell asks to install npm and mix deps. # We will politely say not. send self(), {:mix_shell_input, :yes?, false} send self(), {:mix_shell_input, :yes?, false} :ok end test "bootstraps generated project" do Logger.disable(self()) Application.put_env(:phx_blog, PhxBlogWeb.Endpoint, secret_key_base: String.duplicate("abcdefgh", 8), code_reloader: true) root = File.cwd! in_tmp "bootstrap", fn -> project_path = Path.join(File.cwd!(), "phx_blog") try do Mix.Tasks.Phx.New.run(["phx_blog", "--no-webpack", "--no-ecto"]) in_project :phx_blog, project_path, fn _ -> Mix.Task.clear() Mix.Task.run "compile", ["--no-deps-check"] assert_received {:mix_shell, :info, ["Generated phx_blog app"]} refute_received {:mix_shell, :info, ["Generated phoenix app"]} Mix.shell.flush() # Adding a new template touches file (through mix) File.touch! "lib/phx_blog_web/views/layout_view.ex", @epoch File.write! "lib/phx_blog_web/templates/layout/another.html.eex", "oops" Mix.Task.clear() Mix.Task.run "compile", ["--no-deps-check"] assert File.stat!("lib/phx_blog_web/views/layout_view.ex").mtime > @epoch # Adding a new template triggers recompilation (through request) File.touch! "lib/phx_blog_web/views/page_view.ex", @epoch File.write! "lib/phx_blog_web/templates/page/another.html.eex", "oops" {:ok, _} = Application.ensure_all_started(:phx_blog) PhxBlogWeb.Endpoint.call(conn(:get, "/"), []) assert File.stat!("lib/phx_blog_web/views/page_view.ex").mtime > @epoch # Ensure /priv static files are copied assert File.exists?("priv/static/js/phoenix.js") # We can run tests too, starting the app. assert capture_io(fn -> capture_io(:user, fn -> Mix.Task.run("test", ["--no-start", "--no-compile"]) end) end) =~ ~r"3 tests, 0 failures" if Version.match?(System.version(), ">= 1.6.0") do File.mkdir_p!("deps/phoenix") File.cp_r!(Path.join(root, ".formatter.exs"), "deps/phoenix/.formatter.exs") Mix.Task.run("format", ["--check-formatted"]) end end after Code.delete_path Path.join(project_path, "_build/test/consolidated") Code.delete_path Path.join(project_path, "_build/test/lib/phx_blog/ebin") end end end test "assets are in sync with installer" do for file <- ~w(favicon.ico phoenix.js phoenix.png) do assert File.read!("priv/static/#{file}") == File.read!("installer/templates/phx_static/#{file}") end end end
35.382353
88
0.607648
0876d8a4cb28cd608f65cd74ff7c6b87d3373338
3,512
ex
Elixir
lib/changelog_web/controllers/page_controller.ex
snyk-omar/changelog.com
66a8cff17ed8a237e439976aa7fb96b58ef276a3
[ "MIT" ]
2,599
2016-10-25T15:02:53.000Z
2022-03-26T02:34:42.000Z
lib/changelog_web/controllers/page_controller.ex
snyk-omar/changelog.com
66a8cff17ed8a237e439976aa7fb96b58ef276a3
[ "MIT" ]
253
2016-10-25T20:29:24.000Z
2022-03-29T21:52:36.000Z
lib/changelog_web/controllers/page_controller.ex
snyk-omar/changelog.com
66a8cff17ed8a237e439976aa7fb96b58ef276a3
[ "MIT" ]
298
2016-10-25T15:18:31.000Z
2022-01-18T21:25:52.000Z
defmodule ChangelogWeb.PageController do use ChangelogWeb, :controller alias Changelog.{Cache, Episode, Newsletters, NewsSponsorship, Podcast} alias ChangelogWeb.TimeView alias ChangelogWeb.Plug.ResponseCache plug RequireGuest, "before joining" when action in [:join] plug ResponseCache # pages that need special treatment get their own matched function # all others simply render the template of the same name def action(conn, _) do case action_name(conn) do :guest -> guest(conn, Map.get(conn.params, "slug")) :home -> home(conn, conn.params) :sponsor -> sponsor(conn, conn.params) :sponsor_pricing -> sponsor_pricing(conn, conn.params) :sponsor_story -> sponsor_story(conn, Map.get(conn.params, "slug")) :weekly -> weekly(conn, conn.params) :weekly_archive -> weekly_archive(conn, conn.params) :++ -> plusplus(conn, conn.params) :plusplus -> plusplus(conn, conn.params) name -> render(conn, name) end end def guest(conn, slug) when is_nil(slug), do: guest(conn, "podcast") def guest(conn, slug) do active = Podcast.active() |> Podcast.oldest_first() |> Repo.all() podcast = Podcast.get_by_slug!(slug) episode = Podcast.get_episodes(podcast) |> Episode.published() |> Episode.newest_first() |> Episode.limit(1) |> Repo.one() |> Episode.preload_podcast() conn |> assign(:active, active) |> assign(:podcast, podcast) |> assign(:episode, episode) |> ResponseCache.cache_public() |> render(:guest) end def home(conn, _params) do featured = Episode.published() |> Episode.featured() |> Episode.newest_first() |> Episode.limit(5) |> Repo.all() |> Episode.preload_podcast() |> Episode.preload_sponsors() render(conn, :home, featured: featured) end def sponsor(conn, _params) do weekly = Newsletters.weekly() |> Newsletters.get_stats() examples = Changelog.SponsorStory.examples() ads = NewsSponsorship.get_ads_for_index() render(conn, :sponsor, weekly: weekly, examples: examples, ads: ads) end def sponsor_pricing(conn, _params) do weekly = Newsletters.weekly() |> Newsletters.get_stats() weeks = Timex.today() |> TimeView.closest_monday_to() |> TimeView.weeks(12) render(conn, :sponsor_pricing, weekly: weekly, weeks: weeks) end def sponsor_story(conn, slug) do story = Changelog.SponsorStory.get_by_slug(slug) render(conn, :sponsor_story, story: story) end def weekly(conn, _params) do latest = get_weekly_issues() |> List.first() conn |> assign(:latest, latest) |> ResponseCache.cache_public(:timer.hours(1)) |> render(:weekly) end def plusplus(conn, _params) do redirect(conn, external: "https://changelog.supercast.tech") end def weekly_archive(conn, _params) do issues_by_year = get_weekly_issues() |> Enum.group_by(fn c -> String.slice(c["SentDate"], 0..3) end) |> Enum.reverse() conn |> assign(:issues, issues_by_year) |> ResponseCache.cache_public(:timer.hours(1)) |> render(:weekly_archive) end defp get_weekly_issues do Cache.get_or_store("weekly_archive", :timer.hours(24), fn -> Craisin.Client.campaigns("e8870c50d493e5cc72c78ffec0c5b86f") |> Enum.filter(fn c -> String.starts_with?(c["Name"], "Weekly") end) |> Enum.filter(fn c -> String.match?(c["Name"], ~r/Issue \#\d+\z/) end) end) end end
29.762712
79
0.660308
0876e35c7aaa311627648bdf65c385a9e02f5679
3,341
ex
Elixir
lib/warpath/element.ex
Cleidiano/warpath
b566c7aa65dc5ad1063f0d2e878d9878e7e8ae38
[ "MIT" ]
16
2020-04-28T12:39:27.000Z
2021-12-21T16:50:58.000Z
lib/warpath/element.ex
cleidiano/warpath
216a0e3c1bf72460daec7e5a75d0c45f3d0ae3af
[ "MIT" ]
41
2020-02-01T18:10:50.000Z
2022-01-18T08:11:22.000Z
lib/warpath/element.ex
cleidiano/warpath
216a0e3c1bf72460daec7e5a75d0c45f3d0ae3af
[ "MIT" ]
3
2020-04-27T12:53:57.000Z
2020-10-02T18:33:32.000Z
defmodule Warpath.Element do @moduledoc false alias __MODULE__ alias Warpath.Element.Path @type t :: %Element{value: any, path: Path.acc()} @type path_accumulator :: (Path.token(), Path.acc() -> Path.acc()) defstruct value: nil, path: nil @doc """ Create a new element struct. ## Example iex> Warpath.Element.new("Warpath", [{:root, "$"}]) %Warpath.Element{value: "Warpath", path: [{:root, "$"}]} """ @spec new(any, Path.acc()) :: Element.t() def new(value, path) when is_list(path) do %Element{value: value, path: path} end @doc """ Create element for each item. ## Example #List iex> Warpath.Element.elementify([:a, :b], []) [ %Warpath.Element{value: :a, path: [{:index_access, 0}]}, %Warpath.Element{value: :b, path: [{:index_access, 1}]} ] #List iex> Warpath.Element.elementify(%{name: "Warpath", category: "Autobots"}, []) [ %Warpath.Element{value: "Autobots", path: [{:property, :category }]}, %Warpath.Element{value: "Warpath", path: [{:property, :name }]} ] """ @spec elementify(map() | struct() | list(), Path.acc(), path_accumulator) :: [Element.t()] def elementify(enum, relative_path, path_fun \\ &Path.accumulate/2) def elementify(list, relative_path, path_fun) when is_list(list) do list |> Stream.with_index() |> Enum.map(fn {item, index} -> Element.new(item, path_fun.({:index_access, index}, relative_path)) end) end def elementify(%_{} = struct, relative_path, path_fun) do struct |> Map.from_struct() |> elementify(relative_path, path_fun) end def elementify(map, relative_path, path_fun) when is_map(map) do Enum.map( map, fn {k, v} -> key_path = path_fun.({:property, k}, relative_path) Element.new(v, key_path) end ) end @doc """ Extract the path of given element ## Example iex> path = [{:root, "$"}] ...> element = Warpath.Element.new("Warpath", path) ...> Warpath.Element.path(element) [{:root, "$"}] """ @spec path(t) :: Path.acc() def path(%Element{path: path}), do: path @doc """ Extract the value of given element ## Example iex> element = Warpath.Element.new("Warpath", [{:root, "$"}]) ...> Warpath.Element.value(element) "Warpath" """ @spec value(t) :: any() def value(%Element{value: value}), do: value @doc """ Verify if element value is a list. ## Example iex> element = Warpath.Element.new([], [{:root, "$"}]) ...> Warpath.Element.value_list?(element) true iex> element = Warpath.Element.new(:atom, [{:root, "$"}]) ...> Warpath.Element.value_list?(element) false """ @spec value_list?(t) :: boolean() def value_list?(%Element{value: value}), do: is_list(value) @doc """ Verify if the element value is a map. ## Example iex> element = Warpath.Element.new(%{}, [{:root, "$"}]) ...> Warpath.Element.value_map?(element) true iex> element = Warpath.Element.new("String", [{:root, "$"}]) ...> Warpath.Element.value_map?(element) false """ @spec value_map?(t) :: boolean() def value_map?(%Element{value: value}), do: is_map(value) end
27.162602
92
0.577073
087710170f7185749263ecc5cd3f6475022f6b62
1,251
ex
Elixir
clients/cloud_build/lib/google_api/cloud_build/v1/model/retry_build_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_build/lib/google_api/cloud_build/v1/model/retry_build_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_build/lib/google_api/cloud_build/v1/model/retry_build_request.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.CloudBuild.V1.Model.RetryBuildRequest do @moduledoc """ Specifies a build to retry. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.CloudBuild.V1.Model.RetryBuildRequest do def decode(value, options) do GoogleApi.CloudBuild.V1.Model.RetryBuildRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudBuild.V1.Model.RetryBuildRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
29.785714
79
0.760991
08772390b0595a19318f3b6debfa0bdd434fd9d0
1,673
exs
Elixir
test/board_test.exs
tpetersen0308/tic_tac_toe
db7dbf77eadc6a9a98f10f3a4c0f27deae5d559f
[ "MIT" ]
null
null
null
test/board_test.exs
tpetersen0308/tic_tac_toe
db7dbf77eadc6a9a98f10f3a4c0f27deae5d559f
[ "MIT" ]
null
null
null
test/board_test.exs
tpetersen0308/tic_tac_toe
db7dbf77eadc6a9a98f10f3a4c0f27deae5d559f
[ "MIT" ]
null
null
null
defmodule TicTacToe.BoardTest do use ExUnit.Case doctest TicTacToe.Board import TicTacToe.Board @empty_board empty() @full_board %{ 1 => "X", 2 => "O", 3 => "X", 4 => "O", 5 => "X", 6 => "O", 7 => "O", 8 => "X", 9 => "O"} test "it can create an empty board" do assert %{ 1 => nil, 2 => nil, 3 => nil, 4 => nil, 5 => nil, 6 => nil, 7 => nil, 8 => nil, 9 => nil } == empty() end test "it can create an empty board of an arbitrary size given a row length" do assert %{ 1 => nil, 2 => nil, 3 => nil, 4 => nil, 5 => nil, 6 => nil, 7 => nil, 8 => nil, 9 => nil, 10 => nil, 11 => nil, 12 => nil, 13 => nil, 14 => nil, 15 => nil, 16 => nil } == empty(4) end test "it can update the board" do board = @empty_board assert %{ 1 => nil, 2 => nil, 3 => nil, 4 => nil, 5 => "X", 6 => nil, 7 => nil, 8 => nil, 9 => nil } == update(board, 5, "X") end describe "Board.is_full" do test "it returns true for a full board" do board = @full_board assert is_full(board) end test "it returns false for a board that has at least one available position" do board = @full_board board = Map.put(board, 6, nil) assert !is_full(board) end end test "it can return the number of turns played so far" do board = @empty_board board = update(board, 5, "X") |> update(8, "O") |> update(2, "X") assert 3 == turn_count(board) end test "it can return the available positions" do board = %{1 => "X", 2 => "O", 3 => nil, 4 => "X", 5 => nil, 6 => nil, 7 => "O", 8 => nil, 9 => "X" } expected_result = [3, 5, 6, 8] assert available_positions(board) == expected_result end end
32.803922
193
0.54991
08772c855ac85138cbfd709e7815c2a67bbc5ff2
3,818
exs
Elixir
test/registry_test.exs
diodechain/diode_server
1692788bd92cc17654965878abd059d13b5e236c
[ "Apache-2.0" ]
8
2021-03-12T15:35:09.000Z
2022-03-06T06:37:49.000Z
test/registry_test.exs
diodechain/diode_server_ex
5cf47e5253a0caafd335d0af4dba711d4dcad42d
[ "Apache-2.0" ]
15
2019-09-06T07:58:01.000Z
2021-03-06T17:04:46.000Z
test/registry_test.exs
diodechain/diode_server
1692788bd92cc17654965878abd059d13b5e236c
[ "Apache-2.0" ]
5
2021-10-01T12:52:28.000Z
2022-02-02T19:29:56.000Z
# Diode Server # Copyright 2021 Diode # Licensed under the Diode License, Version 1.1 defmodule RegistryTest do alias Object.Ticket import Ticket alias Contract.{Fleet, Registry} use ExUnit.Case, async: false import Edge2Client import While setup_all do Chain.reset_state() while Chain.peak() < Chain.epoch_length() do Chain.Worker.work() end :ok end test "future ticket" do tck = ticket( server_id: Wallet.address!(Diode.miner()), total_connections: 1, total_bytes: 0, local_address: "spam", block_number: Chain.peak() + Chain.epoch_length(), fleet_contract: <<0::unsigned-size(160)>>, device_signature: Secp256k1.sign(clientkey(1), Hash.sha3_256("random")) ) raw = Ticket.raw(tck) tx = Registry.submit_ticket_raw_tx(raw) ret = Shell.call_tx(tx, "latest") {{:evmc_revert, "Ticket from the future?"}, _} = ret # if you get a {{:evmc_revert, ""}, 85703} here it means for some reason the transaction # passed the initial test but failed on fleet_contract == 0 end test "zero ticket" do tck = ticket( server_id: Wallet.address!(Diode.miner()), total_connections: 1, total_bytes: 0, local_address: "spam", block_number: Chain.peak() - Chain.epoch_length(), fleet_contract: <<0::unsigned-size(160)>> ) |> Ticket.device_sign(clientkey(1)) raw = Ticket.raw(tck) tx = Registry.submit_ticket_raw_tx(raw) {{:evmc_revert, ""}, _} = Shell.call_tx(tx, "latest") end test "unregistered device" do # Ensuring queue is empty Chain.Worker.work() # Creating new tx op = ac = Wallet.address!(Diode.miner()) fleet_tx = Fleet.deploy_new(op, ac) Chain.Pool.add_transaction(fleet_tx) Chain.Worker.work() fleet = Chain.Transaction.new_contract_address(fleet_tx) IO.puts("fleet: #{Base16.encode(fleet)}") client = clientid(1) assert Fleet.operator(fleet) == op assert Fleet.accountant(fleet) == ac assert Fleet.device_allowlisted?(fleet, client) == false tck = ticket( server_id: Wallet.address!(Diode.miner()), total_connections: 1, total_bytes: 0, local_address: "spam", block_number: Chain.peak() - Chain.epoch_length(), fleet_contract: fleet ) |> Ticket.device_sign(clientkey(1)) raw = Ticket.raw(tck) tx = Registry.submit_ticket_raw_tx(raw) error = "Unregistered device (#{Base16.encode(Wallet.address!(client))})" {{:evmc_revert, ^error}, _} = Shell.call_tx(tx, "latest") # Now registering device tx = Fleet.set_device_allowlist(fleet, client, true) Chain.Pool.add_transaction(tx) Chain.Worker.work() assert Fleet.device_allowlisted?(fleet, client) == true tck = ticket( server_id: Wallet.address!(Diode.miner()), total_connections: 1, total_bytes: 0, local_address: "spam", block_number: Chain.peak() - Chain.epoch_length(), fleet_contract: fleet ) |> Ticket.device_sign(clientkey(1)) raw = Ticket.raw(tck) tx = Registry.submit_ticket_raw_tx(raw) {"", _gas_cost} = Shell.call_tx(tx, "latest") end test "registered device (dev_contract)" do assert Fleet.device_allowlisted?(clientid(1)) == true tck = ticket( server_id: Wallet.address!(Diode.miner()), total_connections: 1, total_bytes: 0, local_address: "spam", block_number: Chain.peak() - Chain.epoch_length(), fleet_contract: Diode.fleet_address() ) |> Ticket.device_sign(clientkey(1)) raw = Ticket.raw(tck) tx = Registry.submit_ticket_raw_tx(raw) {"", _gas_cost} = Shell.call_tx(tx, "latest") end end
28.073529
93
0.635411
0877ba3b187d641109b45767747f5f2ed4df99a5
453
ex
Elixir
lib/blue_jet/core/service/helper.ex
freshcom/freshcom-api
4f2083277943cf4e4e8fd4c4d443c7309f285ad7
[ "BSD-3-Clause" ]
44
2018-05-09T01:08:57.000Z
2021-01-19T07:25:26.000Z
lib/blue_jet/core/service/helper.ex
freshcom/freshcom-api
4f2083277943cf4e4e8fd4c4d443c7309f285ad7
[ "BSD-3-Clause" ]
36
2018-05-08T23:59:54.000Z
2018-09-28T13:50:30.000Z
lib/blue_jet/core/service/helper.ex
freshcom/freshcom-api
4f2083277943cf4e4e8fd4c4d443c7309f285ad7
[ "BSD-3-Clause" ]
9
2018-05-09T14:09:19.000Z
2021-03-21T21:04:04.000Z
defmodule BlueJet.Service.Helper do def extract_filter(fields) do fields[:filter] || %{} end def extract_nil_filter(map) do Enum.reduce(map, %{}, fn({k, v}, acc) -> if is_nil(v) do Map.put(acc, k, v) else acc end end) end def extract_clauses(map) do Enum.reduce(map, %{}, fn({k, v}, acc) -> if is_nil(v) do acc else Map.put(acc, k, v) end end) end end
18.12
44
0.527594
0877bfcb7f2ed45d975c5355b457ba82f9379f35
637
ex
Elixir
lib/nets_easy/model/get_order_response/order_details.ex
hooplab/nets-easy-elixir
5d60a31ef36bb1518d7a3768851d09b258f62411
[ "MIT" ]
null
null
null
lib/nets_easy/model/get_order_response/order_details.ex
hooplab/nets-easy-elixir
5d60a31ef36bb1518d7a3768851d09b258f62411
[ "MIT" ]
null
null
null
lib/nets_easy/model/get_order_response/order_details.ex
hooplab/nets-easy-elixir
5d60a31ef36bb1518d7a3768851d09b258f62411
[ "MIT" ]
null
null
null
defmodule NetsEasy.Model.GetOrderResponse.OrderDetails do @moduledoc """ """ @typedoc """ .order_details """ @type t :: %__MODULE__{ amount: String.t(), currency: String.t(), reference: String.t() } @derive Poison.Encoder defstruct [ :amount, :currency, :reference ] @doc false def shell(), do: %__MODULE__{} end defimpl Poison.Decoder, for: NetsEasy.Model.CreatePaymentRequest.OrderDetails do def decode(%{currency: currency} = order_details, _) do %{ order_details | currency: NetsEasy.Model.Currency.from_string(currency) } end end
18.735294
63
0.627943
0877cddb7f3ad8ab9d95adf44dc92eef5c2ecc27
239
exs
Elixir
year_2020/test/day_09_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2020/test/day_09_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2020/test/day_09_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
defmodule Day09Test do use ExUnit.Case test "it finds the weakness" do assert Day09.part_one(InputTestFile, 5) == 127 end test "it finds the encryption weakness" do assert Day09.part_two(InputTestFile, 5) == 62 end end
19.916667
50
0.715481
0878041db7641671f053521952438283bde8ec5e
4,622
ex
Elixir
apps/tai/lib/tai/trading/order_store.ex
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
1
2019-12-19T05:16:26.000Z
2019-12-19T05:16:26.000Z
apps/tai/lib/tai/trading/order_store.ex
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
null
null
null
apps/tai/lib/tai/trading/order_store.ex
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
1
2020-05-03T23:32:11.000Z
2020-05-03T23:32:11.000Z
defmodule Tai.Trading.OrderStore do @moduledoc """ Track and manage the local state of orders with a swappable backend """ use GenServer alias Tai.Trading.{Order, OrderSubmissions, OrderStore} @type submission :: OrderSubmissions.Factory.submission() @type order :: Order.t() @type status :: Order.status() @type client_id :: Order.client_id() @type action :: OrderStore.Action.t() @type store_id :: atom @default_id :default @default_backend Tai.Trading.OrderStore.Backends.ETS defmodule State do @type t :: %State{id: atom, name: atom, backend: module} defstruct ~w(id name backend)a end def start_link(args) do id = Keyword.get(args, :id, @default_id) backend = Keyword.get(args, :backend, @default_backend) name = :"#{__MODULE__}_#{id}" state = %State{id: id, name: name, backend: backend} GenServer.start_link(__MODULE__, state, name: name) end def init(state), do: {:ok, state, {:continue, :init}} def handle_continue(:init, state) do :ok = state.backend.create(state.name) {:noreply, state} end def handle_call({:enqueue, submission}, _from, state) do order = OrderSubmissions.Factory.build!(submission) response = state.backend.insert(order, state.name) {:reply, response, state} end def handle_call({:update, action}, _from, state) do response = with {:ok, old_order} <- state.backend.find_by_client_id(action.client_id, state.name) do required = action |> OrderStore.Action.required() |> List.wrap() if Enum.member?(required, old_order.status) do new_attrs = action |> OrderStore.Action.attrs() |> normalize_attrs(old_order, action) |> Map.put(:updated_at, Timex.now()) updated_order = old_order |> Map.merge(new_attrs) state.backend.update(updated_order, state.name) {:ok, {old_order, updated_order}} else reason = {:invalid_status, old_order.status, required |> format_required, action} {:error, reason} end else {:error, :not_found} -> {:error, {:not_found, action}} end {:reply, response, state} end def handle_call(:all, _from, state) do response = state.backend.all(state.name) {:reply, response, state} end def handle_call({:find_by_client_id, client_id}, _from, state) do response = state.backend.find_by_client_id(client_id, state.name) {:reply, response, state} end @doc """ Enqueue an order from the submission by adding it into the backend """ @spec enqueue(submission) :: {:ok, order} | no_return def enqueue(submission, store_id \\ @default_id) do store_id |> to_name |> GenServer.call({:enqueue, submission}) end @doc """ Update the state of the order from the actions params """ @spec update(action) :: {:ok, {old :: order, updated :: order}} | {:error, {:not_found, action} | {:invalid_status, current :: status, required :: [status], action}} def update(action, store_id \\ @default_id) do store_id |> to_name |> GenServer.call({:update, action}) end @doc """ Return a list of all orders currently stored in the backend """ @spec all :: [] | [order] def all(store_id \\ @default_id) do store_id |> to_name |> GenServer.call(:all) end @doc """ Return the number of orders currently stored in the backend """ @spec count :: non_neg_integer def count(store_id \\ @default_id), do: store_id |> all() |> Enum.count() @doc """ Return the order from the backend that matches the given client_id """ @spec find_by_client_id(client_id) :: {:ok, order} | {:error, :not_found} def find_by_client_id(client_id, store_id \\ @default_id) do store_id |> to_name |> GenServer.call({:find_by_client_id, client_id}) end @spec to_name(store_id) :: atom def to_name(store_id), do: :"#{__MODULE__}_#{store_id}" defp normalize_attrs( update_attrs, %Order{cumulative_qty: cumulative_qty}, %OrderStore.Actions.Amend{leaves_qty: leaves_qty} ) do qty = Decimal.add(cumulative_qty, leaves_qty) update_attrs |> Map.put(:qty, qty) end defp normalize_attrs( update_attrs, %Order{cumulative_qty: cumulative_qty}, %OrderStore.Actions.Cancel{} ) do update_attrs |> Map.put(:qty, cumulative_qty) end defp normalize_attrs(update_attrs, _, _), do: update_attrs defp format_required([required | []]), do: required defp format_required(required), do: required end
29.628205
95
0.64907
087829c278bb08db64fdea4a4aa860ba17add8e2
1,609
exs
Elixir
test/get_inputs_test.exs
danielburnley/Advent-Of-Code-1
84038e91cc9561755db0d5973ed6af27b50f9dd3
[ "MIT" ]
null
null
null
test/get_inputs_test.exs
danielburnley/Advent-Of-Code-1
84038e91cc9561755db0d5973ed6af27b50f9dd3
[ "MIT" ]
null
null
null
test/get_inputs_test.exs
danielburnley/Advent-Of-Code-1
84038e91cc9561755db0d5973ed6af27b50f9dd3
[ "MIT" ]
null
null
null
defmodule AdventOfCodeHelper.GetInputsTest do alias AdventOfCodeHelper.GetInputs use ExUnit.Case, async: true use ExVCR.Mock setup_all _context do cache_dir = Application.get_env(:advent_of_code_helper, :cache_dir) File.mkdir(cache_dir) File.write(Path.join(cache_dir,"input_2016_2"), "test_post_pls_ignore", []) on_exit fn -> File.rm_rf(cache_dir) end {:ok, [id: Application.get_env(:advent_of_code_helper, :session), content_length: 7000, cached_content: "test_post_pls_ignore", cache_dir: cache_dir]} end setup_all do ExVCR.Config.cassette_library_dir("test/fixture/vcr_cassettes") ExVCR.Config.filter_request_headers("session") :ok end test "does it run", context do use_cassette("whole_chain") do {:ok, body} = GetInputs.get_value(2015,1,context[:id]) assert String.length(body) == context[:content_length] end end test "cache hit should bypass http", context do use_cassette("makerequest_alreadycached") do {:ok, contents} = GetInputs.get_value(2016,2,context[:id]) assert contents == context[:cached_content] end end test "non-cached result should be stored after get", context do use_cassette("non-cached_request") do {:ok, _contents} = GetInputs.get_value(2015,1,context[:id]) assert File.exists?("#{Path.join(context[:cache_dir],"input_2015_1")}") end end test "incorrect day should return error", context do use_cassette("should_404") do {:fail, msg} = GetInputs.get_value(2012,5,context[:id]) assert msg == "404 Not Found\n" end end end
30.358491
154
0.704786
08783d089afe693cbd0e87645c6e88ff4adf3da9
1,487
ex
Elixir
lib/landing_page_web/views/error_helpers.ex
paulfioravanti/phoenix-and-elm-landing-page
8453cf0209bca8da46248d78a17092982e5a7e62
[ "MIT" ]
null
null
null
lib/landing_page_web/views/error_helpers.ex
paulfioravanti/phoenix-and-elm-landing-page
8453cf0209bca8da46248d78a17092982e5a7e62
[ "MIT" ]
null
null
null
lib/landing_page_web/views/error_helpers.ex
paulfioravanti/phoenix-and-elm-landing-page
8453cf0209bca8da46248d78a17092982e5a7e62
[ "MIT" ]
null
null
null
defmodule LandingPageWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "help-block") end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext "errors", "is invalid" # # # Translate the number of files with plural rules # dngettext "errors", "1 file", "%{count} files", count # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(LandingPageWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(LandingPageWeb.Gettext, "errors", msg, opts) end end end
33.044444
80
0.67384
08784c5acbefdd9d22bc82ad2f3e2e4d60101346
520
ex
Elixir
lib/triplex/plugs/subdomain_plug_config.ex
felipe-kosouski/triplex
daa68037217a17eedf9eef4c9e8ca88da4ad8870
[ "MIT" ]
null
null
null
lib/triplex/plugs/subdomain_plug_config.ex
felipe-kosouski/triplex
daa68037217a17eedf9eef4c9e8ca88da4ad8870
[ "MIT" ]
null
null
null
lib/triplex/plugs/subdomain_plug_config.ex
felipe-kosouski/triplex
daa68037217a17eedf9eef4c9e8ca88da4ad8870
[ "MIT" ]
null
null
null
defmodule Triplex.SubdomainPlugConfig do @moduledoc """ This is a struct that holds the configuration for `Triplex.SubdomainPlug`. Here are the config keys allowed: - `tenant_handler`: function to handle the tenant param. Its return will be used as the tenant. - `assign`: the name of the assign where we must save the tenant. - `endpoint`: the Phoenix.Endpoint to get the host name to dicover the subdomain. """ defstruct [ :endpoint, :tenant_handler, assign: :current_tenant ] end
26
76
0.717308
0878dc3d6001654eccc4528fd148b396e95eb7b3
24,976
exs
Elixir
lib/elixir/test/elixir/base_test.exs
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
1
2021-04-28T21:35:01.000Z
2021-04-28T21:35:01.000Z
lib/elixir/test/elixir/base_test.exs
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/base_test.exs
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
8
2018-02-20T18:30:53.000Z
2019-06-18T14:23:31.000Z
Code.require_file("test_helper.exs", __DIR__) defmodule BaseTest do use ExUnit.Case, async: true doctest Base import Base test "encode16/1" do assert "" == encode16("") assert "66" == encode16("f") assert "666F" == encode16("fo") assert "666F6F" == encode16("foo") assert "666F6F62" == encode16("foob") assert "666F6F6261" == encode16("fooba") assert "666F6F626172" == encode16("foobar") assert "A1B2C3D4E5F67891" == encode16(<<161, 178, 195, 212, 229, 246, 120, 145>>) assert "a1b2c3d4e5f67891" == encode16(<<161, 178, 195, 212, 229, 246, 120, 145>>, case: :lower) end test "decode16/1" do assert {:ok, ""} == decode16("") assert {:ok, "f"} == decode16("66") assert {:ok, "fo"} == decode16("666F") assert {:ok, "foo"} == decode16("666F6F") assert {:ok, "foob"} == decode16("666F6F62") assert {:ok, "fooba"} == decode16("666F6F6261") assert {:ok, "foobar"} == decode16("666F6F626172") assert {:ok, <<161, 178, 195, 212, 229, 246, 120, 145>>} == decode16("A1B2C3D4E5F67891") assert {:ok, <<161, 178, 195, 212, 229, 246, 120, 145>>} == decode16("a1b2c3d4e5f67891", case: :lower) assert {:ok, <<161, 178, 195, 212, 229, 246, 120, 145>>} == decode16("a1B2c3D4e5F67891", case: :mixed) end test "decode16!/1" do assert "" == decode16!("") assert "f" == decode16!("66") assert "fo" == decode16!("666F") assert "foo" == decode16!("666F6F") assert "foob" == decode16!("666F6F62") assert "fooba" == decode16!("666F6F6261") assert "foobar" == decode16!("666F6F626172") assert <<161, 178, 195, 212, 229, 246, 120, 145>> == decode16!("A1B2C3D4E5F67891") assert <<161, 178, 195, 212, 229, 246, 120, 145>> == decode16!("a1b2c3d4e5f67891", case: :lower) assert <<161, 178, 195, 212, 229, 246, 120, 145>> == decode16!("a1B2c3D4e5F67891", case: :mixed) end test "decode16/1 errors on non-alphabet digit" do assert :error == decode16("66KF") assert :error == decode16("66ff") assert :error == decode16("66FF", case: :lower) end test "decode16!/1 errors on non-alphabet digit" do assert_raise ArgumentError, "non-alphabet digit found: \"K\" (byte 75)", fn -> decode16!("66KF") end assert_raise ArgumentError, "non-alphabet digit found: \"f\" (byte 102)", fn -> decode16!("66ff") end assert_raise ArgumentError, "non-alphabet digit found: \"F\" (byte 70)", fn -> decode16!("66FF", case: :lower) end end test "decode16/1 errors on odd-length string" do assert :error == decode16("666") end test "decode16!/1 errors odd-length string" do assert_raise ArgumentError, "odd-length string", fn -> decode16!("666") end end test "encode64/1 can deal with empty strings" do assert "" == encode64("") end test "encode64/1 with two pads" do assert "QWxhZGRpbjpvcGVuIHNlc2FtZQ==" == encode64("Aladdin:open sesame") end test "encode64/1 with one pad" do assert "SGVsbG8gV29ybGQ=" == encode64("Hello World") end test "encode64/1 with no pad" do assert "QWxhZGRpbjpvcGVuIHNlc2Ft" == encode64("Aladdin:open sesam") assert "MDEyMzQ1Njc4OSFAIzBeJiooKTs6PD4sLiBbXXt9" == encode64(<<"0123456789!@#0^&*();:<>,. []{}">>) end test "encode64/1 with one pad and ignoring padding" do assert "SGVsbG8gV29ybGQ" == encode64("Hello World", padding: false) end test "encode64/1 with two pads and ignoring padding" do assert "QWxhZGRpbjpvcGVuIHNlc2FtZQ" == encode64("Aladdin:open sesame", padding: false) end test "encode64/1 with no pads and ignoring padding" do assert "QWxhZGRpbjpvcGVuIHNlc2Ft" == encode64("Aladdin:open sesam", padding: false) end test "decode64/1 can deal with empty strings" do assert {:ok, ""} == decode64("") end test "decode64!/1 can deal with empty strings" do assert "" == decode64!("") end test "decode64/1 with two pads" do assert {:ok, "Aladdin:open sesame"} == decode64("QWxhZGRpbjpvcGVuIHNlc2FtZQ==") end test "decode64!/1 with two pads" do assert "Aladdin:open sesame" == decode64!("QWxhZGRpbjpvcGVuIHNlc2FtZQ==") end test "decode64/1 with one pad" do assert {:ok, "Hello World"} == decode64("SGVsbG8gV29ybGQ=") end test "decode64!/1 with one pad" do assert "Hello World" == decode64!("SGVsbG8gV29ybGQ=") end test "decode64/1 with no pad" do assert {:ok, "Aladdin:open sesam"} == decode64("QWxhZGRpbjpvcGVuIHNlc2Ft") end test "decode64!/1 with no pad" do assert "Aladdin:open sesam" == decode64!("QWxhZGRpbjpvcGVuIHNlc2Ft") end test "decode64/1 errors on non-alphabet digit" do assert :error == decode64("Zm9)") end test "decode64!/1 errors on non-alphabet digit" do assert_raise ArgumentError, "non-alphabet digit found: \")\" (byte 41)", fn -> decode64!("Zm9)") end end test "decode64/1 errors on whitespace unless there's ignore: :whitespace" do assert :error == decode64("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t") assert {:ok, "Aladdin:open sesam"} == decode64("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t", ignore: :whitespace) end test "decode64!/1 errors on whitespace unless there's ignore: :whitespace" do assert_raise ArgumentError, "non-alphabet digit found: \"\\n\" (byte 10)", fn -> decode64!("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t") end assert "Aladdin:open sesam" == decode64!("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t", ignore: :whitespace) end test "decode64/1 errors on incorrect padding" do assert :error == decode64("SGVsbG8gV29ybGQ") end test "decode64!/1 errors on incorrect padding" do assert_raise ArgumentError, "incorrect padding", fn -> decode64!("SGVsbG8gV29ybGQ") end end test "decode64/2 with two pads and ignoring padding" do assert {:ok, "Aladdin:open sesame"} == decode64("QWxhZGRpbjpvcGVuIHNlc2FtZQ", padding: false) end test "decode64!/2 with two pads and ignoring padding" do assert "Aladdin:open sesame" == decode64!("QWxhZGRpbjpvcGVuIHNlc2FtZQ", padding: false) end test "decode64/2 with one pad and ignoring padding" do assert {:ok, "Hello World"} == decode64("SGVsbG8gV29ybGQ", padding: false) end test "decode64!/2 with one pad and ignoring padding" do assert "Hello World" == decode64!("SGVsbG8gV29ybGQ", padding: false) end test "decode64/2 with no pad and ignoring padding" do assert {:ok, "Aladdin:open sesam"} == decode64("QWxhZGRpbjpvcGVuIHNlc2Ft", padding: false) end test "decode64!/2 with no pad and ignoring padding" do assert "Aladdin:open sesam" == decode64!("QWxhZGRpbjpvcGVuIHNlc2Ft", padding: false) end test "decode64/2 with incorrect padding and ignoring padding" do assert {:ok, "Hello World"} == decode64("SGVsbG8gV29ybGQ", padding: false) end test "decode64!/2 with incorrect padding and ignoring padding" do assert "Hello World" == decode64!("SGVsbG8gV29ybGQ", padding: false) end test "url_encode64/1 can deal with empty strings" do assert "" == url_encode64("") end test "url_encode64/1 with two pads" do assert "QWxhZGRpbjpvcGVuIHNlc2FtZQ==" == url_encode64("Aladdin:open sesame") end test "url_encode64/1 with one pad" do assert "SGVsbG8gV29ybGQ=" == url_encode64("Hello World") end test "url_encode64/1 with no pad" do assert "QWxhZGRpbjpvcGVuIHNlc2Ft" == url_encode64("Aladdin:open sesam") assert "MDEyMzQ1Njc4OSFAIzBeJiooKTs6PD4sLiBbXXt9" == url_encode64(<<"0123456789!@#0^&*();:<>,. []{}">>) end test "url_encode64/2 with two pads and ignoring padding" do assert "QWxhZGRpbjpvcGVuIHNlc2FtZQ" == url_encode64("Aladdin:open sesame", padding: false) end test "url_encode64/2 with one pad and ignoring padding" do assert "SGVsbG8gV29ybGQ" == url_encode64("Hello World", padding: false) end test "url_encode64/2 with no pad and ignoring padding" do assert "QWxhZGRpbjpvcGVuIHNlc2Ft" == url_encode64("Aladdin:open sesam", padding: false) end test "url_encode64/1 doesn't produce URL-unsafe characters" do refute "/3/+/A==" == url_encode64(<<255, 127, 254, 252>>) assert "_3_-_A==" == url_encode64(<<255, 127, 254, 252>>) end test "url_decode64/1 can deal with empty strings" do assert {:ok, ""} == url_decode64("") end test "url_decode64!/1 can deal with empty strings" do assert "" == url_decode64!("") end test "url_decode64/1 with two pads" do assert {:ok, "Aladdin:open sesame"} == url_decode64("QWxhZGRpbjpvcGVuIHNlc2FtZQ==") end test "url_decode64!/1 with two pads" do assert "Aladdin:open sesame" == url_decode64!("QWxhZGRpbjpvcGVuIHNlc2FtZQ==") end test "url_decode64/1 with one pad" do assert {:ok, "Hello World"} == url_decode64("SGVsbG8gV29ybGQ=") end test "url_decode64!/1 with one pad" do assert "Hello World" == url_decode64!("SGVsbG8gV29ybGQ=") end test "url_decode64/1 with no pad" do assert {:ok, "Aladdin:open sesam"} == url_decode64("QWxhZGRpbjpvcGVuIHNlc2Ft") end test "url_decode64!/1 with no pad" do assert "Aladdin:open sesam" == url_decode64!("QWxhZGRpbjpvcGVuIHNlc2Ft") end test "url_decode64/1,2 error on whitespace unless there's ignore: :whitespace" do assert :error == url_decode64("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t") assert {:ok, "Aladdin:open sesam"} == url_decode64("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t", ignore: :whitespace) end test "url_decode64!/1,2 error on whitespace unless there's ignore: :whitespace" do assert_raise ArgumentError, "non-alphabet digit found: \"\\n\" (byte 10)", fn -> url_decode64!("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t") end assert "Aladdin:open sesam" == url_decode64!("\nQWxhZGRp bjpvcGVu\sIHNlc2Ft\t", ignore: :whitespace) end test "url_decode64/1 errors on non-alphabet digit" do assert :error == url_decode64("Zm9)") end test "url_decode64!/1 errors on non-alphabet digit" do assert_raise ArgumentError, "non-alphabet digit found: \")\" (byte 41)", fn -> url_decode64!("Zm9)") end end test "url_decode64/1 errors on incorrect padding" do assert :error == url_decode64("SGVsbG8gV29ybGQ") end test "url_decode64!/1 errors on incorrect padding" do assert_raise ArgumentError, "incorrect padding", fn -> url_decode64!("SGVsbG8gV29ybGQ") end end test "url_decode64/2 with two pads and ignoring padding" do assert {:ok, "Aladdin:open sesame"} == url_decode64("QWxhZGRpbjpvcGVuIHNlc2FtZQ", padding: false) end test "url_decode64!/2 with two pads and ignoring padding" do assert "Aladdin:open sesame" == url_decode64!("QWxhZGRpbjpvcGVuIHNlc2FtZQ", padding: false) end test "url_decode64/2 with one pad and ignoring padding" do assert {:ok, "Hello World"} == url_decode64("SGVsbG8gV29ybGQ", padding: false) end test "url_decode64!/2 with one pad and ignoring padding" do assert "Hello World" == url_decode64!("SGVsbG8gV29ybGQ", padding: false) end test "url_decode64/2 with no pad and ignoring padding" do assert {:ok, "Aladdin:open sesam"} == url_decode64("QWxhZGRpbjpvcGVuIHNlc2Ft", padding: false) end test "url_decode64!/2 with no pad and ignoring padding" do assert "Aladdin:open sesam" == url_decode64!("QWxhZGRpbjpvcGVuIHNlc2Ft", padding: false) end test "url_decode64/2 ignores incorrect padding when :padding is false" do assert {:ok, "Hello World"} == url_decode64("SGVsbG8gV29ybGQ", padding: false) end test "url_decode64!/2 ignores incorrect padding when :padding is false" do assert "Hello World" == url_decode64!("SGVsbG8gV29ybGQ", padding: false) end test "encode32/1 can deal with empty strings" do assert "" == encode32("") end test "encode32/1 with one pad" do assert "MZXW6YQ=" == encode32("foob") end test "encode32/1 with three pads" do assert "MZXW6===" == encode32("foo") end test "encode32/1 with four pads" do assert "MZXQ====" == encode32("fo") end test "encode32/1 with six pads" do assert "MZXW6YTBOI======" == encode32("foobar") assert "MY======" == encode32("f") end test "encode32/1 with no pads" do assert "MZXW6YTB" == encode32("fooba") end test "encode32/2 with one pad and ignoring padding" do assert "MZXW6YQ" == encode32("foob", padding: false) end test "encode32/2 with three pads and ignoring padding" do assert "MZXW6" == encode32("foo", padding: false) end test "encode32/2 with four pads and ignoring padding" do assert "MZXQ" == encode32("fo", padding: false) end test "encode32/2 with six pads and ignoring padding" do assert "MZXW6YTBOI" == encode32("foobar", padding: false) end test "encode32/2 with no pads and ignoring padding" do assert "MZXW6YTB" == encode32("fooba", padding: false) end test "encode32/2 with lowercase" do assert "mzxw6ytb" == encode32("fooba", case: :lower) end test "decode32/1 can deal with empty strings" do assert {:ok, ""} == decode32("") end test "decode32!/2 can deal with empty strings" do assert "" == decode32!("") end test "decode32/1 with one pad" do assert {:ok, "foob"} == decode32("MZXW6YQ=") end test "decode32!/1 with one pad" do assert "foob" == decode32!("MZXW6YQ=") end test "decode32/1 with three pads" do assert {:ok, "foo"} == decode32("MZXW6===") end test "decode32!/1 with three pads" do assert "foo" == decode32!("MZXW6===") end test "decode32/1 with four pads" do assert {:ok, "fo"} == decode32("MZXQ====") end test "decode32!/1 with four pads" do assert "fo" == decode32!("MZXQ====") end test "decode32/2 with lowercase" do assert {:ok, "fo"} == decode32("mzxq====", case: :lower) end test "decode32!/2 with lowercase" do assert "fo" == decode32!("mzxq====", case: :lower) end test "decode32/2 with mixed case" do assert {:ok, "fo"} == decode32("mZXq====", case: :mixed) end test "decode32!/2 with mixed case" do assert "fo" == decode32!("mZXq====", case: :mixed) end test "decode32/1 with six pads" do assert {:ok, "foobar"} == decode32("MZXW6YTBOI======") assert {:ok, "f"} == decode32("MY======") end test "decode32!/1 with six pads" do assert "foobar" == decode32!("MZXW6YTBOI======") assert "f" == decode32!("MY======") end test "decode32/1 with no pads" do assert {:ok, "fooba"} == decode32("MZXW6YTB") end test "decode32!/1 with no pads" do assert "fooba" == decode32!("MZXW6YTB") end test "decode32/1,2 error on non-alphabet digit" do assert :error == decode32("MZX)6YTB") assert :error == decode32("66ff") assert :error == decode32("66FF", case: :lower) end test "decode32!/1,2 error on non-alphabet digit" do assert_raise ArgumentError, "non-alphabet digit found: \")\" (byte 41)", fn -> decode32!("MZX)6YTB") end assert_raise ArgumentError, "non-alphabet digit found: \"m\" (byte 109)", fn -> decode32!("mzxw6ytboi======") end assert_raise ArgumentError, "non-alphabet digit found: \"M\" (byte 77)", fn -> decode32!("MZXW6YTBOI======", case: :lower) end end test "decode32/1 errors on incorrect padding" do assert :error == decode32("MZXW6YQ") end test "decode32!/1 errors on incorrect padding" do assert_raise ArgumentError, "incorrect padding", fn -> decode32!("MZXW6YQ") end end test "decode32/2 with one pad and :padding to false" do assert {:ok, "foob"} == decode32("MZXW6YQ", padding: false) end test "decode32!/2 with one pad and :padding to false" do assert "foob" == decode32!("MZXW6YQ", padding: false) end test "decode32/2 with three pads and ignoring padding" do assert {:ok, "foo"} == decode32("MZXW6", padding: false) end test "decode32!/2 with three pads and ignoring padding" do assert "foo" == decode32!("MZXW6", padding: false) end test "decode32/2 with four pads and ignoring padding" do assert {:ok, "fo"} == decode32("MZXQ", padding: false) end test "decode32!/2 with four pads and ignoring padding" do assert "fo" == decode32!("MZXQ", padding: false) end test "decode32/2 with :lower case and ignoring padding" do assert {:ok, "fo"} == decode32("mzxq", case: :lower, padding: false) end test "decode32!/2 with :lower case and ignoring padding" do assert "fo" == decode32!("mzxq", case: :lower, padding: false) end test "decode32/2 with :mixed case and ignoring padding" do assert {:ok, "fo"} == decode32("mZXq", case: :mixed, padding: false) end test "decode32!/2 with :mixed case and ignoring padding" do assert "fo" == decode32!("mZXq", case: :mixed, padding: false) end test "decode32/2 with six pads and ignoring padding" do assert {:ok, "foobar"} == decode32("MZXW6YTBOI", padding: false) end test "decode32!/2 with six pads and ignoring padding" do assert "foobar" == decode32!("MZXW6YTBOI", padding: false) end test "decode32/2 with no pads and ignoring padding" do assert {:ok, "fooba"} == decode32("MZXW6YTB", padding: false) end test "decode32!/2 with no pads and ignoring padding" do assert "fooba" == decode32!("MZXW6YTB", padding: false) end test "decode32/2 ignores incorrect padding when :padding is false" do assert {:ok, "foob"} == decode32("MZXW6YQ", padding: false) end test "decode32!/2 ignores incorrect padding when :padding is false" do "foob" = decode32!("MZXW6YQ", padding: false) end test "hex_encode32/1 can deal with empty strings" do assert "" == hex_encode32("") end test "hex_encode32/1 with one pad" do assert "CPNMUOG=" == hex_encode32("foob") end test "hex_encode32/1 with three pads" do assert "CPNMU===" == hex_encode32("foo") end test "hex_encode32/1 with four pads" do assert "CPNG====" == hex_encode32("fo") end test "hex_encode32/1 with six pads" do assert "CPNMUOJ1E8======" == hex_encode32("foobar") assert "CO======" == hex_encode32("f") end test "hex_encode32/1 with no pads" do assert "CPNMUOJ1" == hex_encode32("fooba") end test "hex_encode32/2 with one pad and ignoring padding" do assert "CPNMUOG" == hex_encode32("foob", padding: false) end test "hex_encode32/2 with three pads and ignoring padding" do assert "CPNMU" == hex_encode32("foo", padding: false) end test "hex_encode32/2 with four pads and ignoring padding" do assert "CPNG" == hex_encode32("fo", padding: false) end test "hex_encode32/2 with six pads and ignoring padding" do assert "CPNMUOJ1E8" == hex_encode32("foobar", padding: false) end test "hex_encode32/2 with no pads and ignoring padding" do assert "CPNMUOJ1" == hex_encode32("fooba", padding: false) end test "hex_encode32/2 with lowercase" do assert "cpnmuoj1" == hex_encode32("fooba", case: :lower) end test "hex_decode32/1 can deal with empty strings" do assert {:ok, ""} == hex_decode32("") end test "hex_decode32!/1 can deal with empty strings" do assert "" == hex_decode32!("") end test "hex_decode32/1 with one pad" do assert {:ok, "foob"} == hex_decode32("CPNMUOG=") end test "hex_decode32!/1 with one pad" do assert "foob" == hex_decode32!("CPNMUOG=") end test "hex_decode32/1 with three pads" do assert {:ok, "foo"} == hex_decode32("CPNMU===") end test "hex_decode32!/1 with three pads" do assert "foo" == hex_decode32!("CPNMU===") end test "hex_decode32/1 with four pads" do assert {:ok, "fo"} == hex_decode32("CPNG====") end test "hex_decode32!/1 with four pads" do assert "fo" == hex_decode32!("CPNG====") end test "hex_decode32/1 with six pads" do assert {:ok, "foobar"} == hex_decode32("CPNMUOJ1E8======") assert {:ok, "f"} == hex_decode32("CO======") end test "hex_decode32!/1 with six pads" do assert "foobar" == hex_decode32!("CPNMUOJ1E8======") assert "f" == hex_decode32!("CO======") end test "hex_decode32/1 with no pads" do assert {:ok, "fooba"} == hex_decode32("CPNMUOJ1") end test "hex_decode32!/1 with no pads" do assert "fooba" == hex_decode32!("CPNMUOJ1") end test "hex_decode32/1,2 error on non-alphabet digit" do assert :error == hex_decode32("CPN)UOJ1") assert :error == hex_decode32("66f") assert :error == hex_decode32("66F", case: :lower) end test "hex_decode32!/1,2 error non-alphabet digit" do assert_raise ArgumentError, "non-alphabet digit found: \")\" (byte 41)", fn -> hex_decode32!("CPN)UOJ1") end assert_raise ArgumentError, "non-alphabet digit found: \"c\" (byte 99)", fn -> hex_decode32!("cpnmuoj1e8======") end assert_raise ArgumentError, "non-alphabet digit found: \"C\" (byte 67)", fn -> hex_decode32!("CPNMUOJ1E8======", case: :lower) end end test "hex_decode32/1 errors on incorrect padding" do assert :error == hex_decode32("CPNMUOG") end test "hex_decode32!/1 errors on incorrect padding" do assert_raise ArgumentError, "incorrect padding", fn -> hex_decode32!("CPNMUOG") end end test "hex_decode32/2 with lowercase" do assert {:ok, "fo"} == hex_decode32("cpng====", case: :lower) end test "hex_decode32!/2 with lowercase" do assert "fo" == hex_decode32!("cpng====", case: :lower) end test "hex_decode32/2 with mixed case" do assert {:ok, "fo"} == hex_decode32("cPNg====", case: :mixed) end test "hex_decode32!/2 with mixed case" do assert "fo" == hex_decode32!("cPNg====", case: :mixed) end test "decode16!/1 errors on non-UTF-8 char" do assert_raise ArgumentError, "non-alphabet digit found: \"\\0\" (byte 0)", fn -> decode16!("012" <> <<0>>) end end test "hex_decode32/2 with one pad and ignoring padding" do assert {:ok, "foob"} == hex_decode32("CPNMUOG", padding: false) end test "hex_decode32!/2 with one pad and ignoring padding" do assert "foob" == hex_decode32!("CPNMUOG", padding: false) end test "hex_decode32/2 with three pads and ignoring padding" do assert {:ok, "foo"} == hex_decode32("CPNMU", padding: false) end test "hex_decode32!/2 with three pads and ignoring padding" do assert "foo" == hex_decode32!("CPNMU", padding: false) end test "hex_decode32/2 with four pads and ignoring padding" do assert {:ok, "fo"} == hex_decode32("CPNG", padding: false) end test "hex_decode32!/2 with four pads and ignoring padding" do assert "fo" == hex_decode32!("CPNG", padding: false) end test "hex_decode32/2 with six pads and ignoring padding" do assert {:ok, "foobar"} == hex_decode32("CPNMUOJ1E8", padding: false) end test "hex_decode32!/2 with six pads and ignoring padding" do assert "foobar" == hex_decode32!("CPNMUOJ1E8", padding: false) end test "hex_decode32/2 with no pads and ignoring padding" do assert {:ok, "fooba"} == hex_decode32("CPNMUOJ1", padding: false) end test "hex_decode32!/2 with no pads and ignoring padding" do assert "fooba" == hex_decode32!("CPNMUOJ1", padding: false) end test "hex_decode32/2 ignores incorrect padding when :padding is false" do assert {:ok, "foob"} == hex_decode32("CPNMUOG", padding: false) end test "hex_decode32!/2 ignores incorrect padding when :padding is false" do "foob" = hex_decode32!("CPNMUOG", padding: false) end test "hex_decode32/2 with :lower case and ignoring padding" do assert {:ok, "fo"} == hex_decode32("cpng", case: :lower, padding: false) end test "hex_decode32!/2 with :lower case and ignoring padding" do assert "fo" == hex_decode32!("cpng", case: :lower, padding: false) end test "hex_decode32/2 with :mixed case and ignoring padding" do assert {:ok, "fo"} == hex_decode32("cPNg====", case: :mixed, padding: false) end test "hex_decode32!/2 with :mixed case and ignoring padding" do assert "fo" == hex_decode32!("cPNg", case: :mixed, padding: false) end test "encode then decode is identity" do for {encode, decode} <- [ {&encode16/2, &decode16!/2}, {&encode32/2, &decode32!/2}, {&hex_encode32/2, &hex_decode32!/2}, {&encode64/2, &decode64!/2}, {&url_encode64/2, &url_decode64!/2} ], encode_case <- [:upper, :lower], decode_case <- [:upper, :lower, :mixed], encode_case == decode_case or decode_case == :mixed, pad? <- [true, false], len <- 0..256 do data = 0 |> :lists.seq(len - 1) |> Enum.shuffle() |> IO.iodata_to_binary() expected = data |> encode.(case: encode_case, pad: pad?) |> decode.(case: decode_case, pad: pad?) assert data == expected, "identity did not match for #{inspect(data)} when #{inspect(encode)} (#{encode_case})" end end end
30.910891
99
0.653547
08791588fb7459db8c2ee817a5b00a5692666acf
3,653
ex
Elixir
clients/dataproc/lib/google_api/dataproc/v1/model/py_spark_job.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dataproc/lib/google_api/dataproc/v1/model/py_spark_job.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dataproc/lib/google_api/dataproc/v1/model/py_spark_job.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.Dataproc.V1.Model.PySparkJob do @moduledoc """ A Dataproc job for running Apache PySpark (https://spark.apache.org/docs/0.9.0/python-programming-guide.html) applications on YARN. ## Attributes * `archiveUris` (*type:* `list(String.t)`, *default:* `nil`) - Optional. HCFS URIs of archives to be extracted into the working directory of each executor. Supported file types: .jar, .tar, .tar.gz, .tgz, and .zip. * `args` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The arguments to pass to the driver. Do not include arguments, such as --conf, that can be set as job properties, since a collision may occur that causes an incorrect job submission. * `fileUris` (*type:* `list(String.t)`, *default:* `nil`) - Optional. HCFS URIs of files to be placed in the working directory of each executor. Useful for naively parallel tasks. * `jarFileUris` (*type:* `list(String.t)`, *default:* `nil`) - Optional. HCFS URIs of jar files to add to the CLASSPATHs of the Python driver and tasks. * `loggingConfig` (*type:* `GoogleApi.Dataproc.V1.Model.LoggingConfig.t`, *default:* `nil`) - Optional. The runtime log config for job execution. * `mainPythonFileUri` (*type:* `String.t`, *default:* `nil`) - Required. The HCFS URI of the main Python file to use as the driver. Must be a .py file. * `properties` (*type:* `map()`, *default:* `nil`) - Optional. A mapping of property names to values, used to configure PySpark. Properties that conflict with values set by the Dataproc API may be overwritten. Can include properties set in /etc/spark/conf/spark-defaults.conf and classes in user code. * `pythonFileUris` (*type:* `list(String.t)`, *default:* `nil`) - Optional. HCFS file URIs of Python files to pass to the PySpark framework. Supported file types: .py, .egg, and .zip. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :archiveUris => list(String.t()) | nil, :args => list(String.t()) | nil, :fileUris => list(String.t()) | nil, :jarFileUris => list(String.t()) | nil, :loggingConfig => GoogleApi.Dataproc.V1.Model.LoggingConfig.t() | nil, :mainPythonFileUri => String.t() | nil, :properties => map() | nil, :pythonFileUris => list(String.t()) | nil } field(:archiveUris, type: :list) field(:args, type: :list) field(:fileUris, type: :list) field(:jarFileUris, type: :list) field(:loggingConfig, as: GoogleApi.Dataproc.V1.Model.LoggingConfig) field(:mainPythonFileUri) field(:properties, type: :map) field(:pythonFileUris, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Dataproc.V1.Model.PySparkJob do def decode(value, options) do GoogleApi.Dataproc.V1.Model.PySparkJob.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataproc.V1.Model.PySparkJob do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
53.720588
305
0.701889
087963a245ff310be111887e12f3ec97a8470af0
4,649
ex
Elixir
lib/stripe/issuing/card.ex
neneboe/stripity_stripe
e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17
[ "BSD-3-Clause" ]
null
null
null
lib/stripe/issuing/card.ex
neneboe/stripity_stripe
e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17
[ "BSD-3-Clause" ]
null
null
null
lib/stripe/issuing/card.ex
neneboe/stripity_stripe
e86be7cd8f19dd208ee3cb7d9bd6165be3e71f17
[ "BSD-3-Clause" ]
null
null
null
defmodule Stripe.Issuing.Card do @moduledoc """ Work with Stripe Issuing card objects. You can: - Create a card - Retrieve a card - Update a card - List all cards Stripe API reference: https://stripe.com/docs/api/issuing/cards """ use Stripe.Entity import Stripe.Request @type t :: %__MODULE__{ id: Stripe.id(), object: String.t(), authorization_controls: Stripe.Issuing.Types.authorization_controls(), brand: String.t(), cardholder: Stripe.Issuing.Cardholder.t(), created: Stripe.timestamp(), currency: String.t(), exp_month: pos_integer, exp_year: pos_integer, last4: String.t(), livemode: boolean, metadata: Stripe.Types.metadata(), name: String.t(), replacement_for: t | Stripe.id() | nil, replacement_reason: String.t() | nil, shipping: Stripe.Types.shipping() | nil, status: String.t(), type: atom() | String.t() } defstruct [ :id, :object, :authorization_controls, :brand, :cardholder, :created, :currency, :exp_month, :exp_year, :last4, :livemode, :metadata, :name, :replacement_for, :replacement_reason, :shipping, :status, :type ] @plural_endpoint "issuing/cards" @doc """ Create a card. """ @spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()} when params: %{ :currency => String.t(), :type => :physical | :virtual, optional(:authorization_controls) => Stripe.Issuing.Types.authorization_controls(), optional(:cardholder) => Stripe.Issuing.Cardholder.t(), optional(:metadata) => Stripe.Types.metadata(), optional(:replacement_for) => t | Stripe.id(), optional(:replacement_reason) => String.t(), optional(:shipping) => Stripe.Types.shipping(), optional(:status) => String.t() } | %{} def create(params, opts \\ []) do new_request(opts) |> put_endpoint(@plural_endpoint) |> put_params(params) |> put_method(:post) |> make_request() end @doc """ Retrieve a card. """ @spec retrieve(Stripe.id() | t, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()} def retrieve(id, opts \\ []) do new_request(opts) |> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}") |> put_method(:get) |> make_request() end @doc """ Update a card. """ @spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()} when params: %{ optional(:authorization_controls) => Stripe.Issuing.Types.authorization_controls(), optional(:cardholder) => Stripe.Issuing.Cardholder.t(), optional(:metadata) => Stripe.Types.metadata(), optional(:replacement_for) => t | Stripe.id(), optional(:replacement_reason) => String.t(), optional(:shipping) => Stripe.Types.shipping(), optional(:status) => String.t() } | %{} def update(id, params, opts \\ []) do new_request(opts) |> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}") |> put_method(:post) |> put_params(params) |> make_request() end @doc """ List all cards. """ @spec list(params, Stripe.options()) :: {:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()} when params: %{ optional(:cardholder) => Stripe.Issuing.Cardholder.t() | Stripe.id(), optional(:created) => String.t() | Stripe.date_query(), optional(:ending_before) => t | Stripe.id(), optional(:exp_month) => String.t(), optional(:exp_year) => String.t(), optional(:last4) => String.t(), optional(:limit) => 1..100, optional(:source) => String.t(), optional(:starting_after) => t | Stripe.id(), optional(:status) => String.t(), optional(:type) => String.t() } | %{} def list(params \\ %{}, opts \\ []) do new_request(opts) |> prefix_expansions() |> put_endpoint(@plural_endpoint) |> put_method(:get) |> put_params(params) |> cast_to_id([:cardholder, :ending_before, :starting_after]) |> make_request() end end
30.585526
98
0.529791
08798364dd0b799776d6f40e9b31459bb53252aa
150
ex
Elixir
web/controllers/page_controller.ex
flipjs/film-is-not-dead
a7ee56362e98ee08403532435dc3c05aa1ee58c3
[ "MIT" ]
null
null
null
web/controllers/page_controller.ex
flipjs/film-is-not-dead
a7ee56362e98ee08403532435dc3c05aa1ee58c3
[ "MIT" ]
null
null
null
web/controllers/page_controller.ex
flipjs/film-is-not-dead
a7ee56362e98ee08403532435dc3c05aa1ee58c3
[ "MIT" ]
null
null
null
defmodule FilmIsNotDead.PageController do use FilmIsNotDead.Web, :controller def index(conn, _params) do render conn, "index.html" end end
18.75
41
0.753333
0879e9981a01d245f41c8838d589425669979eb6
5,016
exs
Elixir
test/bodyguard/plug_test.exs
annkissam/bodyguard
601bdc123a56186b76779fd8993d060ccd17c948
[ "MIT" ]
608
2016-09-09T19:35:31.000Z
2022-03-30T15:46:26.000Z
test/bodyguard/plug_test.exs
annkissam/bodyguard
601bdc123a56186b76779fd8993d060ccd17c948
[ "MIT" ]
69
2016-09-08T14:21:36.000Z
2021-08-04T00:10:41.000Z
test/bodyguard/plug_test.exs
annkissam/bodyguard
601bdc123a56186b76779fd8993d060ccd17c948
[ "MIT" ]
45
2016-09-08T20:06:51.000Z
2021-12-20T18:04:54.000Z
defmodule PlugTest do use ExUnit.Case, async: false import Bodyguard.Action alias Bodyguard.Action setup do conn = Plug.Test.conn(:get, "/") allow_user = %TestContext.User{allow: true} deny_user = %TestContext.User{allow: false} {:ok, conn: conn, allow_user: allow_user, deny_user: deny_user} end def build_action(conn, opts \\ []) do opts = Keyword.merge([context: TestContext, policy: TestDeferralContext.Policy], opts) plug_opts = Bodyguard.Plug.BuildAction.init(opts) Bodyguard.Plug.BuildAction.call(conn, plug_opts) end def get_action(conn), do: conn.assigns.action def get_user(conn), do: conn.assigns.user def get_params(conn), do: conn.assigns.params test "putting an updating an action", %{conn: conn} do conn = Bodyguard.Plug.put_action(conn, act(TestContext)) assert %Action{} = conn.assigns.action conn = Bodyguard.Plug.update_action(conn, &put_user(&1, %TestContext.User{})) assert %Action{user: %TestContext.User{}} = conn.assigns.action end test "BuildAction plug", %{conn: conn} do conn = build_action(conn) assert %Action{context: TestContext, policy: TestDeferralContext.Policy} = conn.assigns.action end test "BuildAction plug with a custom key", %{conn: conn} do conn = build_action(conn, key: :custom_action) assert %Action{context: TestContext, policy: TestDeferralContext.Policy} = conn.assigns.custom_action end test "Authorize plug with raising", %{conn: conn, allow_user: allow_user, deny_user: deny_user} do # Failure opts = Bodyguard.Plug.Authorize.init( policy: TestContext, action: :any, user: fn _ -> deny_user end ) assert_raise Bodyguard.NotAuthorizedError, fn -> Bodyguard.Plug.Authorize.call(conn, opts) end # Success opts = Bodyguard.Plug.Authorize.init( policy: TestContext, action: :any, user: fn _ -> allow_user end ) assert Bodyguard.Plug.Authorize.call(conn, opts) end test "Authorize plug with fallback", %{conn: conn, allow_user: allow_user, deny_user: deny_user} do conn = build_action(conn) # Failure opts = Bodyguard.Plug.Authorize.init( policy: TestContext, action: :any, user: fn _ -> deny_user end, fallback: TestFallbackController ) fail_conn = Bodyguard.Plug.Authorize.call(conn, opts) assert fail_conn.assigns[:fallback_handled] assert fail_conn.halted # Success opts = Bodyguard.Plug.Authorize.init( policy: TestContext, action: :any, user: fn _ -> allow_user end, fallback: TestFallbackController ) ok_conn = Bodyguard.Plug.Authorize.call(conn, opts) refute ok_conn.assigns[:fallback_handled] refute ok_conn.halted end test "Authorize plug with a custom action function", %{conn: conn, allow_user: allow_user} do conn = Plug.Conn.assign(conn, :user, allow_user) conn = Plug.Conn.assign(conn, :action, :any) inits = [ # function/1 variant [policy: TestContext, action: & &1.assigns.action, user: & &1.assigns.user], # {module, fun} variant [policy: TestContext, action: {__MODULE__, :get_action}, user: {__MODULE__, :get_user}] ] for init <- inits do opts = Bodyguard.Plug.Authorize.init(init) assert Bodyguard.Plug.Authorize.call(conn, opts) end conn = Plug.Conn.assign(conn, :action, :fail) for init <- inits do opts = Bodyguard.Plug.Authorize.init(init) assert_raise Bodyguard.NotAuthorizedError, fn -> Bodyguard.Plug.Authorize.call(conn, opts) end end end test "Authorize plug with a custom params function", %{conn: conn} do conn = conn |> Plug.Conn.assign(:params, %{"id" => 1}) |> Plug.Conn.assign(:action, :param_fun_pass) inits = [ [policy: TestContext, action: & &1.assigns.action, params: & &1.assigns.params], [policy: TestContext, action: {__MODULE__, :get_action}, params: {__MODULE__, :get_params}] ] for init <- inits do opts = Bodyguard.Plug.Authorize.init(init) assert Bodyguard.Plug.Authorize.call(conn, opts) end conn = Plug.Conn.assign(conn, :action, :param_fun_fail) for init <- inits do opts = Bodyguard.Plug.Authorize.init(init) assert_raise Bodyguard.NotAuthorizedError, fn -> Bodyguard.Plug.Authorize.call(conn, opts) end end end test "Authorize plug with default options", %{conn: conn} do conn = conn |> Plug.Conn.assign(:params, %{"id" => 1}) |> Plug.Conn.assign(:action, :any) Application.put_env(:bodyguard, Bodyguard.Plug.Authorize, action: {__MODULE__, :get_action}, params: {__MODULE__, :get_params} ) opts = Bodyguard.Plug.Authorize.init(policy: TestContext) assert Bodyguard.Plug.Authorize.call(conn, opts) Application.delete_env(:bodyguard, Bodyguard.Plug.Authorize) end end
29.333333
101
0.662281
087a0096c1764064a55f2fc2704da08eafef172b
4,292
ex
Elixir
lib/stripe.ex
Rutaba/stripity_stripe
12c525301c781f9c8c7e578cc0d933f5d35183d5
[ "BSD-3-Clause" ]
555
2016-11-29T05:02:27.000Z
2022-03-30T00:47:59.000Z
lib/stripe.ex
Rutaba/stripity_stripe
12c525301c781f9c8c7e578cc0d933f5d35183d5
[ "BSD-3-Clause" ]
532
2016-11-28T18:22:25.000Z
2022-03-30T17:04:32.000Z
lib/stripe.ex
Rutaba/stripity_stripe
12c525301c781f9c8c7e578cc0d933f5d35183d5
[ "BSD-3-Clause" ]
296
2016-12-05T14:04:09.000Z
2022-03-28T20:39:37.000Z
defmodule Stripe do @moduledoc """ A HTTP client for Stripe. ## Configuration ### API Key You need to set your API key in your application configuration. Typically this is done in `config/config.exs` or a similar file. For example: config :stripity_stripe, api_key: "sk_test_abc123456789qwerty" You can also utilize `System.get_env/1` to retrieve the API key from an environment variable, but remember that this can cause issues if you use a release tool like exrm or Distillery. config :stripity_stripe, api_key: System.get_env("STRIPE_API_KEY") ### Shared Options Almost all of the requests that can be sent accept the following options: * `:api_key` - The Stripe API key to use for the request. See [https://stripe.com/docs/api/authentication](https://stripe.com/docs/api/authentication) * `:api_version` - The version of the api that is being used, defaults to the version the library is written for. See [https://stripe.com/docs/api/versioning](https://stripe.com/docs/api/versioning) * `:connect_account` - The ID of a Stripe Connect account for which the request should be made, passed through as the "Stripe-Account" header. The preferred authentication method for Stripe Connect. See [https://stripe.com/docs/connect/authentication#stripe-account-header](https://stripe.com/docs/connect/authentication#stripe-account-header) * `:expand` - Takes a list of fields that should be expanded in the response from Stripe. See [https://stripe.com/docs/api/expanding_objects](https://stripe.com/docs/api/expanding_objects) * `:idempotency_key` - A string that is passed through as the "Idempotency-Key" header on all POST requests. This is used by Stripe's idempotency layer to manage duplicate requests to the stripe API. See [https://stripe.com/docs/api/idempotent_requests](https://stripe.com/docs/api/idempotent_requests) ### HTTP Connection Pool Stripity Stripe is set up to use an HTTP connection pool by default. This means that it will reuse already opened HTTP connections in order to minimize the overhead of establishing connections. The pool is directly supervised by Stripity Stripe. Two configuration options are available to tune how this pool works: `:timeout` and `:max_connections`. `:timeout` is the amount of time that a connection will be allowed to remain open but idle (no data passing over it) before it is closed and cleaned up. This defaults to 5 seconds. `:max_connections` is the maximum number of connections that can be open at any time. This defaults to 10. Both these settings are located under the `:pool_options` key in your application configuration: config :stripity_stripe, :pool_options, timeout: 5_000, max_connections: 10 If you prefer, you can also turn pooling off completely using the `:use_connection_pool` setting: config :stripity_stripe, use_connection_pool: false """ use Application @type id :: String.t() @type date_query :: %{ optional(:gt) => timestamp, optional(:gte) => timestamp, optional(:lt) => timestamp, optional(:lte) => timestamp } @type integer_query :: %{ optional(:gt) => integer, optional(:gte) => integer, optional(:lt) => integer, optional(:lte) => integer } @type options :: Keyword.t() @type timestamp :: pos_integer @doc """ Callback for the application Start the supervision tree including the supervised HTTP connection pool (if it's being used) when the VM loads the application pool. Note that we are taking advantage of the BEAM application standard in order to start the pool when the application is started. While we do start a supervisor, the supervisor is only to comply with the expectations of the BEAM application standard. It is not given any children to supervise. """ @spec start(Application.start_type(), any) :: {:error, any} | {:ok, pid} | {:ok, pid, any} def start(_start_type, _args) do import Supervisor.Spec, warn: false children = Stripe.API.supervisor_children() opts = [strategy: :one_for_one, name: Stripe.Supervisor] Supervisor.start_link(children, opts) end end
40.490566
165
0.716682
087a05797bc89c11a2da28e5e40ea1bb956b7535
2,404
ex
Elixir
clients/composer/lib/google_api/composer/v1/model/date.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/composer/lib/google_api/composer/v1/model/date.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/composer/lib/google_api/composer/v1/model/date.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Composer.V1.Model.Date do @moduledoc """ Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp ## Attributes * `day` (*type:* `integer()`, *default:* `nil`) - Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. * `month` (*type:* `integer()`, *default:* `nil`) - Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. * `year` (*type:* `integer()`, *default:* `nil`) - Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :day => integer() | nil, :month => integer() | nil, :year => integer() | nil } field(:day) field(:month) field(:year) end defimpl Poison.Decoder, for: GoogleApi.Composer.V1.Model.Date do def decode(value, options) do GoogleApi.Composer.V1.Model.Date.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Composer.V1.Model.Date do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.358491
590
0.709235
087a1ef2408c56ccd636b7d2824d20cca65739fa
2,411
ex
Elixir
lib/geocoder/worker.ex
fancyturtle/geocoder
e897bba5645a86cbf2cab09d2260b61a5dbe7c56
[ "MIT" ]
98
2015-08-21T08:47:11.000Z
2021-10-18T07:48:40.000Z
lib/geocoder/worker.ex
DaoDeCyrus/geocoder
330f000cc620ef4141ed94deb1b40b11979f8e01
[ "MIT" ]
42
2015-09-03T14:02:18.000Z
2021-05-17T13:56:24.000Z
lib/geocoder/worker.ex
DaoDeCyrus/geocoder
330f000cc620ef4141ed94deb1b40b11979f8e01
[ "MIT" ]
63
2015-09-03T13:50:27.000Z
2021-09-14T20:50:58.000Z
defmodule Geocoder.Worker do use GenServer use Towel # Public API def geocode(params) do assign(:geocode, params) end def geocode_list(params) do assign(:geocode_list, params) end def reverse_geocode(params) do assign(:reverse_geocode, params) end def reverse_geocode_list(params) do assign(:reverse_geocode_list, params) end # GenServer API @worker_defaults [ store: Geocoder.Store, provider: Geocoder.Providers.OpenStreetMaps ] def init(conf) do {:ok, Keyword.merge(@worker_defaults, conf)} end def start_link(conf) do GenServer.start_link(__MODULE__, conf) end def handle_call({function, params}, _from, conf) do # unfortunately, both the worker and param defaults use `store` # for the worker, this defines which store to use, for the params # this defines if the store should be used use_store = params[:store] params = Keyword.merge(conf, Keyword.drop(params, [:store])) {:reply, run(function, params, use_store), conf} end def handle_cast({function, params}, conf) do Task.start_link(fn -> send(params[:stream_to], run(function, params, params[:store])) end) {:noreply, conf} end # Private API @assign_defaults [ timeout: 5000, stream_to: nil, store: true ] defp assign(name, params) do gen_server_options = Keyword.merge(@assign_defaults, params) params_with_defaults = Keyword.drop(gen_server_options, [:timeout, :stream_to]) function = case {gen_server_options[:stream_to], {name, params_with_defaults}} do {nil, message} -> &GenServer.call(&1, message, gen_server_options[:timeout]) {_, message} -> &GenServer.cast(&1, message) end :poolboy.transaction(Geocoder.pool_name(), function, gen_server_options[:timeout]) end def run(function, params, useStore) def run(function, params, _) when function in [:geocode_list, :reverse_geocode_list] do apply(params[:provider], function, [params]) end def run(function, params, false) do apply(params[:provider], function, [params]) |> Monad.tap(&params[:store].update/1) |> Monad.tap(&params[:store].link(params, &1)) end def run(function, params, true) do case apply(params[:store], function, [params]) do {:just, coords} -> ok(coords) :nothing -> run(function, params, false) end end end
25.378947
89
0.676483
087a6dadae94c83defebcb2bb75a37e275d044cc
2,045
exs
Elixir
chat/config/dev.exs
ikhlas-firlana/web-chat-service-elixir
bad0426619a7e217890c06e506f11d0999ee6ff3
[ "Apache-2.0" ]
null
null
null
chat/config/dev.exs
ikhlas-firlana/web-chat-service-elixir
bad0426619a7e217890c06e506f11d0999ee6ff3
[ "Apache-2.0" ]
null
null
null
chat/config/dev.exs
ikhlas-firlana/web-chat-service-elixir
bad0426619a7e217890c06e506f11d0999ee6ff3
[ "Apache-2.0" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :chat, ChatWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :chat, ChatWeb.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/chat_web/views/.*(ex)$}, ~r{lib/chat_web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime # Configure your database config :chat, Chat.Repo, username: "root", password: "root", database: "chat_dev", hostname: "localhost", pool_size: 10
26.907895
68
0.681174
087a6fb40c64724e8c0589fb868009a92cbcffff
7,853
ex
Elixir
lib/codes/codes_c4a.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_c4a.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_c4a.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_C4A do alias IcdCode.ICDCode def _C4A0 do %ICDCode{full_code: "C4A0", category_code: "C4A", short_code: "0", full_name: "Merkel cell carcinoma of lip", short_name: "Merkel cell carcinoma of lip", category_name: "Merkel cell carcinoma of lip" } end def _C4A10 do %ICDCode{full_code: "C4A10", category_code: "C4A", short_code: "10", full_name: "Merkel cell carcinoma of unspecified eyelid, including canthus", short_name: "Merkel cell carcinoma of unspecified eyelid, including canthus", category_name: "Merkel cell carcinoma of unspecified eyelid, including canthus" } end def _C4A11 do %ICDCode{full_code: "C4A11", category_code: "C4A", short_code: "11", full_name: "Merkel cell carcinoma of right eyelid, including canthus", short_name: "Merkel cell carcinoma of right eyelid, including canthus", category_name: "Merkel cell carcinoma of right eyelid, including canthus" } end def _C4A12 do %ICDCode{full_code: "C4A12", category_code: "C4A", short_code: "12", full_name: "Merkel cell carcinoma of left eyelid, including canthus", short_name: "Merkel cell carcinoma of left eyelid, including canthus", category_name: "Merkel cell carcinoma of left eyelid, including canthus" } end def _C4A20 do %ICDCode{full_code: "C4A20", category_code: "C4A", short_code: "20", full_name: "Merkel cell carcinoma of unspecified ear and external auricular canal", short_name: "Merkel cell carcinoma of unspecified ear and external auricular canal", category_name: "Merkel cell carcinoma of unspecified ear and external auricular canal" } end def _C4A21 do %ICDCode{full_code: "C4A21", category_code: "C4A", short_code: "21", full_name: "Merkel cell carcinoma of right ear and external auricular canal", short_name: "Merkel cell carcinoma of right ear and external auricular canal", category_name: "Merkel cell carcinoma of right ear and external auricular canal" } end def _C4A22 do %ICDCode{full_code: "C4A22", category_code: "C4A", short_code: "22", full_name: "Merkel cell carcinoma of left ear and external auricular canal", short_name: "Merkel cell carcinoma of left ear and external auricular canal", category_name: "Merkel cell carcinoma of left ear and external auricular canal" } end def _C4A30 do %ICDCode{full_code: "C4A30", category_code: "C4A", short_code: "30", full_name: "Merkel cell carcinoma of unspecified part of face", short_name: "Merkel cell carcinoma of unspecified part of face", category_name: "Merkel cell carcinoma of unspecified part of face" } end def _C4A31 do %ICDCode{full_code: "C4A31", category_code: "C4A", short_code: "31", full_name: "Merkel cell carcinoma of nose", short_name: "Merkel cell carcinoma of nose", category_name: "Merkel cell carcinoma of nose" } end def _C4A39 do %ICDCode{full_code: "C4A39", category_code: "C4A", short_code: "39", full_name: "Merkel cell carcinoma of other parts of face", short_name: "Merkel cell carcinoma of other parts of face", category_name: "Merkel cell carcinoma of other parts of face" } end def _C4A4 do %ICDCode{full_code: "C4A4", category_code: "C4A", short_code: "4", full_name: "Merkel cell carcinoma of scalp and neck", short_name: "Merkel cell carcinoma of scalp and neck", category_name: "Merkel cell carcinoma of scalp and neck" } end def _C4A51 do %ICDCode{full_code: "C4A51", category_code: "C4A", short_code: "51", full_name: "Merkel cell carcinoma of anal skin", short_name: "Merkel cell carcinoma of anal skin", category_name: "Merkel cell carcinoma of anal skin" } end def _C4A52 do %ICDCode{full_code: "C4A52", category_code: "C4A", short_code: "52", full_name: "Merkel cell carcinoma of skin of breast", short_name: "Merkel cell carcinoma of skin of breast", category_name: "Merkel cell carcinoma of skin of breast" } end def _C4A59 do %ICDCode{full_code: "C4A59", category_code: "C4A", short_code: "59", full_name: "Merkel cell carcinoma of other part of trunk", short_name: "Merkel cell carcinoma of other part of trunk", category_name: "Merkel cell carcinoma of other part of trunk" } end def _C4A60 do %ICDCode{full_code: "C4A60", category_code: "C4A", short_code: "60", full_name: "Merkel cell carcinoma of unspecified upper limb, including shoulder", short_name: "Merkel cell carcinoma of unspecified upper limb, including shoulder", category_name: "Merkel cell carcinoma of unspecified upper limb, including shoulder" } end def _C4A61 do %ICDCode{full_code: "C4A61", category_code: "C4A", short_code: "61", full_name: "Merkel cell carcinoma of right upper limb, including shoulder", short_name: "Merkel cell carcinoma of right upper limb, including shoulder", category_name: "Merkel cell carcinoma of right upper limb, including shoulder" } end def _C4A62 do %ICDCode{full_code: "C4A62", category_code: "C4A", short_code: "62", full_name: "Merkel cell carcinoma of left upper limb, including shoulder", short_name: "Merkel cell carcinoma of left upper limb, including shoulder", category_name: "Merkel cell carcinoma of left upper limb, including shoulder" } end def _C4A70 do %ICDCode{full_code: "C4A70", category_code: "C4A", short_code: "70", full_name: "Merkel cell carcinoma of unspecified lower limb, including hip", short_name: "Merkel cell carcinoma of unspecified lower limb, including hip", category_name: "Merkel cell carcinoma of unspecified lower limb, including hip" } end def _C4A71 do %ICDCode{full_code: "C4A71", category_code: "C4A", short_code: "71", full_name: "Merkel cell carcinoma of right lower limb, including hip", short_name: "Merkel cell carcinoma of right lower limb, including hip", category_name: "Merkel cell carcinoma of right lower limb, including hip" } end def _C4A72 do %ICDCode{full_code: "C4A72", category_code: "C4A", short_code: "72", full_name: "Merkel cell carcinoma of left lower limb, including hip", short_name: "Merkel cell carcinoma of left lower limb, including hip", category_name: "Merkel cell carcinoma of left lower limb, including hip" } end def _C4A8 do %ICDCode{full_code: "C4A8", category_code: "C4A", short_code: "8", full_name: "Merkel cell carcinoma of overlapping sites", short_name: "Merkel cell carcinoma of overlapping sites", category_name: "Merkel cell carcinoma of overlapping sites" } end def _C4A9 do %ICDCode{full_code: "C4A9", category_code: "C4A", short_code: "9", full_name: "Merkel cell carcinoma, unspecified", short_name: "Merkel cell carcinoma, unspecified", category_name: "Merkel cell carcinoma, unspecified" } end end
38.307317
96
0.634662
087a7cb8c5ab7959be508184bbd0f2b235bf1975
2,730
ex
Elixir
lib/pulsar/dashboard_server.ex
walmartlabs/pulsar
d2362082078e2be5d7158177674b29f96075d47e
[ "Apache-2.0" ]
22
2017-10-10T17:00:10.000Z
2021-10-04T08:08:01.000Z
lib/pulsar/dashboard_server.ex
walmartlabs/pulsar
d2362082078e2be5d7158177674b29f96075d47e
[ "Apache-2.0" ]
null
null
null
lib/pulsar/dashboard_server.ex
walmartlabs/pulsar
d2362082078e2be5d7158177674b29f96075d47e
[ "Apache-2.0" ]
1
2020-03-12T20:33:20.000Z
2020-03-12T20:33:20.000Z
defmodule Pulsar.DashboardServer do alias Pulsar.Dashboard, as: D @moduledoc """ Responsible for managing a Dashboard, updating it based on received messages, and periodically flushing it to output. The `Pulsar` module is the client API for creating and updating jobs. The `:pulsar` application defines two configuration values: * `:flush_interval` - interval at which output is written to the console * `:active_highlight_duration` - how long an updated job is "bright" Both values are in milliseconds. Updates to jobs accumluate between flushes; this reduces the amount of output that must be written. """ use GenServer def start_link(state) do GenServer.start_link(__MODULE__, state, name: __MODULE__) end def init(_) do enqueue_flush() dashboard = D.new_dashboard(Application.get_env(:pulsar, :active_highlight_duration)) {:ok, %{dashboard: dashboard, paused: false}} end def terminate(_reason, state) do # TODO: Shutdown the dashboard properly, marking all jobs as complete {_, output} = D.flush(state.dashboard) IO.write(output) end # -- requests sent from the client -- def handle_call(:job, _from, state) do jobid = System.unique_integer() {:reply, jobid, update_in(state.dashboard, &(D.add_job(&1, jobid)))} end def handle_call(:pause, _from, state) do if state.paused do {:reply, :ok, state} end {new_dashboard, output} = D.pause(state.dashboard) IO.write(output) {:reply, :ok, %{state | dashboard: new_dashboard, paused: true}} end def handle_cast(:resume, state) do {:noreply, %{state | paused: false}} end def handle_cast({:update, jobid, message}, state) do update_job(state, jobid, message: message) end def handle_cast({:complete, jobid}, state) do {:noreply, update_in(state.dashboard, &(D.complete_job(&1, jobid)))} end def handle_cast({:status, jobid, status}, state) do update_job(state, jobid, status: status) end def handle_cast({:prefix, jobid, prefix}, state) do update_job(state, jobid, prefix: prefix) end # -- internal callbacks def handle_info(:flush, state) do enqueue_flush() if state.paused do {:noreply, state} else {new_dashboard, output} = state.dashboard |> D.update() |> D.flush() IO.write(output) {:noreply, %{state | dashboard: new_dashboard}} end end defp enqueue_flush() do Process.send_after(self(), :flush, Application.get_env(:pulsar, :flush_interval)) end defp update_job(state, jobid, job_data) do new_dashboard = D.update_job(state.dashboard, jobid, job_data) {:noreply, %{state | dashboard: new_dashboard}} end end
24.818182
90
0.683883
087a8ceb6517409396b7630eb6fd4bcbcb4cf1aa
2,980
exs
Elixir
lib/mix/test/mix/tasks/profile.cprof_test.exs
tmbb/exdocs_makedown_demo
6a0039c54d2fa10d79c080efcef8d70d359678f8
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/profile.cprof_test.exs
tmbb/exdocs_makedown_demo
6a0039c54d2fa10d79c080efcef8d70d359678f8
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/profile.cprof_test.exs
tmbb/exdocs_makedown_demo
6a0039c54d2fa10d79c080efcef8d70d359678f8
[ "Apache-2.0" ]
null
null
null
Code.require_file "../../test_helper.exs", __DIR__ defmodule Mix.Tasks.Profile.CprofTest do use MixTest.Case import ExUnit.CaptureIO alias Mix.Tasks.Profile.Cprof @moduletag apps: [:sample] @expr "Enum.each(1..5, &String.Chars.Integer.to_string/1)" test "profiles evaluated expression", context do in_tmp context.test, fn -> assert capture_io(fn -> Cprof.run(["-e", @expr]) end) =~ ~r(String\.Chars\.Integer\.to_string\/1 *\d) end end test "profiles the script", context do in_tmp context.test, fn -> profile_script_name = "profile_script.ex" File.write! profile_script_name, @expr assert capture_io(fn -> Cprof.run([profile_script_name]) end) =~ ~r(String\.Chars\.Integer\.to_string\/1 *\d) end end test "filters based on limit", context do in_tmp context.test, fn -> refute capture_io(fn -> Cprof.run(["--limit", "5", "-e", @expr]) end) =~ ~r(:erlang\.trace_pattern\/3 *\d) end end test "filters based on module", context do in_tmp context.test, fn -> refute capture_io(fn -> Cprof.run(["--module", "Enum", "-e", @expr]) end) =~ ~r(String\.Chars\.Integer\.to_string\/1 *\d) end end test "Module matching", context do in_tmp context.test, fn -> refute capture_io(fn -> Cprof.run(["--matching", "Enum", "-e", @expr]) end) =~ ~r(String\.Chars\.Integer\.to_string\/1 *\d) end end test "Module.function matching", context do in_tmp context.test, fn -> refute capture_io(fn -> Cprof.run(["--matching", "Enum.each", "-e", @expr]) end) =~ ~r(anonymous fn\/3 in Enum\.each\/2 *\d) end end test "Module.function/arity matching", context do in_tmp context.test, fn -> assert capture_io(fn -> Cprof.run(["--matching", "Enum.each/8", "-e", @expr]) end) =~ ~r(Profile done over 0 matching functions) end end test "errors on missing files", context do in_tmp context.test, fn -> assert_raise Mix.Error, "No files matched pattern \"non-existent\" given to --require", fn -> capture_io(fn -> Cprof.run ["-r", "non-existent"] end) end assert_raise Mix.Error, "No files matched pattern \"non-existent\" given to --require", fn -> capture_io(fn -> Cprof.run ["-pr", "non-existent"] end) end assert_raise Mix.Error, "No such file: non-existent", fn -> capture_io(fn -> Cprof.run ["non-existent"] end) end File.mkdir_p!("lib") assert_raise Mix.Error, "No such file: lib", fn -> capture_io(fn -> Cprof.run ["lib"] end) end end end test "warmup", context do in_tmp context.test, fn -> assert capture_io(fn -> Cprof.run(["-e", @expr]) end) =~ "Warmup..." refute capture_io(fn -> Cprof.run(["-e", "Enum.each(1..5, fn(_) -> MapSet.new end)", "--no-warmup"]) end) =~ "Warmup..." end end end
28.113208
99
0.594295
087a940ed217068d55f9a707fbeb188fd47e1b05
300
ex
Elixir
lib/utils.ex
Sanchos01/Cachets
b3b0e3524c99ac847553e753c4ecbad61ea55843
[ "MIT" ]
null
null
null
lib/utils.ex
Sanchos01/Cachets
b3b0e3524c99ac847553e753c4ecbad61ea55843
[ "MIT" ]
null
null
null
lib/utils.ex
Sanchos01/Cachets
b3b0e3524c99ac847553e753c4ecbad61ea55843
[ "MIT" ]
null
null
null
defmodule Cachets.Utils do def nowstamp do {a,b,c} = :os.timestamp a * 1000000000 + b * 1000 + div(c, 1000) end def name_for_table(name) do String.to_atom("__Cachets__" <> name <> "__") end def via_tuple(name) do {:via, Registry, {Cachets.Worker.Registry, name}} end end
21.428571
53
0.643333
087ac8d0672ba24005bca26c4bc0f9408ff45fb9
335
exs
Elixir
macro/trans/i18n.exs
techgaun/dumpster
c2a5394afe759fb99041aea677e9b0bc4bf91aec
[ "Unlicense" ]
1
2019-12-10T22:25:31.000Z
2019-12-10T22:25:31.000Z
macro/trans/i18n.exs
techgaun/dumpster
c2a5394afe759fb99041aea677e9b0bc4bf91aec
[ "Unlicense" ]
3
2020-10-25T04:40:05.000Z
2020-10-25T04:48:10.000Z
macro/trans/i18n.exs
techgaun/dumpster
c2a5394afe759fb99041aea677e9b0bc4bf91aec
[ "Unlicense" ]
null
null
null
defmodule I18n do use Translator locale "en", flash: [ hello: "Hello %{first} %{last}", bye: "Bye, ${name}!" ], users: [ title: "Users" ] locale "fr", flash: [ hello: "Salut %{first} %{last}", bye: "Au revoir, %{name}" ], users: [ title: "Utilisateurs" ] end
15.227273
38
0.468657
087adc33582961aff0237195333cb2b2a9d72cad
572
ex
Elixir
lib/lambda.ex
nimaai/shen-elixir
41db4935d43615503ed46aff36af1bf8359b2d12
[ "MIT" ]
null
null
null
lib/lambda.ex
nimaai/shen-elixir
41db4935d43615503ed46aff36af1bf8359b2d12
[ "MIT" ]
null
null
null
lib/lambda.ex
nimaai/shen-elixir
41db4935d43615503ed46aff36af1bf8359b2d12
[ "MIT" ]
null
null
null
defmodule Kl.Lambda do require IEx # param is not free def beta_reduce([:lambda, param, _] = lambda, param, _) do lambda end # param is free def beta_reduce([:lambda, param_x, body], param_y, val) do [:lambda, param_x, beta_reduce(body, param_y, val)] end def beta_reduce([fst | rest], param, val) do [beta_reduce(fst, param, val) | beta_reduce(rest, param, val)] end def beta_reduce(param, param, val) when is_atom(param) do val end def beta_reduce([], _, _) do [] end def beta_reduce(val, _, _) do val end end
19.066667
66
0.643357
087afb9bdaa65fb009faf5e1de45cf146f54ed7e
26,150
ex
Elixir
lib/plug/debugger.ex
shadowfacts/plug
c27823e537df26557a1facc3febad5ebe5f1e415
[ "Apache-2.0" ]
null
null
null
lib/plug/debugger.ex
shadowfacts/plug
c27823e537df26557a1facc3febad5ebe5f1e415
[ "Apache-2.0" ]
null
null
null
lib/plug/debugger.ex
shadowfacts/plug
c27823e537df26557a1facc3febad5ebe5f1e415
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Debugger do @moduledoc """ A module (**not a plug**) for debugging in development. This module is commonly used within a `Plug.Builder` or a `Plug.Router` and it wraps the `call/2` function. Notice `Plug.Debugger` *does not* catch errors, as errors should still propagate so that the Elixir process finishes with the proper reason. This module does not perform any logging either, as all logging is done by the web server handler. **Note:** If this module is used with `Plug.ErrorHandler`, only one of them will effectively handle errors. For this reason, it is recommended that `Plug.Debugger` is used before `Plug.ErrorHandler` and only in particular environments, like `:dev`. ## Examples defmodule MyApp do use Plug.Builder if Mix.env == :dev do use Plug.Debugger, otp_app: :my_app end plug :boom def boom(conn, _) do # Error raised here will be caught and displayed in a debug page # complete with a stacktrace and other helpful info. raise "oops" end end ## Options * `:otp_app` - the OTP application that is using Plug. This option is used to filter stacktraces that belong only to the given application. * `:style` - custom styles (see below) * `:banner` - the optional MFA (`{module, function, args}`) which receives exception details and returns banner contents to appear at the top of the page. May be any string, including markup. ## Custom styles You may pass a `:style` option to customize the look of the HTML page. use Plug.Debugger, style: [primary: "#c0392b", logo: "data:image/png;base64,..."] The following keys are available: * `:primary` - primary color * `:accent` - accent color * `:logo` - logo URI, or `nil` to disable The `:logo` is preferred to be a base64-encoded data URI so not to make any external requests, though external URLs (eg, `https://...`) are supported. ## Custom Banners You may pass an MFA (`{module, function, args}`) to be invoked when an error is rendered which provides a custom banner at the top of the debugger page. The function receives the following arguments, with the passed `args` concentated at the end: [conn, status, kind, reason, stacktrace] For example, the following `:banner` option: use Plug.Debugger, banner: {MyModule, :debug_banner, []} would invoke the function: MyModule.debug_banner(conn, status, kind, reason, stacktrace) ## Links to the text editor If a `PLUG_EDITOR` environment variable is set, `Plug.Debugger` will use it to generate links to your text editor. The variable should be set with `__FILE__` and `__LINE__` placeholders which will be correctly replaced. For example (with the [TextMate](http://macromates.com) editor): txmt://open/?url=file://__FILE__&line=__LINE__ Or, using Visual Studio Code: vscode://file/__FILE__:__LINE__ """ @already_sent {:plug_conn, :sent} @logo "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD0AAABgCAYAAACucnrAAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAJOpJREFUeAHFnFmPHeeZ39/aztZ7c2myuTVJLRxZsaPQ1lhjj+Oxg2AymAFyFUyAAOMgQO7yHZKLXAbIR8l9rgaDGMlgnCCLEcuxNBQlk5K49t5nqar5/Z7q1kJRNCV2K8U+59Spepfn/+zvU+9hkf6/Hjerq3OvvT4qr/e3Z+9uflOklN/URE/MU1xZ+seXyzb//SyvXulPp/+J+7efaHNiX79x0IvpW6sr8+d/nKf2Rpu3/SxNUlWkwYkhfMrA3yTo7NLoxzdHVf69uk1rbZvqLDXjlBW9Jk+jp9B2YpfyExv5iYGvL/30X/d7vf84bYszKcsmWZbqaNI0bdtkQ86zJ7qc2NdvQtL51YWf/KsiK/9D27YfNu1k2mSfTlsmLDtrlLSg2xND+pmBP539MxeP8TS/OPeDf55n5b9vUzbXJGSal1nWtE3MkecgbZu6zfp8/8YkfaLqfWn0/T8ti96/a1N7qm5a1LntpTbLE16sYyzos1lbN+PVlC72jpHZzxzqxECfH73x3Twf/NvU5hspaw8wYYw39XBepWaMhOus5ryu14s8e219YW3umZQe480TAb0yvHa5Kub+TZ6l38NhHWDLLTLVcfWR8QDlntVtParT7DJOfLVtZovFpL90jLieOdRJgF5ayE//edEWf4xUp6g0oalu8Ni82kqwKZstty2A23a+TQWqnvfyvF17JqXHePO4QZfne2/8ozLr/wv0d4DzmrVYLD6qAXgNyDzP2g2Efg5mVJh22DYerGyL6uIx4nrmUMcJOlvsX9zoV/1/1mbZZWx22mbaLu6Zf3zWbTPJZ019nnsxb+ZhjsIBQy48k9JjvHlsoFfSyuJicfYnKS+/1ybst22aLjSF02oRs3NlZZ4tAvEz86r3Xi/Pn06vLhwjti8d6jOTf2mb57kxHA7XvlWk/p81bVrAWU3oBBZclmGYOIUNywM9+AIRuZ8hfeJzSDnPMjXh9OLiGmp/8sdxgM5Xh+unq3zwA2h/PTU4L8EFaLwYUsV3E5q5hFDhxAAe4LnLQ8gAhxN5ni82Tf6NqPhxgB712oWXUjv4EYo8QIpdTo0kPTKddxxZWwicWA34paK7CuJO2twZFBkx/Rs4Xgj0zZs3q7P9S2tFmvsDJHsDmBP0WDHrqfmY4aAFSmJCvCI0saBqcuR6GvF+JgXW7psCDl0F84lnZi8E+u1ffLBCiF0r8+Im9tsHkGBZQJhb+xHOG9D6bw5tN8/VhJU6QyviUBOUNp2y4uK59MaJJykvAPrM/GChXK7yuZfJOq6hprOU5cRjnZVa3IgQ1Eg4HJUS55WymrRzgYnJt2nmm0sQYjUdzuT9kddP9Pi6oPO1wehMWc8tkXndBNYcsiQRQcIAV61ByB9qfQQcx6bGowqhBTBiHbhFoMtkQrGYtbP7uHUzs87iTwj61wK9nDYWU1nOFXVxFvt8VREWOmo+wdapKxelWfCcxDkfOja+s9Ros1OkJqSkBSWjtDpLzSPU4oO6rAD91omWj74O6KJK+RlkVmZl9RK41jBeQq4GrLPSjkNUAkXHve4rgHNim5SKrO1lbX4lS/kpumyjAPcwjI+Q8fLFfnOiKelXBr2W1k5Vo3whjUckGeVrrKQq9RgkpGFEZfIrAKjCIWFQauTaLMANW6YlOnjMIMuucL3E/h/i5j9CvfdolRdF7xX4cmJe/KuC7qX5+bNKqhxkZ5HZBpQDIBwRDkqrBkonVeUeUrW9Ehc4pzQPB8cl1tdtM4RnB/i/j7hF6jrFsedn1wY/PDFpfyXQp9OVU6nOWexXiKfcANOKUhYSMTgAKk2uIeAAibbCBf4h+jgMXsC2DSbdzvg8Sw0JLzh9aBs8Iaoy6w3y7Pf4WnW9jvf9q4Au87nBmRJicdN9lhPX8MA91LLuMpAQuDqMJwvECpZXZ8Nh7+iBE+IDSMgw99RSAk4DFGSNGM3am0s4gDplU5CvIe1Lxwu3G+25QZ9JG6fLJi3kVV73snw5L9IFBUYehT2TNfMiUOOXuAraQxVXrH5FiC6mWF929zSEOmtmOIF2AtZXqtS8jqVM6Admx2szSoj/4CRWXs8Luqyq8jw16zzNpLp3FpKXcWJ+a/FO+CVgIU4TUD6VcIBEdJx3B428rjjp1LgSkyOoOFfz4qdc3aDTDM7pGaZlmZaH82tvcLuL590wL/z+XIMh5bNZPnehZMUAeZA0fINV0beRDKADg1go/LQVxJp+Qhgs4aK8CFBRMIAreQaLZqDFSrpbU24d0GEBcz9H31tojsyEQ7EqW1nILuxv1x/cf2G0hwM8D+j+wnD9BsRW4CLWNL1eNfwpNnexaaf7oAAa+BAukuxhqmq2WP2HuP1OoMKbeY33irA+hRMN6aitx1zHMuiZp1UarTLQ++DltOExV9vLi/Zsf7r84W76ePc4gP9O9V4aXFkno15xstIyX15QJOhtoM6sHfLa5SKSRAPMuzkl6hqDgwuITRftqysAInnA8jdlIWb8xidmY+M47gv7Tkr8Rl5kf8Qlamjawazg7qn+cPST47Lv3wW6GJbDy02qYxk4I4CUWbWK2C5C3KHXzvFlAtdZkZSIGbEJGklbQTBgHTq2FmOlUAhqGQHTtOspjIMBhaCJ0dmYob7NY6AfMi+3Q0U0o/XRaOkfprT+wg/7ngl6Pl0/hV2dyxBfn9rGVPrr6gqdzgApq3NAkkb7hgR1YebgCJVLCokDRvDyE/kH/RQMLRLSnkqhUp7BkvD+aDjXEuEqm3L+XR4HvQX7DsfwYUH96vro9A05+iLHs0Bn89VgA0Mj+a8NqFY+iqrKr0AGsTWVRea6Xy9tkYDcEkoRCV+1Z4l1+JiC8+7ABGZZZR3cSlI7oR+80jzkjj5PjSkmePMJjP0+BvFdXZ9uEkaiJSxSLDm9wPGloFfT6gICvtKTHJYHCQUHNk8nyssxH6sjTRmQSKnAcxGyEX7YNQ3oJtDuhbdyGDUfW9WO0ZMWaWZ6CYBEacUmmIzaUiPxbBLMyNJbdP77RDKUICecjethOnWKtj70+1rHl4Iue+sbeVkuodUwnVQEyGXZW6FyeRHSqQMVc/WMG3mqCUDos+voBqKw1cg60XINOqSXw5QmGoCsW5x0Uj6sJyllPFmjqcTaU39henuAu4RB+R+2RfmtrIAZmEBvsNtbGa677v5ai5IvAb0xKMvsWl63OYCo78DzmYrcWyNKL+NsyJpSn0JeH//blATovIjVpQ4HoDlpDJ/6t07anUS8UtQuN2dYBuobxXAAmoFlTZnj9RE6Xs6OXMPhte3YeA3bfkTrV2HkZJCWcBvZgCqswJ8n7HbzH74/FfTaYGEdSZ7J8dYFoi5mqrfVoHwdzeRxjQ+nctxVMd/yjmsCHiukQ3WNSK2QOQDEp6cgoV+B7ipVVFxTUNdtwDXErDM03KHu9FbduaSTS+xcYEtOKn9c1vM3x2nTe7jPNDefzlleinDhtec5ngY66xflNYQ1YCmRMz0aDFRKHIC6yMtI7B+0FssdGJaW1PJnhYV9iO3wAhXnw4P3o0M77jQ4IT3B6vtwez7R5A0GRRhkDhkDN42BvmAQEkcDqibr/cUoe+UPpmmK+vdSv9c/zbPtyCOO5vldn59SdNhyJV1bpHRzCZeC9zH/MJMkpLal9oM6AQs6jDhFno+QwxB1mLWq+FTijtJLBRsHn5gHB/nZFDWe8U0n5gBaQgeeoOw6k0OpwwBXbz4eUgFgKhcZcZwVlBiyuZ8t5ufezLPZrO21+amFxjX+fMz2HG9fAD3oLa+TAS7VOc/MMSSIK0gE0WXX0WZm0BBH2F3BzWVWGZ0qFlh4LEKiAbSGh+uaI00rBHg0nF23UHGBhqNAYgWDzrgFq9EtIpSThKrDJICTvJjRMjnfxy07klI2/Fm/XXlzOK2n0NY70794nvufqaV30z7t/UnQJeJ9hQlLBko5JKBwKCjRqMV78PAN0ShNwoqSVDTFCuZmGq0ngzAcVKiDwgUTDs0Pvszwfz4M4H60M1YhQySPV8YMQsIz8IWdh62rUVZlbGraqrQ1iXavyKt+Xg3ZwHP6zdq1eFHMr6T1deZ5EhOXPn98rsF8emOlKtNFLpo/AlZJczbLSjR9GeLZ+qSZabSNy6AaUMOmKedBh4RMHsyrJZR4Fb6LluHEGnYVtTznShMGACBSK0HmWI3S5Bqi14ujOeHRoUJGhJ3LbFrTlftwmHt7LNiKVPT/5dxs6U20clJWc6s4NmP4M4/Pgx4WV2dN4lGqsiAqassCz1OPBT2lIVdIOhj/KT7BK8vylHImEEvQhBiiNJCuwxPkOAMXOXWaMFptiFN6jAB/YhwZyQgAJ+53Usc/YOe0hIHmeDDEspIcN5lhLkjbRTp9tP1no2b1LYau53rlORzPM/evfDbGlcvluR/BaRIQRyTJjBBobGHo1LuOwF5DfmHA0Cpi/5g8G9BkEy+wT7hCA4s5VL6kvdEL5ChFMd3CpnezGVLVf2kd3KDBVEVwNC4flv/hhfySrQYDWedIfiacWUbs5oLXYQTxPi0QU7+Tt72drKzvzPKl4V79eJPbMPOLxyegT49urlUpe4uZKofXg6m9MQ1vrHpucGkD2gwzzOOch2c4eUTM1/qBekq6KmifTjItizDaQ9tj3sewoBtW8ZvKUCFhNPMRWjEvZ4AFk7xkFMblW8BnZOggK2A5CvPVMSjgH41RhxHu9ltNW06xtLvtdGE2TY93YtAn3j4BvVKefx1yXiMZsUjFKT6S4dRA4i3RqXwdMs8wVXCPc/U3JoVmMyce0zZbhOa9vCnn8G0sCnCGrlPw2imfPkbRWWDQRSna18jfXYORjBbSZAZ5yuj+03F4WdhSxQmVlrSPXtjKhtyX53iEphnQ9AYpBvE73dme3ttiGpj6+eNwejWrvIpG9gCMHYducq0HQ3km2dZUPbGTkHJ4T4DjVNR0Xjhz5CPfq/NwEX1POjNIopdLpKbeZ1cRFRKUWOXXyxMm+IaEzOR0WJwb+rRhywa+vK5dGxkO43mMoUvxWmdpnk8ZjTxdgKXJxZ+Vqf9Pz8+/fAW4Rxg/QR6SXk0vLQyq0R/CywWcCIShc1gxFUrEamGswY+Vr4Fg3pDBxIdi1qz91v0Bs9/k9SbSA0iJnSEE3EETUm536AiWuNpJDXrwvxCMpdM5lBjVCIk6B5egOCaDNh2BkQDvWuzFd4ZiAWS7GI9TEiiaqxttcb1oKzOeX03Szt4niDkJLvQHCyuoYKRyAHR6pF1jbHpvAjUNATvGuUKR7lbHEw2FIJGCFxPrjmoNVQuddnjEgKTqXRroC6wJMYUOOexYJzxjNcFlHBySpa+O0hUW58aETrNC+ngD5lBzVDQcTqSr+lkGRE72C/uPmhu3qz9dnbvwJ9Jlv6MjJD1XbdzAU38H4lG9aCE4tq7idaQR7Qf5KRby52EjKw9XRyEa5uKK57yY0fg2ZMkwo46IEMiVKR6yNH7ASCKludyRTcEqhTL2nhxB1ZmJXjqxTnbctheD28ATKAbBHleZju8INSxNB9n6RMTSFniliwcJnL86qs7+cmf64Z0YgDc5kPNA6RyCo4P+CP4iXeKNvpHqQFWUlsHydhcbIrzAaWmAdD9pHx9clRGdDLP8DBSxD9SL011uWAVBoHQrTD5C6iF52BkSwvJ9WB/rZVSzi8tMCBIXI6EB0EhUZEypZ+3ndQAjE7TCdFXtwLRkIucQmI0xhtVeqv6CzUufbNcSNKum8ozGgQT4Dljk+in4Kevpgk3ZlG3zdkcDY1AkCu9DqxAg0H0TI1anbyrxOwt4fYhqd7CKWu8F9U3O+jvchJLHdvBU1MhwVmQvjBvAYTrQDkEAKIALGHXX0/EdRzODaYzF8zDocBVm3qKJHdpAkCRR+7z9/oXh5X/iPY+csmqffQ+nzNSLHFoB3aTyE/BNqvDe5nswJWvuww15TTgk/8LTxTmSo/snr+B6hrdvJjj/2XYoILAgwIwqgIfUa5yYSW5HtevLAALLWWZhz4n8kOe/MLLz7pRSBc536CNqkKCBGrcR3pX5USbW9/YPhsgEbul4cJl/fiq9ciFAz43myZtNPYXtKsPVA50PwTMe5zhd7AXJbPJtLwyJgJEbKFQj2E1nFAYWlFpYhBP8wrTPDTyhhQABde0kDMnLpCgBM78hyUwNSSpx9qUgdVPWTuqoO5JHGfnOesToDTJG7BgSy1mG1+JJwoGsGwpRSxd9KULkl+YHy3/MdypttcV7Nq/quohXSBRJ484OwYMXdca2ccjB8Wx2z47IzVU/ut4N3pZKUs4yF6rDDXS0HsHF08gEkDADCRgOlA4k8oSDiggBnOFcrKDqigVdRZtCIxwP5gRwtTYkgNrzxzUnA7QvFMjNAURKTQaxYv7wRTEHQdDkUeR/dDn9vRUcdLGM/NlxbyKJ3CiMQDy/slAqNgaVuYoaomfN0zYgtvkyR4vIdpAcrW2ve+PQA1JLQfLkyfl51HcbM93CW3QpKaKN1m27z+IJuVA4Y0DmBbK0MYJfmAxeqiZQL2YogB5MGjnzVf4wOKc9jA9zUintJxGeKkQ9HRcoQDDKtcmg/x1qccWiqZROh4GdWo0N75JTleoUqcbZIYtOkEhrdp/x5pwxzC9miPkQTNTC0a92yrhTlBRVyS5gbLswS6lKtwTziDaNzbUtPfJGiGBlx4p+irWCGtUJyzEdhn7kyTxAwIvpf2FsSV0Y1jL+ErzpySdXAdwi9sEA1MZ0VVD0ZZJs0E8FDxHYsuiITEL2Bn2oNemytg3hdag7XMBWROZ4WFsiu2raXTxxD7YynhyW95CNYhA1UPXZhHdBIqpsnkanoaVbG6MQjLTDpFNVHrmr7apL2DJuFIdFG7lsdYL7CtuXYY1+jktn1+3lKjOyWV6JMQgE0JpLkoulhkCiv/qFZrbfLlYH178HXzbkJh1pwy0jPmhIRuBA0D1kkJHKKWw4IguJgZSP2EhGJ8NFTMS7JzKYjgDpJpVRcywwCB/tPgLgqWXziOkoeqghNkIB4iy+KCyJjsIZJQxG13jimUPEKCTk0hUt5WXOKOv8ox1yie/hpxijw6KmeDMbqgTsyjXlpAvWxJuqpdR54Y2sYJMJ0BMAHVkMph4c1EV7j5H6sBDVond4XRwUU2KWhBPECNrO53G7TRdgY68o2DNWZfu4jxoEJhnUzTrP7ac+Dcw6qRn1d/yaF/IZ2Fgusqm0zRcQyTlkSjHQ4WlB5JBTEBlBFRzdzFIQHARUhL5sUMYzKgDCcGcTuA4QHPaH17IgLEQSOIO/XKclXqlOD2mOPSWWkpDatgdIY4ZZygOiPUHYT8YOP1G3Q+z0LDH4bRQT1cY6velzET6dyaAKOAyAzmg0SgcDOVw2tsU8Gku0yUYoIC5cs/LolMsTOviBksISWedtDNbgqt0JpliuLr0O+de9DkQsggK26i0u/jr6WaAapx0AVihoTRhum7dS7MsXUVNWYjy4Z2Rzw24anTKHFkJDrB/hk9Rk7Q6PcDYRvZMa2+EJnBYyQzswPfgRAD9HbItltG6ZaVeZZwEfx6Y9qIF8VHESPgGMWCKdsHqG6lweAyNJ2SI7GRcoQU3Bk8ecZCNqsIxrnMOLhinaMtRFAjq97j5Aqx9CtPqflOOQ2i0er60UFgWsp6W8YrAZ8NxxQLWT2IzrRm0OYP8Bk1zj5wsHs1Q/hC4YZfqfs4sYM8nyERPgQ/hVXpP1cUykOwIx+Iez8hFTRw+ZQIksjNp4B2UiMlhm8RZPjmszn9V7Mx4nEYMagnJNzGVAlSocD7cAzgBqZDBd1J8/6G3q69yckiN+jJgHeGs2Hsns4BJb9wu1QznAJkKYo5rr4mqQCrW46n3MhGoKcTbcj3mZ4oguwVg9Np3VLPSVngwhID71s37FruCHVwWGMDRydDZu2THGo7uqRivS4CY9UglEgIWRYwtex6Wu48wMxfq2cImO46T+dSdwGAQZlZH2I9Q2mMVt70tI5MzMgxZSH+OgUFzpJfEa8wx6mUsuRR1Sm2jQFsYw2JJkIwXa4cO8phqGitFWqeIkSTlN9hgHTnlNicoxxBWnVD8Y1+/4QD8ZglBLFugmVDbM+JwIdAEyRAhYA13HsiAY4PKv46FxoTuYHFJLFhYZxT+ogwCoZP5oq8ZN6MTigjmN4Thq/IwLjSE0+1vqECATulYyBkbfw/5+KAOtnP6BRpdsES/adZ8daC4fAvejcyd05iwa64bu5c3B/H263qYtKoemMJZlInrwUn2QPKPK6ieOGPToGg2ZpXzAd4oCMQtvcpaNNFlmucb2hy8lJ9OVYppDgGyD9l43LQPFeSclzlmOGhoQGrzT+mLWwzoKTA6cTqrE4Yu3oVnVPlRvOyPBeitlkzvFbnonnR68cgYB+yOx2MQSe/UwD0hm/HCleFL0DSpphyj0WI7n8NqZGLihB8aBIQ2L7XTnaQaemrZKJohCk1U/vnqle0MDkLhjZ/tejMFohMYwCOxQUEQwL4hPdeSGDYgcBE4oYSTHxbXqxlUuxgd3zNZxYJPfbt9Bmz+Uau0Oaefv0+pjOhqylbqGzJ8xpDswxS9K3BHwBAweVMOnbaZ/zJREl3YHPzrDKIhnSEg2AJSmOhogdN+9RDBfwX9Sp2N6LwQIFneou4wN9sA8CELCMEBvzePDQ8rgRGduStr+cV1ZAICV5wMqzbe4xlK2eWjLdq7cWCB7v0r7x4zvYxl+4B1bG0AtD2Ph48ww0QTembkVyQ4k0divTiebAe4vafexW1nS0esJh15VPJ1+MDA0IaJoRPchAQTXWLKfLJwzjdUNvtkxetE6fICdWCfL7G5ixg4LjWlgCPx2X8v0DqHxfYabEZh77B/4X8GeXrVeDMr+DSSBQhRbYNEpOar17goA+v0OtEMygnR0TTrLj9YqBTznzkOQ38WzslUDJZNH8ZI6bS5a0zB4gvbEaHJU1R2CQhsmWYTFmpAjOp8XmBX6IMDqfoaDVDFDs0MQNEI9WItlzSNyl1t1OfvYCZgZRWVF0zZ/HaD3psV0qTr9EnxagjbN64BxH+JsHzFZjZX0WTDxvApWd/NLtXnZocT0jFzBoCB6l2Loh5C/DxXmzxTkjmRJm6BXlPyFDIMJXEU/1ClxZYQxiARLbLSJKSMz5ipaFZFe8WallRf1T7rkLFWV+l7dTv42lePfku7uyQkCrywnTNY7PE37eYBO6fFsZfgyP0JpL0AsMYWGmijqQ6x8RAHgARSRV8t3dySTzeBBnFAiJT8OT9v6Di7B1RSpd87jl9CKBVlJ26BfQuSY35mJrtoHB3PKCBmAdCk1KWZU2GuIKSTugKRpjoRioq0EHHwHxZO7bEb6zbQ6uBOmFWObEttB0Aqk+fDudPw3h6Ax4t6VosrKl+SbAjA4SA8qRLeWLLPZY1H0AIyPibPG9W48mmgWMJ7WzRbg2K3r4o0RqBzicql7838hID3H5S9mMJgYzeVYqIzzWIIMIqUYuPznL3x1CUlKSw+gR9LNIx9gb7HL5b1JObnVFAe3eE7/EZKdsAjBPdEUHXOx5EgIDjPRLOpfbU9//f8+Ab09GW2v9heukjl22ykgxincT2HRH9C0NTS2Y5b1W1xxK/I99OEhlaFdKMZ5ZR8TNKZImPAmg3HrsM2qCeIZMVQ/BoWhHopTgXHCG3+RMwXgAE0LlRzQ3mgeE6FuQ/ijVB6Mm3Tw63E2/lU/r3dJ21zZQJY+AAM+HMIagxlB6AtPaPZ2xz8/SI82rX0dHr9ElS+8zQahSzSjM+4OO+IBOiVIVgW4YvfzxOEEuu6G/5Em1ewUmvEsuK5ZGu9QsyzYBunj3goq+G0ZnyT36CBF/fYqe8ZRdWEqcI/QpFAAZrLaaWUE22x4OsmOopwdDK66kSIua5sqKpqFD4EJph/kLLFcgsNRz6Rc5xIZC+Nrt+Ag40LzmnT3UXo3nnJ8BjSWnU/eXm16N9GdJUQ0FTD0QRsiR2IVXt9KYKeUcAUWxt4AmETLKeGHipXlteZgxv9+YN2Troa2EC3g36cacIPmQ4E5EvpDedE9seYL8FLyFDGeJWI732gb/KFoQeEgH6FuW4yxh2SshGIU5rk4RLKnKcJx66mG7i+2qYk1/B4QjtRvM67Le8PJp8fBwa2DUW+DvVPFdVQEOnTlKKSGB0CLVpDIdRQ2kKiR0EM+Q9t9hAS/jA62CJfKp3GZPsVMFvC0o30ECdTaQ2Un0kkTN3ApYQSMHTkLfMZyHQx8XuWbT6BSWsReWCo1bHh3yMI0N+RAOw5rC+HaYbrEqhbNxx/u/uq/cvOLoO1STla3e4PRdRjOj80iNw6DATNz4XqUmV/4gJbwi6g5SpaxTo7U3YY24hUI6BXM0oNaYdajHyAQ6+1GAcAE+YetoJPhEZJzxSIAZPLRGzz+hd95ex+AlJezBe4R12mpnJkPIUkLGkgHHL6pG9tg/mZ78pjffXXH5yTtpYN0d7zcx/SytEFoYy4JZs5DpyZUaVDzHddhYQIcjM3p3uPA6CGD1T/JgKogE5QZB9SgursMi3PL57lvJu/TC4lVzRGcK3lzMQb3GmoPw/3fcObINll+tISn7MDN4XoQmDnKS/7/I/IJhEwN3KeXrJuydkTd/MGdnXf/mplDypLwBdBefDxe+Wh1MDzLRGchQp8oBShkxwbLZPgWVZpoIxN0PDzk0V8AOa4EdjrIeERDH1AjCNSgh5Mhdd5j89UWtesh41AxIciAFUZSDwmwLCW45jgyvSwXmYpKWvJ3mXe9DvUI18dA8MhnBjx4Y0bMmN9m582IJ3v5/rj9y3H96GOJPDqeCjqlu01VnbvP/1dyFc65YsJWQ2vRMA0sTI4ZMa54oefd3g4g6bVorE/wnCZKEczaZhgueyVlTNbv5WP8NbuO2J3EXg9ESjt8W+z1j6EdTKZTo8vnItRm7W/ROhY1MSTzgkx56NC1JxcymjJiL/LJf3uw897/OAJ79PkloFPanby/u1it75R57yV2uVlPsoohnAAL18N2CBBkJiXLSXaGxq24rYARiuott8huuOxDJgiTEZoFOg0Z/N6QD5Z9ken1fUTHpuOuWgID6EMlsCKVxRtkLIgEraJoV6iGVU85TYfOF3Tkudp45+7j23/lDEdgjz6/FLQNNifvPVjsX3Mv5xW+Yj6qNWFRgwaSNDuTul+REnaZgbyA+4jVXbKaAMyAdIQGJT5yrGhPNRleAMUFA7wh6bHqQq6d8TNLHixyjXEp4lVu5vMB4xgWvMNw7ELgnw5LF4vasemBsdRvKA1vkj7+cHPzPzPcs7dU0fqpx+PxO3cWe9eYorlsvqMtqeqyVzfHcyelxyVs+lCfO5oACWf8x6FuI/UwQ69CpLGAe9qlysB9BLaLHVl0IKezgMv2y5TzZIQ2WfseFb37agjyNZOGjuCcHhvwjG/U50HC9nTvL6fTh2aMTz2eKemjHpuTdz5YGF4fIwGA838ORQFA5QVEp2ZqNpWHklJv+OuIbOG2VGcIDTah48EE5WJGIQfVnDh1tsA/ISJuNniVqi1O4Q+s/VLkmN0ioaXCSGvBBveBDzfoiHUwaNY+2Jkc/Je9vft3j2h/2udzgbbj1vjdO2zIeVBl/TXq7fM4ICuXyizMG80q+ti1+W53BWIO46wqHvqghuCayX4In1Ku3/Ge/5ShuqGO9pZY7w8w+oM6n75XZ+P/G0DjvxAhajAjjRhDBTCFcYdxcfujxzs/n04ffKmEjxjw3KDtsD352wf96txttgQvUh3m/yrRLYd2eVst54OfFqHt0OXqlASD0w4WxAIKdQE50jlkhFL3iRkpLFkHj7mq5SJVS3CgZE/aB9N09xck4fdIbncQOY97ZyQl5PxtzUOKeo//QIffNuS/ubf1/v9he8nn9otJ1NOOrwTaAXYmt/ceT7J3lqtlV2+rwMDJqGa4JTDOZpP/zcntdjY9wD7x6HgbnZ1ajulhGrCAAMwF16ZsrCA4wB5+iMLPQ1YAT4g0Q5n9di9/+D8PpgcHJT/Lh3+k0Ps+IQF4bw8nz5o93xynvfc2dx7cZoIveGnpfdqhaL72cXbup2vzRfZdBPQy6o5nMfGd3d1rtv7q/t4vtKtyLX27v5/q/tnh/IigzHOp/OysnY18kOSvr8iwKpZk8yzORhhqWZij1/u/3qt/+5sDmIkN8BSmLfr9RbjF+hWHvuBPtur+1v29+Ycp3fL3mV/peCHQhzOVF/o/vFZWg9cR3nk0G7HUu/zg6r9/sLWJyv3icyrHlszFQf/U91kgmTf3eLw95IFwhe2ag27PJo9/eW9664P5eZx0M6r29tgRORiUsbt2sNIsVFvje/d23dYsWJ3YVz6OA/TRpOXa4M1LvWL+ZfYxrBOPFyhwPCTevptV7f16ws4EHBHL4fM8zHqJpciAsIUs0ZGs2eH/lLwzObj3zoP0gTt3yZ0jDSjm5thFTSt8+fjRo0fWxV3dfi2w9IvjOEEfjck+ix8s1MNsZZTa9TIrVvG8I3STh3mcART9PcC02cIx25o0k/vT8aN7m+m2v43W+AF8mo/7KEKkt9qq5Qu/H8txIqCfoIxCxUZ5Ol2oZmmXIFdQYr2LtO4osSMw0nHkVAV3JMmjzyeGfLGvfwc7xKMiheWKzQAAAABJRU5ErkJggg==" @default_style %{ primary: "#4e2a8e", accent: "#607080", highlight: "#f0f4fa", red_highlight: "#ffe5e5", line_color: "#eee", text_color: "#203040", logo: @logo, monospace_font: "menlo, consolas, monospace" } import Plug.Conn require Logger @doc false defmacro __using__(opts) do quote do @plug_debugger unquote(opts) @before_compile Plug.Debugger end end @doc false defmacro __before_compile__(_) do quote location: :keep do defoverridable call: 2 def call(conn, opts) do try do super(conn, opts) rescue e in Plug.Conn.WrapperError -> %{conn: conn, kind: kind, reason: reason, stack: stack} = e Plug.Debugger.__catch__(conn, kind, reason, stack, @plug_debugger) catch kind, reason -> Plug.Debugger.__catch__(conn, kind, reason, System.stacktrace(), @plug_debugger) end end end end @doc false def __catch__(conn, kind, reason, stack, opts) do reason = Exception.normalize(kind, reason, stack) status = status(kind, reason) receive do @already_sent -> send(self(), @already_sent) log(status, kind, reason, stack) :erlang.raise(kind, reason, stack) after 0 -> render(conn, status, kind, reason, stack, opts) log(status, kind, reason, stack) :erlang.raise(kind, reason, stack) end end # We don't log status >= 500 because those are treated as errors and logged later. defp log(status, kind, reason, stack) when status < 500, do: Logger.debug(Exception.format(kind, reason, stack)) defp log(_status, _kind, _reason, _stack), do: :ok ## Rendering require EEx html_template_path = "lib/plug/templates/debugger.html.eex" EEx.function_from_file(:defp, :template_html, html_template_path, [:assigns]) markdown_template_path = "lib/plug/templates/debugger.md.eex" EEx.function_from_file(:defp, :template_markdown, markdown_template_path, [:assigns]) # Made public with @doc false for testing. @doc false def render(conn, status, kind, reason, stack, opts) do session = maybe_fetch_session(conn) params = maybe_fetch_query_params(conn) {title, message} = info(kind, reason) style = Enum.into(opts[:style] || [], @default_style) banner = banner(conn, status, kind, reason, stack, opts) if accepts_html?(get_req_header(conn, "accept")) do conn = put_resp_content_type(conn, "text/html") assigns = [ conn: conn, frames: frames(stack, opts), title: title, message: message, session: session, params: params, style: style, banner: banner ] send_resp(conn, status, template_html(assigns)) else # TODO: Remove exported check once we depend on Elixir v1.5 only {reason, stack} = if function_exported?(Exception, :blame, 3) do apply(Exception, :blame, [kind, reason, stack]) else {reason, stack} end conn = put_resp_content_type(conn, "text/markdown") assigns = [ conn: conn, title: title, formatted: Exception.format(kind, reason, stack), session: session, params: params ] send_resp(conn, status, template_markdown(assigns)) end end defp accepts_html?(_accept_header = []), do: false defp accepts_html?(_accept_header = [header | _]), do: String.contains?(header, ["*/*", "text/*", "text/html"]) defp maybe_fetch_session(conn) do if conn.private[:plug_session_fetch] do conn |> fetch_session(conn) |> get_session() end end defp maybe_fetch_query_params(conn) do fetch_query_params(conn).params rescue Plug.Conn.InvalidQueryError -> case conn.params do %Plug.Conn.Unfetched{} -> %{} params -> params end end defp status(:error, error), do: Plug.Exception.status(error) defp status(_, _), do: 500 defp info(:error, error), do: {inspect(error.__struct__), Exception.message(error)} defp info(:throw, thrown), do: {"unhandled throw", inspect(thrown)} defp info(:exit, reason), do: {"unhandled exit", Exception.format_exit(reason)} defp frames(stacktrace, opts) do app = opts[:otp_app] editor = System.get_env("PLUG_EDITOR") stacktrace |> Enum.map_reduce(0, &each_frame(&1, &2, app, editor)) |> elem(0) end defp each_frame(entry, index, root, editor) do {module, info, location, app, fun, arity, args} = get_entry(entry) {file, line} = {to_string(location[:file] || "nofile"), location[:line]} doc = module && get_doc(module, fun, arity, app) clauses = module && get_clauses(module, fun, args) source = get_source(module, file) context = get_context(root, app) snippet = get_snippet(source, line) {%{ app: app, info: info, file: file, line: line, context: context, snippet: snippet, index: index, doc: doc, clauses: clauses, args: args, link: editor && get_editor(source, line, editor) }, index + 1} end # From :elixir_compiler_* defp get_entry({module, :__MODULE__, 0, location}) do {module, inspect(module) <> " (module)", location, get_app(module), nil, nil, nil} end # From :elixir_compiler_* defp get_entry({_module, :__MODULE__, 1, location}) do {nil, "(module)", location, nil, nil, nil, nil} end # From :elixir_compiler_* defp get_entry({_module, :__FILE__, 1, location}) do {nil, "(file)", location, nil, nil, nil, nil} end defp get_entry({module, fun, args, location}) when is_list(args) do arity = length(args) formatted_mfa = Exception.format_mfa(module, fun, arity) {module, formatted_mfa, location, get_app(module), fun, arity, args} end defp get_entry({module, fun, arity, location}) do {module, Exception.format_mfa(module, fun, arity), location, get_app(module), fun, arity, nil} end defp get_entry({fun, arity, location}) do {nil, Exception.format_fa(fun, arity), location, nil, fun, arity, nil} end defp get_app(module) do case :application.get_application(module) do {:ok, app} -> app :undefined -> nil end end defp get_doc(module, fun, arity, app) do with true <- has_docs?(module, fun, arity), {:ok, vsn} <- :application.get_key(app, :vsn) do vsn = vsn |> List.to_string() |> String.split("-") |> hd() fun = fun |> Atom.to_string() |> URI.encode() "https://hexdocs.pm/#{app}/#{vsn}/#{inspect(module)}.html##{fun}/#{arity}" else _ -> nil end end # TODO: Remove exported check once we depend on Elixir v1.7+ if Code.ensure_loaded?(Code) and function_exported?(Code, :fetch_docs, 1) do def has_docs?(module, name, arity) do case Code.fetch_docs(module) do {:docs_v1, _, _, _, module_doc, _, docs} when module_doc != :hidden -> Enum.any?(docs, has_doc_matcher?(name, arity)) _ -> false end end defp has_doc_matcher?(name, arity) do &match?( {{kind, ^name, ^arity}, _, _, doc, _} when kind in [:function, :macro] and doc != :hidden, &1 ) end else def has_docs?(module, fun, arity) do docs = Code.get_docs(module, :docs) not is_nil(docs) and List.keymember?(docs, {fun, arity}, 0) end end defp get_clauses(module, fun, args) do # TODO: Remove exported check once we depend on Elixir v1.5 only with true <- is_list(args) and function_exported?(Exception, :blame_mfa, 3), {:ok, kind, clauses} <- apply(Exception, :blame_mfa, [module, fun, args]) do top_10 = clauses |> Enum.take(10) |> Enum.map(fn {args, guards} -> code = Enum.reduce(guards, {fun, [], args}, &{:when, [], [&2, &1]}) "#{kind} " <> Macro.to_string(code, &clause_match/2) end) {length(top_10), length(clauses), top_10} else _ -> nil end end defp clause_match(%{match?: true, node: node}, _), do: ~s(<i class="green">) <> h(Macro.to_string(node)) <> "</i>" defp clause_match(%{match?: false, node: node}, _), do: ~s(<i class="red">) <> h(Macro.to_string(node)) <> "</i>" defp clause_match(_, string), do: string defp get_context(app, app) when app != nil, do: :app defp get_context(_app1, _app2), do: :all defp get_source(module, file) do cond do File.regular?(file) -> file source = module && Code.ensure_loaded?(module) && module.module_info(:compile)[:source] -> to_string(source) true -> file end end defp get_editor(file, line, editor) do editor |> :binary.replace("__FILE__", URI.encode(Path.expand(file))) |> :binary.replace("__LINE__", to_string(line)) |> h end @radius 5 defp get_snippet(file, line) do if File.regular?(file) and is_integer(line) do to_discard = max(line - @radius - 1, 0) lines = File.stream!(file) |> Stream.take(line + 5) |> Stream.drop(to_discard) {first_five, lines} = Enum.split(lines, line - to_discard - 1) first_five = with_line_number(first_five, to_discard + 1, false) {center, last_five} = Enum.split(lines, 1) center = with_line_number(center, line, true) last_five = with_line_number(last_five, line + 1, false) first_five ++ center ++ last_five end end defp with_line_number(lines, initial, highlight) do lines |> Enum.map_reduce(initial, fn line, acc -> {{acc, line, highlight}, acc + 1} end) |> elem(0) end defp banner(conn, status, kind, reason, stack, opts) do case Keyword.fetch(opts, :banner) do {:ok, {mod, func, args}} -> apply(mod, func, [conn, status, kind, reason, stack] ++ args) {:ok, other} -> raise ArgumentError, "expected :banner to be an MFA ({module, func, args}), got: #{inspect(other)}" :error -> nil end end ## Helpers defp method(%Plug.Conn{method: method}), do: method defp url(%Plug.Conn{scheme: scheme, host: host, port: port} = conn), do: "#{scheme}://#{host}:#{port}#{conn.request_path}" defp h(string) do string |> to_string() |> Plug.HTML.html_escape() end end
57.853982
12,756
0.79587
087b15098ffbe85931cc60c95d4d3fe7e176cca0
16,047
exs
Elixir
test/game/quest_test.exs
deep-spaced/ex_venture
45848abe509620d6d2643b2a780dab01c1ac523b
[ "MIT" ]
null
null
null
test/game/quest_test.exs
deep-spaced/ex_venture
45848abe509620d6d2643b2a780dab01c1ac523b
[ "MIT" ]
null
null
null
test/game/quest_test.exs
deep-spaced/ex_venture
45848abe509620d6d2643b2a780dab01c1ac523b
[ "MIT" ]
null
null
null
defmodule Game.QuestTest do use Data.ModelCase alias Data.QuestProgress alias Data.QuestStep alias Game.Quest describe "start a quest" do test "creates a new quest progress record" do guard = create_npc(%{is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon"}) user = create_user() assert :ok = Quest.start_quest(user, quest) assert Quest.progress_for(user, quest.id) end end describe "start tracking a quest" do test "marks the quest progress as tracking" do guard = create_npc(%{is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon"}) user = create_user() Quest.start_quest(user, quest) {:ok, _qp} = Quest.track_quest(user, quest.id) {:ok, progress} = Quest.progress_for(user, quest.id) assert progress.is_tracking end test "does nothing if the quest progress is not found" do guard = create_npc(%{is_quest_giver: true}) quest1 = create_quest(guard, %{name: "Into the Dungeon"}) quest2 = create_quest(guard, %{name: "Into the Dungeon Again"}) user = create_user() Quest.start_quest(user, quest1) {:ok, _} = Quest.track_quest(user, quest1.id) {:error, :not_started} = Quest.track_quest(user, quest2.id) {:ok, progress} = Quest.progress_for(user, quest1.id) assert progress.is_tracking end end describe "current step progress" do test "item/collect - no progress on a step yet" do step = %QuestStep{type: "item/collect", item_id: 1} progress = %QuestProgress{progress: %{}} save = %{items: []} assert Quest.current_step_progress(step, progress, save) == 0 end test "item/collect - progress started" do step = %QuestStep{id: 1, type: "item/collect", item_id: 1} progress = %QuestProgress{progress: %{}} save = %{items: [item_instance(1)]} assert Quest.current_step_progress(step, progress, save) == 1 end test "item/give - no progress on a step yet" do step = %QuestStep{type: "item/give", item_id: 1} progress = %QuestProgress{progress: %{}} save = %{} assert Quest.current_step_progress(step, progress, save) == 0 end test "item/give - progress started" do step = %QuestStep{id: 1, type: "item/give", item_id: 1} progress = %QuestProgress{progress: %{step.id => 3}} save = %{} assert Quest.current_step_progress(step, progress, save) == 3 end test "item/have - no progress on a step yet" do step = %QuestStep{type: "item/have", item_id: 1} progress = %QuestProgress{progress: %{}} save = %{items: [], wearing: %{}, wielding: %{}} assert Quest.current_step_progress(step, progress, save) == 0 end test "item/have - progress started" do step = %QuestStep{id: 1, type: "item/have", item_id: 1} progress = %QuestProgress{progress: %{}} save = %{items: [item_instance(1)], wearing: %{chest: item_instance(1)}, wielding: %{}} assert Quest.current_step_progress(step, progress, save) == 2 end test "item/have - progress complete" do step = %QuestStep{id: 1, type: "item/have", item_id: 1, count: 2} progress = %QuestProgress{status: "complete", progress: %{}} save = %{items: [], wearing: %{chest: item_instance(1)}, wielding: %{}} assert Quest.current_step_progress(step, progress, save) == 2 end test "npc/kill - no progress on a step yet" do step = %QuestStep{type: "npc/kill"} progress = %QuestProgress{progress: %{}} save = %{} assert Quest.current_step_progress(step, progress, save) == 0 end test "npc/kill - progress started" do step = %QuestStep{id: 1, type: "npc/kill"} progress = %QuestProgress{progress: %{step.id => 3}} save = %{} assert Quest.current_step_progress(step, progress, save) == 3 end test "room/explore - no progress on a step yet" do step = %QuestStep{type: "room/explore"} progress = %QuestProgress{progress: %{}} save = %{} assert Quest.current_step_progress(step, progress, save) == false end test "room/explore - progress started" do step = %QuestStep{id: 1, type: "room/explore"} progress = %QuestProgress{progress: %{step.id => %{explored: true}}} save = %{} assert Quest.current_step_progress(step, progress, save) == true end end describe "determine if a user has all progress required for a quest" do test "quest complete when all step requirements are met - npc" do step = %QuestStep{id: 1, type: "npc/kill", count: 2} quest = %Data.Quest{quest_steps: [step]} progress = %QuestProgress{progress: %{step.id => 2}, quest: quest} save = %{} assert Quest.requirements_complete?(progress, save) end test "quest complete when all step requirements are met - item" do step = %QuestStep{id: 1, type: "item/collect", count: 2, item_id: 2} quest = %Data.Quest{quest_steps: [step]} progress = %QuestProgress{progress: %{}, quest: quest} save = %{items: [item_instance(2), item_instance(2)]} assert Quest.requirements_complete?(progress, save) end test "quest complete when all step requirements are met - item/give" do step = %QuestStep{id: 1, type: "item/give", count: 2, item_id: 2} quest = %Data.Quest{quest_steps: [step]} progress = %QuestProgress{progress: %{step.id => 2}, quest: quest} save = %{} assert Quest.requirements_complete?(progress, save) end test "quest complete when all step requirements are met - room/explored" do step = %QuestStep{id: 1, type: "room/explore", room_id: 2} quest = %Data.Quest{quest_steps: [step]} progress = %QuestProgress{progress: %{step.id => %{explored: true}}, quest: quest} save = %{} assert Quest.requirements_complete?(progress, save) end end describe "complete a quest" do test "marks the quest progress as complete" do guard = create_npc(%{name: "Guard", is_quest_giver: true}) goblin = create_npc(%{name: "Goblin"}) quest = create_quest(guard, %{name: "Into the Dungeon"}) potion = create_item(%{name: "Potion"}) npc_step = create_quest_step(quest, %{type: "npc/kill", count: 3, npc_id: goblin.id}) create_quest_step(quest, %{type: "item/collect", count: 1, item_id: potion.id}) user = create_user() items = [item_instance(potion.id), item_instance(potion.id), item_instance(potion), item_instance(3)] user = %{user | save: %{user.save | items: items}} create_quest_progress(user, quest, %{progress: %{npc_step.id => 3}}) {:ok, progress} = Quest.progress_for(user, quest.id) # get preloads {:ok, save} = Quest.complete(progress, user.save) assert Data.Repo.get(QuestProgress, progress.id).status == "complete" assert save.items |> length() == 3 end end describe "track progress - npc kill" do setup do user = create_user() goblin = create_npc(%{name: "Goblin"}) %{user: user, goblin: goblin} end test "no current quest that matches", %{user: user, goblin: goblin} do assert :ok = Quest.track_progress(user, {:npc, goblin}) end test "updates any quest progresses that match the user and the npc", %{user: user, goblin: goblin} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) npc_step = create_quest_step(quest, %{type: "npc/kill", count: 3, npc_id: goblin.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:npc, goblin}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{npc_step.id => 1} end test "ignores steps if they do not match the npc being passed in", %{user: user, goblin: goblin} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) create_quest_step(quest, %{type: "npc/kill", count: 3, npc_id: goblin.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:npc, guard}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{} end end describe "track progress - exploring a room" do setup do user = create_user() zone = create_zone() room = create_room(zone, %{name: "Goblin Hideout"}) %{user: user, room: room} end test "no current quest that matches", %{user: user, room: room} do assert :ok = Quest.track_progress(user, {:room, room.id}) end test "moving in the overworld", %{user: user} do assert :ok = Quest.track_progress(user, {:room, "overworld:1:1,1,"}) end test "updates any quest progresses that match the user and the room", %{user: user, room: room} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) npc_step = create_quest_step(quest, %{type: "room/explore", room_id: room.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:room, room.id}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{npc_step.id => %{explored: true}} end test "ignores steps if they do not match the room being passed in", %{user: user, room: room} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) create_quest_step(quest, %{type: "room/explore", room_id: room.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:room, -1}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{} end end describe "track progress - give an item to an npc" do setup do user = create_user() baker = create_npc(%{name: "Baker"}) flour = create_item(%{name: "Flour"}) flour_instance = item_instance(flour.id) %{user: user, baker: baker, flour: flour_instance} end test "no current quest that matches", %{user: user, baker: baker, flour: flour} do assert :ok = Quest.track_progress(user, {:item, flour, baker}) end test "updates any quest progresses that match the user, the npc, and the item", %{user: user, baker: baker, flour: flour} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) npc_step = create_quest_step(quest, %{type: "item/give", count: 3, item_id: flour.id, npc_id: baker.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:item, flour, baker}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{npc_step.id => 1} end test "ignores steps if they do not match the npc being passed in", %{user: user, baker: baker, flour: flour} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) create_quest_step(quest, %{type: "item/give", count: 3, item_id: flour.id, npc_id: baker.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:item, flour, guard}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{} end test "ignores steps if they do not match the item being passed in", %{user: user, baker: baker, flour: flour} do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest = create_quest(guard, %{name: "Into the Dungeon", experience: 200}) create_quest_step(quest, %{type: "item/give", count: 3, item_id: flour.id, npc_id: baker.id}) quest_progress = create_quest_progress(user, quest) assert :ok = Quest.track_progress(user, {:item, item_instance(0), baker}) quest_progress = Data.Repo.get(QuestProgress, quest_progress.id) assert quest_progress.progress == %{} end end describe "next available quest" do test "find the next quest available from an NPC" do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest1 = create_quest(guard, %{name: "Root 1"}) quest2 = create_quest(guard, %{name: "Root 2"}) quest3 = create_quest(guard, %{name: "Child Root 1"}) create_quest_relation(quest3, quest1) quest4 = create_quest(guard, %{name: "Child Root 2"}) create_quest_relation(quest4, quest2) quest5 = create_quest(guard, %{name: "Child Child Root 1"}) create_quest_relation(quest5, quest3) user = create_user() {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest1.id create_quest_progress(user, quest1, %{status: "complete"}) {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest2.id create_quest_progress(user, quest2, %{status: "complete"}) {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest3.id create_quest_progress(user, quest3, %{status: "complete"}) {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest4.id create_quest_progress(user, quest4, %{status: "complete"}) {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest5.id create_quest_progress(user, quest5, %{status: "complete"}) assert {:error, :no_quests} = Quest.next_available_quest_from(guard, user) end test "stops if a parent quest is not complete" do guard = create_npc(%{name: "Guard", is_quest_giver: true}) quest1 = create_quest(guard, %{name: "Root 1"}) quest2 = create_quest(guard, %{name: "Root 2"}) quest3 = create_quest(guard, %{name: "Child Root 1"}) create_quest_relation(quest3, quest1) create_quest_relation(quest3, quest2) user = create_user() {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest1.id create_quest_progress(user, quest1, %{status: "complete"}) {:ok, next_quest} = Quest.next_available_quest_from(guard, user) assert next_quest.id == quest2.id create_quest_progress(user, quest2, %{status: "active"}) assert {:error, :no_quests} = Quest.next_available_quest_from(guard, user) end test "can find a quest that is in the middle of a quest chain" do guard = create_npc(%{name: "Guard", is_quest_giver: true}) captain = create_npc(%{name: "Captain", is_quest_giver: true}) quest1 = create_quest(guard, %{name: "Root 1"}) quest2 = create_quest(guard, %{name: "Root 2"}) quest3 = create_quest(captain, %{name: "Child Root 1"}) create_quest_relation(quest3, quest1) user = create_user() create_quest_progress(user, quest1, %{status: "complete"}) create_quest_progress(user, quest2, %{status: "complete"}) {:error, :no_quests} = Quest.next_available_quest_from(guard, user) {:ok, next_quest} = Quest.next_available_quest_from(captain, user) assert next_quest.id == quest3.id end test "does not give out a quest if you are below its level" do guard = create_npc(%{name: "Guard", is_quest_giver: true}) create_quest(guard, %{level: 2}) user = create_user() {:error, :no_quests} = Quest.next_available_quest_from(guard, user) end end end
37.846698
128
0.653269
087b2292b94c5dfd7b50a4f401630764c504fd77
1,094
ex
Elixir
lib/jeff_bank_web/channels/user_socket.ex
jeffersono7/jeffbank
b817b298ed2729fb0f458e19807b1503681ffb1d
[ "BSD-2-Clause" ]
null
null
null
lib/jeff_bank_web/channels/user_socket.ex
jeffersono7/jeffbank
b817b298ed2729fb0f458e19807b1503681ffb1d
[ "BSD-2-Clause" ]
null
null
null
lib/jeff_bank_web/channels/user_socket.ex
jeffersono7/jeffbank
b817b298ed2729fb0f458e19807b1503681ffb1d
[ "BSD-2-Clause" ]
null
null
null
defmodule JeffBankWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", JeffBankWeb.RoomChannel # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. @impl true def connect(_params, socket, _connect_info) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # JeffBankWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.388889
83
0.695612
087b230da7239e121db6d58b20c07082589338d6
3,956
ex
Elixir
deps/plug/lib/plug/ssl.ex
renatoalmeidaoliveira/Merlin
92a0e318872190cdfa07ced85ee54cc69cad5c14
[ "Apache-2.0" ]
null
null
null
deps/plug/lib/plug/ssl.ex
renatoalmeidaoliveira/Merlin
92a0e318872190cdfa07ced85ee54cc69cad5c14
[ "Apache-2.0" ]
null
null
null
deps/plug/lib/plug/ssl.ex
renatoalmeidaoliveira/Merlin
92a0e318872190cdfa07ced85ee54cc69cad5c14
[ "Apache-2.0" ]
null
null
null
defmodule Plug.SSL do @moduledoc """ A plug to force SSL connections. If the scheme of a request is `https`, it'll add a `strict-transport-security` header to enable HTTP Strict Transport Security. Otherwise, the request will be redirected to a corresponding location with the `https` scheme by setting the `location` header of the response. The status code will be 301 if the method of `conn` is `GET` or `HEAD`, or 307 in other situations. ## x-forwarded-proto If your Plug application is behind a proxy that handles HTTPS, you will need to tell Plug to parse the proper protocol from the `x-forwarded-proto` header. This can be done using the `:rewrite_on` option: plug Plug.SSL, rewrite_on: [:x_forwarded_proto] The command above will effectively change the value of `conn.scheme` by the one sent in `x-forwarded-proto`. Since rewriting the scheme based on `x-forwarded-proto` can open up security vulnerabilities, only provide the option above if: * your app is behind a proxy * your proxy strips `x-forwarded-proto` headers from all incoming requests * your proxy sets the `x-forwarded-proto` and sends it to Plug ## Options * `:rewrite_on` - rewrites the scheme to https based on the given headers * `:hsts` - a boolean on enabling HSTS or not, defaults to true. * `:expires` - seconds to expires for HSTS, defaults to 31536000 (a year). * `:subdomains` - a boolean on including subdomains or not in HSTS, defaults to false. * `:host` - a new host to redirect to if the request's scheme is `http`, defaults to `conn.host`. It may be set to a binary or a tuple `{module, function, args}` that will be invoked on demand ## Port It is not possible to directly configure the port in `Plug.SSL` because HSTS expects the port to be 443 for SSL. If you are not using HSTS and wants to redirect to HTTPS on another port, you can sneak it alongside the host, for example: `host: "example.com:443"`. """ @behaviour Plug import Plug.Conn alias Plug.Conn def init(opts) do {hsts_header(opts), Keyword.get(opts, :host), Keyword.get(opts, :rewrite_on, [])} end def call(conn, {hsts, host, rewrites}) do conn = rewrite_on(conn, rewrites) if conn.scheme == :https do put_hsts_header(conn, hsts) else redirect_to_https(conn, host) end end defp rewrite_on(conn, rewrites) do Enum.reduce rewrites, conn, fn :x_forwarded_proto, acc -> if get_req_header(acc, "x-forwarded-proto") == ["https"] do %{acc | scheme: :https} else acc end other, _acc -> raise "unknown rewrite: #{inspect other}" end end # http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02 defp hsts_header(opts) do if Keyword.get(opts, :hsts, true) do expires = Keyword.get(opts, :expires, 31_536_000) subdomains = Keyword.get(opts, :subdomains, false) "max-age=#{expires}" <> if(subdomains, do: "; includeSubDomains", else: "") end end defp put_hsts_header(conn, hsts_header) when is_binary(hsts_header) do put_resp_header(conn, "strict-transport-security", hsts_header) end defp put_hsts_header(conn, _), do: conn defp redirect_to_https(%Conn{host: host} = conn, custom_host) do status = if conn.method in ~w(HEAD GET), do: 301, else: 307 location = "https://" <> host(custom_host, host) <> conn.request_path <> qs(conn.query_string) conn |> put_resp_header("location", location) |> send_resp(status, "") |> halt end defp host(nil, host), do: host defp host(host, _) when is_binary(host), do: host defp host({mod, fun, args}, host), do: host(apply(mod, fun, args), host) # TODO: Deprecate this format defp host({:system, env}, host), do: host(System.get_env(env), host) defp qs(""), do: "" defp qs(qs), do: "?" <> qs end
33.811966
85
0.67088
087b2c9c34291895393998d46d64ae8f3a6acef3
1,921
exs
Elixir
test/elixir_google_spreadsheets/client/limiter_test.exs
trusty/elixir_google_spreadsheets
b7f74d75e61027dc0b12aa5260168563d0777c92
[ "MIT" ]
50
2016-12-21T06:39:08.000Z
2022-03-16T04:52:42.000Z
test/elixir_google_spreadsheets/client/limiter_test.exs
trusty/elixir_google_spreadsheets
b7f74d75e61027dc0b12aa5260168563d0777c92
[ "MIT" ]
36
2017-01-31T19:12:19.000Z
2022-03-10T17:27:58.000Z
test/elixir_google_spreadsheets/client/limiter_test.exs
nested-tech/elixir_google_spreadsheets
45895fe6ac5bc9f256bc2e271be1a3324ce8aded
[ "MIT" ]
34
2017-01-16T04:22:16.000Z
2022-03-01T01:46:39.000Z
defmodule GSS.Client.LimiterTest do use ExUnit.Case, async: true alias GSS.Client.Limiter alias GSS.StubModules.{Producer, Consumer} setup context do {:ok, client} = Producer.start_link([]) {:ok, limiter} = GenStage.start_link( Limiter, name: context.test, clients: [client], max_demand: 3, max_interval: 500, interval: 0 ) {:ok, _consumer} = Consumer.start_link(limiter) [client: client, limiter: limiter] end test "receive events in packs with limits", %{client: client} do GenStage.call(client, {:add, [1, 2, 3, 4, 5]}) assert_receive {:handled_demand, [1, 2, 3], 3} refute_receive {:handled_demand, [4, 5], 3}, 400, "error waiting limits" assert_receive {:handled_demand, [4, 5], 3}, 200 assert_receive {:handled_demand, [], 3} GenStage.call(client, {:add, [6, 7, 8, 9]}) assert_receive {:handled_demand, [6, 7, 8], 3} refute_receive {:handled_demand, [9], 3}, 400, "error waiting limits" assert_receive {:handled_demand, [9], 3}, 200 assert_receive {:handled_demand, [], 3} end test "receive events with limits", %{client: client} do GenStage.call(client, {:add, [1]}) assert_receive {:handled_demand, [1], 3} GenStage.call(client, {:add, [2]}) assert_receive {:handled_demand, [2], 3} GenStage.call(client, {:add, [3]}) assert_receive {:handled_demand, [3], 3} GenStage.call(client, {:add, [4]}) GenStage.call(client, {:add, [5]}) refute_receive {:handled_demand, [4, 5], 3}, 400, "error waiting limits" assert_receive {:handled_demand, [4, 5], 3}, 200 end test "receive events in expired interval", %{client: client} do GenStage.call(client, {:add, [1]}) assert_receive {:handled_demand, [1], 3} Process.sleep(500) GenStage.call(client, {:add, [2]}) assert_receive {:handled_demand, [2], 3} end end
28.25
76
0.628839
087b41a3ab07c15273a2040aac537f288e31a3dd
985
ex
Elixir
lib/orders/create_or_update.ex
LuizFerK/Exlivery
22c91a2ae71506f694b7d7213bf8343b9201cce1
[ "MIT" ]
1
2022-03-16T20:41:39.000Z
2022-03-16T20:41:39.000Z
lib/orders/create_or_update.ex
LuizFerK/Exlivery
22c91a2ae71506f694b7d7213bf8343b9201cce1
[ "MIT" ]
null
null
null
lib/orders/create_or_update.ex
LuizFerK/Exlivery
22c91a2ae71506f694b7d7213bf8343b9201cce1
[ "MIT" ]
null
null
null
defmodule Exlivery.Orders.CreateOrUpdate do alias Exlivery.Orders.Agent, as: OrderAgent alias Exlivery.Orders.{Item, Order} alias Exlivery.Users.Agent, as: UserAgent def call(%{user_cpf: user_cpf, items: items}) do with {:ok, user} <- UserAgent.get(user_cpf), {:ok, items} <- build_items(items), {:ok, order} <- Order.build(user, items) do OrderAgent.save(order) else error -> error end end defp build_items(items) do items |> Enum.map(&build_item/1) |> handle_build() end defp build_item(%{ description: description, category: category, unity_price: unity_price, quantity: quantity }) do case Item.build(description, category, unity_price, quantity) do {:ok, item} -> item {:error, _reason} = error -> error end end defp handle_build(items) do if Enum.all?(items, &is_struct/1), do: {:ok, items}, else: {:error, "Invalid items"} end end
25.921053
88
0.627411
087b4ea59ba255383e4f9abdcffc0b0413787093
328
exs
Elixir
priv/repo/migrations/20150428072308_change_to_jsonb.exs
findmypast/hexfmp
38a50f5e1057833fd98748faac230bf4b9cc26a3
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20150428072308_change_to_jsonb.exs
findmypast/hexfmp
38a50f5e1057833fd98748faac230bf4b9cc26a3
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20150428072308_change_to_jsonb.exs
findmypast/hexfmp
38a50f5e1057833fd98748faac230bf4b9cc26a3
[ "Apache-2.0" ]
null
null
null
defmodule Hexpm.Repo.Migrations.ChangeToJsonb do use Ecto.Migration def up do execute """ ALTER TABLE packages ALTER COLUMN meta TYPE jsonb USING meta::text::jsonb """ end def down do execute """ ALTER TABLE packages ALTER COLUMN meta TYPE json USING meta::text::json """ end end
18.222222
58
0.658537
087b75b605bf2d79c80dd8d0aac1a5d85223e725
1,275
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/accelerator_type_list.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/accelerator_type_list.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/accelerator_type_list.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Compute.V1.Model.AcceleratorTypeList do @moduledoc """ Contains a list of accelerator types. """ @derive [Poison.Encoder] defstruct [ :"id", :"items", :"kind", :"nextPageToken", :"selfLink" ] end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.AcceleratorTypeList do import GoogleApi.Compute.V1.Deserializer def decode(value, options) do value |> deserialize(:"items", :list, GoogleApi.Compute.V1.Model.AcceleratorType, options) end end
29.651163
88
0.735686
087b8e363aa66a5f515a16d866ec8747af96c7e3
1,614
ex
Elixir
lib/ecto/adapter/migration.ex
rbishop/ecto
a8a3215c9e2e35f7556f54c8d47d78a3670796d8
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapter/migration.ex
rbishop/ecto
a8a3215c9e2e35f7556f54c8d47d78a3670796d8
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapter/migration.ex
rbishop/ecto
a8a3215c9e2e35f7556f54c8d47d78a3670796d8
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Adapter.Migration do @moduledoc """ Specifies the adapter migrations API. """ use Behaviour alias Ecto.Migration.Table alias Ecto.Migration.Index alias Ecto.Migration.Reference @typedoc "All migration commands" @type command :: raw :: String.t | {:create, Table.t, [table_subcommand]} | {:create_if_not_exists, Table.t, [table_subcommand]} | {:alter, Table.t, [table_subcommand]} | {:drop, Table.t} | {:drop_if_exists, Table.t} | {:create, Index.t} | {:create_if_not_exists, Index.t} | {:drop, Index.t} | {:drop_if_exists, Index.t} @typedoc "All commands allowed within the block passed to `table/2`" @type table_subcommand :: {:add, field :: atom, type :: Ecto.Type.t | Reference.t, Keyword.t} | {:modify, field :: atom, type :: Ecto.Type.t | Reference.t, Keyword.t} | {:remove, field :: atom} @typedoc """ A DDL object is a struct that represents a table or index in a database schema. These database objects can be modified through the use of a Data Definition Language, hence the name DDL object. """ @type ddl_object :: Table.t | Index.t @doc """ Checks if the adapter supports ddl transaction. """ defcallback supports_ddl_transaction? :: boolean @doc """ Executes migration commands. ## Options * `:timeout` - The time in milliseconds to wait for the call to finish, `:infinity` will wait indefinitely (default: 5000); * `:log` - When false, does not log begin/commit/rollback queries """ defcallback execute_ddl(Ecto.Repo.t, command, Keyword.t) :: :ok | no_return end
29.345455
87
0.671623
087ba10c4b19a0d402db4b10a9d1c3f453f367f3
5,747
ex
Elixir
lib/tzdata/parser.ex
hoyon/tzdata
28b470c5ca0ce80d67e1606b5839adb13e1375a8
[ "MIT" ]
1
2020-01-31T10:23:37.000Z
2020-01-31T10:23:37.000Z
lib/tzdata/parser.ex
hoyon/tzdata
28b470c5ca0ce80d67e1606b5839adb13e1375a8
[ "MIT" ]
1
2018-12-30T12:15:35.000Z
2018-12-30T12:15:35.000Z
lib/tzdata/parser.ex
hoyon/tzdata
28b470c5ca0ce80d67e1606b5839adb13e1375a8
[ "MIT" ]
2
2020-09-08T08:16:34.000Z
2020-10-26T01:53:39.000Z
defmodule Tzdata.Parser do @moduledoc false require Tzdata.Util import Tzdata.Util def read_file(file_name, dir_prepend) do File.stream!("#{dir_prepend}/#{file_name}") |> process_file end def process_file(file_stream) do file_stream |> filter_comment_lines |> filter_empty_lines |> Stream.map(fn string -> strip_comment(string) end) # Strip comments at line end. Like this comment. |> Enum.to_list |> process_tz_list end def process_tz_list([]), do: [] def process_tz_list([ head | tail ]) do split = String.split(head, ~r{\s}) case hd(split) do "Rule" -> [process_rule(head)|process_tz_list(tail)] "Link" -> [process_link(head)|process_tz_list(tail)] "Zone" -> process_zone([head|tail]) ______ -> [head|process_tz_list(tail)] # pass through end end def process_rule(line) do rule_regex = ~r/Rule[\s]+(?<name>[^\s]+)[\s]+(?<from>[^\s]+)[\s]+(?<to>[^\s]+)[\s]+(?<type>[^\s]+)[\s]+(?<in>[^\s]+)[\s]+(?<on>[^\s]+)[\s]+(?<at>[^\s]+)[\s]+(?<save>[^\s]+)[\s]+(?<letter>[^\n]+)/ captured = Regex.named_captures(rule_regex, line) captured = %{name: captured["name"], from: captured["from"] |> to_int, to: captured["to"] |> process_rule_to, type: captured["type"], # we don't use this column for anything in: captured["in"] |> month_number_for_month_name, on: captured["on"], at: captured["at"] |> transform_rule_at, save: captured["save"] |> string_amount_to_secs, letter: captured["letter"]} Map.merge(captured, %{record_type: :rule}) end # process "to" value of rule defp process_rule_to("only"), do: :only defp process_rule_to("max"), do: :max defp process_rule_to(val), do: val |> to_int def process_link(line) do link_regex = ~r/Link[\s]+(?<from>[^\s]+)[\s]+(?<to>[^\s]+)/ captured = Regex.named_captures(link_regex, line) %{record_type: :link, from: captured["from"], to: captured["to"]} end def process_zone(:head_no_until, captured, [head|tail]) do name = captured["name"] captured = captured_zone_map_clean_up(captured) [%{record_type: :zone, name: name, zone_lines: [captured]}|process_tz_list([head|tail])] end def process_zone(:head_no_until, captured, []) do name = captured["name"] captured = captured_zone_map_clean_up(captured) [%{record_type: :zone, name: name, zone_lines: [captured]}] end def process_zone(:head_with_until, captured, [head|tail]) do name = captured["name"] captured = captured_zone_map_clean_up(captured) {line_type, new_capture} = zone_mapped(head) process_zone(line_type, new_capture, name, [captured], tail) end def process_zone(:continuation_with_until, captured, zone_name, zone_lines, [head|tail]) do captured = captured_zone_map_clean_up(captured) zone_lines = zone_lines ++ [captured] {line_type, new_capture} = zone_mapped(head) process_zone(line_type, new_capture, zone_name, zone_lines, tail) end def process_zone(:continuation_no_until, captured, zone_name, zone_lines, [head|tail]) do captured = captured_zone_map_clean_up(captured) zone_lines = zone_lines ++ [captured] [%{record_type: :zone, name: zone_name, zone_lines: zone_lines}|process_tz_list([head|tail])] end def process_zone(:continuation_no_until, captured, zone_name, zone_lines, []) do captured = captured_zone_map_clean_up(captured) zone_lines = zone_lines ++ [captured] [%{record_type: :zone, name: zone_name, zone_lines: zone_lines}] end def process_zone([head|tail]) do {line_type, captured} = zone_mapped(head) process_zone(line_type, captured, tail) end def zone_mapped(line) do # I use the term "head" in this context as the first line of a zone # definition. So it will start with "Zone" zone_line_regex = [ {:head_with_until, ~r/Zone[\s]+(?<name>[^\s]+)[\s]+(?<gmtoff>[^\s]+)[\s]+(?<rules>[^\s]+)[\s]+(?<format>[^\s]+)[\s]+(?<until>[^\n]+)/}, {:head_no_until, ~r/Zone[\s]+(?<name>[^\s]+)[\s]+(?<gmtoff>[^\s]+)[\s]+(?<rules>[^\s]+)[\s]+(?<format>[^\s]+)/}, {:continuation_with_until, ~r/[\s]+(?<gmtoff>[^\s]+)[\s]+(?<rules>[^\s]+)[\s]+(?<format>[^\s]+)[\s]+(?<until>[^\n]+)/}, {:continuation_no_until, ~r/[\s]+(?<gmtoff>[^\s]+)[\s]+(?<rules>[^\s]+)[\s]+(?<format>[^\s]+)/}, ] zone_mapped(line, zone_line_regex) end defp zone_mapped(_line, []), do: {:error, :no_regex_matched} defp zone_mapped(line,[regex_head|tail]) do regex_name = elem(regex_head,0) regex = elem(regex_head,1) if Regex.match?(regex, line) do captured = Regex.named_captures(regex, line) {regex_name, captured} else zone_mapped(line, tail) end end # if format in zone line is "-" change it to nil defp transform_zone_line_rules("-"), do: nil defp transform_zone_line_rules("0"), do: nil defp transform_zone_line_rules(string) do transform_zone_line_rules(string, Regex.match?(~r/\d/, string)) end # If the regexp does not contain a number, we assume a named rule defp transform_zone_line_rules(string, false), do: {:named_rules, string} defp transform_zone_line_rules(string, true) do {:amount, string |> string_amount_to_secs} end # Converts keys to atoms. Discards "name" defp captured_zone_map_clean_up(captured) do until = transform_until_datetime(captured["until"]) Map.merge %{gmtoff: string_amount_to_secs(captured["gmtoff"]), rules: transform_zone_line_rules(captured["rules"]), format: captured["format"]}, # remove until key if it is nil if(until == nil, do: %{}, else: %{until: until}) end end
39.363014
199
0.642422
087bcbf270fa880a6b359434c3ef4ef3547c1027
6,315
ex
Elixir
lib/arkenston/subject.ex
dolfinus/omicron-backend
dd3544a421ce8b05447fe72640f73f180549270f
[ "MIT" ]
1
2019-04-29T18:07:08.000Z
2019-04-29T18:07:08.000Z
lib/arkenston/subject.ex
dolfinus/omicron-backend
dd3544a421ce8b05447fe72640f73f180549270f
[ "MIT" ]
126
2020-12-03T15:39:31.000Z
2022-03-30T22:02:23.000Z
lib/arkenston/subject.ex
dolfinus/arkenston-backend
258880936dce673eb15db0c4b52e68d3d40c58ff
[ "MIT" ]
null
null
null
defmodule Arkenston.Subject do @moduledoc """ The Subject context. """ import Ecto.Query, warn: false alias Arkenston.Helper.QueryHelper alias Arkenston.Repo alias Arkenston.Subject.{User, Author} defp filter_author(query, opts) do opts = opts |> Enum.into(%{}) new_query = case opts do %{name: name, email: email} -> QueryHelper.handle_filter( query, opts |> Map.merge(%{name: {:lower, name}, email: {:lower, email}}) ) %{name: name} -> QueryHelper.handle_filter(query, opts |> Map.merge(%{name: {:lower, name}})) %{email: email} -> QueryHelper.handle_filter(query, opts |> Map.merge(%{email: {:lower, email}})) _ -> query end new_opts = opts |> Map.drop([:name, :email]) {new_query, new_opts} end defp filter_user_by_author(query, opts) do opts = opts |> Enum.into(%{}) {author_filter, _} = filter_author(Author, opts |> Map.take([:name, :email]) |> Map.put(:deleted, nil)) new_query = case author_filter do value when is_atom(value) -> query filter -> filter = from a in filter, select: a.id from u in query, join: a in subquery(filter), on: a.id == u.author_id end new_opts = opts |> Map.drop([:name, :email]) {new_query, new_opts} end @doc """ Returns the list of users. ## Examples iex> list_users() [%User{}, ...] """ @spec list_users(opts :: QueryHelper.query_opts() | list[keyword]) :: [User.t()] def list_users(opts \\ %{}) do {query, opts} = filter_user_by_author(User, opts) query |> QueryHelper.generate_query(opts) |> Repo.all() end @doc """ Returns the list of authors. ## Examples iex> list_authors() [%Author{}, ...] """ @spec list_authors(opts :: QueryHelper.query_opts() | list[keyword]) :: [Author.t()] def list_authors(opts \\ %{}) do {query, opts} = filter_author(Author, opts) query |> QueryHelper.generate_query(opts) |> Repo.all() end @doc """ Gets a single user by search query. ## Examples iex> get_user_by(id: 123) %User{} iex> get_user_by(id: 456) nil """ @spec get_user_by(opts :: QueryHelper.query_opts() | list[keyword]) :: User.t() | nil def get_user_by(opts) do {query, opts} = filter_user_by_author(User, opts) query |> QueryHelper.generate_query(opts) |> QueryHelper.first() |> Repo.one() end @doc """ Gets a single author by search query. ## Examples iex> get_author_by(id: 123) %Author{} iex> get_author_by(id: 456) nil """ @spec get_author_by(opts :: QueryHelper.query_opts() | list[keyword]) :: Author.t() | nil def get_author_by(opts) do {query, opts} = filter_author(Author, opts) query |> QueryHelper.generate_query(opts) |> QueryHelper.first() |> Repo.one() end @doc """ Gets a single user by id. ## Examples iex> get_user(123) %User{} iex> get_user(456) nil """ @spec get_user(id :: User.id()) :: User.t() | nil def get_user(id), do: get_user_by(%{id: id}) @doc """ Gets a single author by id. ## Examples iex> get_author(123) %Author{} iex> get_author(456) nil """ @spec get_author(id :: Author.id()) :: Author.t() | nil def get_author(id), do: get_author_by(%{id: id}) @doc """ Creates a user. ## Examples iex> create_user(%{field: value}) {:ok, %User{}} iex> create_user(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec create_user(attrs :: map, context :: map) :: {:ok, User.t()} | {:error, Repo.changeset()} def create_user(attrs \\ %{}, context \\ %{}) do attrs |> User.create_changeset() |> Repo.audited_insert(context) end @doc """ Creates an author. ## Examples iex> create_author(%{field: value}) {:ok, %Author{}} iex> create_author(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec create_author(attrs :: map, context :: map) :: {:ok, Author.t()} | {:error, Repo.changeset()} def create_author(attrs \\ %{}, context \\ %{}) do attrs |> Author.create_changeset() |> Repo.audited_insert(context) end @doc """ Updates a user. ## Examples iex> update_user(user, %{field: new_value}) {:ok, %User{}} iex> update_user(user, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec update_user(user :: User.t(), attrs :: map, context :: map) :: {:ok, User.t()} | {:error, Repo.changeset()} def update_user(%User{} = user, attrs \\ %{}, context \\ %{}) do user |> User.update_changeset(attrs) |> Repo.audited_update(context) end @doc """ Updates an author. ## Examples iex> update_author(user, %{field: new_value}) {:ok, %Author{}} iex> update_author(user, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ @spec update_author(author :: Author.t(), attrs :: map, context :: map) :: {:ok, Author.t()} | {:error, Repo.changeset()} def update_author(%Author{} = author, attrs \\ %{}, context \\ %{}) do author |> Author.update_changeset(attrs) |> Repo.audited_update(context) end @doc """ Deletes a user. ## Examples iex> delete_user(user) {:ok, %User{}} iex> delete_user(user) {:error, %Ecto.Changeset{}} """ @spec delete_user(user :: User.t(), attrs :: map, context :: map) :: {:ok, User.t()} | {:error, Repo.changeset()} def delete_user(%User{} = user, attrs \\ %{}, context \\ %{}) do user |> User.delete_changeset(attrs) |> Repo.audited_update(context) end @doc """ Deletes an author. ## Examples iex> delete_author(author) {:ok, %Author{}} iex> delete_author(author) {:error, %Ecto.Changeset{}} """ @spec delete_author(author :: Author.t(), attrs :: map, context :: map) :: {:ok, Author.t()} | {:error, Repo.changeset()} def delete_author(%Author{} = author, attrs \\ %{}, context \\ %{}) do author |> Author.delete_changeset(attrs) |> Repo.audited_update(context) end end
21.552901
97
0.568804
087bd17e804412242671afc73223da2fa79f6868
8,686
ex
Elixir
lib/gtfs_realtime_viz.ex
paulswartz/gtfs_realtime_viz
0336cf1f37a168eaf4d39e8cc71ab89364c120dc
[ "MIT" ]
null
null
null
lib/gtfs_realtime_viz.ex
paulswartz/gtfs_realtime_viz
0336cf1f37a168eaf4d39e8cc71ab89364c120dc
[ "MIT" ]
null
null
null
lib/gtfs_realtime_viz.ex
paulswartz/gtfs_realtime_viz
0336cf1f37a168eaf4d39e8cc71ab89364c120dc
[ "MIT" ]
null
null
null
defmodule GTFSRealtimeViz do @moduledoc """ GTFSRealtimeViz is an OTP app that can be run by itself or as part of another application. You can send it protobuf VehiclePositions.pb files, in sequence, and then output them as an HTML fragment, to either open in a browser or embed in another view. Example usage as stand alone: ``` $ iex -S mix iex(1)> proto = File.read!("filename.pb") iex(2)> GTFSRealtimeViz.new_message(:prod, proto, "first protobuf file") iex(3)> File.write!("output.html", GTFSRealtimeViz.visualize(:prod, %{})) ``` """ alias GTFSRealtimeViz.State alias GTFSRealtimeViz.Proto @type route_opts :: %{String.t => [{String.t, String.t, String.t}]} require EEx EEx.function_from_file :defp, :gen_html, "lib/templates/viz.eex", [:assigns], [engine: Phoenix.HTML.Engine] EEx.function_from_file :defp, :render_diff, "lib/templates/diff.eex", [:assigns], [engine: Phoenix.HTML.Engine] EEx.function_from_file :defp, :render_single_file, "lib/templates/single_file.eex", [:assigns], [engine: Phoenix.HTML.Engine] @doc """ Send protobuf files to the app's GenServer. The app can handle a series of files, belonging to different groupings (e.g., test, dev, and prod). When sending the file, you must also provide a comment (perhaps a time stamp or other information about the file), which will be displayed along with the visualization. """ @spec new_message(term, Proto.raw, String.t) :: :ok def new_message(group, raw, comment) do State.single_pb(group, raw, comment) end def new_message(group, vehicle_positions, trip_updates, comment) do State.new_data(group, vehicle_positions, trip_updates, comment) end @doc """ Renders the received protobuf files and comments into an HTML fragment that can either be opened directly in a browser or embedded within the HTML layout of another app. """ @spec visualize(term, route_opts) :: String.t def visualize(group, opts) do routes = Map.keys(opts[:routes]) vehicle_archive = get_vehicle_archive(group, routes) trip_update_archive = get_trip_update_archive(group, routes, opts[:timezone]) [trip_update_archive: trip_update_archive, vehicle_archive: vehicle_archive, routes: opts[:routes], render_diff?: false] |> gen_html |> Phoenix.HTML.safe_to_string end @doc """ Renders an HTML fragment that displays the vehicle differences between two pb files. """ @spec visualize_diff(term, term, route_opts) :: String.t def visualize_diff(group_1, group_2, opts) do routes = Map.keys(opts[:routes]) vehicle_archive_1 = get_vehicle_archive(group_1, routes) trip_archive_1 = get_trip_update_archive(group_1, routes, opts[:timezone]) vehicle_archive_2 = get_vehicle_archive(group_2, routes) trip_archive_2 = get_trip_update_archive(group_2, routes, opts[:timezone]) [trip_update_archive: Enum.zip(trip_archive_1, trip_archive_2), vehicle_archive: Enum.zip(vehicle_archive_1, vehicle_archive_2), routes: opts[:routes], render_diff?: true] |> gen_html() |> Phoenix.HTML.safe_to_string() end defp get_trip_update_archive(group, routes, timezone) do group |> State.trip_updates |> trips_we_care_about(routes) |> trip_updates_by_stop_direction_id(timezone) end def trips_we_care_about(state, routes) do Enum.map(state, fn {descriptor, update_list} -> filtered_positions = update_list |> Enum.filter(fn trip_update -> trip_update.trip.route_id in routes end) {descriptor, filtered_positions} end) end defp trip_updates_by_stop_direction_id(state, timezone) do Enum.map(state, fn {_descriptor, trip_updates} -> trip_updates |> Enum.flat_map(fn trip_update -> trip_update.stop_time_update |> Enum.reduce(%{}, fn stop_update, stop_update_acc -> if stop_update.arrival && stop_update.arrival.time do Map.put(stop_update_acc, {stop_update.stop_id, trip_update.trip.direction_id}, {trip_update.trip.trip_id, stop_update.arrival.time}) else stop_update_acc end end) end) end) |> Enum.map(fn predictions -> Enum.reduce(predictions, %{}, fn {stop_id, {trip_id, time}}, acc -> Map.update(acc, stop_id, [{trip_id, timestamp(time, timezone)}], fn timestamps -> timestamps ++ [{trip_id, timestamp(time, timezone)}] end) end) end) end defp timestamp(diff_time, timezone) do diff_datetime = diff_time |> DateTime.from_unix!() |> Timex.Timezone.convert(timezone) diff_datetime end defp get_vehicle_archive(group, routes) do group |> State.vehicles |> vehicles_we_care_about(routes) |> vehicles_by_stop_direction_id() end def vehicles_we_care_about(state, routes) do Enum.map(state, fn {descriptor, position_list} -> filtered_positions = position_list |> Enum.filter(fn position -> position.trip && position.trip.route_id in routes end) {descriptor, filtered_positions} end) end @spec vehicles_by_stop_direction_id([{String.t, [Proto.vehicle_position]}]) :: [{String.t, %{required(String.t) => [Proto.vehicle_position]}}] defp vehicles_by_stop_direction_id(state) do Enum.map(state, fn {comment, vehicles} -> vehicles_by_stop = Enum.reduce(vehicles, %{}, fn v, acc -> update_in acc, [{v.stop_id, v.trip.direction_id}], fn vs -> [v | (vs || [])] end end) {comment, vehicles_by_stop} end) end @spec format_times([{String.t, DateTime.t}] | nil) :: [Phoenix.HTML.Safe.t] def format_times(nil) do [] end def format_times(time_list) do time_list |> sort_by_time() |> Enum.take(2) |> Enum.map(&format_time/1) end def sort_by_time(time_list) do Enum.sort(time_list, &time_list_sorter/2) end defp time_list_sorter({_, time1}, {_, time2}) do Timex.before?(time1, time2) end defp format_time({_, nil}) do nil end defp format_time({trip_id, time}) do ascii = Timex.format!(time, "{h24}:{m}:{s}") span_for_id({ascii, trip_id}) end @spec format_time_diff(time_list, time_list) :: [{time_output, time_output}] when time_list: {String.t, DateTime.t} | nil, time_output: Phoenix.HTML.Safe.t | nil def format_time_diff(base_list, nil) do for format <- format_times(base_list) do {format, nil} end end def format_time_diff(nil, diff_list) do for format <- format_times(diff_list) do {nil, format} end end def format_time_diff(base_list, diff_list) do base_map = Map.new(base_list) diff_map = Map.new(diff_list) trips = for trip_id <- Map.keys(Map.merge(base_map, diff_map)), base = base_map[trip_id], diff = diff_map[trip_id], is_nil(base) or is_nil(diff) or DateTime.compare(base, diff) != :eq do {format_time({trip_id, base}), format_time({trip_id, diff})} end Enum.take(trips, 2) end @spec trainify([Proto.vehicle_position], Proto.vehicle_position_statuses, String.t) :: iodata defp trainify(vehicles, status, ascii_train) do vehicles |> vehicles_with_status(status) |> Enum.map(fn status -> label = if status.vehicle do status.vehicle.label || "" else "" end [ascii_train, " ", label] end) |> Enum.intersperse(",") end @spec trainify_diff([Proto.vehicle_position], [Proto.vehicle_position], Proto.vehicle_position_statuses, String.t, String.t) :: Phoenix.HTML.Safe.t defp trainify_diff(vehicles_base, vehicles_diff, status, ascii_train_base, ascii_train_diff) do base = vehicles_with_status(vehicles_base, status) |> Enum.map(& &1.vehicle && &1.vehicle.id) diff = vehicles_with_status(vehicles_diff, status) |> Enum.map(& &1.vehicle && &1.vehicle.id) unique_base = unique_trains(base, diff, ascii_train_base) unique_diff = unique_trains(diff, base, ascii_train_diff) [unique_base, unique_diff] |> List.flatten() |> Enum.map(&span_for_id/1) |> Enum.intersperse(",") end defp span_for_id({ascii, id}) do tag_opts = [class: "vehicle-#{id}", onmouseover: "highlight('#{id}', 'red')", onmouseout: "highlight('#{id}', 'black')"] :span |> Phoenix.HTML.Tag.content_tag([ascii, "(", id, ")"], tag_opts) end # removes any vehicles that appear in given list defp unique_trains(vehicles_1, vehicles_2, ascii) do Enum.reject(vehicles_1, & &1 in vehicles_2) |> Enum.map(&{ascii, &1}) end defp vehicles_with_status(vehicles, status) do Enum.filter(vehicles, & &1.current_status == status) end end
35.165992
175
0.683168
087c12b944d8c156cb5d3f311f1afc172e444a2b
3,663
exs
Elixir
test/elixir_google_scraper/scraper/keywords_test.exs
junan/elixir_google_scraper
d032f3a9d5a30e354f1e6d607434670334936630
[ "MIT" ]
null
null
null
test/elixir_google_scraper/scraper/keywords_test.exs
junan/elixir_google_scraper
d032f3a9d5a30e354f1e6d607434670334936630
[ "MIT" ]
25
2021-05-21T02:23:37.000Z
2021-07-09T09:22:32.000Z
test/elixir_google_scraper/scraper/keywords_test.exs
junan/elixir_google_scraper
d032f3a9d5a30e354f1e6d607434670334936630
[ "MIT" ]
null
null
null
defmodule ElixirGoogleScraper.Scraper.KeywordsTest do use ElixirGoogleScraper.DataCase, async: true alias ElixirGoogleScraper.Scraper.Keywords alias ElixirGoogleScraper.Scraper.Schemas.Keyword describe "mark_as_completed/1" do test "updates the keyword as completed" do user = insert(:user) keyword = insert(:keyword, status: :pending, user: user) result = Keywords.mark_as_completed(keyword) assert result.status == :completed end end describe "save_keywords/2" do test "stores the keywords" do user = insert(:user) file = %Plug.Upload{content_type: "text/csv", path: "test/fixture/keywords.csv"} assert :ok = Keywords.save_keywords(file, user) assert [keyword1, keyword2] = Repo.all(Keyword) assert keyword1.name == "buy domain" assert keyword1.user_id == user.id assert keyword1.status == :pending assert keyword2.name == "buy bike" assert keyword2.user_id == user.id assert keyword2.status == :pending end end describe "paginated_user_keywords/2" do test "returns only user's keywords" do user = insert(:user) user2 = insert(:user) keyword = insert(:keyword, user: user) insert(:keyword, user: user2) {keywords, _} = Keywords.paginated_user_keywords(user, %{page: 1}) assert length(keywords) == 1 assert List.first(keywords).id == keyword.id end test "returns user's paginated keywords" do user = insert(:user) insert_list(13, :keyword, user: user) {keywords, _} = Keywords.paginated_user_keywords(user, %{page: 1}) assert length(keywords) == 12 end test "returns filtered user's keywords when the query string is available" do user = insert(:user) insert_list(2, :keyword, user: user) keyword = insert(:keyword, name: "shopping", user: user) {keywords, _} = Keywords.paginated_user_keywords(user, %{"name" => "shopping", page: 1}) assert List.first(keywords).id == keyword.id end end describe "get_keyword!/1" do test "returns the keyword with preloded search result when the ID is valid" do user = insert(:user) keyword = insert(:keyword, user: user) search_result = insert(:search_result, keyword: keyword) result = Keywords.get_keyword!(keyword.id) assert result.id == keyword.id assert result.search_result.id == search_result.id end test "raises an Ecto.NoResultsError exception when the ID is invalid" do user = insert(:user) keyword = insert(:keyword, user: user) assert_raise Ecto.NoResultsError, fn -> Keywords.get_keyword!(keyword.id + 1) end end end describe "get_user_keyword/2" do test "returns the keyword with preloded search result when the given keyword belongs to the user" do user = insert(:user) keyword = insert(:keyword, user: user) search_result = insert(:search_result, keyword: keyword) result = Keywords.get_user_keyword(user, keyword.id) assert result.id == keyword.id assert result.search_result.id == search_result.id end test "returns nil when given keyword does not belong to the user" do user = insert(:user) user2 = insert(:user) keyword = insert(:keyword, user: user) insert(:search_result, keyword: keyword) result = Keywords.get_user_keyword(user2, keyword.id) assert result == nil end test "returns nil when the given keyword does not exist" do user = insert(:user) result = Keywords.get_user_keyword(user, 1000) assert result == nil end end end
29.780488
104
0.668305
087c4de226b64c022eaefc010aa316bdf98f3346
6,016
ex
Elixir
clients/service_management/lib/google_api/service_management/v1/model/quota_limit.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/service_management/lib/google_api/service_management/v1/model/quota_limit.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/service_management/lib/google_api/service_management/v1/model/quota_limit.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.ServiceManagement.V1.Model.QuotaLimit do @moduledoc """ &#x60;QuotaLimit&#x60; defines a specific limit that applies over a specified duration for a limit type. There can be at most one limit for a duration and limit type combination defined within a &#x60;QuotaGroup&#x60;. ## Attributes - defaultLimit (String): Default number of tokens that can be consumed during the specified duration. This is the number of tokens assigned when a client application developer activates the service for his/her project. Specifying a value of 0 will block all requests. This can be used if you are provisioning quota to selected consumers and blocking others. Similarly, a value of -1 will indicate an unlimited quota. No other negative values are allowed. Used by group-based quotas only. Defaults to: `null`. - description (String): Optional. User-visible, extended description for this quota limit. Should be used only when more context is needed to understand this limit than provided by the limit&#39;s display name (see: &#x60;display_name&#x60;). Defaults to: `null`. - displayName (String): User-visible display name for this limit. Optional. If not set, the UI will provide a default display name based on the quota configuration. This field can be used to override the default display name generated from the configuration. Defaults to: `null`. - duration (String): Duration of this limit in textual notation. Example: \&quot;100s\&quot;, \&quot;24h\&quot;, \&quot;1d\&quot;. For duration longer than a day, only multiple of days is supported. We support only \&quot;100s\&quot; and \&quot;1d\&quot; for now. Additional support will be added in the future. \&quot;0\&quot; indicates indefinite duration. Used by group-based quotas only. Defaults to: `null`. - freeTier (String): Free tier value displayed in the Developers Console for this limit. The free tier is the number of tokens that will be subtracted from the billed amount when billing is enabled. This field can only be set on a limit with duration \&quot;1d\&quot;, in a billable group; it is invalid on any other limit. If this field is not set, it defaults to 0, indicating that there is no free tier for this service. Used by group-based quotas only. Defaults to: `null`. - maxLimit (String): Maximum number of tokens that can be consumed during the specified duration. Client application developers can override the default limit up to this maximum. If specified, this value cannot be set to a value less than the default limit. If not specified, it is set to the default limit. To allow clients to apply overrides with no upper bound, set this to -1, indicating unlimited maximum quota. Used by group-based quotas only. Defaults to: `null`. - metric (String): The name of the metric this quota limit applies to. The quota limits with the same metric will be checked together during runtime. The metric must be defined within the service config. Used by metric-based quotas only. Defaults to: `null`. - name (String): Name of the quota limit. The name is used to refer to the limit when overriding the default limit on per-consumer basis. For metric-based quota limits, the name must be provided, and it must be unique within the service. The name can only include alphanumeric characters as well as &#39;-&#39;. The maximum length of the limit name is 64 characters. The name of a limit is used as a unique identifier for this limit. Therefore, once a limit has been put into use, its name should be immutable. You can use the display_name field to provide a user-friendly name for the limit. The display name can be evolved over time without affecting the identity of the limit. Defaults to: `null`. - unit (String): Specify the unit of the quota limit. It uses the same syntax as Metric.unit. The supported unit kinds are determined by the quota backend system. The [Google Service Control](https://cloud.google.com/service-control) supports the following unit components: * One of the time intevals: * \&quot;/min\&quot; for quota every minute. * \&quot;/d\&quot; for quota every 24 hours, starting 00:00 US Pacific Time. * Otherwise the quota won&#39;t be reset by time, such as storage limit. * One and only one of the granted containers: * \&quot;/{project}\&quot; quota for a project Here are some examples: * \&quot;1/min/{project}\&quot; for quota per minute per project. Note: the order of unit components is insignificant. The \&quot;1\&quot; at the beginning is required to follow the metric unit syntax. Used by metric-based quotas only. Defaults to: `null`. - values (Map[String, String]): Tiered limit values, currently only STANDARD is supported. Defaults to: `null`. """ defstruct [ :"defaultLimit", :"description", :"displayName", :"duration", :"freeTier", :"maxLimit", :"metric", :"name", :"unit", :"values" ] end defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.QuotaLimit do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.QuotaLimit do def encode(value, options) do GoogleApi.ServiceManagement.V1.Deserializer.serialize_non_nil(value, options) end end
94
886
0.756316
087c67bc49152e417e80f22eef0f45aa3e244884
1,931
ex
Elixir
clients/pub_sub/lib/google_api/pub_sub/v1/model/list_subscriptions_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/pub_sub/lib/google_api/pub_sub/v1/model/list_subscriptions_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/pub_sub/lib/google_api/pub_sub/v1/model/list_subscriptions_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.PubSub.V1.Model.ListSubscriptionsResponse do @moduledoc """ Response for the `ListSubscriptions` method. ## Attributes * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new `ListSubscriptionsRequest` to get more subscriptions. * `subscriptions` (*type:* `list(GoogleApi.PubSub.V1.Model.Subscription.t)`, *default:* `nil`) - The subscriptions that match the request. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :nextPageToken => String.t(), :subscriptions => list(GoogleApi.PubSub.V1.Model.Subscription.t()) } field(:nextPageToken) field(:subscriptions, as: GoogleApi.PubSub.V1.Model.Subscription, type: :list) end defimpl Poison.Decoder, for: GoogleApi.PubSub.V1.Model.ListSubscriptionsResponse do def decode(value, options) do GoogleApi.PubSub.V1.Model.ListSubscriptionsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PubSub.V1.Model.ListSubscriptionsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.134615
142
0.741067
087c83244bae50def1388aa93a16462cef827d3f
3,748
exs
Elixir
apps/tai/test/tai/venue_adapters/bitmex/stream/process_auth/messages/update_orders/to_partially_filled_test.exs
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
1
2019-12-19T05:16:26.000Z
2019-12-19T05:16:26.000Z
apps/tai/test/tai/venue_adapters/bitmex/stream/process_auth/messages/update_orders/to_partially_filled_test.exs
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
null
null
null
apps/tai/test/tai/venue_adapters/bitmex/stream/process_auth/messages/update_orders/to_partially_filled_test.exs
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
null
null
null
defmodule Tai.VenueAdapters.Bitmex.Stream.ProcessAuth.Messages.UpdateOrders.ToPartiallyFilledTest do use ExUnit.Case, async: false import Tai.TestSupport.Assertions.Event alias Tai.VenueAdapters.Bitmex.ClientId alias Tai.VenueAdapters.Bitmex.Stream.ProcessAuth alias Tai.Trading.OrderStore alias Tai.Events setup do {:ok, _} = Application.ensure_all_started(:tzdata) start_supervised!({Tai.Events, 1}) start_supervised!(Tai.Trading.OrderStore) :ok end @venue_client_id "gtc-TCRG7aPSQsmj1Z8jXfbovg==" @received_at Timex.now() @timestamp "2019-09-07T06:00:04.808Z" @state struct(ProcessAuth.State, venue_id: :my_venue) test ".process/3 passively fills the order" do Events.firehose_subscribe() assert {:ok, order} = enqueue() action = struct(Tai.Trading.OrderStore.Actions.Open, client_id: order.client_id, cumulative_qty: Decimal.new(0), leaves_qty: Decimal.new(20) ) assert {:ok, {old, updated}} = OrderStore.update(action) msg = struct(ProcessAuth.Messages.UpdateOrders.ToPartiallyFilled, cl_ord_id: order.client_id |> ClientId.to_venue(:gtc), timestamp: @timestamp, cum_qty: 15, leaves_qty: 5 ) ProcessAuth.Message.process(msg, @received_at, @state) assert_event(%Events.OrderUpdated{status: :partially_filled} = partially_filled_event) assert partially_filled_event.client_id == order.client_id assert partially_filled_event.venue_id == :my_venue assert partially_filled_event.cumulative_qty == Decimal.new(15) assert partially_filled_event.leaves_qty == Decimal.new(5) assert partially_filled_event.qty == Decimal.new(20) assert %DateTime{} = partially_filled_event.last_received_at assert %DateTime{} = partially_filled_event.last_venue_timestamp end test ".process/3 broadcasts an invalid status warning" do Events.firehose_subscribe() assert {:ok, order} = enqueue() action = struct(Tai.Trading.OrderStore.Actions.Skip, client_id: order.client_id) assert {:ok, {old, updated}} = OrderStore.update(action) msg = struct(ProcessAuth.Messages.UpdateOrders.ToPartiallyFilled, cl_ord_id: order.client_id |> ClientId.to_venue(:gtc), timestamp: @timestamp, cum_qty: 15, leaves_qty: 5 ) ProcessAuth.Message.process(msg, @received_at, @state) assert_event(%Events.OrderUpdateInvalidStatus{} = invalid_status_event) assert invalid_status_event.action == Tai.Trading.OrderStore.Actions.PassivePartialFill assert invalid_status_event.was == :skip assert invalid_status_event.required == [ :open, :partially_filled, :pending_amend, :pending_cancel, :amend_error, :cancel_accepted, :cancel_error ] end test ".process/3 broadcasts a not found warning" do Events.firehose_subscribe() msg = struct(ProcessAuth.Messages.UpdateOrders.ToPartiallyFilled, cl_ord_id: @venue_client_id, timestamp: @timestamp, cum_qty: 15, leaves_qty: 5 ) ProcessAuth.Message.process(msg, @received_at, @state) assert_event(%Events.OrderUpdateNotFound{} = not_found_event) assert not_found_event.client_id != @venue_client_id assert not_found_event.action == Tai.Trading.OrderStore.Actions.PassivePartialFill end defp enqueue, do: build_submission() |> OrderStore.enqueue() defp build_submission do struct(Tai.Trading.OrderSubmissions.BuyLimitGtc, venue_id: :my_venue, account_id: :main, product_symbol: :btc_usd, price: Decimal.new("100.1"), qty: Decimal.new(20) ) end end
31.495798
100
0.699306
087c8f02a16931b17452be6b59fb81f04cd497e0
549
ex
Elixir
lib/gistsio/gist_client_manager.ex
sntran/gists.io
74575514c0760cbfe2313b1479919ac45a29e8a2
[ "MIT" ]
1
2015-05-22T18:31:28.000Z
2015-05-22T18:31:28.000Z
lib/gistsio/gist_client_manager.ex
sntran/gists.io
74575514c0760cbfe2313b1479919ac45a29e8a2
[ "MIT" ]
null
null
null
lib/gistsio/gist_client_manager.ex
sntran/gists.io
74575514c0760cbfe2313b1479919ac45a29e8a2
[ "MIT" ]
1
2020-10-23T01:23:36.000Z
2020-10-23T01:23:36.000Z
defmodule GistsIO.GistClientManager do use Supervisor.Behaviour def start_link(client_id, client_secret) do :supervisor.start_link({:local, __MODULE__}, __MODULE__, [client_id, client_secret]) end def start_client(args // []) do :supervisor.start_child(__MODULE__, args) end def init([client_id, client_secret]) do children = [ worker(GistsIO.GistClient, [client_id, client_secret], restart: :transient) ] supervise(children, strategy: :simple_one_for_one) end end
27.45
92
0.677596
087c93220729575163a9cc4b83df9bb1c9868dc2
1,833
ex
Elixir
clients/logging/lib/google_api/logging/v2/model/list_sinks_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/model/list_sinks_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/model/list_sinks_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.Logging.V2.Model.ListSinksResponse do @moduledoc """ Result returned from ListSinks. ## Attributes - nextPageToken (String.t): If there might be more results than appear in this response, then nextPageToken is included. To get the next set of results, call the same method again using the value of nextPageToken as pageToken. Defaults to: `null`. - sinks ([LogSink]): A list of sinks. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :nextPageToken => any(), :sinks => list(GoogleApi.Logging.V2.Model.LogSink.t()) } field(:nextPageToken) field(:sinks, as: GoogleApi.Logging.V2.Model.LogSink, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Logging.V2.Model.ListSinksResponse do def decode(value, options) do GoogleApi.Logging.V2.Model.ListSinksResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Logging.V2.Model.ListSinksResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.941176
249
0.742499
087cc549c4023d009482ef3f8ca4e928f9fb4527
763
exs
Elixir
test/document_viewer_web/ueberauth/strategy/fake_test.exs
arkadyan/document_viewer
d45594632b83559520820744e4afd37d3bfdb03d
[ "MIT" ]
1
2021-03-17T19:04:28.000Z
2021-03-17T19:04:28.000Z
test/document_viewer_web/ueberauth/strategy/fake_test.exs
mbta/document_viewer
f3af972f4996759bc18811186f753b87bbe43b53
[ "MIT" ]
121
2021-03-18T21:03:02.000Z
2022-03-28T09:24:49.000Z
test/document_viewer_web/ueberauth/strategy/fake_test.exs
arkadyan/document_viewer
d45594632b83559520820744e4afd37d3bfdb03d
[ "MIT" ]
1
2021-05-19T21:21:56.000Z
2021-05-19T21:21:56.000Z
defmodule DocumentViewerWeb.Ueberauth.Strategy.FakeTest do use ExUnit.Case, async: true alias DocumentViewerWeb.Ueberauth.Strategy.Fake alias Ueberauth.Auth.{Credentials, Extra, Info} test "credentials returns a credentials struct" do assert Fake.credentials(%{}) == %Credentials{ token: "fake_access_token", refresh_token: "fake_refresh_token", expires: true, expires_at: System.system_time(:second) + 60 * 60, other: %{groups: ["document-viewer"]} } end test "info returns an empty Info struct" do assert Fake.info(%{}) == %Info{} end test "extra returns an Extra struct with empty raw_info" do assert Fake.extra(%{}) == %Extra{raw_info: %{}} end end
30.52
63
0.650066
087cc7e45e192f53e889a501765fa184487ea969
2,625
exs
Elixir
apps/glayu_core/test/glayu/validations/validator_test.exs
pmartinezalvarez/glayu
8dc30eea4d04c38f5c7999b593c066828423a3dc
[ "MIT" ]
51
2017-05-21T07:27:34.000Z
2017-11-30T04:34:17.000Z
apps/glayu_core/test/glayu/validations/validator_test.exs
doc22940/glayu
8dc30eea4d04c38f5c7999b593c066828423a3dc
[ "MIT" ]
17
2017-06-14T18:40:44.000Z
2017-08-20T16:14:58.000Z
apps/glayu_core/test/glayu/validations/validator_test.exs
doc22940/glayu
8dc30eea4d04c38f5c7999b593c066828423a3dc
[ "MIT" ]
5
2017-06-04T19:55:56.000Z
2017-07-29T16:18:58.000Z
defmodule Glayu.Validations.ValidatorTest do use ExUnit.Case test "validate raises a ValidationError when receives an invalid proplist " do source = [ {'title', 'The Glayu Times'}, {'permalink', 'categories/year/month/day/titl'}, # invalid permalink format {'source_dir', 'source'}, {'theme', 'glayu-times'}, {'theme_uri', 'glayu-times'}, # invalid uri format {'base_dir', '/my-glayu-site'} # public_dir is required ] validators = [ {'title', [Glayu.Validations.RequiredValidator.validator()]}, {'source_dir', [Glayu.Validations.RequiredValidator.validator()]}, {'public_dir', [Glayu.Validations.RequiredValidator.validator()]}, {'permalink', [Glayu.Validations.RequiredValidator.validator(), Glayu.Validations.PermalinkConfValidator.validator()]}, {'theme', [Glayu.Validations.RequiredValidator.validator()]}, {'theme_uri', [Glayu.Validations.URIValidator.validator()]} ] assert_raise Glayu.Validations.ValidationError, "Validation Error:\n'public_dir': \"is required\"\n'permalink': \"invalid permalink format\"\n'theme_uri': \"invalid uri format\"", fn -> Glayu.Validations.Validator.validate!(source, validators, fn (source, field) -> found = :proplists.get_value(field, source) case found do :undefined -> nil _ -> to_string found end end) end end test "validate returns :ok when receives a valid document context" do source = %{ categories: [ %{keys: ["software"], name: "Software", path: "/software/index.html"}, %{keys: ["software", "static-sites"], name: "Static Sites", path: "/software/static-sites/index.html"} ], content: "<p>A new Glayu post</p>\n", date: DateTime.from_naive!(~N[2017-05-11 07:20:03.000], "Etc/UTC"), layout: :draft, path: "/software/static-sites/new-post.html", raw: "A new Glayu post\n", score: 10, source: "/Users/pablomartinezalvarez/Documents/development/workspaces/glayu/glayu-test-site/source/_drafts/new-post.md", summary: "<p>A new Glayu post</p>\n", tags: ["Glayu", "Elixir"], title: "New Post", type: :draft } validators = [ {:title, [Glayu.Validations.RequiredValidator.validator()]}, {:categories, [Glayu.Validations.RequiredValidator.validator()]}, {:date, [Glayu.Validations.RequiredValidator.validator()]} ] assert source == Glayu.Validations.Validator.validate!(source, validators, fn (source, field) -> source[field] end) end end
36.458333
189
0.638095
087cdca8aa571782decc2950ef49990329946b59
3,709
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/bigtable_column.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/bigtable_column.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/big_query/lib/google_api/big_query/v2/model/bigtable_column.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.BigQuery.V2.Model.BigtableColumn do @moduledoc """ ## Attributes * `encoding` (*type:* `String.t`, *default:* `nil`) - [Optional] The encoding of the values when the type is not STRING. Acceptable encoding values are: TEXT - indicates values are alphanumeric text strings. BINARY - indicates values are encoded using HBase Bytes.toBytes family of functions. 'encoding' can also be set at the column family level. However, the setting at this level takes precedence if 'encoding' is set at both levels. * `fieldName` (*type:* `String.t`, *default:* `nil`) - [Optional] If the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as the column field name and is used as field name in queries. * `onlyReadLatest` (*type:* `boolean()`, *default:* `nil`) - [Optional] If this is set, only the latest version of value in this column are exposed. 'onlyReadLatest' can also be set at the column family level. However, the setting at this level takes precedence if 'onlyReadLatest' is set at both levels. * `qualifierEncoded` (*type:* `String.t`, *default:* `nil`) - [Required] Qualifier of the column. Columns in the parent column family that has this exact qualifier are exposed as . field. If the qualifier is valid UTF-8 string, it can be specified in the qualifier_string field. Otherwise, a base-64 encoded value must be set to qualifier_encoded. The column field name is the same as the column qualifier. However, if the qualifier is not a valid BigQuery field identifier i.e. does not match [a-zA-Z][a-zA-Z0-9_]*, a valid identifier must be provided as field_name. * `qualifierString` (*type:* `String.t`, *default:* `nil`) - * `type` (*type:* `String.t`, *default:* `nil`) - [Optional] The type to convert the value in cells of this column. The values are expected to be encoded using HBase Bytes.toBytes function when using the BINARY encoding value. Following BigQuery types are allowed (case-sensitive) - BYTES STRING INTEGER FLOAT BOOLEAN Default type is BYTES. 'type' can also be set at the column family level. However, the setting at this level takes precedence if 'type' is set at both levels. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :encoding => String.t(), :fieldName => String.t(), :onlyReadLatest => boolean(), :qualifierEncoded => String.t(), :qualifierString => String.t(), :type => String.t() } field(:encoding) field(:fieldName) field(:onlyReadLatest) field(:qualifierEncoded) field(:qualifierString) field(:type) end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.BigtableColumn do def decode(value, options) do GoogleApi.BigQuery.V2.Model.BigtableColumn.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.BigtableColumn do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
59.822581
571
0.728498
087ce11c61343430842de2f3378fc3007eef31fe
1,084
ex
Elixir
clients/hydra/elixir/lib/ory/api/metadata.ex
ory/sdk-generator
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
clients/hydra/elixir/lib/ory/api/metadata.ex
ory/sdk-generator
958314d130922ad6f20f439b5230141a832231a5
[ "Apache-2.0" ]
null
null
null
clients/hydra/elixir/lib/ory/api/metadata.ex
ory/sdk-generator
958314d130922ad6f20f439b5230141a832231a5
[ "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 Ory.Api.Metadata do @moduledoc """ API calls for all endpoints tagged `Metadata`. """ alias Ory.Connection import Ory.RequestBuilder @doc """ Get snapshot metrics from the service. If you're using k8s, you can then add annotations to your deployment like so: ``` metadata: annotations: prometheus.io/port: \"4434\" prometheus.io/path: \"/metrics/prometheus\" ``` ## Parameters - connection (Ory.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, nil} on success {:error, Tesla.Env.t} on failure """ @spec prometheus(Tesla.Env.client, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def prometheus(connection, _opts \\ []) do %{} |> method(:get) |> url("/metrics/prometheus") |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> evaluate_response([ { 200, false} ]) end end
27.794872
118
0.661439
087cff20f1788ddd84084a8c45cda3bf9c3ebd8e
2,214
ex
Elixir
apps/ewallet_db/lib/ewallet_db/invite.ex
turbo-play/ewallet
b7fee3eed62ac716f46246132c2ead1045f2e4f3
[ "Apache-2.0" ]
2
2019-07-13T05:49:03.000Z
2021-08-19T23:58:23.000Z
apps/ewallet_db/lib/ewallet_db/invite.ex
turbo-play/ewallet
b7fee3eed62ac716f46246132c2ead1045f2e4f3
[ "Apache-2.0" ]
null
null
null
apps/ewallet_db/lib/ewallet_db/invite.ex
turbo-play/ewallet
b7fee3eed62ac716f46246132c2ead1045f2e4f3
[ "Apache-2.0" ]
3
2018-05-08T17:15:42.000Z
2021-11-10T04:08:33.000Z
defmodule EWalletDB.Invite do @moduledoc """ Ecto Schema representing invite. """ use Ecto.Schema import Ecto.{Changeset, Query} alias Ecto.UUID alias EWalletDB.{Repo, Invite, User} alias EWalletDB.Helpers.Crypto @primary_key {:id, UUID, autogenerate: true} @token_length 32 @allowed_user_attrs [:email] schema "invite" do field :token, :string has_one :user, User timestamps() end defp changeset(changeset, attrs) do changeset |> cast(attrs, [:token]) |> validate_required([:token]) end @doc """ Retrieves a specific invite by its ID. """ def get(id) do Repo.get(Invite, id) end @doc """ Retrieves a specific invite by email and token. """ def get(email, input_token) do case get(:user, :email, email) do %Invite{} = invite -> if Crypto.secure_compare(invite.token, input_token), do: invite, else: nil _ -> nil end end @doc """ Retrieves a specific invite by the given user's attribute. Only user attributes defined in `@allowed_user_attrs` can be used. """ def get(:user, user_attr, value) do if Enum.member?(@allowed_user_attrs, user_attr) do query = from i in Invite, join: u in User, on: u.invite_id == i.id, where: field(u, ^user_attr) == ^value Repo.one(query) else nil end end @doc """ Generates an invite for the given user. """ def generate(user, opts \\ [preload: []]) do # Insert a new invite {:ok, invite} = insert(%{token: Crypto.generate_key(@token_length)}) # Assign the invite to the user changeset = change(user, invite_id: invite.id) {:ok, _user} = Repo.update(changeset) invite = Repo.preload(invite, opts[:preload]) {:ok, invite} end defp insert(attrs) do %Invite{} |> changeset(attrs) |> Repo.insert() end @doc """ Accepts an invitation and sets the given password to the user. """ def accept(invite, password) do invite = Repo.preload(invite, :user) {:ok, _user} = User.update(invite.user, %{invite_id: nil, password: password}) delete(invite) end defp delete(invite), do: Repo.delete(invite) end
23.0625
82
0.629178
087cff5d39545f776c3f21d64d030a845f6f1ace
873
ex
Elixir
lib/nubank_api/config.ex
jeffhsta/nubank_api
c4ca246f6e6ff6e77e349293daaff3741d3975ff
[ "MIT" ]
14
2019-02-19T16:59:16.000Z
2021-10-30T14:57:10.000Z
lib/nubank_api/config.ex
fernandozoomp/API_NuBank
cb05de00d48275f3eae94fa3cb4ea55684289937
[ "MIT" ]
32
2019-02-21T02:40:03.000Z
2020-06-09T00:04:03.000Z
lib/nubank_api/config.ex
fernandozoomp/API_NuBank
cb05de00d48275f3eae94fa3cb4ea55684289937
[ "MIT" ]
3
2019-02-22T00:20:34.000Z
2021-04-08T20:35:07.000Z
defmodule NubankAPI.Config do @moduledoc """ This configuration module is responsable for load the essential information from the configurations and set a default value for the missing configurations. """ @default_token_api_uri "https://prod-s0-webapp-proxy.nubank.com.br/api/proxy/AJxL5LBUC2Tx4PB-W6VD1SEIOd2xp14EDQ.aHR0cHM6Ly9wcm9kLWdsb2JhbC1hdXRoLm51YmFuay5jb20uYnIvYXBpL3Rva2Vu" def default_headers do [ {"Content-Type", "application/json"}, {"X-Correlation-Id", "WEB-APP.jO4x1"}, {"User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"}, {"Origin", "https://conta.nubank.com.br"}, {"Referer", "https://conta.nubank.com.br/"} ] end def token_api_uri, do: Application.get_env(:nubank_api, :token_api_uri) || @default_token_api_uri end
37.956522
179
0.719359
087d10dcdff0303733d5b9fdaeff723def7d1183
195
ex
Elixir
test/support/web/controllers/broadcast3_controller.ex
bdfinlayson/drab
ce11a643ec8fe7e7f622489af5792ef12e69a8c7
[ "MIT" ]
null
null
null
test/support/web/controllers/broadcast3_controller.ex
bdfinlayson/drab
ce11a643ec8fe7e7f622489af5792ef12e69a8c7
[ "MIT" ]
null
null
null
test/support/web/controllers/broadcast3_controller.ex
bdfinlayson/drab
ce11a643ec8fe7e7f622489af5792ef12e69a8c7
[ "MIT" ]
null
null
null
defmodule DrabTestApp.Broadcast3Controller do @moduledoc false use DrabTestApp.Web, :controller use Drab.Controller def index(conn, _params) do render(conn, "index.html") end end
17.727273
45
0.748718
087d75f9d5f614a26f5593ab01bcbb6b99691a67
3,610
exs
Elixir
test/oli_web/controllers/api/product_controller_test.exs
wyeworks/oli-torus
146ee79a7e315e57bdf3c7b6fd4f7dbe73610647
[ "MIT" ]
null
null
null
test/oli_web/controllers/api/product_controller_test.exs
wyeworks/oli-torus
146ee79a7e315e57bdf3c7b6fd4f7dbe73610647
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
test/oli_web/controllers/api/product_controller_test.exs
wyeworks/oli-torus
146ee79a7e315e57bdf3c7b6fd4f7dbe73610647
[ "MIT" ]
null
null
null
defmodule OliWeb.ProductControllerTest do @moduledoc false use OliWeb.ConnCase alias Oli.Inventories alias Oli.Seeder describe "index" do setup [:setup_session] test "lists all products", %{ conn: conn, api_key: api_key, map: map } do publisher_id = Inventories.default_publisher().id prod1 = map.prod1 prod2 = map.prod2 conn = conn |> Plug.Conn.put_req_header("authorization", "Bearer " <> Base.encode64(api_key)) |> get(Routes.product_path(conn, :index)) assert json_response(conn, 200)["products"] |> Enum.count() == 2 assert json_response(conn, 200)["products"] |> Enum.find(fn p -> p == %{ "amount" => Money.to_string!(prod1.amount), "description" => "a description", "grace_period_days" => prod1.grace_period_days, "grace_period_strategy" => Atom.to_string(prod1.grace_period_strategy), "has_grace_period" => prod1.has_grace_period, "requires_payment" => prod1.requires_payment, "pay_by_institution" => prod1.pay_by_institution, "slug" => prod1.slug, "status" => Atom.to_string(prod1.status), "title" => prod1.title, "publisher_id" => publisher_id } end) assert json_response(conn, 200)["products"] |> Enum.find(fn p -> p == %{ "amount" => nil, "description" => nil, "grace_period_days" => 0, "grace_period_strategy" => Atom.to_string(prod2.grace_period_strategy), "has_grace_period" => prod2.has_grace_period, "requires_payment" => prod2.requires_payment, "pay_by_institution" => prod1.pay_by_institution, "slug" => prod2.slug, "status" => Atom.to_string(prod2.status), "title" => prod2.title, "publisher_id" => publisher_id } end) end test "renders error when api key does not have product scope", %{ conn: conn, api_key: api_key, key: key } do conn = Plug.Conn.put_req_header(conn, "authorization", "Bearer " <> Base.encode64(api_key)) Oli.Interop.update_key(key, %{products_enabled: false}) conn = get(conn, Routes.product_path(conn, :index)) assert response(conn, 401) end test "renders error when api key has been disabled", %{ conn: conn, api_key: api_key, key: key } do conn = Plug.Conn.put_req_header(conn, "authorization", "Bearer " <> Base.encode64(api_key)) Oli.Interop.update_key(key, %{status: :disabled}) conn = get(conn, Routes.product_path(conn, :index)) assert response(conn, 401) end end defp setup_session(%{conn: conn}) do map = Seeder.base_project_with_resource2() |> Seeder.create_product( %{ title: "My 1st product", amount: Money.new(:USD, 100), requires_payment: true, grace_period_days: 14 }, :prod1 ) |> Seeder.create_product( %{title: "My 2nd product", amount: Money.new(:USD, "24.99"), description: nil}, :prod2 ) conn = Plug.Test.init_test_session(conn, lti_session: nil) api_key = UUID.uuid4() {:ok, key} = Oli.Interop.create_key(api_key, "hint") {:ok, conn: conn, map: map, api_key: api_key, key: key} end end
30.59322
97
0.559557