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
0380d285f025c8ff4b843d271f033bebcef32008
236
ex
Elixir
apps/tanx/lib/tanx/game/notifications.ex
4eek/tanx
32750c15966d6272db9d96fa620fb277a61520e4
[ "MIT" ]
112
2016-05-10T17:17:08.000Z
2022-01-25T22:41:29.000Z
apps/tanx/lib/tanx/game/notifications.ex
4eek/tanx
32750c15966d6272db9d96fa620fb277a61520e4
[ "MIT" ]
3
2016-05-10T04:39:02.000Z
2019-07-19T12:50:07.000Z
apps/tanx/lib/tanx/game/notifications.ex
4eek/tanx
32750c15966d6272db9d96fa620fb277a61520e4
[ "MIT" ]
22
2016-05-17T01:51:51.000Z
2022-03-15T03:21:02.000Z
defmodule Tanx.Game.Notifications.Ended do defstruct( id: nil, time: nil, data: nil ) end defmodule Tanx.Game.Notifications.Moved do defstruct( id: nil, time: nil, from_node: nil, to_node: nil ) end
13.882353
42
0.639831
0380d404e2d6985b48040d4ef611595e98939e67
781
ex
Elixir
lib/utilities/maps.ex
mgwidmann/options_tracker
5520f88a9a5873842a63a23d4bcc5da82a51feba
[ "MIT" ]
12
2020-06-25T17:25:15.000Z
2021-09-30T20:13:33.000Z
lib/utilities/maps.ex
mgwidmann/options_tracker
5520f88a9a5873842a63a23d4bcc5da82a51feba
[ "MIT" ]
5
2020-08-05T03:12:31.000Z
2021-07-15T04:59:03.000Z
lib/utilities/maps.ex
mgwidmann/options_tracker
5520f88a9a5873842a63a23d4bcc5da82a51feba
[ "MIT" ]
2
2021-07-03T17:20:15.000Z
2021-09-01T15:38:58.000Z
defmodule OptionsTracker.Utilities.Maps do @doc """ Convert map atom keys to strings """ def stringify_keys(nil), do: nil def stringify_keys(struct = %{__struct__: _}) do struct end def stringify_keys(map = %{}) do map |> Enum.map(fn {k, v} when is_atom(k) -> {Atom.to_string(k), stringify_keys(v)} {k, v} -> {k, v} end) |> Enum.into(%{}) end # Walk the list and stringify the keys of # of any map members def stringify_keys([head | rest]) do [stringify_keys(head) | stringify_keys(rest)] end def stringify_keys(not_a_map) do not_a_map end def compact(map = %{}) do map |> Enum.filter(fn {_key, ""} -> false {_key, nil} -> false _ -> true end) |> Enum.into(%{}) end end
19.525
70
0.587708
0380f5b4b898733b482857fe54d7a651f7909443
2,436
ex
Elixir
lib/aws.ex
salemove/aws-elixir
debdf6482158a71a57636ac664c911e682093395
[ "Apache-2.0" ]
null
null
null
lib/aws.ex
salemove/aws-elixir
debdf6482158a71a57636ac664c911e682093395
[ "Apache-2.0" ]
null
null
null
lib/aws.ex
salemove/aws-elixir
debdf6482158a71a57636ac664c911e682093395
[ "Apache-2.0" ]
1
2020-10-28T08:56:54.000Z
2020-10-28T08:56:54.000Z
defmodule AWS do @moduledoc """ AWS provides an API to talk with Amazon Web Services. Each module in this project corresponds with an AWS service, and they can be used by calling the functions of those modules. For example, "AWS DynamoDB" operations can be found in `AWS.DynamoDB` module. First we need to setup a `AWS.Client` structure with credentials and details about the region we want to use. client = %AWS.Client{ access_key_id: "<access-key-id>", secret_access_key: "<secret-access-key>", region: "us-east-1" } Alternatively you can create a `client` with `AWS.Client.create/3`. So we pass this client struct to our service modules: {:ok, result, _http_response} = AWS.Kinesis.list_streams(client, %{}) The second argument in this case is the `input` which is a map with the parameters for [this operation](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListStreams.html). Another example is the upload of a given file to `AWS.S3` using `AWS.S3.put_object/5`: client = AWS.Client.create("your-access-key-id", "your-secret-access-key", "us-east-1") file = File.read!("./tmp/your-file.txt") md5 = :crypto.hash(:md5, file) |> Base.encode64() AWS.S3.put_object(client, "your-bucket-name", "foo/your-file-on-s3.txt", %{"Body" => file, "ContentMD5" => md5}) You can find more details about those parameters in the [AWS API reference](https://docs.aws.amazon.com/index.html). ## Custom HTTP client and JSON/XML parsers You can customize your HTTP client or the module responsible for parsing and encoding JSON or XML by using options for the `AWS.Client`. By default, AWS Elixir uses hackney for the HTTP client, Jason for JSON, and a custom module for XML that is written on top of xmlerl. For more details, check `AWS.Client` documentation. """ defmodule ServiceMetadata do @moduledoc """ It is a struct containing AWS service metadata. Each service module has a function that returns its metadata. """ defstruct abbreviation: nil, api_version: nil, content_type: nil, credential_scope: nil, endpoint_prefix: nil, global?: nil, protocol: nil, service_id: nil, signature_version: nil, signing_name: nil, target_prefix: nil end end
35.823529
118
0.670361
0381109fc61edf9ce39d5b89446acc19279711d7
914
ex
Elixir
priv/templates/phx.gen.json/view.ex
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
18,092
2015-01-01T01:51:04.000Z
2022-03-31T19:37:14.000Z
priv/templates/phx.gen.json/view.ex
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,905
2015-01-01T00:22:47.000Z
2022-03-31T17:06:21.000Z
priv/templates/phx.gen.json/view.ex
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,205
2015-01-03T10:58:22.000Z
2022-03-30T14:55:57.000Z
defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>View do use <%= inspect context.web_module %>, :view alias <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>View def render("index.json", %{<%= schema.plural %>: <%= schema.plural %>}) do %{data: render_many(<%= schema.plural %>, <%= inspect schema.alias %>View, "<%= schema.singular %>.json")} end def render("show.json", %{<%= schema.singular %>: <%= schema.singular %>}) do %{data: render_one(<%= schema.singular %>, <%= inspect schema.alias %>View, "<%= schema.singular %>.json")} end def render("<%= schema.singular %>.json", %{<%= schema.singular %>: <%= schema.singular %>}) do %{ <%= [{:id, :id} | schema.attrs] |> Enum.map(fn {k, _} -> " #{k}: #{schema.singular}.#{k}" end) |> Enum.join(",\n") %> } end end
48.105263
123
0.601751
03815bd4ab514f2257f5ebaf0f9e9110a1f73155
80
exs
Elixir
test/crater_web/views/layout_view_test.exs
blvdgroup/crater
78d03de2eac73d90148df6c5d2d03e99b9b5ccb7
[ "Apache-2.0" ]
1
2018-03-13T08:15:50.000Z
2018-03-13T08:15:50.000Z
test/crater_web/views/layout_view_test.exs
blvdgroup/crater
78d03de2eac73d90148df6c5d2d03e99b9b5ccb7
[ "Apache-2.0" ]
1
2018-03-17T15:45:26.000Z
2018-03-17T15:45:26.000Z
test/crater_web/views/layout_view_test.exs
blvdgroup/crater
78d03de2eac73d90148df6c5d2d03e99b9b5ccb7
[ "Apache-2.0" ]
1
2017-08-30T16:13:09.000Z
2017-08-30T16:13:09.000Z
defmodule CraterWeb.LayoutViewTest do use CraterWeb.ConnCase, async: true end
20
37
0.825
03815ddc0890c4c3c3cfdd9df3485a42a65844bd
1,907
exs
Elixir
clients/life_sciences/mix.exs
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
null
null
null
clients/life_sciences/mix.exs
jamesvl/elixir-google-api
6c87fb31d996f08fb42ce6066317e9d652a87acc
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/life_sciences/mix.exs
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "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.LifeSciences.Mixfile do use Mix.Project @version "0.9.0" def project() do [ app: :google_api_life_sciences, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/life_sciences" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Life Sciences API client library. Cloud Life Sciences is a suite of services and tools for managing, processing, and transforming life sciences data. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/life_sciences", "Homepage" => "https://cloud.google.com/life-sciences" } ] end end
28.462687
159
0.662297
038194f0a80e911ca9f3926af9753175a107c3fd
7,227
ex
Elixir
lib/hexpm_web/controllers/package_controller.ex
Benjamin-Philip/hexpm
6f38244f81bbabd234c660f46ea973849ba77a7f
[ "Apache-2.0" ]
691
2017-03-08T09:15:45.000Z
2022-03-23T22:04:47.000Z
lib/hexpm_web/controllers/package_controller.ex
Benjamin-Philip/hexpm
6f38244f81bbabd234c660f46ea973849ba77a7f
[ "Apache-2.0" ]
491
2017-03-07T12:58:42.000Z
2022-03-29T23:32:54.000Z
lib/hexpm_web/controllers/package_controller.ex
Benjamin-Philip/hexpm
6f38244f81bbabd234c660f46ea973849ba77a7f
[ "Apache-2.0" ]
200
2017-03-12T23:03:39.000Z
2022-03-05T17:55:52.000Z
defmodule HexpmWeb.PackageController do use HexpmWeb, :controller @packages_per_page 30 @audit_logs_per_page 10 @sort_params ~w(name recent_downloads total_downloads inserted_at updated_at recently_published) @letters for letter <- ?A..?Z, do: <<letter>> def index(conn, params) do letter = Hexpm.Utils.parse_search(params["letter"]) search = Hexpm.Utils.parse_search(params["search"]) filter = cond do letter -> {:letter, letter} search -> search true -> nil end organizations = Users.all_organizations(conn.assigns.current_user) repositories = Enum.map(organizations, & &1.repository) sort = sort(params["sort"]) page_param = Hexpm.Utils.safe_int(params["page"]) || 1 package_count = Packages.count(repositories, filter) page = Hexpm.Utils.safe_page(page_param, package_count, @packages_per_page) packages = fetch_packages(repositories, page, @packages_per_page, filter, sort) downloads = Packages.packages_downloads_with_all_views(packages) exact_match = exact_match(repositories, search) render( conn, "index.html", title: "Packages", container: "container", per_page: @packages_per_page, search: search, letter: letter, sort: sort, package_count: package_count, page: page, packages: packages, letters: @letters, downloads: downloads, exact_match: exact_match ) end def show(conn, params) do # TODO: Show flash if private package and organization does not have active billing params = fixup_params(params) access_package(conn, params, fn package, repositories -> releases = Releases.all(package) {release, type} = if version = params["version"] do {matching_release(releases, version), :release} else {Release.latest_version(releases, only_stable: true, unstable_fallback: true), :package} end if release do package(conn, repositories, package, releases, release, type) else not_found(conn) end end) end def audit_logs(conn, params) do access_package(conn, params, fn package, _ -> page = Hexpm.Utils.safe_int(params["page"]) || 1 per_page = 100 audit_logs = AuditLogs.all_by(package, page, per_page) total_count = AuditLogs.count_by(package) render(conn, "audit_logs.html", title: "Recent Activities for #{package.name}", container: "container package-view", package: package, audit_logs: audit_logs, page: page, per_page: per_page, total_count: total_count ) end) end defp access_package(conn, params, fun) do %{"repository" => repository, "name" => name} = params organizations = Users.all_organizations(conn.assigns.current_user) repositories = Map.new(organizations, &{&1.repository.name, &1.repository}) if repository = repositories[repository] do package = repository && Packages.get(repository, name) # Should have access even though organization does not have active billing if package do fun.(package, Enum.map(organizations, & &1.repository)) end end || not_found(conn) end defp sort(nil), do: sort("recent_downloads") defp sort("downloads"), do: sort("recent_downloads") defp sort(param), do: Hexpm.Utils.safe_to_atom(param, @sort_params) defp matching_release(releases, version) do Enum.find(releases, &(to_string(&1.version) == version)) end defp package(conn, repositories, package, releases, release, type) do repository = package.repository release = Releases.preload(release, [:requirements, :downloads, :publisher]) latest_release_with_docs = Release.latest_version(releases, only_stable: true, unstable_fallback: true, with_docs: true) docs_assigns = cond do type == :package && latest_release_with_docs -> [ docs_html_url: Hexpm.Utils.docs_html_url(repository, package, nil), docs_tarball_url: Hexpm.Utils.docs_tarball_url(repository, package, latest_release_with_docs) ] type == :release and release.has_docs -> [ docs_html_url: Hexpm.Utils.docs_html_url(repository, package, release), docs_tarball_url: Hexpm.Utils.docs_tarball_url(repository, package, release) ] true -> [docs_html_url: nil, docs_tarball_url: nil] end downloads = Packages.package_downloads(package) graph_downloads = case type do :package -> Enum.map(releases, & &1.id) |> Releases.downloads_for_last_n_days(31) :release -> release.id |> Releases.downloads_for_last_n_days(31) end daily_graph = Date.utc_today() |> Date.add(-31) |> Date.range(Date.add(Date.utc_today(), -1)) |> Enum.map(fn date -> Enum.find(graph_downloads, fn dl -> date == Date.from_iso8601!(dl.day) end) end) |> Enum.map(fn nil -> 0 %{downloads: dl} -> dl end) owners = Owners.all(package, user: [:emails, :organization]) dependants = Packages.search( repositories, 1, 20, "depends:#{repository.name}:#{package.name}", :recent_downloads, [:name, :repository_id] ) dependants_count = Packages.count(repositories, "depends:#{repository.name}:#{package.name}") audit_logs = AuditLogs.all_by(package, 1, @audit_logs_per_page) render( conn, "show.html", [ title: package.name, description: package.meta.description, container: "container package-view", canonical_url: Routes.package_url(conn, :show, package), package: package, repository_name: repository.name, releases: releases, current_release: release, downloads: downloads, owners: owners, dependants: dependants, dependants_count: dependants_count, audit_logs: audit_logs, daily_graph: daily_graph, type: type ] ++ docs_assigns ) end defp fetch_packages(repositories, page, packages_per_page, search, sort) do packages = Packages.search(repositories, page, packages_per_page, search, sort, nil) Packages.attach_versions(packages) end defp exact_match(_organizations, nil) do nil end defp exact_match(repositories, search) do case String.split(search, "/", parts: 2) do [repository, package] -> if repository in Enum.map(repositories, & &1.name) do Packages.get(repository, package) end _ -> try do Packages.get(repositories, search) rescue Ecto.MultipleResultsError -> nil end end end defp fixup_params(%{"name" => name, "version" => version} = params) do case Version.parse(version) do {:ok, _} -> params :error -> params |> Map.put("repository", name) |> Map.put("name", version) |> Map.delete("version") end end defp fixup_params(params) do params end end
29.378049
99
0.638854
0381a3dcf089d5bb03a8df2d13e129aad89c815d
1,584
exs
Elixir
test/cforum/read_messages_test.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
16
2019-04-04T06:33:33.000Z
2021-08-16T19:34:31.000Z
test/cforum/read_messages_test.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
294
2019-02-10T11:10:27.000Z
2022-03-30T04:52:53.000Z
test/cforum/read_messages_test.exs
jrieger/cforum_ex
61f6ce84708cb55bd0feedf69853dae64146a7a0
[ "MIT" ]
10
2019-02-10T10:39:24.000Z
2021-07-06T11:46:05.000Z
defmodule Cforum.ReadMessagesTest do use Cforum.DataCase alias Cforum.ReadMessages alias Cforum.ReadMessages.ReadMessage setup do user = insert(:user) forum = insert(:public_forum) thread = insert(:thread, forum: forum) message = insert(:message, thread: thread, forum: forum, user: user, tags: []) tag = insert(:tag, messages: [message]) {:ok, user: user, forum: forum, thread: thread, message: message, tag: tag} end describe "mark messages read" do test "mark_messages_read/2 marks messages read for a user", %{message: m, user: u, thread: t, forum: f} do m1 = insert(:message, thread: t, forum: f) assert [%ReadMessage{}, %ReadMessage{}] = ReadMessages.mark_messages_read(u, [m, m1]) end test "mark_messages_read/2 marks a message read for a user", %{message: m, user: u} do assert [%ReadMessage{}] = ReadMessages.mark_messages_read(u, m) end test "mark_messages_read/2 returns nil when called w/o a user", %{message: m} do assert ReadMessages.mark_messages_read(nil, m) == nil end end describe "cound unread messages" do test "cound_unread_messages/2 counts the number of unread messages for a user", %{message: m, user: u, forum: f} do assert ReadMessages.count_unread_messages(u, [f]) == {1, 1} ReadMessages.mark_messages_read(u, m) assert ReadMessages.count_unread_messages(u, [f]) == {0, 0} end test "count_unread_messages/2 returns 0 w/o a user", %{forum: f} do assert ReadMessages.count_unread_messages(nil, [f]) == {0, 0} end end end
36
119
0.677399
0381b4bb79bb99015e34ce78e33965651db041a2
19,452
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/https_health_checks.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/https_health_checks.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/https_health_checks.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Compute.V1.Api.HttpsHealthChecks do @moduledoc """ API calls for all endpoints tagged `HttpsHealthChecks`. """ alias GoogleApi.Compute.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Deletes the specified HttpsHealthCheck resource. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - https_health_check (String.t): Name of the HttpsHealthCheck resource to delete. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_https_health_checks_delete(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_https_health_checks_delete( connection, project, https_health_check, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/{project}/global/httpsHealthChecks/{httpsHealthCheck}", %{ "project" => URI.encode_www_form(project), "httpsHealthCheck" => URI.encode_www_form(https_health_check) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Returns the specified HttpsHealthCheck resource. Gets a list of available HTTPS health checks by making a list() request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - https_health_check (String.t): Name of the HttpsHealthCheck resource to return. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.Compute.V1.Model.HttpsHealthCheck{}} on success {:error, info} on failure """ @spec compute_https_health_checks_get(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.HttpsHealthCheck.t()} | {:error, Tesla.Env.t()} def compute_https_health_checks_get( connection, project, https_health_check, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/httpsHealthChecks/{httpsHealthCheck}", %{ "project" => URI.encode_www_form(project), "httpsHealthCheck" => URI.encode_www_form(https_health_check) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.HttpsHealthCheck{}]) end @doc """ Creates a HttpsHealthCheck resource in the specified project using the data included in the request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - :body (HttpsHealthCheck): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_https_health_checks_insert(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_https_health_checks_insert(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/global/httpsHealthChecks", %{ "project" => URI.encode_www_form(project) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Retrieves the list of HttpsHealthCheck resources available to the specified project. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :filter (String.t): A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either &#x3D;, !&#x3D;, &gt;, or &lt;. For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name !&#x3D; example-instance. You can also filter nested fields. For example, you could specify scheduling.automaticRestart &#x3D; false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart &#x3D; true) (cpuPlatform &#x3D; \&quot;Intel Skylake\&quot;). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform &#x3D; \&quot;Intel Skylake\&quot;) OR (cpuPlatform &#x3D; \&quot;Intel Broadwell\&quot;) AND (scheduling.automaticRestart &#x3D; true). - :maxResults (integer()): The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) - :orderBy (String.t): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy&#x3D;\&quot;creationTimestamp desc\&quot;. This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. - :pageToken (String.t): Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. ## Returns {:ok, %GoogleApi.Compute.V1.Model.HttpsHealthCheckList{}} on success {:error, info} on failure """ @spec compute_https_health_checks_list(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.HttpsHealthCheckList.t()} | {:error, Tesla.Env.t()} def compute_https_health_checks_list(connection, project, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :filter => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{project}/global/httpsHealthChecks", %{ "project" => URI.encode_www_form(project) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.HttpsHealthCheckList{}]) end @doc """ Updates a HttpsHealthCheck resource in the specified project using the data included in the request. This method supports PATCH semantics and uses the JSON merge patch format and processing rules. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - https_health_check (String.t): Name of the HttpsHealthCheck resource to patch. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - :body (HttpsHealthCheck): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_https_health_checks_patch(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_https_health_checks_patch( connection, project, https_health_check, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/{project}/global/httpsHealthChecks/{httpsHealthCheck}", %{ "project" => URI.encode_www_form(project), "httpsHealthCheck" => URI.encode_www_form(https_health_check) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Updates a HttpsHealthCheck resource in the specified project using the data included in the request. ## Parameters - connection (GoogleApi.Compute.V1.Connection): Connection to server - project (String.t): Project ID for this request. - https_health_check (String.t): Name of the HttpsHealthCheck resource to update. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :requestId (String.t): An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - :body (HttpsHealthCheck): ## Returns {:ok, %GoogleApi.Compute.V1.Model.Operation{}} on success {:error, info} on failure """ @spec compute_https_health_checks_update(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()} def compute_https_health_checks_update( connection, project, https_health_check, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/{project}/global/httpsHealthChecks/{httpsHealthCheck}", %{ "project" => URI.encode_www_form(project), "httpsHealthCheck" => URI.encode_www_form(https_health_check) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end end
53.586777
1,213
0.706097
0381b8ca8e70af1eb294be890380c6bb1797d97d
1,727
exs
Elixir
config/releases.exs
remerle/asciinema-server
895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57
[ "Apache-2.0" ]
893
2017-09-14T14:18:29.000Z
2022-03-31T21:45:08.000Z
config/releases.exs
remerle/asciinema-server
895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57
[ "Apache-2.0" ]
103
2017-09-29T22:15:33.000Z
2022-03-27T21:47:43.000Z
config/releases.exs
remerle/asciinema-server
895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57
[ "Apache-2.0" ]
152
2017-09-07T12:43:15.000Z
2022-03-10T18:47:47.000Z
import Config env = &System.get_env/1 secret_key_base = env.("SECRET_KEY_BASE") config :asciinema, AsciinemaWeb.Endpoint, url: [ scheme: env.("URL_SCHEME") || "https", host: env.("URL_HOST") || "asciinema.org", port: String.to_integer(env.("URL_PORT") || "443") ], secret_key_base: secret_key_base config :asciinema, Asciinema.Accounts, secret: secret_key_base config :asciinema, Asciinema.Repo, pool_size: String.to_integer(env.("DB_POOL_SIZE") || "20") if env.("S3_BUCKET") do config :asciinema, :file_store, Asciinema.FileStore.Cached config :asciinema, Asciinema.FileStore.Cached, remote_store: Asciinema.FileStore.S3, cache_store: Asciinema.FileStore.Local config :asciinema, Asciinema.FileStore.S3, region: env.("S3_REGION"), bucket: env.("S3_BUCKET"), path: "uploads/", proxy: !!env.("S3_PROXY_ENABLED") config :ex_aws, access_key_id: [{:system, "AWS_ACCESS_KEY_ID"}, :instance_role], secret_access_key: [{:system, "AWS_SECRET_ACCESS_KEY"}, :instance_role] config :asciinema, Asciinema.FileStore.Local, path: "cache/uploads/" end config :asciinema, Asciinema.PngGenerator.Rsvg, pool_size: String.to_integer(env.("RSVG_POOL_SIZE") || "2"), font_family: env.("RSVG_FONT_FAMILY") || "monospace" if dsn = env.("SENTRY_DSN") do config :sentry, dsn: dsn else config :sentry, included_environments: [] end if gc_days = env.("ASCIICAST_GC_DAYS") do config :asciinema, :asciicast_gc_days, String.to_integer(gc_days) end if String.downcase("#{env.("CRON")}") in ["0", "false", "no"] do config :asciinema, Oban, plugins: [{Oban.Plugins.Cron, crontab: []}] end config :asciinema, :sign_up_enabled?, env.("SIGN_UP_DISABLED") not in ["1", "true"]
29.775862
93
0.708164
0381d4529f3415bbb2c1b9ff9592636da75c2f77
688
exs
Elixir
test/language_test.exs
bitchef/exocco
b0e93b01794d71c0458f52907b2f66b03e3f207e
[ "MIT" ]
null
null
null
test/language_test.exs
bitchef/exocco
b0e93b01794d71c0458f52907b2f66b03e3f207e
[ "MIT" ]
1
2016-02-09T12:27:42.000Z
2016-02-09T12:27:42.000Z
test/language_test.exs
bitchef/exocco
b0e93b01794d71c0458f52907b2f66b03e3f207e
[ "MIT" ]
null
null
null
defmodule LanguageTest do use ExUnit.Case import :hamcrest, only: [ assert_that: 2 ] import :hamcrest_matchers test "Language.from_file_ext/1 returns nil for an unknown file extension" do result = Language.from_file_ext(".dummy") assert_that result, is nil end test "Language.from_file_ext/1 gets a Language map for a known file extension" do result = Language.from_file_ext(".ex") expected = %Language{name: "elixir", symbol: "#", dividerText: "\n#DIVIDER\n", commentMatcher: Regex.compile!("^\s*#+\s?"), dividerHtml: Regex.compile!("\n*<span class=\"c1?\">#DIVIDER</span>\n*")} assert_that result, is expected end end
31.272727
83
0.674419
0381d61608e4dc3c71e6125021833c3216b7f8d2
828
exs
Elixir
apps/waylon_web/config/config.exs
thyagostall/waylon
d2298e8b66d7a0e2e4819f11607c0bc94a7e8543
[ "MIT" ]
null
null
null
apps/waylon_web/config/config.exs
thyagostall/waylon
d2298e8b66d7a0e2e4819f11607c0bc94a7e8543
[ "MIT" ]
null
null
null
apps/waylon_web/config/config.exs
thyagostall/waylon
d2298e8b66d7a0e2e4819f11607c0bc94a7e8543
[ "MIT" ]
null
null
null
# Since configuration is shared in umbrella projects, this file # should only configure the :waylon_web application itself # and only for organization purposes. All other config goes to # the umbrella root. use Mix.Config # General application configuration config :waylon_web, ecto_repos: [Waylon.Repo], generators: [context_app: :waylon] # Configures the endpoint config :waylon_web, WaylonWeb.Endpoint, url: [host: "localhost"], secret_key_base: "3AdUn103Qv1sLpYNBC5zTlHqigdAjff/hY56HlZjUtJbLUAanOYeectj2FTRekwP", render_errors: [view: WaylonWeb.ErrorView, accepts: ~w(html json)], pubsub: [name: WaylonWeb.PubSub, adapter: Phoenix.PubSub.PG2] # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
37.636364
86
0.782609
0381d903701c1dd721a2859058fe480b750b2ff9
324
ex
Elixir
lib/battle_box/games/marooned/ais/wilson.ex
GrantJamesPowell/battle_box
301091955b68cd4672f6513d645eca4e3c4e17d0
[ "Apache-2.0" ]
2
2020-10-17T05:48:49.000Z
2020-11-11T02:34:15.000Z
lib/battle_box/games/marooned/ais/wilson.ex
FlyingDutchmanGames/battle_box
301091955b68cd4672f6513d645eca4e3c4e17d0
[ "Apache-2.0" ]
3
2020-05-18T05:52:21.000Z
2020-06-09T07:24:14.000Z
lib/battle_box/games/marooned/ais/wilson.ex
FlyingDutchmanGames/battle_box
301091955b68cd4672f6513d645eca4e3c4e17d0
[ "Apache-2.0" ]
null
null
null
defmodule BattleBox.Games.Marooned.Ais.Wilson do @behaviour BattleBox.Games.AiOpponent def name, do: "wilson" def description, do: "Tries to stay close to you" def difficulty, do: 3 def creator, do: "the-notorious-gjp" def initialize(_settings) do :ok end def commands(_commands) do %{} end end
19.058824
51
0.700617
0381e6401632f0ca6348ae0884e2288721c8321e
1,597
ex
Elixir
clients/games/lib/google_api/games/v1/model/event_child.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/event_child.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/event_child.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.Games.V1.Model.EventChild do @moduledoc """ This is a JSON template for an event child relationship resource. ## Attributes * `childId` (*type:* `String.t`, *default:* `nil`) - The ID of the child event. * `kind` (*type:* `String.t`, *default:* `games#eventChild`) - Uniquely identifies the type of this resource. Value is always the fixed string games#eventChild. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :childId => String.t(), :kind => String.t() } field(:childId) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.EventChild do def decode(value, options) do GoogleApi.Games.V1.Model.EventChild.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.EventChild do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.94
164
0.718848
0381f86120e76cceea30359b43139e98e0492da3
4,678
exs
Elixir
test/elenchos_ex/lib/deployment_test.exs
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
test/elenchos_ex/lib/deployment_test.exs
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
test/elenchos_ex/lib/deployment_test.exs
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
defmodule ElenchosEx.DeploymentTest do use ExUnit.Case, async: true import ElenchosEx.Deployment alias ElenchosEx.{Release, Release.Model} @ref "abcd" @message_delay 11 setup do :ets.delete(:releases, @ref) rel = %Model{ref: @ref} Release.save(rel) {:ok, %{rel: rel}} end describe "init" do test "starts a new deployment process if the release exists" do assert {:ok, _release} = init(@ref) end test "does not start when the release does not exist" do assert {:stop, "Could not find release"} = init("") end test "changes state to :initial when starting" do {:ok, release} = init(@ref) assert release.deployment_state == :initial end end describe "get" do test "returns the state of the process" do {:ok, pid} = start_link(@ref) assert get(pid).ref == @ref Process.exit(pid, :kill) end end describe "update" do test "updates the state of the process", %{rel: rel} do {:ok, pid} = start_link(@ref) update(pid, %{rel | sha: "1234"}) assert get(pid) == %{rel | sha: "1234"} Process.exit(pid, :kill) end end describe "next" do test "changes the state from applying_configuration -> awaiting_deployment", %{rel: rel} do rel = %{rel | deployment_state: :applying_configuration} assert {:noreply, %{deployment_state: :awaiting_deployment}} = handle_info(:next, rel) assert_receive :await_deployment, @message_delay end test "changes the state from awaiting_deployment -> deployed if there is an IP in the release", %{rel: rel} do rel = %{rel | deployment_state: :awaiting_deployment, ip: :foo} assert {:noreply, %{deployment_state: :deployed}} = handle_info(:next, rel) end test "keeps the state awaiting_deployment if there is no IP in the release", %{rel: rel} do rel = %{rel | deployment_state: :awaiting_deployment} assert {:noreply, %{deployment_state: :awaiting_deployment}} = handle_info(:next, rel) assert_receive :poll_loadbalancer, @message_delay end test "changes the state from building_docker_files -> configuring_kustomize", %{rel: rel} do rel = %{rel | deployment_state: :building_docker_files} assert {:noreply, %{deployment_state: :configuring_kustomize}} = handle_info(:next, rel) assert_receive :configure_kustomize, @message_delay end test "changes the state from configuring_kustomize -> applying_configuration", %{rel: rel} do rel = %{rel | deployment_state: :configuring_kustomize} assert {:noreply, %{deployment_state: :applying_configuration}} = handle_info(:next, rel) assert_receive :apply_configuration, @message_delay end test "changes the state from creating_cluster -> building_docker_files if there is a cluster id in the release", %{rel: rel} do rel = %{rel | deployment_state: :creating_cluster, cluster_id: :foo} assert {:noreply, %{deployment_state: :building_docker_files}} = handle_info(:next, rel) assert_receive :build_docker_files, @message_delay end test "keeps the state creating_cluster if there is no cluster id in the release", %{rel: rel} do rel = %{rel | deployment_state: :creating_cluster} assert {:noreply, %{deployment_state: :creating_cluster}} = handle_info(:next, rel) assert_receive :poll_cluster, @message_delay end test "changes the state from initial -> creating_cluster", %{rel: rel} do rel = %{rel | deployment_state: :initial} assert {:noreply, %{deployment_state: :creating_cluster}} = handle_info(:next, rel) assert_receive :create_cluster, @message_delay end test "does not change state if the state is unkown", %{rel: rel} do rel = %{rel | deployment_state: :huh} assert {:noreply, rel} = handle_info(:next, rel) end end describe "reset" do test "returns the state to :initial unless it it initial or creating_cluster", %{rel: rel} do rel = %{rel | deployment_state: :huh} assert {:noreply, %{deployment_state: :initial}} = handle_info(:reset, rel) assert_receive :next, @message_delay end test "retains the initial state", %{rel: rel} do rel = %{rel | deployment_state: :initial} assert {:noreply, %{deployment_state: :initial}} = handle_info(:reset, rel) refute_receive :next, @message_delay end test "retains the creating_cluster state", %{rel: rel} do rel = %{rel | deployment_state: :creating_cluster} assert {:noreply, %{deployment_state: :creating_cluster}} = handle_info(:reset, rel) refute_receive :next, @message_delay end end end
37.424
131
0.675289
03822f92193e172657ed6484bfc2094d9c78cd2b
3,966
ex
Elixir
lib/crit/field_converters/to_span.ex
jesseshieh/crit19
0bba407fea09afed72cbb90ca579ba34c537edef
[ "MIT" ]
null
null
null
lib/crit/field_converters/to_span.ex
jesseshieh/crit19
0bba407fea09afed72cbb90ca579ba34c537edef
[ "MIT" ]
null
null
null
lib/crit/field_converters/to_span.ex
jesseshieh/crit19
0bba407fea09afed72cbb90ca579ba34c537edef
[ "MIT" ]
null
null
null
defmodule Crit.FieldConverters.ToSpan do use Ecto.Schema use Crit.Global.Constants use Crit.Errors alias Ecto.Changeset alias Pile.TimeHelper alias Ecto.Datespan import Pile.Interface alias Crit.Setup.InstitutionApi # Assumes this partial schema. Fields are constant because they come from # the domain. # field :in_service_datestring, :string # field :out_of_service_datestring, :string # field :institution, :string # field :span, Datespan # Note: it's an assumed precondition that the first three fields # exist in either the changeset's `data` or its `changes`. That is, # they have already been `cast` and `validate_required`. @required [:in_service_datestring, :out_of_service_datestring, :institution] # Having two versions of the function is clearer for testing. # Non-testing clients will use this one. def synthesize(struct_or_changeset, attrs) do struct_or_changeset |> Changeset.cast(attrs, @required) |> Changeset.validate_required(@required) |> synthesize end def synthesize(changeset) do changeset |> assume_infinite_up |> apply_out_of_service_date |> check_date_compatibility end defp assume_infinite_up(changeset) do case parse_date(changeset, :in_service_datestring) do {:ok, @never} -> msg = ~S{"must be a date or "today"} safely_add_error(changeset, :in_service_datestring, msg) {:ok, in_service} -> put_span(changeset, Datespan.inclusive_up(in_service)) {:error, _tag} -> safely_add_error(changeset, :in_service_datestring, "is invalid") end end defp apply_out_of_service_date(changeset) do case parse_date(changeset, :out_of_service_datestring) do {:ok, @never} -> changeset # this is what the first step assumed {:ok, out_of_service} -> case Changeset.fetch_field!(changeset, :span) do nil -> changeset # This means first step failed. tentative_span -> put_span(changeset, Datespan.put_last(tentative_span, out_of_service)) end {:error, _tag} -> safely_add_error(changeset, :out_of_service_datestring, "is invalid") end end # This is somewhat complicated. You might think that you could guard this # function with: # # defp check_date_compatibility(%{valid?: false} = changeset), do: changeset # # That doesn't work if nested changesets are validated before this # changeset's `:span` is calculated. If any of those prove invalid, # this changeset is marked as also invalid, which leads to no date # misorder message until the user fixes the error in the nested form # and resubmits. That would be rude, so we check if there's any `span` # *to* check. defp check_date_compatibility(changeset) do span = Changeset.fetch_field!(changeset, :span) cond do span == nil -> changeset not Datespan.is_customary?(span) -> changeset Date.compare(span.first, span.last) == :lt -> changeset :else -> safely_add_error(changeset, :out_of_service_datestring, @date_misorder_message) end end defp put_span(changeset, span), do: Changeset.put_change(changeset, :span, span) # Delete span so as to prevent invalid value from being visible outside the module. defp safely_add_error(changeset, field, message) do changeset |> Changeset.add_error(field, message) |> Changeset.delete_change(:span) end defp parse_date(changeset, field) do datestring = Changeset.fetch_field!(changeset, field) case datestring do nil -> {:error, :irrelevant} @never -> {:ok, @never} @today -> institution = Changeset.fetch_field!(changeset, :institution) timezone = some(InstitutionApi).timezone(institution) {:ok, TimeHelper.today_date(timezone)} _ -> Date.from_iso8601(datestring) end end end
32.508197
87
0.687342
03824cae2d96bfab9813353dcad0261d56d27378
1,090
ex
Elixir
lib/lotus/list.ex
code-shoily/lotus
d14958956103f2376d51974f40bcc7d7c59c2ad9
[ "MIT" ]
3
2021-09-20T10:34:15.000Z
2021-09-20T16:23:07.000Z
lib/lotus/list.ex
code-shoily/lotus
d14958956103f2376d51974f40bcc7d7c59c2ad9
[ "MIT" ]
null
null
null
lib/lotus/list.ex
code-shoily/lotus
d14958956103f2376d51974f40bcc7d7c59c2ad9
[ "MIT" ]
1
2021-11-23T13:10:27.000Z
2021-11-23T13:10:27.000Z
defmodule Lotus.List do @moduledoc """ Easily create nice looking lists, which come in different styles Documentation: https://getuikit.com/docs/list """ use Lotus.SimpleComponent @doc """ Marker """ prop marker, :string, values: ~w/disc circle square decimal hyphen/ @doc """ Color """ prop color, :string, values: ~w/muted emphasis primary secondary/ @doc """ Divider """ prop divider, :boolean @doc """ Striped """ prop striped, :boolean @doc """ Size """ prop size, :string, values: ~w/large collapse/ slot default def render(assigns) do ~F""" <ul class={list_class(assigns)} {...@opts}> <#slot /> </ul> """ end defp list_class(assigns) do [ Surface.css_class( "uk-list": true, "uk-list-#{assigns.marker}": assigns.marker, "uk-list-#{assigns.color}": assigns.color, "uk-list-divider": assigns.divider, "uk-list-striped": assigns.striped, "uk-list-#{assigns.size}": assigns.size ) | simple_base_classes(assigns) ] end end
18.793103
69
0.598165
03825fa085590e04909ae7eb0400850697acb736
1,029
ex
Elixir
lib/ambry_web/live/admin/components/button.ex
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
null
null
null
lib/ambry_web/live/admin/components/button.ex
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
null
null
null
lib/ambry_web/live/admin/components/button.ex
froseph/ambry
86c1a8528b9f3cc7e4a7debd8005df4116a7d1b1
[ "MIT" ]
null
null
null
defmodule AmbryWeb.Admin.Components.Button do @moduledoc """ Renders a button """ use AmbryWeb, :component @classes ~w( text-white font-bold w-full inline-flex justify-center rounded shadow px-5 py-2 sm:ml-3 sm:w-auto transition-colors focus:outline-none focus:ring-2 disabled:bg-gray-400 ) @color_classes %{ yellow: ~w( bg-yellow-500 hover:bg-yellow-700 focus:ring-yellow-300 ), red: ~w( bg-red-500 hover:bg-red-700 focus:ring-red-300 ) } prop label, :string, required: true prop click, :event, required: true prop color, :atom, default: :yellow prop class, :string, default: "" prop values, :list, default: [] def render(assigns) do ~F""" <button :on-click={@click} :values={@values} class={@class <> " " <> classes(@color)}> {@label} </button> """ end defp classes(color) do @classes |> Enum.concat(@color_classes[color]) |> Enum.join(" ") end end
18.052632
90
0.587949
03827a1e448e79221edbc3099662eadcf9cf59f6
370
ex
Elixir
lib/oli/activities/model/feedback.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
lib/oli/activities/model/feedback.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
lib/oli/activities/model/feedback.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Activities.Model.Feedback do @derive Jason.Encoder defstruct [:id, :content] def parse(%{"id" => id, "content" => content}) do {:ok, %Oli.Activities.Model.Feedback{id: id, content: content}} end def parse(%{"content" => _}) do {:error, "invalid feedback: missing id"} end def parse(_) do {:error, "invalid feedback"} end end
21.764706
67
0.640541
038291232118010cabd73ddca2bd6e8ce6293b6a
2,018
exs
Elixir
test/wobserver/web/router/system_test.exs
coby-spotim/wobserver
b0b9d77fb4ff40bb417f6b370ee343b8d42de750
[ "MIT" ]
null
null
null
test/wobserver/web/router/system_test.exs
coby-spotim/wobserver
b0b9d77fb4ff40bb417f6b370ee343b8d42de750
[ "MIT" ]
null
null
null
test/wobserver/web/router/system_test.exs
coby-spotim/wobserver
b0b9d77fb4ff40bb417f6b370ee343b8d42de750
[ "MIT" ]
1
2018-09-12T16:13:57.000Z
2018-09-12T16:13:57.000Z
defmodule Wobserver.Web.Router.SystemTest do use ExUnit.Case, async: true use Plug.Test alias Wobserver.Web.Router.System @opts System.init([]) test "/ returns overview" do conn = conn(:get, "/") conn = System.call(conn, @opts) assert conn.state == :sent assert conn.status == 200 assert %{ "architecture" => _, "cpu" => _, "memory" => _, "statistics" => _ } = Poison.decode!(conn.resp_body) end test "/architecture returns architecture" do conn = conn(:get, "/architecture") conn = System.call(conn, @opts) assert conn.state == :sent assert conn.status == 200 assert Poison.encode!(Wobserver.System.Info.architecture()) == conn.resp_body end test "/cpu returns cpu" do conn = conn(:get, "/cpu") conn = System.call(conn, @opts) assert conn.state == :sent assert conn.status == 200 assert Poison.encode!(Wobserver.System.Info.cpu()) == conn.resp_body end test "/memory returns memory" do conn = conn(:get, "/memory") conn = System.call(conn, @opts) assert conn.state == :sent assert conn.status == 200 assert %{ "atom" => _, "binary" => _, "code" => _, "ets" => _, "process" => _, "total" => _ } = Poison.decode!(conn.resp_body) end test "/statistics returns statistics" do conn = conn(:get, "/statistics") conn = System.call(conn, @opts) assert conn.state == :sent assert conn.status == 200 assert %{ "uptime" => _, "process_running" => _, "process_total" => _, "process_max" => _, "input" => _, "output" => _ } = Poison.decode!(conn.resp_body) end test "unknown url returns 404" do conn = conn(:get, "/unknown") conn = System.call(conn, @opts) assert conn.state == :sent assert conn.status == 404 end end
22.422222
81
0.54559
038292d95562a69f516dc515a6ab99ee37c4a5f9
1,925
exs
Elixir
clients/storage_transfer/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/storage_transfer/mix.exs
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.StorageTransfer.Mixfile do use Mix.Project @version "0.19.2" def project() do [ app: :google_api_storage_transfer, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/storage_transfer" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Storage Transfer API client library. Transfers data from external data sources to a Google Cloud Storage bucket or between Google Cloud Storage buckets. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/storage_transfer", "Homepage" => "https://cloud.google.com/storage-transfer/docs" } ] end end
28.731343
156
0.666494
038296136bc5b8cf44e488450b687a51f284874b
2,111
exs
Elixir
test/glimesh/community_team_test.exs
DeeRock94/glimesh.tv
e4517e4e3b03f98a3cab2d16b82f365e3b23fd9d
[ "MIT" ]
null
null
null
test/glimesh/community_team_test.exs
DeeRock94/glimesh.tv
e4517e4e3b03f98a3cab2d16b82f365e3b23fd9d
[ "MIT" ]
null
null
null
test/glimesh/community_team_test.exs
DeeRock94/glimesh.tv
e4517e4e3b03f98a3cab2d16b82f365e3b23fd9d
[ "MIT" ]
null
null
null
defmodule Glimesh.CommunityTeamTest do use Glimesh.DataCase import Glimesh.AccountsFixtures alias Glimesh.CommunityTeam describe "community team permission check functions" do test "access level returns correct title" do user = gct_fixture(%{gct_level: 5, tfa_token: "Fake 2fa token"}) assert CommunityTeam.access_level_to_title(user.gct_level) == "Admin" end test "can't edit user if no permission" do user = gct_fixture(%{gct_level: 2, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :edit_user, user, user_fixture()) == false end test "can't edit channel if no permission" do user = gct_fixture(%{gct_level: 1, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :edit_channel, user, user_fixture()) == false end test "can't edit user profile if no permission" do user = gct_fixture(%{gct_level: 1, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :edit_user_profile, user, user_fixture()) == false end test "can't ban user if no permission" do user = gct_fixture(%{gct_level: 1, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :can_ban, user, user_fixture()) == false end test "can't view audit log if no permission" do user = gct_fixture(%{gct_level: 2, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :view_audit_log, user, user_fixture()) == false end test "can't view billing info if no permission" do user = gct_fixture(%{gct_level: 3, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :view_billing_info, user, user_fixture()) == false end test "can't delete channel if no permission" do user = gct_fixture(%{gct_level: 2, tfa_token: "Fake 2fa token"}) assert Bodyguard.permit?(Glimesh.CommunityTeam, :soft_delete_channel, user, user_fixture()) == false end end end
34.048387
100
0.674562
03829c16d08de7cfeb2739aac01592dacc746b30
65
exs
Elixir
test/dataset_test.exs
edw/elixir-dataset
9f9265176019f2800927a0be7df511fa520533c8
[ "Apache-2.0" ]
1
2019-07-10T17:31:43.000Z
2019-07-10T17:31:43.000Z
test/dataset_test.exs
edw/elixir-dataset
9f9265176019f2800927a0be7df511fa520533c8
[ "Apache-2.0" ]
2
2019-04-14T20:36:05.000Z
2019-04-15T18:31:09.000Z
test/dataset_test.exs
edw/elixir-dataset
9f9265176019f2800927a0be7df511fa520533c8
[ "Apache-2.0" ]
null
null
null
defmodule DatasetTest do use ExUnit.Case doctest Dataset end
13
24
0.8
0382abb860b206ff344104d6cb76abfedb81c817
28
ex
Elixir
lib/genserver_example.ex
AbleTech/genserver_example
4c44e247b5d11eaafb01a32d8da892689d312091
[ "MIT" ]
null
null
null
lib/genserver_example.ex
AbleTech/genserver_example
4c44e247b5d11eaafb01a32d8da892689d312091
[ "MIT" ]
null
null
null
lib/genserver_example.ex
AbleTech/genserver_example
4c44e247b5d11eaafb01a32d8da892689d312091
[ "MIT" ]
null
null
null
defmodule GenExample do end
9.333333
23
0.857143
0382adc3b06bf19ae5995d1a3fd248b7dc72bf18
789
exs
Elixir
apps/irc/mix.exs
friendshipismagic/Hekateros
0d340b6818583e2e65b0395227c9bb91796e5f89
[ "MIT" ]
2
2019-03-22T12:29:37.000Z
2021-01-08T17:25:32.000Z
apps/irc/mix.exs
friendshipismagic/Hecateros
0d340b6818583e2e65b0395227c9bb91796e5f89
[ "MIT" ]
8
2017-12-04T16:53:35.000Z
2018-04-08T11:01:46.000Z
apps/irc/mix.exs
friendshipismagic/Hekateros
0d340b6818583e2e65b0395227c9bb91796e5f89
[ "MIT" ]
null
null
null
defmodule IRC.Mixfile do use Mix.Project def project do [ app: :irc, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.5", start_permanent: Mix.env == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {IRC.Application, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:core, in_umbrella: true}, {:exirc, github: "bitwalker/exirc", runtime: Mix.env() != :test}, {:open_graph_extended, "~> 0.1"}, {:web, in_umbrella: true} ] end end
21.916667
71
0.550063
0382b41b3419a4aece05b5e53f4bced3e35b9d7d
22,470
ex
Elixir
lib/ecto/adapters/sql.ex
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapters/sql.ex
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapters/sql.ex
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Adapters.SQL do @moduledoc """ Behaviour and implementation for SQL adapters. The implementation for SQL adapter relies on `DBConnection` to provide pooling, prepare, execute and more. Developers that use `Ecto.Adapters.SQL` should implement the callbacks required both by this module and the ones from `Ecto.Adapters.SQL.Connection` for handling connections and performing queries. """ @doc false defmacro __using__(adapter) do quote do @behaviour Ecto.Adapter @behaviour Ecto.Adapter.Migration @behaviour Ecto.Adapter.Transaction @conn __MODULE__.Connection @adapter unquote(adapter) @doc false defmacro __before_compile__(env) do Ecto.Adapters.SQL.__before_compile__(@adapter, env) end @doc false def ensure_all_started(repo, type) do Ecto.Adapters.SQL.ensure_all_started(@adapter, repo, type) end @doc false def child_spec(repo, opts) do Ecto.Adapters.SQL.child_spec(@conn, @adapter, repo, opts) end ## Types @doc false def autogenerate(:id), do: nil def autogenerate(:embed_id), do: Ecto.UUID.generate() def autogenerate(:binary_id), do: Ecto.UUID.bingenerate() @doc false def loaders({:embed, _} = type, _), do: [&Ecto.Adapters.SQL.load_embed(type, &1)] def loaders(:binary_id, type), do: [Ecto.UUID, type] def loaders(_, type), do: [type] @doc false def dumpers({:embed, _} = type, _), do: [&Ecto.Adapters.SQL.dump_embed(type, &1)] def dumpers(:binary_id, type), do: [type, Ecto.UUID] def dumpers(_, type), do: [type] ## Query @doc false def prepare(:all, query), do: {:cache, {System.unique_integer([:positive]), IO.iodata_to_binary(@conn.all(query))}} def prepare(:update_all, query), do: {:cache, {System.unique_integer([:positive]), IO.iodata_to_binary(@conn.update_all(query))}} def prepare(:delete_all, query), do: {:cache, {System.unique_integer([:positive]), IO.iodata_to_binary(@conn.delete_all(query))}} @doc false def execute(repo, meta, query, params, opts) do Ecto.Adapters.SQL.execute(repo, meta, query, params, opts) end @doc false def stream(repo, meta, query, params, opts) do Ecto.Adapters.SQL.stream(repo, meta, query, params, opts) end @doc false def insert_all(repo, %{source: source, prefix: prefix}, header, rows, {_, conflict_params, _} = on_conflict, returning, opts) do {rows, params} = Ecto.Adapters.SQL.unzip_inserts(header, rows) sql = @conn.insert(prefix, source, header, rows, on_conflict, returning) %{rows: rows, num_rows: num} = Ecto.Adapters.SQL.query!(repo, sql, Enum.reverse(params) ++ conflict_params, opts) {num, rows} end @doc false def insert(repo, %{source: source, prefix: prefix}, params, {kind, conflict_params, _} = on_conflict, returning, opts) do {fields, values} = :lists.unzip(params) sql = @conn.insert(prefix, source, fields, [fields], on_conflict, returning) Ecto.Adapters.SQL.struct(repo, @conn, sql, {:insert, source, []}, values ++ conflict_params, kind, returning, opts) end @doc false def update(repo, %{source: source, prefix: prefix}, fields, params, returning, opts) do {fields, field_values} = :lists.unzip(fields) filter_values = params |> Keyword.values() |> Enum.reject(&is_nil(&1)) sql = @conn.update(prefix, source, fields, params, returning) Ecto.Adapters.SQL.struct(repo, @conn, sql, {:update, source, params}, field_values ++ filter_values, :raise, returning, opts) end @doc false def delete(repo, %{source: source, prefix: prefix}, params, opts) do filter_values = params |> Keyword.values() |> Enum.reject(&is_nil(&1)) sql = @conn.delete(prefix, source, params, []) Ecto.Adapters.SQL.struct(repo, @conn, sql, {:delete, source, params}, filter_values, :raise, [], opts) end ## Transaction @doc false def transaction(repo, opts, fun) do Ecto.Adapters.SQL.transaction(repo, opts, fun) end @doc false def in_transaction?(repo) do Ecto.Adapters.SQL.in_transaction?(repo) end @doc false def rollback(repo, value) do Ecto.Adapters.SQL.rollback(repo, value) end ## Migration @doc false def execute_ddl(repo, definition, opts) do sqls = @conn.execute_ddl(definition) for sql <- List.wrap(sqls) do Ecto.Adapters.SQL.query!(repo, sql, [], opts) end :ok end @doc false def lock_for_migrations(repo, query, opts, fun) do Ecto.Adapters.SQL.lock_for_migrations(repo, query, opts, fun) end defoverridable [prepare: 2, execute: 5, insert: 6, update: 6, delete: 4, insert_all: 7, execute_ddl: 3, loaders: 2, dumpers: 2, autogenerate: 1, ensure_all_started: 2, lock_for_migrations: 4] end end @doc """ Converts the given query to SQL according to its kind and the adapter in the given repository. ## Examples The examples below are meant for reference. Each adapter will return a different result: iex> Ecto.Adapters.SQL.to_sql(:all, repo, Post) {"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []} iex> Ecto.Adapters.SQL.to_sql(:update_all, repo, from(p in Post, update: [set: [title: ^"hello"]])) {"UPDATE posts AS p SET title = $1", ["hello"]} This function is also available under the repository with name `to_sql`: iex> Repo.to_sql(:all, Post) {"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []} """ @spec to_sql(:all | :update_all | :delete_all, Ecto.Repo.t, Ecto.Queryable.t) :: {String.t, [term]} def to_sql(kind, repo, queryable) do adapter = repo.__adapter__ queryable |> Ecto.Queryable.to_query() |> Ecto.Query.Planner.ensure_select(kind == :all) |> Ecto.Query.Planner.query(kind, repo, adapter, 0) |> case do {_meta, {:cached, _reset, {_id, cached}}, params} -> {String.Chars.to_string(cached), params} {_meta, {:cache, _update, {_id, prepared}}, params} -> {prepared, params} {_meta, {:nocache, {_id, prepared}}, params} -> {prepared, params} end end @doc """ Same as `query/4` but raises on invalid queries. """ @spec query!(Ecto.Repo.t, String.t, [term], Keyword.t) :: %{:rows => nil | [[term] | binary], :num_rows => non_neg_integer, optional(atom) => any} | no_return def query!(repo, sql, params \\ [], opts \\ []) do case query(repo, sql, params, opts) do {:ok, result} -> result {:error, err} -> raise err end end @doc """ Runs custom SQL query on given repo. In case of success, it must return an `:ok` tuple containing a map with at least two keys: * `:num_rows` - the number of rows affected * `:rows` - the result set as a list. `nil` may be returned instead of the list if the command does not yield any row as result (but still yields the number of affected rows, like a `delete` command without returning would) ## Options * `:timeout` - The time in milliseconds to wait for a query to finish, `:infinity` will wait indefinitely. (default: 15_000) * `:pool_timeout` - The time in milliseconds to wait for a call to the pool to finish, `:infinity` will wait indefinitely. (default: 5_000) * `:log` - When false, does not log the query ## Examples iex> Ecto.Adapters.SQL.query(MyRepo, "SELECT $1::integer + $2", [40, 2]) {:ok, %{rows: [[42]], num_rows: 1}} For convenience, this function is also available under the repository: iex> MyRepo.query("SELECT $1::integer + $2", [40, 2]) {:ok, %{rows: [[42]], num_rows: 1}} """ @spec query(Ecto.Repo.t, String.t, [term], Keyword.t) :: {:ok, %{:rows => nil | [[term] | binary], :num_rows => non_neg_integer, optional(atom) => any}} | {:error, Exception.t} def query(repo, sql, params \\ [], opts \\ []) do sql_call(repo, :execute, [sql], params, opts) end defp sql_call(repo, callback, args, params, opts) do {repo_mod, sql, pool, default_opts} = lookup_pool(repo) conn = get_conn(pool) || pool opts = with_log(repo_mod, params, opts ++ default_opts) args = args ++ [params, opts] try do apply(sql, callback, [conn | args]) rescue err in DBConnection.OwnershipError -> message = err.message <> "\nSee Ecto.Adapters.SQL.Sandbox docs for more information." reraise %{err | message: message}, System.stacktrace end end defp put_source(opts, %{sources: sources}) when tuple_size(elem(sources, 0)) == 2 do {source, _} = elem(sources, 0) Keyword.put(opts, :source, source) end defp put_source(opts, _) do opts end ## Worker @doc false def __before_compile__(adapter, _env) do case Application.get_env(:ecto, :json_library) do nil -> :ok Jason -> IO.warn """ Jason is the default :json_library in Ecto 3.0. You no longer need to configure it explicitly, please remove this line from your config files: config :ecto, :json_library, Jason """ value -> IO.warn """ The :json_library configuration for the :ecto application is deprecated. Please configure the :json_library in the adapter instead: config #{inspect adapter}, :json_library, #{inspect value} """ end quote do @doc """ A convenience function for SQL-based repositories that executes the given query. See `Ecto.Adapters.SQL.query/4` for more information. """ def query(sql, params \\ [], opts \\ []) do Ecto.Adapters.SQL.query(__MODULE__, sql, params, opts) end @doc """ A convenience function for SQL-based repositories that executes the given query. See `Ecto.Adapters.SQL.query!/4` for more information. """ def query!(sql, params \\ [], opts \\ []) do Ecto.Adapters.SQL.query!(__MODULE__, sql, params, opts) end @doc """ A convenience function for SQL-based repositories that translates the given query to SQL. See `Ecto.Adapters.SQL.to_sql/3` for more information. """ def to_sql(operation, queryable) do Ecto.Adapters.SQL.to_sql(operation, __MODULE__, queryable) end end end @doc false def ensure_all_started(adapter, repo, type) do opts = pool_config(repo, repo.config) with {:ok, from_pool} <- DBConnection.ensure_all_started(opts, type), {:ok, from_adapter} <- Application.ensure_all_started(adapter, type), # We always return the adapter to force it to be restarted if necessary do: {:ok, from_pool ++ List.delete(from_adapter, adapter) ++ [adapter]} end defp pool_config(repo, opts) do opts |> Keyword.drop([:loggers, :priv, :url]) |> Keyword.put(:name, pool_name(repo, opts)) |> Keyword.update(:pool, DBConnection.Poolboy, &normalize_pool/1) end defp normalize_pool(pool) do if Code.ensure_loaded?(pool) && function_exported?(pool, :unboxed_run, 2) do DBConnection.Ownership else pool end end defp pool_name(repo, config) do Keyword.get_lazy(config, :pool_name, fn -> Module.concat(Keyword.get(config, :name, repo), Pool) end) end @doc false def child_spec(connection, adapter, repo, opts) do unless Code.ensure_loaded?(connection) do raise """ could not find #{inspect connection}. Please verify you have added #{inspect adapter} as a dependency: {#{inspect adapter}, ">= 0.0.0"} And remember to recompile Ecto afterwards by cleaning the current build: mix deps.clean --build ecto """ end pool_config = pool_config(repo, opts) pool_name = Keyword.fetch!(pool_config, :name) Ecto.Registry.associate(self(), {repo, connection, pool_name, pool_config}) connection.child_spec(pool_config) end ## Types @doc false def load_embed(type, value) do Ecto.Type.load(type, value, fn {:embed, _} = type, value -> load_embed(type, value) type, value -> Ecto.Type.cast(type, value) end) end @doc false def dump_embed(type, value) do Ecto.Type.dump(type, value, fn {:embed, _} = type, value -> dump_embed(type, value) _type, value -> {:ok, value} end) end ## Query @doc false def unzip_inserts(header, rows) do Enum.map_reduce rows, [], fn fields, params -> Enum.map_reduce header, params, fn key, acc -> case :lists.keyfind(key, 1, fields) do {^key, value} -> {key, [value|acc]} false -> {nil, acc} end end end end @doc false def execute(repo, meta, prepared, params, opts) do %{num_rows: num, rows: rows} = do_execute(repo, meta, prepared, params, put_source(opts, meta)) {num, rows} end defp do_execute(repo, _meta, {:cache, update, {id, prepared}}, params, opts) do execute_and_cache(repo, id, update, prepared, params, opts) end defp do_execute(repo, _meta, {:cached, reset, {id, cached}}, params, opts) do execute_or_reset(repo, id, reset, cached, params, opts) end defp do_execute(repo, _meta, {:nocache, {_id, prepared}}, params, opts) do case sql_call(repo, :execute, [prepared], params, opts) do {:ok, res} -> res {:error, err} -> raise err end end defp execute_and_cache(repo, id, update, prepared, params, opts) do name = "ecto_" <> Integer.to_string(id) case sql_call(repo, :prepare_execute, [name, prepared], params, opts) do {:ok, query, result} -> update.({id, query}) result {:error, err} -> raise err end end defp execute_or_reset(repo, id, reset, cached, params, opts) do case sql_call(repo, :execute, [cached], params, opts) do {:ok, result} -> result {:error, err} -> raise err {:reset, err} -> reset.({id, String.Chars.to_string(cached)}) raise err end end @doc """ Returns a stream that runs a custom SQL query on given repo when reduced. In case of success it is a enumerable containing maps with at least two keys: * `:num_rows` - the number of rows affected * `:rows` - the result set as a list. `nil` may be returned instead of the list if the command does not yield any row as result (but still yields the number of affected rows, like a `delete` command without returning would) In case of failure it raises an exception. If the adapter supports a collectable stream, the stream may also be used as the collectable in `Enum.into/3`. Behaviour depends on the adapter. ## Options * `:timeout` - The time in milliseconds to wait for a query to finish, `:infinity` will wait indefinitely (default: 15_000) * `:pool_timeout` - The time in milliseconds to wait for a call to the pool to finish, `:infinity` will wait indefinitely (default: 5_000) * `:log` - When false, does not log the query * `:max_rows` - The number of rows to load from the database as we stream ## Examples iex> Ecto.Adapters.SQL.stream(MyRepo, "SELECT $1::integer + $2", [40, 2]) |> Enum.to_list() [%{rows: [[42]], num_rows: 1}] """ @spec stream(Ecto.Repo.t, String.t, [term], Keyword.t) :: Enum.t def stream(repo, sql, params \\ [], opts \\ []) do Ecto.Adapters.SQL.Stream.__build__(repo, sql, params, opts) end @doc false def stream(repo, meta, prepared, params, opts) do do_stream(repo, meta, prepared, params, put_source(opts, meta)) end defp do_stream(repo, _meta, {:cache, _, {_, prepared}}, params, opts) do prepare_stream(repo, prepared, params, opts) end defp do_stream(repo, _, {:cached, _, {_, cached}}, params, opts) do prepare_stream(repo, String.Chars.to_string(cached), params, opts) end defp do_stream(repo, _meta, {:nocache, {_id, prepared}}, params, opts) do prepare_stream(repo, prepared, params, opts) end defp prepare_stream(repo, prepared, params, opts) do repo |> Ecto.Adapters.SQL.Stream.__build__(prepared, params, opts) |> Stream.map(fn(%{num_rows: nrows, rows: rows}) -> {nrows, rows} end) end @doc false def reduce(repo, statement, params, opts, acc, fun) do {repo_mod, sql, pool, default_opts} = lookup_pool(repo) opts = with_log(repo_mod, params, opts ++ default_opts) case get_conn(pool) do nil -> raise "cannot reduce stream outside of transaction" conn -> apply(sql, :stream, [conn, statement, params, opts]) |> Enumerable.reduce(acc, fun) end end @doc false def into(repo, statement, params, opts) do {repo_mod, sql, pool, default_opts} = lookup_pool(repo) opts = with_log(repo_mod, params, opts ++ default_opts) case get_conn(pool) do nil -> raise "cannot collect into stream outside of transaction" conn -> apply(sql, :stream, [conn, statement, params, opts]) |> Collectable.into() end end @doc false def struct(repo, conn, sql, {operation, source, params}, values, on_conflict, returning, opts) do case query(repo, sql, values, opts) do {:ok, %{rows: nil, num_rows: 1}} -> {:ok, []} {:ok, %{rows: [values], num_rows: 1}} -> {:ok, Enum.zip(returning, values)} {:ok, %{num_rows: 0}} -> if on_conflict == :nothing, do: {:ok, []}, else: {:error, :stale} {:ok, %{num_rows: num_rows}} when num_rows > 1 -> raise Ecto.MultiplePrimaryKeyError, source: source, params: params, count: num_rows, operation: operation {:error, err} -> case conn.to_constraints(err) do [] -> raise err constraints -> {:invalid, constraints} end end end ## Transactions @doc false def transaction(repo, opts, fun) do {repo_mod, _sql, pool, default_opts} = lookup_pool(repo) opts = with_log(repo_mod, [], opts ++ default_opts) case get_conn(pool) do nil -> do_transaction(pool, opts, fun) conn -> DBConnection.transaction(conn, fn(_) -> fun.() end, opts) end end defp do_transaction(pool, opts, fun) do run = fn(conn) -> try do put_conn(pool, conn) fun.() after delete_conn(pool) end end DBConnection.transaction(pool, run, opts) end @doc false def in_transaction?(repo) do {_repo_mod, _sql, pool, _default_opts} = lookup_pool(repo) !!get_conn(pool) end @doc false def rollback(repo, value) do {_repo_mod, _sql, pool, _default_opts} = lookup_pool(repo) case get_conn(pool) do nil -> raise "cannot call rollback outside of transaction" conn -> DBConnection.rollback(conn, value) end end ## Migrations @doc false def lock_for_migrations(repo, query, opts, fun) do {_repo_mod, _sql, _pool, default_opts} = lookup_pool(repo) if Keyword.fetch(default_opts, :pool_size) == {:ok, 1} do raise_pool_size_error() end {:ok, result} = transaction(repo, opts ++ [log: false, timeout: :infinity], fn -> query |> Map.put(:lock, Keyword.get(default_opts, :migration_lock, "FOR UPDATE")) |> repo.all() |> fun.() end) result end defp raise_pool_size_error do raise Ecto.MigrationError, """ Migrations failed to run because the connection pool size is less than 2. Ecto requires a pool size of at least 2 to support concurrent migrators. When migrations run, Ecto uses one connection to maintain a lock and another to run migrations. If you are running migrations with Mix, you can increase the number of connections via the pool size option: mix ecto.migrate --pool-size 2 If you are running the Ecto.Migrator programmatically, you can configure the pool size via your application config: config :my_app, Repo, adapter: Ecto.Adapters.Postgres, database: "ecto_simple", username: "postgres", password: "postgres", hostname: "localhost", pool_size: 2 # at least """ end ## Log defp with_log(repo, params, opts) do case Keyword.pop(opts, :log, true) do {true, opts} -> [log: &log(repo, params, &1, opts)] ++ opts {false, opts} -> opts end end defp log(repo, params, entry, opts) do %{connection_time: query_time, decode_time: decode_time, pool_time: queue_time, result: result, query: query} = entry source = Keyword.get(opts, :source) caller_pid = Keyword.get(opts, :caller, self()) query_string = String.Chars.to_string(query) repo.__log__(%Ecto.LogEntry{query_time: query_time, decode_time: decode_time, queue_time: queue_time, result: log_result(result), params: params, query: query_string, ansi_color: sql_color(query_string), source: source, caller_pid: caller_pid}) end defp log_result({:ok, _query, res}), do: {:ok, res} defp log_result(other), do: other ## Connection helpers defp lookup_pool(repo) do Ecto.Registry.lookup(repo) end defp put_conn(pool, conn) do _ = Process.put(key(pool), conn) :ok end defp get_conn(pool) do Process.get(key(pool)) end defp delete_conn(pool) do _ = Process.delete(key(pool)) :ok end defp key(pool), do: {__MODULE__, pool} defp sql_color("SELECT" <> _), do: :cyan defp sql_color("ROLLBACK" <> _), do: :red defp sql_color("LOCK" <> _), do: :white defp sql_color("INSERT" <> _), do: :green defp sql_color("UPDATE" <> _), do: :yellow defp sql_color("DELETE" <> _), do: :red defp sql_color("begin" <> _), do: :magenta defp sql_color("commit" <> _), do: :magenta defp sql_color(_), do: nil end
31.87234
133
0.622608
0382f4d073ee7881407a3ba7cf12346621b270fe
1,082
exs
Elixir
test/views/error_view_test.exs
remerle/asciinema-server
895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57
[ "Apache-2.0" ]
893
2017-09-14T14:18:29.000Z
2022-03-31T21:45:08.000Z
test/views/error_view_test.exs
remerle/asciinema-server
895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57
[ "Apache-2.0" ]
103
2017-09-29T22:15:33.000Z
2022-03-27T21:47:43.000Z
test/views/error_view_test.exs
remerle/asciinema-server
895bf5a7ffb7db1b418c97cfd2ac9136c46dfb57
[ "Apache-2.0" ]
152
2017-09-07T12:43:15.000Z
2022-03-10T18:47:47.000Z
defmodule Asciinema.ErrorViewTest do use AsciinemaWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(AsciinemaWeb.ErrorView, "404.html", []) =~ "Not Found" end test "renders 404.json" do assert render_to_string(AsciinemaWeb.ErrorView, "404.json", []) == "{\"error\":\"Not Found\"}" end test "render 500.html" do assert render_to_string(AsciinemaWeb.ErrorView, "500.html", []) == "Internal Server Error" end test "render 500.json" do assert render_to_string(AsciinemaWeb.ErrorView, "500.json", []) == "{\"error\":\"Internal Server Error\"}" end test "render any other (html)" do assert render_to_string(AsciinemaWeb.ErrorView, "505.html", []) == "HTTP Version Not Supported" end test "render any other (json)" do assert render_to_string(AsciinemaWeb.ErrorView, "505.json", []) == "{\"error\":\"HTTP Version Not Supported\"}" end end
29.243243
70
0.644177
03831833d65718f9d29853abb7ceebff9b1f0a05
1,935
ex
Elixir
lib/mix/lib/mix/tasks/loadpaths.ex
Tica2/elixir
6cf1dcbfe4572fc75619f05e40c10fd0844083ef
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/loadpaths.ex
Tica2/elixir
6cf1dcbfe4572fc75619f05e40c10fd0844083ef
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/loadpaths.ex
Tica2/elixir
6cf1dcbfe4572fc75619f05e40c10fd0844083ef
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Loadpaths do use Mix.Task @moduledoc """ Loads the application and its dependencies paths. ## Command line options * `--no-deps-check` - do not check dependencies * `--no-elixir-version-check` - do not check elixir version """ @spec run(OptionParser.argv) :: :ok def run(args) do config = Mix.Project.config unless "--no-elixir-version-check" in args do check_elixir_version(config, args) end # --no-deps is used only internally. It has not purpose # from Mix.CLI because the CLI itself already loads deps. unless "--no-deps" in args do load_deps(config, args) end if config[:app] do load_project(config, args) end :ok end defp check_elixir_version(config, _) do if req = config[:elixir] do case Version.parse_requirement(req) do {:ok, req} -> unless Version.match?(System.version, req) do Mix.raise Mix.ElixirVersionError, target: config[:app] || Mix.Project.get, expected: req, actual: System.version end :error -> Mix.raise "Invalid Elixir version requirement #{req} in mix.exs file" end end end defp load_deps(_config, args) do unless "--no-deps-check" in args do Mix.Task.run "deps.check", args end Mix.Task.run "deps.loadpaths" end defp load_project(config, _args) do vsn = System.version scm = config[:build_scm] # Force recompile if we have lock mismatch case Mix.Dep.Lock.status() do {:ok, old_vsn, _} when old_vsn != vsn -> rm_rf_app(config) {:ok, _, old_scm} when old_scm != scm -> rm_rf_app(config) _ -> :ok end Enum.each Mix.Project.load_paths(config), &Code.prepend_path(&1) end defp rm_rf_app(config) do File.rm_rf Mix.Project.app_path(config) end end
25.460526
86
0.611886
03831fe76a36061d424449771d9a13e6c70e29fd
913
ex
Elixir
lib/gute_taten.ex
honeypotio/gute_taten
043e3f53d5f5d9439654032f851a89287fa6d7ca
[ "MIT" ]
1
2016-06-08T08:12:55.000Z
2016-06-08T08:12:55.000Z
lib/gute_taten.ex
honeypotio/gute_taten
043e3f53d5f5d9439654032f851a89287fa6d7ca
[ "MIT" ]
6
2016-03-26T08:49:12.000Z
2018-04-10T15:51:46.000Z
lib/gute_taten.ex
honeypotio/gute_taten
043e3f53d5f5d9439654032f851a89287fa6d7ca
[ "MIT" ]
1
2016-03-30T08:09:17.000Z
2016-03-30T08:09:17.000Z
defmodule GuteTaten do @doc """ Retrieves a list of good deeds for a given github username ## Example GuteTaten.retrieve("duksis") """ @default_rules ["UsefulProjects", "GivingBackTheLove"] @rules Application.get_env(:gute_taten, :rules, @default_rules) @spec retrieve(binary) :: binary def retrieve(github_identity) do github_identity |> search_deeds |> format_output end @spec search_deeds(binary, [binary]) :: [map] defp search_deeds(github_username, rules \\ @rules) do Enum.map(rules, fn(x) -> Module.concat(__MODULE__, x).call(github_username) end) |> List.flatten end @spec format_output([map]) :: binary defp format_output(response) do #TODO implement cofigurable output formaters csv, json ... response |> to_json end @spec to_json([map]) :: binary defp to_json(deeds) do deeds |> JSX.encode! |> JSX.prettify! end end
25.361111
84
0.684556
038342df9917d6f686cc9233978c40395bb2a376
2,906
ex
Elixir
lib/dornach_web/views/select_helpers.ex
ream88/jw-dornach
0a25deae13fafd832421bde21bc21035a128ac7d
[ "MIT" ]
null
null
null
lib/dornach_web/views/select_helpers.ex
ream88/jw-dornach
0a25deae13fafd832421bde21bc21035a128ac7d
[ "MIT" ]
4
2020-01-28T10:12:25.000Z
2021-05-10T23:05:12.000Z
lib/dornach_web/views/select_helpers.ex
ream88/jw-dornach
0a25deae13fafd832421bde21bc21035a128ac7d
[ "MIT" ]
null
null
null
defmodule DornachWeb.SelectHelpers do @moduledoc """ A module which helps with creating the select fields for the event datetimes. """ defmodule Option do @moduledoc false defstruct local: nil, utc: nil, disabled: false, selected: false end @opaque option :: [key: String.t(), value: String.t(), disabled: boolean(), selected: boolean()] alias Dornach.Calendar alias DornachWeb.SelectHelpers.Option @spec from_options(Phoenix.HTML.Form.t(), Date.t()) :: [option()] def from_options(form, date) do events = Calendar.get_events(date) from = fetch_field(form, :from, default(:from, date)) date |> options() |> Enum.map(fn %{local: local, utc: utc} -> [ key: NimbleStrftime.format(local, "%H:%M"), value: DateTime.to_iso8601(utc), disabled: Enum.any?(events, &Timex.between?(utc, &1.from, &1.to, inclusive: :start)), selected: DateTime.compare(utc, from) == :eq ] end) end @spec to_options(Phoenix.HTML.Form.t(), Date.t()) :: [option()] def to_options(form, date) do from = fetch_field(form, :from, default(:from, date)) to = fetch_field(form, :to, default(:to, date)) date |> options() |> Enum.filter(fn %{utc: utc} -> DateTime.compare(from, utc) == :lt end) |> Enum.map(fn %{local: local, utc: utc} -> key = NimbleStrftime.format(local, "%H:%M") <> " – " <> duration_in_hours(from, utc) <> " h" [ key: key, value: DateTime.to_iso8601(utc), disabled: false, selected: DateTime.compare(utc, to) == :eq ] end) end defp options(date) do for hour <- 0..23 do for minute <- Enum.take_every(0..59, 15) do {:ok, time} = Time.new(hour, minute, 0) {:ok, naive} = NaiveDateTime.new(date, time) {:ok, local} = DateTime.from_naive(naive, "Europe/Vienna") {:ok, utc} = DateTime.shift_zone(local, "UTC") %Option{local: local, utc: utc} end end |> List.flatten() end defp duration_in_hours(from, to) do diff = DateTime.diff(to, from, :second) case {div(diff, 3600), rem(diff, 3600)} do {0, 900} -> "¼" {0, 1800} -> "½" {0, 2700} -> "¾" {quotient, 0} -> to_string(quotient) {quotient, 900} -> to_string(quotient) <> " ¼" {quotient, 1800} -> to_string(quotient) <> " ½" {quotient, 2700} -> to_string(quotient) <> " ¾" _ -> "" end end defp fetch_field(form, field, default_value) do case Ecto.Changeset.fetch_field!(form.source, field) do nil -> default_value value -> value end end defp default(:from, date) do {:ok, time} = Time.new(0, 0, 0) {:ok, naive} = NaiveDateTime.new(date, time) {:ok, local} = DateTime.from_naive(naive, "Europe/Vienna") local end defp default(:to, date) do default(:from, date) |> DateTime.add(900, :second) end end
28.490196
98
0.594632
03834faf0992b8359ec778f4606b7cce1d9f8969
1,033
ex
Elixir
lib/version_tasks/fn_expr.ex
kianmeng/version_tasks
9b07113ce5155bcadae47c49a0ecaec22b1d7c68
[ "MIT" ]
18
2017-07-09T23:47:38.000Z
2021-09-30T09:24:37.000Z
lib/version_tasks/fn_expr.ex
kianmeng/version_tasks
9b07113ce5155bcadae47c49a0ecaec22b1d7c68
[ "MIT" ]
1
2022-01-29T08:48:10.000Z
2022-01-29T08:48:10.000Z
lib/version_tasks/fn_expr.ex
kianmeng/version_tasks
9b07113ce5155bcadae47c49a0ecaec22b1d7c68
[ "MIT" ]
2
2019-09-24T11:09:28.000Z
2021-11-02T00:40:05.000Z
defmodule VersionTasks.FnExpr do @moduledoc """ THIS IS A DUPLICATE OF https://hex.pm/packages/fn_expr so that project can leverage this version management (avoiding) a circular dependency. If you want this functionality, then please install it instead @deps [ fn_expr: "~> 0.1.0" ] """ defmacro __using__(_) do quote do defmacro invoke(piped_in_argument, expr) do fun = is_tuple(expr) && elem(expr, 0) case fun do :fn -> quote do unquote(expr).(unquote(piped_in_argument)) end _ -> quote do (&unquote(expr)).(unquote(piped_in_argument)) end end end end end def default(piped_in_argument, default_value) do case piped_in_argument do nil -> default_value _ -> piped_in_argument end end defmacro unquote(:&&)(piped_in_argument, expr) do quote do (&unquote(expr)).(unquote(piped_in_argument)) end end end
21.978723
68
0.595353
038352de74138d56673bb2e10ef32c77fd7373d8
1,426
exs
Elixir
test/changelog_web/controllers/page_controller_test.exs
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
1
2021-03-14T21:12:49.000Z
2021-03-14T21:12:49.000Z
test/changelog_web/controllers/page_controller_test.exs
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
null
null
null
test/changelog_web/controllers/page_controller_test.exs
PsOverflow/changelog.com
53f4ecfc39b021c6b8cfcc0fa11f29aff8038a7f
[ "MIT" ]
1
2018-10-03T20:55:52.000Z
2018-10-03T20:55:52.000Z
defmodule ChangelogWeb.PageControllerTest do use ChangelogWeb.ConnCase test "static pages all render", %{conn: conn} do Enum.each([ "/about", "/contact", "/films", "/community", "/nightly", "/sponsor", "/sponsor/pricing", "/team", "/weekly", "/weekly/archive" ], fn route -> conn = get(conn, route) assert conn.status == 200 end) end describe "guest" do test "it falls back to The Changelog with no slug", %{conn: conn} do changelog = insert(:podcast, name: "The Changelog", slug: "podcast") conn = get(conn, "/guest") assert html_response(conn, 200) =~ changelog.name end test "it uses the provided Podcast slug", %{conn: conn} do rfc = insert(:podcast, name: "Request For Commits", slug: "rfc") conn = get(conn, "/guest/rfc") assert html_response(conn, 200) =~ rfc.name end end describe "sponsor stories" do test "it renders for all known sponsor stories", %{conn: conn} do for story <- Changelog.SponsorStory.all() do conn = get(conn, page_path(conn, :sponsor_story, story.slug)) assert html_response(conn, 200) =~ story.sponsor end end test "it falls back to the rollbar story", %{conn: conn} do conn = get(conn, page_path(conn, :sponsor_story, "ohai")) assert html_response(conn, 200) =~ "Rollbar" end end end
28.52
74
0.607994
03835ff08d92c3ce31603aa5c317b407b6f29882
3,798
exs
Elixir
integration_test/test/code_generation/app_with_mysql_adapter_test.exs
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
18,092
2015-01-01T01:51:04.000Z
2022-03-31T19:37:14.000Z
integration_test/test/code_generation/app_with_mysql_adapter_test.exs
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,905
2015-01-01T00:22:47.000Z
2022-03-31T17:06:21.000Z
integration_test/test/code_generation/app_with_mysql_adapter_test.exs
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,205
2015-01-03T10:58:22.000Z
2022-03-30T14:55:57.000Z
defmodule Phoenix.Integration.CodeGeneration.AppWithMySqlAdapterTest do use Phoenix.Integration.CodeGeneratorCase, async: true describe "phx.gen.html" do @tag database: :mysql test "has a passing test suite" do with_installer_tmp("app_with_defaults", fn tmp_dir -> {app_root_path, _} = generate_phoenix_app(tmp_dir, "default_mysql_app", ["--database", "mysql"]) mix_run!(~w(phx.gen.html Blog Post posts title body:string status:enum:unpublished:published:deleted), app_root_path) modify_file(Path.join(app_root_path, "lib/default_mysql_app_web/router.ex"), fn file -> inject_before_final_end(file, """ scope "/", DefaultMysqlAppWeb do pipe_through [:browser] resources "/posts", PostController end """) end) drop_test_database(app_root_path) assert_tests_pass(app_root_path) end) end end describe "phx.gen.json" do @tag database: :mysql test "has a passing test suite" do with_installer_tmp("app_with_defaults", fn tmp_dir -> {app_root_path, _} = generate_phoenix_app(tmp_dir, "default_mysql_app", ["--database", "mysql"]) mix_run!(~w(phx.gen.json Blog Post posts title body:string status:enum:unpublished:published:deleted), app_root_path) modify_file(Path.join(app_root_path, "lib/default_mysql_app_web/router.ex"), fn file -> inject_before_final_end(file, """ scope "/", DefaultMysqlAppWeb do pipe_through [:api] resources "/posts", PostController, except: [:new, :edit] end """) end) drop_test_database(app_root_path) assert_tests_pass(app_root_path) end) end end describe "phx.gen.live" do @tag database: :mysql test "has a passing test suite" do with_installer_tmp("app_with_defaults", fn tmp_dir -> {app_root_path, _} = generate_phoenix_app(tmp_dir, "default_mysql_app", ["--database", "mysql", "--live"]) mix_run!(~w(phx.gen.live Blog Post posts title body:string status:enum:unpublished:published:deleted), app_root_path) modify_file(Path.join(app_root_path, "lib/default_mysql_app_web/router.ex"), fn file -> inject_before_final_end(file, """ scope "/", DefaultMysqlAppWeb do pipe_through [:browser] live "/posts", PostLive.Index, :index live "/posts/new", PostLive.Index, :new live "/posts/:id/edit", PostLive.Index, :edit live "/posts/:id", PostLive.Show, :show live "/posts/:id/show/edit", PostLive.Show, :edit end """) end) drop_test_database(app_root_path) assert_tests_pass(app_root_path) end) end end describe "phx.gen.auth + argon2" do test "has no compilation or formatter warnings" do with_installer_tmp("new with defaults", fn tmp_dir -> {app_root_path, _} = generate_phoenix_app(tmp_dir, "phx_blog", ["--database", "mysql", "--binary-id"]) mix_run!(~w(phx.gen.auth Accounts User users --hashing-lib argon2), app_root_path) assert_no_compilation_warnings(app_root_path) assert_passes_formatter_check(app_root_path) end) end @tag database: :mysql test "has a passing test suite" do with_installer_tmp("app_with_defaults", fn tmp_dir -> {app_root_path, _} = generate_phoenix_app(tmp_dir, "default_app", ["--database", "mysql", "--binary-id"]) mix_run!(~w(phx.gen.auth Accounts User users --hashing-lib argon2), app_root_path) drop_test_database(app_root_path) assert_tests_pass(app_root_path) end) end end end
33.910714
125
0.640074
0383941c83fa9f45e6cfc067ff3ce9270d73f685
483
ex
Elixir
lib/ex_phone_number/constants/phone_number_types.ex
msharp/ex_phone_number
ae8d4fb8d78b119b64fb926d4047ddf133d9998b
[ "MIT" ]
179
2016-05-18T17:51:14.000Z
2022-03-17T17:01:53.000Z
lib/ex_phone_number/constants/phone_number_types.ex
msharp/ex_phone_number
ae8d4fb8d78b119b64fb926d4047ddf133d9998b
[ "MIT" ]
45
2016-05-18T15:46:39.000Z
2022-03-04T12:48:54.000Z
lib/ex_phone_number/constants/phone_number_types.ex
msharp/ex_phone_number
ae8d4fb8d78b119b64fb926d4047ddf133d9998b
[ "MIT" ]
52
2016-06-06T05:21:00.000Z
2022-01-07T22:38:22.000Z
defmodule ExPhoneNumber.Constants.PhoneNumberTypes do def fixed_line(), do: :fixed_line def mobile(), do: :mobile def fixed_line_or_mobile(), do: :fixed_line_or_mobile def toll_free(), do: :toll_free def premium_rate(), do: :premium_rate def shared_cost(), do: :shared_cost def voip(), do: :voip def personal_number(), do: :personal_number def pager(), do: :pager def uan(), do: :uan def voicemail(), do: :voicemail def unknown(), do: :unknown end
18.576923
55
0.691511
0383ace693d73aeae509e0a35f3b79b859d82747
5,097
exs
Elixir
integration_test/cases/queue_test.exs
ericentin/db_connection
5a11383dd250e77b8475fddba92e26e2bf9efad8
[ "Apache-2.0" ]
null
null
null
integration_test/cases/queue_test.exs
ericentin/db_connection
5a11383dd250e77b8475fddba92e26e2bf9efad8
[ "Apache-2.0" ]
null
null
null
integration_test/cases/queue_test.exs
ericentin/db_connection
5a11383dd250e77b8475fddba92e26e2bf9efad8
[ "Apache-2.0" ]
null
null
null
defmodule QueueTest do use ExUnit.Case, async: true alias TestPool, as: P alias TestAgent, as: A test "queue: false raises on busy" do stack = [{:ok, :state}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self()] {:ok, pool} = P.start_link(opts) P.run(pool, fn(_) -> {queue_time, _} = :timer.tc(fn() -> opts = [queue: false] assert_raise DBConnection.ConnectionError, "connection not available and queuing is disabled", fn() -> P.run(pool, fn(_) -> flunk("got connection") end, opts) end end) assert queue_time <= 1_000_000, "request was queued" end) end test "queue many async" do stack = [{:ok, :state}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self()] {:ok, pool} = P.start_link(opts) run = fn() -> P.run(pool, fn(_) -> :timer.sleep(20) end) end for task <- Enum.map(1..10, fn(_) -> Task.async(run) end) do assert :ok = Task.await(task) end end test "queue many async timeouts" do stack = [{:ok, :state}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self(), queue_timeout: 50] {:ok, pool} = P.start_link(opts) parent = self() runner = spawn_link(fn() -> P.run(pool, fn(_) -> send(parent, {:go, self()}) receive do {:done, ^parent} -> :ok end end) end) assert_receive {:go, ^runner} run = fn() -> try do P.run(pool, fn(_) -> flunk("run ran") end, [pool_timeout: 50]) rescue DBConnection.ConnectionError -> :error catch :exit, {:timeout, _} -> :error end end for task <- Enum.map(1..10, fn(_) -> Task.async(run) end) do assert Task.await(task) == :error end send(runner, {:done, self()}) assert P.run(pool, fn(_) -> :result end) == :result end test "queue many async exits" do stack = [{:ok, :state}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self()] {:ok, pool} = P.start_link(opts) parent = self() runner = spawn_link(fn() -> P.run(pool, fn(_) -> send(parent, {:go, self()}) receive do {:done, ^parent} -> :ok end end) end) assert_receive {:go, ^runner} run = fn() -> _ = :timer.apply_after(100, Process, :exit, [self(), :shutdown]) P.run(pool, fn(_) -> flunk("run ran") end) end Process.flag(:trap_exit, true) for task <- Enum.map(1..10, fn(_) -> Task.async(run) end) do assert catch_exit(Task.await(task)) == {:shutdown, {Task, :await, [task, 5_000]}} end send(runner, {:done, self()}) assert P.run(pool, fn(_) -> :result end) == :result end @tag :enqueue_disconnected test "queue raises disconnect error when disconnected" do stack = [{:error, RuntimeError.exception("oops")}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self(), backoff_start: 30_000] {:ok, pool} = P.start_link(opts) {queue_time, _} = :timer.tc(fn() -> opts = [queue: false] assert_raise DBConnection.ConnectionError, "connection not available because of disconnection", fn() -> P.run(pool, fn(_) -> flunk("got connection") end, opts) end end) assert queue_time <= 1_000_000, "request was queued" end @tag :dequeue_disconnected test "queue raises dropped from queue when disconnected" do stack = [{:error, RuntimeError.exception("oops")}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self(), backoff_start: 30_000] {:ok, pool} = P.start_link(opts) {queue_time, _} = :timer.tc(fn() -> opts = [queue: false] assert_raise DBConnection.ConnectionError, "connection not available and queuing is disabled", fn() -> P.run(pool, fn(_) -> flunk("got connection") end, opts) end end) assert queue_time <= 1_000_000, "request was queued" end @tag :queue_timeout_exit test "queue exits on timeout" do stack = [{:ok, :state}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self(), backoff_start: 30_000, queue_timeout: 10, pool_timeout: 10] {:ok, pool} = P.start_link(opts) P.run(pool, fn(_) -> assert {:timeout, {_, _, _}} = catch_exit(P.run(pool, fn() -> flunk("got connection") end, opts)) end) assert P.run(pool, fn(_) -> :hi end) == :hi end @tag :queue_timeout_raise test "queue raise on timeout" do stack = [{:ok, :state}] {:ok, agent} = A.start_link(stack) opts = [agent: agent, parent: self(), backoff_start: 30_000, queue_timeout: 10, pool_timeout: 10] {:ok, pool} = P.start_link(opts) P.run(pool, fn(_) -> assert_raise DBConnection.ConnectionError, ~r"^connection not available and request was dropped from queue after \d+ms$", fn() -> P.run(pool, fn(_) -> flunk("got connection") end, opts) end end) assert P.run(pool, fn(_) -> :hi end) == :hi end end
28.316667
86
0.578772
0383f57d8d4e3e95816d3c8e4e008a0dfc7c1c2b
9,645
exs
Elixir
apps/ae_socket_connector/test/client_runner_test.exs
nikita-fuchs/ae-channel-service
ae757a65d4ccaf553faa6703324f4e9953d0640e
[ "ISC" ]
null
null
null
apps/ae_socket_connector/test/client_runner_test.exs
nikita-fuchs/ae-channel-service
ae757a65d4ccaf553faa6703324f4e9953d0640e
[ "ISC" ]
null
null
null
apps/ae_socket_connector/test/client_runner_test.exs
nikita-fuchs/ae-channel-service
ae757a65d4ccaf553faa6703324f4e9953d0640e
[ "ISC" ]
null
null
null
defmodule ClientRunner do use GenServer require Logger defmacro ae_url, do: Application.get_env(:ae_socket_connector, :node)[:ae_url] defmacro network_id, do: Application.get_env(:ae_socket_connector, :node)[:network_id] defstruct pid_session_holder: nil, color: nil, match_list: nil, role: nil, fuzzy_counter: 0, paused: false def start_link( {_pub_key, _priv_key, _state_channel_configuration, _log_config, _ae_url, _network_id, _role, _jobs, _color, _name} = params ) do GenServer.start_link(__MODULE__, params) end defp log_callback({type, message}) do Logger.info( "received: #{inspect({type, message})} pid is: #{inspect(self())}", ansi_color: Map.get(message, :color, nil) ) end def filter_jobs(job_list, role) do for {runner, event} <- job_list, runner == role, do: event end # Server def init( {pub_key, priv_key, state_channel_configuration, log_config, ae_url, network_id, role, jobs, color, name} ) do {:ok, pid_session_holder} = SessionHolder.start_link(%{ socket_connector: %{ pub_key: pub_key, session: state_channel_configuration, role: role }, log_config: log_config, ae_url: ae_url, network_id: network_id, priv_key: priv_key, connection_callbacks: SessionHolderHelper.connection_callback(self(), color, &log_callback/1), color: color, }, name) {:ok, %__MODULE__{ pid_session_holder: pid_session_holder, match_list: jobs, role: role, color: [ansi_color: color] }} end def run_next(match) do case Map.get(match, :next, false) do false -> :ok job -> # Logger.debug("running next", state.color) GenServer.cast(self(), {:process_job_lists, job}) end end def process_sign_request(message, to_sign, pid_session_holder, mode \\ %{sign: {:default}}) def process_sign_request({}, _to_sign, _pid_session_holder, _mode) do Logger.debug("Empty request") end def process_sign_request(message, to_sign, pid_session_holder, %{sign: sign_info}) do case elem(message, 0) do :sign_approve -> case sign_info do {:default} -> signed = SessionHolder.sign_message(pid_session_holder, to_sign) fun = &SocketConnector.send_signed_message(&1, elem(message, 2), signed) SessionHolder.run_action(pid_session_holder, fun) {:backchannel, pid_other_session_holder} -> signed = SessionHolder.sign_message(pid_session_holder, to_sign) signed2 = SessionHolder.sign_message(pid_other_session_holder, signed) fun = &SocketConnector.send_signed_message(&1, elem(message, 2), signed2) SessionHolder.run_action(pid_session_holder, fun) {:check_poi} -> fun = &SocketConnector.get_poi/2 poi = SessionHolder.run_action_sync(pid_session_holder, fun) case SessionHolder.verify_poi(pid_session_holder, to_sign, poi) do :ok -> signed = SessionHolder.sign_message(pid_session_holder, to_sign) fun = fn pid -> SocketConnector.send_signed_message(pid, elem(message, 2), signed) end SessionHolder.run_action(pid_session_holder, fun) :unsecure -> Logger.warn("POI missmatch, refuse signing") end {:abort, abort_code} -> method = elem(message, 2) fun = &SocketConnector.abort(&1, method, abort_code, "some message") SessionHolder.run_action(pid_session_holder, fun) _ -> Logger.debug("Don't sign") end _ -> :ok end end def process_sign_request(message, to_sign, pid_session_holder, _not_sign_request) do process_sign_request(message, to_sign, pid_session_holder) end def handle_cast({:connection_update, update}, state) do Logger.debug("Connection update, #{inspect update}") {:noreply, state} end def handle_cast({:end_pause}, state) do GenServer.cast(self(), {:match_jobs, {}, nil}) {:noreply, %__MODULE__{state | paused: false}} end def handle_cast({:match_jobs, received_message, _to_sign}, %__MODULE__{paused: true} = state) do Logger.debug( "PAUSED role: #{inspect(state.role)} ignoring message #{inspect(received_message)}", state.color ) {:noreply, state} end # message is mandated in every entry def handle_cast({:match_jobs, received_message, to_sign}, state) do case state.match_list do [%{message: expected} = entry | rest] -> Logger.debug( "match: #{inspect(expected == received_message)} role: #{inspect(state.role)} expected #{ inspect(expected) } received #{inspect(received_message)}", state.color ) process_sign_request(received_message, to_sign, state.pid_session_holder, entry) case expected == received_message do true -> run_next(entry) {:noreply, %__MODULE__{state | match_list: rest, fuzzy_counter: 0}} false -> case Map.get(entry, :fuzzy, 0) do 0 -> throw("message not matching") value -> case state.fuzzy_counter >= value do true -> throw( "message role #{inspect(state.role)} #{inspect(expected)}, last received is #{ inspect(received_message) } has not arrived, waited for #{inspect(state.fuzzy_counter)} max wait #{inspect(value)}" ) false -> Logger.debug( "adding to counter... #{inspect(state.fuzzy_counter)} max wait #{inspect(value)}", state.color ) {:noreply, %__MODULE__{state | fuzzy_counter: state.fuzzy_counter + 1}} end end end [%{next: _next} = entry | rest] -> process_sign_request(received_message, to_sign, state.pid_session_holder, entry) run_next(entry) {:noreply, %__MODULE__{state | match_list: rest, fuzzy_counter: 0}} [] -> process_sign_request(received_message, to_sign, state.pid_session_holder) Logger.debug("list reached end", state.color) {:noreply, state} end end def handle_cast({:process_job_lists, next}, state) do {mode, fun, assert_fun} = next case mode do :async -> SessionHolder.run_action(state.pid_session_holder, fun) {:noreply, state} :sync -> response = SessionHolder.run_action_sync(state.pid_session_holder, fun) case assert_fun do :empty -> :empty _ -> assert_fun.(response) end GenServer.cast(self(), {:match_jobs, {}, nil}) {:noreply, state} :local -> fun.(self(), state.pid_session_holder) {:noreply, state} :pause -> fun.(self(), state.pid_session_holder) Logger.debug("role: #{inspect(state.role)} entering pause") {:noreply, %__MODULE__{state | paused: true}} end end # def gen_name(name, suffix) do # String.to_atom(to_string(name) <> Integer.to_string(suffix)) # end # elimiation overlap yields issues, need to be investigated # @grace_period_ms 2000 # def start_helper(ae_url, network_id, initiator_keys, responder_keys, joblist) do # Enum.each(Enum.zip(joblist, 1..Enum.count(joblist)), fn {fun, suffix} -> # Logger.info("Launching next job in queue") # start_peers( # ae_url, # network_id, # {gen_name(:alice, suffix), initiator_keys}, # {gen_name(:bob, suffix), responder_keys}, # fun # ) # Process.sleep(@grace_period_ms) # end) # end def await_finish([]) do Logger.debug("Scenario reached end") end def await_finish(expected_messages) do receive do {:test_finished, name} -> reduced_list = List.delete(expected_messages, name) Logger.debug("Received message from runner: #{inspect(name)} remaining: #{inspect(reduced_list)}") await_finish(reduced_list) end end def start_peers( ae_url, network_id, %{ initiator: %{name: name_initiator, keypair: {initiator_pub, _initiator_priv}}, responder: %{name: name_responder, keypair: {responder_pub, _responder_priv}} } = clients, job_builder ) do Logger.debug("executing test: #{inspect(job_builder)}") job_list = job_builder.({name_initiator, initiator_pub}, {name_responder, responder_pub}, self()) Enum.map(clients, fn{role, %{name: name, keypair: {pub, priv}} = config} -> channel_configuration = Map.get(config, :custom_configuration, &SessionHolderHelper.default_configuration/2) case Map.get(config, :start, true) do true -> color = case role do :initiator -> :yellow :responder -> :blue end start_link( {pub, priv, channel_configuration.(initiator_pub, responder_pub), Map.get(config, :log_config, %{}), ae_url, network_id, role, filter_jobs(job_list, role), color, name} ) false -> # test running with only one client :ok end end) await_finish([name_initiator, name_responder]) end end
31.622951
114
0.607983
0384133e619dca0042180c22406942001d9102bb
1,391
ex
Elixir
test/support/helpers.ex
learn-co/railway_ipc
aeec16fb5b315fb3d8472b38c6eeea20d20e731a
[ "MIT" ]
2
2021-03-22T19:37:33.000Z
2022-01-04T08:48:20.000Z
test/support/helpers.ex
learn-co/railway_ipc
aeec16fb5b315fb3d8472b38c6eeea20d20e731a
[ "MIT" ]
10
2019-11-29T20:24:24.000Z
2021-02-26T22:06:13.000Z
test/support/helpers.ex
learn-co/railway_ipc
aeec16fb5b315fb3d8472b38c6eeea20d20e731a
[ "MIT" ]
1
2020-01-09T17:13:29.000Z
2020-01-09T17:13:29.000Z
defmodule Test.Support.Helpers do @moduledoc """ Various test helpers. """ @doc """ Repeatedly executes `fun` until it either returns `true` or reaches `timeout`. ## Example In a test, publish a message to a queue, then wait until it arrives in the queue. Fail if the message hasn't arrived after two seconds. ``` wait_for_true(_2_seconds = 2000, fn -> assert 1 == queue_count("example_queue") end) ``` """ def wait_for_true(timeout, fun) when timeout > 0 do fun.() rescue _ -> Process.sleep(100) wait_for_true(timeout - 100, fun) end def wait_for_true(_timeout, fun), do: fun.() @doc """ Given an `expr` that evaluates to an integer, execute `expr` and store the result. Then execute `block` which should trigger a side effect that changes the result of `expr`. The before and after results of `expr` are compared to the value of `by`, ensuring they are equal. ## Example Asserts that a database table row count was changed. ``` assert_difference row_count("railway_ipc_published_messages"), by: 1 do :ok = Client.publish("railwayipc:test", proto, "json_protobuf") end ``` """ defmacro assert_difference(expr, [by: by], do: block) do quote do before = unquote(expr) unquote(block) after_ = unquote(expr) assert unquote(by) == after_ - before end end end
23.576271
78
0.664989
03841bca90f4e9a2367060cd825d444e02cce5b5
229
exs
Elixir
test/test_helper.exs
camelohq/cocktail
9b25d8f24d148397be6537ab1414abdbdec1ce8d
[ "MIT" ]
null
null
null
test/test_helper.exs
camelohq/cocktail
9b25d8f24d148397be6537ab1414abdbdec1ce8d
[ "MIT" ]
1
2020-11-12T10:04:27.000Z
2020-11-12T10:13:29.000Z
test/test_helper.exs
camelohq/cocktail
9b25d8f24d148397be6537ab1414abdbdec1ce8d
[ "MIT" ]
2
2020-08-03T12:03:39.000Z
2020-11-11T14:36:45.000Z
ExUnit.configure(exclude: [pending: true], formatters: [ExUnit.CLIFormatter, ExUnitNotifier]) ExUnit.start() {:ok, files} = File.ls("./test/support") Enum.each(files, fn file -> Code.require_file("test/support/#{file}") end)
25.444444
93
0.71179
038438b913285ab8302aba6c53d6cc95fcaee445
1,363
ex
Elixir
lib/ark_client/api/two/transaction.ex
supaiku0/elixir-client
2d5549ce3a876a18750a36a14ff769427688c5bb
[ "MIT" ]
null
null
null
lib/ark_client/api/two/transaction.ex
supaiku0/elixir-client
2d5549ce3a876a18750a36a14ff769427688c5bb
[ "MIT" ]
null
null
null
lib/ark_client/api/two/transaction.ex
supaiku0/elixir-client
2d5549ce3a876a18750a36a14ff769427688c5bb
[ "MIT" ]
null
null
null
defmodule ArkEcosystem.Client.API.Two.Transaction do @moduledoc """ Documentation for ArkEcosystem.Client.API.One.Transaction. """ import ArkClient @spec list(Tesla.Client.t(), List.t()) :: ArkEcosystem.Client.response() def list(client, parameters \\ []) do client |> get("transactions", parameters) end @spec create(Tesla.Client.t(), List.t()) :: ArkEcosystem.Client.response() def create(client, parameters) do client |> post("transactions", %{transactions: transactions}) end @spec show(Tesla.Client.t(), String.t()) :: ArkEcosystem.Client.response() def show(client, id) do client |> get("transactions/#{id}") end @spec list_unconfirmed(Tesla.Client.t(), List.t()) :: ArkEcosystem.Client.response() def list_unconfirmed(client, parameters \\ []) do client |> get("transactions/unconfirmed", parameters) end @spec get_unconfirmed(Tesla.Client.t(), String.t()) :: ArkEcosystem.Client.response() def get_unconfirmed(client, id) do client |> get("transactions/unconfirmed/#{id}") end @spec search(Tesla.Client.t(), List.t()) :: ArkEcosystem.Client.response() def search(client, parameters) do client |> post("transactions/search", parameters) end @spec types(Tesla.Client.t()) :: ArkEcosystem.Client.response() def types(client) do client |> get("transactions/types") end end
31.697674
87
0.694057
03848c71cb42961f16d2033d334bacfcc3a0d031
2,308
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/public_delegated_prefix_aggregated_list_warning.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/public_delegated_prefix_aggregated_list_warning.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/public_delegated_prefix_aggregated_list_warning.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.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarning do @moduledoc """ [Output Only] Informational warning message. ## Attributes * `code` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. * `data` (*type:* `list(GoogleApi.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarningData.t)`, *default:* `nil`) - [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": "scope", "value": "zones/us-east1-d" } * `message` (*type:* `String.t`, *default:* `nil`) - [Output Only] A human-readable description of the warning code. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => String.t() | nil, :data => list(GoogleApi.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarningData.t()) | nil, :message => String.t() | nil } field(:code) field(:data, as: GoogleApi.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarningData, type: :list ) field(:message) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarning do def decode(value, options) do GoogleApi.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarning.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.PublicDelegatedPrefixAggregatedListWarning do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.466667
262
0.72617
03848d05f1182f17f120a4c294352cb06a54e9e4
4,488
ex
Elixir
clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/dynamic_link_info.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/dynamic_link_info.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/dynamic_link_info.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.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo do @moduledoc """ Information about a Dynamic Link. ## Attributes - analyticsInfo (AnalyticsInfo): Parameters used for tracking. See all tracking parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). Defaults to: `null`. - androidInfo (AndroidInfo): Android related information. See Android related parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). Defaults to: `null`. - desktopInfo (DesktopInfo): Desktop related information. See desktop related parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). Defaults to: `null`. - domainUriPrefix (String.t): E.g. https://maps.app.goo.gl, https://maps.page.link, https://g.co/maps More examples can be found in description of getNormalizedUriPrefix in j/c/g/firebase/dynamiclinks/uri/DdlDomain.java Defaults to: `null`. - dynamicLinkDomain (String.t): Dynamic Links domain that the project owns, e.g. abcd.app.goo.gl [Learn more](https://firebase.google.com/docs/dynamic-links/android/receive) on how to set up Dynamic Link domain associated with your Firebase project. Required. Defaults to: `null`. - iosInfo (IosInfo): iOS related information. See iOS related parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). Defaults to: `null`. - link (String.t): The link your app will open, You can specify any URL your app can handle. This link must be a well-formatted URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. See &#39;link&#39; parameters in the [documentation](https://firebase.google.com/docs/dynamic-links/create-manually). Required. Defaults to: `null`. - navigationInfo (NavigationInfo): Information of navigation behavior of a Firebase Dynamic Links. Defaults to: `null`. - socialMetaTagInfo (SocialMetaTagInfo): Parameters for social meta tag params. Used to set meta tag data for link previews on social sites. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :analyticsInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.AnalyticsInfo.t(), :androidInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.AndroidInfo.t(), :desktopInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.DesktopInfo.t(), :domainUriPrefix => any(), :dynamicLinkDomain => any(), :iosInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.IosInfo.t(), :link => any(), :navigationInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.NavigationInfo.t(), :socialMetaTagInfo => GoogleApi.FirebaseDynamicLinks.V1.Model.SocialMetaTagInfo.t() } field(:analyticsInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.AnalyticsInfo) field(:androidInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.AndroidInfo) field(:desktopInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.DesktopInfo) field(:domainUriPrefix) field(:dynamicLinkDomain) field(:iosInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.IosInfo) field(:link) field(:navigationInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.NavigationInfo) field(:socialMetaTagInfo, as: GoogleApi.FirebaseDynamicLinks.V1.Model.SocialMetaTagInfo) end defimpl Poison.Decoder, for: GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo do def decode(value, options) do GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.FirebaseDynamicLinks.V1.Model.DynamicLinkInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
62.333333
343
0.761809
0384a135ff069fddeb08671397643217c06ababa
1,349
ex
Elixir
lib/person/male_person.ex
vinceurag/kups
456d4e1e030721e70ffe616bc1fbb81c85a98c76
[ "MIT" ]
3
2018-02-19T05:22:59.000Z
2018-02-19T05:37:45.000Z
lib/person/male_person.ex
vinceurag/kups
456d4e1e030721e70ffe616bc1fbb81c85a98c76
[ "MIT" ]
null
null
null
lib/person/male_person.ex
vinceurag/kups
456d4e1e030721e70ffe616bc1fbb81c85a98c76
[ "MIT" ]
null
null
null
defmodule Kups.Person.Male do @moduledoc """ Functions for generating fake data related to a male person. """ alias Kups.Collection @doc """ Generates a full name of a male person. Accepts a boolean parameter. Defaults to `false`. ## Examples iex(1)> Kups.Person.Male.full_name(true) "Juan R. Dela Cruz" iex(2)> Kups.Person.Male.full_name "Juan Dela Cruz" """ @spec full_name() :: String.t def full_name(with_middle_initial \\ false) do case with_middle_initial do true -> middle_initial = String.split("abcdefghijklmnopqrstuvwxyz", "", trim: true) first_name() <> " #{String.capitalize(Enum.random(middle_initial))}. " <> last_name() false -> "#{first_name()} #{last_name()}" end end @doc """ Generates first name of a male person. ## Example iex> Kups.Person.Male.first_name "Juan" """ @spec first_name() :: String.t def first_name do Enum.random(Collection.Person.male_first_name) end @doc """ Generates last name of a male person. ## Example iex> Kups.Person.Male.last_name "Dela Cruz" """ @spec last_name() :: String.t def last_name do Enum.random(Collection.Person.last_name) end end
22.864407
95
0.595256
0384bb06f1b9e062aae25370395ca737b279144b
40,960
ex
Elixir
lib/livebook/session.ex
oo6/livebook
0e059f4f840a56c122266a62cc8fdb3b97920efc
[ "Apache-2.0" ]
null
null
null
lib/livebook/session.ex
oo6/livebook
0e059f4f840a56c122266a62cc8fdb3b97920efc
[ "Apache-2.0" ]
null
null
null
lib/livebook/session.ex
oo6/livebook
0e059f4f840a56c122266a62cc8fdb3b97920efc
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.Session do @moduledoc false # Server corresponding to a single notebook session. # # The process keeps the current notebook state and serves # as a source of truth that multiple clients talk to. # Receives update requests from the clients and notifies # them of any changes applied to the notebook. # # ## Collaborative state # # The core concept is the `Livebook.Session.Data` structure # to which we can apply reproducible operations. # See `Livebook.Session.Data` for more information. # # ## Evaluation # # All regular sections are evaluated in the same process # (the :main_flow evaluation container). On the other hand, # each branching section is evaluated in its own process # and thus runs concurrently. # # ### Implementation considerations # # In practice, every evaluation container is a `Livebook.Evaluator` # process, so we have one such process for the main flow and one # for each branching section. Since a branching section inherits # the evaluation context from the parent section, the last context # needs to be copied from the main flow evaluator to the branching # section evaluator. The latter synchronously asks the former for # that context using `Livebook.Evaluator.fetch_evaluation_context/3`. # Consequently, in order to evaluate the first cell in a branching # section, the main flow needs to be free of work, otherwise we wait. # This assumptions are mirrored in by `Livebook.Session.Data` when # determining cells for evaluation. # # Note: the context could be copied asynchronously if evaluator # kept the contexts in its process dictionary, however the other # evaluator could only read the whole process dictionary, thus # allocating a lot of memory unnecessarily, which would be unacceptable # for large data. By making a synchronous request to the evalutor # for a single specific evaluation context we make sure to copy # as little memory as necessary. # The struct holds the basic session information that we track # and pass around. The notebook and evaluation state is kept # within the process state. defstruct [:id, :pid, :origin, :notebook_name, :file, :images_dir, :created_at, :memory_usage] use GenServer, restart: :temporary alias Livebook.Session.{Data, FileGuard} alias Livebook.{Utils, Notebook, Delta, Runtime, LiveMarkdown, FileSystem} alias Livebook.Users.User alias Livebook.Notebook.{Cell, Section} @timeout :infinity @type t :: %__MODULE__{ id: id(), pid: pid(), origin: Livebook.ContentLoader.location() | nil, notebook_name: String.t(), file: FileSystem.File.t() | nil, images_dir: FileSystem.File.t(), created_at: DateTime.t(), memory_usage: memory_usage() } @type state :: %{ session_id: id(), data: Data.t(), created_at: DateTime.t(), runtime_monitor_ref: reference() | nil, autosave_timer_ref: reference() | nil, save_task_pid: pid() | nil, saved_default_file: FileSystem.File.t() | nil, memory_usage: memory_usage() } @type memory_usage :: %{ runtime: Livebook.Runtime.runtime_memory() | nil, system: Livebook.SystemResources.memory() } @typedoc """ An id assigned to every running session process. """ @type id :: Utils.id() ## API @doc """ Starts a session server process. ## Options * `:id` (**required**) - a unique session identifier * `:notebook` - the initial `Notebook` structure (e.g. imported from a file) * `:origin` - location from where the notebook was obtained, can be either `{:file, file}`, a remote `{:url, url}`, or `nil` * `:file` - the file to which the notebook should be saved * `:copy_images_from` - a directory file to copy notebook images from * `:images` - a map from image name to its binary content, an alternative to `:copy_images_from` when the images are in memory * `:autosave_path` - a local directory to save notebooks without a file into. Defaults to `Livebook.Settings.autosave_path/0` """ @spec start_link(keyword()) :: {:ok, pid} | {:error, any()} def start_link(opts) do GenServer.start_link(__MODULE__, opts) end @doc """ Fetches session information from the session server. """ @spec get_by_pid(pid()) :: Session.t() def get_by_pid(pid) do GenServer.call(pid, :describe_self, @timeout) end @doc """ Registers a session client, so that the session is aware of it. The client process is automatically unregistered when it terminates. Returns the current session data, which the client can than keep in sync with the server by subscribing to the `sessions:id` topic and receiving operations to apply. """ @spec register_client(pid(), pid(), User.t()) :: Data.t() def register_client(pid, client_pid, user) do GenServer.call(pid, {:register_client, client_pid, user}, @timeout) end @doc """ Returns data of the given session. """ @spec get_data(pid()) :: Data.t() def get_data(pid) do GenServer.call(pid, :get_data, @timeout) end @doc """ Returns the current notebook structure. """ @spec get_notebook(pid()) :: Notebook.t() def get_notebook(pid) do GenServer.call(pid, :get_notebook, @timeout) end @doc """ Fetches assets matching the given hash. The assets are cached locally and fetched from the runtime only once. See `local_asset_path/2` for locating a specific asset. """ @spec fetch_assets(pid(), String.t()) :: :ok | {:error, String.t()} def fetch_assets(pid, hash) do local_assets_path = local_assets_path(hash) if File.exists?(local_assets_path) do :ok else with {:ok, runtime, archive_path} <- GenServer.call(pid, {:get_runtime_and_archive_path, hash}, @timeout) do fun = fn -> # Make sure the file hasn't been fetched by this point unless File.exists?(local_assets_path) do {:ok, archive_binary} = Runtime.read_file(runtime, archive_path) extract_archive!(archive_binary, local_assets_path) end end # Fetch assets in a separate process and avoid several # simultaneous fateches of the same assets case Livebook.UniqueTask.run(hash, fun) do :ok -> :ok :error -> {:error, "failed to fetch assets"} end end end end @doc """ Sends notebook attributes update to the server. """ @spec set_notebook_attributes(pid(), map()) :: :ok def set_notebook_attributes(pid, attrs) do GenServer.cast(pid, {:set_notebook_attributes, self(), attrs}) end @doc """ Sends section insertion request to the server. """ @spec insert_section(pid(), non_neg_integer()) :: :ok def insert_section(pid, index) do GenServer.cast(pid, {:insert_section, self(), index}) end @doc """ Sends section insertion request to the server. """ @spec insert_section_into(pid(), Section.id(), non_neg_integer()) :: :ok def insert_section_into(pid, section_id, index) do GenServer.cast(pid, {:insert_section_into, self(), section_id, index}) end @doc """ Sends parent update request to the server. """ @spec set_section_parent(pid(), Section.id(), Section.id()) :: :ok def set_section_parent(pid, section_id, parent_id) do GenServer.cast(pid, {:set_section_parent, self(), section_id, parent_id}) end @doc """ Sends parent update request to the server. """ @spec unset_section_parent(pid(), Section.id()) :: :ok def unset_section_parent(pid, section_id) do GenServer.cast(pid, {:unset_section_parent, self(), section_id}) end @doc """ Sends cell insertion request to the server. """ @spec insert_cell(pid(), Section.id(), non_neg_integer(), Cell.type()) :: :ok def insert_cell(pid, section_id, index, type) do GenServer.cast(pid, {:insert_cell, self(), section_id, index, type}) end @doc """ Sends section deletion request to the server. """ @spec delete_section(pid(), Section.id(), boolean()) :: :ok def delete_section(pid, section_id, delete_cells) do GenServer.cast(pid, {:delete_section, self(), section_id, delete_cells}) end @doc """ Sends cell deletion request to the server. """ @spec delete_cell(pid(), Cell.id()) :: :ok def delete_cell(pid, cell_id) do GenServer.cast(pid, {:delete_cell, self(), cell_id}) end @doc """ Sends cell restoration request to the server. """ @spec restore_cell(pid(), Cell.id()) :: :ok def restore_cell(pid, cell_id) do GenServer.cast(pid, {:restore_cell, self(), cell_id}) end @doc """ Sends cell move request to the server. """ @spec move_cell(pid(), Cell.id(), integer()) :: :ok def move_cell(pid, cell_id, offset) do GenServer.cast(pid, {:move_cell, self(), cell_id, offset}) end @doc """ Sends section move request to the server. """ @spec move_section(pid(), Section.id(), integer()) :: :ok def move_section(pid, section_id, offset) do GenServer.cast(pid, {:move_section, self(), section_id, offset}) end @doc """ Sends cell evaluation request to the server. """ @spec queue_cell_evaluation(pid(), Cell.id()) :: :ok def queue_cell_evaluation(pid, cell_id) do GenServer.cast(pid, {:queue_cell_evaluation, self(), cell_id}) end @doc """ Sends section evaluation request to the server. """ @spec queue_section_evaluation(pid(), Section.id()) :: :ok def queue_section_evaluation(pid, section_id) do GenServer.cast(pid, {:queue_section_evaluation, self(), section_id}) end @doc """ Sends input bound cells evaluation request to the server. """ @spec queue_bound_cells_evaluation(pid(), Data.input_id()) :: :ok def queue_bound_cells_evaluation(pid, input_id) do GenServer.cast(pid, {:queue_bound_cells_evaluation, self(), input_id}) end @doc """ Sends full evaluation request to the server. All outdated (new/stale/changed) cells, as well as cells given as `forced_cell_ids` are scheduled for evaluation. """ @spec queue_full_evaluation(pid(), list(Cell.id())) :: :ok def queue_full_evaluation(pid, forced_cell_ids) do GenServer.cast(pid, {:queue_full_evaluation, self(), forced_cell_ids}) end @doc """ Sends cell evaluation cancellation request to the server. """ @spec cancel_cell_evaluation(pid(), Cell.id()) :: :ok def cancel_cell_evaluation(pid, cell_id) do GenServer.cast(pid, {:cancel_cell_evaluation, self(), cell_id}) end @doc """ Sends erase outputs request to the server. """ @spec erase_outputs(pid()) :: :ok def erase_outputs(pid) do GenServer.cast(pid, {:erase_outputs, self()}) end @doc """ Sends notebook name update request to the server. """ @spec set_notebook_name(pid(), String.t()) :: :ok def set_notebook_name(pid, name) do GenServer.cast(pid, {:set_notebook_name, self(), name}) end @doc """ Sends section name update request to the server. """ @spec set_section_name(pid(), Section.id(), String.t()) :: :ok def set_section_name(pid, section_id, name) do GenServer.cast(pid, {:set_section_name, self(), section_id, name}) end @doc """ Sends a cell delta to apply to the server. """ @spec apply_cell_delta(pid(), Cell.id(), Delta.t(), Data.cell_revision()) :: :ok def apply_cell_delta(pid, cell_id, delta, revision) do GenServer.cast(pid, {:apply_cell_delta, self(), cell_id, delta, revision}) end @doc """ Informs at what revision the given client is. This helps to remove old deltas that are no longer necessary. """ @spec report_cell_revision(pid(), Cell.id(), Data.cell_revision()) :: :ok def report_cell_revision(pid, cell_id, revision) do GenServer.cast(pid, {:report_cell_revision, self(), cell_id, revision}) end @doc """ Sends a cell attributes update to the server. """ @spec set_cell_attributes(pid(), Cell.id(), map()) :: :ok def set_cell_attributes(pid, cell_id, attrs) do GenServer.cast(pid, {:set_cell_attributes, self(), cell_id, attrs}) end @doc """ Sends a input value update to the server. """ @spec set_input_value(pid(), Data.input_id(), term()) :: :ok def set_input_value(pid, input_id, value) do GenServer.cast(pid, {:set_input_value, self(), input_id, value}) end @doc """ Connects to the given runtime. Note that this results in initializing the corresponding remote node with modules and processes required for evaluation. """ @spec connect_runtime(pid(), Runtime.t()) :: :ok def connect_runtime(pid, runtime) do GenServer.cast(pid, {:connect_runtime, self(), runtime}) end @doc """ Sends file location update request to the server. """ @spec set_file(pid(), FileSystem.File.t() | nil) :: :ok def set_file(pid, file) do GenServer.cast(pid, {:set_file, self(), file}) end @doc """ Sends save request to the server. If there's a file set and the notebook changed since the last save, it will be persisted to said file. Note that notebooks are automatically persisted every @autosave_interval milliseconds. """ @spec save(pid()) :: :ok def save(pid) do GenServer.cast(pid, :save) end @doc """ Synchronous version of `save/1`. """ @spec save_sync(pid()) :: :ok def save_sync(pid) do GenServer.call(pid, :save_sync, @timeout) end @doc """ Closes one or more sessions. This results in saving the file and broadcasting a :closed message to the session topic. """ @spec close(pid() | [pid()]) :: :ok def close(pid) do _ = call_many(List.wrap(pid), :close) Livebook.SystemResources.update() :ok end @doc """ Disconnects one or more sessions from the current runtime. Note that this results in clearing the evaluation state. """ @spec disconnect_runtime(pid() | [pid()]) :: :ok def disconnect_runtime(pid) do _ = call_many(List.wrap(pid), {:disconnect_runtime, self()}) Livebook.SystemResources.update() :ok end defp call_many(list, request) do list |> Enum.map(&:gen_server.send_request(&1, request)) |> Enum.map(&:gen_server.wait_response(&1, :infinity)) end ## Callbacks @impl true def init(opts) do with {:ok, state} <- init_state(opts), :ok <- if(copy_images_from = opts[:copy_images_from], do: copy_images(state, copy_images_from), else: :ok ), :ok <- if(images = opts[:images], do: dump_images(state, images), else: :ok ) do state = schedule_autosave(state) {:ok, state} else {:error, error} -> {:stop, error} end end defp init_state(opts) do id = Keyword.fetch!(opts, :id) with {:ok, data} <- init_data(opts) do state = %{ session_id: id, data: data, created_at: DateTime.utc_now(), runtime_monitor_ref: nil, autosave_timer_ref: nil, autosave_path: opts[:autosave_path], save_task_pid: nil, saved_default_file: nil, memory_usage: %{runtime: nil, system: Livebook.SystemResources.memory()} } {:ok, state} end end defp init_data(opts) do notebook = Keyword.get_lazy(opts, :notebook, &default_notebook/0) file = opts[:file] origin = opts[:origin] data = Data.new(notebook) data = %{data | origin: origin} if file do case FileGuard.lock(file, self()) do :ok -> {:ok, %{data | file: file}} {:error, :already_in_use} -> {:error, "the given file is already in use"} end else {:ok, data} end end defp default_notebook() do %{Notebook.new() | sections: [%{Section.new() | cells: [Cell.new(:elixir)]}]} end defp schedule_autosave(state) do if interval_s = state.data.notebook.autosave_interval_s do ref = Process.send_after(self(), :autosave, interval_s * 1000) %{state | autosave_timer_ref: ref} else %{state | autosave_timer_ref: nil} end end defp unschedule_autosave(%{autosave_timer_ref: nil} = state), do: state defp unschedule_autosave(state) do if Process.cancel_timer(state.autosave_timer_ref) == false do receive do :autosave -> :ok end end %{state | autosave_timer_ref: nil} end @impl true def handle_call(:describe_self, _from, state) do {:reply, self_from_state(state), state} end def handle_call({:register_client, client_pid, user}, _from, state) do Process.monitor(client_pid) state = handle_operation(state, {:client_join, client_pid, user}) {:reply, state.data, state} end def handle_call(:get_data, _from, state) do {:reply, state.data, state} end def handle_call({:get_runtime_and_archive_path, hash}, _from, state) do assets_info = Notebook.find_asset_info(state.data.notebook, hash) runtime = state.data.runtime reply = cond do assets_info == nil -> {:error, "unknown hash"} runtime == nil -> {:error, "no runtime"} true -> {:ok, runtime, assets_info.archive_path} end {:reply, reply, state} end def handle_call(:get_notebook, _from, state) do {:reply, state.data.notebook, state} end def handle_call(:save_sync, _from, state) do {:reply, :ok, maybe_save_notebook_sync(state)} end def handle_call(:close, _from, state) do maybe_save_notebook_sync(state) broadcast_message(state.session_id, :session_closed) {:stop, :shutdown, :ok, state} end def handle_call({:disconnect_runtime, client_pid}, _from, state) do if old_runtime = state.data.runtime do Runtime.disconnect(old_runtime) end {:reply, :ok, %{state | runtime_monitor_ref: nil} |> handle_operation({:set_runtime, client_pid, nil})} end @impl true def handle_cast({:set_notebook_attributes, client_pid, attrs}, state) do operation = {:set_notebook_attributes, client_pid, attrs} {:noreply, handle_operation(state, operation)} end def handle_cast({:insert_section, client_pid, index}, state) do # Include new id in the operation, so it's reproducible operation = {:insert_section, client_pid, index, Utils.random_id()} {:noreply, handle_operation(state, operation)} end def handle_cast({:insert_section_into, client_pid, section_id, index}, state) do # Include new id in the operation, so it's reproducible operation = {:insert_section_into, client_pid, section_id, index, Utils.random_id()} {:noreply, handle_operation(state, operation)} end def handle_cast({:set_section_parent, client_pid, section_id, parent_id}, state) do # Include new id in the operation, so it's reproducible operation = {:set_section_parent, client_pid, section_id, parent_id} {:noreply, handle_operation(state, operation)} end def handle_cast({:unset_section_parent, client_pid, section_id}, state) do # Include new id in the operation, so it's reproducible operation = {:unset_section_parent, client_pid, section_id} {:noreply, handle_operation(state, operation)} end def handle_cast({:insert_cell, client_pid, section_id, index, type}, state) do # Include new id in the operation, so it's reproducible operation = {:insert_cell, client_pid, section_id, index, type, Utils.random_id()} {:noreply, handle_operation(state, operation)} end def handle_cast({:delete_section, client_pid, section_id, delete_cells}, state) do operation = {:delete_section, client_pid, section_id, delete_cells} {:noreply, handle_operation(state, operation)} end def handle_cast({:delete_cell, client_pid, cell_id}, state) do operation = {:delete_cell, client_pid, cell_id} {:noreply, handle_operation(state, operation)} end def handle_cast({:restore_cell, client_pid, cell_id}, state) do operation = {:restore_cell, client_pid, cell_id} {:noreply, handle_operation(state, operation)} end def handle_cast({:move_cell, client_pid, cell_id, offset}, state) do operation = {:move_cell, client_pid, cell_id, offset} {:noreply, handle_operation(state, operation)} end def handle_cast({:move_section, client_pid, section_id, offset}, state) do operation = {:move_section, client_pid, section_id, offset} {:noreply, handle_operation(state, operation)} end def handle_cast({:queue_cell_evaluation, client_pid, cell_id}, state) do operation = {:queue_cells_evaluation, client_pid, [cell_id]} {:noreply, handle_operation(state, operation)} end def handle_cast({:queue_section_evaluation, client_pid, section_id}, state) do case Notebook.fetch_section(state.data.notebook, section_id) do {:ok, section} -> cell_ids = for cell <- section.cells, is_struct(cell, Cell.Elixir), do: cell.id operation = {:queue_cells_evaluation, client_pid, cell_ids} {:noreply, handle_operation(state, operation)} :error -> {:noreply, state} end end def handle_cast({:queue_bound_cells_evaluation, client_pid, input_id}, state) do cell_ids = for {bound_cell, _} <- Data.bound_cells_with_section(state.data, input_id), do: bound_cell.id operation = {:queue_cells_evaluation, client_pid, cell_ids} {:noreply, handle_operation(state, operation)} end def handle_cast({:queue_full_evaluation, client_pid, forced_cell_ids}, state) do cell_ids = Data.cell_ids_for_full_evaluation(state.data, forced_cell_ids) operation = {:queue_cells_evaluation, client_pid, cell_ids} {:noreply, handle_operation(state, operation)} end def handle_cast({:cancel_cell_evaluation, client_pid, cell_id}, state) do operation = {:cancel_cell_evaluation, client_pid, cell_id} {:noreply, handle_operation(state, operation)} end def handle_cast({:erase_outputs, client_pid}, state) do operation = {:erase_outputs, client_pid} {:noreply, handle_operation(state, operation)} end def handle_cast({:set_notebook_name, client_pid, name}, state) do operation = {:set_notebook_name, client_pid, name} {:noreply, handle_operation(state, operation)} end def handle_cast({:set_section_name, client_pid, section_id, name}, state) do operation = {:set_section_name, client_pid, section_id, name} {:noreply, handle_operation(state, operation)} end def handle_cast({:apply_cell_delta, client_pid, cell_id, delta, revision}, state) do operation = {:apply_cell_delta, client_pid, cell_id, delta, revision} {:noreply, handle_operation(state, operation)} end def handle_cast({:report_cell_revision, client_pid, cell_id, revision}, state) do operation = {:report_cell_revision, client_pid, cell_id, revision} {:noreply, handle_operation(state, operation)} end def handle_cast({:set_cell_attributes, client_pid, cell_id, attrs}, state) do operation = {:set_cell_attributes, client_pid, cell_id, attrs} {:noreply, handle_operation(state, operation)} end def handle_cast({:set_input_value, client_pid, input_id, value}, state) do operation = {:set_input_value, client_pid, input_id, value} {:noreply, handle_operation(state, operation)} end def handle_cast({:connect_runtime, client_pid, runtime}, state) do if old_runtime = state.data.runtime do Runtime.disconnect(old_runtime) end runtime_monitor_ref = Runtime.connect(runtime) {:noreply, %{state | runtime_monitor_ref: runtime_monitor_ref} |> handle_operation({:set_runtime, client_pid, runtime})} end def handle_cast({:set_file, client_pid, file}, state) do if file do FileGuard.lock(file, self()) else :ok end |> case do :ok -> if state.data.file do FileGuard.unlock(state.data.file) end {:noreply, handle_operation(state, {:set_file, client_pid, file})} {:error, :already_in_use} -> broadcast_error(state.session_id, "failed to set new file because it is already in use") {:noreply, state} end end def handle_cast(:save, state) do {:noreply, maybe_save_notebook_async(state)} end @impl true def handle_info({:DOWN, ref, :process, _, _}, %{runtime_monitor_ref: ref} = state) do broadcast_info(state.session_id, "runtime node terminated unexpectedly") {:noreply, %{state | runtime_monitor_ref: nil} |> handle_operation({:set_runtime, self(), nil})} end def handle_info({:DOWN, _, :process, pid, _}, state) do state = if Map.has_key?(state.data.clients_map, pid) do handle_operation(state, {:client_leave, pid}) else state end {:noreply, state} end def handle_info({:evaluation_output, cell_id, output}, state) do operation = {:add_cell_evaluation_output, self(), cell_id, output} {:noreply, handle_operation(state, operation)} end def handle_info({:evaluation_response, cell_id, response, metadata}, state) do {memory_usage, metadata} = Map.pop(metadata, :memory_usage) operation = {:add_cell_evaluation_response, self(), cell_id, response, metadata} {:noreply, state |> put_memory_usage(memory_usage) |> handle_operation(operation) |> notify_update()} end def handle_info({:evaluation_input, cell_id, reply_to, input_id}, state) do {reply, state} = with {:ok, cell, _section} <- Notebook.fetch_cell_and_section(state.data.notebook, cell_id), {:ok, value} <- Map.fetch(state.data.input_values, input_id) do state = handle_operation(state, {:bind_input, self(), cell.id, input_id}) {{:ok, value}, state} else _ -> {:error, state} end send(reply_to, {:evaluation_input_reply, reply}) {:noreply, state} end def handle_info({:runtime_broadcast, topic, subtopic, message}, state) do full_topic = runtime_messages_topic(state.session_id, topic, subtopic) Phoenix.PubSub.broadcast(Livebook.PubSub, full_topic, message) {:noreply, state} end def handle_info({:container_down, container_ref, message}, state) do broadcast_error(state.session_id, "evaluation process terminated - #{message}") operation = case container_ref do :main_flow -> {:reflect_main_evaluation_failure, self()} section_id -> {:reflect_evaluation_failure, self(), section_id} end {:noreply, handle_operation(state, operation)} end def handle_info(:autosave, state) do {:noreply, state |> maybe_save_notebook_async() |> schedule_autosave()} end def handle_info({:user_change, user}, state) do operation = {:update_user, self(), user} {:noreply, handle_operation(state, operation)} end def handle_info({:save_finished, pid, result, file, default?}, %{save_task_pid: pid} = state) do state = %{state | save_task_pid: nil} {:noreply, handle_save_finished(state, result, file, default?)} end def handle_info({:memory_usage, runtime_memory}, state) do {:noreply, state |> put_memory_usage(runtime_memory) |> notify_update()} end def handle_info(_message, state), do: {:noreply, state} @impl true def terminate(_reason, state) do cleanup_tmp_dir(state.session_id) :ok end # --- defp self_from_state(state) do %__MODULE__{ id: state.session_id, pid: self(), origin: state.data.origin, notebook_name: state.data.notebook.name, file: state.data.file, images_dir: images_dir_from_state(state), created_at: state.created_at, memory_usage: state.memory_usage } end defp images_dir_from_state(%{data: %{file: nil}, session_id: id}) do tmp_dir = session_tmp_dir(id) FileSystem.File.resolve(tmp_dir, "images/") end defp images_dir_from_state(%{data: %{file: file}}) do images_dir_for_notebook(file) end @doc """ Returns images directory corresponding to the given notebook file. """ @spec images_dir_for_notebook(FileSystem.File.t()) :: FileSystem.File.t() def images_dir_for_notebook(file) do file |> FileSystem.File.containing_dir() |> FileSystem.File.resolve("images/") end defp session_tmp_dir(session_id) do livebook_tmp_path() |> Path.join("sessions/#{session_id}") |> FileSystem.Utils.ensure_dir_path() |> FileSystem.File.local() end defp cleanup_tmp_dir(session_id) do tmp_dir = session_tmp_dir(session_id) FileSystem.File.remove(tmp_dir) end defp local_assets_path(hash) do Path.join([livebook_tmp_path(), "assets", encode_path_component(hash)]) end @doc """ Returns a local path to asset matching the given hash and path. The file is not guaranteed to exist. See `fetch_assets/2` for fetching assets through a particular session. The path is expected to be a simple relative path within the assets directory, otherwise an error is returned. """ @spec local_asset_path(String.t(), String.t()) :: {:ok, String.t()} | :error def local_asset_path(hash, asset_path) do assets_path = local_assets_path(hash) local_asset_path = Path.expand(asset_path, assets_path) if String.starts_with?(local_asset_path, assets_path <> "/") do {:ok, local_asset_path} else :error end end defp encode_path_component(component) do String.replace(component, [".", "/", "\\", ":"], "_") end defp livebook_tmp_path() do tmp_dir = System.tmp_dir!() |> Path.expand() Path.join(tmp_dir, "livebook") end defp copy_images(state, source) do images_dir = images_dir_from_state(state) with {:ok, source_exists?} <- FileSystem.File.exists?(source) do if source_exists? do FileSystem.File.copy(source, images_dir) else :ok end end end defp move_images(state, source) do images_dir = images_dir_from_state(state) with {:ok, source_exists?} <- FileSystem.File.exists?(source) do if source_exists? do with {:ok, destination_exists?} <- FileSystem.File.exists?(images_dir) do if not destination_exists? do # If the directory doesn't exist, we can just change # the directory name, which is more efficient if # available in the given file system FileSystem.File.rename(source, images_dir) else # If the directory exists, we use copy to place # the images there with :ok <- FileSystem.File.copy(source, images_dir) do FileSystem.File.remove(source) end end end else :ok end end end defp dump_images(state, images) do images_dir = images_dir_from_state(state) Enum.reduce(images, :ok, fn {filename, content}, result -> with :ok <- result do file = FileSystem.File.resolve(images_dir, filename) FileSystem.File.write(file, content) end end) end # Given any operation on `Livebook.Session.Data`, the process # does the following: # # * broadcasts the operation to all clients immediately, # so that they can update their local `Livebook.Session.Data` # # * applies the operation to own local `Livebook.Session.Data` # # * if necessary, performs the relevant actions (e.g. starts cell evaluation), # to reflect the new `Livebook.Session.Data` # defp handle_operation(state, operation) do broadcast_operation(state.session_id, operation) case Data.apply_operation(state.data, operation) do {:ok, new_data, actions} -> %{state | data: new_data} |> after_operation(state, operation) |> handle_actions(actions) :error -> state end end defp after_operation(state, _prev_state, {:set_notebook_name, _pid, _name}) do notify_update(state) end defp after_operation(state, _prev_state, {:set_runtime, _pid, runtime}) do if runtime do state else state |> put_memory_usage(nil) |> notify_update() end end defp after_operation(state, prev_state, {:set_file, _pid, _file}) do prev_images_dir = images_dir_from_state(prev_state) if prev_state.data.file do copy_images(state, prev_images_dir) else move_images(state, prev_images_dir) end |> case do :ok -> :ok {:error, message} -> broadcast_error(state.session_id, "failed to copy images - #{message}") end notify_update(state) end defp after_operation( state, _prev_state, {:set_notebook_attributes, _client_pid, %{autosave_interval_s: _}} ) do state |> unschedule_autosave() |> schedule_autosave() end defp after_operation(state, prev_state, {:client_join, _client_pid, user}) do unless Map.has_key?(prev_state.data.users_map, user.id) do Phoenix.PubSub.subscribe(Livebook.PubSub, "users:#{user.id}") end state end defp after_operation(state, prev_state, {:client_leave, client_pid}) do user_id = prev_state.data.clients_map[client_pid] unless Map.has_key?(state.data.users_map, user_id) do Phoenix.PubSub.unsubscribe(Livebook.PubSub, "users:#{user_id}") end state end defp after_operation(state, _prev_state, {:delete_cell, _client_pid, cell_id}) do entry = Enum.find(state.data.bin_entries, fn entry -> entry.cell.id == cell_id end) # The session LV drops cell's source, so we send them # the complete bin entry to override broadcast_message(state.session_id, {:hydrate_bin_entries, [entry]}) state end defp after_operation(state, prev_state, {:delete_section, _client_pid, section_id, true}) do {:ok, section} = Notebook.fetch_section(prev_state.data.notebook, section_id) cell_ids = Enum.map(section.cells, & &1.id) entries = Enum.filter(state.data.bin_entries, fn entry -> entry.cell.id in cell_ids end) broadcast_message(state.session_id, {:hydrate_bin_entries, entries}) state end defp after_operation(state, _prev_state, _operation), do: state defp handle_actions(state, actions) do Enum.reduce(actions, state, &handle_action(&2, &1)) end defp handle_action(state, :start_runtime) do {runtime_module, args} = Livebook.Config.default_runtime() case apply(runtime_module, :init, args) do {:ok, runtime} -> runtime_monitor_ref = Runtime.connect(runtime) %{state | runtime_monitor_ref: runtime_monitor_ref} |> handle_operation({:set_runtime, self(), runtime}) {:error, error} -> broadcast_error(state.session_id, "failed to setup runtime - #{error}") handle_operation(state, {:set_runtime, self(), nil}) end end defp handle_action(state, {:start_evaluation, cell, section}) do path = case state.data.file do nil -> "" file -> file.path end file = path <> "#cell" opts = [file: file] locator = {container_ref_for_section(section), cell.id} prev_locator = find_prev_locator(state.data.notebook, cell, section) Runtime.evaluate_code(state.data.runtime, cell.source, locator, prev_locator, opts) evaluation_digest = :erlang.md5(cell.source) handle_operation(state, {:evaluation_started, self(), cell.id, evaluation_digest}) end defp handle_action(state, {:stop_evaluation, section}) do if state.data.runtime do Runtime.drop_container(state.data.runtime, container_ref_for_section(section)) end state end defp handle_action(state, {:forget_evaluation, cell, section}) do if state.data.runtime do Runtime.forget_evaluation(state.data.runtime, {container_ref_for_section(section), cell.id}) end state end defp handle_action(state, _action), do: state defp broadcast_operation(session_id, operation) do broadcast_message(session_id, {:operation, operation}) end defp broadcast_error(session_id, error) do broadcast_message(session_id, {:error, error}) end defp broadcast_info(session_id, info) do broadcast_message(session_id, {:info, info}) end defp broadcast_message(session_id, message) do Phoenix.PubSub.broadcast(Livebook.PubSub, "sessions:#{session_id}", message) end defp put_memory_usage(state, runtime) do put_in(state.memory_usage, %{runtime: runtime, system: Livebook.SystemResources.memory()}) end defp notify_update(state) do session = self_from_state(state) Livebook.Sessions.update_session(session) broadcast_message(state.session_id, {:session_updated, session}) state end defp maybe_save_notebook_async(state) do {file, default?} = notebook_autosave_file(state) if file && should_save_notebook?(state) do pid = self() notebook = state.data.notebook {:ok, pid} = Task.start(fn -> content = LiveMarkdown.Export.notebook_to_markdown(notebook) result = FileSystem.File.write(file, content) send(pid, {:save_finished, self(), result, file, default?}) end) %{state | save_task_pid: pid} else state end end defp maybe_save_notebook_sync(state) do {file, default?} = notebook_autosave_file(state) if file && should_save_notebook?(state) do content = LiveMarkdown.Export.notebook_to_markdown(state.data.notebook) result = FileSystem.File.write(file, content) handle_save_finished(state, result, file, default?) else state end end defp should_save_notebook?(state) do state.data.dirty and state.save_task_pid == nil end defp notebook_autosave_file(state) do file = state.data.file || default_notebook_file(state) default? = state.data.file == nil {file, default?} end defp default_notebook_file(state) do if path = state.autosave_path || Livebook.Settings.autosave_path() do dir = path |> FileSystem.Utils.ensure_dir_path() |> FileSystem.File.local() notebook_rel_path = default_notebook_path(state) FileSystem.File.resolve(dir, notebook_rel_path) end end defp default_notebook_path(state) do title_str = state.data.notebook.name |> String.downcase() |> String.replace(~r/\s+/, "_") |> String.replace(~r/[^\w]/, "") # We want a random, but deterministic part, so we # use a few trailing characters from the session id, # which are random already random_str = String.slice(state.session_id, -4..-1) [date_str, time_str, _] = state.created_at |> DateTime.to_iso8601() |> String.replace(["-", ":"], "_") |> String.split(["T", "."]) "#{date_str}/#{time_str}_#{title_str}_#{random_str}.livemd" end defp handle_save_finished(state, result, file, default?) do state = if default? do if state.saved_default_file && state.saved_default_file != file do FileSystem.File.remove(state.saved_default_file) end %{state | saved_default_file: file} else state end case result do :ok -> handle_operation(state, {:mark_as_not_dirty, self()}) {:error, message} -> broadcast_error(state.session_id, "failed to save notebook - #{message}") state end end defp extract_archive!(binary, path) do :ok = :erl_tar.extract({:binary, binary}, [:compressed, {:cwd, String.to_charlist(path)}]) end @doc """ Subscribes the caller to runtime messages under the given topic. """ @spec subscribe_to_runtime_events(id(), String.t(), String.t()) :: :ok | {:error, term()} def subscribe_to_runtime_events(session_id, topic, subtopic) do Phoenix.PubSub.subscribe(Livebook.PubSub, runtime_messages_topic(session_id, topic, subtopic)) end @doc """ Unsubscribes the caller from runtime messages subscribed earlier with `subscribe_to_runtime_events/3`. """ @spec unsubscribe_from_runtime_events(id(), String.t(), String.t()) :: :ok | {:error, term()} def unsubscribe_from_runtime_events(session_id, topic, subtopic) do Phoenix.PubSub.unsubscribe( Livebook.PubSub, runtime_messages_topic(session_id, topic, subtopic) ) end defp runtime_messages_topic(session_id, topic, subtopic) do "sessions:#{session_id}:runtime_messages:#{topic}:#{subtopic}" end @doc """ Determines locator of the evaluation that the given cell depends on. """ @spec find_prev_locator(Notebook.t(), Cell.t(), Section.t()) :: Runtime.locator() def find_prev_locator(notebook, cell, section) do default = {container_ref_for_section(section), nil} notebook |> Notebook.parent_cells_with_section(cell.id) |> Enum.find_value(default, fn {cell, section} -> is_struct(cell, Cell.Elixir) && {container_ref_for_section(section), cell.id} end) end defp container_ref_for_section(%{parent_id: nil}), do: :main_flow defp container_ref_for_section(section), do: section.id end
30.843373
98
0.677686
03851813b51ce79bf7044f1b45f621805af89d89
37,043
ex
Elixir
lib/elixir/lib/supervisor.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/supervisor.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/supervisor.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
defmodule Supervisor do @moduledoc ~S""" A behaviour module for implementing supervisors. A supervisor is a process which supervises other processes, which we refer to as *child processes*. Supervisors are used to build a hierarchical process structure called a *supervision tree*. Supervision trees provide fault-tolerance and encapsulate how our applications start and shutdown. A supervisor may be started directly with a list of children via `start_link/2` or you may define a module-based supervisor that implements the required callbacks. The sections below use `start_link/2` to start supervisors in most examples, but it also includes a specific section on module-based ones. ## Examples In order to start a supervisor, we need to first define a child process that will be supervised. As an example, we will define a GenServer that represents a stack: defmodule Stack do use GenServer def start_link(state) do GenServer.start_link(__MODULE__, state, name: __MODULE__) end ## Callbacks def init(stack) do {:ok, stack} end def handle_call(:pop, _from, [h | t]) do {:reply, h, t} end def handle_cast({:push, h}, t) do {:noreply, [h | t]} end end The stack is a small wrapper around lists. It allows us to put an element on the top of the stack, by prepending to the list, and to get the top of the stack by pattern matching. We can now start a supervisor that will start and supervise our stack process. The first step is to define a list of **child specifications** that control how each child behaves. Each child specification is a map, as shown below: children = [ # The Stack is a child started via Stack.start_link([:hello]) %{ id: Stack, start: {Stack, :start_link, [[:hello]]} } ] # Now we start the supervisor with the children and a strategy {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one) # After started, we can query the supervisor for information Supervisor.count_children(pid) #=> %{active: 1, specs: 1, supervisors: 0, workers: 1} Notice that when starting the GenServer, we are registering it with name `Stack`, which allows us to call it directly and get what is on the stack: GenServer.call(Stack, :pop) #=> :hello GenServer.cast(Stack, {:push, :world}) #=> :ok GenServer.call(Stack, :pop) #=> :world However, there is a bug in our stack server. If we call `:pop` and the stack is empty, it is going to crash because no clause matches: GenServer.call(Stack, :pop) ** (exit) exited in: GenServer.call(Stack, :pop, 5000) Luckily, since the server is being supervised by a supervisor, the supervisor will automatically start a new one, with the initial stack of `[:hello]`: GenServer.call(Stack, :pop) #=> :hello Supervisors support different strategies; in the example above, we have chosen `:one_for_one`. Furthermore, each supervisor can have many workers and supervisors as children, each of them with their specific configuration, shutdown values, and restart strategies. The rest of this document will cover how child processes are started, how they can be specified, different supervision strategies and more. ## Start and shutdown When the supervisor starts, it traverses all child specifications and then starts each child in the order they are defined. This is done by calling the function defined under the `:start` key in the child specification and typically defaults to `start_link/1`. The `start_link/1` (or a custom) is then called for each child process. The `start_link/1` function must return `{:ok, pid}` where `pid` is the process identifier of a new process that is linked to the supervisor. The child process usually starts its work by executing the `init/1` callback. Generally speaking, the `init` callback is where we initialize and configure the child process. The shutdown process happens in reverse order. When a supervisor shuts down, it terminates all children in the opposite order they are listed. The termination happens by sending a shutdown exit signal, via `Process.exit(child_pid, :shutdown)`, to the child process and then awaiting for a time interval for the child process to terminate. This interval defaults to 5000 milliseconds. If the child process does not terminate in this interval, the supervisor abruptly terminates the child with reason `:brutal_kill`. The shutdown time can be configured in the child specification which is fully detailed in the next section. If the child process is not trapping exits, it will shutdown immediately when it receives the first exit signal. If the child process is trapping exits, then the `terminate` callback is invoked, and the child process must terminate in a reasonable time interval before being abruptly terminated by the supervisor. In other words, if it is important that a process cleans after itself when your application or the supervision tree is shutting down, then this process must trap exits and its child specification should specify the proper `:shutdown` value, ensuring it terminates within a reasonable interval. Now that we understand the start and shutdown process, let's take a complete look at all of the options provided in the child specification. ## Child specification The child specification describes how the supervisor start, shutdown and restart child processes. The child specification contains 5 keys. The first two are required and the remaining ones are optional: * `:id` - a value used to identify the child specification internally by the supervisor; defaults to the given module. In case of conflicting `:id`, the supervisor will refuse to initialize and require explicit IDs. This key is required. * `:start` - a tuple with the module-function-args to be invoked to start the child process. This key is required. * `:restart` - an atom that defines when a terminated child process should be restarted (see the "Restart values" section below). This key is optional and defaults to `:permanent`. * `:shutdown` - an atom that defines how a child process should be terminated (see the "Shutdown values" section below). This key is optional and defaults to `5000` if the type is `:worker` or `:infinity` if the type is `:supervisor`. * `:type` - if the child process is a `:worker` or a `:supervisor`. This key is optional and defaults to `:worker`. There is a sixth key, called `:modules`, which is rarely changed and it is set automatically based on the value in `:start`. Let's understand what the `:shutdown` and `:restart` options control. ### Shutdown values (:shutdown) The following shutdown values are supported in the `:shutdown` option: * `:brutal_kill` - the child process is unconditionally and immediately terminated using `Process.exit(child, :kill)`. * any integer >= 0 - the amount of time in milliseconds that the supervisor will wait for children to terminate after emitting a `Process.exit(child, :shutdown)` signal. If the child process is not trapping exits, the initial `:shutdown` signal will terminate the child process immediately. If the child process is trapping exits, it has the given amount of time in milliseconds to terminate. If it doesn't terminate within the specified time, the child process is unconditionally terminated by the supervisor via `Process.exit(child, :kill)`. * `:infinity` - works as an integer except the supervisor will wait indefinitely for the child to terminate. If the child process is a supervisor, the recommended value is `:infinity` to give the supervisor and its children enough time to shutdown. This option can be used with regular workers but doing so is discouraged and requires extreme care. If not used carefully and the child process does not terminate, it means your application will never terminate as well. ### Restart values (:restart) The `:restart` option controls what the supervisor should consider to be a successful termination or not. If the termination is successful, the supervisor won't restart the child. If the child process crashed, the supervisor will start a new one. The following restart values are supported in the `:restart` option: * `:permanent` - the child process is always restarted. * `:temporary` - the child process is never restarted, regardless of the supervision strategy. * `:transient` - the child process is restarted only if it terminates abnormally, i.e., with an exit reason other than `:normal`, `:shutdown` or `{:shutdown, term}`. For a more complete understanding of the exit reasons and their impact, see the "Exit reasons and restarts" section. ## child_spec/1 When starting a supervisor, we pass a list of child specifications. Those specifications are maps that tell how the supervisor should start, stop and restart each of its children: %{ id: Stack, start: {Stack, :start_link, [[:hello]]} } The map above defines a supervisor with `:id` of `Stack` that is started by calling `Stack.start_link([:hello])`. However, specifying the child specification for each child as a map can be quite error prone, as we may change the Stack implementation and forget to update its specification. That's why Elixir allows you to pass a tuple with the module name and the `start_link` argument instead of the specification: children = [ {Stack, [:hello]} ] The supervisor will then invoke `Stack.child_spec([:hello])` to retrieve a child specification. Now the `Stack` module is responsible for building its own specification. By default, `use GenServer` defines a `Stack.child_spec/1` function which returns the same child specification we had before: %{ id: Stack, start: {Stack, :start_link, [[:hello]]} } It is also possible to simply pass the `Stack` module as a child: children = [ Stack ] When only the module name is given, it is equivalent to `{Stack, []}`. In this case, we will end-up with a child specification that looks like this: %{ id: Stack, start: {Stack, :start_link, [[]]} } By replacing the map specification by `{Stack, [:hello]}` or `Stack`, we keep the child specification encapsulated in the Stack module, using the default implementation defined by `use GenServer`. We can now share our `Stack` worker with other developers and they can add it directly to their supervision tree without worrying about the low-level details of the worker. If you need to access or modify how a worker or a supervisor runs, you can use the `Supervisor.child_spec/2` function. For example, to run the stack with a different `:id` and a `:shutdown` value of 10 seconds (10_000 milliseconds): children = [ Supervisor.child_spec({Stack, [:hello]}, id: MyStack, shutdown: 10_000) ] The call to `Supervisor.child_spec/2` above will return the following specification: %{ id: MyStack, start: {Stack, :start_link, [[:hello]]}, shutdown: 10_000 } You may also configure the child specification in the Stack module itself to use a different `:id` or `:shutdown` value by passing options to `use GenServer`: defmodule Stack do use GenServer, id: MyStack, shutdown: 10_000 The options above will customize the `Stack.child_spec/1` function defined by `use GenServer`. It accepts the same options as the `Supervisor.child_spec/2` function. You may also completely override the `child_spec/1` function in the Stack module and return your own child specification. Note there is no guarantee the `child_spec/1` function will be called by the Supervisor process, as other processes may invoke it to retrieve the child specification before reaching the supervisor. ## Exit reasons and restarts A supervisor restarts a child process depending on its `:restart` configuration. For example, when `:restart` is set to `:transient`, the supervisor does not restart the child in case it exits with reason `:normal`, `:shutdown` or `{:shutdown, term}`. So one may ask: which exit reason should I choose when exiting? There are three options: * `:normal` - in such cases, the exit won't be logged, there is no restart in transient mode, and linked processes do not exit * `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be logged, there is no restart in transient mode, and linked processes exit with the same reason unless they're trapping exits * any other term - in such cases, the exit will be logged, there are restarts in transient mode, and linked processes exit with the same reason unless they're trapping exits Notice that supervisor that reached maximum restart intensity will exit with `:shutdown` reason. In this case the supervisor will only be restarted if its child specification was defined with the `:restart` option set to `:permanent` (the default). ## Module-based supervisors In the example above, a supervisor was started by passing the supervision structure to `start_link/2`. However, supervisors can also be created by explicitly defining a supervision module: defmodule MyApp.Supervisor do # Automatically defines child_spec/1 use Supervisor def start_link(arg) do Supervisor.start_link(__MODULE__, arg, name: __MODULE__) end def init(_arg) do children = [ {Stack, [:hello]} ] Supervisor.init(children, strategy: :one_for_one) end end The difference between the two approaches is that a module-based supervisor gives you more direct control over how the supervisor is initialized. Instead of calling `Supervisor.start_link/2` with a list of children that are automatically initialized, we have defined a supervisor alongside its `c:init/1` callback and manually initialized the children by calling `Supervisor.init/2`, passing the same arguments we would have given to `start_link/2`. You may want to use a module-based supervisor if: * You need to perform some particular action on supervisor initialization, like setting up an ETS table. * You want to perform partial hot-code swapping of the tree. The module-based approach allow you to add and remove children on a case-by-case basis. Note `use Supervisor` defines a `child_spec/1` function, allowing the defined module itself to be put under a supervision tree. The generated `child_spec/1` can be customized with the following options: * `:id` - the child specification id, defaults to the current module * `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`) * `:restart` - when the supervisor should be restarted, defaults to `:permanent` ## `start_link/2`, `init/2`, and strategies So far we have started the supervisor passing a single child as a tuple as well as a strategy called `:one_for_one`: Supervisor.start_link([ {Stack, [:hello]} ], strategy: :one_for_one) or from inside the `c:init/1` callback: Supervisor.init([ {Stack, [:hello]} ], strategy: :one_for_one) Although we have mentioned that the supervisor automatically expands `{Stack, [:hello]}` to a child specification by calling `Stack.child_spec([:hello])`, we haven't formally defined all of the arguments accepted by `start_link/2` and `init/2`. Let's rectify that now. The first argument given to `start_link/2` is a list of children which may be either: * a map representing the child specification itself - as outlined in the "Child specification" section * a tuple with a module as first element and the start argument as second - such as `{Stack, [:hello]}`. In this case, `Stack.child_spec([:hello])` is called to retrieve the child specification * a module - such as `Stack`. In this case, `Stack.child_spec([])` is called to retrieve the child specification The second argument is a keyword list of options: * `:strategy` - the restart strategy option. It can be either `:one_for_one`, `:rest_for_one` or `:one_for_all`. See the "Strategies" section. * `:max_restarts` - the maximum number of restarts allowed in a time frame. Defaults to `3`. * `:max_seconds` - the time frame in which `:max_restarts` applies. Defaults to `5`. The `:strategy` option is required and by default a maximum of 3 restarts is allowed within 5 seconds. ### Strategies Supervisors support different supervision strategies (through the `:strategy` option, as seen above): * `:one_for_one` - if a child process terminates, only that process is restarted. * `:one_for_all` - if a child process terminates, all other child processes are terminated and then all child processes (including the terminated one) are restarted. * `:rest_for_one` - if a child process terminates, the "rest" of the child processes, i.e., the child processes after the terminated one in start order, are terminated. Then the terminated child process and the rest of the child processes are restarted. There is also a deprecated strategy called `:simple_one_for_one` which has been replaced by the `DynamicSupervisor`. The `:simple_one_for_one` supervisor was similar to `:one_for_one` but suits better when dynamically attaching children. Many functions in this module behaved slightly differently when this strategy is used. See the `DynamicSupervisor` module for more information and migration strategies. ## Name registration A supervisor is bound to the same name registration rules as a `GenServer`. Read more about these rules in the documentation for `GenServer`. """ @doc false defmacro __using__(opts) do quote location: :keep, bind_quoted: [opts: opts] do import Supervisor.Spec @behaviour Supervisor @doc """ Returns a specification to start this module under a supervisor. See `Supervisor`. """ def child_spec(arg) do default = %{ id: __MODULE__, start: {__MODULE__, :start_link, [arg]}, type: :supervisor } Supervisor.child_spec(default, unquote(Macro.escape(opts))) end defoverridable child_spec: 1 @doc false def init(arg) end end @doc """ Callback invoked to start the supervisor and during hot code upgrades. Developers typically invoke `Supervisor.init/2` at the end of their init callback to return the proper supervision flags. """ @callback init(args :: term) :: {:ok, {:supervisor.sup_flags(), [:supervisor.child_spec()]}} | :ignore @typedoc "Return values of `start_link` functions" @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | {:shutdown, term} | term} @typedoc "Return values of `start_child` functions" @type on_start_child :: {:ok, child} | {:ok, child, info :: term} | {:error, {:already_started, child} | :already_present | term} @type child :: pid | :undefined @typedoc "The Supervisor name" @type name :: atom | {:global, term} | {:via, module, term} @typedoc "Option values used by the `start*` functions" @type option :: {:name, name} | init_option() @typedoc "Options used by the `start*` functions" @type options :: [option, ...] @typedoc "The supervisor reference" @type supervisor :: pid | name | {atom, node} @typedoc "Options given to `start_link/2` and `init/2`" @type init_option :: {:strategy, strategy} | {:max_restarts, non_neg_integer} | {:max_seconds, pos_integer} @typedoc "Supported strategies" @type strategy :: :one_for_one | :one_for_all | :rest_for_one # Note we have inlined all types for readability @typedoc "The supervisor specification" @type child_spec :: %{ required(:id) => term(), required(:start) => {module(), atom(), [term()]}, optional(:restart) => :permanent | :transient | :temporary, optional(:shutdown) => :brutal_kill | non_neg_integer() | :infinity, optional(:type) => :worker | :supervisor, optional(:modules) => [module()] | :dynamic } @doc """ Starts a supervisor with the given children. The children is a list of modules, 2-element tuples with module and arguments or a map with the child specification. A strategy is required to be provided through the `:strategy` option. See "start_link/2, init/2 and strategies" for examples and other options. The options can also be used to register a supervisor name. The supported values are described under the "Name registration" section in the `GenServer` module docs. If the supervisor and its child processes are successfully spawned (if the start function of each child process returns `{:ok, child}`, `{:ok, child, info}`, or `:ignore`) this function returns `{:ok, pid}`, where `pid` is the PID of the supervisor. If the supervisor is given a name and a process with the specified name already exists, the function returns `{:error, {:already_started, pid}}`, where `pid` is the PID of that process. If the start function of any of the child processes fails or returns an error tuple or an erroneous value, the supervisor first terminates with reason `:shutdown` all the child processes that have already been started, and then terminates itself and returns `{:error, {:shutdown, reason}}`. Note that a supervisor started with this function is linked to the parent process and exits not only on crashes but also if the parent process exits with `:normal` reason. """ @spec start_link([:supervisor.child_spec() | {module, term} | module], options) :: on_start def start_link(children, options) when is_list(children) do {sup_opts, start_opts} = Keyword.split(options, [:strategy, :max_seconds, :max_restarts]) start_link(Supervisor.Default, init(children, sup_opts), start_opts) end @doc """ Receives a list of children to initialize and a set of options. This is typically invoked at the end of the `c:init/1` callback of module-based supervisors. See the sections "Module-based supervisors" and "start_link/2, init/2 and strategies" in the module documentation for more information. This function returns a tuple containing the supervisor flags and child specifications. ## Examples def init(_arg) do Supervisor.init([ {Stack, [:hello]} ], strategy: :one_for_one) end ## Options * `:strategy` - the restart strategy option. It can be either `:one_for_one`, `:rest_for_one`, `:one_for_all`, or the deprecated `:simple_one_for_one`. * `:max_restarts` - the maximum number of restarts allowed in a time frame. Defaults to `3`. * `:max_seconds` - the time frame in which `:max_restarts` applies. Defaults to `5`. The `:strategy` option is required and by default a maximum of 3 restarts is allowed within 5 seconds. Check the `Supervisor` module for a detailed description of the available strategies. """ # TODO: Warn if simple_one_for_one strategy is used on Elixir v1.8. @since "1.5.0" @spec init([:supervisor.child_spec() | {module, term} | module], [init_option]) :: {:ok, tuple} def init(children, options) when is_list(children) and is_list(options) do unless strategy = options[:strategy] do raise ArgumentError, "expected :strategy option to be given" end intensity = Keyword.get(options, :max_restarts, 3) period = Keyword.get(options, :max_seconds, 5) flags = %{strategy: strategy, intensity: intensity, period: period} {:ok, {flags, Enum.map(children, &init_child/1)}} end defp init_child(module) when is_atom(module) do init_child({module, []}) end defp init_child({module, arg}) when is_atom(module) do try do module.child_spec(arg) rescue e in UndefinedFunctionError -> case __STACKTRACE__ do [{^module, :child_spec, [^arg], _} | _] -> raise ArgumentError, child_spec_error(module) stack -> reraise e, stack end end end defp init_child(map) when is_map(map) do map end defp init_child({_, _, _, _, _, _} = tuple) do tuple end defp init_child(other) do raise ArgumentError, """ supervisors expect each child to be one of: * a module * a {module, arg} tuple * a child specification as a map with at least the :id and :start fields * or a tuple with 6 elements generated by Supervisor.Spec (deprecated) Got: #{inspect(other)} """ end defp child_spec_error(module) do if Code.ensure_loaded?(module) do """ The module #{inspect(module)} was given as a child to a supervisor but it does not implement child_spec/1. If you own the given module, please define a child_spec/1 function that receives an argument and returns a child specification as a map. For example: def child_spec(opts) do %{ id: __MODULE__, start: {__MODULE__, :start_link, [opts]}, type: :worker, restart: :permanent, shutdown: 500 } end Note that "use Agent", "use GenServer" and so on automatically define this function for you. However, if you don't own the given module and it doesn't implement child_spec/1, instead of passing the module name directly as a supervisor child, you will have to pass a child specification as a map: %{ id: #{inspect(module)}, start: {#{inspect(module)}, :start_link, [arg1, arg2]} } See the Supervisor documentation for more information. """ else "The module #{inspect(module)} was given as a child to a supervisor but it does not exist." end end @doc """ Builds and overrides a child specification. Similar to `start_link/2` and `init/2`, it expects a `module`, `{module, arg}` or a map as the child specification. If a module is given, the specification is retrieved by calling `module.child_spec(arg)`. After the child specification is retrieved, the fields on `config` are directly applied on the child spec. If `config` has keys that do not map to any child specification field, an error is raised. See the "Child specification" section in the module documentation for all of the available keys for overriding. ## Examples This function is often used to set an `:id` option when the same module needs to be started multiple times in the supervision tree: Supervisor.child_spec({Agent, fn -> :ok end}, id: {Agent, 1}) #=> %{id: {Agent, 1}, #=> start: {Agent, :start_link, [fn -> :ok end]}} """ @spec child_spec(child_spec() | {module, arg :: term} | module, keyword) :: child_spec() def child_spec(module_or_map, overrides) def child_spec({_, _, _, _, _, _} = tuple, _overrides) do raise ArgumentError, "old tuple-based child specification #{inspect(tuple)} " <> "is not supported in Supervisor.child_spec/2" end def child_spec(module_or_map, overrides) do Enum.reduce(overrides, init_child(module_or_map), fn {key, value}, acc when key in [:id, :start, :restart, :shutdown, :type, :modules] -> Map.put(acc, key, value) {key, _value}, _acc -> raise ArgumentError, "unknown key #{inspect(key)} in child specification override" end) end @doc """ Starts a module-based supervisor process with the given `module` and `arg`. To start the supervisor, the `c:init/1` callback will be invoked in the given `module`, with `arg` as its argument. The `c:init/1` callback must return a supervisor specification which can be created with the help of the `init/2` function. If the `c:init/1` callback returns `:ignore`, this function returns `:ignore` as well and the supervisor terminates with reason `:normal`. If it fails or returns an incorrect value, this function returns `{:error, term}` where `term` is a term with information about the error, and the supervisor terminates with reason `term`. The `:name` option can also be given in order to register a supervisor name, the supported values are described in the "Name registration" section in the `GenServer` module docs. """ # It is important to keep the 2-arity spec because it is a catch # all to start_link(children, options). @spec start_link(module, term) :: on_start @spec start_link(module, term, GenServer.options()) :: on_start def start_link(module, arg, options \\ []) when is_list(options) do case Keyword.get(options, :name) do nil -> :supervisor.start_link(module, arg) atom when is_atom(atom) -> :supervisor.start_link({:local, atom}, module, arg) {:global, _term} = tuple -> :supervisor.start_link(tuple, module, arg) {:via, via_module, _term} = tuple when is_atom(via_module) -> :supervisor.start_link(tuple, module, arg) other -> raise ArgumentError, """ expected :name option to be one of: * nil * atom * {:global, term} * {:via, module, term} Got: #{inspect(other)} """ end end @doc """ Adds a child specification to `supervisor` and starts that child. `child_spec` should be a valid child specification. The child process will be started as defined in the child specification. If a child specification with the specified id already exists, `child_spec` is discarded and this function returns an error with `:already_started` or `:already_present` if the corresponding child process is running or not, respectively. If the child process start function returns `{:ok, child}` or `{:ok, child, info}`, then child specification and PID are added to the supervisor and this function returns the same value. If the child process start function returns `:ignore`, the child specification is added to the supervisor, the PID is set to `:undefined` and this function returns `{:ok, :undefined}`. If the child process start function returns an error tuple or an erroneous value, or if it fails, the child specification is discarded and this function returns `{:error, error}` where `error` is a term containing information about the error and child specification. """ @spec start_child(supervisor, :supervisor.child_spec() | {module, term} | module | [term]) :: on_start_child def start_child(supervisor, {_, _, _, _, _, _} = child_spec) do call(supervisor, {:start_child, child_spec}) end # TODO: Deprecate this on Elixir v1.8. Remove and update typespec on v2.0. def start_child(supervisor, args) when is_list(args) do call(supervisor, {:start_child, args}) end def start_child(supervisor, child_spec) do call(supervisor, {:start_child, Supervisor.child_spec(child_spec, [])}) end @doc """ Terminates the given child identified by child id. The process is terminated, if there's one. The child specification is kept unless the child is temporary. A non-temporary child process may later be restarted by the supervisor. The child process can also be restarted explicitly by calling `restart_child/2`. Use `delete_child/2` to remove the child specification. If successful, this function returns `:ok`. If there is no child specification for the given child id, this function returns `{:error, :not_found}`. """ @spec terminate_child(supervisor, term()) :: :ok | {:error, error} when error: :not_found | :simple_one_for_one # TODO: Deprecate this on Elixir v1.8 def terminate_child(supervisor, child_id) def terminate_child(supervisor, pid) when is_pid(pid) do call(supervisor, {:terminate_child, pid}) end def terminate_child(supervisor, child_id) do call(supervisor, {:terminate_child, child_id}) end @doc """ Deletes the child specification identified by `child_id`. The corresponding child process must not be running; use `terminate_child/2` to terminate it if it's running. If successful, this function returns `:ok`. This function may return an error with an appropriate error tuple if the `child_id` is not found, or if the current process is running or being restarted. """ @spec delete_child(supervisor, term()) :: :ok | {:error, error} when error: :not_found | :simple_one_for_one | :running | :restarting def delete_child(supervisor, child_id) do call(supervisor, {:delete_child, child_id}) end @doc """ Restarts a child process identified by `child_id`. The child specification must exist and the corresponding child process must not be running. Note that for temporary children, the child specification is automatically deleted when the child terminates, and thus it is not possible to restart such children. If the child process start function returns `{:ok, child}` or `{:ok, child, info}`, the PID is added to the supervisor and this function returns the same value. If the child process start function returns `:ignore`, the PID remains set to `:undefined` and this function returns `{:ok, :undefined}`. This function may return an error with an appropriate error tuple if the `child_id` is not found, or if the current process is running or being restarted. If the child process start function returns an error tuple or an erroneous value, or if it fails, this function returns `{:error, error}`. """ @spec restart_child(supervisor, term()) :: {:ok, child} | {:ok, child, term} | {:error, error} when error: :not_found | :simple_one_for_one | :running | :restarting | term def restart_child(supervisor, child_id) do call(supervisor, {:restart_child, child_id}) end @doc """ Returns a list with information about all children of the given supervisor. Note that calling this function when supervising a large number of children under low memory conditions can cause an out of memory exception. This function returns a list of `{id, child, type, modules}` tuples, where: * `id` - as defined in the child specification * `child` - the PID of the corresponding child process, `:restarting` if the process is about to be restarted, or `:undefined` if there is no such process * `type` - `:worker` or `:supervisor`, as specified by the child specification * `modules` - as specified by the child specification """ @spec which_children(supervisor) :: [ {term() | :undefined, child | :restarting, :worker | :supervisor, :supervisor.modules()} ] def which_children(supervisor) do call(supervisor, :which_children) end @doc """ Returns a map containing count values for the given supervisor. The map contains the following keys: * `:specs` - the total count of children, dead or alive * `:active` - the count of all actively running child processes managed by this supervisor * `:supervisors` - the count of all supervisors whether or not these child supervisors are still alive * `:workers` - the count of all workers, whether or not these child workers are still alive """ @spec count_children(supervisor) :: %{ specs: non_neg_integer, active: non_neg_integer, supervisors: non_neg_integer, workers: non_neg_integer } def count_children(supervisor) do call(supervisor, :count_children) |> :maps.from_list() end @doc """ Synchronously stops the given supervisor with the given `reason`. It returns `:ok` if the supervisor terminates with the given reason. If it terminates with another reason, the call exits. This function keeps OTP semantics regarding error reporting. If the reason is any other than `:normal`, `:shutdown` or `{:shutdown, _}`, an error report is logged. """ @spec stop(supervisor, reason :: term, timeout) :: :ok def stop(supervisor, reason \\ :normal, timeout \\ :infinity) do GenServer.stop(supervisor, reason, timeout) end @compile {:inline, call: 2} defp call(supervisor, req) do GenServer.call(supervisor, req, :infinity) end end
37.645325
98
0.695948
038521a5a5b349ca8bd82fdcd33a958e1d391248
476
ex
Elixir
lib/game/application.ex
drewfravert/2048
cbe6b75635f7d2713277c3c60fb5147e256e73e3
[ "MIT" ]
null
null
null
lib/game/application.ex
drewfravert/2048
cbe6b75635f7d2713277c3c60fb5147e256e73e3
[ "MIT" ]
1
2021-10-18T21:44:37.000Z
2021-10-18T21:44:37.000Z
lib/game/application.ex
drewfravert/2048
cbe6b75635f7d2713277c3c60fb5147e256e73e3
[ "MIT" ]
null
null
null
defmodule Game.Application do @moduledoc false use Application def start(_type, _args) do children = [ Game.Repo, GameWeb.Telemetry, {Phoenix.PubSub, name: Game.PubSub}, GameWeb.Endpoint, Game.Manager ] opts = [name: Game.Supervisor, strategy: :one_for_one] Supervisor.start_link(children, opts) end def config_change(changed, _new, removed) do GameWeb.Endpoint.config_change(changed, removed) :ok end end
19.833333
58
0.67437
038529a6eef496a9eaced5c1db998122f78cd895
5,620
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_face_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_face_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p4beta1_face_annotation.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.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotation do @moduledoc """ A face annotation object contains the results of face detection. ## Attributes * `angerLikelihood` (*type:* `String.t`, *default:* `nil`) - Anger likelihood. * `blurredLikelihood` (*type:* `String.t`, *default:* `nil`) - Blurred likelihood. * `boundingPoly` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly.t`, *default:* `nil`) - The bounding polygon around the face. The coordinates of the bounding box are in the original image's scale. The bounding box is computed to "frame" the face in accordance with human expectations. It is based on the landmarker results. Note that one or more x and/or y coordinates may not be generated in the `BoundingPoly` (the polygon will be unbounded) if only a partial face appears in the image to be annotated. * `detectionConfidence` (*type:* `number()`, *default:* `nil`) - Detection confidence. Range [0, 1]. * `fdBoundingPoly` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly.t`, *default:* `nil`) - The `fd_bounding_poly` bounding polygon is tighter than the `boundingPoly`, and encloses only the skin part of the face. Typically, it is used to eliminate the face from any image analysis that detects the "amount of skin" visible in an image. It is not based on the landmarker results, only on the initial face detection, hence the <code>fd</code> (face detection) prefix. * `headwearLikelihood` (*type:* `String.t`, *default:* `nil`) - Headwear likelihood. * `joyLikelihood` (*type:* `String.t`, *default:* `nil`) - Joy likelihood. * `landmarkingConfidence` (*type:* `number()`, *default:* `nil`) - Face landmarking confidence. Range [0, 1]. * `landmarks` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotationLandmark.t)`, *default:* `nil`) - Detected face landmarks. * `panAngle` (*type:* `number()`, *default:* `nil`) - Yaw angle, which indicates the leftward/rightward angle that the face is pointing relative to the vertical plane perpendicular to the image. Range [-180,180]. * `rollAngle` (*type:* `number()`, *default:* `nil`) - Roll angle, which indicates the amount of clockwise/anti-clockwise rotation of the face relative to the image vertical about the axis perpendicular to the face. Range [-180,180]. * `sorrowLikelihood` (*type:* `String.t`, *default:* `nil`) - Sorrow likelihood. * `surpriseLikelihood` (*type:* `String.t`, *default:* `nil`) - Surprise likelihood. * `tiltAngle` (*type:* `number()`, *default:* `nil`) - Pitch angle, which indicates the upwards/downwards angle that the face is pointing relative to the image's horizontal plane. Range [-180,180]. * `underExposedLikelihood` (*type:* `String.t`, *default:* `nil`) - Under-exposed likelihood. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :angerLikelihood => String.t(), :blurredLikelihood => String.t(), :boundingPoly => GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly.t(), :detectionConfidence => number(), :fdBoundingPoly => GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly.t(), :headwearLikelihood => String.t(), :joyLikelihood => String.t(), :landmarkingConfidence => number(), :landmarks => list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotationLandmark.t()), :panAngle => number(), :rollAngle => number(), :sorrowLikelihood => String.t(), :surpriseLikelihood => String.t(), :tiltAngle => number(), :underExposedLikelihood => String.t() } field(:angerLikelihood) field(:blurredLikelihood) field(:boundingPoly, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly) field(:detectionConfidence) field(:fdBoundingPoly, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1BoundingPoly) field(:headwearLikelihood) field(:joyLikelihood) field(:landmarkingConfidence) field( :landmarks, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotationLandmark, type: :list ) field(:panAngle) field(:rollAngle) field(:sorrowLikelihood) field(:surpriseLikelihood) field(:tiltAngle) field(:underExposedLikelihood) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotation do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p4beta1FaceAnnotation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
50.178571
193
0.709609
03855a3015e2f54cff19a62e27f8b106544c15ce
3,594
exs
Elixir
apps/ewallet/test/ewallet/emails/forget_password_email_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/ewallet/test/ewallet/emails/forget_password_email_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/ewallet/test/ewallet/emails/forget_password_email_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-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 EWallet.ForgetPasswordEmailTest do use EWallet.DBCase, async: true import EWalletDB.Factory alias EWallet.ForgetPasswordEmail alias EWalletDB.ForgetPasswordRequest defp create_email(email, token, forward_url \\ nil) do user = insert(:user, email: email) _request = insert(:forget_password_request, token: token, user_uuid: user.uuid) request = ForgetPasswordRequest.get(user, token) email = ForgetPasswordEmail.create( request, "https://reset_url/?email={email}&token={token}", forward_url ) email end describe "ForgetPasswordEmail.create/3" do test "creates an email with correct from and to addresses" do email = create_email("forgetpassword@example.com", "the_token") # `from` should be the one set in the config assert email.from == Application.get_env(:ewallet, :sender_email) # `to` should be the user's email assert email.to == "forgetpassword@example.com" end test "creates an email with non-empty subject" do email = create_email("forgetpassword@example.com", "the_token") assert String.length(email.subject) > 0 end test "creates an email with email and token in the html body" do email = create_email("forgetpassword@example.com", "the_token") assert email.html_body =~ "https://reset_url/?email=forgetpassword%40example.com&token=the_token" end test "creates an email with email and token in the text body" do email = create_email("forgetpassword@example.com", "the_token") assert email.text_body =~ "https://reset_url/?email=forgetpassword%40example.com&token=the_token" end test "creates an email with properly encoded plus sign" do email = create_email("forgetpassword+test@example.com", "the_token") assert email.html_body =~ "https://reset_url/?email=forgetpassword%2Btest%40example.com&token=the_token" end test "creates an email with a forward_url and a normal email" do email = "forgetpassword@example.com" token = "the_token" forward_url = "my-app://reset_password?email={email}&token={token}" email = create_email(email, token, forward_url) assert email.html_body =~ "https://reset_url/?email=forgetpassword%40example.com&token=the_token&forward_url=my-app%3A%2F%2Freset_password%3Femail%3Dforgetpassword%40example.com%26token%3Dthe_token" end test "creates an email with a forward_url and an email containing +" do email = "forgetpassword+test@example.com" token = "the_token" forward_url = "my-app://reset_password?email={email}&token={token}" email = create_email(email, token, forward_url) assert email.html_body =~ "https://reset_url/?email=forgetpassword%2Btest%40example.com&token=the_token&forward_url=my-app%3A%2F%2Freset_password%3Femail%3Dforgetpassword%2Btest%40example.com%26token%3Dthe_token" end end end
38.234043
201
0.709794
03855ccc32f243cad6c7339c4d743c070406edf7
1,158
ex
Elixir
lib/chartjs_phoenix_demo/application.ex
jszod/chartjs_phoenix_demo
648b14d0dcdb5adf4b457adbd29172142f9fc8bf
[ "Apache-2.0" ]
null
null
null
lib/chartjs_phoenix_demo/application.ex
jszod/chartjs_phoenix_demo
648b14d0dcdb5adf4b457adbd29172142f9fc8bf
[ "Apache-2.0" ]
null
null
null
lib/chartjs_phoenix_demo/application.ex
jszod/chartjs_phoenix_demo
648b14d0dcdb5adf4b457adbd29172142f9fc8bf
[ "Apache-2.0" ]
null
null
null
defmodule ChartjsPhoenixDemo.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Ecto repository # Don't start for this non-database demo # ChartjsPhoenixDemo.Repo, # Start the Telemetry supervisor ChartjsPhoenixDemoWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: ChartjsPhoenixDemo.PubSub}, # Start the Endpoint (http/https) ChartjsPhoenixDemoWeb.Endpoint # Start a worker by calling: ChartjsPhoenixDemo.Worker.start_link(arg) # {ChartjsPhoenixDemo.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: ChartjsPhoenixDemo.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do ChartjsPhoenixDemoWeb.Endpoint.config_change(changed, removed) :ok end end
32.166667
76
0.724525
03857312084549c83c7405301f9130b5a173eaa2
53,724
ex
Elixir
lib/phoenix_live_view.ex
gaslight/phoenix_live_view
17a4c0790823e3c59eda8fca24a1604240f63811
[ "MIT" ]
4,659
2019-03-14T20:22:43.000Z
2022-03-31T20:13:30.000Z
lib/phoenix_live_view.ex
gaslight/phoenix_live_view
17a4c0790823e3c59eda8fca24a1604240f63811
[ "MIT" ]
1,745
2019-03-14T22:04:38.000Z
2022-03-31T17:26:25.000Z
lib/phoenix_live_view.ex
gaslight/phoenix_live_view
17a4c0790823e3c59eda8fca24a1604240f63811
[ "MIT" ]
744
2019-03-14T20:48:05.000Z
2022-03-25T14:35:04.000Z
defmodule Phoenix.LiveView do @moduledoc ~S''' LiveView provides rich, real-time user experiences with server-rendered HTML. The LiveView programming model is declarative: instead of saying "once event X happens, change Y on the page", events in LiveView are regular messages which may cause changes to its state. Once the state changes, LiveView will re-render the relevant parts of its HTML template and push it to the browser, which updates itself in the most efficient manner. This means developers write LiveView templates as any other server-rendered HTML and LiveView does the hard work of tracking changes and sending the relevant diffs to the browser. At the end of the day, a LiveView is nothing more than a process that receives events as messages and updates its state. The state itself is nothing more than functional and immutable Elixir data structures. The events are either internal application messages (usually emitted by `Phoenix.PubSub`) or sent by the client/browser. LiveView is first rendered statically as part of regular HTTP requests, which provides quick times for "First Meaningful Paint", in addition to helping search and indexing engines. Then a persistent connection is established between client and server. This allows LiveView applications to react faster to user events as there is less work to be done and less data to be sent compared to stateless requests that have to authenticate, decode, load, and encode data on every request. The flipside is that LiveView uses more memory on the server compared to stateless requests. ## Use cases There are many use cases where LiveView is an excellent fit right now: * Handling of user interaction and inputs, buttons, and forms - such as input validation, dynamic forms, autocomplete, etc; * Events and updates pushed by server - such as notifications, dashboards, etc; * Page and data navigation - such as navigating between pages, pagination, etc can be built with LiveView using the excellent live navigation feature set. This reduces the amount of data sent over the wire, gives developers full control over the LiveView life-cycle, while controlling how the browser tracks those changes in state; There are also use cases which are a bad fit for LiveView: * Animations - animations, menus, and general UI events that do not need the server in the first place are a bad fit for LiveView. Those can be achieved without LiveView in multiple ways, such as with CSS and CSS transitions, using LiveView hooks, or even integrating with UI toolkits designed for this purpose, such as Bootstrap, Alpine.JS, and similar. ## Life-cycle A LiveView begins as a regular HTTP request and HTML response, and then upgrades to a stateful view on client connect, guaranteeing a regular HTML page even if JavaScript is disabled. Any time a stateful view changes or updates its socket assigns, it is automatically re-rendered and the updates are pushed to the client. You begin by rendering a LiveView typically from your router. When LiveView is first rendered, the `c:mount/3` callback is invoked with the current params, the current session and the LiveView socket. As in a regular request, `params` contains public data that can be modified by the user. The `session` always contains private data set by the application itself. The `c:mount/3` callback wires up socket assigns necessary for rendering the view. After mounting, `c:render/1` is invoked and the HTML is sent as a regular HTML response to the client. After rendering the static page, LiveView connects from the client to the server where stateful views are spawned to push rendered updates to the browser, and receive client events via `phx-` bindings. Just like the first rendering, `c:mount/3` is invoked with params, session, and socket state, where mount assigns values for rendering. However in the connected client case, a LiveView process is spawned on the server, pushes the result of `c:render/1` to the client and continues on for the duration of the connection. If at any point during the stateful life-cycle a crash is encountered, or the client connection drops, the client gracefully reconnects to the server, calling `c:mount/3` once again. ## Example Before writing your first example, make sure that Phoenix LiveView is properly installed. If you are just getting started, this can be easily done by running `mix phx.new my_app --live`. The `phx.new` command with the `--live` flag will create a new project with LiveView installed and configured. Otherwise, please follow the steps in the [installation guide](installation.md) before continuing. A LiveView is a simple module that requires two callbacks: `c:mount/3` and `c:render/1`: defmodule MyAppWeb.ThermostatLive do # If you generated an app with mix phx.new --live, # the line below would be: use MyAppWeb, :live_view use Phoenix.LiveView def render(assigns) do ~H""" Current temperature: <%= @temperature %> """ end def mount(_params, %{"current_user_id" => user_id}, socket) do temperature = Thermostat.get_user_reading(user_id) {:ok, assign(socket, :temperature, temperature)} end end The `c:render/1` callback receives the `socket.assigns` and is responsible for returning rendered content. We use the `~H` sigil to define a HEEx template, which stands for HTML+EEx. They are an extension of Elixir's builtin EEx templates, with support for HTML validation, syntax-based components, smart change tracking, and more. You can learn more about the template syntax in `Phoenix.LiveView.Helpers.sigil_H/2`. Next, decide where you want to use your LiveView. You can serve the LiveView directly from your router (recommended): defmodule MyAppWeb.Router do use Phoenix.Router import Phoenix.LiveView.Router scope "/", MyAppWeb do live "/thermostat", ThermostatLive end end *Note:* the above assumes there is `plug :put_root_layout` call in your router that configures the LiveView layout. This call is automatically included by `mix phx.new --live` and described in the installation guide. If you don't want to configure a root layout, you must pass `layout: {MyAppWeb.LayoutView, "app.html"}` as an option to the `Phoenix.LiveView.Router.live/3` macro above. Alternatively, you can `live_render` from any template. In your view: import Phoenix.LiveView.Helpers Then in your template: <h1>Temperature Control</h1> <%= live_render(@conn, MyAppWeb.ThermostatLive) %> When a LiveView is rendered, all of the data currently stored in the connection session (see `Plug.Conn.get_session/1`) will be given to the LiveView. It is also possible to pass additional session information to the LiveView through a `:session` option: # In the router live "/thermostat", ThermostatLive, session: %{"extra_token" => "foo"} # In a view <%= live_render(@conn, MyAppWeb.ThermostatLive, session: %{"extra_token" => "foo"}) %> Notice the `:session` uses string keys as a reminder that session data is serialized and sent to the client. So you should always keep the data in the session to a minimum. For example, instead of storing a User struct, you should store the "user_id" and load the User when the LiveView mounts. Once the LiveView is rendered, a regular HTML response is sent. In your app.js file, you should find the following: import {Socket} from "phoenix" import {LiveSocket} from "phoenix_live_view" let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) liveSocket.connect() After the client connects, `c:mount/3` will be invoked inside a spawned LiveView process. At this point, you can use `connected?/1` to conditionally perform stateful work, such as subscribing to pubsub topics, sending messages, etc. For example, you can periodically update a LiveView with a timer: defmodule DemoWeb.ThermostatLive do use Phoenix.LiveView ... def mount(_params, %{"current_user_id" => user_id}, socket) do if connected?(socket), do: Process.send_after(self(), :update, 30000) case Thermostat.get_user_reading(user_id) do {:ok, temperature} -> {:ok, assign(socket, temperature: temperature, user_id: user_id)} {:error, _reason} -> {:ok, redirect(socket, to: "/error")} end end def handle_info(:update, socket) do Process.send_after(self(), :update, 30000) {:ok, temperature} = Thermostat.get_reading(socket.assigns.user_id) {:noreply, assign(socket, :temperature, temperature)} end end We used `connected?(socket)` on mount to send our view a message every 30s if the socket is in a connected state. We receive the `:update` message in the `c:handle_info/2` callback, just like in an Elixir `GenServer`, and update our socket assigns. Whenever a socket's assigns change, `c:render/1` is automatically invoked, and the updates are sent to the client. ## Colocating templates In the examples above, we have placed the template directly inside the LiveView: defmodule MyAppWeb.ThermostatLive do use Phoenix.LiveView def render(assigns) do ~H""" Current temperature: <%= @temperature %> """ end For larger templates, you can place them in a file in the same directory and same name as the LiveView. For example, if the file above is placed at `lib/my_app_web/live/thermostat_live.ex`, you can also remove the `c:render/1` definition above and instead put the template code at `lib/my_app_web/live/thermostat_live.html.heex`. Alternatively, you can keep the `c:render/1` callback but delegate to an existing `Phoenix.View` module in your application. For example: defmodule MyAppWeb.ThermostatLive do use Phoenix.LiveView def render(assigns) do Phoenix.View.render(MyAppWeb.PageView, "page.html", assigns) end end In all cases, each assign in the template will be accessible as `@assign`. You can learn more about [assigns and HEEx templates in their own guide](assigns-eex.md). ## Bindings Phoenix supports DOM element bindings for client-server interaction. For example, to react to a click on a button, you would render the element: <button phx-click="inc_temperature">+</button> Then on the server, all LiveView bindings are handled with the `c:handle_event/3` callback, for example: def handle_event("inc_temperature", _value, socket) do {:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id) {:noreply, assign(socket, :temperature, new_temp)} end | Binding | Attributes | |------------------------|------------| | [Params](bindings.md#click-events) | `phx-value-*` | | [Click Events](bindings.md#click-events) | `phx-click`, `phx-capture-click` | | [Focus/Blur Events](bindings.md#focus-and-blur-events) | `phx-blur`, `phx-focus`, `phx-window-blur`, `phx-window-focus` | | [Key Events](bindings.md#key-events) | `phx-keydown`, `phx-keyup`, `phx-window-keydown`, `phx-window-keyup`, `phx-key` | | [Form Events](form-bindings.md) | `phx-change`, `phx-submit`, `phx-feedback-for`, `phx-disable-with`, `phx-trigger-action`, `phx-auto-recover` | | [Rate Limiting](bindings.md#rate-limiting-events-with-debounce-and-throttle) | `phx-debounce`, `phx-throttle` | | [DOM Patching](dom-patching.md) | `phx-update` | | [JS Interop](js-interop.md#client-hooks) | `phx-hook` | ## Compartmentalize state, markup, and events in LiveView LiveView supports two extension mechanisms: function components, provided by `HEEx` templates, and stateful components. Function components are any function that receives an assigns map, similar to `render(assigns)` in our LiveView, and returns a `~H` template. For example: def weather_greeting(assigns) do ~H""" <div title="My div" class={@class}> <p>Hello <%= @name %></p> <MyApp.Weather.city name="Kraków"/> </div> """ end You can learn more about function components in the `Phoenix.Component` module. At the end of the day, they are useful mechanism to reuse markup in your LiveViews. However, sometimes you need to compartmentalize or reuse more than markup. Perhaps you want to move part of the state or part of the events in your LiveView to a separate module. For these cases, LiveView provides `Phoenix.LiveComponent`, which are rendered using [`live_component/1`](`Phoenix.LiveView.Helpers.live_component/1`): <.live_component module={UserComponent} id={user.id} user={user} /> Components have their own `c:mount/3` and `c:handle_event/3` callbacks, as well as their own state with change tracking support. Components are also lightweight as they "run" in the same process as the parent `LiveView`. However, this means an error in a component would cause the whole view to fail to render. See `Phoenix.LiveComponent` for a complete rundown on components. Finally, if you want complete isolation between parts of a LiveView, you can always render a LiveView inside another LiveView by calling [`live_render/3`](`Phoenix.LiveView.Helpers.live_render/3`). This child LiveView runs in a separate process than the parent, with its own callbacks. If a child LiveView crashes, it won't affect the parent. If the parent crashes, all children are terminated. When rendering a child LiveView, the `:id` option is required to uniquely identify the child. A child LiveView will only ever be rendered and mounted a single time, provided its ID remains unchanged. Given that a LiveView runs on its own process, it is an excellent tool for creating completely isolated UI elements, but it is a slightly expensive abstraction if all you want is to compartmentalize markup or events (or both). To sum it up: * use `Phoenix.Component` to compartmentalize/reuse markup * use `Phoenix.LiveComponent` to compartmentalize state, markup, and events * use nested `Phoenix.LiveView` to compartmentalize state, markup, events, and error isolation ## Endpoint configuration LiveView accepts the following configuration in your endpoint under the `:live_view` key: * `:signing_salt` (required) - the salt used to sign data sent to the client * `:hibernate_after` (optional) - the idle time in milliseconds allowed in the LiveView before compressing its own memory and state. Defaults to 15000ms (15 seconds) ## Guides LiveView has many guides to help you on your journey. ## Server-side These guides focus on server-side functionality: * [Assigns and HEEx templates](assigns-eex.md) * [Error and exception handling](error-handling.md) * [Live Layouts](live-layouts.md) * [Live Navigation](live-navigation.md) * [Security considerations of the LiveView model](security-model.md) * [Telemetry](telemetry.md) * [Uploads](uploads.md) * [Using Gettext for internationalization](using-gettext.md) ## Client-side These guides focus on LiveView bindings and client-side integration: * [Bindings](bindings.md) * [Form bindings](form-bindings.md) * [DOM patching and temporary assigns](dom-patching.md) * [JavaScript interoperability](js-interop.md) * [Uploads (External)](uploads-external.md) ''' alias Phoenix.LiveView.{Socket, Route} @type unsigned_params :: map @doc """ The LiveView entry-point. For each LiveView in the root of a template, `c:mount/3` is invoked twice: once to do the initial page load and again to establish the live socket. It expects three arguments: * `params` - a map of string keys which contain public information that can be set by the user. The map contains the query params as well as any router path parameter. If the LiveView was not mounted at the router, this argument is the atom `:not_mounted_at_router` * `session` - the connection session * `socket` - the LiveView socket It must return either `{:ok, socket}` or `{:ok, socket, options}`, where `options` is one of: * `:temporary_assigns` - a keyword list of assigns that are temporary and must be reset to their value after every render. Note that once the value is reset, it won't be re-rendered again until it is explicitly assigned * `:layout` - the optional layout to be used by the LiveView """ @callback mount( unsigned_params() | :not_mounted_at_router, session :: map, socket :: Socket.t() ) :: {:ok, Socket.t()} | {:ok, Socket.t(), keyword()} @callback render(assigns :: Socket.assigns()) :: Phoenix.LiveView.Rendered.t() @callback terminate(reason, socket :: Socket.t()) :: term when reason: :normal | :shutdown | {:shutdown, :left | :closed | term} @callback handle_params(unsigned_params(), uri :: String.t(), socket :: Socket.t()) :: {:noreply, Socket.t()} @callback handle_event(event :: binary, unsigned_params(), socket :: Socket.t()) :: {:noreply, Socket.t()} | {:reply, map, Socket.t()} @callback handle_call(msg :: term, {pid, reference}, socket :: Socket.t()) :: {:noreply, Socket.t()} | {:reply, term, Socket.t()} @callback handle_info(msg :: term, socket :: Socket.t()) :: {:noreply, Socket.t()} @callback handle_cast(msg :: term, socket :: Socket.t()) :: {:noreply, Socket.t()} @optional_callbacks mount: 3, terminate: 2, handle_params: 3, handle_event: 3, handle_call: 3, handle_info: 2, handle_cast: 2 @doc """ Uses LiveView in the current module to mark it a LiveView. use Phoenix.LiveView, namespace: MyAppWeb, container: {:tr, class: "colorized"}, layout: {MyAppWeb.LayoutView, "live.html"} ## Options * `:namespace` - configures the namespace the `LiveView` is in * `:container` - configures the container the `LiveView` will be wrapped in * `:layout` - configures the layout the `LiveView` will be rendered in """ defmacro __using__(opts) do # Expand layout if possible to avoid compile-time dependencies opts = with true <- Keyword.keyword?(opts), {layout, template} <- Keyword.get(opts, :layout) do layout = Macro.expand(layout, %{__CALLER__ | function: {:__live__, 0}}) Keyword.replace!(opts, :layout, {layout, template}) else _ -> opts end quote bind_quoted: [opts: opts] do @behaviour Phoenix.LiveView use Phoenix.Component require Phoenix.LiveView.Renderer @before_compile Phoenix.LiveView.Renderer @phoenix_live_opts opts Module.register_attribute(__MODULE__, :phoenix_live_mount, accumulate: true) @before_compile Phoenix.LiveView end end defmacro __before_compile__(env) do opts = Module.get_attribute(env.module, :phoenix_live_opts) layout = case opts[:layout] do {mod, template} when is_atom(mod) and is_binary(template) -> {mod, template} nil -> nil other -> raise ArgumentError, ":layout expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <> "got: #{inspect(other)}" end phoenix_live_mount = Module.get_attribute(env.module, :phoenix_live_mount) lifecycle = Phoenix.LiveView.Lifecycle.mount(env.module, phoenix_live_mount) namespace = opts[:namespace] || env.module |> Module.split() |> Enum.take(1) |> Module.concat() name = env.module |> Atom.to_string() |> String.replace_prefix("#{namespace}.", "") container = opts[:container] || {:div, []} live = %{ container: container, name: name, kind: :view, module: env.module, layout: layout, lifecycle: lifecycle } quote do @doc false def __live__ do unquote(Macro.escape(live)) end end end @doc """ Declares a module callback to be invoked on the LiveView's mount. The function within the given module, which must be named `on_mount`, will be invoked before both disconnected and connected mounts. The hook has the option to either halt or continue the mounting process as usual. If you wish to redirect the LiveView, you **must** halt, otherwise an error will be raised. Tip: if you need to define multiple `on_mount` callbacks, avoid defining multiple modules. Instead, pass a tuple and use pattern matching to handle different cases: def on_mount(:admin, _params, _session, _socket) do {:cont, socket} end def on_mount(:user, _params, _session, _socket) do {:cont, socket} end And then invoke it as: on_mount {MyAppWeb.SomeHook, :admin} on_mount {MyAppWeb.SomeHook, :user} Registering `on_mount` hooks can be useful to perform authentication as well as add custom behaviour to other callbacks via `attach_hook/4`. ## Examples The following is an example of attaching a hook via `Phoenix.LiveView.Router.live_session/3`: # lib/my_app_web/live/init_assigns.ex defmodule MyAppWeb.InitAssigns do @moduledoc "\"" Ensures common `assigns` are applied to all LiveViews attaching this hook. "\"" import Phoenix.LiveView def on_mount(:default, _params, _session, socket) do {:cont, assign(socket, :page_title, "DemoWeb")} end def on_mount(:user, _params, _session, socket) do end def on_mount(:admin, _params, _session, socket) do end end # lib/my_app_web/router.ex defmodule MyAppWeb.Router do use MyAppWeb, :router # pipelines, plugs, etc. live_session :default, on_mount: MyAppWeb.InitAssigns do scope "/", MyAppWeb do pipe_through :browser live "/", PageLive, :index end live_session :authenticated, on_mount: {MyAppWeb.InitAssigns, :user} do scope "/", MyAppWeb do pipe_through [:browser, :require_user] live "/profile", UserLive.Profile, :index end end live_session :admins, on_mount: {MyAppWeb.InitAssigns, :admin} do scope "/admin", MyAppWeb.Admin do pipe_through [:browser, :require_user, :require_admin] live "/", AdminLive.Index, :index end end end """ defmacro on_mount(mod_or_mod_arg) do mod_or_mod_arg = if Macro.quoted_literal?(mod_or_mod_arg) do Macro.prewalk(mod_or_mod_arg, &expand_alias(&1, __CALLER__)) else mod_or_mod_arg end quote do Module.put_attribute( __MODULE__, :phoenix_live_mount, Phoenix.LiveView.Lifecycle.on_mount(__MODULE__, unquote(mod_or_mod_arg)) ) end end defp expand_alias({:__aliases__, _, _} = alias, env), do: Macro.expand(alias, %{env | function: {:on_mount, 4}}) defp expand_alias(other, _env), do: other @doc """ Returns true if the socket is connected. Useful for checking the connectivity status when mounting the view. For example, on initial page render, the view is mounted statically, rendered, and the HTML is sent to the client. Once the client connects to the server, a LiveView is then spawned and mounted statefully within a process. Use `connected?/1` to conditionally perform stateful work, such as subscribing to pubsub topics, sending messages, etc. ## Examples defmodule DemoWeb.ClockLive do use Phoenix.LiveView ... def mount(_params, _session, socket) do if connected?(socket), do: :timer.send_interval(1000, self(), :tick) {:ok, assign(socket, date: :calendar.local_time())} end def handle_info(:tick, socket) do {:noreply, assign(socket, date: :calendar.local_time())} end end """ def connected?(%Socket{transport_pid: transport_pid}), do: transport_pid != nil @doc """ Assigns the given `key` with value from `fun` into `socket_or_assigns` if one does not yet exist. The first argument is either a LiveView `socket` or an `assigns` map from function components. Useful for lazily assigning values and referencing parent assigns. ## Referencing parent assigns When a LiveView is mounted in a disconnected state, the `Plug.Conn` assigns will be available for reference via `assign_new/3`, allowing assigns to be shared for the initial HTTP request. The `Plug.Conn` assigns will not be available during the connected mount. Likewise, nested LiveView children have access to their parent's assigns on mount using `assign_new/3`, which allows assigns to be shared down the nested LiveView tree. ## Examples # controller conn |> assign(:current_user, user) |> LiveView.Controller.live_render(MyLive, session: %{"user_id" => user.id}) # LiveView mount def mount(_params, %{"user_id" => user_id}, socket) do {:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)} end """ def assign_new(socket_or_assigns, key, fun) def assign_new(%Socket{} = socket, key, fun) when is_function(fun, 0) do validate_assign_key!(key) case socket do %{assigns: %{^key => _}} -> socket %{private: %{assign_new: {assigns, keys}}} -> # It is important to store the keys even if they are not in assigns # because maybe the controller doesn't have it but the view does. socket = put_in(socket.private.assign_new, {assigns, [key | keys]}) Phoenix.LiveView.Utils.force_assign(socket, key, Map.get_lazy(assigns, key, fun)) %{} -> Phoenix.LiveView.Utils.force_assign(socket, key, fun.()) end end def assign_new(%{__changed__: changed} = assigns, key, fun) when is_function(fun, 0) do case assigns do %{^key => _} -> assigns %{} -> Phoenix.LiveView.Utils.force_assign(assigns, changed, key, fun.()) end end def assign_new(assigns, _key, fun) when is_function(fun, 0) do raise ArgumentError, "assign_new/3 expects a socket or an assigns map from a function component as first argument, got: " <> inspect(assigns) end @doc """ Adds a `key`-`value` pair to `socket_or_assigns`. The first argument is either a LiveView `socket` or an `assigns` map from function components. ## Examples iex> assign(socket, :name, "Elixir") """ def assign(socket_or_assigns, key, value) def assign(%Socket{} = socket, key, value) do validate_assign_key!(key) Phoenix.LiveView.Utils.assign(socket, key, value) end def assign(%{__changed__: changed} = assigns, key, value) do case assigns do %{^key => ^value} -> assigns %{} -> Phoenix.LiveView.Utils.force_assign(assigns, changed, key, value) end end def assign(assigns, _key, _val) do raise ArgumentError, "assign/3 expects a socket or an assigns map from a function component as first argument, got: " <> inspect(assigns) end @doc """ Adds key-value pairs to assigns. The first argument is either a LiveView `socket` or an `assigns` map from function components. A keyword list or a map of assigns must be given as argument to be merged into existing assigns. ## Examples iex> assign(socket, name: "Elixir", logo: "💧") iex> assign(socket, %{name: "Elixir"}) """ def assign(socket_or_assigns, keyword_or_map) when is_map(keyword_or_map) or is_list(keyword_or_map) do Enum.reduce(keyword_or_map, socket_or_assigns, fn {key, value}, acc -> assign(acc, key, value) end) end defp validate_assign_key!(:flash) do raise ArgumentError, ":flash is a reserved assign by LiveView and it cannot be set directly. " <> "Use the appropriate flash functions instead." end defp validate_assign_key!(_key), do: :ok @doc """ Updates an existing `key` with `fun` in the given `socket_or_assigns`. The first argument is either a LiveView `socket` or an `assigns` map from function components. The update function receives the current key's value and returns the updated value. Raises if the key does not exist. ## Examples iex> update(socket, :count, fn count -> count + 1 end) iex> update(socket, :count, &(&1 + 1)) """ def update(socket_or_assigns, key, fun) def update(%Socket{assigns: assigns} = socket, key, fun) when is_function(fun, 1) do case assigns do %{^key => val} -> assign(socket, key, fun.(val)) %{} -> raise KeyError, key: key, term: assigns end end def update(assigns, key, fun) when is_function(fun, 1) do case assigns do %{^key => val} -> assign(assigns, key, fun.(val)) %{} -> raise KeyError, key: key, term: assigns end end def update(assigns, _key, fun) when is_function(fun, 1) do raise ArgumentError, "update/3 expects a socket or an assigns map from a function component as first argument, got: " <> inspect(assigns) end @doc """ Checks if the given key changed in `socket_or_assigns`. The first argument is either a LiveView `socket` or an `assigns` map from function components. ## Examples iex> changed?(socket, :count) """ def changed?(socket_or_assigns, key) def changed?(%Socket{assigns: assigns}, key) do Phoenix.LiveView.Utils.changed?(assigns, key) end def changed?(%{__changed__: _} = assigns, key) do Phoenix.LiveView.Utils.changed?(assigns, key) end def changed?(assigns, _key) do raise ArgumentError, "changed?/2 expects a socket or an assigns map from a function component as first argument, got: " <> inspect(assigns) end @doc """ Adds a flash message to the socket to be displayed. *Note*: While you can use `put_flash/3` inside a `Phoenix.LiveComponent`, components have their own `@flash` assigns. The `@flash` assign in a component is only copied to its parent LiveView if the component calls `push_redirect/2` or `push_patch/2`. *Note*: You must also place the `Phoenix.LiveView.Router.fetch_live_flash/2` plug in your browser's pipeline in place of `fetch_flash` for LiveView flash messages be supported, for example: import Phoenix.LiveView.Router pipeline :browser do ... plug :fetch_live_flash end ## Examples iex> put_flash(socket, :info, "It worked!") iex> put_flash(socket, :error, "You can't access that page") """ defdelegate put_flash(socket, kind, msg), to: Phoenix.LiveView.Utils @doc """ Clears the flash. ## Examples iex> clear_flash(socket) """ defdelegate clear_flash(socket), to: Phoenix.LiveView.Utils @doc """ Clears a key from the flash. ## Examples iex> clear_flash(socket, :info) """ defdelegate clear_flash(socket, key), to: Phoenix.LiveView.Utils @doc """ Pushes an event to the client to be consumed by hooks. *Note*: events will be dispatched to all active hooks on the client who are handling the given `event`. Scoped events can be achieved by namespacing your event names. ## Examples {:noreply, push_event(socket, "scores", %{points: 100, user: "josé"})} """ defdelegate push_event(socket, event, payload), to: Phoenix.LiveView.Utils @doc ~S""" Allows an upload for the provided name. ## Options * `:accept` - Required. A list of unique file type specifiers or the atom :any to allow any kind of file. For example, `[".jpeg"]`, `:any`, etc. * `:max_entries` - The maximum number of selected files to allow per file input. Defaults to 1. * `:max_file_size` - The maximum file size in bytes to allow to be uploaded. Defaults 8MB. For example, `12_000_000`. * `:chunk_size` - The chunk size in bytes to send when uploading. Defaults `64_000`. * `:chunk_timeout` - The time in milliseconds to wait before closing the upload channel when a new chunk has not been received. Defaults `10_000`. * `:external` - The 2-arity function for generating metadata for external client uploaders. See the Uploads section for example usage. * `:progress` - The optional 3-arity function for receiving progress events * `:auto_upload` - Instructs the client to upload the file automatically on file selection instead of waiting for form submits. Default false. Raises when a previously allowed upload under the same name is still active. ## Examples allow_upload(socket, :avatar, accept: ~w(.jpg .jpeg), max_entries: 2) allow_upload(socket, :avatar, accept: :any) For consuming files automatically as they are uploaded, you can pair `auto_upload: true` with a custom progress function to consume the entries as they are completed. For example: allow_upload(socket, :avatar, accept: :any, progress: &handle_progress/3, auto_upload: true) defp handle_progress(:avatar, entry, socket) do if entry.done? do uploaded_file = consume_uploaded_entry(socket, entry, fn %{} = meta -> ... end) {:noreply, put_flash(socket, :info, "file #{uploaded_file.name} uploaded")} else {:noreply, socket} end end """ defdelegate allow_upload(socket, name, options), to: Phoenix.LiveView.Upload @doc """ Revokes a previously allowed upload from `allow_upload/3`. ## Examples disallow_upload(socket, :avatar) """ defdelegate disallow_upload(socket, name), to: Phoenix.LiveView.Upload @doc """ Cancels an upload for the given entry. ## Examples <%= for entry <- @uploads.avatar.entries do %> ... <button phx-click="cancel-upload" phx-value-ref="<%= entry.ref %>">cancel</button> <% end %> def handle_event("cancel-upload", %{"ref" => ref}, socket) do {:noreply, cancel_upload(socket, :avatar, ref)} end """ defdelegate cancel_upload(socket, name, entry_ref), to: Phoenix.LiveView.Upload @doc """ Returns the completed and in progress entries for the upload. ## Examples case uploaded_entries(socket, :photos) do {[_ | _] = completed, []} -> # all entries are completed {[], [_ | _] = in_progress} -> # all entries are still in progress end """ defdelegate uploaded_entries(socket, name), to: Phoenix.LiveView.Upload @doc ~S""" Consumes the uploaded entries. Raises when there are still entries in progress. Typically called when submitting a form to handle the uploaded entries alongside the form data. For form submissions, it is guaranteed that all entries have completed before the submit event is invoked. Once entries are consumed, they are removed from the upload. ## Examples def handle_event("save", _params, socket) do uploaded_files = consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry -> dest = Path.join("priv/static/uploads", Path.basename(path)) File.cp!(path, dest) Routes.static_path(socket, "/uploads/#{Path.basename(dest)}") end) {:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))} end """ defdelegate consume_uploaded_entries(socket, name, func), to: Phoenix.LiveView.Upload @doc ~S""" Consumes an individual uploaded entry. Raises when the entry is still in progress. Typically called when submitting a form to handle the uploaded entries alongside the form data. Once entries are consumed, they are removed from the upload. This is a lower-level feature than `consume_uploaded_entries/3` and useful for scenarios where you want to consume entries as they are individually completed. ## Examples def handle_event("save", _params, socket) do case uploaded_entries(socket, :avatar) do {[_|_] = entries, []} -> uploaded_files = for entry <- entries do consume_uploaded_entry(socket, entry, fn %{path: path} -> dest = Path.join("priv/static/uploads", Path.basename(path)) File.cp!(path, dest) Routes.static_path(socket, "/uploads/#{Path.basename(dest)}") end) end {:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))} _ -> {:noreply, socket} end end """ defdelegate consume_uploaded_entry(socket, entry, func), to: Phoenix.LiveView.Upload @doc """ Annotates the socket for redirect to a destination path. *Note*: LiveView redirects rely on instructing client to perform a `window.location` update on the provided redirect location. The whole page will be reloaded and all state will be discarded. ## Options * `:to` - the path to redirect to. It must always be a local path * `:external` - an external path to redirect to """ def redirect(%Socket{} = socket, to: url) do validate_local_url!(url, "redirect/2") put_redirect(socket, {:redirect, %{to: url}}) end def redirect(%Socket{} = socket, external: url) do put_redirect(socket, {:redirect, %{external: url}}) end def redirect(%Socket{}, _) do raise ArgumentError, "expected :to or :external option in redirect/2" end @doc """ Annotates the socket for navigation within the current LiveView. When navigating to the current LiveView, `c:handle_params/3` is immediately invoked to handle the change of params and URL state. Then the new state is pushed to the client, without reloading the whole page while also maintaining the current scroll position. For live redirects to another LiveView, use `push_redirect/2`. ## Options * `:to` - the required path to link to. It must always be a local path * `:replace` - the flag to replace the current history or push a new state. Defaults `false`. ## Examples {:noreply, push_patch(socket, to: "/")} {:noreply, push_patch(socket, to: "/", replace: true)} """ def push_patch(%Socket{} = socket, opts) do %{to: to} = opts = push_opts!(opts, "push_patch/2") case Route.live_link_info!(socket, socket.private.root_view, to) do {:internal, %Route{params: params, action: action}} -> put_redirect(socket, {:live, {params, action}, opts}) {:external, _uri} -> raise ArgumentError, "cannot push_patch/2 to #{inspect(to)} because the given path " <> "does not point to the current root view #{inspect(socket.private.root_view)}" end end @doc """ Annotates the socket for navigation to another LiveView. The current LiveView will be shutdown and a new one will be mounted in its place, without reloading the whole page. This can also be used to remount the same LiveView, in case you want to start fresh. If you want to navigate to the same LiveView without remounting it, use `push_patch/2` instead. ## Options * `:to` - the required path to link to. It must always be a local path * `:replace` - the flag to replace the current history or push a new state. Defaults `false`. ## Examples {:noreply, push_redirect(socket, to: "/")} {:noreply, push_redirect(socket, to: "/", replace: true)} """ def push_redirect(%Socket{} = socket, opts) do opts = push_opts!(opts, "push_redirect/2") put_redirect(socket, {:live, :redirect, opts}) end defp push_opts!(opts, context) do to = Keyword.fetch!(opts, :to) validate_local_url!(to, context) kind = if opts[:replace], do: :replace, else: :push %{to: to, kind: kind} end defp put_redirect(%Socket{redirected: nil} = socket, command) do %Socket{socket | redirected: command} end defp put_redirect(%Socket{redirected: to} = _socket, _command) do raise ArgumentError, "socket already prepared to redirect with #{inspect(to)}" end @invalid_local_url_chars ["\\"] defp validate_local_url!("//" <> _ = to, where) do raise_invalid_local_url!(to, where) end defp validate_local_url!("/" <> _ = to, where) do if String.contains?(to, @invalid_local_url_chars) do raise ArgumentError, "unsafe characters detected for #{where} in URL #{inspect(to)}" else to end end defp validate_local_url!(to, where) do raise_invalid_local_url!(to, where) end defp raise_invalid_local_url!(to, where) do raise ArgumentError, "the :to option in #{where} expects a path but was #{inspect(to)}" end @doc """ Accesses the connect params sent by the client for use on connected mount. Connect params are only sent when the client connects to the server and only remain available during mount. `nil` is returned when called in a disconnected state and a `RuntimeError` is raised if called after mount. ## Reserved params The following params have special meaning in LiveView: * `"_csrf_token"` - the CSRF Token which must be explicitly set by the user when connecting * `"_mounts"` - the number of times the current LiveView is mounted. It is 0 on first mount, then increases on each reconnect. It resets when navigating away from the current LiveView or on errors * `"_track_static"` - set automatically with a list of all href/src from tags with the `phx-track-static` annotation in them. If there are no such tags, nothing is sent ## Examples def mount(_params, _session, socket) do {:ok, assign(socket, width: get_connect_params(socket)["width"] || @width)} end """ def get_connect_params(%Socket{private: private} = socket) do if connect_params = private[:connect_params] do if connected?(socket), do: connect_params, else: nil else raise_connect_only!(socket, "connect_params") end end @doc """ Accesses the connect info from the socket to use on connected mount. Connect info are only sent when the client connects to the server and only remain available during mount. `nil` is returned when called in a disconnected state and a `RuntimeError` is raised if called after mount. ## Examples First, when invoking the LiveView socket, you need to declare the `connect_info` you want to receive. Typically, it includes at least the session but it may include other keys, such as `:peer_data`. See `Phoenix.Endpoint.socket/3`: socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [:peer_data, session: @session_options]] Those values can now be accessed on the connected mount as `get_connect_info/1`: def mount(_params, _session, socket) do if info = get_connect_info(socket) do {:ok, assign(socket, ip: info.peer_data.address)} else {:ok, assign(socket, ip: nil)} end end """ def get_connect_info(%Socket{private: private} = socket) do if connect_info = private[:connect_info] do if connected?(socket), do: connect_info, else: nil else raise_connect_only!(socket, "connect_info") end end @doc """ Returns true if the socket is connected and the tracked static assets have changed. This function is useful to detect if the client is running on an outdated version of the marked static files. It works by comparing the static paths sent by the client with the one on the server. **Note:** this functionality requires Phoenix v1.5.2 or later. To use this functionality, the first step is to annotate which static files you want to be tracked by LiveView, with the `phx-track-static`. For example: <link phx-track-static rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/> <script defer phx-track-static type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script> Now, whenever LiveView connects to the server, it will send a copy `src` or `href` attributes of all tracked statics and compare those values with the latest entries computed by `mix phx.digest` in the server. The tracked statics on the client will match the ones on the server the huge majority of times. However, if there is a new deployment, those values may differ. You can use this function to detect those cases and show a banner to the user, asking them to reload the page. To do so, first set the assign on mount: def mount(params, session, socket) do {:ok, assign(socket, static_changed?: static_changed?(socket))} end And then in your views: <%= if @static_changed? do %> <div id="reload-static"> The app has been updated. Click here to <a href="#" onclick="window.location.reload()">reload</a>. </div> <% end %> If you prefer, you can also send a JavaScript script that immediately reloads the page. **Note:** only set `phx-track-static` on your own assets. For example, do not set it in external JavaScript files: <script defer phx-track-static type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> Because you don't actually serve the file above, LiveView will interpret the static above as missing, and this function will return true. """ def static_changed?(%Socket{private: private, endpoint: endpoint} = socket) do if connect_params = private[:connect_params] do connected?(socket) and static_changed?( connect_params["_track_static"], endpoint.config(:cache_static_manifest_latest) ) else raise_connect_only!(socket, "static_changed?") end end defp static_changed?([_ | _] = statics, %{} = latest) do latest = Map.to_list(latest) not Enum.all?(statics, fn static -> [static | _] = :binary.split(static, "?") Enum.any?(latest, fn {non_digested, digested} -> String.ends_with?(static, non_digested) or String.ends_with?(static, digested) end) end) end defp static_changed?(_, _), do: false defp raise_connect_only!(socket, fun) do if child?(socket) do raise RuntimeError, """ attempted to read #{fun} from a nested child LiveView #{inspect(socket.view)}. Only the root LiveView has access to #{fun}. """ else raise RuntimeError, """ attempted to read #{fun} outside of #{inspect(socket.view)}.mount/3. #{fun} only exists while mounting. If you require access to this information after mount, store the state in socket assigns. """ end end @doc """ Asynchronously updates a `Phoenix.LiveComponent` with new assigns. The `:id` that identifies the component must be passed as part of the assigns and it will be used to identify the live components to be updated. The `pid` argument is optional and it defaults to the current process, which means the update instruction will be sent to a component running on the same LiveView. If the current process is not a LiveView or you want to send updates to a live component running on another LiveView, you should explicitly pass the LiveView's pid instead. When the component receives the update, first the optional [`preload/1`](`c:Phoenix.LiveComponent.preload/1`) then [`update/2`](`c:Phoenix.LiveComponent.update/2`) is invoked with the new assigns. If [`update/2`](`c:Phoenix.LiveComponent.update/2`) is not defined all assigns are simply merged into the socket. While a component may always be updated from the parent by updating some parent assigns which will re-render the child, thus invoking [`update/2`](`c:Phoenix.LiveComponent.update/2`) on the child component, `send_update/3` is useful for updating a component that entirely manages its own state, as well as messaging between components mounted in the same LiveView. ## Examples def handle_event("cancel-order", _, socket) do ... send_update(Cart, id: "cart", status: "cancelled") {:noreply, socket} end def handle_event("cancel-order-asynchronously", _, socket) do ... pid = self() Task.async(fn -> # Do something asynchronously send_update(pid, Cart, id: "cart", status: "cancelled") end) {:noreply, socket} end """ def send_update(pid \\ self(), module, assigns) when is_atom(module) and is_pid(pid) do assigns = Enum.into(assigns, %{}) id = assigns[:id] || raise ArgumentError, "missing required :id in send_update. Got: #{inspect(assigns)}" Phoenix.LiveView.Channel.send_update(pid, module, id, assigns) end @doc """ Similar to `send_update/3` but the update will be delayed according to the given `time_in_milliseconds`. ## Examples def handle_event("cancel-order", _, socket) do ... send_update_after(Cart, [id: "cart", status: "cancelled"], 3000) {:noreply, socket} end def handle_event("cancel-order-asynchronously", _, socket) do ... pid = self() Task.async(fn -> # Do something asynchronously send_update_after(pid, Cart, [id: "cart", status: "cancelled"], 3000) end) {:noreply, socket} end """ def send_update_after(pid \\ self(), module, assigns, time_in_milliseconds) when is_atom(module) and is_integer(time_in_milliseconds) and is_pid(pid) do assigns = Enum.into(assigns, %{}) id = assigns[:id] || raise ArgumentError, "missing required :id in send_update_after. Got: #{inspect(assigns)}" Phoenix.LiveView.Channel.send_update_after(pid, module, id, assigns, time_in_milliseconds) end @doc """ Returns the transport pid of the socket. Raises `ArgumentError` if the socket is not connected. ## Examples iex> transport_pid(socket) #PID<0.107.0> """ def transport_pid(%Socket{}) do case Process.get(:"$callers") do [transport_pid | _] -> transport_pid _ -> raise ArgumentError, "transport_pid/1 may only be called when the socket is connected." end end defp child?(%Socket{parent_pid: pid}), do: is_pid(pid) @doc """ Attaches the given `fun` by `name` for the lifecycle `stage` into `socket`. > Note: This function is for server-side lifecycle callbacks. > For client-side hooks, see the > [JS Interop guide](js-interop.html#client-hooks). Hooks provide a mechanism to tap into key stages of the LiveView lifecycle in order to bind/update assigns, intercept events, patches, and regular messages when necessary, and to inject common functionality. Hooks may be attached to any of the following lifecycle stages: `:mount` (via `on_mount/1`), `:handle_params`, `:handle_event`, and `:handle_info`. ## Return Values Lifecycle hooks take place immediately before a given lifecycle callback is invoked on the LiveView. A hook may return `{:halt, socket}` to halt the reduction, otherwise it must return `{:cont, socket}` so the operation may continue until all hooks have been invoked for the current stage. ## Halting the lifecycle Note that halting from a hook _will halt the entire lifecycle stage_. This means that when a hook returns `{:halt, socket}` then the LiveView callback will **not** be invoked. This has some implications. ### Implications for plugin authors When defining a plugin that matches on specific callbacks, you **must** define a catch-all clause, as your hook will be invoked even for events you may not be interested on. ### Implications for end-users Allowing a hook to halt the invocation of the callback means that you can attach hooks to intercept specific events before detaching themselves, while allowing other events to continue normally. ## Examples def mount(_params, _session, socket) do socket = attach_hook(socket, :my_hook, :handle_event, fn "very-special-event", _params, socket -> # Handle the very special event and then detach the hook {:halt, detach_hook(socket, :my_hook, :handle_event)} _event, _params, socket -> {:cont, socket} end) {:ok, socket} end """ defdelegate attach_hook(socket, name, stage, fun), to: Phoenix.LiveView.Lifecycle @doc """ Detaches a hook with the given `name` from the lifecycle `stage`. > Note: This function is for server-side lifecycle callbacks. > For client-side hooks, see the > [JS Interop guide](js-interop.html#client-hooks). If no hook is found, this function is a no-op. ## Examples def handle_event(_, socket) do {:noreply, detach_hook(socket, :hook_that_was_attached, :handle_event)} end """ defdelegate detach_hook(socket, name, stage), to: Phoenix.LiveView.Lifecycle end
35.275115
148
0.679194
0385c3f883231030ef0df120f28cac87063372c9
937
ex
Elixir
lib/hound/browsers/firefox/profile.ex
eduardodflpereira/hound
d30548b0e6e673b886bb98101628e6227afa8c55
[ "MIT" ]
1,307
2015-01-03T16:50:15.000Z
2022-03-30T05:23:50.000Z
lib/hound/browsers/firefox/profile.ex
eduardodflpereira/hound
d30548b0e6e673b886bb98101628e6227afa8c55
[ "MIT" ]
209
2015-03-28T10:25:46.000Z
2022-02-13T01:16:34.000Z
lib/hound/browsers/firefox/profile.ex
eduardodflpereira/hound
d30548b0e6e673b886bb98101628e6227afa8c55
[ "MIT" ]
168
2015-03-30T10:58:11.000Z
2022-03-19T02:17:04.000Z
defmodule Hound.Browser.Firefox.Profile do @moduledoc false @default_prefs %{ } defstruct [prefs: @default_prefs] def new do %__MODULE__{} end def get_preference(%__MODULE__{prefs: prefs}, key) do Map.get(prefs, key) end def put_preference(profile, key, value) do %{profile | prefs: Map.put(profile.prefs, key, value)} end def set_user_agent(profile, user_agent) do put_preference(profile, "general.useragent.override", user_agent) end def serialize_preferences(profile) do profile.prefs |> Enum.map_join("\n", fn {key, value} -> ~s[user_pref("#{key}", #{Jason.encode!(value)});] end) end def dump(profile) do files = [{'user.js', serialize_preferences(profile)}] case :zip.create('profile.zip', files, [:memory]) do {:ok, {_filename, binary}} -> {:ok, Base.encode64(binary)} {:error, _reason} = error -> error end end end
22.309524
69
0.642476
0385f727de9d4ab75e18238110cee9828a92b727
1,783
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/lease_work_item_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/lease_work_item_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dataflow/lib/google_api/dataflow/v1b3/model/lease_work_item_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dataflow.V1b3.Model.LeaseWorkItemResponse do @moduledoc """ Response to a request to lease WorkItems. ## Attributes * `unifiedWorkerResponse` (*type:* `map()`, *default:* `nil`) - Untranslated bag-of-bytes WorkResponse for UnifiedWorker. * `workItems` (*type:* `list(GoogleApi.Dataflow.V1b3.Model.WorkItem.t)`, *default:* `nil`) - A list of the leased WorkItems. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :unifiedWorkerResponse => map(), :workItems => list(GoogleApi.Dataflow.V1b3.Model.WorkItem.t()) } field(:unifiedWorkerResponse, type: :map) field(:workItems, as: GoogleApi.Dataflow.V1b3.Model.WorkItem, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.LeaseWorkItemResponse do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.LeaseWorkItemResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.LeaseWorkItemResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.66
128
0.739204
0386277ad44d50926fa9eaf4e7a9bf974079b5ff
2,198
exs
Elixir
config/dev.exs
sFractal-Podii/quadquizaminos
1693f2d1c6ffee33065dd2ba7d899ac4aa405762
[ "MIT" ]
null
null
null
config/dev.exs
sFractal-Podii/quadquizaminos
1693f2d1c6ffee33065dd2ba7d899ac4aa405762
[ "MIT" ]
null
null
null
config/dev.exs
sFractal-Podii/quadquizaminos
1693f2d1c6ffee33065dd2ba7d899ac4aa405762
[ "MIT" ]
null
null
null
import Config # Configure your database config :quadquizaminos, Quadquizaminos.Repo, username: "postgres", password: "postgres", database: "quadquizaminos_dev", hostname: "localhost", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :quadquizaminos, QuadquizaminosWeb.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 :quadquizaminos, QuadquizaminosWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/quadquizaminos_web/(live|views)/.*(ex)$", ~r"lib/quadquizaminos_web/templates/.*(eex)$" ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
28.545455
68
0.699727
03862e545356da39e258cfd98f17ad13523bba39
1,024
ex
Elixir
lib/grovepi/registry/subscriber.ex
asummers/grovepi
8092fd704457265929e4d9676bedd8cf2176f48d
[ "Apache-2.0" ]
null
null
null
lib/grovepi/registry/subscriber.ex
asummers/grovepi
8092fd704457265929e4d9676bedd8cf2176f48d
[ "Apache-2.0" ]
null
null
null
lib/grovepi/registry/subscriber.ex
asummers/grovepi
8092fd704457265929e4d9676bedd8cf2176f48d
[ "Apache-2.0" ]
null
null
null
defmodule GrovePi.Registry.Subscriber do @moduledoc false @type event :: atom @type package :: any @type registration :: {GrovePi.pin(), event} @type message :: {GrovePi.pin(), event, package} @spec start_link(Registry.registry()) :: Supervisor.on_start() def start_link(prefix, opts \\ []) do opts = Keyword.put(opts, :id, :subscriber_registry) |> Keyword.put(:keys, :duplicate) |> Keyword.put(:name, registry(prefix)) Registry.start_link(opts) end @spec notify_change(atom, GrovePi.Buttons.message()) :: :ok def notify_change(prefix, {pin, event, _} = message) do Registry.dispatch(registry(prefix), {pin, event}, fn listeners -> for {pid, :ok} <- listeners, do: send(pid, message) end) end @spec subscribe(atom, registration) :: :ok | {:error, {:already_registered, pid}} def subscribe(prefix, message) do Registry.register(registry(prefix), message, :ok) end defp registry(prefix) do String.to_atom("#{prefix}.#{__MODULE__}") end end
29.257143
83
0.666016
03863540cba2599b73f6ab9eb4c681a645d2473a
645
ex
Elixir
othello/lib/othello_web/router.ex
Wycode-fish/WEBDEV-PROJECT-1
fad6870c97225ce206ed6b90645bb626b76f598c
[ "MIT" ]
null
null
null
othello/lib/othello_web/router.ex
Wycode-fish/WEBDEV-PROJECT-1
fad6870c97225ce206ed6b90645bb626b76f598c
[ "MIT" ]
null
null
null
othello/lib/othello_web/router.ex
Wycode-fish/WEBDEV-PROJECT-1
fad6870c97225ce206ed6b90645bb626b76f598c
[ "MIT" ]
null
null
null
defmodule OthelloWeb.Router do use OthelloWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", OthelloWeb do pipe_through :browser # Use the default browser stack get "/", PageController, :index post "/games/join", GameController, :join get "/g/:gname", GameController, :show get "/ai", GameController, :ai end # Other scopes may use custom stacks. # scope "/api", OthelloWeb do # pipe_through :api # end end
21.5
57
0.671318
03863aad098c283102cd554427e5b33c5d35d5da
1,335
exs
Elixir
config/test.exs
rjowens/pow_assent
585f0012a8a1fcec5ce15f86e8fd24a838fa61b5
[ "MIT" ]
null
null
null
config/test.exs
rjowens/pow_assent
585f0012a8a1fcec5ce15f86e8fd24a838fa61b5
[ "MIT" ]
null
null
null
config/test.exs
rjowens/pow_assent
585f0012a8a1fcec5ce15f86e8fd24a838fa61b5
[ "MIT" ]
null
null
null
use Mix.Config config :pow_assent, PowAssent.Test.Ecto.Repo, database: "pow_assent_test", pool: Ecto.Adapters.SQL.Sandbox, priv: "test/support/ecto/priv" config :pow_assent, PowAssent.Test.Phoenix.Endpoint, secret_key_base: String.duplicate("abcdefghijklmnopqrstuvxyz0123456789", 2), render_errors: [view: PowAssent.Test.Phoenix.ErrorView, accepts: ~w(html json)] config :pow_assent, PowAssent.Test.EmailConfirmation.Phoenix.Endpoint, secret_key_base: String.duplicate("abcdefghijklmnopqrstuvxyz0123456789", 2), render_errors: [view: PowAssent.Test.Phoenix.ErrorView, accepts: ~w(html json)] config :pow_assent, PowAssent.Test.Invitation.Phoenix.Endpoint, secret_key_base: String.duplicate("abcdefghijklmnopqrstuvxyz0123456789", 2), render_errors: [view: PowAssent.Test.Phoenix.ErrorView, accepts: ~w(html json)] config :pow_assent, PowAssent.Test.NoRegistration.Phoenix.Endpoint, secret_key_base: String.duplicate("abcdefghijklmnopqrstuvxyz0123456789", 2), render_errors: [view: PowAssent.Test.Phoenix.ErrorView, accepts: ~w(html json)] config :pow_assent, PowAssent.Test.WithAccessToken.Phoenix.Endpoint, secret_key_base: String.duplicate("abcdefghijklmnopqrstuvxyz0123456789", 2), render_errors: [view: PowAssent.Test.Phoenix.ErrorView, accepts: ~w(html json)] config :phoenix, :json_library, Jason
46.034483
81
0.799251
038673f159bb0857e340f810c52a26e099865703
211
exs
Elixir
test/secrets_manager_provider/ex_aws_client_test.exs
FindHotel/secrets_manager_provider
987d78ba949c9ff714b3289d216c9fcce98f4781
[ "MIT", "Unlicense" ]
10
2019-08-09T01:21:01.000Z
2021-08-08T17:27:06.000Z
test/secrets_manager_provider/ex_aws_client_test.exs
FindHotel/secrets_manager_provider
987d78ba949c9ff714b3289d216c9fcce98f4781
[ "MIT", "Unlicense" ]
4
2019-08-06T17:35:21.000Z
2021-09-09T03:32:04.000Z
test/secrets_manager_provider/ex_aws_client_test.exs
christopherlai/secrets_manager_provider
6ef9555611de38d0f2112b9c1fb5844053283b9d
[ "Unlicense", "MIT" ]
4
2019-08-05T19:20:57.000Z
2021-08-04T15:46:00.000Z
defmodule SecretsManagerProvider.ExAwsClientTest do use ExUnit.Case, async: true @moduletag :external describe "get_secrets/1" do test "returns secrets from AWS Secrets Manager" do end end end
19.181818
54
0.753555
03867cb0733691732f6c7aac5d65b035bdd5e057
72
exs
Elixir
.formatter.exs
wolcanism/mix_audit
5217f4be56519dd67dba0084929d1ed50517bc18
[ "BSD-3-Clause" ]
173
2020-03-04T14:04:46.000Z
2022-03-26T21:50:27.000Z
.formatter.exs
wolcanism/mix_audit
5217f4be56519dd67dba0084929d1ed50517bc18
[ "BSD-3-Clause" ]
5
2020-03-09T17:04:19.000Z
2021-12-29T17:38:20.000Z
.formatter.exs
wolcanism/mix_audit
5217f4be56519dd67dba0084929d1ed50517bc18
[ "BSD-3-Clause" ]
6
2020-03-11T21:43:48.000Z
2021-12-21T19:20:48.000Z
[ inputs: ["*.exs", "{lib,test}/**/*.{ex,exs}"], line_length: 180 ]
14.4
48
0.486111
038683a7809a8e93a50d261b8937a0c8fdff941d
442
ex
Elixir
lib/nostrum_boilerplate/consumer.ex
doorgan/nostrum_boilerplate
2206f6a0795da9f3fb896c2810c4da7dbdbd9cf3
[ "Unlicense" ]
3
2022-02-03T22:21:00.000Z
2022-02-21T16:31:53.000Z
lib/nostrum_boilerplate/consumer.ex
doorgan/nostrum_boilerplate
2206f6a0795da9f3fb896c2810c4da7dbdbd9cf3
[ "Unlicense" ]
null
null
null
lib/nostrum_boilerplate/consumer.ex
doorgan/nostrum_boilerplate
2206f6a0795da9f3fb896c2810c4da7dbdbd9cf3
[ "Unlicense" ]
null
null
null
defmodule NostrumBoilerplate.Consumer do @moduledoc false use Nostrum.Consumer alias NostrumBoilerplate.Commands def start_link do Consumer.start_link(__MODULE__) end def handle_event({:READY, _data, _ws_state}) do Commands.register_commands() end def handle_event({:INTERACTION_CREATE, interaction, _ws_state}) do Commands.handle_interaction(interaction) end def handle_event(_data) do :ok end end
19.217391
68
0.757919
0386b0417695b63084a2fcb6a8b7b1f34ac581bd
2,661
ex
Elixir
test/support/test_tools.ex
rubencaro/pedro
b550b3af700962283fa9e3985e1dcc2da2e14d0d
[ "MIT" ]
null
null
null
test/support/test_tools.ex
rubencaro/pedro
b550b3af700962283fa9e3985e1dcc2da2e14d0d
[ "MIT" ]
null
null
null
test/support/test_tools.ex
rubencaro/pedro
b550b3af700962283fa9e3985e1dcc2da2e14d0d
[ "MIT" ]
null
null
null
defmodule Pedro.TestTools do @moduledoc """ Custom assertions and handy functions and macros for testing. `import` into your `Case` modules like: defmodule Pedro.RequestControllerTest do use Pedro.ConnCase, async: true import Pedro.TestTools .... end """ defmacro assert_valid_json(conn) do quote do data = json_response(unquote(conn), 200) assert %{"valid" => true} = data data end end @doc """ `get` with the appropriate sigature from `Cipher` """ defmacro signed_get(conn, url) do quote do get unquote(conn), Cipher.sign_url(unquote(url)) end end defmacro signed_get(conn, path, data) do quote do signed_get(unquote(conn), "#{unquote(path)}?#{URI.encode_query(unquote(data))}") end end @doc """ `post` of JSON body with the appropriate sigature from `Cipher` """ defmacro signed_post(conn, url, data) do quote do input = unquote(data) signed_url = Cipher.sign_url_from_mapped_body(unquote(url), input) conn = unquote(conn) |> put_req_header("content-type", "application/json") |> post(signed_url, Poison.encode!(input)) end end @doc """ Run given block inside a `mnesia` transaction. Always `abort` the transaction after the block is run. No data should be left on the database, and test should be able to run parallel. """ defmacro in_test_transaction(do: block) do quote do run_in_test_transaction(fn-> unquote(block) end) end end def run_in_test_transaction(fun) do # an `Agent` unique for this <pid>_in_test_transaction pid = self |> :erlang.pid_to_list |> to_string agent = "#{pid}_in_test_transaction" |> String.to_atom Agent.start_link(fn -> %{error: nil, throw: nil} end, name: agent) :mnesia.transaction(fn -> # capture any error, exit or throw and save it for afterwards notification try do fun.() rescue x -> t = System.stacktrace # preserve original stacktrace Agent.update(agent, &Map.put(&1,:error,%{msg: x, trace: t})) catch x -> Agent.update(agent, &Map.put(&1,:throw,x)) end :mnesia.abort(:in_test_transaction) end) |> raise_if_unexpected # reproduce any captured specimen %{error: err, throw: thr} = Agent.get(agent, &(&1)) if err, do: reraise(err.msg,err.trace) if thr, do: throw(thr) end defp raise_if_unexpected(response) do case response do {:aborted, :in_test_transaction} -> :ok x -> raise("Unexpected return value from Mnesia transaction: #{inspect x}") end end end
26.878788
86
0.644119
0386d874c03c76c01e99608b4118d6a239b9c54e
4,475
exs
Elixir
lib/logger/test/logger/backends/console_test.exs
evalphobia/elixir
a07a2362e5827b09d8b27be2c1ad2980d25b9768
[ "Apache-2.0" ]
1
2017-07-25T21:46:25.000Z
2017-07-25T21:46:25.000Z
lib/logger/test/logger/backends/console_test.exs
evalphobia/elixir
a07a2362e5827b09d8b27be2c1ad2980d25b9768
[ "Apache-2.0" ]
null
null
null
lib/logger/test/logger/backends/console_test.exs
evalphobia/elixir
a07a2362e5827b09d8b27be2c1ad2980d25b9768
[ "Apache-2.0" ]
1
2017-07-25T21:46:48.000Z
2017-07-25T21:46:48.000Z
defmodule Logger.Backends.ConsoleTest do use Logger.Case require Logger import ExUnit.CaptureIO setup do on_exit fn -> :ok = Logger.configure_backend(:console, [format: nil, device: :user, level: nil, metadata: [], colors: [enabled: false]]) end end test "does not start when there is no user" do :ok = Logger.remove_backend(:console) user = Process.whereis(:user) try do Process.unregister(:user) assert :gen_event.add_handler(Logger, Logger.Backends.Console, :console) == {:error, :ignore} after Process.register(user, :user) end after {:ok, _} = Logger.add_backend(:console) end test "may use another device" do Logger.configure_backend(:console, device: :standard_error) assert capture_io(:standard_error, fn -> Logger.debug("hello") Logger.flush() end) =~ "hello" end test "can configure format" do Logger.configure_backend(:console, format: "$message [$level]") assert capture_log(fn -> Logger.debug("hello") end) =~ "hello [debug]" end test "can configure metadata" do Logger.configure_backend(:console, format: "$metadata$message", metadata: [:user_id]) assert capture_log(fn -> Logger.debug("hello") end) =~ "hello" Logger.metadata(user_id: 11) Logger.metadata(user_id: 13) assert capture_log(fn -> Logger.debug("hello") end) =~ "user_id=13 hello" end test "can configure formatter to {module, function} tuple" do Logger.configure_backend(:console, format: {__MODULE__, :format}) assert capture_log(fn -> Logger.debug("hello") end) =~ "my_format: hello" end def format(_level, message, _ts, _metadata) do "my_format: #{message}" end test "can configure metadata to :all" do Logger.configure_backend(:console, format: "$metadata", metadata: :all) Logger.metadata(user_id: 11) Logger.metadata(dynamic_metadata: 5) %{module: mod, function: {name, arity}, file: file, line: line} = __ENV__ log = capture_log(fn -> Logger.debug("hello") end) assert log =~ "file=#{file}" assert log =~ "line=#{line + 3}" assert log =~ "module=#{inspect(mod)}" assert log =~ "function=#{name}/#{arity}" assert log =~ "dynamic_metadata=5 user_id=11" end test "metadata defaults" do Logger.configure_backend(:console, format: "$metadata", metadata: [:file, :line, :module, :function]) %{module: mod, function: {name, arity}, file: file, line: line} = __ENV__ assert capture_log(fn -> Logger.debug("hello") end) =~ "file=#{file} line=#{line + 3} module=#{inspect(mod)} function=#{name}/#{arity}" end test "can configure level" do Logger.configure_backend(:console, level: :info) assert capture_log(fn -> Logger.debug("hello") end) == "" end test "can configure colors" do Logger.configure_backend(:console, [format: "$message", colors: [enabled: true]]) assert capture_log(fn -> Logger.debug("hello") end) == IO.ANSI.cyan() <> "hello" <> IO.ANSI.reset() Logger.configure_backend(:console, [colors: [debug: :magenta]]) assert capture_log(fn -> Logger.debug("hello") end) == IO.ANSI.magenta() <> "hello" <> IO.ANSI.reset() assert capture_log(fn -> Logger.info("hello") end) == IO.ANSI.normal() <> "hello" <> IO.ANSI.reset() Logger.configure_backend(:console, [colors: [info: :cyan]]) assert capture_log(fn -> Logger.info("hello") end) == IO.ANSI.cyan() <> "hello" <> IO.ANSI.reset() assert capture_log(fn -> Logger.warn("hello") end) == IO.ANSI.yellow() <> "hello" <> IO.ANSI.reset() Logger.configure_backend(:console, [colors: [warn: :cyan]]) assert capture_log(fn -> Logger.warn("hello") end) == IO.ANSI.cyan() <> "hello" <> IO.ANSI.reset() assert capture_log(fn -> Logger.error("hello") end) == IO.ANSI.red() <> "hello" <> IO.ANSI.reset() Logger.configure_backend(:console, [colors: [error: :cyan]]) assert capture_log(fn -> Logger.error("hello") end) == IO.ANSI.cyan() <> "hello" <> IO.ANSI.reset() end test "can use colors from metadata" do Logger.configure_backend(:console, [format: "$message", colors: [enabled: true]]) assert capture_log(fn -> Logger.log(:error, "hello", ansi_color: :yellow) end) == IO.ANSI.yellow() <> "hello" <> IO.ANSI.reset() end end
27.453988
95
0.626369
0386e935c9c3a25b1a4156596dab97f7b8a2ccfd
836
ex
Elixir
lib/platform_web/plugs/https_redirect_plug.ex
lucab85/audioslides.io
cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9
[ "MIT" ]
17
2017-11-14T14:03:18.000Z
2021-12-10T04:18:48.000Z
lib/platform_web/plugs/https_redirect_plug.ex
lucab85/audioslides.io
cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9
[ "MIT" ]
21
2017-11-19T13:38:07.000Z
2022-02-10T00:11:14.000Z
lib/platform_web/plugs/https_redirect_plug.ex
lucab85/audioslides.io
cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9
[ "MIT" ]
2
2019-09-03T03:32:13.000Z
2021-02-23T21:52:57.000Z
defmodule PlatformWeb.HttpsRedirectPlug do @moduledoc """ Redirects http to https if request comes from a proxy and the x-forwarded-proto header is set to http """ import Plug.Conn def init(opts), do: opts def call(conn, _opts) do if get_req_header(conn, "x-forwarded-proto") == ["http"] do redirect_to_https_version(conn) else conn end end defp redirect_to_https_version(conn) do status = if conn.method in ~w(HEAD GET), do: 301, else: 307 location = "https://" <> naked_host(conn.host) <> conn.request_path <> qs(conn.query_string) conn |> put_resp_header("location", location) |> send_resp(status, "You are being redirected") |> halt() end defp naked_host(host), do: String.trim_leading(host, "www.") defp qs(""), do: "" defp qs(qs), do: "?" <> qs end
24.588235
96
0.656699
0386ffcc84968c89be1e953dce1bc0584c3dc781
1,872
ex
Elixir
lib/push_gateway/dispatcher.ex
SmartColumbusOS/push-gateway
4055ac0e320ba178a443336fa016f365745c6773
[ "Apache-2.0" ]
null
null
null
lib/push_gateway/dispatcher.ex
SmartColumbusOS/push-gateway
4055ac0e320ba178a443336fa016f365745c6773
[ "Apache-2.0" ]
null
null
null
lib/push_gateway/dispatcher.ex
SmartColumbusOS/push-gateway
4055ac0e320ba178a443336fa016f365745c6773
[ "Apache-2.0" ]
null
null
null
defmodule PushGateway.Dispatcher do @moduledoc false use GenStage require Logger def start_link({number, init_args}) do name = :"#{__MODULE__}.#{number}" GenStage.start_link(__MODULE__, init_args, name: name) end def init(init_args) do producer_name = Keyword.fetch!(init_args, :producer_name) topic = Keyword.fetch!(init_args, :topic) processors = Keyword.get(init_args, :processors, 1) state = %{ min: Keyword.get(init_args, :min_batch, 75), max: Keyword.get(init_args, :max_batch, 100) } subscription = processors(processors, state.min, state.max) {:consumer, %{topic: topic, producer_name: producer_name}, [subscribe_to: subscription]} end def handle_events(messages, _from, %{producer_name: producer_name, topic: topic} = state) do Logger.debug("Dispatching - #{Enum.count(messages)}") encoded_messages = Enum.map(messages, &encode_as_data_message/1) Elsa.produce(producer_name, topic, encoded_messages, partition: 0) {:noreply, [], state} end defp processors(count, min, max) do 0..(count - 1) |> Enum.map(&subscriptions(&1, min, max)) end defp subscriptions(item, min, max) do {processor_name(item), min_demand: min, max_demand: max} end defp encode_as_data_message(message) do data_message = %{ dataset_id: assigned_dataset_id(), payload: message, operational: %{ timing: [] }, _metadata: %{} } {:ok, smrt_data_message} = SmartCity.Data.new(data_message) Jason.encode!(smrt_data_message) end defp processor_name(item), do: :"Elixir.PushGateway.Processor.#{item}" defp assigned_dataset_id(), do: Application.get_env(:push_gateway, :assigned_dataset_id) end defimpl Jason.Encoder, for: [Tuple] do def encode(tuple, opts) do Jason.Encode.list(Tuple.to_list(tuple), opts) end end
27.130435
94
0.686966
03870eecda64179d0d598807a4ff40d92b5e5013
671
ex
Elixir
elixir/lib/com/spoonacular/client/model/inline_response_200_6.ex
ddsky/spoonacular-api-clients
63f955ceb2c356fefdd48ec634deb3c3e16a6ae7
[ "MIT" ]
21
2019-08-09T18:53:26.000Z
2022-03-14T22:10:10.000Z
elixir/lib/com/spoonacular/client/model/inline_response_200_6.ex
ddsky/spoonacular-api-clients
63f955ceb2c356fefdd48ec634deb3c3e16a6ae7
[ "MIT" ]
null
null
null
elixir/lib/com/spoonacular/client/model/inline_response_200_6.ex
ddsky/spoonacular-api-clients
63f955ceb2c356fefdd48ec634deb3c3e16a6ae7
[ "MIT" ]
55
2019-08-13T17:52:47.000Z
2022-03-27T04:29:34.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule com.spoonacular.client.Model.InlineResponse2006 do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"recipes" ] @type t :: %__MODULE__{ :"recipes" => [InlineResponse2006Recipes] } end defimpl Poison.Decoder, for: com.spoonacular.client.Model.InlineResponse2006 do import com.spoonacular.client.Deserializer def decode(value, options) do value |> deserialize(:"recipes", :list, com.spoonacular.client.Model.InlineResponse2006Recipes, options) end end
23.964286
102
0.727273
0387113c53488e632a74813345e402aec3182b92
2,371
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/list_bid_responses_without_bids_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/list_bid_responses_without_bids_response.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/list_bid_responses_without_bids_response.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.AdExchangeBuyer.V2beta1.Model.ListBidResponsesWithoutBidsResponse do @moduledoc """ Response message for listing all reasons that bid responses were considered to have no applicable bids. ## Attributes * `bidResponseWithoutBidsStatusRows` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.BidResponseWithoutBidsStatusRow.t)`, *default:* `nil`) - List of rows, with counts of bid responses without bids aggregated by status. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A token to retrieve the next page of results. Pass this value in the ListBidResponsesWithoutBidsRequest.pageToken field in the subsequent call to the bidResponsesWithoutBids.list method to retrieve the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :bidResponseWithoutBidsStatusRows => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.BidResponseWithoutBidsStatusRow.t()), :nextPageToken => String.t() } field(:bidResponseWithoutBidsStatusRows, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.BidResponseWithoutBidsStatusRow, type: :list ) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ListBidResponsesWithoutBidsResponse do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.ListBidResponsesWithoutBidsResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ListBidResponsesWithoutBidsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.924242
222
0.754534
03872f1120304595b53526de7ce6825a6d7ccb07
2,327
ex
Elixir
lib/koans/03_numbers.ex
agata-anastazja/elixir-koans
29eda0a5dc820409063ffc921e00c368973ce4ee
[ "MIT" ]
null
null
null
lib/koans/03_numbers.ex
agata-anastazja/elixir-koans
29eda0a5dc820409063ffc921e00c368973ce4ee
[ "MIT" ]
null
null
null
lib/koans/03_numbers.ex
agata-anastazja/elixir-koans
29eda0a5dc820409063ffc921e00c368973ce4ee
[ "MIT" ]
null
null
null
defmodule Numbers do require Integer use Koans @intro "Why is the number six so scared? Because seven eight nine!\nWe should get to know numbers a bit more!" koan "Are you odd?" do assert Integer.is_odd(3) == true end koan "Actually you might be even" do assert Integer.is_even(4) == true end koan "Let's grab the individual digits in a list" do individual_digits = Integer.digits(58127) assert individual_digits == [5,8,1,2,7] end koan "Oh no! I need it back together" do number = Integer.undigits([1, 2, 3, 4]) assert number == 1234 end koan "Actually I want my number as a string" do string_digit = Integer.to_string(1234) assert string_digit == "1234" end koan "The meaning of life in hexidecimal is 2A!" do assert Integer.parse("2A", 16) == {42, ""} end koan "The remaining unparsable part is also returned" do assert Integer.parse("5 years") == {5, " years"} end koan "What if you parse a floating point value as an integer?" do assert Integer.parse("1.2") == {1, ".2"} end koan "Just want to parse to a float" do assert Float.parse("34.5") == {34.5, ""} end koan "Hmm, I want to parse this but it has some strings" do assert Float.parse("1.5 million dollars") == {1.5, " million dollars"} end koan "I don't want this decimal point, let's round up" do assert Float.ceil(34.25) == 35.0 end koan "OK, I only want it to 1 decimal place" do assert Float.ceil(34.25, 1) == 34.3 end koan "Rounding down is what I need" do assert Float.floor(99.99) == 99.0 end koan "Rounding down to 2 decimal places" do assert Float.floor(12.345, 2) == 12.34 end koan "Round the number up or down for me" do assert Float.round(5.5) == 6 assert Float.round(5.4) == 5 assert Float.round(8.94, 1) == 8.9 assert Float.round(-5.5674, 3) == -5.567 end koan "I want the first and last in the range" do first..last = Range.new(1, 10) assert first == 1 assert last == 10 end koan "Does my number exist in the range?" do range = Range.new(1, 10) assert 4 in range == true assert 10 in range == true assert 0 in range == false end koan "Is this a range?" do assert Range.range?(1..10) == true assert Range.range?(0) == false end end
24.494737
112
0.640309
0387305c81f0f530c5143cf92e30c804cd84ec0b
171
ex
Elixir
lib/exhmac/error.ex
lizhaochao/ExHmac
9e7e00999362107e17528d6d9af97da7f461d6a9
[ "MIT" ]
null
null
null
lib/exhmac/error.ex
lizhaochao/ExHmac
9e7e00999362107e17528d6d9af97da7f461d6a9
[ "MIT" ]
null
null
null
lib/exhmac/error.ex
lizhaochao/ExHmac
9e7e00999362107e17528d6d9af97da7f461d6a9
[ "MIT" ]
null
null
null
defmodule ExHmac.Error do @moduledoc false defexception message: nil def warn(text, true = _warn), do: IO.warn(text, []) def warn(_text, _warn), do: :ignore end
19
53
0.690058
03873fca8f084a72c9b7b65d8706edc41ad361c3
4,316
ex
Elixir
clients/access_approval/lib/google_api/access_approval/v1beta1/model/approval_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/access_approval/lib/google_api/access_approval/v1beta1/model/approval_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/access_approval/lib/google_api/access_approval/v1beta1/model/approval_request.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.AccessApproval.V1beta1.Model.ApprovalRequest do @moduledoc """ A request for the customer to approve access to a resource. ## Attributes * `approve` (*type:* `GoogleApi.AccessApproval.V1beta1.Model.ApproveDecision.t`, *default:* `nil`) - Access was approved. * `dismiss` (*type:* `GoogleApi.AccessApproval.V1beta1.Model.DismissDecision.t`, *default:* `nil`) - The request was dismissed. * `name` (*type:* `String.t`, *default:* `nil`) - The resource name of the request. Format is "{projects|folders|organizations}/{id}/approvalRequests/{approval_request_id}". * `requestTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which approval was requested. * `requestedExpiration` (*type:* `DateTime.t`, *default:* `nil`) - The requested expiration for the approval. If the request is approved, access will be granted from the time of approval until the expiration time. * `requestedLocations` (*type:* `GoogleApi.AccessApproval.V1beta1.Model.AccessLocations.t`, *default:* `nil`) - The locations for which approval is being requested. * `requestedReason` (*type:* `GoogleApi.AccessApproval.V1beta1.Model.AccessReason.t`, *default:* `nil`) - The justification for which approval is being requested. * `requestedResourceName` (*type:* `String.t`, *default:* `nil`) - The resource for which approval is being requested. The format of the resource name is defined at https://cloud.google.com/apis/design/resource_names. The resource name here may either be a "full" resource name (e.g. "//library.googleapis.com/shelves/shelf1/books/book2") or a "relative" resource name (e.g. "shelves/shelf1/books/book2") as described in the resource name specification. * `requestedResourceProperties` (*type:* `GoogleApi.AccessApproval.V1beta1.Model.ResourceProperties.t`, *default:* `nil`) - Properties related to the resource represented by requested_resource_name. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :approve => GoogleApi.AccessApproval.V1beta1.Model.ApproveDecision.t(), :dismiss => GoogleApi.AccessApproval.V1beta1.Model.DismissDecision.t(), :name => String.t(), :requestTime => DateTime.t(), :requestedExpiration => DateTime.t(), :requestedLocations => GoogleApi.AccessApproval.V1beta1.Model.AccessLocations.t(), :requestedReason => GoogleApi.AccessApproval.V1beta1.Model.AccessReason.t(), :requestedResourceName => String.t(), :requestedResourceProperties => GoogleApi.AccessApproval.V1beta1.Model.ResourceProperties.t() } field(:approve, as: GoogleApi.AccessApproval.V1beta1.Model.ApproveDecision) field(:dismiss, as: GoogleApi.AccessApproval.V1beta1.Model.DismissDecision) field(:name) field(:requestTime, as: DateTime) field(:requestedExpiration, as: DateTime) field(:requestedLocations, as: GoogleApi.AccessApproval.V1beta1.Model.AccessLocations) field(:requestedReason, as: GoogleApi.AccessApproval.V1beta1.Model.AccessReason) field(:requestedResourceName) field(:requestedResourceProperties, as: GoogleApi.AccessApproval.V1beta1.Model.ResourceProperties ) end defimpl Poison.Decoder, for: GoogleApi.AccessApproval.V1beta1.Model.ApprovalRequest do def decode(value, options) do GoogleApi.AccessApproval.V1beta1.Model.ApprovalRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AccessApproval.V1beta1.Model.ApprovalRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
52
202
0.735171
038749328cec03a4de0df7917a12cb4fe4335327
2,210
ex
Elixir
apps/omg_watcher/lib/exit_validator/validator.ex
SingularityMatrix/elixir-omg
7db3fcc3adfa303e30ff7703148cc5110b587d20
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/lib/exit_validator/validator.ex
SingularityMatrix/elixir-omg
7db3fcc3adfa303e30ff7703148cc5110b587d20
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher/lib/exit_validator/validator.ex
SingularityMatrix/elixir-omg
7db3fcc3adfa303e30ff7703148cc5110b587d20
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.Watcher.ExitValidator.Validator do @moduledoc """ Contains 'challenge_fastly_invalid_exits' and 'challenge_slowly_invalid_exits' functions used for current exit validation design which consits of `FastValidator` and `SlowValidator`. See docs/exit_validation.md for more information. """ use OMG.API.LoggerExt alias OMG.API.EventerAPI alias OMG.API.Utxo alias OMG.Watcher.Eventer.Event require Utxo @doc """ Validates exits and pushes them to `DB.EthEvent`. if exit is invalid then emits `:invalid_exit` event """ @spec challenge_fastly_invalid_exits :: ([OMG.API.State.Core.exit_t()] -> :ok) def challenge_fastly_invalid_exits do challenge_invalid_exits(false) end @doc """ Validates and spends exits in the "OMG.API.State" and if exit is invalid then emits `:invalid_exit` event """ @spec challenge_slowly_invalid_exits :: (fun() -> :ok) def challenge_slowly_invalid_exits do challenge_invalid_exits(true) end defp challenge_invalid_exits(is_slow_validator) do fn utxo_exits -> _ = Enum.map(utxo_exits, &challenge_invalid_exit(&1, is_slow_validator)) :ok end end defp challenge_invalid_exit(utxo_exit, is_slow_validator) do cond do not OMG.API.State.utxo_exists?(utxo_exit) -> EventerAPI.emit_events([struct(Event.InvalidExit, utxo_exit)]) not is_slow_validator -> _ = OMG.Watcher.DB.EthEvent.insert_exits([utxo_exit]) is_slow_validator -> :ok = OMG.API.State.exit_utxos([utxo_exit]) _ = Logger.info(fn -> "Spent exit: #{inspect(utxo_exit)}" end) end end end
33.484848
109
0.729412
038765c0fa6693dc2b72e56f91d4174f3173e5a7
1,950
exs
Elixir
clients/service_consumer_management/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/mix.exs
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.ServiceConsumerManagement.Mixfile do use Mix.Project @version "0.21.0" def project() do [ app: :google_api_service_consumer_management, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/service_consumer_management" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.2"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Service Consumer Management API client library. Manages the service consumers of a Service Infrastructure service. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/service_consumer_management", "Homepage" => "https://cloud.google.com/service-consumer-management/docs/overview" } ] end end
29.104478
118
0.673846
0387983ee4f683f299f01c4ba1593b87b398bba1
971
ex
Elixir
lib/freshcom_web/application.ex
freshcom/freshcom_web
fab44c9468e86b1770eef9971a97ad2b11545e9c
[ "BSD-3-Clause" ]
9
2018-12-16T14:02:59.000Z
2021-01-19T07:25:40.000Z
lib/freshcom_web/application.ex
freshcom/freshcom_web
fab44c9468e86b1770eef9971a97ad2b11545e9c
[ "BSD-3-Clause" ]
null
null
null
lib/freshcom_web/application.ex
freshcom/freshcom_web
fab44c9468e86b1770eef9971a97ad2b11545e9c
[ "BSD-3-Clause" ]
4
2018-12-16T17:50:01.000Z
2021-01-19T07:25:51.000Z
defmodule FreshcomWeb.Application do use Application # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec # Define workers and child supervisors to be supervised children = [ # Start the endpoint when the application starts supervisor(FreshcomWeb.Endpoint, []), # Start your own worker by calling: FreshcomWeb.Worker.start_link(arg1, arg2, arg3) # worker(FreshcomWeb.Worker, [arg1, arg2, arg3]), ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: FreshcomWeb.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do FreshcomWeb.Endpoint.config_change(changed, removed) :ok end end
32.366667
89
0.726056
03879c076b193d16e5ce33e599521973f3ed6e0f
1,994
exs
Elixir
apps/flexray/config/config.exs
niclaslind/signalbroker-server
afb80514dcbabe561ac2da42adc08843a15c37c5
[ "Apache-2.0" ]
17
2020-06-20T11:29:43.000Z
2022-03-21T05:53:06.000Z
apps/flexray/config/config.exs
niclaslind/signalbroker-server
afb80514dcbabe561ac2da42adc08843a15c37c5
[ "Apache-2.0" ]
2
2020-07-09T10:22:50.000Z
2020-09-01T14:46:40.000Z
apps/flexray/config/config.exs
niclaslind/signalbroker-server
afb80514dcbabe561ac2da42adc08843a15c37c5
[ "Apache-2.0" ]
3
2020-07-17T20:04:36.000Z
2022-01-24T14:19:46.000Z
# Copyright 2019 Volvo Cars # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :flexray, key: :value # # and access this configuration in your application as: # # Application.get_env(:flexray, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs" if Mix.env == :prod, do: import_config "#{Mix.env}.exs"
39.098039
73
0.75677
0387a1d15b9668883221abc1914a64e86911f2fe
3,718
ex
Elixir
clients/ad_experience_report/lib/google_api/ad_experience_report/v1/api/violating_sites.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_experience_report/lib/google_api/ad_experience_report/v1/api/violating_sites.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_experience_report/lib/google_api/ad_experience_report/v1/api/violating_sites.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.AdExperienceReport.V1.Api.ViolatingSites do @moduledoc """ API calls for all endpoints tagged `ViolatingSites`. """ alias GoogleApi.AdExperienceReport.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Lists sites that are failing in the Ad Experience Report on at least one platform. ## Parameters * `connection` (*type:* `GoogleApi.AdExperienceReport.V1.Connection.t`) - Connection to server * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.AdExperienceReport.V1.Model.ViolatingSitesResponse{}}` on success * `{:error, info}` on failure """ @spec adexperiencereport_violating_sites_list(Tesla.Env.client(), keyword(), keyword()) :: {:ok, GoogleApi.AdExperienceReport.V1.Model.ViolatingSitesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def adexperiencereport_violating_sites_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 } request = Request.new() |> Request.method(:get) |> Request.url("/v1/violatingSites", %{}) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.AdExperienceReport.V1.Model.ViolatingSitesResponse{}] ) end end
42.735632
196
0.662453
0387aead03d1a19db6a25668aeda9a97913903fb
592
exs
Elixir
Elixir/kv/mix.exs
kkirstein/proglang-playground
d00be09ba2bb2351c6f5287cc4d93fcaf21f75fd
[ "MIT" ]
null
null
null
Elixir/kv/mix.exs
kkirstein/proglang-playground
d00be09ba2bb2351c6f5287cc4d93fcaf21f75fd
[ "MIT" ]
null
null
null
Elixir/kv/mix.exs
kkirstein/proglang-playground
d00be09ba2bb2351c6f5287cc4d93fcaf21f75fd
[ "MIT" ]
null
null
null
defmodule KV.Mixfile do use Mix.Project def project do [app: :kv, version: "0.0.1", elixir: "~> 1.0", deps: deps] end # Configuration for the OTP application # # Type `mix help compile.app` for more information def application do [applications: [], mod: {KV, []}] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type `mix help deps` for more examples and options defp deps do [] end end
18.5
77
0.584459
0387edce1c76b68df2b4547a1d5a6e8dde908cf8
3,961
ex
Elixir
lib/trademark_free_strategic_land_warfare/piece.ex
alanvoss/trademark_free_strategic_land_warfare
d13030adb1936849c5d363e0f4365f087394e6fa
[ "MIT" ]
1
2020-06-30T16:37:50.000Z
2020-06-30T16:37:50.000Z
lib/trademark_free_strategic_land_warfare/piece.ex
alanvoss/trademark_free_strategic_land_warfare
d13030adb1936849c5d363e0f4365f087394e6fa
[ "MIT" ]
null
null
null
lib/trademark_free_strategic_land_warfare/piece.ex
alanvoss/trademark_free_strategic_land_warfare
d13030adb1936849c5d363e0f4365f087394e6fa
[ "MIT" ]
13
2020-06-04T23:10:19.000Z
2020-06-05T01:25:26.000Z
defmodule TrademarkFreeStrategicLandWarfare.Piece do @derive Jason.Encoder @enforce_keys [:uuid, :player, :visible] defstruct uuid: nil, player: nil, name: nil, visible: nil, rank: nil, lose_when_attacked_by: nil @type t() :: %__MODULE__{ uuid: binary(), player: Integer.t(), name: Atom.t(), visible: boolean(), rank: Integer.t(), lose_when_attacked_by: Atom.t() } @name_properties %{ flag: %{}, bomb: %{lose_when_attacked_by: :miner}, spy: %{rank: 1}, scout: %{rank: 2}, miner: %{rank: 3}, sergeant: %{rank: 4}, lieutenant: %{rank: 5}, captain: %{rank: 6}, major: %{rank: 7}, colonel: %{rank: 8}, general: %{rank: 9}, marshall: %{rank: 10, lose_when_attacked_by: :spy} } @type player_number() :: 1 | 2 @names Map.keys(@name_properties) @spec new(binary(), player_number()) :: RuntimeError | %__MODULE__{uuid: binary(), player: player_number(), visible: boolean()} def new(_, player) when player < 1 or player > 2 do raise "player valid range is 1-2!" end def new(name, _) when name not in @names do raise "piece name must be one of #{inspect(@names)}!" end def new(name, player) when name in @names do properties = Map.merge( %{ uuid: UUID.uuid1(), player: player, name: name, visible: false }, @name_properties[name] ) struct(__MODULE__, properties) end @spec reveal(%__MODULE__{}) :: %__MODULE__{} def reveal(piece) do %__MODULE__{piece | visible: true} end # current player, show piece @spec maybe_mask(%__MODULE__{}, player_number()) :: %__MODULE__{} def maybe_mask(piece = %__MODULE__{player: player}, player) do piece end # opposing player, visible (was previously exposed), show piece def maybe_mask(piece = %__MODULE__{visible: true}, _) do piece end def maybe_mask(piece, _) when piece in [nil, :lake], do: piece # opposing player, not visible, mask piece def maybe_mask(piece, _) do %__MODULE__{ uuid: piece.uuid, player: piece.player, name: nil, visible: piece.visible, rank: nil, lose_when_attacked_by: nil } end @spec attack(%__MODULE__{}, %__MODULE__{}) :: {:ok, :win | [remove: [binary()]]} | {:error, binary() | atom()} def attack(%__MODULE__{name: :flag}, _), do: {:error, "flag can never be the attacker"} def attack(%__MODULE__{name: :bomb}, _), do: {:error, "bomb can never be the attacker"} def attack(_, %__MODULE__{name: :flag}), do: {:ok, :win} def attack( %__MODULE__{name: name}, %__MODULE__{lose_when_attacked_by: name, uuid: uuid} ) when name != nil do {:ok, [remove: [uuid]]} end def attack(%__MODULE__{uuid: uuid}, %__MODULE__{name: :bomb}) do {:ok, [remove: [uuid]]} end def attack( %__MODULE__{rank: rank, uuid: uuid_attacker}, %__MODULE__{rank: rank, uuid: uuid_defender} ) when rank != nil do {:ok, [remove: [uuid_attacker, uuid_defender]]} end def attack( %__MODULE__{rank: attacker_rank} = attacker, %__MODULE__{rank: defender_rank} = defender ) when nil not in [attacker_rank, defender_rank] do if attacker.rank > defender.rank do {:ok, [remove: [defender.uuid]]} else {:ok, [remove: [attacker.uuid]]} end end # at least one is a masked piece, so can't be sure what will happen. # this would never happen for the game engine, but when a player # uses it on their turn, the opponent might have a masked piece, # in which case the rank, name, and what they lose to might be hidden # if the piece has never been attacked before or if it is a scout # and has never moved 2 or more pieces. def attack(_, _), do: {:error, :unknown_result} @spec names() :: list(atom()) def names() do @names end end
28.292857
98
0.611967
038818c72cdc62471353cf23658cdba8a3396047
825
ex
Elixir
patterns/rpc/elixir/client/lib/client.ex
thetonymaster/thetonymaster.github.io
2e24d46dd377fed6ab6d1609e5afe24b4953a0f2
[ "MIT" ]
null
null
null
patterns/rpc/elixir/client/lib/client.ex
thetonymaster/thetonymaster.github.io
2e24d46dd377fed6ab6d1609e5afe24b4953a0f2
[ "MIT" ]
null
null
null
patterns/rpc/elixir/client/lib/client.ex
thetonymaster/thetonymaster.github.io
2e24d46dd377fed6ab6d1609e5afe24b4953a0f2
[ "MIT" ]
null
null
null
require Logger defmodule Client do defstruct name: nil, pid: nil @name :rpcserver def connect do Node.connect(:"rpcserver@tony-M14xR2") end def subscribe(name) do pid = spawn(__MODULE__, :notify, []) send :global.whereis_name(@name), {:subscribe, name, pid} %Client{name: name, pid: pid} end def unsubscribe(%Client{name: name, pid: pid}) do send server, {:unsubscribe, name} send pid, :stop end def fib(%Client{name: name}, item) do send server, {:fib, name, item} end def notify do receive do {:fib, items} -> Logger.info("Job received: '#{IO.inspect(items, char_lists: false)}'") notify :stop -> Logger.info("stopping") _any -> notify end end defp server do :global.whereis_name(@name) end end
18.333333
78
0.610909
03883f969ed8858ba60f6d03bc5b49c23099dd60
1,276
ex
Elixir
test/support/conn_case.ex
rgovaerts/tackle_box_cds_api
332cda4d576c469748677b9952a0d7fdf77d61c2
[ "MIT" ]
null
null
null
test/support/conn_case.ex
rgovaerts/tackle_box_cds_api
332cda4d576c469748677b9952a0d7fdf77d61c2
[ "MIT" ]
null
null
null
test/support/conn_case.ex
rgovaerts/tackle_box_cds_api
332cda4d576c469748677b9952a0d7fdf77d61c2
[ "MIT" ]
null
null
null
defmodule TackleBoxCdsWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use TackleBoxCdsWeb.ConnCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections import Plug.Conn import Phoenix.ConnTest import TackleBoxCdsWeb.ConnCase alias TackleBoxCdsWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint TackleBoxCdsWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(TackleBoxCds.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(TackleBoxCds.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
29
74
0.731975
0388437a88ef6a70b755f792103a6189c03e0830
2,725
exs
Elixir
server/config/releases.exs
dreamer820/realtime
c293c7680b84e19a068787d0d7f8e49ef8c275f8
[ "Apache-2.0" ]
1
2021-05-12T01:17:43.000Z
2021-05-12T01:17:43.000Z
server/config/releases.exs
dreamer820/realtime
c293c7680b84e19a068787d0d7f8e49ef8c275f8
[ "Apache-2.0" ]
9
2021-09-01T19:51:47.000Z
2022-02-16T03:28:23.000Z
server/config/releases.exs
dreamer820/realtime
c293c7680b84e19a068787d0d7f8e49ef8c275f8
[ "Apache-2.0" ]
null
null
null
import Config # These defaults mirror the ones in config.exs, remember not to change one # without changing the other. app_port = String.to_integer(System.get_env("PORT", "4000")) db_host = System.get_env("DB_HOST", "localhost") db_port = String.to_integer(System.get_env("DB_PORT", "5432")) db_name = System.get_env("DB_NAME", "postgres") db_user = System.get_env("DB_USER", "postgres") db_password = System.get_env("DB_PASSWORD", "postgres") # HACK: There's probably a better way to set boolean from env db_ssl = System.get_env("DB_SSL", "true") === "true" publications = System.get_env("PUBLICATIONS", "[\"supabase_realtime\"]") slot_name = System.get_env("SLOT_NAME") || :temporary configuration_file = System.get_env("CONFIGURATION_FILE") # Channels are not secured by default in development and # are secured by default in production. secure_channels = System.get_env("SECURE_CHANNELS", "true") != "false" # Supports HS algorithm octet keys # e.g. "95x0oR8jq9unl9pOIx" jwt_secret = System.get_env("JWT_SECRET", "") # Every JWT's claims will be compared (equality checks) to the expected # claims set in the JSON object. # e.g. # Set JWT_CLAIM_VALIDATORS="{'iss': 'Issuer', 'nbf': 1610078130}" # Then JWT's "iss" value must equal "Issuer" and "nbf" value # must equal 1610078130. jwt_claim_validators = System.get_env("JWT_CLAIM_VALIDATORS", "{}") # The secret key base to built the cookie signing/encryption key. session_secret_key_base = System.get_env( "SESSION_SECRET_KEY_BASE", "Kyvjr42ZvLcY6yzZ7vmRUniE7Bta9tpknEAvpxtaYOa/marmeI1jsqxhIKeu6V51" ) # Connect to database via specified IP version. Options are either "IPv4" or "IPv6". # If IP version is not specified and database host is: # - an IP address, then value ("IPv4"/"IPv6") will be disregarded and Realtime will automatically connect via correct version. # - a name (e.g. "db.abcd.supabase.co"), then Realtime will connect either via IPv4 or IPv6. It is recommended # to specify IP version to prevent potential non-existent domain (NXDOMAIN) errors. db_ip_version = %{"ipv4" => :inet, "ipv6" => :inet6} |> Map.fetch(System.get_env("DB_IP_VERSION", "") |> String.downcase()) config :realtime, app_port: app_port, db_host: db_host, db_port: db_port, db_name: db_name, db_user: db_user, db_password: db_password, db_ssl: db_ssl, db_ip_version: db_ip_version, publications: publications, slot_name: slot_name, configuration_file: configuration_file, secure_channels: secure_channels, jwt_secret: jwt_secret, jwt_claim_validators: jwt_claim_validators config :realtime, RealtimeWeb.Endpoint, http: [:inet6, port: app_port], pubsub_server: Realtime.PubSub, secret_key_base: session_secret_key_base
39.492754
128
0.750092
038849e3b86426d9b3a4c9aadb170cafac886079
2,231
exs
Elixir
project4_part2/config/prod.exs
shubhamagiwal/DOSFall2017
3c1522c4163f57402f147b50614d4051b05a080f
[ "MIT" ]
3
2019-10-28T21:02:55.000Z
2020-10-01T02:29:37.000Z
project4_part2/config/prod.exs
shubhamagiwal/DOSFall2017
3c1522c4163f57402f147b50614d4051b05a080f
[ "MIT" ]
null
null
null
project4_part2/config/prod.exs
shubhamagiwal/DOSFall2017
3c1522c4163f57402f147b50614d4051b05a080f
[ "MIT" ]
4
2019-10-12T19:41:58.000Z
2021-09-24T20:24:47.000Z
use Mix.Config # For production, we often load configuration from external # sources, such as your system environment. For this reason, # you won't find the :http configuration below, but set inside # Project4Part2Web.Endpoint.init/2 when load_from_system_env is # true. Any dynamic configuration should be done there. # # Don't forget to configure the url host to something meaningful, # Phoenix uses this information when generating URLs. # # Finally, we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the mix phx.digest task # which you typically run after static files are built. config :project4_part2, Project4Part2Web.Endpoint, load_from_system_env: true, url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :project4_part2, Project4Part2Web.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [:inet6, # port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :project4_part2, Project4Part2Web.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :project4_part2, Project4Part2Web.Endpoint, server: true # # Finally import the config/prod.secret.exs # which should be versioned separately. import_config "prod.secret.exs"
34.323077
69
0.728821
03884b62ab0d50d4bbc35925d15fbc7e4729d667
1,574
ex
Elixir
apps/status/lib/status/release_tasks/sentry.ex
omgnetwork/omg-childchain-v2
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
[ "Apache-2.0" ]
4
2020-11-30T17:38:57.000Z
2021-01-23T21:29:41.000Z
apps/status/lib/status/release_tasks/sentry.ex
omgnetwork/omg-childchain-v2
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
[ "Apache-2.0" ]
24
2020-11-30T17:32:48.000Z
2021-02-22T06:25:22.000Z
apps/status/lib/status/release_tasks/sentry.ex
omgnetwork/omg-childchain-v2
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
[ "Apache-2.0" ]
null
null
null
defmodule Status.ReleaseTasks.Sentry do @moduledoc false @behaviour Config.Provider alias Status.ReleaseTasks.Validators require Logger def init(args) do args end # remember, release tasks run AFTER release.exs gets evaluated. def load(config, args) do _ = on_load(args) current_version = Keyword.fetch!(args, :current_version) sentry_dsn = "SENTRY_DSN" |> get_env() |> Validators.url() hostname = "HOSTNAME" |> get_env() |> Validators.url() included_environments = config |> Keyword.fetch!(:sentry) |> Keyword.fetch!(:included_environments) app_env = "APP_ENV" |> get_env() |> Validators.app_env(included_environments) _ = case {is_binary(sentry_dsn), is_binary(app_env), is_binary(hostname)} do {true, true, true} -> :ok _ -> log = "If you want Sentry enabled set " <> "SENTRY_DSN, HOSTNAME and APP_ENV #{inspect(included_environments)}." Logger.warn(log) end tags = config |> Keyword.fetch!(:sentry) |> Keyword.fetch!(:tags) |> Map.merge(%{current_version: "vsn-#{current_version}"}) Config.Reader.merge(config, sentry: [tags: tags]) end @spec get_env(String.t()) :: String.t() defp get_env(key) do system_adapter().get_env(key) end defp system_adapter() do Process.get(:system_adapter) end defp on_load(args) do adapter = Keyword.get(args, :system_adapter, System) _ = Process.put(:system_adapter, adapter) _ = Application.ensure_all_started(:logger) end end
27.137931
103
0.651207
03886f60f761776abca7da00def7af3e5c89ec61
15,154
ex
Elixir
lib/elixir/lib/agent.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
1
2021-04-28T21:35:01.000Z
2021-04-28T21:35:01.000Z
lib/elixir/lib/agent.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/agent.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
1
2021-09-30T01:21:02.000Z
2021-09-30T01:21:02.000Z
defmodule Agent do @moduledoc """ Agents are a simple abstraction around state. Often in Elixir there is a need to share or store state that must be accessed from different processes or by the same process at different points in time. The `Agent` module provides a basic server implementation that allows state to be retrieved and updated via a simple API. ## Examples For example, in the Mix tool that ships with Elixir, we need to keep a set of all tasks executed by a given project. Since this set is shared, we can implement it with an agent: defmodule Mix.TasksServer do use Agent def start_link(_) do Agent.start_link(fn -> MapSet.new end, name: __MODULE__) end @doc "Checks if the task has already executed" def executed?(task, project) do item = {task, project} Agent.get(__MODULE__, fn set -> item in set end) end @doc "Marks a task as executed" def put_task(task, project) do item = {task, project} Agent.update(__MODULE__, &MapSet.put(&1, item)) end @doc "Resets the executed tasks and returns the previous list of tasks" def take_all() do Agent.get_and_update(__MODULE__, fn set -> {Enum.into(set, []), MapSet.new} end) end end Agents provide a segregation between the client and server APIs (similar to GenServers). In particular, the anonymous functions given to the `Agent` are executed inside the agent (the server). This distinction is important because you may want to avoid expensive operations inside the agent, as they will effectively block the agent until the request is fulfilled. Consider these two examples: # Compute in the agent/server def get_something(agent) do Agent.get(agent, fn state -> do_something_expensive(state) end) end # Compute in the agent/client def get_something(agent) do Agent.get(agent, &(&1)) |> do_something_expensive() end The first function blocks the agent. The second function copies all the state to the client and then executes the operation in the client. One aspect to consider is whether the data is large enough to require processing in the server, at least initially, or small enough to be sent to the client cheaply. Another factor is whether the data needs to be processed atomically: getting the state and calling `do_something_expensive(state)` outside of the agent means that the agent's state can be updated in the meantime. This is specially important in case of updates as computing the new state in the client rather than in the server can lead to race conditions if multiple clients are trying to update the same state to different values. Finally note `use Agent` defines a `child_spec/1` function, allowing the defined module to be put under a supervision tree. The generated `child_spec/1` can be customized with the following options: * `:id` - the child specification id, defaults to the current module * `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`) * `:restart` - when the child should be restarted, defaults to `:permanent` * `:shutdown` - how to shut down the child For example: use Agent, restart: :transient, shutdown: 10_000 See the `Supervisor` docs for more information. ## Name registration An agent is bound to the same name registration rules as GenServers. Read more about it in the `GenServer` documentation. ## A word on distributed agents It is important to consider the limitations of distributed agents. Agents provide two APIs, one that works with anonymous functions and another that expects an explicit module, function, and arguments. In a distributed setup with multiple nodes, the API that accepts anonymous functions only works if the caller (client) and the agent have the same version of the caller module. Keep in mind this issue also shows up when performing "rolling upgrades" with agents. By rolling upgrades we mean the following situation: you wish to deploy a new version of your software by *shutting down* some of your nodes and replacing them with nodes running a new version of the software. In this setup, part of your environment will have one version of a given module and the other part another version (the newer one) of the same module. The best solution is to simply use the explicit module, function, and arguments APIs when working with distributed agents. ## Hot code swapping An agent can have its code hot swapped live by simply passing a module, function, and arguments tuple to the update instruction. For example, imagine you have an agent named `:sample` and you want to convert its inner state from a keyword list to a map. It can be done with the following instruction: {:update, :sample, {:advanced, {Enum, :into, [%{}]}}} The agent's state will be added to the given list of arguments (`[%{}]`) as the first argument. """ @typedoc "Return values of `start*` functions" @type on_start :: {:ok, pid} | {:error, {:already_started, pid} | term} @typedoc "The agent name" @type name :: atom | {:global, term} | {:via, module, term} @typedoc "The agent reference" @type agent :: pid | {atom, node} | name @typedoc "The agent state" @type state :: term @doc """ Returns a specification to start an agent under a supervisor. See `Supervisor`. """ @since "1.5.0" def child_spec(arg) do %{ id: Agent, start: {Agent, :start_link, [arg]} } end @doc false defmacro __using__(opts) do quote location: :keep, bind_quoted: [opts: opts] do @doc """ Returns a specification to start this module under a supervisor. See `Supervisor`. """ def child_spec(arg) do default = %{ id: __MODULE__, start: {__MODULE__, :start_link, [arg]} } Supervisor.child_spec(default, unquote(Macro.escape(opts))) end defoverridable child_spec: 1 end end @doc """ Starts an agent linked to the current process with the given function. This is often used to start the agent as part of a supervision tree. Once the agent is spawned, the given function `fun` is invoked and its return value is used as the agent state. Note that `start_link/2` does not return until the given function has returned. ## Options The `:name` option is used for registration as described in the module documentation. If the `:timeout` option is present, the agent is allowed to spend at most the given number of milliseconds on initialization or it will be terminated and the start function will return `{:error, :timeout}`. If the `:debug` option is present, the corresponding function in the [`:sys` module](http://www.erlang.org/doc/man/sys.html) will be invoked. If the `:spawn_opt` option is present, its value will be passed as options to the underlying process as in `Process.spawn/4`. ## Return values If the server is successfully created and initialized, the function returns `{:ok, pid}`, where `pid` is the PID of the server. If an agent with the specified name already exists, the function returns `{:error, {:already_started, pid}}` with the PID of that process. If the given function callback fails, the function returns `{:error, reason}`. ## Examples iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 iex> {:error, {exception, _stacktrace}} = Agent.start(fn -> raise "oops" end) iex> exception %RuntimeError{message: "oops"} """ @spec start_link((() -> term), GenServer.options()) :: on_start def start_link(fun, options \\ []) when is_function(fun, 0) do GenServer.start_link(Agent.Server, fun, options) end @doc """ Starts an agent linked to the current process. Same as `start_link/2` but a module, function, and arguments are expected instead of an anonymous function; `fun` in `module` will be called with the given arguments `args` to initialize the state. """ @spec start_link(module, atom, [any], GenServer.options()) :: on_start def start_link(module, fun, args, options \\ []) do GenServer.start_link(Agent.Server, {module, fun, args}, options) end @doc """ Starts an agent process without links (outside of a supervision tree). See `start_link/2` for more information. ## Examples iex> {:ok, pid} = Agent.start(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 """ @spec start((() -> term), GenServer.options()) :: on_start def start(fun, options \\ []) when is_function(fun, 0) do GenServer.start(Agent.Server, fun, options) end @doc """ Starts an agent without links with the given module, function, and arguments. See `start_link/4` for more information. """ @spec start(module, atom, [any], GenServer.options()) :: on_start def start(module, fun, args, options \\ []) do GenServer.start(Agent.Server, {module, fun, args}, options) end @doc """ Gets an agent value via the given anonymous function. The function `fun` is sent to the `agent` which invokes the function passing the agent state. The result of the function invocation is returned from this function. `timeout` is an integer greater than zero which specifies how many milliseconds are allowed before the agent executes the function and returns the result value, or the atom `:infinity` to wait indefinitely. If no result is received within the specified time, the function call fails and the caller exits. ## Examples iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 """ @spec get(agent, (state -> a), timeout) :: a when a: var def get(agent, fun, timeout \\ 5000) when is_function(fun, 1) do GenServer.call(agent, {:get, fun}, timeout) end @doc """ Gets an agent value via the given function. Same as `get/3` but a module, function, and arguments are expected instead of an anonymous function. The state is added as first argument to the given list of arguments. """ @spec get(agent, module, atom, [term], timeout) :: any def get(agent, module, fun, args, timeout \\ 5000) do GenServer.call(agent, {:get, {module, fun, args}}, timeout) end @doc """ Gets and updates the agent state in one operation via the given anonymous function. The function `fun` is sent to the `agent` which invokes the function passing the agent state. The function must return a tuple with two elements, the first being the value to return (that is, the "get" value) and the second one being the new state of the agent. `timeout` is an integer greater than zero which specifies how many milliseconds are allowed before the agent executes the function and returns the result value, or the atom `:infinity` to wait indefinitely. If no result is received within the specified time, the function call fails and the caller exits. ## Examples iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.get_and_update(pid, fn state -> {state, state + 1} end) 42 iex> Agent.get(pid, fn state -> state end) 43 """ @spec get_and_update(agent, (state -> {a, state}), timeout) :: a when a: var def get_and_update(agent, fun, timeout \\ 5000) when is_function(fun, 1) do GenServer.call(agent, {:get_and_update, fun}, timeout) end @doc """ Gets and updates the agent state in one operation via the given function. Same as `get_and_update/3` but a module, function, and arguments are expected instead of an anonymous function. The state is added as first argument to the given list of arguments. """ @spec get_and_update(agent, module, atom, [term], timeout) :: any def get_and_update(agent, module, fun, args, timeout \\ 5000) do GenServer.call(agent, {:get_and_update, {module, fun, args}}, timeout) end @doc """ Updates the agent state via the given anonymous function. The function `fun` is sent to the `agent` which invokes the function passing the agent state. The return value of `fun` becomes the new state of the agent. This function always returns `:ok`. `timeout` is an integer greater than zero which specifies how many milliseconds are allowed before the agent executes the function and returns the result value, or the atom `:infinity` to wait indefinitely. If no result is received within the specified time, the function call fails and the caller exits. ## Examples iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.update(pid, fn state -> state + 1 end) :ok iex> Agent.get(pid, fn state -> state end) 43 """ @spec update(agent, (state -> state), timeout) :: :ok def update(agent, fun, timeout \\ 5000) when is_function(fun, 1) do GenServer.call(agent, {:update, fun}, timeout) end @doc """ Updates the agent state via the given function. Same as `update/3` but a module, function, and arguments are expected instead of an anonymous function. The state is added as first argument to the given list of arguments. """ @spec update(agent, module, atom, [term], timeout) :: :ok def update(agent, module, fun, args, timeout \\ 5000) do GenServer.call(agent, {:update, {module, fun, args}}, timeout) end @doc """ Performs a cast (*fire and forget*) operation on the agent state. The function `fun` is sent to the `agent` which invokes the function passing the agent state. The return value of `fun` becomes the new state of the agent. Note that `cast` returns `:ok` immediately, regardless of whether `agent` (or the node it should live on) exists. """ @spec cast(agent, (state -> state)) :: :ok def cast(agent, fun) when is_function(fun, 1) do GenServer.cast(agent, {:cast, fun}) end @doc """ Performs a cast (*fire and forget*) operation on the agent state. Same as `cast/2` but a module, function, and arguments are expected instead of an anonymous function. The state is added as first argument to the given list of arguments. """ @spec cast(agent, module, atom, [term]) :: :ok def cast(agent, module, fun, args) do GenServer.cast(agent, {:cast, {module, fun, args}}) end @doc """ Synchronously stops the agent with the given `reason`. It returns `:ok` if the agent terminates with the given reason. If the agent terminates with another reason, the call will exit. This function keeps OTP semantics regarding error reporting. If the reason is any other than `:normal`, `:shutdown` or `{:shutdown, _}`, an error report will be logged. ## Examples iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.stop(pid) :ok """ @spec stop(agent, reason :: term, timeout) :: :ok def stop(agent, reason \\ :normal, timeout \\ :infinity) do GenServer.stop(agent, reason, timeout) end end
34.997691
95
0.691963
03888f45c986d57aa7999ffd34f260b1935e42c9
728
ex
Elixir
elixir/elixir-sips/samples/twitter_playground/lib/twitter_playground.ex
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
2
2015-12-09T02:16:51.000Z
2021-07-26T22:53:43.000Z
elixir/elixir-sips/samples/twitter_playground/lib/twitter_playground.ex
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
null
null
null
elixir/elixir-sips/samples/twitter_playground/lib/twitter_playground.ex
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
1
2016-05-08T18:40:31.000Z
2016-05-08T18:40:31.000Z
defmodule TwitterPlayground do use Application def start(_type, _args) do import Supervisor.Spec, warn: false ExTwitter.configure( consumer_key: System.get_env("TWITTER_CONSUMER_KEY"), consumer_secret: System.get_env("TWITTER_CONSUMER_SECRET"), access_token: System.get_env("TWITTER_ACCESS_TOKEN"), access_token_secret: System.get_env("TWITTER_ACCESS_SECRET") ) children = [ supervisor(TwitterPlayground.Endpoint, []), ] opts = [strategy: :one_for_one, name: TwitterPlayground.Supervisor] Supervisor.start_link(children, opts) end def config_change(changed, _new, removed) do TwitterPlayground.Endpoint.config_change(changed, removed) :ok end end
26.962963
71
0.729396
03889e9a9934f91527b39237167322ca8443d69b
249
ex
Elixir
lib/photog.ex
allen-garvey/photog-react
c400174d0e456dcbfd565407eb85e8ce80ec59c0
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
lib/photog.ex
allen-garvey/photog-react
c400174d0e456dcbfd565407eb85e8ce80ec59c0
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
apps/photog/lib/photog.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
null
null
null
defmodule Photog do @moduledoc """ Photog keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
24.9
66
0.751004
0388a811e1d6a9ea4affc0d38a7f1dc4dfd570c7
463
ex
Elixir
lib/signalrex/ws_client.ex
mendrugory/signalrex
2b198a856afd45bb1798b9b7491742c6ecdc9e44
[ "MIT" ]
9
2017-12-11T17:55:19.000Z
2021-11-22T23:21:00.000Z
lib/signalrex/ws_client.ex
mendrugory/signalrex
2b198a856afd45bb1798b9b7491742c6ecdc9e44
[ "MIT" ]
3
2018-01-10T14:42:41.000Z
2019-11-10T05:23:53.000Z
lib/signalrex/ws_client.ex
mendrugory/signalrex
2b198a856afd45bb1798b9b7491742c6ecdc9e44
[ "MIT" ]
5
2018-01-09T18:14:39.000Z
2021-10-01T21:51:36.000Z
defmodule Signalrex.WSClient do @moduledoc false use Enchufeweb require Logger def handle_message(data, state) do pid = Keyword.get(state, :ws_opts).client send(pid, {:signalr_message, data}) {:ok, state} end def handle_connection(_, state) do init_message = Map.get(Keyword.get(state, :ws_opts), :init_message, " ") {:reply, init_message, state} end def handle_disconnection(_, state), do: {:close, "end", state} end
24.368421
76
0.680346
0388c74ebef999b31eb509701af81db73a01d7fa
60
ex
Elixir
web/views/tee_view.ex
mfunaro/handiman-phoenix
5d94114f37561647096f1695e3f0a3a3d1c7ca34
[ "MIT", "Unlicense" ]
1
2015-08-15T02:40:27.000Z
2015-08-15T02:40:27.000Z
web/views/tee_view.ex
mfunaro/handiman-phoenix
5d94114f37561647096f1695e3f0a3a3d1c7ca34
[ "MIT", "Unlicense" ]
1
2015-09-11T00:02:33.000Z
2015-09-11T03:24:21.000Z
web/views/tee_view.ex
mfunaro/handiman-phoenix
5d94114f37561647096f1695e3f0a3a3d1c7ca34
[ "MIT", "Unlicense" ]
null
null
null
defmodule Handiman.TeeView do use Handiman.Web, :view end
15
29
0.783333
0388da7d2d57a3e92872c77917353411a4ea7c93
1,754
exs
Elixir
test/skeleton/controller_test.exs
skeleton-elixir/skeleton_phoenix
6b2e38226290c1e2857a8399044f725673ea3707
[ "MIT" ]
null
null
null
test/skeleton/controller_test.exs
skeleton-elixir/skeleton_phoenix
6b2e38226290c1e2857a8399044f725673ea3707
[ "MIT" ]
4
2020-07-02T13:17:36.000Z
2021-02-26T13:37:42.000Z
test/skeleton/controller_test.exs
skeleton-elixir/skeleton_phoenix
6b2e38226290c1e2857a8399044f725673ea3707
[ "MIT" ]
1
2021-04-27T17:44:49.000Z
2021-04-27T17:44:49.000Z
defmodule Skeleton.Phoenix.ControllerTest do use Skeleton.App.TestCase import Plug.Conn alias Plug.Conn alias Skeleton.AppWeb.UserController alias Skeleton.App.User setup context do conn = %Conn{} Map.put(context, :conn, conn) end describe "ensure the user is authenticated" do test "when isn't authenticated", context do conn = UserController.update(context.conn) assert conn.halted assert conn.status == 403 end test "when is authenticated", context do user = %User{id: 1} conn = context.conn |> put_private(:current_user, user) |> assign(:user, user) |> UserController.update() refute conn.halted refute conn.status end end describe "ensure the user is not authenticated" do test "when isn't authenticated", context do conn = UserController.unauthenticated_update(context.conn) refute conn.halted refute conn.status end test "when is authenticated", context do user = %User{id: 1} conn = context.conn |> put_private(:current_user, user) |> assign(:user, user) |> UserController.unauthenticated_update() assert conn.halted assert conn.status == 401 end end describe "resoving controller" do test "when it's valid", context do user = %User{id: 1} conn = context.conn |> put_private(:current_user, user) |> assign(:user, user) |> UserController.update() refute conn.halted refute conn.status end test "when it's not valid", context do conn = UserController.update(context.conn) assert conn.halted assert conn.status == 403 end end end
22.487179
64
0.632269
038932f305bc43cc999012806b17eec5395f3855
1,269
ex
Elixir
lib/milbase_web/schema/user_type.ex
suryakun/milbase-skeleton
1483142bd9ef70a9cf07504c8f03314f2cb7b7d0
[ "Apache-2.0" ]
1
2020-07-14T03:27:30.000Z
2020-07-14T03:27:30.000Z
lib/milbase_web/schema/user_type.ex
suryakun/milbase-skeleton
1483142bd9ef70a9cf07504c8f03314f2cb7b7d0
[ "Apache-2.0" ]
null
null
null
lib/milbase_web/schema/user_type.ex
suryakun/milbase-skeleton
1483142bd9ef70a9cf07504c8f03314f2cb7b7d0
[ "Apache-2.0" ]
null
null
null
defmodule MilbaseWeb.Schema.Types.UserType do use Absinthe.Schema.Notation #alias Milbase.Content.Post object :user_type, description: "Entity of someone" do field :id, :id, description: "ID" field :name, :string, description: "Name" field :first_name, :string, description: "Required first name" field :last_name, :string, description: "optional last name" field :email, :string, description: "Required email" field :role, :string, description: "Role" field :inserted_at, :string, description: "Inserted at" # Uncomment this if you want to populate the posts without pagination #field :posts, list_of(:post_type), resolve: assoc(:posts) # # # # Uncomment this below code if you want to populate the posts with pagination #connection field :posts, node_type: :post_con do # resolve fn # pagination_args, _source -> # Post # |> Absinthe.Relay.Connection.from_query(&Milbase.Repo.all/1, pagination_args) # end #end end input_object :user_input_type do field :first_name, non_null(:string) field :last_name, :string field :email, non_null(:string) field :password, non_null(:string) field :password_confirmation, non_null(:string) end end
32.538462
88
0.690307
038956f851841018eee0ba79fd408aa375767f8f
2,544
ex
Elixir
lib/calcy/evaluator.ex
oransimhony/calcy
aba449080b1c8eaa238a73e2d5fba5f9badafca1
[ "MIT" ]
1
2019-03-23T16:22:17.000Z
2019-03-23T16:22:17.000Z
lib/calcy/evaluator.ex
oransimhony/calcy
aba449080b1c8eaa238a73e2d5fba5f9badafca1
[ "MIT" ]
null
null
null
lib/calcy/evaluator.ex
oransimhony/calcy
aba449080b1c8eaa238a73e2d5fba5f9badafca1
[ "MIT" ]
null
null
null
defmodule Calcy.Evaluator do @moduledoc """ Documentation for the Evaluator. """ import IO.ANSI @doc """ Returns the value of a addition operation between the left and right hand sides """ def eval(env, {:plus, right, left}) do eval(env, right) + eval(env, left) end @doc """ Returns the value of a subtraction operation between the left and right hand sides """ def eval(env, {:minus, right, left}) do eval(env, right) - eval(env, left) end @doc """ Returns the value of a multiplication operation between the left and right hand sides """ def eval(env, {:mult, right, left}) do eval(env, right) * eval(env, left) end @doc """ Returns the value of a division operation between the left and right hand sides """ def eval(env, {:divi, right, left}) do case eval(env, left) do 0 -> "Cannot divide by zero" val -> eval(env, right) / val end end @doc """ Returns the value of a power operation between the left and right hand sides """ def eval(env, {:pow, right, left}) do :math.pow(eval(env, right), eval(env, left)) end @doc """ Returns the value of the integer """ def eval(_env, {:int, int}) do int end @doc """ Returns the value of the float """ def eval(_env, {:float, float}) do float end @doc """ Returns the value of the identifier """ def eval(env, {:ident, name}) do lookup(name, env) end @doc """ Assigns the value of expr to name and saves it in the environment """ def eval(env, {:assign, name, expr}) do val = eval(env, expr) IO.inspect name if name == :pi, do: raise "Cannot change pi" if name == :e, do: raise "Cannot change e" {Map.put(env, name, val), val} end @doc """ Prints the environment """ def eval(env, {:stack}) do Enum.each env, fn {k, v} -> IO.puts blue() <> "#{k}: " <> reset() <> "\t#{v}" end nil end @doc """ Returns an exit atom if the current node is exit """ def eval(_env, {:exit}) do :exit end @doc """ Looks up the variable in the environment Throws an error if the variable is not defined """ def lookup(name, env) do case Map.get(env, name) do nil -> raise "#{name} has not been declared" val -> val end end end
24
89
0.549135
03895d2f22fca9967c1ab13296ce76a8ff7512f8
368
ex
Elixir
web/models/nearby.ex
bolecki/volition
f92cdd45fcc66a2552d1f5f35968b088dbc2e53f
[ "MIT" ]
null
null
null
web/models/nearby.ex
bolecki/volition
f92cdd45fcc66a2552d1f5f35968b088dbc2e53f
[ "MIT" ]
null
null
null
web/models/nearby.ex
bolecki/volition
f92cdd45fcc66a2552d1f5f35968b088dbc2e53f
[ "MIT" ]
null
null
null
defmodule Volition.Nearby do use Volition.Web, :model schema "nearbys" do belongs_to :area, Volition.Area belongs_to :nearby, Volition.Area timestamps() end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, []) |> validate_required([]) end end
18.4
56
0.638587
03897d9ce06822398ef196a641cbbeac5e45af1e
2,246
ex
Elixir
lib/search.ex
ahd-elang/braintree-elixir
c18d37eaff2df8a6d62cc05677b8a03c1d23ad90
[ "MIT" ]
108
2016-02-03T12:45:03.000Z
2022-02-19T16:56:36.000Z
lib/search.ex
ahd-elang/braintree-elixir
c18d37eaff2df8a6d62cc05677b8a03c1d23ad90
[ "MIT" ]
77
2016-02-12T15:52:53.000Z
2022-02-21T14:38:08.000Z
lib/search.ex
ahd-elang/braintree-elixir
c18d37eaff2df8a6d62cc05677b8a03c1d23ad90
[ "MIT" ]
64
2016-04-04T07:07:24.000Z
2022-03-24T05:42:05.000Z
defmodule Braintree.Search do @moduledoc """ This module performs advanced search on a resource. For additional reference see: https://developers.braintreepayments.com/reference/general/searching/search-fields/ruby """ alias Braintree.ErrorResponse, as: Error alias Braintree.HTTP @doc """ Perform an advanced search on a given resource and create new structs based on the initializer given. ## Example search_params = %{first_name: %{is: "Jenna"}} {:ok, customers} = Braintree.Search.perform(search_params, "customers", &Braintree.Customer.new/1) """ @spec perform(map, String.t(), fun(), Keyword.t()) :: {:ok, [any]} | {:error, Error.t()} def perform(params, resource, initializer, opts \\ []) when is_map(params) do with {:ok, payload} <- HTTP.post(resource <> "/advanced_search_ids", %{search: params}, opts) do fetch_all_records(payload, resource, initializer, opts) end end defp fetch_all_records(%{"search_results" => %{"ids" => []}}, _resource, _initializer, _opts) do {:error, :not_found} end defp fetch_all_records( %{"search_results" => %{"page_size" => page_size, "ids" => ids}}, resource, initializer, opts ) do records = ids |> Enum.chunk_every(page_size) |> Enum.flat_map(fn ids_chunk -> fetch_records_chunk(ids_chunk, resource, initializer, opts) end) {:ok, records} end # Credit card verifications and transactions are an odd case because path to endpoints is # different from the object name in the XML. defp fetch_records_chunk(ids, resource, initializer, opts) when is_list(ids) and resource in ~w(verifications transactions) do search_params = %{search: %{ids: ids}} key_name = "credit_card_#{resource}" with {:ok, %{^key_name => data}} <- HTTP.post(resource <> "/advanced_search", search_params, opts) do initializer.(data) end end defp fetch_records_chunk(ids, resource, initializer, opts) when is_list(ids) do search_params = %{search: %{ids: ids}} with {:ok, %{^resource => data}} <- HTTP.post(resource <> "/advanced_search", search_params, opts) do initializer.(data) end end end
32.085714
102
0.659394
038989275dab173808a7c28f3788a2abd4fa40a9
1,206
ex
Elixir
apps/get_functional_tree/lib/get_functional_tree_account.ex
taylonr/get_functional_elixir
a519eb3689749883e3fe5dd59a17253571c5fd33
[ "MIT" ]
4
2017-04-16T21:07:36.000Z
2021-07-21T10:27:10.000Z
apps/get_functional_tree/lib/get_functional_tree_account.ex
taylonr/get_functional_elixir
a519eb3689749883e3fe5dd59a17253571c5fd33
[ "MIT" ]
null
null
null
apps/get_functional_tree/lib/get_functional_tree_account.ex
taylonr/get_functional_elixir
a519eb3689749883e3fe5dd59a17253571c5fd33
[ "MIT" ]
null
null
null
defmodule GetFunctionalTree.Account do use GenServer def start_link(stash_pid) do {:ok, _pid} = GenServer.start_link(__MODULE__, stash_pid, name: :account) end def credit(amount) do GenServer.call(:account, {:credit, amount}) end def debit(amount) do GenServer.call(:account, {:debit, amount}) end def balance() do GenServer.call(:account, :balance) end def crash do GenServer.cast(:account, {:crash}) end def get_pid do Process.whereis(:account) end def init(stash_pid) do balance = GetFunctionalTree.Stash.get_value(stash_pid) {:ok, {balance, stash_pid}} end def handle_call({:credit, amount}, _from, {state, stash_pid}) do {:reply, state + amount, {state + amount, stash_pid}} end def handle_call({:debit, amount}, _from, {state, stash_pid}) do {:noreply, state - amount, {state - amount, stash_pid}} end def handle_call(:balance, _from, state) do {:reply, elem(state, 0), state} end def terminate(_reason, {balance, stash_pid}) do GetFunctionalTree.Stash.save_value(stash_pid, balance) end def handle_cast({:crash}, _state) do Process.whereis(:account) |> Process.exit(:kill) end end
22.333333
77
0.679104
0389b5e1427f343c5c819741b7e2bd33f0fceb12
21,506
ex
Elixir
lib/money/currency.ex
wingyplus/money
18d8eb3581886badb9b89adf455844517c10f599
[ "MIT" ]
null
null
null
lib/money/currency.ex
wingyplus/money
18d8eb3581886badb9b89adf455844517c10f599
[ "MIT" ]
null
null
null
lib/money/currency.ex
wingyplus/money
18d8eb3581886badb9b89adf455844517c10f599
[ "MIT" ]
null
null
null
defmodule Money.Currency do @moduledoc """ Provides currency support to `Money` Some useful helper methods include: - `get/1` - `get!/1` - `exists?/1` - `to_atom/1` - `name/1` - `name!/1` - `symbol/1` - `symbol!/1` - `all/0` A helper function exists for each currency using the lowercase three-character currency code ## Example: iex> Money.Currency.usd(100) %Money{amount: 100, currency: :USD} """ defp custom_currencies do Enum.into(Application.get_env(:money, :custom_currencies, []), %{}) end @currencies %{ AED: %{name: "UAE Dirham", symbol: "د.إ", exponent: 2, number: 784}, AFN: %{name: "Afghani", symbol: "؋", exponent: 2, number: 971}, ALL: %{name: "Lek", symbol: "Lek", exponent: 2, number: 008}, AMD: %{name: "Armenian Dram", symbol: "AMD", exponent: 2, number: 051}, ANG: %{name: "Netherlands Antillian Guilder", symbol: "ƒ", exponent: 2, number: 532}, AOA: %{name: "Kwanza", symbol: "Kz", exponent: 2, number: 973}, ARS: %{name: "Argentine Peso", symbol: "$", exponent: 2, number: 032}, AUD: %{name: "Australian Dollar", symbol: "$", exponent: 2, number: 036}, AWG: %{name: "Aruban Guilder", symbol: "ƒ", exponent: 2, number: 533}, AZN: %{name: "Azerbaijanian Manat", symbol: "ман", exponent: 2, number: 944}, BAM: %{name: "Convertible Marks", symbol: "KM", exponent: 2, number: 977}, BBD: %{name: "Barbados Dollar", symbol: "$", exponent: 2, number: 052}, BDT: %{name: "Taka", symbol: "৳", exponent: 2, number: 050}, BGN: %{name: "Bulgarian Lev", symbol: "лв", exponent: 2, number: 975}, BHD: %{name: "Bahraini Dinar", symbol: ".د.ب", exponent: 3, number: 048}, BIF: %{name: "Burundi Franc", symbol: "FBu", exponent: 0, number: 108}, BMD: %{name: "Bermudian Dollar (customarily known as Bermuda Dollar)", symbol: "$", exponent: 2, number: 060}, BND: %{name: "Brunei Dollar", symbol: "$", exponent: 2, number: 096}, BOB: %{name: "Boliviano Mvdol", symbol: "$b", exponent: 2, number: 068}, BOV: %{name: "Boliviano Mvdol", symbol: "$b", exponent: 2, number: 984}, BRL: %{name: "Brazilian Real", symbol: "R$", exponent: 2, number: 986}, BSD: %{name: "Bahamian Dollar", symbol: "$", exponent: 2, number: 044}, BTN: %{name: "Indian Rupee Ngultrum", symbol: "Nu.", exponent: 2, number: 064}, BWP: %{name: "Pula", symbol: "P", exponent: 2, number: 072}, BYN: %{name: "Belarusian Ruble", symbol: "p.", exponent: 2, number: 933}, BYR: %{name: "Belarusian Ruble", symbol: "p.", exponent: 0, number: 933}, BZD: %{name: "Belize Dollar", symbol: "BZ$", exponent: 2, number: 084}, CAD: %{name: "Canadian Dollar", symbol: "$", exponent: 2, number: 124}, CDF: %{name: "Congolese Franc", symbol: "CF", exponent: 2, number: 976}, CHF: %{name: "Swiss Franc", symbol: "CHF", exponent: 2, number: 756}, CLF: %{name: "Chilean Peso Unidades de fomento", symbol: "$", exponent: 4, number: 990}, CLP: %{name: "Chilean Peso Unidades de fomento", symbol: "$", exponent: 0, number: 152}, CNY: %{name: "Yuan Renminbi", symbol: "¥", exponent: 2, number: 156}, COP: %{name: "Colombian Peso", symbol: "$", exponent: 2, number: 170}, COU: %{name: "Colombian Peso Unidad de Valor Real", symbol: "$", exponent: 2, number: 970}, CRC: %{name: "Costa Rican Colon", symbol: "₡", exponent: 2, number: 188}, CUC: %{name: "Cuban Peso Peso Convertible", symbol: "₱", exponent: 2, number: 931}, CUP: %{name: "Cuban Peso Peso Convertible", symbol: "₱", exponent: 2, number: 192}, CVE: %{name: "Cape Verde Escudo", symbol: "$", exponent: 0, number: 132}, CZK: %{name: "Czech Koruna", symbol: "Kč", exponent: 2, number: 203}, DJF: %{name: "Djibouti Franc", symbol: "Fdj", exponent: 0, number: 262}, DKK: %{name: "Danish Krone", symbol: "kr.", exponent: 2, number: 208}, DOP: %{name: "Dominican Peso", symbol: "RD$", exponent: 2, number: 214}, DZD: %{name: "Algerian Dinar", symbol: "دج", exponent: 2, number: 012}, EEK: %{name: "Kroon", symbol: "KR", exponent: 2, number: 233}, EGP: %{name: "Egyptian Pound", symbol: "£", exponent: 2, number: 818}, ERN: %{name: "Nakfa", symbol: "Nfk", exponent: 2, number: 232}, ETB: %{name: "Ethiopian Birr", symbol: "Br", exponent: 2, number: 230}, EUR: %{name: "Euro", symbol: "€", exponent: 2, number: 978}, FJD: %{name: "Fiji Dollar", symbol: "$", exponent: 2, number: 242}, FKP: %{name: "Falkland Islands Pound", symbol: "£", exponent: 2, number: 238}, GBP: %{name: "Pound Sterling", symbol: "£", exponent: 2, number: 826}, GEL: %{name: "Lari", symbol: "₾", exponent: 2, number: 981}, GHS: %{name: "Cedi", symbol: "GH₵", exponent: 2, number: 936}, GIP: %{name: "Gibraltar Pound", symbol: "£", exponent: 2, number: 292}, GMD: %{name: "Dalasi", symbol: "D", exponent: 2, number: 270}, GNF: %{name: "Guinea Franc", symbol: "FG", exponent: 0, number: 324}, GTQ: %{name: "Quetzal", symbol: "Q", exponent: 2, number: 320}, GYD: %{name: "Guyana Dollar", symbol: "$", exponent: 2, number: 328}, HKD: %{name: "Hong Kong Dollar", symbol: "$", exponent: 2, number: 344}, HNL: %{name: "Lempira", symbol: "L", exponent: 2, number: 340}, HRK: %{name: "Croatian Kuna", symbol: "kn", exponent: 2, number: 191}, HTG: %{name: "Gourde US Dollar", symbol: " ", exponent: 2, number: 332}, HUF: %{name: "Forint", symbol: "Ft", exponent: 2, number: 348}, IDR: %{name: "Rupiah", symbol: "Rp", exponent: 2, number: 360}, ILS: %{name: "New Israeli Sheqel", symbol: "₪", exponent: 2, number: 376}, INR: %{name: "Indian Rupee", symbol: "₹", exponent: 2, number: 356}, IQD: %{name: "Iraqi Dinar", symbol: "‎ع.د", exponent: 3, number: 368}, IRR: %{name: "Iranian Rial", symbol: "﷼", exponent: 2, number: 364}, ISK: %{name: "Iceland Krona", symbol: "kr", exponent: 0, number: 352}, JMD: %{name: "Jamaican Dollar", symbol: "J$", exponent: 2, number: 388}, JOD: %{name: "Jordanian Dinar", symbol: "JOD", exponent: 3, number: 400}, JPY: %{name: "Yen", symbol: "¥", exponent: 0, number: 392}, KES: %{name: "Kenyan Shilling", symbol: "KSh", exponent: 2, number: 404}, KGS: %{name: "Som", symbol: "лв", exponent: 2, number: 417}, KHR: %{name: "Riel", symbol: "៛", exponent: 2, number: 116}, KMF: %{name: "Comoro Franc", symbol: "CF", exponent: 0, number: 174}, KPW: %{name: "North Korean Won", symbol: "₩", exponent: 2, number: 408}, KRW: %{name: "Won", symbol: "₩", exponent: 0, number: 410}, KWD: %{name: "Kuwaiti Dinar", symbol: "د.ك", exponent: 3, number: 414}, KYD: %{name: "Cayman Islands Dollar", symbol: "$", exponent: 2, number: 136}, KZT: %{name: "Tenge", symbol: "лв", exponent: 2, number: 398}, LAK: %{name: "Kip", symbol: "₭", exponent: 2, number: 418}, LBP: %{name: "Lebanese Pound", symbol: "£", exponent: 2, number: 422}, LKR: %{name: "Sri Lanka Rupee", symbol: "₨", exponent: 2, number: 144}, LRD: %{name: "Liberian Dollar", symbol: "$", exponent: 2, number: 430}, LSL: %{name: "Rand Loti", symbol: " ", exponent: 2, number: 426}, LTL: %{name: "Lithuanian Litas", symbol: "Lt", exponent: 2, number: 440}, LVL: %{name: "Latvian Lats", symbol: "Ls", exponent: 2, number: 428}, LYD: %{name: "Libyan Dinar", symbol: "ل.د", exponent: 3, number: 434}, MAD: %{name: "Moroccan Dirham", symbol: "د.م.", exponent: 2, number: 504}, MDL: %{name: "Moldovan Leu", symbol: "MDL", exponent: 2, number: 498}, MGA: %{name: "Malagasy Ariary", symbol: "Ar", exponent: 2, number: 969}, MKD: %{name: "Denar", symbol: "ден", exponent: 2, number: 807}, MMK: %{name: "Kyat", symbol: "K", exponent: 2, number: 104}, MNT: %{name: "Tugrik", symbol: "₮", exponent: 2, number: 496}, MOP: %{name: "Pataca", symbol: "MOP$", exponent: 2, number: 446}, MRO: %{name: "Ouguiya", symbol: "UM", exponent: 2, number: 478}, MRU: %{name: "Ouguiya", symbol: "UM", exponent: 2, number: 929}, MUR: %{name: "Mauritius Rupee", symbol: "₨", exponent: 2, number: 480}, MVR: %{name: "Rufiyaa", symbol: "Rf", exponent: 2, number: 462}, MWK: %{name: "Kwacha", symbol: "MK", exponent: 2, number: 454}, MXN: %{name: "Mexican Peso", symbol: "$", exponent: 2, number: 484}, MXV: %{name: "Mexican Peso Mexican Unidad de Inversion (UDI)", symbol: "UDI", exponent: 2, number: 979}, MYR: %{name: "Malaysian Ringgit", symbol: "RM", exponent: 2, number: 458}, MZN: %{name: "Metical", symbol: "MT", exponent: 2, number: 943}, NAD: %{name: "Rand Namibia Dollar", symbol: "$", exponent: 2, number: 516}, NGN: %{name: "Naira", symbol: "₦", exponent: 2, number: 566}, NIO: %{name: "Cordoba Oro", symbol: "C$", exponent: 2, number: 558}, NOK: %{name: "Norwegian Krone", symbol: "kr", exponent: 2, number: 578}, NPR: %{name: "Nepalese Rupee", symbol: "₨", exponent: 2, number: 524}, NZD: %{name: "New Zealand Dollar", symbol: "$", exponent: 2, number: 554}, OMR: %{name: "Rial Omani", symbol: "﷼", exponent: 3, number: 512}, PAB: %{name: "Balboa US Dollar", symbol: "B/.", exponent: 2, number: 590}, PEN: %{name: "Nuevo Sol", symbol: "S/.", exponent: 2, number: 604}, PGK: %{name: "Kina", symbol: "K", exponent: 2, number: 598}, PHP: %{name: "Philippine Peso", symbol: "₱", exponent: 2, number: 608}, PKR: %{name: "Pakistan Rupee", symbol: "₨", exponent: 2, number: 586}, PLN: %{name: "Zloty", symbol: "zł", exponent: 2, number: 985}, PYG: %{name: "Guarani", symbol: "₲", exponent: 0, number: 600}, QAR: %{name: "Qatari Rial", symbol: "﷼", exponent: 2, number: 634}, RON: %{name: "New Leu", symbol: "lei", exponent: 2, number: 946}, RSD: %{name: "Serbian Dinar", symbol: "Дин.", exponent: 2, number: 941}, RUB: %{name: "Russian Ruble", symbol: "₽", exponent: 2, number: 643}, RWF: %{name: "Rwanda Franc", symbol: " ", exponent: 0, number: 646}, SAR: %{name: "Saudi Riyal", symbol: "﷼", exponent: 2, number: 682}, SBD: %{name: "Solomon Islands Dollar", symbol: "$", exponent: 2, number: 090}, SCR: %{name: "Seychelles Rupee", symbol: "₨", exponent: 2, number: 690}, SDG: %{name: "Sudanese Pound", symbol: "SDG", exponent: 2, number: 938}, SEK: %{name: "Swedish Krona", symbol: "kr", exponent: 2, number: 752}, SGD: %{name: "Singapore Dollar", symbol: "$", exponent: 2, number: 702}, SHP: %{name: "Saint Helena Pound", symbol: "£", exponent: 2, number: 654}, SLL: %{name: "Leone", symbol: "Le", exponent: 2, number: 694}, SOS: %{name: "Somali Shilling", symbol: "S", exponent: 2, number: 706}, SRD: %{name: "Surinam Dollar", symbol: "$", exponent: 2, number: 968}, SSP: %{name: "South Sudanese Pound", symbol: "SS£", exponent: 2, number: 728}, STD: %{name: "Dobra", symbol: "Db", exponent: 2, number: 678}, STN: %{name: "Dobra", symbol: "Db", exponent: 2, number: 930}, SVC: %{name: "El Salvador Colon US Dollar", symbol: "$", exponent: 2, number: 222}, SYP: %{name: "Syrian Pound", symbol: "£", exponent: 2, number: 760}, SZL: %{name: "Lilangeni", symbol: "E", exponent: 2, number: 748}, THB: %{name: "Baht", symbol: "฿", exponent: 2, number: 764}, TJS: %{name: "Somoni", symbol: " ", exponent: 2, number: 972}, TMT: %{name: "Manat", symbol: "₼", exponent: 2, number: 934}, TND: %{name: "Tunisian Dinar", symbol: "د.ت", exponent: 2, number: 788}, TOP: %{name: "Pa'anga", symbol: "T$", exponent: 2, number: 776}, TRY: %{name: "Turkish Lira", symbol: "TL", exponent: 2, number: 949}, TTD: %{name: "Trinidad and Tobago Dollar", symbol: "TT$", exponent: 2, number: 780}, TWD: %{name: "New Taiwan Dollar", symbol: "NT$", exponent: 2, number: 901}, TZS: %{name: "Tanzanian Shilling", symbol: "Tsh", exponent: 2, number: 834}, UAH: %{name: "Hryvnia", symbol: "₴", exponent: 2, number: 980}, UGX: %{name: "Uganda Shilling", symbol: "Ush", exponent: 0, number: 800}, USD: %{name: "US Dollar", symbol: "$", exponent: 2, number: 840}, USN: %{name: "US Dollar next-day funds", symbol: "$", exponent: 2, number: 997}, UYI: %{name: "Peso Uruguayo Uruguay Peso en Unidades Indexadas", symbol: "$U", exponent: 0, number: 940}, UYU: %{name: "Peso Uruguayo Uruguay Peso en Unidades Indexadas", symbol: "$U", exponent: 2, number: 858}, UZS: %{name: "Uzbekistan Sum", symbol: "лв", exponent: 2, number: 860}, VEF: %{name: "Bolivar Fuerte", symbol: "Bs", exponent: 2, number: 937}, VND: %{name: "Dong", symbol: "₫", exponent: 0, number: 704}, VUV: %{name: "Vatu", symbol: "VT", exponent: 0, number: 548}, WST: %{name: "Tala", symbol: "WS$", exponent: 2, number: 882}, XAF: %{name: "CFA Franc BEAC", symbol: "FCFA", exponent: 0, number: 950}, XAG: %{name: "Silver", symbol: " ", exponent: 2, number: 961}, XAU: %{name: "Gold", symbol: " ", exponent: 2, number: 959}, XBA: %{name: "Bond Markets Units European Composite Unit (EURCO)", symbol: " ", exponent: 2, number: 955}, XBB: %{name: "European Monetary Unit (E.M.U.-6)", symbol: " ", exponent: 2, number: 956}, XBC: %{name: "European Unit of Account 9(E.U.A.-9)", symbol: " ", exponent: 2, number: 957}, XBD: %{name: "European Unit of Account 17(E.U.A.-17)", symbol: " ", exponent: 2, number: 958}, XCD: %{name: "East Caribbean Dollar", symbol: "$", exponent: 2, number: 951}, XDR: %{name: "SDR", symbol: " ", exponent: 2, number: 960}, XFU: %{name: "UIC-Franc", symbol: " ", exponent: 2, number: 000}, XOF: %{name: "CFA Franc BCEAO", symbol: " ", exponent: 0, number: 952}, XPD: %{name: "Palladium", symbol: " ", exponent: 2, number: 964}, XPF: %{name: "CFP Franc", symbol: " ", exponent: 0, number: 953}, XPT: %{name: "Platinum", symbol: " ", exponent: 2, number: 962}, XTS: %{name: "Codes specifically reserved for testing purposes", symbol: " ", exponent: 2, number: 963}, XSU: %{name: "Sucre", symbol: " ", exponent: 2, number: 994}, XUA: %{name: "ADB Unit of Account", symbol: " ", exponent: 2, number: 965}, YER: %{name: "Yemeni Rial", symbol: "﷼", exponent: 2, number: 886}, ZAR: %{name: "Rand", symbol: "R", exponent: 2, number: 710}, ZMW: %{name: "Zambian Kwacha", symbol: "ZK", exponent: 2, number: 967}, ZWL: %{name: "Zimbabwe Dollar", symbol: "$", exponent: 2, number: 932} } @type index_type() :: Money.t() | String.t() | atom | integer defp all_currencies do Map.merge(@currencies, custom_currencies()) end Enum.each(@currencies, fn {cur, detail} -> currency = cur |> to_string() |> String.downcase() @doc """ Convenience method to create a `Money` object for the #{detail.name} (#{cur}) currency. ## Example: iex> Money.Currency.#{currency}(100) %Money{amount: 100, currency: :#{cur}} """ def unquote(:"#{currency}")(amount) do Money.new(amount, unquote(cur)) end end) @spec all() :: map @doc ~S""" Returns all the currencies ## Example: iex> Money.Currency.all |> Map.fetch!(:GBP) %{name: "Pound Sterling", symbol: "£", exponent: 2, number: 826} """ def all, do: all_currencies() @spec exists?(index_type()) :: boolean @doc ~S""" Returns true if a currency is defined ## Example: iex> Money.Currency.exists?(:USD) true iex> Money.Currency.exists?("USD") true iex> Money.Currency.exists?(:WRONG) false """ def exists?(%Money{currency: currency}), do: exists?(currency) def exists?(currency), do: Map.has_key?(all_currencies(), convert_currency(currency)) @spec get(index_type()) :: map | nil @doc ~S""" Returns a map with the name and symbol of the currency or nil if it doesn’t exist. ## Example: iex> Money.Currency.get(:USD) %{name: "US Dollar", symbol: "$", exponent: 2, number: 840} iex> Money.Currency.get(:WRONG) nil """ def get(%Money{currency: currency}), do: get(currency) @doc ~S""" Returns a map with the name and symbol of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.get(826) %{name: "Pound Sterling", symbol: "£", exponent: 2, number: 826} """ def get(currency), do: all_currencies()[convert_currency(currency)] @spec get!(index_type()) :: map @doc ~S""" Returns a map with the name and symbol of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.get!(:USD) %{name: "US Dollar", symbol: "$", exponent: 2, number: 840} iex> Money.Currency.get!(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def get!(currency), do: get(currency) || currency_doesnt_exist_error(currency) @spec to_atom(index_type()) :: atom @doc ~S""" Returns the atom representation of the currency key An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.to_atom("usd") :USD iex> Money.Currency.to_atom(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def to_atom(%Money{currency: currency}), do: to_atom(currency) def to_atom(currency) do currency = convert_currency(currency) get!(currency) currency end @spec name(index_type()) :: String.t() | nil @doc ~S""" Returns the name of the currency or nil if it doesn’t exist. ## Example: iex> Money.Currency.name(:USD) "US Dollar" iex> Money.Currency.name(:WRONG) nil """ def name(%Money{currency: currency}), do: name(currency) def name(currency), do: get(currency)[:name] @spec name!(index_type()) :: String.t() @doc ~S""" Returns the name of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.name!(:USD) "US Dollar" iex> Money.Currency.name!(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def name!(currency), do: name(currency) || currency_doesnt_exist_error(currency) @spec symbol(index_type()) :: String.t() | nil @doc ~S""" Returns the symbol of the currency or nil if it doesn’t exist. ## Example: iex> Money.Currency.symbol(:USD) "$" iex> Money.Currency.symbol(:WRONG) nil """ def symbol(%Money{currency: currency}), do: symbol(currency) def symbol(currency), do: get(currency)[:symbol] @spec symbol!(index_type()) :: String.t() @doc ~S""" Returns the symbol of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.symbol!(:USD) "$" iex> Money.Currency.symbol!(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def symbol!(currency), do: symbol(currency) || currency_doesnt_exist_error(currency) @spec exponent(index_type()) :: integer | nil @doc ~S""" Returns the exponent of the currency or nil if it doesn’t exist. ## Example: iex> Money.Currency.exponent(:USD) 2 iex> Money.Currency.exponent(:WRONG) nil """ def exponent(%Money{currency: currency}), do: exponent(currency) def exponent(currency), do: get(currency)[:exponent] @spec exponent!(index_type()) :: integer @doc ~S""" Returns the exponent of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.exponent!(:USD) 2 iex> Money.Currency.exponent!(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def exponent!(currency), do: exponent(currency) || currency_doesnt_exist_error(currency) @spec sub_units_count!(index_type()) :: integer @doc ~S""" Returns the sub_units_count of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.sub_units_count!(:USD) 100 iex> Money.Currency.sub_units_count!(:JPY) 1 iex> Money.Currency.sub_units_count!(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def sub_units_count!(currency) do exponent = exponent!(currency) round(:math.pow(10, exponent)) end @spec number(index_type()) :: integer | nil @doc ~S""" Returns the number of the currency or nil if it doesn’t exist. ## Example: iex> Money.Currency.number(:USD) 840 iex> Money.Currency.number(:WRONG) nil """ def number(%Money{currency: currency}), do: number(currency) def number(currency), do: get(currency)[:number] @spec number!(index_type()) :: integer @doc ~S""" Returns the number of the currency. An ArgumentError is raised if the currency doesn’t exist. ## Example: iex> Money.Currency.number!(:EUR) 978 iex> Money.Currency.exponent!(:WRONG) ** (ArgumentError) currency WRONG doesn’t exist """ def number!(currency), do: number(currency) || currency_doesnt_exist_error(currency) defp convert_currency(currency) when is_binary(currency) do currency |> String.upcase() |> String.to_existing_atom() |> convert_currency rescue _ -> nil end defp convert_currency(currency) when is_integer(currency) do case Enum.find(all_currencies(), fn {_, %{number: number}} -> number == currency end) do {cur, _} -> cur nil -> nil end rescue _ -> nil end defp convert_currency(currency), do: currency defp currency_doesnt_exist_error(currency), do: raise(ArgumentError, "currency #{currency} doesn’t exist") end
43.446465
114
0.608016
0389df733402af0cce2e42c70ff7091eff7fa035
1,993
exs
Elixir
apps/aecore/test/aecore_txs_pool_test.exs
wuminzhe/elixir-node
eb87b47339a8349bac767dd4cf597dfaf0ed75c6
[ "ISC" ]
null
null
null
apps/aecore/test/aecore_txs_pool_test.exs
wuminzhe/elixir-node
eb87b47339a8349bac767dd4cf597dfaf0ed75c6
[ "ISC" ]
null
null
null
apps/aecore/test/aecore_txs_pool_test.exs
wuminzhe/elixir-node
eb87b47339a8349bac767dd4cf597dfaf0ed75c6
[ "ISC" ]
null
null
null
defmodule AecoreTxsPoolTest do @moduledoc """ Unit test for the pool worker module """ use ExUnit.Case alias Aecore.Txs.Pool.Worker, as: Pool alias Aecore.Miner.Worker, as: Miner alias Aecore.Chain.Worker, as: Chain alias Aecore.Structures.SignedTx alias Aecore.Structures.SpendTx alias Aecore.Wallet.Worker, as: Wallet setup ctx do [ to_acc: Wallet.get_public_key() ] end @tag timeout: 20_000 @tag :txs_pool test "add transaction, remove it and get pool", ctx do # Empty the pool from the other tests Pool.get_and_empty_pool() from_acc = Wallet.get_public_key() {:ok, tx1} = SpendTx.create( from_acc, ctx.to_acc, 5, Map.get(Chain.chain_state(), from_acc, %{nonce: 0}).nonce + 1, 10 ) {:ok, tx2} = SpendTx.create( from_acc, ctx.to_acc, 5, Map.get(Chain.chain_state(), from_acc, %{nonce: 0}).nonce + 2, 10 ) :ok = Miner.mine_sync_block_to_chain() priv_key = Wallet.get_private_key() {:ok, signed_tx1} = SignedTx.sign_tx(tx1, priv_key) {:ok, signed_tx2} = SignedTx.sign_tx(tx2, priv_key) assert :ok = Pool.add_transaction(signed_tx1) assert :ok = Pool.add_transaction(signed_tx2) assert :ok = Pool.remove_transaction(signed_tx2) assert Enum.count(Pool.get_pool()) == 1 :ok = Miner.mine_sync_block_to_chain() assert length(Chain.longest_blocks_chain()) > 1 assert Enum.count(Chain.top_block().txs) == 2 assert Enum.empty?(Pool.get_pool()) end test "add negative transaction fail", ctx do from_acc = Wallet.get_public_key() {:ok, tx} = SpendTx.create( from_acc, ctx.to_acc, -5, Map.get(Chain.chain_state(), from_acc, %{nonce: 0}).nonce + 1, 10 ) priv_key = Wallet.get_private_key() {:ok, signed_tx} = SignedTx.sign_tx(tx, priv_key) assert :error = Pool.add_transaction(signed_tx) end end
24.304878
70
0.63422
038a15585ad17ca38dd8b323d7ad58b805c3f6bf
360
exs
Elixir
test/exsolr_test.exs
PharosProduction/exsolr
d93eb75c235d3d729f96efd6a8c28688f232ce39
[ "MIT" ]
25
2016-05-10T00:02:27.000Z
2020-11-08T16:51:43.000Z
test/exsolr_test.exs
PharosProduction/exsolr
d93eb75c235d3d729f96efd6a8c28688f232ce39
[ "MIT" ]
2
2016-11-01T10:23:20.000Z
2016-11-14T23:29:28.000Z
test/exsolr_test.exs
PharosProduction/exsolr
d93eb75c235d3d729f96efd6a8c28688f232ce39
[ "MIT" ]
16
2016-05-22T02:12:15.000Z
2021-02-10T20:56:54.000Z
defmodule ExsolrTest do use ExUnit.Case, async: true doctest Exsolr test "get a document" do Exsolr.get(q: "roses") end test "add a document" do document = %{id: "3", title: "Doc 3" } Exsolr.add(document) end test "delete a document by id" do Exsolr.delete_by_id(3) end test "commit" do assert Exsolr.commit end end
16.363636
42
0.647222
038a3b1732b723f19dd9f48023a95484c458f8f1
10,392
ex
Elixir
apps/jsonrpc2/test/support/bridge_sync_mock.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
152
2018-10-27T04:52:03.000Z
2022-03-26T10:34:00.000Z
apps/jsonrpc2/test/support/bridge_sync_mock.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
270
2018-04-14T07:34:57.000Z
2018-10-25T18:10:45.000Z
apps/jsonrpc2/test/support/bridge_sync_mock.ex
wolflee/mana
db66dac85addfaad98d40da5bd4082b3a0198bb1
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
25
2018-10-27T12:15:13.000Z
2022-01-25T20:31:14.000Z
defmodule JSONRPC2.BridgeSyncMock do alias Blockchain.Account alias Blockchain.Block alias JSONRPC2.Response.Block, as: ResponseBlock alias JSONRPC2.Response.Receipt, as: ResponseReceipt alias JSONRPC2.Response.Transaction, as: ResponseTransaction alias JSONRPC2.Struct.EthSyncing alias MerklePatriciaTree.TrieStorage import JSONRPC2.Response.Helpers @behaviour JSONRPC2.Client use GenServer @impl true def connected_peer_count() do GenServer.call(__MODULE__, :connected_peer_count) end @impl true def last_sync_block_stats() do GenServer.call(__MODULE__, :get_last_sync_block_stats) end @impl true def block(hash_or_number, include_full_transactions) do GenServer.call(__MODULE__, {:get_block, hash_or_number, include_full_transactions}) end @impl true def transaction_by_block_and_index(block_hash_or_number, index) do GenServer.call( __MODULE__, {:get_transaction_by_block_and_index, block_hash_or_number, index} ) end @impl true def transaction_by_hash(transaction_hash) do GenServer.call(__MODULE__, {:get_transaction_by_hash, transaction_hash}) end @impl true def block_transaction_count(block_hash_or_number) do GenServer.call(__MODULE__, {:get_block_transaction_count, block_hash_or_number}) end @impl true def uncle_count(block_number_or_hash) do GenServer.call(__MODULE__, {:get_uncle_count, block_number_or_hash}) end @impl true def starting_block_number do GenServer.call(__MODULE__, :get_starting_block_number) end @impl true def highest_block_number do GenServer.call(__MODULE__, :get_highest_block_number) end @impl true def code(address, block_number) do GenServer.call(__MODULE__, {:get_code, address, block_number}) end @impl true def balance(address, block_number) do GenServer.call(__MODULE__, {:get_balance, address, block_number}) end @impl true def transaction_receipt(transaction_hash) do GenServer.call(__MODULE__, {:get_transaction_receipt, transaction_hash}) end @impl true def uncle(block_number_or_hash, index) do GenServer.call(__MODULE__, {:get_uncle, {block_number_or_hash, index}}) end @impl true def storage(address, storage_key, block_number) do GenServer.call(__MODULE__, {:get_storage, address, storage_key, block_number}) end @impl true def transaction_count(address, block_number) do GenServer.call(__MODULE__, {:get_transaction_count, address, block_number}) end @impl true def last_sync_state() do GenServer.call(__MODULE__, :last_sync_state) end def set_trie(trie) do GenServer.call(__MODULE__, {:set_trie, trie}) end def get_trie do GenServer.call(__MODULE__, :get_trie) end def set_connected_peer_count(connected_peer_count) do GenServer.call(__MODULE__, {:set_connected_peer_count, connected_peer_count}) end def set_starting_block_number(block_number) do GenServer.call(__MODULE__, {:set_starting_block_number, block_number}) end def set_highest_block_number(block_number) do GenServer.call(__MODULE__, {:set_highest_block_number, block_number}) end def set_last_sync_block_stats(block_stats) do GenServer.call(__MODULE__, {:set_last_sync_block_stats, block_stats}) end def put_block(block) do GenServer.call(__MODULE__, {:put_block, block}) end def start_link(state) do GenServer.start_link(__MODULE__, state, name: __MODULE__) end @impl true def init(state) do {:ok, state} end @impl true def handle_call(:connected_peer_count, _, state) do {:reply, state.connected_peer_count, state} end def handle_call(:get_highest_block_number, _, state) do {:reply, Map.get(state, :highest_block_number, 0), state} end def handle_call(:get_starting_block_number, _, state) do {:reply, Map.get(state, :starting_block_number, 0), state} end def handle_call({:set_trie, trie}, _, state) do {:reply, :ok, Map.put(state, :trie, trie)} end def handle_call(:get_trie, _, state) do {:reply, state.trie, state} end def handle_call({:set_connected_peer_count, connected_peer_count}, _, state) do {:reply, :ok, Map.put(state, :connected_peer_count, connected_peer_count)} end def handle_call({:set_highest_block_number, block_number}, _, state) do {:reply, :ok, Map.put(state, :highest_block_number, block_number)} end def handle_call({:set_starting_block_number, block_number}, _, state) do {:reply, :ok, Map.put(state, :set_starting_block_number, block_number)} end def handle_call({:put_block, block}, _, state = %{trie: trie}) do {:ok, {_, updated_trie}} = Block.put_block(block, trie, block.block_hash) updated_state = %{state | trie: updated_trie} {:reply, :ok, updated_state} end def handle_call( {:get_block, hash_or_number, include_full_transactions}, _, state = %{trie: trie} ) do block = case Block.get_block(hash_or_number, trie) do {:ok, block} -> ResponseBlock.new(block, include_full_transactions) _ -> nil end {:reply, block, state} end def handle_call( {:get_transaction_by_block_and_index, block_hash_or_number, trx_index}, _, state = %{trie: trie} ) do result = with {:ok, block} <- Block.get_block(block_hash_or_number, trie) do case Enum.at(block.transactions, trx_index) do nil -> nil transaction -> ResponseTransaction.new(transaction, block) end else _ -> nil end {:reply, result, state} end def handle_call( {:get_block_transaction_count, block_hash_or_number}, _, state = %{trie: trie} ) do result = case Block.get_block(block_hash_or_number, trie) do {:ok, block} -> block.transactions |> Enum.count() |> encode_quantity() _ -> nil end {:reply, result, state} end def handle_call( {:get_uncle_count, block_number_or_hash}, _, state = %{trie: trie} ) do result = case Block.get_block(block_number_or_hash, trie) do {:ok, block} -> block.ommers |> Enum.count() |> encode_quantity() _ -> nil end {:reply, result, state} end def handle_call( {:get_uncle, {block_hash_or_number, index}}, _, state = %{trie: trie} ) do result = case Block.get_block(block_hash_or_number, trie) do {:ok, block} -> case Enum.at(block.ommers, index) do nil -> nil ommer_header -> uncle_block = %Block{header: ommer_header, transactions: [], ommers: []} uncle_block |> Block.add_metadata(trie) |> ResponseBlock.new() end _ -> nil end {:reply, result, state} end def handle_call({:get_code, address, block_number}, _, state = %{trie: trie}) do result = case Block.get_block(block_number, trie) do {:ok, block} -> block_state = TrieStorage.set_root_hash(trie, block.header.state_root) case Account.machine_code(block_state, address) do {:ok, code} -> encode_unformatted_data(code) _ -> nil end _ -> nil end {:reply, result, state} end def handle_call({:get_balance, address, block_number}, _, state = %{trie: trie}) do result = case Block.get_block(block_number, trie) do {:ok, block} -> block_state = TrieStorage.set_root_hash(trie, block.header.state_root) case Account.get_account(block_state, address) do nil -> nil account -> encode_quantity(account.balance) end _ -> nil end {:reply, result, state} end def handle_call({:get_transaction_by_hash, transaction_hash}, _, state = %{trie: trie}) do result = case Block.get_transaction_by_hash(transaction_hash, trie, true) do {transaction, block} -> ResponseTransaction.new(transaction, block) nil -> nil end {:reply, result, state} end def handle_call({:get_transaction_receipt, transaction_hash}, _, state = %{trie: trie}) do result = case Block.get_receipt_by_transaction_hash(transaction_hash, trie) do {receipt, transaction, block} -> ResponseReceipt.new(receipt, transaction, block) _ -> nil end {:reply, result, state} end def handle_call( {:get_storage, storage_address, storage_key, block_number}, _, state = %{trie: trie} ) do result = case Block.get_block(block_number, trie) do {:ok, block} -> block_state = TrieStorage.set_root_hash(trie, block.header.state_root) case Account.get_storage(block_state, storage_address, storage_key) do {:ok, value} -> value |> :binary.encode_unsigned() |> encode_unformatted_data _ -> nil end end {:reply, result, state} end def handle_call({:get_transaction_count, address, block_number}, _, state = %{trie: trie}) do result = case Block.get_block(block_number, trie) do {:ok, block} -> block_state = TrieStorage.set_root_hash(trie, block.header.state_root) case Account.get_account(block_state, address) do nil -> nil account -> encode_quantity(account.nonce) end _ -> nil end {:reply, result, state} end def handle_call(:last_sync_state, _, state) do {:reply, state, state} end @spec handle_call(:get_last_sync_block_stats, {pid, any}, map()) :: {:reply, EthSyncing.output(), map()} def handle_call(:get_last_sync_block_stats, _, state) do {:reply, state.block_stats, state} end @spec handle_call( {:set_last_sync_block_stats, EthSyncing.input()}, {pid, any}, map() ) :: {:reply, :ok, map()} def handle_call({:set_last_sync_block_stats, block_stats}, _, state) do new_state = Map.put(state, :block_stats, block_stats) {:reply, :ok, new_state} end end
26.176322
95
0.651751
038a80fcf36f26d7b8fdc38726316f978117c996
107
ex
Elixir
test/setup/repo.ex
jmhthethird/assoc
d73c556f398d01258cbc17b6de58a621a6bc4397
[ "MIT" ]
6
2019-01-31T23:31:42.000Z
2020-10-06T20:05:34.000Z
test/setup/repo.ex
jmhthethird/assoc
d73c556f398d01258cbc17b6de58a621a6bc4397
[ "MIT" ]
2
2021-11-09T14:35:51.000Z
2021-11-09T18:04:15.000Z
test/setup/repo.ex
jmhthethird/assoc
d73c556f398d01258cbc17b6de58a621a6bc4397
[ "MIT" ]
2
2019-01-31T23:53:33.000Z
2021-11-05T21:47:26.000Z
defmodule Assoc.Test.Repo do use Ecto.Repo, otp_app: :assoc, adapter: Ecto.Adapters.Postgres end
17.833333
35
0.719626
038a937396691bce9341ef599baa435df49117bd
313
ex
Elixir
tests/dirty_nif/NimlerWrapper.ex
pilotier/nimler
bc80503d9e300ba59889f533b79dc51962083ba7
[ "MIT" ]
null
null
null
tests/dirty_nif/NimlerWrapper.ex
pilotier/nimler
bc80503d9e300ba59889f533b79dc51962083ba7
[ "MIT" ]
null
null
null
tests/dirty_nif/NimlerWrapper.ex
pilotier/nimler
bc80503d9e300ba59889f533b79dc51962083ba7
[ "MIT" ]
null
null
null
defmodule NimlerDirtyNif do @on_load :init def init(), do: :erlang.load_nif( to_charlist(Path.join(Path.dirname(__ENV__.file), 'nif')), 0 ) def dirty_cpu(), do: :erlang.nif_error(:nif_library_not_loaded) def dirty_io(), do: :erlang.nif_error(:nif_library_not_loaded) end
22.357143
66
0.664537
038acb607d8e570c95f49155a26dfff560fbb509
2,647
exs
Elixir
apps/nerves_hub_www/test/nerves_hub_www_web/live/device_live_show_test.exs
acrogenesis/nerves_hub_web
27f651dd64b40a034254b50805884f4efd679957
[ "Apache-2.0" ]
1
2019-10-13T10:56:28.000Z
2019-10-13T10:56:28.000Z
apps/nerves_hub_www/test/nerves_hub_www_web/live/device_live_show_test.exs
Eaftos/nerves_hub_web
ac03bd044b97265bf3ba3edd8da249d300fa3668
[ "Apache-2.0" ]
null
null
null
apps/nerves_hub_www/test/nerves_hub_www_web/live/device_live_show_test.exs
Eaftos/nerves_hub_web
ac03bd044b97265bf3ba3edd8da249d300fa3668
[ "Apache-2.0" ]
null
null
null
defmodule NervesHubWWWWeb.DeviceLiveShowTest do use NervesHubWWWWeb.ConnCase.Browser, async: false import Phoenix.ChannelTest alias NervesHubWebCore.{AuditLogs, Repo} alias NervesHubWWWWeb.Endpoint alias Phoenix.Socket.Broadcast setup %{fixture: %{device: device}} do Endpoint.subscribe("device:#{device.id}") end test "redirects on mount with unrecognized session structure", %{conn: conn, fixture: fixture} do home_path = Routes.home_path(Endpoint, :index) conn = clear_session(conn) assert {:error, %{redirect: %{to: ^home_path}}} = live(conn, device_show_path(fixture)) end describe "handle_event" do test "reboot allowed", %{conn: conn, fixture: fixture} do %{device: device} = fixture {:ok, view, _html} = live(conn, device_show_path(fixture)) before_audit_count = AuditLogs.logs_for(device) |> length assert render_change(view, :reboot, %{}) =~ "reboot-requested" assert_broadcast("reboot", %{}) after_audit_count = AuditLogs.logs_for(device) |> length assert after_audit_count == before_audit_count + 1 end test "reboot blocked", %{conn: conn, fixture: fixture} do %{device: device, user: user} = fixture Repo.preload(user, :org_users) |> Map.get(:org_users) |> Enum.map(&NervesHubWebCore.Accounts.change_org_user_role(&1, :read)) {:ok, view, _html} = live(conn, device_show_path(fixture)) before_audit_count = AuditLogs.logs_for(device) |> length assert render_change(view, :reboot, %{}) =~ "reboot-blocked" after_audit_count = AuditLogs.logs_for(device) |> length assert after_audit_count == before_audit_count + 1 end end describe "handle_info" do test "presence_diff with no change", %{conn: conn, fixture: fixture} do payload = %{joins: %{}, leaves: %{}} {:ok, view, html} = live(conn, device_show_path(fixture)) assert html =~ "offline" send(view.pid, %Broadcast{event: "presence_diff", payload: payload}) assert render(view) =~ "offline" end test "presence_diff with changes", %{conn: conn, fixture: fixture} do %{device: device} = fixture payload = %{joins: %{"#{device.id}" => %{status: "online"}}, leaves: %{}} {:ok, view, html} = live(conn, device_show_path(fixture)) assert html =~ "offline" send(view.pid, %Broadcast{event: "presence_diff", payload: payload}) assert render(view) =~ "online" end end def device_show_path(%{device: device, org: org, product: product}) do Routes.device_path(Endpoint, :show, org.name, product.name, device.identifier) end end
32.280488
99
0.669059
038ad7f4dd9707cf87ffcb937e9ea6f3117119de
4,259
exs
Elixir
debug_options.exs
Ajwah/ex_debugger
44cd5b99c0b7751db052887b7a0bc3ce52a2972e
[ "Apache-2.0" ]
3
2020-07-07T20:41:23.000Z
2020-07-17T09:05:37.000Z
debug_options.exs
Ajwah/ex_debugger
44cd5b99c0b7751db052887b7a0bc3ce52a2972e
[ "Apache-2.0" ]
1
2020-07-08T00:04:38.000Z
2020-07-08T00:04:38.000Z
debug_options.exs
Ajwah/ex_debugger
44cd5b99c0b7751db052887b7a0bc3ce52a2972e
[ "Apache-2.0" ]
null
null
null
import Config config :ex_debugger, :meta_debug, all: %{show_module_tokens: false, show_tokenizer: false, show_ast_before: false, show_ast_after: false}, # "Elixir.Support.DiscoveredBugs.ConsOperator.AutoCase": {true, true, true, true}, # "Elixir.Support.DiscoveredBugs.ConsOperator.ManualCase": {true, true, true, true}, placeholder_serving_no_functional_value: "This is only serving as a placeholder to maintain trailing comma of previous line" config :ex_debugger, :manual_debug, capture: :repo, #[:repo, :stdout, :both, :none] warn: false, all: true, placeholder_serving_no_functional_value: "This is only serving as a placeholder to maintain trailing comma of previous line" config :ex_debugger, :debug, capture: :repo, #[:repo, :stdout, :both, :none] warn: false, all: false, "Elixir.HelloWorld": true, "Elixir.Support.EdgeCases.EmptyCase": true, "Elixir.Support.EdgeCases.SingleDefCases.ContractedFormSimple": true, "Elixir.Support.EdgeCases.SingleDefCases.ContractedFormComplex": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormSimple": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormComplex": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormComplex.SingularArgument": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormComplex.PatternMatch": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormComplex.MultipleArgument": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormComplex.Defguard": true, "Elixir.Support.EdgeCases.SingleDefCases.ExpandedFormComplex.MultipleIndependentExpressions": true, "Elixir.Support.EdgeCases.MultipleDefCases.Various": true, "Elixir.Support.EdgeCases.MultipleDefCases.UselessSpaces": true, "Elixir.Support.EdgeCases.MultipleDefCases.DefaultParamWithPrivateHelpers": true, "Elixir.Support.EdgeCases.MultipleDefCases.Overloading": true, "Elixir.Support.EdgeCases.CaseStatement.Minimal": true, "Elixir.Support.EdgeCases.CaseStatement.Elaborate": true, "Elixir.Support.EdgeCases.IfStatement.Minimal": true, "Elixir.Support.EdgeCases.IfStatement.Elaborate": true, "Elixir.Support.EdgeCases.CondStatement.Minimal": true, "Elixir.Support.EdgeCases.CondStatement.Elaborate": true, "Elixir.Support.EdgeCases.MultipleModules.SingleNestedWithoutExDebugger": true, "Elixir.Support.EdgeCases.MultipleModules.SingleNestedWithExDebugger": true, "Elixir.Support.EdgeCases.MultipleModules.SingleNestedWithExDebugger.Helpers": true, "Elixir.Support.EdgeCases.MultipleModules.SiblingsWithExDebugger": true, "Elixir.Support.EdgeCases.MultipleModules.SiblingsWithExDebugger.Helpers": true, "Elixir.Support.EdgeCases.MultipleModules.SingleNestedWithExDebuggerButDebugDisabled": true, "Elixir.Support.EdgeCases.MultipleModules.SingleNestedWithExDebuggerButDebugDisabled.Helpers": false, # Explicitly disabled "Elixir.Support.EdgeCases.ImportCases.MainModuleWithExDebuggerImportingHelperModuleWithExDebugger": true, "Elixir.Support.EdgeCases.ImportCases.MainModuleWithExDebuggerImportingHelperModuleWithoutExDebugger": true, "Elixir.Support.EdgeCases.ImportCases.HelperModuleWithExDebugger": true, "Elixir.Support.EdgeCases.ImportCases.HelperModuleWithoutExDebugger": true, "Elixir.Support.EdgeCases.UseCases.HelperModuleWithExDebugger": true, "Elixir.Support.EdgeCases.UseCases.HelperModuleWithExDebuggerAtModuleLevel": true, "Elixir.Support.EdgeCases.UseCases.HelperModuleWithoutExDebugger": true, "Elixir.Support.EdgeCases.UseCases.MainModuleWithExDebuggerUseHelperModuleWithExDebuggerAtModuleLevel": true, "Elixir.Support.EdgeCases.UseCases.MainModuleWithExDebuggerUseHelperModuleWithoutExDebugger": true, "Elixir.Support.EdgeCases.UseCases.MainModuleWithExDebuggerUseHelperModuleWithExDebugger": true, "Elixir.Support.EdgeCases.UseCases.MainModuleWithoutExDebuggerUseHelperModuleWithExDebugger": true, "Elixir.Support.EdgeCases.UseCases.MainModuleWithoutExDebuggerUseHelperModuleWithExDebuggerAtModuleLevel": true, "Elixir.Support.DiscoveredBugs.ConsOperator.AutoCase": true, "Elixir.Support.DiscoveredBugs.ConsOperator.ManualCase": true, placeholder_serving_no_functional_value: "This is only serving as a placeholder to maintain trailing comma of previous line"
61.724638
126
0.82672
038aea5008a537eeeb0b620cd41223ba2c6b1828
1,426
ex
Elixir
lib/cv_creator_web/router.ex
Foxlabsdevelopers/cv_creator
c77d52cdc67180ed369a3dbd298ca2dea5131c60
[ "MIT" ]
null
null
null
lib/cv_creator_web/router.ex
Foxlabsdevelopers/cv_creator
c77d52cdc67180ed369a3dbd298ca2dea5131c60
[ "MIT" ]
2
2021-05-24T21:41:25.000Z
2021-05-25T16:02:09.000Z
lib/cv_creator_web/router.ex
Foxlabsdevelopers/cv_creator
c77d52cdc67180ed369a3dbd298ca2dea5131c60
[ "MIT" ]
null
null
null
defmodule CvCreatorWeb.Router do use CvCreatorWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", CvCreatorWeb do pipe_through :browser get "/", PageController, :index get "/about-this-project", PageController, :login get "/createdBy", PageController, :createdby get "/home", PageController, :home get "/contact", PageController, :contact resources "/super-user", SuperUsersController # Las rutas siempre deben tener guion medio... resources "/general-data", GeneralDataController end # Other scopes may use custom stacks. # scope "/api", CvCreatorWeb do # pipe_through :api # end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through :browser live_dashboard "/dashboard", metrics: CvCreatorWeb.Telemetry end end end
28.52
70
0.704067
038af8aef846753b70a0d516b8aebc4231c8508b
7,126
ex
Elixir
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_api_proxy_revision.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_api_proxy_revision.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_api_proxy_revision.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.Apigee.V1.Model.GoogleCloudApigeeV1ApiProxyRevision do @moduledoc """ API proxy revision. ## Attributes * `basepaths` (*type:* `list(String.t)`, *default:* `nil`) - Base URL of the API proxy. * `configurationVersion` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ConfigVersion.t`, *default:* `nil`) - Version of the API proxy configuration schema to which the API proxy conforms. Currently, the only supported value is 4.0 (`majorVersion.minorVersion`). This setting may be used in the future to track the evolution of the API proxy format. * `contextInfo` (*type:* `String.t`, *default:* `nil`) - Revision number, app name, and organization for the API proxy. * `createdAt` (*type:* `String.t`, *default:* `nil`) - Time that the API proxy revision was created in milliseconds since epoch. * `description` (*type:* `String.t`, *default:* `nil`) - Description of the API proxy revision. * `displayName` (*type:* `String.t`, *default:* `nil`) - Human-readable name of the API proxy. * `entityMetaDataAsProperties` (*type:* `map()`, *default:* `nil`) - Metadata describing the API proxy revision as a key-value map. * `integrationEndpoints` (*type:* `list(String.t)`, *default:* `nil`) - List of IntegrationEndpoints in the '/integration-endpoints' directory of the API proxy. This is a 'manifest' setting designed to provide visibility into the contents of the API proxy. * `lastModifiedAt` (*type:* `String.t`, *default:* `nil`) - Time that the API proxy revision was last modified in milliseconds since epoch. * `name` (*type:* `String.t`, *default:* `nil`) - Name of the API proxy. * `policies` (*type:* `list(String.t)`, *default:* `nil`) - List of policy names included in the API proxy revision.. * `proxies` (*type:* `list(String.t)`, *default:* `nil`) - List of proxy names included in the API proxy revision. * `proxyEndpoints` (*type:* `list(String.t)`, *default:* `nil`) - List of ProxyEndpoints in the `/proxies` directory of the API proxy. Typically, this element is included only when the API proxy was created using the Edge UI. This is a 'manifest' setting designed to provide visibility into the contents of the API proxy. * `resourceFiles` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles.t`, *default:* `nil`) - List of resource files included in the API proxy revision. * `resources` (*type:* `list(String.t)`, *default:* `nil`) - List of the resources included in the API proxy revision formatted as "{type}://{name}". * `revision` (*type:* `String.t`, *default:* `nil`) - API proxy revision. * `sharedFlows` (*type:* `list(String.t)`, *default:* `nil`) - List of the shared flows included in the API proxy revision. * `spec` (*type:* `String.t`, *default:* `nil`) - OpenAPI Specification that is associated with the API proxy. The value is set to a URL or to a path in the specification store. * `targetEndpoints` (*type:* `list(String.t)`, *default:* `nil`) - List of TargetEndpoints in the `/targets` directory of the API proxy. Typically, this element is included only when the API proxy was created using the Edge UI. This is a 'manifest' setting designed to provide visibility into the contents of the API proxy. * `targetServers` (*type:* `list(String.t)`, *default:* `nil`) - List of TargetServers referenced in any TargetEndpoint in the API proxy. Typically, you will see this element only when the API proxy was created using the Edge UI. This is a 'manifest' setting designed to provide visibility into the contents of the API proxy. * `targets` (*type:* `list(String.t)`, *default:* `nil`) - List of the targets included in the API proxy revision. * `teams` (*type:* `list(String.t)`, *default:* `nil`) - List of the teams included in the API proxy revision. * `type` (*type:* `String.t`, *default:* `nil`) - Type. Set to `Application`. Maintained for compatibility with the Apigee Edge API. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :basepaths => list(String.t()) | nil, :configurationVersion => GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ConfigVersion.t() | nil, :contextInfo => String.t() | nil, :createdAt => String.t() | nil, :description => String.t() | nil, :displayName => String.t() | nil, :entityMetaDataAsProperties => map() | nil, :integrationEndpoints => list(String.t()) | nil, :lastModifiedAt => String.t() | nil, :name => String.t() | nil, :policies => list(String.t()) | nil, :proxies => list(String.t()) | nil, :proxyEndpoints => list(String.t()) | nil, :resourceFiles => GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles.t() | nil, :resources => list(String.t()) | nil, :revision => String.t() | nil, :sharedFlows => list(String.t()) | nil, :spec => String.t() | nil, :targetEndpoints => list(String.t()) | nil, :targetServers => list(String.t()) | nil, :targets => list(String.t()) | nil, :teams => list(String.t()) | nil, :type => String.t() | nil } field(:basepaths, type: :list) field(:configurationVersion, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ConfigVersion) field(:contextInfo) field(:createdAt) field(:description) field(:displayName) field(:entityMetaDataAsProperties, type: :map) field(:integrationEndpoints, type: :list) field(:lastModifiedAt) field(:name) field(:policies, type: :list) field(:proxies, type: :list) field(:proxyEndpoints, type: :list) field(:resourceFiles, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ResourceFiles) field(:resources, type: :list) field(:revision) field(:sharedFlows, type: :list) field(:spec) field(:targetEndpoints, type: :list) field(:targetServers, type: :list) field(:targets, type: :list) field(:teams, type: :list) field(:type) end defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ApiProxyRevision do def decode(value, options) do GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ApiProxyRevision.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ApiProxyRevision do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
62.508772
361
0.685237